7

I have the following C file:

//thing.c
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

#include <stdio.h>

lua_State* L;

int main(){
        L = lua_open();

        lua_dostring(L, "print(\"lua\")");
        printf("hello\n");

        return 0; }

and the following makefile:

default:
        gcc -I/usr/include/lua50 -L/usr/lib -o qwerty thing.c -llua50 -llualib50

the code builds just fine, but when I run it I get the following:

[string "print("lua")"]:1: attempt to call global `print' (a nil value)
hello

Note: I have seen the many other questions on this error, but they all deal with working directly in Lua, as opposed to with the C api. They also seem to imply that the problem is that the print function was never defined. I don't understand this, as I can run both a lua interpreter and a lua script just fine directly from the command line.

EDIT: I am using lua 5.0

1 Answer 1

10

You have to initialize the libraries in Lua. After you call lua_open, call

luaL_openlibs(L);

Edit: for Lua 5.0, I believe you'll have to open the libraries manually. For the print function, you just need the base library:

luaopen_base(L);
2
  • thing.c:(.text+0x20): undefined reference to 'luaL_openlibs' Noteworthy: I am using lua 5.0
    – ewok
    Commented Aug 7, 2012 at 16:11
  • @ewok, see edit. However, since you're getting a linking error (and not a compiler error), I think you may be including the 5.1 or 5.2 header, but linking the 5.0 library. I see you're specifying the 5.0 include path, but I wonder if you have the 5.1 or 5.2 headers somewhere in your default include path? Commented Aug 7, 2012 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.