aboutsummaryrefslogtreecommitdiff
path: root/src/except.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/except.c')
-rw-r--r--src/except.c52
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
6static int global_try(lua_State *L);
7static int global_protect(lua_State *L);
8static int protected(lua_State *L);
9
10static luaL_reg func[] = {
11 {"try", global_try},
12 {"protect", global_protect},
13 {NULL, NULL}
14};
15
16/*-------------------------------------------------------------------------*\
17* Exception handling: try method
18\*-------------------------------------------------------------------------*/
19static 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\*-------------------------------------------------------------------------*/
30static 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
40static 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\*-------------------------------------------------------------------------*/
49int except_open(lua_State *L) {
50 luaL_openlib(L, NULL, func, 0);
51 return 0;
52}