这是我的代码:
test_tab1={}
test_tab2={}
actual={}
actual.nest={}
actual.nest.a=10
test_tab1=actual.nest
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 10
actual.nest.a=20
test_tab2=actual.nest
print("test_tab2.a:" .. test_tab2.a) -- prints test_tab2.a equal to 20
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 20
实际输出:
test_tab1.a:10
test_tab2.a:20
test_tab1.a:20
根据我的理解,test_tab1
和 test_tab2
都指向同一个地址,即 actual.nest 所以当我分配 actual.nest.a =20
test_tab1.a
的值也更改为 20,之前为 10。
预期输出:
test_tab1.a:10
test_tab2.a:20
test_tab1.a:10
谁能帮我得到这个输出?如果我第二次更改 actual.nest.a=20
它不应该反射(reflect)在 test_tab1.a
即 10
最佳答案
您必须将表从source
复制/克隆到destination
。执行 t1 = t2
只是将 t1
t2
的地址分配给 t1
。
这是 shallow copy method 的副本你可以使用:
function shallowcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
actual={}
actual.nest={}
actual.nest.a=10
test_tab1 = shallowcopy(actual.nest)
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 10
actual.nest.a = 20
test_tab2 = shallowcopy(actual.nest)
print("test_tab2.a:" .. test_tab2.a) -- prints test_tab2.a equal to 20
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 20
关于memory - Lua 表 : how to assign value not address?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39567123/