[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: References (as in Perl)
- From: David KOENIG <karhudever@...>
- Date: Mon, 18 Dec 2006 08:53:13 -0800
Jérôme VUARAND wrote:
> 2006/12/18, David KOENIG <karhudever@gmail.com>:
>> 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
> print(b[1])
>> foo
> a[1] = "bar"
> print(b[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
> print(b._)
>> foo
> a._ = "bar"
> print(b._)
>> 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;
> })
> end
>
> a = box("foo")
> b = a
> print(b())
>> foo
> a._ = "bar"
> print(a())
>> bar
> print(b())
>> 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)
>
Thanks for the help. I'm just playing around still and seeing what I can
do in here. I really like the easy currying and such--with a couple
functions, Lua actually makes a pretty good functional language.