memory - Lua 表 : how to assign value not address?

标签 memory lua lua-table luajit

这是我的代码:

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_tab1test_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/

相关文章:

c++ - Lua 保留全局值

sorting - 如何在记录原始位置的同时对表格进行排序?

Lua 弱引用

r - 不同大小矩阵的相同内存使用

javascript - Node.js、Jsdom、HttpAgent 的内存使用情况

lua - 为什么可以将 __index 设置为等于表

Lua - 删除非空目录

python - 在 Python 中通过 ctypes 调用 GetExtendedTcpTable 时,谁负责释放 MIB_TCPROW_OWNER_PID 结构?

从 Xcode 启动 iPhone 应用程序会崩溃,但从 iPhone 启动时不会崩溃

Lua reference function from inside table inside the table (Using "self"inside of table)