我一直在努力让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()
答案 0 :(得分:6)