Wrong variable update in PICO-8

160 views Asked by At

I was building a simple snake game from scratch as practice for PICO-8 and Lua.

I'm attempting to have the body follow the head by creating a copy of the old body locations and update along the length.

I created a t_old variable to store the original body locations but it is being updated at the same time as t. I lack an explanation as to why.

function train_move(t,d)
 local t_old=t --grab existing
 --update head based on direction of movement
 if d==0 then 
  t[1].x-=sprite_size --left
 elseif d==1 then
  t[1].x+=sprite_size --right
 elseif d==2 then
  t[1].y-=sprite_size --up
 else
  t[1].y+=sprite_size --down
 end
 --update body **I have noticed that t[1]==t_old[1] here??
 for i=2,#train do
  t[i].x=t_old[i-1].x
  t[i].y=t_old[i-1].y
 end
 return t
end
1

There are 1 answers

0
Piglet On BEST ANSWER

Table values are copied by reference.

t and t_old refer to the same table value.

Read this How do you copy a Lua table by value?