how do I check the value of the top of the stack in Lua?
I have the following C++ code:
if (luaL_loadfile(L, filename) == NULL) { return 0;// error.. } lua_pcall(L,0,0,0); // execute the current script.. lua_getglobal(L,'variable'); if (!lua_isstring(L,-1)){ // fails this check.. lua_pop(L,1); return 0; // error }
The contents of the file in question is
-- A comment variable = 'MyString'
Any ideas?
The likely problem is that
luaL_loadfile()is documented to return the same values aslua_load()or one additional error code. In either case, the return value is anintwhere 0 means success and a nonzero value is an error code.So, the test
luaL_loadfile(...) == NULLis true if the file was loaded, but the code calls that an error and returns.The function
lua_pcall()also returns a status code, and you may want to verify that as well.Otherwise, the script as shown does create a global variable, and
lua_getglobal()would retrieve that to the stack where it could be tested withlua_isstring(), or probably more usefully let you return its value if it is sufficiently string-like withlua_tostring(). The latter function will return either aconst char *pointing at a nul-terminated string, or NULL if the value at the stack index can’t be converted to a string. See the Lua reference manual as linked for the rest of the details and a caveat about usinglua_tostring()inside a loop.Edit: I added better links to the manual in a couple of places.