Getting Values From Lua

lua-users home
wiki

Return values from dostring

Question: How can I get the return value of the Lua chunk executed by lua_dostring from the C side, i.e. like getting the result returned by the Lua dostring function?

(lhf) Just like the return values of any function. Here is an example:

lua_State *L=lua_open(0);
printf( "%d\n", lua_gettop(L) );
lua_dostring(L, "return 1,'a'" );
printf( "%d\n", lua_gettop(L) );
printf( "%s\n", lua_tostring(L,-2) );
printf( "%s\n", lua_tostring(L,-1) );
In general, you should take the k top values in the stack, where k is the difference between lua_gettop(L) before calling lua_dostring and lua_gettop(L) after calling it, that is, for indices from -1 to -k.


Note: These examples are for Lua 4.0. VersionNotice


Example code for Lua 5.0:

returnone.c:

#include <lua.h>
#include <lualib.h>

int main()
{
  lua_State *L=lua_open();
  printf( "%d\n", lua_gettop(L) );
  lua_dostring(L, "return 1,'a'" );
  printf( "%d\n", lua_gettop(L) );
  printf( "%s\n", lua_tostring(L,-2) );
  printf( "%s\n", lua_tostring(L,-1) );
  return 0;
}

Build:

gcc -o returnone returnone.c -I/usr/include/lua50 -llua50 -llualib50

Run: # ./returnone

0
2
1
a


Example code for Lua 5.1.1:

lua_dostring() no longer exists:

returnone.c:

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int main()
{
   lua_State *L = luaL_newstate();
   char buff[] = "return 1,'a'";
   int error;
   printf( "%d\n", lua_gettop(L) );
   error = luaL_loadbuffer(L, buff, strlen(buff), "my test") || lua_pcall(L, 0, LUA_MULTRET, 0);
   if (error) {
      fprintf(stderr, "%s", lua_tostring(L, -1));
      lua_pop(L, 1);  /* pop error message from the stack */
   }
   printf( "%d\n", lua_gettop(L) );
   printf( "%s\n", lua_tostring(L,-2) );
   printf( "%s\n", lua_tostring(L,-1) );
   return 0;
}


RecentChanges · preferences
edit · history
Last edited February 17, 2010 12:35 pm GMT (diff)