How to embed Lua 5.1 in C++

Lua, is a scripting language providing dynamic data structures, maths, io and string manipulations just like any interprete language such as Bash, Python, Ruby etc.

What is so special about Lua?
Lua is Fast, Light-weight and Embeddable.

Lua can be embedded into c and c++ programs and Lua core are statically complied with your c++ programs, meaning your c++ program itself are now becoming Lua interpreter that execute Lua scripts. To extend your c++ application to execute Lua script is simple, lets check it out.


Before you start, please download and install Lua from HERE.
Disclaimer: My example are based on Lua 5.1.3.

1. Create a simple Lua script and name it as foo.lua.

io.write("Please enter your name: ")
name = io.read() -- read input from user
print ("Hi " .. name .. ", enjoy hacking with Lua");

2. Write a cpp program clua.cpp to execute foo.lua.

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

int main()
{
    int s=0;

    lua_State *L = lua_open();

    // load the libs
    luaL_openlibs(L);

    //run a Lua scrip here
    luaL_dofile(L,"foo.lua");

    printf("\nI am done with Lua in C++.\n");

    lua_close(L);

    return 0;
}

Lua API are in c format, in order to make it work with C++ you need to extern “C”. luaL_openlibs(L) loading up all the basic libs such as IO, String, Math etc. I believe if you are using Lua 5.0, you have to replace luaL_open(L) to load the libs one by one like this:

      luaopen_base(L);
      luaopen_table(L);
      luaopen_io(L);
      luaopen_string(L);
      luaopen_math(L);

3. Compile the clua.cpp with g++.

g++ -o clua{,.cpp} -llua -ldl

IMPORTANT! You need to link you program with libdl besides liblua. I believe the use of luaL_openlibs() are calling dlopen, dlclose, dlerror, dlsym which needs libdl.

Else you may get linking error like this:

/usr/local/lib/liblua.a(loadlib.o): In function `ll_loadfunc':
loadlib.c:(.text+0x917): undefined reference to `dlsym'
loadlib.c:(.text+0x924): undefined reference to `dlerror'
loadlib.c:(.text+0x9fc): undefined reference to `dlopen'
loadlib.c:(.text+0xa11): undefined reference to `dlerror'
/usr/local/lib/liblua.a(loadlib.o): In function `gctm':
loadlib.c:(.text+0x101e): undefined reference to `dlclose'
collect2: ld returned 1 exit status

4. Execute your c++ app

$ ./clua
Please enter your name: surface
Hi surface, enjoy hacking with Lua

I am done with Lua in C++.

Cool isn’t it?

Lets try to change foo.lua into this:

io.write("Please enter your name: ")
name = io.read()
io.write("Hi " .. string.format("\27\91\1;38;40m%s\27\91\0;47;40m",name) .. ", enjoy hacking with Lua\n");

Now, run ./clua again! You name will be in RED, check out text color example HERE

Ofcause, in order to really extend your c++ apps to Lua script, you need more than lua_dofile(), you need to allow Lua script calling your c++ functions, you may need to access variables from Lua to c++ and vice versa. Well, mean while I am still learning, I will share more when I learn more tricks!

Reference and Tutorial!
Lua provides excellent documentation:

  • 1. Lua Reference Manual
  • 2. Ebook: Programming in Lua
  • I am dilemma here whether should I post this at http://linux.byexamples.com or http://cc.byexamples.com. As an introduction post for Lua programming, I will put it on both blogs. For future post, if I write about Lua scripting, I will post at http://linux.byexamples.com and if I write about Lua C++ API, it will be at http://cc.byexamples.com.

    Hope you enjoy this post, and start to script with Lua.
    @lightstar: In case you are reading this, I would like to say thank you for introduce this wonderful language to me, I enjoy it very much!

    10 thoughts on “How to embed Lua 5.1 in C++

    1. Pingback: Accessing Lua global variables from c++ » c/c++ linux programming by examples

    2. Wow, thanks! I googled for some time, this is the first “Hello, Word!”-like thing I found of this kind which really works! :D I want to write something in C++ that uses lua scripts, on ubuntu.

    3. This article isn’t useful. You tell not enough to start on Lua.

      For example, how i can bind c-funcs and lua-funcs?

    4. Wow. I was struggling for hours on a “undefined reference to luaL_newstate” error. Thanks for providing the solution! (wrapping the includes within extern “C” {})

    5. this is a wonderful example for the very beginning and i remember it had been working pretty, as it is, as well as with some of my mods e.g. using pure C and binding the C code even further to use it from an Ada program. but it stopped working since my ubuntu upgrade to oneiric giving:

      /tmp/ccEKChqe.o: In function `main’:
      luaembed.c:(.text+0×12): undefined reference to `luaL_newstate’
      luaembed.c:(.text+0×22): undefined reference to `luaL_openlibs’
      luaembed.c:(.text+0×36): undefined reference to `luaL_loadfile’
      luaembed.c:(.text+0x5e): undefined reference to `lua_pcall’
      luaembed.c:(.text+0×78): undefined reference to `lua_close’
      collect2: ld gab 1 als Ende-Status zurück

      NOTICE, i tried all possible combinations of compiler/linker calls, switches, pure C, C++ with extern “C” {#include} ‘s, all versions of -llua (40,50,5.1), -static and -shared, with and without auxlib, and YES i am aware of using -ldl

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>