[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: OOBit
- From: Gyepi SAM <self-lua@...>
- Date: Wed, 29 Sep 2010 18:43:54 -0400
On Wed, Sep 29, 2010 at 11:25:00PM +0200, Petite Abeille wrote:
> On Sep 29, 2010, at 10:39 PM, Peter Sommerfeld wrote:
> Yes, yes, just sugar... but still... at first glance... OMG!
>
> local aTable = { dwim = function( self ) print( self ) end }
>
> aTable[ 'dwim' ]( aTable )
> aTable:dwim()
> aTable.dwim()
>
> > table: 0x1001058e0
> > table: 0x1001058e0
> > nil
>
> WTF?!? :P
I don't find this confusing at all.
These are all calls to a table key whose value is a function reference to a
function that expects an argument named 'self'.
The argument is explicitly provided in the first case and implicitly
provided in the second. However, in the third case, no argument is provided so
the function prints nil.
> To further confuse matters...
>
> local aTable = setmetatable( {}, { __index = function( self, key ) return function() print( self ) end end } )
>
> aTable.dwim()
>
> > table: 0x1001058e0
This result is to be expected. The function returned from 'aTable.dwim' is a closure,
which, when called, references the 'self' variable that it 'closes over'.
> "Lua gives you the power; you [choose how to hang yourself]" :P
I'm not sure I agree with this. Compared to many other languages, Lua
has very little 'magic'. The confusion may arise from expecting magic
where there is none.
-Gyepi