Lua API计算的是变量名,而不是变量值。

我正在使用 Lua 5.2 C API。我试图让一个函数接受一个字符串变量或一个字符串字面值。

这段代码:

static int printTest(lua_State *L)
{
    size_t lslen = NULL;
    const char *lsrc = lua_tolstring(L, 0, &lslen);
    printf("%s\n", lsrc);
}
/* ----- Registration array ----- */
static const luaL_Reg testhook[] = {
        {"printTest", printTest},
        {NULL, NULL} /* sentinel */
};
/* ----- Registration function ----- */
LUALIB_API int registerTestHookFunctions(lua_State *L)
{
    lua_newtable(L);
    lua_setglobal(L, "hook");
    lua_getglobal(L, "hook");
    luaL_setfuncs(L, testhook, 0);
    lua_settop(L, 0);
    return 0;
}

当从 Lua 运行时,会执行:

hook.printTest('hello')  -- prints 'hello'
a = 'hello'
hook.printTest(a) -- prints 'a'

我非常新于 Lua,并使用此文档:http://www.lua.org/manual/5.2/manual.html,并且没有找到/理解如何区分变量和字面值。(例如,没有 lua_isliteral() 或 lua_isvariable() 方法)。

点赞
用户298661
用户298661

您向lua_tolstring传递了一个错误的索引。参考手册明确声明

0从不是可以接受的索引。

使用负数索引表示相对值,使用正数索引表示绝对值。这两个条件都不会是0。

2012-05-22 14:33:55