如何在Lua中通过引用将变量分配给另一个变量?

例如:想做等价于“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 = aab都引用同一个表值,因此可以使用以下代码:

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中的所有变量赋值视为引用。

从技术上讲,表,函数,协程和字符串都是如此。数字, bool 值和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。在这两种情况下,赋值都是复制引用,而不是值(即,不是对象的克隆或副本,而是指针赋值)。

关于lua - 如何通过引用分配lua变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11218330/

10-11 22:38
查看更多