Lua API评估变量名而不是值

Pau*_*aul 1 c api lua

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

从Lua运行时,会这样做:

hook.printTest('hello')  -- prints 'hello'
a = 'hello'
hook.printTest(a) -- prints 'a'
Run Code Online (Sandbox Code Playgroud)

我对Lua很新,并使用这个文档:http://www.lua.org/manual/5.2/manual.html ,我没有找到/理解如何从文字中识别变量.(例如,没有lua_isliteral()或lua_isvariable()方法).

Pup*_*ppy 5

你已经传递了一个糟糕的索引lua_tolstring.参考手册明确指出

0绝不是可接受的索引.

您对相对值使用负指数,对绝对值使用正指数.这些条件都不是0.