加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何通过引用分配lua变量

发布时间:2020-12-14 21:47:38 所属栏目:大数据 来源:网络整理
导读:如何通过Lua中的引用将变量分配给另一个变量? 例如:想要相当于“a = b”,其中a将是指向b的指针 背景: 有一个案例我有效地这样: local a,b,c,d,e,f,g -- lots of variablesif answer == 1 then -- do stuff with aelsif answer == 1 then -- do stuff wit
如何通过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 = 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,3
print(b.value) -- Testing 1,3

a = { value = "Duck" }

-- a now refers to a different table; b is unaffected
print(a.value) -- Duck
print(b.value) -- Testing 1,3

您可以通过引用将Lua中的所有变量赋值都考虑在内.

这在技术上适用于表,函数,协同程序和字符串.数字,布尔值和零也可能是正确的,因为这些是不可变的类型,所以就你的程序而言,没有区别.

例如:

t = {}
b = true
s = "testing 1,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.在这两种情况下,赋值都是复制引用,而不是值(即不是对象的克隆或副本,而是指针赋值).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读