Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable names in table field not working

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".

like image 400
Connor Simpson Avatar asked Dec 15 '22 12:12

Connor Simpson


2 Answers

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
like image 86
hjpotter92 Avatar answered Jan 07 '23 13:01

hjpotter92


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
like image 43
James T Avatar answered Jan 07 '23 12:01

James T