Need help with table.insert and updating already existing values

I have a looping function that creates a table and inserts position values into it. the issue is that the values themselves more and more times each time the loop runs. I need the values not to duplicate because I will use table.sort later on. However, i do need the values to update themselves (the positions will be moving). how do I update the values after initally retrieving them without them cloning themselves?

the script:

while x == true do
	wait(1)
for i, v in ipairs(workspace:GetChildren()) do
	if v:IsA("Model") then
			local human = v:FindFirstChild("HumanoidRootPart")
			if human then
					table.insert(pos_tracking, human.Position)	
			end
	end
end end end

an example of the duplicating i’m referring to: (notice the numbers repeat again and again)

You have a while-loop that runs every second. Each time it adds a bunch of values based on your NPC and players in workspace. The list gets longer each second.

Probably you want to make a new list every time. You could just overwrite it with an empty list {} each time at the beginning of the loop.

2 Likes

this solution solved my problem. thank you

1 Like

I’d recommend using table.clear(t) where t is a variable reference/pointer to the table value, if you intend on reusing the table.

2 Likes

Indeed, depending on if you want to conserve or refresh the reference to your original table, in this case you could use table.clear, instead of making a new empty table and overwriting your variable with it. I think table.clear might actually cost slightly more CPU, but it doesn’t matter for small tables.

1 Like