4

in my C file I call luaL_dostring like this:

luaL_dostring(L, "return 'somestring'");

How do I read this return value in C after this line?

Thanks.

Edit: Thanks for the help.

I'd like to add that to remove the element after retrieving it, you use:

lua_pop(L, 1);
Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • [Related question](http://stackoverflow.com/questions/12528820/lual-dostring-puts-nothing-on-the-stack). This doesn't work in all Lua versions. – Albert Mar 14 '16 at 10:30

2 Answers2

8

The value is left on the Lua stack. In order to retrieve the value, use one of the lua_toXXXX functions, with -1 as the index argument (-1 refers to the top of the stack). Alternatively, use lua_gettop() to get the size of the stack.

In your case, use this:

luaL_dostring(L, "return 'somestring'");
const char * str = lua_tostring(L, -1);
Michal Kottman
  • 16,375
  • 3
  • 47
  • 62
  • "The value is left on the C stack." should read "The value is left on the Lua stack." – gwell Sep 09 '10 at 19:14
  • This is not correct, you are ignoring the return value of `luaL_dostring`. I posted [an answer](http://stackoverflow.com/a/33580406/1127972) – doug65536 Nov 07 '15 at 07:38
  • And yes I realize the ambiguity of the "return value" from `luaL_dostring` vs the return value of the executed Lua code. Regardless, you should not ignore error returns. – doug65536 Nov 07 '15 at 07:40
2

The documentation says luaL_dostring does have a return value, which is zero on success:

luaL_dostring

Loads and runs the given string. It is defined as the following macro:

 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))

It returns 0 if there are no errors or 1 in case of errors.

Robust code should check for 0 return value.

Strictly speaking, the macro expands to a boolean value, which is true if there was an error, in C++. This might be significant in something like a unit test.

doug65536
  • 6,562
  • 3
  • 43
  • 53