如何通过Lua中的引用将变量分配给另一个变量? 例如:想要相当于“a = b”,其中a将是指向b的指针 背景: 有一个案例我有效地这样: local a,b,c,d,e,f,g -- lots of variablesif answer == 1 then --
例如:想要相当于“a = b”,其中a将是指向b的指针
背景:
有一个案例我有效地这样:
local a,b,c,d,e,f,g -- lots of variables if answer == 1 then -- do stuff with a elsif answer == 1 then -- do stuff with b . . .
PS.例如,在下面,显然b = a是值.注意:我正在使用Corona SDK.
a = 1 b = a a = 2 print ("a/b:", a, b) -- OUTPUT: a/b: 2 1编辑:关于你澄清的帖子和例子,在Lua中没有你想要的参考类型.您希望变量引用另一个变量.在Lua中,变量只是值的名称.而已.
以下是有效的,因为b = a使a和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中的所有变量赋值都考虑在内.
这在技术上适用于表,函数,协同程序和字符串.数字,布尔值和零也可能是正确的,因为这些是不可变的类型,所以就你的程序而言,没有区别.
例如:
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.在这两种情况下,赋值都是复制引用,而不是值(即不是对象的克隆或副本,而是指针赋值).