btbytes (owner)

Revisions

gist: 137456 Download_button fork
public
Public Clone URL: git://gist.github.com/137456.git
beginning_lua.markdown

Getting started with Lua and C++

Step 1: Install Lua

$ sudo apt-get install libreadline5-dev
$ sudo apt-get install lua-5.1 liblua5.1-0-dev

Step 2: Test C++ and Lua


/*
moon1.cpp
*/
#include 

extern "C" {
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"  
}

void report_errors(lua_State *L, int status)
{
    if ( status!=0 ) {
        std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
        lua_pop(L, 1); // remove error message
    }
}

int main(int argc, char** argv)
{
    for ( int n=1; n<< "-- Loading file: " << file << std::endl;
        int s = luaL_loadfile(L, file);
        if ( s==0 ) {
            // execute Lua program
            s = lua_pcall(L, 0, LUA_MULTRET, 0);
        }

        report_errors(L, s);
        lua_close(L);
        std::cerr << std::endl;
    }
    return 0;
}

The above code runs on Lua 5.1. There is an important change in Lua 5.1 API which requires the luaopen_* functions to be called through Lua, like Lua functions. See luaL_openlibs(L); line.

Compile


    $ gcc moon1.cpp -o moon1 `pkg-config --cflags --libs lua5.1`

Create a simple Lua script


-- hello.lua
print ("Hello Lua")

Run the Lua script via the CPP program.


$ ./moon1 hello.lua
-- Loading file: hello.lua
Hello Lua