3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
34 void script_error(lua_State *L, const char *fmt, ...)
38 vfprintf(stderr, fmt, argp);
44 void script_call_va(lua_State *L, const char *func, const char *sig, ...)
47 int narg, nres; /* number of arguments and results */
50 lua_getglobal(L, func); /* push function */
52 for (narg = 0; *sig; narg++) {
53 /* repeat for each argument */
54 /* check stack space */
55 luaL_checkstack(L, 1, "too many arguments");
57 case 'd': /* double argument */
58 lua_pushnumber(L, va_arg(vl, double));
60 case 'i': /* int argument */
61 lua_pushinteger(L, va_arg(vl, int));
63 case 's': /* string argument */
64 lua_pushstring(L, va_arg(vl, char *));
66 case '>': /* end of arguments */
69 script_error(L, "invalid option (%c)", *(sig - 1));
74 nres = strlen(sig); /* number of expected results */
76 if (lua_pcall(L, narg, nres, 0) != 0) /* do the call */
77 script_error(L, "error calling '%s': %s", func, lua_tostring(L, -1));
79 nres = -nres; /* stack index of first result */
80 while (*sig) { /* repeat for each result */
82 case 'd': /* double result */
83 if (!lua_isnumber(L, nres))
84 script_error(L, "wrong result type");
85 *va_arg(vl, double *) = lua_tonumber(L, nres);
87 case 'i': /* int result */
88 if (!lua_isnumber(L, nres))
89 script_error(L, "wrong result type");
90 *va_arg(vl, int *) = lua_tointeger(L, nres);
92 case 's': /* string result */
93 if (!lua_isstring(L, nres))
94 script_error(L, "wrong result type");
95 *va_arg(vl, const char **) = lua_tostring(L, nres);
98 script_error(L, "invalid option (%c)", *(sig - 1));
106 bool script_load(lua_State *L, const char *path)
108 infostream<<"Loading and running script from "<<path<<std::endl;
109 int ret = luaL_loadfile(L, path) || lua_pcall(L, 0, 0, 0);
111 errorstream<<"Failed to load and run script from "<<path<<": "<<lua_tostring(L, -1)<<std::endl;
112 lua_pop(L, 1); // Pop error message from stack
118 lua_State* script_init()
120 lua_State *L = luaL_newstate();
125 lua_State* script_deinit(lua_State *L)