zxmatzx
Advanced OT User
Hello,
I realized that if i copy table1, to another table2 field, make changes in table2, table1 will be changed too. I had same problem using C# sometime ago. I want to know WHY its happen and if have some way to avoid that(im using a function to copy that is avoiding it, just wanting to know if have another way).
Ex:
Why its happen? Have another way to solve this? If yes, what should i use?(and why).
Thanks.
I realized that if i copy table1, to another table2 field, make changes in table2, table1 will be changed too. I had same problem using C# sometime ago. I want to know WHY its happen and if have some way to avoid that(im using a function to copy that is avoiding it, just wanting to know if have another way).
Ex:
Lua:
BASE_INFOS = {
[1] = {
name = "adam",
hp = 100,
mp = 50,
atk = 5,
},
[2] = {
name = "jack",
hp = 150,
mp = 10,
atk = 50,
},
[3] = {
name = "john",
hp = 1000,
mp = 500,
atk = 50,
},
[4] = {
name = "rick",
hp = 1,
mp = 5,
atk = 5,
},
}
function getWrongWayJackInfo()
local newInfos = {
nickname = "the ripper",
alive = false,
baseStats = BASE_INFOS[2]
}
--newInfos.baseStats = {name = "jack", hp = 150, mp = 10, atk = 50}
--BASE_INFOS[2] = {name = "jack", hp = 150, mp = 10, atk = 50}
newInfos.baseStats.def = 20
--newInfos.baseStats = {name = "jack", hp = 150, mp = 10, atk = 50, def = 50}
--BASE_INFOS[2] = {name = "jack", hp = 150, mp = 10, atk = 50, def = 50}
end
function getRightWayJackInfo()
local newInfos = {
nickname = "the ripper",
alive = false,
baseStats = tableDeepCopy(BASE_INFOS[2])
}
--newInfos.baseStats = {name = "jack", hp = 150, mp = 10, atk = 50}
--BASE_INFOS[2] = {name = "jack", hp = 150, mp = 10, atk = 50}
newInfos.baseStats.def = 20
--newInfos.baseStats = {name = "jack", hp = 150, mp = 10, atk = 50, def = 50}
--BASE_INFOS[2] = {name = "jack", hp = 150, mp = 10, atk = 50}
end
function tableDeepCopy(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == table then
v = tableDeepCopy(v)
end
copy[k] = v
end
return copy
end
Thanks.
Last edited: