4
votes

I am trying to learn how to embed lua in a C program, but I am not great at reading technical documents, and I haven't found any current tutorials. This is my program:

#include <iostream>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>


void report_errors(lua_State*, int);

int main(int argc, char** argv) {
    for (int n = 1; n < argc; ++n) {
        const char* file = argv[n];
        lua_State *L = luaL_newstate();

        luaL_openlibs(L);

        std::cerr << "-- Loading File: " << file << std::endl;

        int s = luaL_loadfile(L, file);

        if (s == 0) {
            s = lua_pcall(L, 0, LUA_MULTRET, 0);
        }

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

void report_errors(lua_State *L, int status) {
    if (status) {
        std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
        lua_pop(L, 1);
    }
}

The compiler gives undefined reference errors for luaL_newstate, luaL_openlibs, luaL_loadfilex, lua_pcallk, and lua_close. I am using Code::Blocks one a Windows computer and I have added the lua include directory to all of the search paths and liblua53.a to the link libraries. The IDE autocompleted the header names and the parser displays most of the lua functions, but with a brief search I found that the parser could not find either lua_newstate or luaL_newstate. Why does it find some of the functions and not others?

2
That's c++ not c, you might get more help if you switch the tag.2trill2spill
Use extern "C" (link)Egor Skriptunoff
"I am not great at reading technical documents" Can you elaborate on this? This is a skill you will have to learn, not just give up on.Lightness Races in Orbit
Clearly answered by the very first result on Google for lua c++. :(Lightness Races in Orbit
Following this tutorial i get 'luaopen_loadlib' was not declared in this scope, and when I remove that statement it compiles; however, when I run it lua panics unprotected error to Lua API (no calling environment).Giaphage47

2 Answers

5
votes

In c++ you should include lua.hpp not lua.h. lua.h does not define the extern "C" block to stop the name mangling of the c++ compiler.

0
votes

The arguments for g++ had -llua before the input file. I put -llua at the end, and everything works fine now.