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
Lua's function , table , userdata and thread (coroutine) types are passed by reference. The other types are passed by value.
As the name implies, we use references mainly when we need to store a reference to a Lua value inside a C structure. As we have seen, we should never store pointers to Lua strings outside the C function that retrieved them. Moreover, Lua does not even offer pointers to other objects, such as tables or functions.
The lua_State is basically a way to access what's going on in the Lua "box" during execution of your program and allows you to glue the two languages together.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With