如何通过引用分配lua变量 [英] how to assign lua variable by reference

查看:121
本文介绍了如何通过引用分配lua变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I assign a variable by reference in Lua to another one?

例如:想做"a = b"的等效项,其中a将成为指向b的指针

For example: want to do equivalent of "a = b" where a will then be a pointer to b

背景: 在某些情况下,我实际上有这样的事情:

Background: have a case where I have effectively something like this:

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.

PS. For example in the below it appears apparent the b=a is by value. NOTE: I'm using Corona SDK.

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

-- OUTPUT: a/b: 2   1

推荐答案

关于您明确的帖子和示例,在Lua中没有您想要的引用类型.您希望一个变量引用另一个变量.在Lua中,变量只是值的名称.就是这样.

regarding your clarifed post and example, there is no such thing as a the type of reference you want in Lua. You want a variable to refer to another variable. In Lua, variables are simply names for values. That's it.

以下方法起作用,因为b = a使ab都引用相同的表值:

The following works because b = a leaves both a and b referring to the same table value:

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中的所有变量分配视为参考.


You can think of all variable assignments in Lua as by reference.

从技术上讲,这适用于表,函数,协程和字符串. 对于数字,布尔值和nil也是正确的,因为它们是不可变的类型,因此就您的程序而言,没有区别.

This is technically true of tables, functions, coroutines, and strings. It may as well be true of numbers, booleans, and nil, because these are immutable types, so as far as your program is concerned, there's no difference.

例如:

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


Short version: this only has practical implications for mutable types, which in Lua is userdata and table. In both cases, assignment is copying a reference, not a value (i.e. not a clone or copy of the object, but a pointer assignment).

这篇关于如何通过引用分配lua变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆