Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling functions in a Lua table from C++

Tags:

c++

lua

swig

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.

like image 359
Tom J Nowell Avatar asked Dec 11 '09 15:12

Tom J Nowell


People also ask

How do you call a function in C Lua?

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.

Can Lua use C?

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.

How do I make and call a function in Lua?

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.

How do I use table insert in Lua?

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.


1 Answers

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);
like image 178
uroc Avatar answered Oct 01 '22 23:10

uroc