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

What is the highest possible index of a table?

For example, instead of looping through every single player in a table like so


local players = {"player1", "player2"}

game.Players.PlayerAdded:Connect(function(plr)

	table.insert(players, #players + 1, plr.Name) --Getting number of indexed values, and adding 1 to get the next position
	
	local found = false
	
	for k, v in pairs(players) do
		if v == plr.Name then
			found = true
			break
		end
	end
end)

I could just jump straight to the index to which it is located, through the userid

local players = {}

game.Players.PlayerAdded:Connect(function(plr)

	table.insert(playertable, plr.UserId, plr.Name) --jumping straight to a free position, as userid's are unique

	local found = false

	if players[plr.UserId] == plr.Name then
		found = true
	end

end)

In other words, what is the highest a value can be indexed at in a table? Studio crashes if the number is too big

1 answer

✓ Accepted answer

Technically, in Lua, tables can be as large as you want them to. They have no set size. The only limit is the hardware your computer is running on, and probably other things like the limitations of the Lua VM or Roblox engine.

Also, in case you were wondering, you can get the highest index in a table by doing this:

tbl = {"string", "string2", "string3"}
print(tbl[#tbl])

Output: "string3"

Using the # operator gets the length of an array (the size) and indexing it with its size will give you the value at the top-most index.

TLDR: You rarely need to worry about the size of a table in Lua, and the exact largest size you can have is most likely going to vary from person to person.

Also, I want to note; although you can use the UserId for inserting the value into a table, I don't recommend it. The looping method is perfectly fine, and you can store the player's id fairly easily by doing something like this:

tbl[#tbl + 1] = player.UserId

If you do it this way, you can run the in pairs loop and still check the value, without having to worry about weird keys/weird table sizes.

1 comment

0

Also, if a player leaves the game, you should find their position in the table and remove their UserId. By doing this, you can save a bit on memory. (If you set that key to nil, the garbage collector will eventually pick it up and reallocate the memory used). Bit of a micro-optimization, but might actually be of use in a large game with lots of players. (Especially in saving time for the loops)

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