Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I get the max index in a table?

Asked by
emervise 123
3 years ago

Hello, I am making a players table so I can easily access players, but here is my problem:

local playersTable = {}

game.Players.PlayerAdded:Connect(function(player)
    table.insert(playersTable, table.getn(playersTable) + 1, player)
end)
print(playersTable)

Once I run this script I get this in the output: table: 0x51474be0bb02eb5c I probably shouldn't use table.getn I'm guessing? If not then what could I use? Sorry if this question is easy, but I look over the developer hub and couldn't find anything

1 answer

Log in to vote
1
Answered by 3 years ago

You are getting the "strange" output because you are outputting the table itself and not the contents of the table. A simple for loop can fix that:

for i,v in pairs(playersTable) do
    print(v) -- v would be the entry and i is the index (position in the table)
end

Additionally to get the amount of entries in a table just do #playersTable. In this specific use case you wouldn't need to even specify the index number since new table entries will always default to #table + 1 (which is what you are doing)

0
Thank you! emervise 123 — 3y
Ad

Answer this question