6

如何通过 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
4

2 回答 2

12

编辑:关于您澄清的帖子和示例,在 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

您可以将 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。在这两种情况下,赋值都是复制引用,而不是值(即不是对象的克隆或副本,而是指针赋值)。

于 2012-06-27T02:16:06.030 回答
-1

确实,变量只是值的名称。但是,如果您正在处理表中的键,则可以计算变量名。这意味着您可以使用键名来执行条件逻辑。

myvars = { a=1, b=2, c=3.14 }

function choose(input)
    print(myvars[input])
end

choose('a')
choose('b')
a = 'a'
choose(a)
b = a
choose(b)
a = 'c'
choose(a)
choose(b)

输出:

1
2
1
1
3.14
1
于 2012-08-03T23:14:35.710 回答