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