Return values with lua?

Started by
2 comments, last by Antheus 16 years, 3 months ago
Every time I use a function with a return value in lua, I notice that the lua-side function always returns "0". Why is this? Currently I'm just exposing functions to lua with the function itself, and a glue function similar to this one:
int l_dbLoadImage( lua_State* luaVM)
{
	dbLoadImage( const_cast<char *> (lua_tostring(luaVM, -2)), lua_tointeger(luaVM, -1));
	lua_pushnumber( luaVM, 0 );
	return 1;
}

and a register function, like this:
lua_register( luaVM, "dbLoadImage", l_dbLoadImage );
What am I missing/what else must be done? Also, I'm not using any additional libraries. Just lua.
Advertisement
Because you tell it to return 0:
lua_pushnumber( luaVM, 0 );



The following should work:
int l_dbLoadImage( lua_State* luaVM){	int result = dbLoadImage( const_cast<char *> (lua_tostring(luaVM, -2)), lua_tointeger(luaVM, -1));	lua_pushnumber( luaVM, result );	return 1;}
So, does this mean that it will act as a return value in lua, and that has been the purpose of the function? I learned how to make glue functions from a tutorial, I didn't know that the pushnumber was part of that :o
Quote:Original post by Elspin
So, does this mean that it will act as a return value in lua, and that has been the purpose of the function?


Function calls are made via stack. Doesn't matter which way, C to Lua or vice versa, or within Lua.

lua_to... query the parameters on stack.
lua_push... puts something on stack.
lua_pop removes something from stack.

The convention is, that executed function pushes results on stack, and returns number of return values. In Lua, function can return multiple values. This is how Lua calls functions, either its own, or external.

If an error happens, you push a string with description of error and call lua_error() - this would be equivalent of throwing an exception.

This topic is closed to new replies.

Advertisement