Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

how to assign lua variable by reference

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

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. 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: 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.

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

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

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.

For example:

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 --

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...