lua-users home
lua-l archive

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

Hello all,

when we have userdata with a metatable as described in the "array" example in the PiL1 or PiL2, chapter 28.3 "Object-Oriented Access" (, I would like to be able to add more functions in Lua.

For example, chapter 28.3 in PiL2 starts with the example

a =
a:set(10, true)

And now I'd like to be able to add a statement like

function a:OnMouseClick()
    -- do something...

The intention here is to call a:OnMouseClick() from C/C++ code later, and overall it means that some "methods" of a would be provided/implemented by C(++) code, and others by Lua code.

When I try to do define a:OnMouseClick() as above, of course there is an error message saying that indexing a is not possible, because it is of type userdata.

==> Is there any way to be able to achieve this anyway??

I looked into the lunar.h template, but it only allows to provide Lua-methods on a per-class basis, e.g. with lunar, we could write

function array:OnMouseClick()
    -- Do something with "self".

    -- Note that this is a class-wide member function ("array"),
    -- not per-instance as with "a" above.

My currently best idea is to have the C++ code create "a" as a normal table, as
    a = { }
would do, then set a field with key "userdata" and value of the original userdata, and finally set its ("a"s) metatable to the metatable of the original userdata... but I really don't know if that can work (will try so now), and/or if maybe there is a much better approach to this problem that I have overlooked.

I'd be very grateful for your help and any comments!

Best regards,

Ca3D - Engine
Carsten Fuchs