Rok Povsic
Rok Povsic

Reputation: 4925

C & Lua: luaL_dostring return value

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);

Upvotes: 4

Views: 8865

Answers (2)

doug65536
doug65536

Reputation: 6771

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.

Upvotes: 2

Michal Kottman
Michal Kottman

Reputation: 16753

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);

Upvotes: 8

Related Questions