-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlua_script.c
More file actions
98 lines (80 loc) · 2.13 KB
/
Copy pathlua_script.c
File metadata and controls
98 lines (80 loc) · 2.13 KB
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
#include "lua/lua.h"
#include "lua/lauxlib.h"
#include "lua/lualib.h"
#include "lua_script.h"
#include "lua_freeslot.h"
#include "lua_sound.h"
#include "lua_draw.h"
#include "lua_hook.h"
#include "lua_obj.h"
#include "lua_kart.h"
lua_State *gL = NULL;
void script_init(void)
{
gL = luaL_newstate();
luaL_requiref(gL, "_G", luaopen_base, 1);
luaL_requiref(gL, LUA_COLIBNAME, luaopen_coroutine, 1);
luaL_requiref(gL, LUA_TABLIBNAME, luaopen_table, 1);
luaL_requiref(gL, LUA_STRLIBNAME, luaopen_string, 1);
luaL_requiref(gL, LUA_MATHLIBNAME, luaopen_math, 1);
/* luaL_requiref leaves copy of module on top of stack, we don't need those */
lua_settop(gL, 0);
freeslot_init();
luasound_init();
luadraw_init();
luaobj_init();
luakart_init();
hook_init();
}
#define SCRIPTBUFSIZE 1024
typedef struct script_reader_state_s {
SDL_RWops *src;
char buf[SCRIPTBUFSIZE+1];
} script_reader_state_t;
static const char *script_reader(lua_State *L, void *data, size_t *size)
{
(void)L;
script_reader_state_t *state = (script_reader_state_t*)data;
*size = SDL_RWread(state->src, state->buf, 1, SCRIPTBUFSIZE);
if (*size == 0)
{
SDL_RWclose(state->src);
return NULL;
}
state->buf[*size] = 0;
return state->buf;
}
bool script_run(SDL_RWops *src, const char *filename)
{
script_reader_state_t state = {0};
state.src = src;
if (lua_load(gL, script_reader, &state, filename, NULL) != LUA_OK)
{
printf("Error loading script %s: %s\n", filename, lua_tostring(gL, -1));
lua_pop(gL, 1);
return false;
}
/* TODO - error message handler */
if (lua_pcall(gL, 0, 0, 0) != LUA_OK)
{
printf("Error running script %s: %s\n", filename, lua_tostring(gL, -1));
lua_pop(gL, 1);
return false;
}
return true;
}
bool script_call(lua_State *L, int nargs, int nret, int msgh)
{
if (lua_pcall(L, nargs, nret, msgh) != LUA_OK)
{
printf("%s\n", lua_tostring(L, -1));
return false;
}
return true;
}
void script_deinit(void)
{
hook_deinit();
lua_close(gL);
gL = NULL;
}