My local players
table uses the PlayerServerId as Index.
When i now want to access the player data at Index 1 (My PlayerServerId) i get nil
as a result.
But when i now iterate through the players table and print out the index for the iterations, I get the Index 1 (like how i expect)
Debug Code:
print("PlayerServerId: ".. GetPlayerServerId(PlayerId())) -- --> Output: "PlayerServerId: 1"
print(players[1]) -- --> Output "nil"
for i, player in pairs(players) do
print("Index: " .. i) -- --> Output: "Index: 1"
end
Output:
How is this possible? What am i doing wrong or what do I oversee?
I tried to debug every single step to make sure the data i want to access is available.
i
is probably the string "1"
.
1 ~= "1"
due to things of different types never being equal in Lua. So t[1]
can be nil
, while t["1"]
can be something else.
When you iterate with pairs
, you also iterate over string keys. print("Index: " .. i)
will then print Index: 1
if i
is the string "1"
. It would also print the same if i
was the number 1
.
Effectively, your print
debugging is flawed, because it performs number to string coercion. To properly debug, you need something that tells you the type as well, for example by quoting strings.
I would recommend using something like inspect.lua
or writing your own equivalent. For now, printing type(i)
as well should tell you everything you need to know.