Skip to content

Instantly share code, notes, and snippets.

@btbytes
Created June 29, 2009 03:47
Show Gist options
  • Save btbytes/137456 to your computer and use it in GitHub Desktop.
Save btbytes/137456 to your computer and use it in GitHub Desktop.

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

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment