lua-users home
lua-l archive

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


A useful indexing trick is to use a table for your metatable's __index
member rather than a function.  When you do this the VM will just look up
the requested key in that table.  Thus you don't have to write any lookup
code for your member functions, all you have to do is supply a table
containing the member functions.  (You might have already been doing this.)

Adding per instance Lua data to userdata is, however, something of a failing
of Lua 5 (and you can find a LOT of discussion of this in the list
archives).

Here, are a couple of ways to go about it...

1. Use a weak keyed table to map userdata instances (as keys) to tables
holding the per userdata instance Lua data (as values).  Then you'll have to
write the userdata's __index method as a function that understands this
mapping.  This allows all userdata instances of a particular "type"/"class"
to use the same metatable (which in turn means that the metatable can be
used as a type identifier).  However, if any of the per userdata instance
Lua data refers back to the userdata instance this will create an
uncollectable cycle.

2. Supply a Lua table as the object instance rather than supplying the
userdata directly, fill in the table with function closures for your
methods.  Each closure should be given an upvalue that references your
userdata.  Since the userdata itself is not directly accessed by Lua code it
can be either a full userdata or a light userdata, however, only a full
userdata can have a metatable and __gc metamethod.  In this way your methods
can have access to both the C side data (the userdata upvalue) AND the per
instance Lua data (the table itself).  However, the __gc metamethod won't
have access to the Lua data.



-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br]On Behalf Of Rob Sadedin
Sent: Monday, August 09, 2004 9:55 PM
To: Lua list
Subject: Object oriented access of c++ objects in lua


Hey all, some advice, if you don't mind:

I'm accessing a number of c++ objects by create a lua user data that
contains a pointer to the object, and sets a meta table that fires on
indexing that points to functions that link to the appropriate c++ methods
for the given object.

lobj = create_my_cpp_obj_and_return_lua_data()
lobj::callsomecppmethod()


Is this a sensible method, and if not, what would be better?

Secondly, I'd like the users to be able to add lua data to the c++ objects.

That is, say something like:

-- Set a variable
lobj.x = 6


waaaaay later in the code:

lobj = get_that_object_I_created_before_and_stored_in_a_cpp_list_somewhere()

print(lobj.x)

* this should output 6 ... well, I'd like it to :)

I hope this makes sense, thanks guys,


Rob