|
Well, to show an example of using __index:On Fri, May 25, 2012 at 3:53 AM, Emeka <emekamicro@gmail.com> wrote:
> Dirk,
>
> If won't mind, I would like to see an example.
>
> Regards, Janus
>
> On Fri, May 25, 2012 at 8:10 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>>
>> 2012/5/25 Tim Mensch <tim-lua-l@bitgems.com>:
>>
>>
>> > The __index metamethod tells Lua what to do if someone tries to look up
>> > an
>> > undefined key on a table.
>>
>> And (ex-Pythonistas please beware) it does NOT override the
>> normal table indexing method when the key is already present.
>>
>
>
>
> --
> Satajanus Nig. Ltd
>
>
>
local meta = {}
local methods = {}
meta.__index = methods
function method:getContent() return self.content end
local myObject = setmetatable({content='hello'}, meta)
print(myObject:getContent()) --prints hello
What you posted about is the same idea, except the metatable points to itself:
local meta = {}
meta.__index = meta
function meta:getContent() return self.content end
local myObject = setmetatable({content='hello'}, meta)
print(myObject:getContent()) --prints hello
The only major difference doing it this way is that now
myObject.__index returns the metatable, since it's now looking in
'meta', instead of 'methods' where no such key exists.
--
Sent from my Game Boy.