9
votes

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.

2

2 Answers

10
votes

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);
-1
votes

Maybe "Simpler Cpp Binding" will be helpful.