lua-users home
lua-l archive

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

2006/12/18, David KOENIG <>:
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.

Lua has no general references to any kind of value, so you will never
have the same kind of syntax that what you quote with stock Lua. It
has references to tables, functions, threads and userdata. You have to
put your value in one of these types. The table is the easiest to use,
and then you can have two variables point to that table.

a = {"foo"}
b = a
a[1] = "bar"

This has the drawback that you must use [1] for each variable access,
except initialisations that need {}. You can use a single character
field name, which may overall save some characters :

a = {_="foo"}
b = a
a._ = "bar"

There are other mechanisms to box a value that way. The principle is
to associate it with a kind of value that is held by reference in Lua.
That the case for tables (my example above), userdata, functions and
threads. Alternatively you can put it in the metatable of an empty
table/userdata, or in the environment of an empty function/userdata.
You can also play with metamethods to have a better syntax :

function box(value)
  return setmetatable({_=value}, {
     __call=function(t) return t._ end;

a = box("foo")
b = a
a._ = "bar"

If you really need the perl syntax you can use token filters or
metalua to create a reference mechanism that would do all that for you
at preprocessing.

(Sorry for the overlong answer, but your mail title is likely to be
found often in future searchs, so a complete answer seemed a good idea
to me)