1

I'm using the Lua 5.2 C API. I am trying to get a function to accept a string variable or a string literal.

this code:

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;
}

when run from Lua, will do this:

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

I'm very new to Lua and using this documentation: http://www.lua.org/manual/5.2/manual.html and am not finding/understanding how to discern a variable from a literal. (There are no lua_isliteral() or lua_isvariable() methods, for example).

0

1 Answer 1

5

You have passed a bad index to lua_tolstring. The reference manual clearly states that

0 is never an acceptable index.

You use negative indices for relative values, and positive indices for absolute values. Neither of those conditions is ever 0.

Sign up to request clarification or add additional context in comments.

1 Comment

Sigh. Embarrassingly obvious now that I see it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.