1f96373dc922e35bbbd47372a07c9a581b167442
[oweals/minetest.git] / src / script / cpp_api / s_base.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "cpp_api/s_base.h"
21 #include "cpp_api/s_internal.h"
22 #include "lua_api/l_object.h"
23 #include "serverobject.h"
24 #include "debug.h"
25 #include "filesys.h"
26 #include "log.h"
27 #include "mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30
31
32 extern "C" {
33 #include "lualib.h"
34 #if USE_LUAJIT
35         #include "luajit.h"
36 #endif
37 }
38
39 #include <stdio.h>
40 #include <cstdarg>
41
42
43 class ModNameStorer
44 {
45 private:
46         lua_State *L;
47 public:
48         ModNameStorer(lua_State *L_, const std::string &modname):
49                 L(L_)
50         {
51                 // Store current modname in registry
52                 lua_pushstring(L, modname.c_str());
53                 lua_setfield(L, LUA_REGISTRYINDEX, "current_modname");
54         }
55         ~ModNameStorer()
56         {
57                 // Clear current modname in registry
58                 lua_pushnil(L);
59                 lua_setfield(L, LUA_REGISTRYINDEX, "current_modname");
60         }
61 };
62
63
64 /*
65         ScriptApiBase
66 */
67
68 ScriptApiBase::ScriptApiBase()
69 {
70         #ifdef SCRIPTAPI_LOCK_DEBUG
71         m_locked = false;
72         #endif
73
74         m_luastack = luaL_newstate();
75         assert(m_luastack);
76
77         luaL_openlibs(m_luastack);
78
79         // Add and save an error handler
80         lua_pushcfunction(m_luastack, script_error_handler);
81         m_errorhandler = lua_gettop(m_luastack);
82
83         // Make the ScriptApiBase* accessible to ModApiBase
84         lua_pushlightuserdata(m_luastack, this);
85         lua_setfield(m_luastack, LUA_REGISTRYINDEX, "scriptapi");
86
87         // If we are using LuaJIT add a C++ wrapper function to catch
88         // exceptions thrown in Lua -> C++ calls
89 #if USE_LUAJIT
90         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
91         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
92         lua_pop(m_luastack, 1);
93 #endif
94
95         // Add basic globals
96         lua_newtable(m_luastack);
97         lua_setglobal(m_luastack, "core");
98
99         lua_pushstring(m_luastack, DIR_DELIM);
100         lua_setglobal(m_luastack, "DIR_DELIM");
101
102         lua_pushstring(m_luastack, porting::getPlatformName());
103         lua_setglobal(m_luastack, "PLATFORM");
104
105         m_server = NULL;
106         m_environment = NULL;
107         m_guiengine = NULL;
108 }
109
110 ScriptApiBase::~ScriptApiBase()
111 {
112         lua_close(m_luastack);
113 }
114
115 bool ScriptApiBase::loadMod(const std::string &scriptpath,
116                 const std::string &modname)
117 {
118         ModNameStorer modnamestorer(getStack(), modname);
119
120         if (!string_allowed(modname, MODNAME_ALLOWED_CHARS)) {
121                 errorstream<<"Error loading mod \""<<modname
122                                 <<"\": modname does not follow naming conventions: "
123                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
124                 return false;
125         }
126
127         return loadScript(scriptpath);
128 }
129
130 bool ScriptApiBase::loadScript(const std::string &scriptpath)
131 {
132         verbosestream<<"Loading and running script from "<<scriptpath<<std::endl;
133
134         lua_State *L = getStack();
135
136         int ret = luaL_loadfile(L, scriptpath.c_str()) || lua_pcall(L, 0, 0, m_errorhandler);
137         if (ret) {
138                 errorstream << "========== ERROR FROM LUA ===========" << std::endl;
139                 errorstream << "Failed to load and run script from " << std::endl;
140                 errorstream << scriptpath << ":" << std::endl;
141                 errorstream << std::endl;
142                 errorstream << lua_tostring(L, -1) << std::endl;
143                 errorstream << std::endl;
144                 errorstream << "======= END OF ERROR FROM LUA ========" << std::endl;
145                 lua_pop(L, 1); // Pop error message from stack
146                 return false;
147         }
148         return true;
149 }
150
151 void ScriptApiBase::realityCheck()
152 {
153         int top = lua_gettop(m_luastack);
154         if(top >= 30){
155                 dstream<<"Stack is over 30:"<<std::endl;
156                 stackDump(dstream);
157                 std::string traceback = script_get_backtrace(m_luastack);
158                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
159         }
160 }
161
162 void ScriptApiBase::scriptError()
163 {
164         throw LuaError(lua_tostring(m_luastack, -1));
165 }
166
167 void ScriptApiBase::stackDump(std::ostream &o)
168 {
169         int i;
170         int top = lua_gettop(m_luastack);
171         for (i = 1; i <= top; i++) {  /* repeat for each level */
172                 int t = lua_type(m_luastack, i);
173                 switch (t) {
174
175                         case LUA_TSTRING:  /* strings */
176                                 o<<"\""<<lua_tostring(m_luastack, i)<<"\"";
177                                 break;
178
179                         case LUA_TBOOLEAN:  /* booleans */
180                                 o<<(lua_toboolean(m_luastack, i) ? "true" : "false");
181                                 break;
182
183                         case LUA_TNUMBER:  /* numbers */ {
184                                 char buf[10];
185                                 snprintf(buf, 10, "%g", lua_tonumber(m_luastack, i));
186                                 o<<buf;
187                                 break; }
188
189                         default:  /* other values */
190                                 o<<lua_typename(m_luastack, t);
191                                 break;
192
193                 }
194                 o<<" ";
195         }
196         o<<std::endl;
197 }
198
199 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
200 {
201         SCRIPTAPI_PRECHECKHEADER
202         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
203
204         // Create object on stack
205         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
206         int object = lua_gettop(L);
207
208         // Get core.object_refs table
209         lua_getglobal(L, "core");
210         lua_getfield(L, -1, "object_refs");
211         luaL_checktype(L, -1, LUA_TTABLE);
212         int objectstable = lua_gettop(L);
213
214         // object_refs[id] = object
215         lua_pushnumber(L, cobj->getId()); // Push id
216         lua_pushvalue(L, object); // Copy object to top of stack
217         lua_settable(L, objectstable);
218 }
219
220 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
221 {
222         SCRIPTAPI_PRECHECKHEADER
223         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
224
225         // Get core.object_refs table
226         lua_getglobal(L, "core");
227         lua_getfield(L, -1, "object_refs");
228         luaL_checktype(L, -1, LUA_TTABLE);
229         int objectstable = lua_gettop(L);
230
231         // Get object_refs[id]
232         lua_pushnumber(L, cobj->getId()); // Push id
233         lua_gettable(L, objectstable);
234         // Set object reference to NULL
235         ObjectRef::set_null(L);
236         lua_pop(L, 1); // pop object
237
238         // Set object_refs[id] = nil
239         lua_pushnumber(L, cobj->getId()); // Push id
240         lua_pushnil(L);
241         lua_settable(L, objectstable);
242 }
243
244 // Creates a new anonymous reference if cobj=NULL or id=0
245 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
246                 ServerActiveObject *cobj)
247 {
248         if(cobj == NULL || cobj->getId() == 0){
249                 ObjectRef::create(L, cobj);
250         } else {
251                 objectrefGet(L, cobj->getId());
252         }
253 }
254
255 void ScriptApiBase::objectrefGet(lua_State *L, u16 id)
256 {
257         // Get core.object_refs[i]
258         lua_getglobal(L, "core");
259         lua_getfield(L, -1, "object_refs");
260         luaL_checktype(L, -1, LUA_TTABLE);
261         lua_pushnumber(L, id);
262         lua_gettable(L, -2);
263         lua_remove(L, -2); // object_refs
264         lua_remove(L, -2); // core
265 }
266