Skip to content

Example 3: Calling Lua Functions from C

kamih edited this page Jul 14, 2012 · 1 revision

This is functions.lua, it contains two tables, a simple squaring function, and a function to merge two tables:

-- Create two simple tables
T1 = { a = 2, 42, 32 }
T2 = { b = 3, 21 }

-- return square of x
function square(x)
    return x * x
end

-- merge t2 table into t1
function merge(t1, t2)
    for k, v in pairs(t2) do
        if (type(v) == "table") and (type(t1[k] or false) == "table") then
            merge(t1[k], t2[k])
        else
            t1[k] = v
        end
    end
end

Here is how you get these functions with LuaUtils in order to call them from your C++ code:

using namespace LuaUtils;

// Create a new LuaState and load the functions.lua file
LuaState state;
state.loadFile("functions.lua");

// Read the functions
LuaFunction<double> square;
state.getValue("square", square);
     
LuaFunction<void> merge;
state.getValue("merge", merge);
 
// Read T1 and T2 tables
LuaTable t1, t2;
state.getValue("T1", t1);
state.getValue("T2", t2);
 
// Merge T2 into T1
// After merge, T1 will contain { 21, 32, a = 2, b = 3 }
merge(t1, t2);

// Get the square of 42
double v = square(42.0);

As you can see, it’s very easy to call Lua functions from your C++ code.

The LuaFunction class is templated with the return type. If you need to return more than one value, simply return a LuaTable.

The function arguments are also templated so you can pass values of any type, just like in Lua. You can use as many as four arguments. If you need to use more, simply put them in a LuaTable and pass that.

You can create a new table to do this with LuaState::newTable. When calling this method, you give it a string to use as the global name of the new table. If the string is empty, it will be an anonymous table.

Clone this wiki locally