0fb777c578ea0a807f43b09b4c13af26f3d1d527
[apps/madmutt.git] / lib-lua / runtime.c
1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License as published by
4  *  the Free Software Foundation; either version 2 of the License, or (at
5  *  your option) any later version.
6  *
7  *  This program is distributed in the hope that it will be useful, but
8  *  WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  *  General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15  *  MA 02110-1301, USA.
16  *
17  *  Copyright © 2007 Pierre Habouzit
18  */
19
20 #include <lib-lib/lib-lib.h>
21 #include "lib-lua_priv.h"
22
23 static lua_State *L;
24 static reg_entry registry[LTK_count];
25
26 static const luaL_Reg lualibs[] = {
27     {"",              luaopen_base},
28     {LUA_OSLIBNAME,   luaopen_os},
29     {LUA_LOADLIBNAME, luaopen_package},
30     {LUA_TABLIBNAME,  luaopen_table},
31     {LUA_IOLIBNAME,   luaopen_io},
32     {LUA_STRLIBNAME,  luaopen_string},
33     {LUA_MATHLIBNAME, luaopen_math},
34     {LUA_DBLIBNAME,   luaopen_debug},
35     {LUA_MADMUTT,     luaopen_madmutt},
36 };
37
38 void mlua_initialize(void)
39 {
40     int i;
41
42     L = lua_open();
43     for (i = 0; i < countof(lualibs); i++) {
44         lua_pushcfunction(L, lualibs[i].func);
45         lua_pushstring(L, lualibs[i].name);
46         lua_call(L, 1, 0);
47     }
48 }
49
50 void mlua_shutdown(void)
51 {
52     lua_close(L);
53 }
54
55
56 int mlua_dofile(const char *filename)
57 {
58     return luaL_dofile(L, filename);
59 }
60
61 int mlua_wrap(void (*errfun)(const char *fmt, ...), int status)
62 {
63     if (status) {
64         (*errfun)("-[lua]-: %s\n", lua_tostring(L, -1));
65         lua_pop(L, 1);
66     }
67     return status;
68 }
69
70 const char *mlua_reggets(int tk)
71 {
72     if (registry[tk].type != REG_STR)
73         return NULL;
74     return registry[tk].s;
75 }
76
77 int mlua_reggeti(int tk)
78 {
79     if (registry[tk].type != REG_INT)
80         return -1;
81     return registry[tk].i;
82 }
83
84 void mlua_regsets(int tk, const char *s)
85 {
86     reg_entry_wipe(registry + tk);
87     registry[tk].type = REG_STR;
88     registry[tk].s    = m_strdup(s);
89 }
90
91 void mlua_regseti(int tk, int i)
92 {
93     reg_entry_wipe(registry + tk);
94     registry[tk].type = REG_INT;
95     registry[tk].i    = i;
96 }