lua-users home
lua-l archive

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


Am 25.08.2013 15:50 schröbte Philipp Kraus:
On 2013-08-23 16:45:09 +0000, Philipp Kraus said:

I can do x.test() or x:test(), both calls result nil.
The parameter "self" is always nil, so imho I have a wrong definition
in my metatable

[...]

            __index = function(self, key, ...)

The __index metamethod gets called with only two arguments (self and key), so your vararg list is always empty. So ...

                local lxReturn = self.__instancedata[key]

                if type(lxReturn) == "function" then
                    return lxReturn( self.__instancedata, ... )

... this function is always called with exactly one argument (self.__instancedata). All other explicit parameters will be nil, and a vararg parameter list will be empty.

                end

[...]

I run this with
local myClass = class("MyClass")

function myClass:constructor( self, pxID )
    self.id = pxID
end

function myclass:test(self, ...)

If you define your methods using the colon operator you already get an implicit self parameter, so your function definition is equivalent to:

    function myclass.test( self, self, ... )

where the second self parameter shadows the first one. As stated above, the second self argument will always be nil, and the vararg parameter list will be empty. The constructor function has a similar problem ...

    print(self)
end


local x = myClass( 123 )
x:test()

the print(self) results always nil. the __call and __gc works well also
the __newindex, but the __index does not work

Using __index for method calling will not work, because then you can't pass arguments to the method. It must always be a two-step process, where you return something callable from your __index metamethod.

Remember that `x:test()` is the same as `x[ "test" ]( x )` and you are trying to do all the work in `x[ "test" ]` ...


Thanks for help

Phil

HTH,
Philipp