diff options
Diffstat (limited to 'src/except.c')
-rw-r--r-- | src/except.c | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/src/except.c b/src/except.c new file mode 100644 index 0000000..c9eb20e --- /dev/null +++ b/src/except.c | |||
@@ -0,0 +1,52 @@ | |||
1 | #include <lauxlib.h> | ||
2 | #include <stdio.h> | ||
3 | |||
4 | #include "except.h" | ||
5 | |||
6 | static int global_try(lua_State *L); | ||
7 | static int global_protect(lua_State *L); | ||
8 | static int protected(lua_State *L); | ||
9 | |||
10 | static luaL_reg func[] = { | ||
11 | {"try", global_try}, | ||
12 | {"protect", global_protect}, | ||
13 | {NULL, NULL} | ||
14 | }; | ||
15 | |||
16 | /*-------------------------------------------------------------------------*\ | ||
17 | * Exception handling: try method | ||
18 | \*-------------------------------------------------------------------------*/ | ||
19 | static int global_try(lua_State *L) { | ||
20 | if (lua_isnil(L, 1) || (lua_isboolean(L, 1) && !lua_toboolean(L, 1))) { | ||
21 | lua_settop(L, 2); | ||
22 | lua_error(L); | ||
23 | return 0; | ||
24 | } else return lua_gettop(L); | ||
25 | } | ||
26 | |||
27 | /*-------------------------------------------------------------------------*\ | ||
28 | * Exception handling: protect factory | ||
29 | \*-------------------------------------------------------------------------*/ | ||
30 | static int protected(lua_State *L) { | ||
31 | lua_pushvalue(L, lua_upvalueindex(1)); | ||
32 | lua_insert(L, 1); | ||
33 | if (lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0) != 0) { | ||
34 | lua_pushnil(L); | ||
35 | lua_insert(L, 1); | ||
36 | return 2; | ||
37 | } else return lua_gettop(L); | ||
38 | } | ||
39 | |||
40 | static int global_protect(lua_State *L) { | ||
41 | lua_insert(L, 1); | ||
42 | lua_pushcclosure(L, protected, 1); | ||
43 | return 1; | ||
44 | } | ||
45 | |||
46 | /*-------------------------------------------------------------------------*\ | ||
47 | * Init module | ||
48 | \*-------------------------------------------------------------------------*/ | ||
49 | int except_open(lua_State *L) { | ||
50 | luaL_openlib(L, NULL, func, 0); | ||
51 | return 0; | ||
52 | } | ||