jimt
jimt

Reputation: 2010

How to determine if a Lua error has been thrown?

I've embedded a Lua interpreter into my C program, and I've got a simple question that I can't seem to find a clear answer to.

Suppose I have a C function that I expose to Lua as follows:

static int calculate_value(lua_State *L) 
{
    double x = luaL_checknumber(L, 1);
    return 0;
}

How can I determine (in C, after this function was called) that Lua threw an error when calling luaL_checknumber? Is there an error message just sitting on the top of the stack? Is there some other indicator that an error has been thrown?

Upvotes: 1

Views: 741

Answers (2)

lhf
lhf

Reputation: 72422

If that function is called via Lua, you can use pall. Or use lua_pcall before running the Lua script that called that function.

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 474446

In general, you don't. Lua functions that throw errors use setjmp/longjmp (or exceptions if compiled as C++) to return control to the calling Lua runtime. The error will be presented to the Lua function that called your calculate_value function.

If you want to handle parameter errors differently, you cannot use Lua's luaL_check* functions.

Upvotes: 2

Related Questions