Table.Insert() inserting in weird way (wrong position)

I have code that is supposed to create a table with spawnlocations (not actual spawn locations, just parts) but it is putting the spawnlocations in the wrong position. Code:

for i,level in pairs(levels) do
	local levelNum:number = level:WaitForChild("Level").Value
	local _spawnLocation = level:WaitForChild("Lvl "..tostring(levelNum).." Spawn Location")
	local _spawnHitbox = level:WaitForChild("Lvl "..tostring(levelNum).." Spawn Hitbox")
	table.insert(spawns, levelNum, _spawnLocation)
	table.insert(spawnHitboxes, levelNum, _spawnHitbox)
end

print("spawns:", spawns)
print("hitboxes:", spawnHitboxes)

here is the output:


You can see that the spawn locations are in order but their positions are messed up in multiple areas

Any help is appreciated!

What about, instead of having lots of Values called “Lvl 1 Spawn Location”, “Lvl 2 Spawn Location” etc. and “Lvl 1 Spawn Hitbox”… etc.

Why not just create a dictionary and actually store the real positions, references to parts etc in one single table for easy access?

local Spawns = {}

for i,level in pairs(levels) do
	local levelNum:number = level:WaitForChild("Level").Value
	Spawns[levelNum] = level.Position -- Explandable to store everything you need
end

warn(Spawns)
1 Like

I changed the script to do your table[number] = value vs table.insert() and it seems to be working now. I’ll mark your post as the solution but I would still like to know why the table.insert() wasn’t working

I dont see any reason for that code to fail, there is no way that table.insert() fails or that the iteration fails.
Due to the overcomplicated structure you were using, its hard to maintain hardcorded values, and code that depends on hardcorded stuff, its more likely a human mistake which would be tedious to find.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.