This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Wilma456's profile picture

table is not copied

Started by Wilma456, 28 May 2017 - 10:18 AM
Wilma456 #1
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?
Wojbie #2
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...TablesTutorial
Your 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
Bomb Bloke #3
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].