lua-users home
lua-l archive

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


Gang,

I'm continually impressed with lua and its flexibility. So I intuitively know what I want to do is possible, but I keep asking more and more tweaky things of lua and get more and more confused the more abstract of a thing I try. And again, I need help getting my head around this one.

OK, I have a userdata "object": obj I have a metatable associate with it so it can have methods and data (obj:Foo(), obj.bar = 4)

Goal: I now want to have it inherent from another object: x, where is is a table or a userdata

x = { Bar = function() print("bar") end }

So that after calling SetInhereitance(obj, x) I can then calll: obj:Bar()...

So I want to patch in a new metatable that will, for any __index call (to start with) it will first call the original metatable and if something is found, return that. Otherwise it'll index x to see if it has anything, returning the result.

But now matter what I try I cant get this to work. I think I have a solution were obj a table but not for user data. For illustration purposes, this is the direction I've been going:

SetInheritance = function(obj, parent)
local nmt

obj.omt = getmetatable(sf)
nmt = obj.omt
nmt.__index = function(object, key)
local result = rawget(object, "omt")[key]
if result then return result end
return parent[key]
end
application:SetObjectMetatable(sf, nmt)
end

I *think* this conceptually encapsulates (heh, no pun intended) my approach. But obviously the rawget doesnt work on a userdata type. And If I try object.omt[key] I of course get a recursive stack overflow...

I'm pretty sure there is a way to accomplish this with storing an associate between obj and its original metatable (omt) in some other table, but I'd really like to store the original within the userdata itself. But I think I may be looking down the throat of disappointment on this one. Am I wrong?

Anyone know how to accomplish what I'm looking to do?

thx,
ando