lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 12/18/06, David KOENIG <karhudever@gmail.com> wrote:
Is there any way to make two variables point to the same exact object,
as with references or typeglob assignment in Perl?

Example in Perl:
$a = 5;
*b = $a;
print $b; #prints 5
$a = 6;
print $b; #prints 6

I've tried messing with _G and all that, but no luck so far.

All Lua variables are, indeed, *references* to Lua objects.
str= "Hello"
local s= str

Both 's' and 'str' refer to the very same object, string "Hello".
Since strings and numbers are immutable in Lua, Lua reference
mechanism does not help you to mimic in Lua your Perl code example. To
get what you want you need to rely upon some mutable Lua object that
is a table. As it was suggested previously in this thread, wrap your
number in a Lua table:
a= {5}
b= a
a[1]= 6
print(b)

On a personal note, I really like the fact that Lua has only one way
to referencing objects. It is simple, uniform and makes code readable
(unlike Perl). Special cases like the one you described can be handled
in Lua as well, albeit in a bit "ugly" fashion when applied to numbers
or strings (explicit boxing needed).

--Leo--