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.
Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way. When Lua calls a C function, it uses the same kind of stack that C uses to call Lua. The C function gets its arguments from the stack and pushes the results on the stack.
The C API is the set of functions that allow C code to interact with Lua. It comprises functions to read and write Lua global variables, to call Lua functions, to run pieces of Lua code, to register C functions so that they can later be called by Lua code, and so on.
In Lua, we declare functions with the help of the function keyword and then, we can invoke(call) the functions just by writing a pair of parentheses followed by the functions name.
In Lua, the table library provides functions to insert elements into the table. The insert function usually takes two arguments, the first argument is usually the name of the table from which we want to insert the element to, and the second argument is the element that we want to insert.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With