-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlua_interface.cpp
108 lines (89 loc) · 2.44 KB
/
lua_interface.cpp
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
#include <stdarg.h>
#include <string.h>
#include "lua_interface.h"
#include "wtypedef.h"
#include "log.h"
extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
extern lua_State* L;
int
call_lua (const char *func, const char *sig, ...)
{
va_list vl;
int narg, nres; /* number of arguments and results */
va_start(vl, sig);
lua_getglobal(L, func); /* get function */
/* push arguments */
narg = 0;
while (*sig) { /* push arguments */
switch (*sig++) {
case 'f': /* double argument */
lua_pushnumber(L, va_arg(vl, double));
break;
case 'd': /* int argument */
lua_pushnumber(L, va_arg(vl, int));
break;
case 's': /* string argument */
lua_pushstring(L, va_arg(vl, char *));
break;
case '>':
goto endwhile;
default:
{
log_error("invalid option (%c)", *(sig - 1));
return -1;
}
}
narg++;
luaL_checkstack(L, 1, "too many arguments");
} endwhile:
/* do the call */
nres = strlen(sig); /* number of expected results */
if (lua_pcall(L, narg, nres, 0) != 0) /* do the call */
{
log_error( "error running function `%s': %s", func, lua_tostring(L, -1));
return -1;
}
/* retrieve results */
nres = -nres; /* stack index of first result */
while (*sig) { /* get results */
switch (*sig++) {
case 'f': /* double result */
if (!lua_isnumber(L, nres))
{
log_error( "wrong result type");
return -1;
}
*va_arg(vl, double *) = lua_tonumber(L, nres);
break;
case 'd': /* int result */
if (!lua_isnumber(L, nres))
{
log_error("wrong result type");
return -1;
}
*va_arg(vl, int *) = (int)lua_tonumber(L, nres);
break;
case 's': /* string result */
if (!lua_isstring(L, nres))
{
log_error("wrong result type");
return -1;
}
*va_arg(vl, const char **) = lua_tostring(L, nres);
break;
default:
{
log_error("invalid option (%c)", *(sig - 1));
return -1;
}
}
nres++;
}
va_end(vl);
return 0;
}