lua-users home
lua-l archive

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


2014-10-20 11:42 GMT+02:00 Paco Zamora Martínez <pakozm@gmail.com>:

> local metainstance = {
>   __index = {
>     foo = function(self) return self.v end,
>   },
> }
> setmetatable(metainstance.__index, {
>       __index = {
> bar = function(self) return self.v end,
>       },
> })
> setmetatable(getmetatable(metainstance.__index).__index, {
>       __index = function(self,key)
> if key == "baz" then return rawget(self,v) end
>       end,
> })
> local class = {
>   new = function(v) local t = {v=v} setmetatable(t, metainstance) return t
> end,
> }
> local o = class.new(5)
> print( o:foo() )
> print( o:bar() )
> print( o:baz() )
>
> The output of this code is:
>
> 5
> 5
> lua: min.lua:24: attempt to call method 'baz' (a nil value)
> stack traceback:
> min.lua:24: in main chunk
> [C]: in ?
>
> because the nested __index function receives as argument a table which is
> not the caller o table, and the rawget(self,v) function returns nil

o:baz() ->
o.baz(o) ->
o["baz"](o) ->
getmetatable(o).__index"baz"(o) ->
rawget(o,nil) ->
nil

Maybe make that rawget(self,self.v)?