lua-users home
lua-l archive

Re: Inheriting from a userdata object

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


于 2012年6月18日 17:06, Stephen Virgo 写道:
[

reduce to

__proto__.out(__proto__,"foo") ?

i don't use the ":" sugar much, but, i didn't think it was that sophisticated... shouldn't it just yield

__proto__.out( my_game ,"foo") ?



I think you could be correct, the lua snippet from Peng Zhicheng didn't work with the same "calling 'out' on bad self (game_class expected, got table)" error. I wonder if this is possible..

*account changed to prevent corporate sig spam
sorry about that. the code in my last post is incorrect.
one possible working __index function might be like this:

---------------------------- code begine -------------------------------------
---
-- the __index meta method will do the following:
-- firstly get the indexed field of the wrapped object(i.e. the proto)
-- if the field is not a method(i.e. function), just return it
-- else return a wrapped function to call the method on the wrapped object
-- note however if the field indexed is just retrived but not called on
-- the wrapper object, unwanted behavior might occur.

function game_wrapper_mt:__index(key)
local proto = rawget(self, "__proto__")
local field = proto and proto[key]
if type(field) ~= "function" then
return field
else
return function (obj, ...)
if obj == self then
return field(proto, ...)
else
return field(obj, ...)
end
end
end
end
----------------------------- code end ---------------------------------------

best regards.


AltStyle によって変換されたページ (->オリジナル) /