Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why are my tables not working as expected?

I am working on a round based game and am storing player "states" in tables. I am able to insert players into the table with the AddPlayerToTable function but when it looks for the player in the table it is unable to find it. Returning nil.

I'm not really sure why this is the case, my best guess is when I add the player to the table (using val) it is creating a separate table to place the player in instead of the one defined in Tables.

Any help on this issue is appreciated.

Tables

local Tables = {
	Playing = {},
	CurrentPlayers = {},
	DeadPlayers = {}
}

Function for adding players to the table

--val = Playing 
function module:AddPlayerToTable(player,val)--val is the table to edit
	if Tables[val] then
		if not Tables[val][player] then
			table.insert(Tables[val],player)
		end
	end
end

Function for finding if player is in the table

--val = Playing 
function module:PlayerIsInTable(player,val)
	if Tables[val] then
		if Tables[val][player] then
			return true
		end
	end
	print('not in table')
	return nil
end

1 answer

✓ Accepted answer

You're problem lies with how the PlayerIsInTable function checks to see if the player is there. The values inside a table are identifiable using a key, if not specified a key, which is usually the case when using table.insert, the key is the position it is in in the table.

So, the reason your function can't find the value, the player, in the table, is because the player object you are using to find the value, the player, isn't used. How do we fix this then?

Since you don't know where slot the player is being saved to inside Tables[val], you have to go through each value inside that table and see if that value is the player.

--val = Playing 
function module:PlayerIsInTable(player,val)
    if Tables[val] then
        for _,v in pairs(Tables[val]) do
            if v==player then
                return true
            end
        end
    end
    print('not in table')
    return nil
end

This discussion is preserved as it was. New answers, comments, and votes are closed.