简体   繁体   中英

Tracking Lua tables in C

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?

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!!

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.

ps 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM