编辑:关于您澄清的帖子和示例,Lua 中不存在您想要的参考类型。您希望一个变量引用另一个变量。在 Lua 中,变量只是值的名称。就是这样。
以下工作是因为b = a
两者都留下a
and b
引用同一个表值:
a = { value = "Testing 1,2,3" }
b = a
-- b and a now refer to the same table
print(a.value) -- Testing 1,2,3
print(b.value) -- Testing 1,2,3
a = { value = "Duck" }
-- a now refers to a different table; b is unaffected
print(a.value) -- Duck
print(b.value) -- Testing 1,2,3
您可以将 Lua 中的所有变量赋值视为通过引用。
从技术上来说,表、函数、协程和字符串都是如此。它也可以数字、布尔值和 nil 都是正确的,因为这些是不可变的类型,所以就你的程序而言,没有什么区别。
例如:
t = {}
b = true
s = "testing 1,2,3"
f = function() end
t2 = t -- t2 refers to the same table
t2.foo = "Donut"
print(t.foo) -- Donut
s2 = s -- s2 refers to the same string as s
f2 = f -- f2 refers to the same function as f
b2 = b -- b2 contains a copy of b's value, but since it's immutable there's no practical difference
-- so on and so forth --
简短版本:这仅对可变类型有实际影响,在 Lua 中是 userdata 和 table。在这两种情况下,赋值都是复制引用,而不是值(即不是对象的克隆或副本,而是指针赋值)。