我一直试图让 lua 脚本为我正在开发的一个小游戏工作,但 lua 似乎比它的价值更麻烦。经过多次谷歌搜索和头发撕裂,我设法让简单的脚本运行,但很快就碰壁了。C 函数似乎不想绑定到 lua,或者至少不想在绑定后运行。g++ 编译 c 代码没有意外,但 lua 解释器生成以下语法错误:
LUA ERROR: bin/lua/main.lua:1: syntax error near 'getVersion'
我的 C(++) 代码:
#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代码:
print getVersion()