如何通过引用分配lua变量

Gre*_*reg 6 lua

如何通过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
.
.
.
Run Code Online (Sandbox Code Playgroud)

PS.例如,在下面,显然b = a是值.注意:我正在使用Corona SDK.

a = 1
b = a
a = 2
print ("a/b:", a, b)

-- OUTPUT: a/b: 2   1
Run Code Online (Sandbox Code Playgroud)

Mud*_*Mud 10

编辑:关于你澄清的帖子和例子,在Lua中没有你想要的参考类型.您希望变量引用另一个变量.在Lua中,变量只是值的名称.而已.

以下工作原因是,b = a将两者都保留ab引用相同的表值:

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
Run Code Online (Sandbox Code Playgroud)

您可以通过引用将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 --
Run Code Online (Sandbox Code Playgroud)

简短版本:这只对可变类型有实际意义,在Lua中是userdata和table.在这两种情况下,赋值都是复制引用,而不是值(即不是对象的克隆或副本,而是指针赋值).

  • 好的,谢谢 - 所以我猜我正在做的事情是可能的,但是我需要把变量放在一个表中然后才对吗? (3认同)