tags:

views:

610

answers:

2

Hi, 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?

A: 

I think you want to replace luaL_loadfile with lua_dofile. lua_pcall is unnecessary. My guess is loading a file as a function using luaL_loadfile and then running it using pcall may not create the globals you want.

Paul
No, lua_dofile loads the file and runs it. I want to do them separately. Am I using loadfile and pcall incorrectly?
krebstar
+2  A: 

The likely problem is that luaL_loadfile() is documented to return the same values as lua_load() or one additional error code. In either case, the return value is an int where 0 means success and a nonzero value is an error code.

So, the test luaL_loadfile(...) == NULL is 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 with lua_isstring(), or probably more usefully let you return its value if it is sufficiently string-like with lua_tostring(). The latter function will return either a const 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 using lua_tostring() inside a loop.

Edit: I added better links to the manual in a couple of places.

RBerteig
Will follow this trail and update you on the result, thanks! :D
krebstar
Well, it seems like you were on the right track.. luaL_loadfile returns 6.. What does it mean? Where can I find the list of error codes for this? Thanks..
krebstar
nvm, figured it out, thanks to you :) I was passing in the wrong filename and it couldn't open it.. Needed the fully qualified path name..
krebstar