Hi,
Lately after I updated Defold, I found that some problems. I have an example of what happening:
If a have a vector A
local A = vmath.vector3(1, 1, 0)
local B = A
…
B.x = B.x + 1 or something … —> it affected A too: A became (2, 1, 0), not (1, 1, 0) anymore
Same with other datatype like table, …
It drives me crazy. Anh I don’t understand why ? It never happened before.
Please help me. Thanks
Lua objects (tables, userdata objects, like vector3s and functions) are not stored as values in variables, but as references, so this is expected behaviour—your two variables A and B will point to the same vector3 object.
Also note that comparison of some of these objects does not look at the content but at the object itself, so:
local a = {}
local b = {}
print(a == b) // --> false
but (for convenience):
local a = vmath.vector3(1, 2, 3)
local b = vmath.vector3(1, 2, 3)
print(a == b) // --> true
Thanks Defold team.
How can I do this:
Table A = Table B
Insert more value to Table A and not affect Table B. Because I want use B for other thing to do.
That will perform a shallow copy of the table. If you have any nested tables, they won’t get copied, but left as the same reference.
For nested tables you need a recursive deep copy.
Here is some info on that http://lua-users.org/wiki/CopyTable
What you’re looking for is a function to make a deep copy of a Lua table. There are multiple solutions provided on the Lua user wiki, with this being one of the them (beware of deep tables or tables with circular refs as this is a recursive function):
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end