-
Notifications
You must be signed in to change notification settings - Fork 13
/
libeco.c
93 lines (74 loc) · 1.75 KB
/
libeco.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* SPDX-License-Identifier: MIT */
/*
* Author: Jianhui Zhao <zhaojh329@gmail.com>
*/
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include "eco.h"
static const char *eco_context_registry = "eco-context";
static const char *obj_registry = "eco{obj}";
const char **eco_get_context_registry()
{
return &eco_context_registry;
}
const char **eco_get_obj_registry()
{
return &obj_registry;
}
int eco_push_context(lua_State *L)
{
lua_rawgetp(L, LUA_REGISTRYINDEX, &eco_context_registry);
return 1;
}
void eco_push_context_env(lua_State *L)
{
eco_push_context(L);
lua_getuservalue(L, -1);
lua_remove(L, -2);
}
struct eco_context *eco_get_context(lua_State *L)
{
struct eco_context *ctx;
eco_push_context(L);
ctx = lua_touserdata(L, -1);
lua_pop(L, 1);
return ctx;
}
void eco_resume(lua_State *L, lua_State *co, int narg)
{
#if LUA_VERSION_NUM > 503
int nres;
int status = lua_resume(co, L, narg, &nres);
#else
int status = lua_resume(co, L, narg);
#endif
switch (status) {
case 0: /* dead */
eco_push_context_env(L);
lua_rawgetp(L, LUA_REGISTRYINDEX, &obj_registry);
lua_pushlightuserdata(L, co);
lua_rawget(L, -2);
lua_remove(L, -2);
lua_pushnil(L);
lua_rawset(L, -3);
lua_pop(L, 1);
break;
case LUA_YIELD:
break;
default:
lua_xmove(co, L, 1);
lua_getglobal(L, "eco");
lua_getfield(L, -1, "panic_hook");
lua_remove(L, -2);
if (lua_isfunction(L, -1)) {
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
} else {
fprintf(stderr, "%s\n", lua_tostring(L, -2));
}
exit(1);
break;
}
}