forked from libretro/RetroArch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlua_converter.c
119 lines (98 loc) · 2.12 KB
/
lua_converter.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
118
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include "libretrodb.h"
#include "lua_common.h"
int master_key = 1;
const char * LUA_COMMON = " \
function binary(s) if s ~= nil then return {binary = s} else return nil end end \
function uint(s) if s ~= nil then return {uint = s} else return nil end end \
";
static int call_init(
lua_State * L,
int argc,
const char ** argv
) {
int rv = -1;
int i;
lua_getglobal(L, "init");
for (i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
}
if (lua_pcall(L, argc, 0, 0) != 0) {
printf(
"error running function `init': %s\n",
lua_tostring(L, -1)
);
}
return rv;
}
static int value_provider(
void * ctx,
struct rmsgpack_dom_value * out
) {
int rv;
lua_State * L = ctx;
lua_getglobal(L, "get_value");
if (lua_pcall(L, 0, 1, 0) != 0) {
printf(
"error running function `get_value': %s\n",
lua_tostring(L, -1)
);
}
if (lua_isnil(L, -1)) {
rv = 1;
} else if (lua_istable(L, -1)) {
rv = libretrodb_lua_to_rmsgpack_value(L, -1, out);
} else {
printf("function `get_value' must return a table or nil\n");
}
lua_pop(L, 1);
return rv;
}
int main(
int argc,
char ** argv
){
const char * db_file;
const char * lua_file;
int dst = -1;
int rv = 0;
if (argc < 3) {
printf("usage:\n%s <db file> <lua file> [args ...]\n", argv[0]);
return 1;
}
db_file = argv[1];
lua_file = argv[2];
lua_State * L = luaL_newstate();
luaL_openlibs(L);
luaL_dostring(L, LUA_COMMON);
if (luaL_dofile(L, lua_file) != 0) {
return 1;
}
call_init(L, argc - 2, (const char **) argv + 2);
dst = open(db_file, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (dst == -1) {
printf(
"Could not open destination file '%s': %s\n",
db_file,
strerror(errno)
);
rv = errno;
goto clean;
}
rv = libretrodb_create(dst, &value_provider, L);
clean:
lua_close(L);
if (dst != -1) {
close(dst);
}
return rv;
}