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"
29 #include "util/string.h"
45 #include "script/common/c_content.h"
54 ModNameStorer(lua_State *L_, const std::string &mod_name):
57 // Store current mod name in registry
58 lua_pushstring(L, mod_name.c_str());
59 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
63 // Clear current mod name from registry
65 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
74 ScriptApiBase::ScriptApiBase()
76 #ifdef SCRIPTAPI_LOCK_DEBUG
77 m_lock_recursion_count = 0;
80 m_luastack = luaL_newstate();
81 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
83 lua_atpanic(m_luastack, &luaPanic);
85 luaL_openlibs(m_luastack);
87 // Make the ScriptApiBase* accessible to ModApiBase
88 lua_pushlightuserdata(m_luastack, this);
89 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
91 // Add and save an error handler
92 lua_pushcfunction(m_luastack, script_error_handler);
93 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
95 // If we are using LuaJIT add a C++ wrapper function to catch
96 // exceptions thrown in Lua -> C++ calls
98 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
99 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
100 lua_pop(m_luastack, 1);
104 lua_newtable(m_luastack);
105 lua_setglobal(m_luastack, "core");
107 lua_pushstring(m_luastack, DIR_DELIM);
108 lua_setglobal(m_luastack, "DIR_DELIM");
110 lua_pushstring(m_luastack, porting::getPlatformName());
111 lua_setglobal(m_luastack, "PLATFORM");
114 ScriptApiBase::~ScriptApiBase()
116 lua_close(m_luastack);
119 int ScriptApiBase::luaPanic(lua_State *L)
121 std::ostringstream oss;
122 oss << "LUA PANIC: unprotected error in call to Lua API ("
123 << lua_tostring(L, -1) << ")";
124 FATAL_ERROR(oss.str().c_str());
129 void ScriptApiBase::loadMod(const std::string &script_path,
130 const std::string &mod_name)
132 ModNameStorer mod_name_storer(getStack(), mod_name);
134 loadScript(script_path);
137 void ScriptApiBase::loadScript(const std::string &script_path)
139 verbosestream << "Loading and running script from " << script_path << std::endl;
141 lua_State *L = getStack();
143 int error_handler = PUSH_ERROR_HANDLER(L);
147 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
149 ok = !luaL_loadfile(L, script_path.c_str());
151 ok = ok && !lua_pcall(L, 0, 0, error_handler);
153 std::string error_msg = lua_tostring(L, -1);
154 lua_pop(L, 2); // Pop error message and error handler
155 throw ModError("Failed to load and run script from " +
156 script_path + ":\n" + error_msg);
158 lua_pop(L, 1); // Pop error handler
161 // Push the list of callbacks (a lua table).
162 // Then push nargs arguments.
163 // Then call this function, which
164 // - runs the callbacks
165 // - replaces the table and arguments with the return value,
166 // computed depending on mode
167 // This function must only be called with scriptlock held (i.e. inside of a
168 // code block with SCRIPTAPI_PRECHECKHEADER declared)
169 void ScriptApiBase::runCallbacksRaw(int nargs,
170 RunCallbacksMode mode, const char *fxn)
172 #ifdef SCRIPTAPI_LOCK_DEBUG
173 assert(m_lock_recursion_count > 0);
175 lua_State *L = getStack();
176 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
178 // Insert error handler
179 PUSH_ERROR_HANDLER(L);
180 int error_handler = lua_gettop(L) - nargs - 1;
181 lua_insert(L, error_handler);
183 // Insert run_callbacks between error handler and table
184 lua_getglobal(L, "core");
185 lua_getfield(L, -1, "run_callbacks");
187 lua_insert(L, error_handler + 1);
189 // Insert mode after table
190 lua_pushnumber(L, (int)mode);
191 lua_insert(L, error_handler + 3);
193 // Stack now looks like this:
194 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
196 int result = lua_pcall(L, nargs + 2, 1, error_handler);
198 scriptError(result, fxn);
200 lua_remove(L, error_handler);
203 void ScriptApiBase::realityCheck()
205 int top = lua_gettop(m_luastack);
207 dstream << "Stack is over 30:" << std::endl;
209 std::string traceback = script_get_backtrace(m_luastack);
210 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
214 void ScriptApiBase::scriptError(int result, const char *fxn)
216 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
219 void ScriptApiBase::stackDump(std::ostream &o)
221 int top = lua_gettop(m_luastack);
222 for (int i = 1; i <= top; i++) { /* repeat for each level */
223 int t = lua_type(m_luastack, i);
225 case LUA_TSTRING: /* strings */
226 o << "\"" << lua_tostring(m_luastack, i) << "\"";
228 case LUA_TBOOLEAN: /* booleans */
229 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
231 case LUA_TNUMBER: /* numbers */ {
233 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
237 default: /* other values */
238 o << lua_typename(m_luastack, t);
246 void ScriptApiBase::setOriginDirect(const char *origin)
248 m_last_run_mod = origin ? origin : "??";
251 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
253 #ifdef SCRIPTAPI_DEBUG
254 lua_State *L = getStack();
256 m_last_run_mod = lua_istable(L, index) ?
257 getstringfield_default(L, index, "mod_origin", "") : "";
258 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
262 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
264 SCRIPTAPI_PRECHECKHEADER
265 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
267 // Create object on stack
268 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
269 int object = lua_gettop(L);
271 // Get core.object_refs table
272 lua_getglobal(L, "core");
273 lua_getfield(L, -1, "object_refs");
274 luaL_checktype(L, -1, LUA_TTABLE);
275 int objectstable = lua_gettop(L);
277 // object_refs[id] = object
278 lua_pushnumber(L, cobj->getId()); // Push id
279 lua_pushvalue(L, object); // Copy object to top of stack
280 lua_settable(L, objectstable);
283 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
285 SCRIPTAPI_PRECHECKHEADER
286 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
288 // Get core.object_refs table
289 lua_getglobal(L, "core");
290 lua_getfield(L, -1, "object_refs");
291 luaL_checktype(L, -1, LUA_TTABLE);
292 int objectstable = lua_gettop(L);
294 // Get object_refs[id]
295 lua_pushnumber(L, cobj->getId()); // Push id
296 lua_gettable(L, objectstable);
297 // Set object reference to NULL
298 ObjectRef::set_null(L);
299 lua_pop(L, 1); // pop object
301 // Set object_refs[id] = nil
302 lua_pushnumber(L, cobj->getId()); // Push id
304 lua_settable(L, objectstable);
307 // Creates a new anonymous reference if cobj=NULL or id=0
308 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
309 ServerActiveObject *cobj)
311 if (cobj == NULL || cobj->getId() == 0) {
312 ObjectRef::create(L, cobj);
314 push_objectRef(L, cobj->getId());
318 Server* ScriptApiBase::getServer()
320 return dynamic_cast<Server *>(m_gamedef);
323 Client* ScriptApiBase::getClient()
325 return dynamic_cast<Client *>(m_gamedef);