我尝试有效地制作 lua 表的副本。我编写了以下运行良好的函数 copyTable() (见下文)。但我想我可以使用函数的“按值传递”机制获得更有效的东西。我做了一些测试来探索这个机制:
function nop(x)
return x
end
function noop(x)
x={}
return x
end
function nooop(x)
x[#x+1]=4
return x
end
function copyTable(datatable)
local tblRes={}
if type(datatable)=="table" then
for k,v in pairs(datatable) do tblRes[k]=copyTable(v) end
else
tblRes=datatable
end
return tblRes
end
tab={1,2,3}
print(tab) -->table: 0x1d387e0 tab={1,2,3}
print(nop(tab)) -->table: 0x1d387e0 tab={1,2,3}
print(noop(tab)) -->table: 0x1e76f90 tab={1,2,3}
print(nooop(tab)) -->table: 0x1d387e0 tab={1,2,3,4}
print(tab) -->table: 0x1d387e0 tab={1,2,3,4}
print(copyTable(tab)) -->table: 0x1d388d0
Run Code Online (Sandbox Code Playgroud)
我们可以看到,对表的引用通过函数(当我刚刚读取它或添加内容时)不变地传输,除了在 noop() 中,我尝试对现有的进行彻底修改。
我读了Bas Bossink和Michael Anderson在这个 Q/A中的回答。关于将表或表作为参数传递,他们强调了“通过引用传递的参数”和“通过值和表传递的参数是引用”之间的区别,并举例说明了这种差异的出现。
但这到底意味着什么呢?我们是否有引用的副本,但这与传递 ref …
lua arguments parameter-passing deep-copy pass-by-reference-value
我在lua中写了很多互相调用的函数。
lua中是否有“前向声明”这样的概念?
这将允许我声明所有没有实现的函数,然后稍后实现它们。然后我就可以解决函数的顺序问题。