iDevGames Forums
lua_pcall returns a value 2 - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Programming Languages & Scripting (/forum-8.html)
+--- Thread: lua_pcall returns a value 2 (/thread-9932.html)



lua_pcall returns a value 2 - knowledge_seeker - Mar 15, 2012 09:27 PM

I have a test.lua file that contains the following code

Code:
function lFunction()
print("Hello From Lua!")
end


I am trying to run that code using the dofile method:
Code:
.....
  lua_State *L = lua_open();
  luaL_openlibs(L);
  int returnvalue1 = luaL_dofile(L,"test.lua");
  cout<<"The return value from the dofile method is: "<<returnvalue1<<" \n";

  lua_getglobal(L, "lFunction");
  lua_pcall(L, 0, 0, 0);
  int returnvalue2=  lua_pcall(L, 0, 0, 0);
  cout<<"The return value from the lua_pcall method is: "<<returnvalue2<<" \n";
  lua_close(L);
  .....


The return value from the dofile method is 0
The return value from the lua_pcall method is: 2

what can i do to fix it ? why am i getting an error with such a simple code ??


RE: lua_pcall returns a value 2 - OneSadCookie - Mar 15, 2012 10:57 PM

you have (accidentally, I guess) 2 calls to lua_pcall, the first of which will consume the function, and the second of which will error on the empty stack.


RE: lua_pcall returns a value 2 - knowledge_seeker - Mar 16, 2012 10:37 AM

(Mar 15, 2012 10:57 PM)OneSadCookie Wrote:  you have (accidentally, I guess) 2 calls to lua_pcall, the first of which will consume the function, and the second of which will error on the empty stack.

I fixed that and im still getting the same error...please help


RE: lua_pcall returns a value 2 - Oddity007 - Mar 16, 2012 06:05 PM

You should really use better error handling to make errors more meaningful than simple numbers.

Documentation of lua_pcall:
http://pgl.yoyo.org/luai/i/lua_pcall
Quote:In case of runtime errors, this function will be called with the error message and its return value will be the message returned on the stack by lua_pcall.

(The return value is a string holding the error message)

A return value of two corresponds to LUA_ERRRUN, meaning an error running the code, according to the headers
Code:
/* thread status; 0 is OK */
#define LUA_YIELD    1
#define LUA_ERRRUN    2
#define LUA_ERRSYNTAX    3
#define LUA_ERRMEM    4
#define LUA_ERRERR    5

To get your proper error message, get the value on the top of the stack and print it:
Code:
lua_State *L = lua_open();
luaL_openlibs(L);
int errorCode = 0;
if(errorCode = luaL_dofile(L,"test.lua"))
{
    puts(lua_tostring(L, -1));
    abort();
}
lua_getglobal(L, "lFunction");
if(errorCode = lua_pcall(L, 0, 0, 0))
{
    puts(lua_tostring(L, -1));
    abort();
}
lua_close(L);
[/quote]