Calling c function from lua 5.2 generates syntax error

I'm trying to get a lua script while working on a little game I'm working on, but lua seems more complex than its value. After much disassembly and tearing my hair, I managed to run simple scripts, but quickly hit the wall. The C functions do not seem to want to communicate with lua, or at least they do not want to start after binding. g ++ compiles c code without incident, but the lua interpreter generates this syntax error:

LUA ERROR: bin/lua/main.lua:1: syntax error near 'getVersion' 

My C code (++):

 #include <lua.hpp> static const luaL_Reg lualibs[] = { {"base", luaopen_base}, {"io", luaopen_io}, {NULL, NULL} }; void initLua(lua_State* state); int getVersion(lua_State* state); int main(int argc, char* argv[]) { lua_State* state = luaL_newstate(); initLua(state); lua_register(state, "getVersion", getVersion); int status = luaL_loadfile(state, "bin/lua/main.lua"); if(status == LUA_OK){ lua_pcall(state, 0, LUA_MULTRET, 0); }else{ fprintf(stderr, "LUA ERROR: %s\n", lua_tostring(state, -1)); lua_close(state); return -1; } lua_close(state); return 0; } void initLua(lua_State* state) { const luaL_Reg* lib = lualibs; for (; lib->func != NULL; lib ++) { luaL_requiref(state, lib->name, lib->func, 1); lua_settop(state, 0); }; delete lib; } int getVersion(lua_State* state) { lua_pushnumber(state, 1); return 1; }; 

Lua Code:

 print getVersion() 
+4
source share
1 answer

print is a function. Since its argument is neither a table constructor nor a string literal, you must call it with () :

 print(getVersion()) 

Read the funny guide here.

+6
source

Source: https://habr.com/ru/post/1495854/


All Articles