Log In  


I was using a 2d array with a 'cell' object for each grid and found this weird issue. For some reason i can't change a value in a particular cell on a grid without changing it for the whole grid. Hope i explained it clear enough. Here's an example:

cls()
cell={1,1}
arr={{cell,cell},{cell,cell}}

arr[1][1][1]=2

for x=1,2 do
for y=1,2 do
?arr[x][y][1],x*8,y*8,15
end
end

As you can see i'm changing only the first number in the first column and the first row to 2 but the output shows that every first number in the whole grid was changed into 2. Why does that happen??



1

cell remains the same table even when referenced elsewhere, so changing it in one place changes it in all the others. You can make a function which returns a copy of a table

function copytbl(tbl)
 copy={}
 for k,v in pairs(tbl) do
  if typeof(v)=="table" then
   copy[k]=copytbl(v)
  else
   copy[k]=v
  end
 end
 return copy
end

typed on phone and untested but I think that ought to do it


I see it now! thank you @kozm0naut! It just seemed so weird at first. I thought that once its in an array its already a separate copy in each cell🙈



[Please log in to post a comment]