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