Question

I came across a problem while writing some code up for a game. It seems I can't use variables in statements like;

local Username = "Cranavvo"
game.Players.Username:BreakJoints() -- Kills the player

And the output is telling me "No such user as 'Username'" which should be "Cranavvo".

Was it helpful?

Solution

From Lua PiL on tables

To represent records, you use the field name as an index. Lua supports this representation by providing a.name as syntactic sugar for a["name"].

A common mistake for beginners is to confuse a.x with a[x]. The first form represents a["x"], that is, a table indexed by the string "x".

Therefore, when you try:

game.Players.Username:BreakJoints()

Lua interprets it as:

game["Players"]["Username"]:BreakJoints()

which ofcourse is wrong. If you want to use varying name as index for a table, use them like this:

local foo = "Cranavvo"
game.Players[foo]:BreakJoints()

But to be mentioned is that the Player class do not have a BreakJoints method, you have to get the character model with help of the .Character attribute like this:

local foo = "Cranavvo"
game.Players[foo].Character:BreakJoints()

Also to be mentioned is that if the player with that name does not exist the code will break, and also that the character can be null, in which case it also breaks. Thus you need to add some error handling. Like this:

local foo = "Cranavvo"
local Player = game.Players:findFirstChild(foo)
if Player ~= nil and Player.Character ~= nil then
    Player.Character:BreakJoints()
end

OTHER TIPS

The correct way to do this in roblox is this:

local Username = "Cranavvo"
local p = game.Players:FindFirstChild(Username)
if(p ~= nil) then
    if(p.Character ~= nil) then
        p.Character:BreakJoints()
    end
end

Double check if the user really exists at the time your code gets executed.

Also it should be:

game.Players.Username:BreakJoints()

EDIT:

I misread what you wanted to do: in

...Players.Username

lua interprets Username as a named index and does not use the Username variable declared beforehand.

If you want to access an array variable with a dynamic name you can do it like this:

game.Players[Username]:BreakJoints()

additionally in roblox you could just use the following:

game.Players:GetPlayerByID(userId):BreakJoints()

Variables are very confusing in Lua sometimes.

For example, there are global and local variables.

Local variables are variables that can be forgotten/erased after the operation ends: local x = 2

Global variables are variables that stay within the game/application unforgotten, this is good with high scores and other neat things. x = 2 (Notice there isn't a "local" statement)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top