I'm trying to bind Lua in my applications, now I trying to test how bind Lua into C++. My problem is very strange because I want to call function main()
from script at start, after luaL_loadfile
. My code:
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include "lua.hpp"
#include "lauxlib.h"
#include "lualib.h"
using namespace std;
int main(int argc, char **argv) {
lua_State* lua = luaL_newstate();
luaL_openlibs(lua);
if (luaL_loadfile(lua, "test.lua") != 0) {
std::cout << lua_tostring(lua, -1) << "\n";
lua_pop(lua, 1);
return 1;
}
lua_getfield(lua, LUA_REGISTRYINDEX, "main");
if (lua_pcall(lua, 0, 1, 0) != 0) {
printf("Error running function 'main': %s\n", lua_tostring(lua, -1));
return 1;
}
lua_close(lua);
return 0;
}
and my output is:
Error running function 'main': attempt to call a nil value
Try
luaL_dofile
instead ofluaL_loadfile
.This is one of the most frequent mistakes:
luaL_loadfile
loads the file but does not run it; it just leaves on the stack a function representing the loaded file, ready to be called. The functionmain
will only be defined when the script is run, that is, when the script function is called. The error message is trying to tell you so. (I assume that your script defines a function calledmain
. There isn't any real need for that, but it is harmless.)