Table.insert inserts changes all element's values(SOLVED)

Hello everyone,
Just a strange thing happened today. While registering my racers using

local function register_racer(self, id)
	self.new_racer = racer
	self.new_racer.my_id = id
	self.new_racer.pos = go.get_position(id)
	self.new_racer.position = #racers + 1
	pprint(self.new_racer)
	table.insert(racers,#racers +1, self.new_racer)
	pprint(racers)
end

I get some thing totally off - Every value in the table is changed, have a look here(There are just continuous output)

Any ideas about what is happening here?
Thanks in advance

What is racer that you are assigning to self.new_racer?
What I can tell you are assigning the same table to self.new_racer, altering that tables element somewhat and then inserting it in the table.
As it is a reference to the same table, all fields in the indexed table will be altered and get the last values.

4 Likes

The racer table is

local racer = {
position = 0,
id = hash(""), -- just a placeholder for go's id 
}

Looks like what you mentioned is correct, so initializing self.new_racer to an empty table will do the trick, isn’t it?

Yes as long as you are not reusing the table. In this case there are no need creating the racer object beforehand as both the position is wrong type (not a vector3) and not used and same thing with the id which you are overwriting them both.
If you are not using self.new_racer anywhere else as explicit the last racer that was registered then you could easily do with:

local function register_racer(self, id)
  table.insert(racers, {
    my_id = id,
    pos = go.get_position(id),
    position = #racers + 1
  })
end

Also you can skip the #racers + 1 in the insert command as it will be added to the end of the table if not defined otherwise. Good luck!

Oh yes!! It’s working now. Thanks a ton @andreas.strangequest

1 Like