tags:

views:

444

answers:

2

I have C++ objects and I have Lua objects/tables. (Also have SWIG C++ bindings.)

What I need to be able to do is associate the two objects so that if I do say

CObject* o1 = getObject();
o1->Update();

it will do the equivalent Lua:

myluatable1.Update();

So far I can imagine that CObject::Update would have the following code:

void CObject::Update(){
    // Acquire table.

    // ???

    // Do the following operations on the table.
    lua_getfield(L, -1, "Update");
    lua_pcall(L, 0, 0, 0);
}

How would I store/set the Lua table to be used, and what would go in the // ??? above to make the Update call work?

+2  A: 

I am curious for the reasons of this "reverse SWIG"...

The objects in Lua live within the Lua contexts, so at a minimum you would need to store "L" inside your object.

The issue of passing the "table pointer" is a bit more delicate - even though Lua allows to retrieve the pointer off the Lua stack (using lua_topointer()), there is no way of putting that back. Understandingly - because otherwise one would also need to check that the pointer does point to a valid object, etc, etc.

What you might do however, is to store the references to the tables in the global table, the index being the lightuserdata being the pointer to your object. Then by having the Lua state, and the name of the global array, you can retrieve the reference to the table and push it onto the Lua stack for that context.

This is sketchy, and I haven't even touched the question of garbage-collecting with this construct.

But in any case this is not going to be the speed racer performance-wise, and looks like a lot of boilerplate C++ code to me. I'd try to reconsider the approach and push some of what you want to do into the Lua domain.

p.s. looks like it is the third question which seems almost a dupe of the previous two ones, here and here are the previous ones. If those were not answered fully, would have been better to edit them/add the bounty to accumulate the answers.

Andrew Y
the 3 questions have their differences although they have the same eventual goal, I can move all this into pure lua in one project solving the problem, but this for another project it would require me to rewrite large swathes of the project.
Tom J Nowell
Ah ok, thanks. Nevermind my p.s. then and good luck!
Andrew Y
+2  A: 

I cant believe nobody noticed this!

http://www.lua.org/pil/27.3.2.html

A section of the Lua API for storing references to lua objects and tables and returning references for the purposes of being stored in C structures!!

Tom J Nowell