lua-users home
lua-l archive

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


gary ng wrote:
> Given the following construct(as mentioned in PIL)
> 
> A={}
> 
> function A:new(o)
>  local o=o or {}
>  setmetatable(o,self)
>  self.__index = self
> end
> 
> function A:foo()
>  print("foo of A")
> end
> 
> a=A:new()
> 
> how can I easily define a method a.foo which is equivalent to this :
> 
> function a.foo()
>  a.super.foo()
>  print("foo of a")
> end
> 
> which has this output :
> 
> foo of A
> foo of a

Here is a slightly modified version of your code that do what you want.
I put three alternative solutions. foo is the closest from your original
example. bar is slightly better. baz is the best. IMHO baz is the way to
go.

A={}

function A:new(o)
    local o=o or {}
    setmetatable(o,self)
    self.__index = self
    self.super = self --< You can simply define super to point to the
class itself
    return o --< You forgot to return the object
end

function A:foo()
    print("foo of A")
end
function A:bar()
    print("bar of A")
end
function A:baz()
    print("baz of A")
end

a = A:new()

function a.foo()
    a.super.foo()
    print("foo of a")
end
function a.bar(a) --< You should pass a as parameter
    a.super.bar()
    print("bar of a")
end
function a:baz() --< Even better, use implicit self
    self.super.baz() --< Here use self instead of a
    print("baz of a")
end

a.foo()
a:bar() --< Method syntax is more suited to methods
a:baz() --< Method syntax is more suited to methods