lua_pcall returns a value 2

Nibbie
Posts: 2
Joined: 2012.03
Post: #1
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 ??
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #2
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.
Quote this message in a reply
Nibbie
Posts: 2
Joined: 2012.03
Post: #3
(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
Quote this message in a reply
Member
Posts: 227
Joined: 2008.08
Post: #4
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]
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Lua and lua_pcall problems ChrisS 2 5,474 Nov 5, 2005 10:24 PM
Last Post: phydeaux