【发布时间】:2013-08-08 06:39:45
【问题描述】:
我一直在尝试让 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()
【问题讨论】:
-
print(getVersion()) -
@H2CO3:我相信这就是答案;你应该发布它。 (不,我不是在跟踪你!)
-
@KeithThompson 我刚刚做了 :)
-
@KeithThompson 你知道有什么好笑的吗?我不会说Lua。我通过尝试一些常识(约 5 秒)找到了答案,然后通过谷歌搜索“lua 函数字符串括号”找到了准确的解释,它在官方文档中(第 4 次点击,约 1 分钟)。