1

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
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

2

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?

Piglet
  • 27,501
  • 3
  • 20
  • 43