Wednesday, 12 January 2011

Lua and C++, Part 2

OK, so: Having explained the Lua stack, we can now find out why the program is failing (I have a sneaking suspicion, but let's do this by the numbers).

This is the code:

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

using namespace std;

#include <string>
#include <iostream>

int main()
{
        string prog = "print \"hello\"";
        cout    << "prog = [["
                << prog
                << "]]"
                << endl
        ;

        lua_State *L = lua_open();

        int rc = luaL_dostring(L, prog.c_str());
        if(rc == 1) {
                cout    << "there was an error executing the script: [["
                        << lua_tostring(L, -1)
                        << "]]"
                        << endl
                ;      

        }

        lua_close(L);
        return 0;
}


Now when I say that lua_tostring(L, -1) takes the error string on top of the stack and returns it as a const char *, it hopefully makes sense. Compile and run...

I get this:

prog = [[print "hello"]]
there was an error executing the script: [[[string "print "hello""]:1: attempt to call global 'print' (a nil value)]]

First things first: I'd forgotten that Lua uses square brackets to delimit the offending Lua code. That makes my use if them confusing. Second thing... print undefined? Why can Lua find print in the interpreter and not when I call it?

The reason is quite simple. Creating a Lua state gets you an empty Lua interpretter. Nothing has been defined as yet - including the lua library functions. There C functions to load all the stand lua libs. Or this one to load them all at once:

        luaL_openlibs(L);

Add that in under lua_open and it works.


And after all that, I've forgotten where I was going with all this. Let me have a think about it...

1 comment:

DrB said...

I finally started learning Lua after years of hearing about it, and I got stuck on this part. Thanks for posting this.