-
Notifications
You must be signed in to change notification settings - Fork 202
/
cond.c
117 lines (95 loc) · 2.21 KB
/
cond.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
* See Licensing and Copyright notice in naev.h
*/
/**
* @file mission.c
*
* @brief Handles missions.
*/
#include "cond.h"
#include "naev.h"
#include "log.h"
#include "nlua.h"
#include "nluadef.h"
static lua_State *cond_L = NULL; /** Conditional Lua state. */
/**
* @brief Initializes the conditional subsystem.
*/
int cond_init (void)
{
if (cond_L != NULL)
return 0;
cond_L = nlua_newState();
nlua_loadStandard(cond_L,1);
return 0;
}
/**
* @brief Destroys the conditional subsystem.
*/
void cond_exit (void)
{
if (cond_L == NULL)
return;
lua_close(cond_L);
cond_L = NULL;
}
/**
* @brief Checks to see if a condition is true.
*
* @param cond Condition to check.
* @return 0 if is false, 1 if is true, -1 on error.
*/
int cond_check( const char* cond )
{
int b;
int ret;
/* Lazy loading. */
if (cond_L == NULL) { /* must create the conditional environment */
cond_L = nlua_newState();
nlua_loadStandard(cond_L,1);
}
/* Load the string. */
lua_pushstring(cond_L, "return ");
lua_pushstring(cond_L, cond);
lua_concat(cond_L, 2);
ret = luaL_loadbuffer(cond_L, lua_tostring(cond_L,-1),
lua_strlen(cond_L,-1), "Lua Conditional");
switch (ret) {
case LUA_ERRSYNTAX:
WARN("Lua conditional syntax error");
return 0;
case LUA_ERRMEM:
WARN("Lua Conditional ran out of memory");
return 0;
default:
break;
}
/* Run the string. */
ret = lua_pcall( cond_L, 0, 1, 0 );
switch (ret) {
case LUA_ERRRUN:
WARN("Lua Conditional had a runtime error: %s", lua_tostring(cond_L, -1));
return 0;
case LUA_ERRMEM:
WARN("Lua Conditional ran out of memory");
return 0;
case LUA_ERRERR:
WARN("Lua Conditional had an error while handling error function");
return 0;
default:
break;
}
/* Check the result. */
if (lua_isboolean(cond_L, -1)) {
b = lua_toboolean(cond_L, -1);
lua_pop(cond_L, 1);
if (b)
return 1;
else
return 0;
}
WARN("Lua Conditional didn't return a boolean");
/* Clear stack. */
lua_settop(cond_L, 0);
return 0;
}