lua-users home
lua-l archive

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


I'm working on integrating some C code with Lua. The C code is
dynamically bound, so I'm able to do things like the following:

void *obj = obj_new("name_of_obj");
obj_method(obj, "draw");
obj_method(obj, "scale", 2, [0.5, 0.5]);
...

The above C code will allocate an object, then call the object's draw
method, and then set the object's scale parameter.  What I'd like to
be able to do with Lua is the following

obj = Obj.new("name_of_obj");
obj:draw()
obj.scale = {0.5, 0.5}


You can do it with metatables and closures.

Consider the following function, to be used as the __index field of
your userdata metatable.

local function __index(u, k)
 return function(u, ...) return obj_method(u, k, ...) end
end

With this setup:

0) obj:draw() stands for (obj.draw)(obj)

1) obj.draw triggers the metamethod: __index(obj, "draw")

2) __index returns a closure where k is bound to "draw":

 function(u, ...) return obj_method(u, "draw", ...) end

3) the closure is called with obj: obj_method(obj, "draw")

Once you get the knack of both metatables and closures you can mold
about any object system you like.

For properties, you will need a thin reflection layer to distinguish
them from methods, and to marshal arguments as C arrays like your
example suggests. But the basic mechanisms are the same.

I hope this helps.