lua-users home
lua-l archive

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


This idea almost works. The problem is that userdata isn't a table, and can't store values. That means that lobj.x = 6 won't work.

But you can add a __newindex function to your metatable and use that to store the value and the key somewhere useful. If you want to update members of the c++ class, you could call lobj->Setx(6) in the __newindex function.

You said, though, that you wanted to store lua data. One way to do this is to create a table (let's call it 'x') during create_my_cpp_obj_and_return_lua_data() and store it in the table you're going to use as the metatable.

Then, have your __newindex function write the key and value to the 'x' table. You'll also have to change your __index function to look in table 'x' before the table of c++ methods, but that's okay because it will allow you to overload the c++ functions in lua.

The only drag about this situation is that you don't have a way to access the Lua objects from the c++ side.

Rob Sadedin wrote:

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