Lua improvements:
[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/lib-lua.h>
22
23 static lua_State *L;
24
25 void luaM_initialize(void)
26 {
27     static const luaL_Reg lualibs[] = {
28         {"",              luaopen_base},
29         {LUA_OSLIBNAME,   luaopen_os},
30         {LUA_LOADLIBNAME, luaopen_package},
31         {LUA_TABLIBNAME,  luaopen_table},
32         {LUA_IOLIBNAME,   luaopen_io},
33         {LUA_STRLIBNAME,  luaopen_string},
34         {LUA_MATHLIBNAME, luaopen_math},
35         {LUA_DBLIBNAME,   luaopen_debug},
36         {"madmutt",       luaopen_madmutt},
37     };
38
39     int i;
40
41     L = lua_open();
42     for (i = 0; i < countof(lualibs); i++) {
43         lua_pushcfunction(L, lualibs[i].func);
44         lua_pushstring(L, lualibs[i].name);
45         lua_call(L, 1, 0);
46     }
47 }
48
49 void luaM_shutdown(void)
50 {
51     lua_close(L);
52 }
53
54
55 int luaM_dofile(const char *filename)
56 {
57     return luaL_dofile(L, filename);
58 }
59
60 int luaM_wrap(void (*errfun)(const char *fmt, ...), int status)
61 {
62     if (status) {
63         (*errfun)("-[lua]-: %s\n", lua_tostring(L, -1));
64         lua_pop(L, 1);
65     }
66     return status;
67 }
68
69
70 quadopt_t luaM_checkquadopt(lua_State *Ls, int narg)
71 {
72     const char *s;
73     int i = luaL_checkinteger(Ls, narg);
74
75     if (i & ~3) {
76         s = lua_pushfstring(Ls, "int in [0-3] expected, got %d", i);
77         return luaL_argerror(Ls, narg, s);
78     }
79     return i;
80 }
81