3 Copyright (C) 2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser 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.
20 #include "cpp_api/s_base.h"
21 #include "cpp_api/s_internal.h"
22 #include "cpp_api/s_security.h"
23 #include "lua_api/l_object.h"
24 #include "common/c_converter.h"
25 #include "serverobject.h"
31 #include "util/string.h"
50 ModNameStorer(lua_State *L_, const std::string &mod_name):
53 // Store current mod name in registry
54 lua_pushstring(L, mod_name.c_str());
55 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
59 // Clear current mod name from registry
61 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
70 ScriptApiBase::ScriptApiBase()
72 #ifdef SCRIPTAPI_LOCK_DEBUG
76 m_luastack = luaL_newstate();
77 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
79 luaL_openlibs(m_luastack);
81 // Make the ScriptApiBase* accessible to ModApiBase
82 lua_pushlightuserdata(m_luastack, this);
83 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
85 // Add and save an error handler
86 lua_pushcfunction(m_luastack, script_error_handler);
87 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
89 // If we are using LuaJIT add a C++ wrapper function to catch
90 // exceptions thrown in Lua -> C++ calls
92 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
93 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
94 lua_pop(m_luastack, 1);
98 lua_newtable(m_luastack);
99 lua_setglobal(m_luastack, "core");
101 lua_pushstring(m_luastack, DIR_DELIM);
102 lua_setglobal(m_luastack, "DIR_DELIM");
104 lua_pushstring(m_luastack, porting::getPlatformName());
105 lua_setglobal(m_luastack, "PLATFORM");
107 // m_secure gets set to true inside
108 // ScriptApiSecurity::initializeSecurity(), if neccessary.
109 // Default to false otherwise
113 m_environment = NULL;
117 ScriptApiBase::~ScriptApiBase()
119 lua_close(m_luastack);
122 void ScriptApiBase::loadMod(const std::string &script_path,
123 const std::string &mod_name)
125 ModNameStorer mod_name_storer(getStack(), mod_name);
127 loadScript(script_path);
130 void ScriptApiBase::loadScript(const std::string &script_path)
132 verbosestream << "Loading and running script from " << script_path << std::endl;
134 lua_State *L = getStack();
136 int error_handler = PUSH_ERROR_HANDLER(L);
140 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
142 ok = !luaL_loadfile(L, script_path.c_str());
144 ok = ok && !lua_pcall(L, 0, 0, error_handler);
146 std::string error_msg = lua_tostring(L, -1);
147 lua_pop(L, 2); // Pop error message and error handler
148 throw ModError("Failed to load and run script from " +
149 script_path + ":\n" + error_msg);
151 lua_pop(L, 1); // Pop error handler
154 // Push the list of callbacks (a lua table).
155 // Then push nargs arguments.
156 // Then call this function, which
157 // - runs the callbacks
158 // - replaces the table and arguments with the return value,
159 // computed depending on mode
160 void ScriptApiBase::runCallbacksRaw(int nargs,
161 RunCallbacksMode mode, const char *fxn)
163 lua_State *L = getStack();
164 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
166 // Insert error handler
167 PUSH_ERROR_HANDLER(L);
168 int error_handler = lua_gettop(L) - nargs - 1;
169 lua_insert(L, error_handler);
171 // Insert run_callbacks between error handler and table
172 lua_getglobal(L, "core");
173 lua_getfield(L, -1, "run_callbacks");
175 lua_insert(L, error_handler + 1);
177 // Insert mode after table
178 lua_pushnumber(L, (int)mode);
179 lua_insert(L, error_handler + 3);
181 // Stack now looks like this:
182 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
184 int result = lua_pcall(L, nargs + 2, 1, error_handler);
186 scriptError(result, fxn);
188 lua_remove(L, error_handler);
191 void ScriptApiBase::realityCheck()
193 int top = lua_gettop(m_luastack);
195 dstream << "Stack is over 30:" << std::endl;
197 std::string traceback = script_get_backtrace(m_luastack);
198 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
202 void ScriptApiBase::scriptError(int result, const char *fxn)
204 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
207 void ScriptApiBase::stackDump(std::ostream &o)
209 int top = lua_gettop(m_luastack);
210 for (int i = 1; i <= top; i++) { /* repeat for each level */
211 int t = lua_type(m_luastack, i);
213 case LUA_TSTRING: /* strings */
214 o << "\"" << lua_tostring(m_luastack, i) << "\"";
216 case LUA_TBOOLEAN: /* booleans */
217 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
219 case LUA_TNUMBER: /* numbers */ {
221 snprintf(buf, 10, "%g", lua_tonumber(m_luastack, i));
225 default: /* other values */
226 o << lua_typename(m_luastack, t);
234 void ScriptApiBase::setOriginDirect(const char *origin)
236 m_last_run_mod = origin ? origin : "??";
239 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
241 #ifdef SCRIPTAPI_DEBUG
242 lua_State *L = getStack();
244 m_last_run_mod = lua_istable(L, index) ?
245 getstringfield_default(L, index, "mod_origin", "") : "";
246 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
250 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
252 SCRIPTAPI_PRECHECKHEADER
253 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
255 // Create object on stack
256 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
257 int object = lua_gettop(L);
259 // Get core.object_refs table
260 lua_getglobal(L, "core");
261 lua_getfield(L, -1, "object_refs");
262 luaL_checktype(L, -1, LUA_TTABLE);
263 int objectstable = lua_gettop(L);
265 // object_refs[id] = object
266 lua_pushnumber(L, cobj->getId()); // Push id
267 lua_pushvalue(L, object); // Copy object to top of stack
268 lua_settable(L, objectstable);
271 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
273 SCRIPTAPI_PRECHECKHEADER
274 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
276 // Get core.object_refs table
277 lua_getglobal(L, "core");
278 lua_getfield(L, -1, "object_refs");
279 luaL_checktype(L, -1, LUA_TTABLE);
280 int objectstable = lua_gettop(L);
282 // Get object_refs[id]
283 lua_pushnumber(L, cobj->getId()); // Push id
284 lua_gettable(L, objectstable);
285 // Set object reference to NULL
286 ObjectRef::set_null(L);
287 lua_pop(L, 1); // pop object
289 // Set object_refs[id] = nil
290 lua_pushnumber(L, cobj->getId()); // Push id
292 lua_settable(L, objectstable);
295 // Creates a new anonymous reference if cobj=NULL or id=0
296 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
297 ServerActiveObject *cobj)
299 if (cobj == NULL || cobj->getId() == 0) {
300 ObjectRef::create(L, cobj);
302 objectrefGet(L, cobj->getId());
306 void ScriptApiBase::objectrefGet(lua_State *L, u16 id)
308 // Get core.object_refs[i]
309 lua_getglobal(L, "core");
310 lua_getfield(L, -1, "object_refs");
311 luaL_checktype(L, -1, LUA_TTABLE);
312 lua_pushnumber(L, id);
314 lua_remove(L, -2); // object_refs
315 lua_remove(L, -2); // core