简体   繁体   中英

Calling functions in a Lua table from C++

I have for example, a Lua table/object:

bannana

And this Lua table has a function inside it called chew , that takes a parameter

bannana.chew(5)

I have also used SWIG , and have for example a class CPerson :

class CPerson {
    public:
        // ....
        void Eat();
        // ....
};

I can obtain an instance of this object from Lua:

person = engine:getPerson()

What I need to be able to do is the following Lua code:

person = engine:getPerson()
person:Eat(bannana)

Where person:eat would call the chew function in the bannana table, passing a parameter.

Since CPerson is implemented in C++, what changes are needed to implement Eat() assuming the CPerson class already has a Lua state pointer?

Edit1: I do not want to know how to bind C++ classes to Lua, I already have SWIG to do this for me, I want to know how to call Lua functions inside Lua tables, from C++.

Edit2: The CPerson class and bannana table, are both general examples, it can be assumed that the CPerson class already has a LuaState pointer/reference, and that the function signature of the Eat method can be changed by the person answering.

Ignoring any error checking ...

lua_getglobal(L, "banana"); // or get 'banana' from person:Eat()
lua_getfield(L, -1, "chew");
lua_pushinteger(L, 5);
lua_pcall(L, 1, 0, 0);

也许“ Simpler Cpp Binding ”会很有帮助。

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