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(given the Playing table the function should return true).

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

Instead of table.insert(Tables[val],player) in the second block do Tables[val][player] = true

table.insert assigns a number as the key, you’re trying to index the player as the key so you gotta assign it as the key

The values are not saved as indices, so you can’t use that. If you’d want your way to work, you’ll have to do this:

Tables[tbl][player] = true

This is what it should look like:

function find(tbl, player)
   if tables[tbl] then
       for _,v in pairs(tables[tbl]) then
           if v == player then
                return true
           end
       end
   end
    return false
end

You can read about how to insert values into LUA tables on the Developer Hub here.

Basically, instead of,

table.insert(Tables[val],player)

you would want to do,

table.insert(Tables, val, player)

Then, you’d need to change the function module:PlayerIsInTable(player,val) to do

if Tables[val] == player then

instead of,

if Tables[val][player] then