lua-users home
lua-l archive

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


It's  hard to figure out exactly how you've implemented the widget object produced by widget.create() Is it a Lua table, or a Lua userdata object? Personally I would choose a userdata object, defined (loosely) as

struct widget
int x, y, w, h; // hot spot
int values; // lua values associated with this widget

'values' would contain a value produced by 'luaL_ref', which refers to a table. The metatable for the userdata object would implement the following functions:

__index: looks up values in the table referred to by 'values', and potentially in a shared table as well. You can store this table in the registry.
__newindex: stores value in the table referred to by 'values', indexed by key.
__gc: calls luaL_unref on 'value' to allow collection of the table. If you keep the 'widget' structure in a linked list this is the routine that should remove it.

The routine that dispatches the left click should identify the correct 'widget', get the table associated with the widget, get the 'leftclick' value, and if it's not nil call it with the widget as its first argument.

I've attached some crude sample code.

Attachment: widget.c
Description: Binary data

Attachment: test.lua
Description: Binary data


On Jul 7, 2008, at 11:35 AM, Max van Rooij (van Rooij Electronics Design & Software Engineering) wrote:

Dear all,
I'm new to Lua and very enthusiastic about it, especially in it's ability to interface with C. I've written a GUI in C and have given the users the ability to customize behaviours (such as mouse clicks) in Lua.
I've defined a so called "click-able" region as a struct in C. The user can create a region that's click-able in a lua script with a single line like this:
mywidget1 = widget.create(100,100,10,10) --create click-able region at (x,y) = 100,100 width 10 and height 10
By implementing the __index in C code, the user can write:
function mywidget1:leftclick
print("hurray! a left click!")
Now, the C code is capable to relate the clicked region to the right Lua object and a get a nice "hurray!" printed. Unfortunatly, if my user does:
mywidget1 = widget.create(100,100,10,10)
mywidget2 = widget.create(110,110,20,20)
function mywidget1:leftclick
print("left click widget 1")
function mywidget2:leftclick
print("left click widget 2")
I always get "left click widget 2". This is, because the widgets share the same method table, so the last definition simply overwrites all previous ones. How do I change my C code, so my users can have the above code working?

Gé Weijers