Simple Lua Icxx Example

lua-users home

This gives an example of using the [Lua-icxx API] to use Lua in a C++ application rather than using the Lua C API directly. Note how

 * The lua-icxx (C++) equivalent of API example at 
 * Oliver Schoenborn, Jul 2011

#include "lua_icxx/lua_icxx.h"
#include "iof/fmtr.hpp"

#include <iostream>

    LuaInterpreter L;

    /* Load the file containing the script we are going to run */
    LuaFuncRef chunk = L.chunkFromFile("sample1.lua");
    if ( chunk.isError() ) {
        std::cerr << "Couldn't load file: " << chunk.getErrMsg() << std::endl;

    LuaTableRef table = L.newTable();
    for (int i = 1; i <= 5; i++)
        table[i] = i*2;

    /* By what name is the script going to reference our table? */
    L.setGlobal("foo", table);

    /* Ask Lua to run our little script */
    LuaTempResult res = chunk();
    if ( res.isError() ) {
        std::cerr << "Failed to run script: " << res.getErrMsg() << std::endl;

    /* Get the returned value at the top of the stack (index -1) */
    double sum = res[1]; 

    // following line uses the iof library ( for printf-output in c++
    std::cout << iof::fmtr("Script returned: %.0fs") << sum << std::endl;

    return 0;

In version 1.x, lua-icxx only supports part of the Lua C API, but the C API can be used in conjunction with lua-icxx. Extending lua-icxx to cover more of the C API is easy to do, email author (

If you wonder why lua-icxx does not provide ways to bind to C++ code from Lua, it is because this can be done by other tools like SWIG and tolua++. Lua-icxx provides what those and other binding libs typically do not provide (easy access to a Lua interpreter from a C++ application).

RecentChanges · preferences
edit · history
Last edited August 24, 2011 8:19 pm GMT (diff)