Confused about table.insert()

I’ve stopped scripting for a year so spare me. :sweat_smile:

When I was working with table.insert(), I though that of course, it does as it says, inserts a value given into the table.

So of course, applying what I know, I tried doing this:

queuePad.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	
	-- First Part
	if not player then return end
	if leaving[player] or queueTable[player] or #queueTable == playerLimit then return end
	local charRemoving, leavingConnection
		
	-- Second Part
	table.insert(queueTable, player)
	if queueTable[player] then print("Got Player") end
	
	-- Unimportant things continuation.

The first part works as it would “expected”. However, the second part is where it was confusing me.
By doing table.insert(queueTable, player) and checking the queueTable by doing print(queueTable). It would of course show my player HOWEVER before and after:

queuePad.Touched:Connect(function(hit)
   local player = Players:GetPlayerFromCharacter(hit.Parent)
   
   -- First Part
   if not player then return end
   if leaving[player] or queueTable[player] or #queueTable == playerLimit then return end
   local charRemoving, leavingConnection
   	
   -- Second Part
   print(queueTable, "before")
   table.insert(queueTable, player)
   print(queueTable, "after")
   if queueTable[player] then print("Got Player") end
   
   -- Unimportant things continuation.

For some reason, before prints nil and after prints nil.
Only after I try firing the event again will it show and add onto it (in a clunky manner as well).

Doing print(queueTable[player]) also leads to nil.

Since I’m getting no results, I’m pretty sure I’m using table.insert() wrong, any hint/reason/course to how table.insert() works? Thanks. Yes I checked devhub, couldn’t find anything about it or maybe I’m searching wrong.

table.insert() are for array-like tables. i.e. indexed by numbers and have no gaps. If you print the table after insertion you’ll understand what I mean by indexed by numbers

1 Like

To be a little more direct, this little check here needs to be changed to this.
if table.find(queueTable, player) then

1 Like

if table[key] then
would be used for dictionaries. For this to work you would have to set your values by doing table[key] = value, instead of using table.insert().

1 Like

table.insert is working fine. The way you are referencing the player is for dictionaries.

1 Like

Ah, no wonder I was confused. Got table.insert() wrong with dictionaries. :sweat_smile:

I decided to try using table.find() and it seemed to have “resolve” the issue however, several other issues popped up (mostly due to the fact of how my code is structured).

I decided that I’ll just be resorting to the daily average dictionary use and not mess with the table functions until I’ve gotten a better grasp.

Though this’ll be useful in the future :+1: