188 posts
Location
Germany
Posted 28 May 2017 - 12:18 PM
I'm working on a game and had a problem. This code isfor changing the map:
gamename.map[posx][posy] = gamename.place
This worked. But if I change gamename.place, the full map is cahnged. This is not in a loop ar something. e.g. gamename.map[1][1] is foo. If I cahnge gamename.place to bar, gamename.map is also foo. Why?
724 posts
Location
Kinda lost
Posted 28 May 2017 - 01:13 PM
This is how tables work in Lua. You can read more about it here:
http://lua-users.org...TablesTutorialYour exact problem is explained in "Table values are references" part.
TLDR: When you run
gamename.map[posx][posy] = gamename.place
you are not creating a copy of table. Exact same reference to table you have in gamename.place is beeng put in gamename.map[posx][posy]. Soo if you change something in gamename.place you effectivly change it in both places due to it beeing reference to same table.
If you want to create a copy of table you have to make a function that goes over said table and manually copies values to 2nd one.
Personally i use this function when i need to copy a table.
local function copyTable(...)
tArgs={...}
local B={}
for _,A in pairs(tArgs) do
if A and type(A)=="table" then
for i,k in pairs(A) do
if type(k)=="table" then B[i]=copyTable( B[i] or {},k)
else B[i]=k end
end
end
end
return B
end
Edited on 29 May 2017 - 08:25 AM
7083 posts
Location
Tasmania (AU)
Posted 29 May 2017 - 01:02 AM
you are not creating a copy of table. Exact same reference to a table you have in gamename.place is beeng put in gamename.map[posx][posy].