Add dtime_s to entity activation
[oweals/minetest.git] / src / scriptapi.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2011 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 "scriptapi.h"
21
22 #include <iostream>
23 #include <list>
24 extern "C" {
25 #include <lua.h>
26 #include <lualib.h>
27 #include <lauxlib.h>
28 }
29
30 #include "log.h"
31 #include "server.h"
32 #include "porting.h"
33 #include "filesys.h"
34 #include "serverobject.h"
35 #include "script.h"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
38 #include "itemdef.h"
39 #include "nodedef.h"
40 #include "craftdef.h"
41 #include "main.h" // For g_settings
42 #include "settings.h" // For accessing g_settings
43 #include "nodemetadata.h"
44 #include "mapblock.h" // For getNodeBlockPos
45 #include "content_nodemeta.h"
46 #include "tool.h"
47 #include "daynightratio.h"
48 #include "noise.h" // PseudoRandom for LuaPseudoRandom
49 #include "util/pointedthing.h"
50 #include "rollback.h"
51
52 static void stackDump(lua_State *L, std::ostream &o)
53 {
54   int i;
55   int top = lua_gettop(L);
56   for (i = 1; i <= top; i++) {  /* repeat for each level */
57         int t = lua_type(L, i);
58         switch (t) {
59
60           case LUA_TSTRING:  /* strings */
61                 o<<"\""<<lua_tostring(L, i)<<"\"";
62                 break;
63
64           case LUA_TBOOLEAN:  /* booleans */
65                 o<<(lua_toboolean(L, i) ? "true" : "false");
66                 break;
67
68           case LUA_TNUMBER:  /* numbers */ {
69                 char buf[10];
70                 snprintf(buf, 10, "%g", lua_tonumber(L, i));
71                 o<<buf;
72                 break; }
73
74           default:  /* other values */
75                 o<<lua_typename(L, t);
76                 break;
77
78         }
79         o<<" ";
80   }
81   o<<std::endl;
82 }
83
84 static void realitycheck(lua_State *L)
85 {
86         int top = lua_gettop(L);
87         if(top >= 30){
88                 dstream<<"Stack is over 30:"<<std::endl;
89                 stackDump(L, dstream);
90                 script_error(L, "Stack is over 30 (reality check)");
91         }
92 }
93
94 class StackUnroller
95 {
96 private:
97         lua_State *m_lua;
98         int m_original_top;
99 public:
100         StackUnroller(lua_State *L):
101                 m_lua(L),
102                 m_original_top(-1)
103         {
104                 m_original_top = lua_gettop(m_lua); // store stack height
105         }
106         ~StackUnroller()
107         {
108                 lua_settop(m_lua, m_original_top); // restore stack height
109         }
110 };
111
112 class ModNameStorer
113 {
114 private:
115         lua_State *L;
116 public:
117         ModNameStorer(lua_State *L_, const std::string modname):
118                 L(L_)
119         {
120                 // Store current modname in registry
121                 lua_pushstring(L, modname.c_str());
122                 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
123         }
124         ~ModNameStorer()
125         {
126                 // Clear current modname in registry
127                 lua_pushnil(L);
128                 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
129         }
130 };
131
132 /*
133         Getters for stuff in main tables
134 */
135
136 static Server* get_server(lua_State *L)
137 {
138         // Get server from registry
139         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
140         Server *server = (Server*)lua_touserdata(L, -1);
141         lua_pop(L, 1);
142         return server;
143 }
144
145 static ServerEnvironment* get_env(lua_State *L)
146 {
147         // Get environment from registry
148         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
149         ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
150         lua_pop(L, 1);
151         return env;
152 }
153
154 static void objectref_get(lua_State *L, u16 id)
155 {
156         // Get minetest.object_refs[i]
157         lua_getglobal(L, "minetest");
158         lua_getfield(L, -1, "object_refs");
159         luaL_checktype(L, -1, LUA_TTABLE);
160         lua_pushnumber(L, id);
161         lua_gettable(L, -2);
162         lua_remove(L, -2); // object_refs
163         lua_remove(L, -2); // minetest
164 }
165
166 static void luaentity_get(lua_State *L, u16 id)
167 {
168         // Get minetest.luaentities[i]
169         lua_getglobal(L, "minetest");
170         lua_getfield(L, -1, "luaentities");
171         luaL_checktype(L, -1, LUA_TTABLE);
172         lua_pushnumber(L, id);
173         lua_gettable(L, -2);
174         lua_remove(L, -2); // luaentities
175         lua_remove(L, -2); // minetest
176 }
177
178 /*
179         Table field getters
180 */
181
182 static bool getstringfield(lua_State *L, int table,
183                 const char *fieldname, std::string &result)
184 {
185         lua_getfield(L, table, fieldname);
186         bool got = false;
187         if(lua_isstring(L, -1)){
188                 size_t len = 0;
189                 const char *ptr = lua_tolstring(L, -1, &len);
190                 result.assign(ptr, len);
191                 got = true;
192         }
193         lua_pop(L, 1);
194         return got;
195 }
196
197 static bool getintfield(lua_State *L, int table,
198                 const char *fieldname, int &result)
199 {
200         lua_getfield(L, table, fieldname);
201         bool got = false;
202         if(lua_isnumber(L, -1)){
203                 result = lua_tonumber(L, -1);
204                 got = true;
205         }
206         lua_pop(L, 1);
207         return got;
208 }
209
210 static bool getfloatfield(lua_State *L, int table,
211                 const char *fieldname, float &result)
212 {
213         lua_getfield(L, table, fieldname);
214         bool got = false;
215         if(lua_isnumber(L, -1)){
216                 result = lua_tonumber(L, -1);
217                 got = true;
218         }
219         lua_pop(L, 1);
220         return got;
221 }
222
223 static bool getboolfield(lua_State *L, int table,
224                 const char *fieldname, bool &result)
225 {
226         lua_getfield(L, table, fieldname);
227         bool got = false;
228         if(lua_isboolean(L, -1)){
229                 result = lua_toboolean(L, -1);
230                 got = true;
231         }
232         lua_pop(L, 1);
233         return got;
234 }
235
236 static std::string checkstringfield(lua_State *L, int table,
237                 const char *fieldname)
238 {
239         lua_getfield(L, table, fieldname);
240         std::string s = luaL_checkstring(L, -1);
241         lua_pop(L, 1);
242         return s;
243 }
244
245 static std::string getstringfield_default(lua_State *L, int table,
246                 const char *fieldname, const std::string &default_)
247 {
248         std::string result = default_;
249         getstringfield(L, table, fieldname, result);
250         return result;
251 }
252
253 static int getintfield_default(lua_State *L, int table,
254                 const char *fieldname, int default_)
255 {
256         int result = default_;
257         getintfield(L, table, fieldname, result);
258         return result;
259 }
260
261 static float getfloatfield_default(lua_State *L, int table,
262                 const char *fieldname, float default_)
263 {
264         float result = default_;
265         getfloatfield(L, table, fieldname, result);
266         return result;
267 }
268
269 static bool getboolfield_default(lua_State *L, int table,
270                 const char *fieldname, bool default_)
271 {
272         bool result = default_;
273         getboolfield(L, table, fieldname, result);
274         return result;
275 }
276
277 struct EnumString
278 {
279         int num;
280         const char *str;
281 };
282
283 static bool string_to_enum(const EnumString *spec, int &result,
284                 const std::string &str)
285 {
286         const EnumString *esp = spec;
287         while(esp->str){
288                 if(str == std::string(esp->str)){
289                         result = esp->num;
290                         return true;
291                 }
292                 esp++;
293         }
294         return false;
295 }
296
297 /*static bool enum_to_string(const EnumString *spec, std::string &result,
298                 int num)
299 {
300         const EnumString *esp = spec;
301         while(esp){
302                 if(num == esp->num){
303                         result = esp->str;
304                         return true;
305                 }
306                 esp++;
307         }
308         return false;
309 }*/
310
311 static int getenumfield(lua_State *L, int table,
312                 const char *fieldname, const EnumString *spec, int default_)
313 {
314         int result = default_;
315         string_to_enum(spec, result,
316                         getstringfield_default(L, table, fieldname, ""));
317         return result;
318 }
319
320 static void setintfield(lua_State *L, int table,
321                 const char *fieldname, int value)
322 {
323         lua_pushinteger(L, value);
324         if(table < 0)
325                 table -= 1;
326         lua_setfield(L, table, fieldname);
327 }
328
329 static void setfloatfield(lua_State *L, int table,
330                 const char *fieldname, float value)
331 {
332         lua_pushnumber(L, value);
333         if(table < 0)
334                 table -= 1;
335         lua_setfield(L, table, fieldname);
336 }
337
338 static void setboolfield(lua_State *L, int table,
339                 const char *fieldname, bool value)
340 {
341         lua_pushboolean(L, value);
342         if(table < 0)
343                 table -= 1;
344         lua_setfield(L, table, fieldname);
345 }
346
347 static void warn_if_field_exists(lua_State *L, int table,
348                 const char *fieldname, const std::string &message)
349 {
350         lua_getfield(L, table, fieldname);
351         if(!lua_isnil(L, -1)){
352                 infostream<<script_get_backtrace(L)<<std::endl;
353                 infostream<<"WARNING: field \""<<fieldname<<"\": "
354                                 <<message<<std::endl;
355         }
356         lua_pop(L, 1);
357 }
358
359 /*
360         EnumString definitions
361 */
362
363 struct EnumString es_ItemType[] =
364 {
365         {ITEM_NONE, "none"},
366         {ITEM_NODE, "node"},
367         {ITEM_CRAFT, "craft"},
368         {ITEM_TOOL, "tool"},
369         {0, NULL},
370 };
371
372 struct EnumString es_DrawType[] =
373 {
374         {NDT_NORMAL, "normal"},
375         {NDT_AIRLIKE, "airlike"},
376         {NDT_LIQUID, "liquid"},
377         {NDT_FLOWINGLIQUID, "flowingliquid"},
378         {NDT_GLASSLIKE, "glasslike"},
379         {NDT_ALLFACES, "allfaces"},
380         {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
381         {NDT_TORCHLIKE, "torchlike"},
382         {NDT_SIGNLIKE, "signlike"},
383         {NDT_PLANTLIKE, "plantlike"},
384         {NDT_FENCELIKE, "fencelike"},
385         {NDT_RAILLIKE, "raillike"},
386         {NDT_NODEBOX, "nodebox"},
387         {0, NULL},
388 };
389
390 struct EnumString es_ContentParamType[] =
391 {
392         {CPT_NONE, "none"},
393         {CPT_LIGHT, "light"},
394         {0, NULL},
395 };
396
397 struct EnumString es_ContentParamType2[] =
398 {
399         {CPT2_NONE, "none"},
400         {CPT2_FULL, "full"},
401         {CPT2_FLOWINGLIQUID, "flowingliquid"},
402         {CPT2_FACEDIR, "facedir"},
403         {CPT2_WALLMOUNTED, "wallmounted"},
404         {0, NULL},
405 };
406
407 struct EnumString es_LiquidType[] =
408 {
409         {LIQUID_NONE, "none"},
410         {LIQUID_FLOWING, "flowing"},
411         {LIQUID_SOURCE, "source"},
412         {0, NULL},
413 };
414
415 struct EnumString es_NodeBoxType[] =
416 {
417         {NODEBOX_REGULAR, "regular"},
418         {NODEBOX_FIXED, "fixed"},
419         {NODEBOX_WALLMOUNTED, "wallmounted"},
420         {0, NULL},
421 };
422
423 struct EnumString es_CraftMethod[] =
424 {
425         {CRAFT_METHOD_NORMAL, "normal"},
426         {CRAFT_METHOD_COOKING, "cooking"},
427         {CRAFT_METHOD_FUEL, "fuel"},
428         {0, NULL},
429 };
430
431 struct EnumString es_TileAnimationType[] =
432 {
433         {TAT_NONE, "none"},
434         {TAT_VERTICAL_FRAMES, "vertical_frames"},
435         {0, NULL},
436 };
437
438 /*
439         C struct <-> Lua table converter functions
440 */
441
442 static void push_v3f(lua_State *L, v3f p)
443 {
444         lua_newtable(L);
445         lua_pushnumber(L, p.X);
446         lua_setfield(L, -2, "x");
447         lua_pushnumber(L, p.Y);
448         lua_setfield(L, -2, "y");
449         lua_pushnumber(L, p.Z);
450         lua_setfield(L, -2, "z");
451 }
452
453 static v2s16 read_v2s16(lua_State *L, int index)
454 {
455         v2s16 p;
456         luaL_checktype(L, index, LUA_TTABLE);
457         lua_getfield(L, index, "x");
458         p.X = lua_tonumber(L, -1);
459         lua_pop(L, 1);
460         lua_getfield(L, index, "y");
461         p.Y = lua_tonumber(L, -1);
462         lua_pop(L, 1);
463         return p;
464 }
465
466 static v2f read_v2f(lua_State *L, int index)
467 {
468         v2f p;
469         luaL_checktype(L, index, LUA_TTABLE);
470         lua_getfield(L, index, "x");
471         p.X = lua_tonumber(L, -1);
472         lua_pop(L, 1);
473         lua_getfield(L, index, "y");
474         p.Y = lua_tonumber(L, -1);
475         lua_pop(L, 1);
476         return p;
477 }
478
479 static v3f read_v3f(lua_State *L, int index)
480 {
481         v3f pos;
482         luaL_checktype(L, index, LUA_TTABLE);
483         lua_getfield(L, index, "x");
484         pos.X = lua_tonumber(L, -1);
485         lua_pop(L, 1);
486         lua_getfield(L, index, "y");
487         pos.Y = lua_tonumber(L, -1);
488         lua_pop(L, 1);
489         lua_getfield(L, index, "z");
490         pos.Z = lua_tonumber(L, -1);
491         lua_pop(L, 1);
492         return pos;
493 }
494
495 static v3f check_v3f(lua_State *L, int index)
496 {
497         v3f pos;
498         luaL_checktype(L, index, LUA_TTABLE);
499         lua_getfield(L, index, "x");
500         pos.X = luaL_checknumber(L, -1);
501         lua_pop(L, 1);
502         lua_getfield(L, index, "y");
503         pos.Y = luaL_checknumber(L, -1);
504         lua_pop(L, 1);
505         lua_getfield(L, index, "z");
506         pos.Z = luaL_checknumber(L, -1);
507         lua_pop(L, 1);
508         return pos;
509 }
510
511 static void pushFloatPos(lua_State *L, v3f p)
512 {
513         p /= BS;
514         push_v3f(L, p);
515 }
516
517 static v3f checkFloatPos(lua_State *L, int index)
518 {
519         return check_v3f(L, index) * BS;
520 }
521
522 static void push_v3s16(lua_State *L, v3s16 p)
523 {
524         lua_newtable(L);
525         lua_pushnumber(L, p.X);
526         lua_setfield(L, -2, "x");
527         lua_pushnumber(L, p.Y);
528         lua_setfield(L, -2, "y");
529         lua_pushnumber(L, p.Z);
530         lua_setfield(L, -2, "z");
531 }
532
533 static v3s16 read_v3s16(lua_State *L, int index)
534 {
535         // Correct rounding at <0
536         v3f pf = read_v3f(L, index);
537         return floatToInt(pf, 1.0);
538 }
539
540 static v3s16 check_v3s16(lua_State *L, int index)
541 {
542         // Correct rounding at <0
543         v3f pf = check_v3f(L, index);
544         return floatToInt(pf, 1.0);
545 }
546
547 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
548 {
549         lua_newtable(L);
550         lua_pushstring(L, ndef->get(n).name.c_str());
551         lua_setfield(L, -2, "name");
552         lua_pushnumber(L, n.getParam1());
553         lua_setfield(L, -2, "param1");
554         lua_pushnumber(L, n.getParam2());
555         lua_setfield(L, -2, "param2");
556 }
557
558 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
559 {
560         lua_getfield(L, index, "name");
561         const char *name = luaL_checkstring(L, -1);
562         lua_pop(L, 1);
563         u8 param1;
564         lua_getfield(L, index, "param1");
565         if(lua_isnil(L, -1))
566                 param1 = 0;
567         else
568                 param1 = lua_tonumber(L, -1);
569         lua_pop(L, 1);
570         u8 param2;
571         lua_getfield(L, index, "param2");
572         if(lua_isnil(L, -1))
573                 param2 = 0;
574         else
575                 param2 = lua_tonumber(L, -1);
576         lua_pop(L, 1);
577         return MapNode(ndef, name, param1, param2);
578 }
579
580 static video::SColor readARGB8(lua_State *L, int index)
581 {
582         video::SColor color;
583         luaL_checktype(L, index, LUA_TTABLE);
584         lua_getfield(L, index, "a");
585         if(lua_isnumber(L, -1))
586                 color.setAlpha(lua_tonumber(L, -1));
587         lua_pop(L, 1);
588         lua_getfield(L, index, "r");
589         color.setRed(lua_tonumber(L, -1));
590         lua_pop(L, 1);
591         lua_getfield(L, index, "g");
592         color.setGreen(lua_tonumber(L, -1));
593         lua_pop(L, 1);
594         lua_getfield(L, index, "b");
595         color.setBlue(lua_tonumber(L, -1));
596         lua_pop(L, 1);
597         return color;
598 }
599
600 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
601 {
602         aabb3f box;
603         if(lua_istable(L, index)){
604                 lua_rawgeti(L, index, 1);
605                 box.MinEdge.X = lua_tonumber(L, -1) * scale;
606                 lua_pop(L, 1);
607                 lua_rawgeti(L, index, 2);
608                 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
609                 lua_pop(L, 1);
610                 lua_rawgeti(L, index, 3);
611                 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
612                 lua_pop(L, 1);
613                 lua_rawgeti(L, index, 4);
614                 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
615                 lua_pop(L, 1);
616                 lua_rawgeti(L, index, 5);
617                 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
618                 lua_pop(L, 1);
619                 lua_rawgeti(L, index, 6);
620                 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
621                 lua_pop(L, 1);
622         }
623         return box;
624 }
625
626 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
627 {
628         std::vector<aabb3f> boxes;
629         if(lua_istable(L, index)){
630                 int n = lua_objlen(L, index);
631                 // Check if it's a single box or a list of boxes
632                 bool possibly_single_box = (n == 6);
633                 for(int i = 1; i <= n && possibly_single_box; i++){
634                         lua_rawgeti(L, index, i);
635                         if(!lua_isnumber(L, -1))
636                                 possibly_single_box = false;
637                         lua_pop(L, 1);
638                 }
639                 if(possibly_single_box){
640                         // Read a single box
641                         boxes.push_back(read_aabb3f(L, index, scale));
642                 } else {
643                         // Read a list of boxes
644                         for(int i = 1; i <= n; i++){
645                                 lua_rawgeti(L, index, i);
646                                 boxes.push_back(read_aabb3f(L, -1, scale));
647                                 lua_pop(L, 1);
648                         }
649                 }
650         }
651         return boxes;
652 }
653
654 static NodeBox read_nodebox(lua_State *L, int index)
655 {
656         NodeBox nodebox;
657         if(lua_istable(L, -1)){
658                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
659                                 es_NodeBoxType, NODEBOX_REGULAR);
660
661                 lua_getfield(L, index, "fixed");
662                 if(lua_istable(L, -1))
663                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
664                 lua_pop(L, 1);
665
666                 lua_getfield(L, index, "wall_top");
667                 if(lua_istable(L, -1))
668                         nodebox.wall_top = read_aabb3f(L, -1, BS);
669                 lua_pop(L, 1);
670
671                 lua_getfield(L, index, "wall_bottom");
672                 if(lua_istable(L, -1))
673                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
674                 lua_pop(L, 1);
675
676                 lua_getfield(L, index, "wall_side");
677                 if(lua_istable(L, -1))
678                         nodebox.wall_side = read_aabb3f(L, -1, BS);
679                 lua_pop(L, 1);
680         }
681         return nodebox;
682 }
683
684 /*
685         Groups
686 */
687 static void read_groups(lua_State *L, int index,
688                 std::map<std::string, int> &result)
689 {
690         if (!lua_istable(L,index))
691                 return;
692         result.clear();
693         lua_pushnil(L);
694         if(index < 0)
695                 index -= 1;
696         while(lua_next(L, index) != 0){
697                 // key at index -2 and value at index -1
698                 std::string name = luaL_checkstring(L, -2);
699                 int rating = luaL_checkinteger(L, -1);
700                 result[name] = rating;
701                 // removes value, keeps key for next iteration
702                 lua_pop(L, 1);
703         }
704 }
705
706 /*
707         Privileges
708 */
709 static void read_privileges(lua_State *L, int index,
710                 std::set<std::string> &result)
711 {
712         result.clear();
713         lua_pushnil(L);
714         if(index < 0)
715                 index -= 1;
716         while(lua_next(L, index) != 0){
717                 // key at index -2 and value at index -1
718                 std::string key = luaL_checkstring(L, -2);
719                 bool value = lua_toboolean(L, -1);
720                 if(value)
721                         result.insert(key);
722                 // removes value, keeps key for next iteration
723                 lua_pop(L, 1);
724         }
725 }
726
727 /*
728         ToolCapabilities
729 */
730
731 static ToolCapabilities read_tool_capabilities(
732                 lua_State *L, int table)
733 {
734         ToolCapabilities toolcap;
735         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
736         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
737         lua_getfield(L, table, "groupcaps");
738         if(lua_istable(L, -1)){
739                 int table_groupcaps = lua_gettop(L);
740                 lua_pushnil(L);
741                 while(lua_next(L, table_groupcaps) != 0){
742                         // key at index -2 and value at index -1
743                         std::string groupname = luaL_checkstring(L, -2);
744                         if(lua_istable(L, -1)){
745                                 int table_groupcap = lua_gettop(L);
746                                 // This will be created
747                                 ToolGroupCap groupcap;
748                                 // Read simple parameters
749                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
750                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
751                                 // DEPRECATED: maxwear
752                                 float maxwear = 0;
753                                 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
754                                         if(maxwear != 0)
755                                                 groupcap.uses = 1.0/maxwear;
756                                         else
757                                                 groupcap.uses = 0;
758                                         infostream<<script_get_backtrace(L)<<std::endl;
759                                         infostream<<"WARNING: field \"maxwear\" is deprecated; "
760                                                         <<"should replace with uses=1/maxwear"<<std::endl;
761                                 }
762                                 // Read "times" table
763                                 lua_getfield(L, table_groupcap, "times");
764                                 if(lua_istable(L, -1)){
765                                         int table_times = lua_gettop(L);
766                                         lua_pushnil(L);
767                                         while(lua_next(L, table_times) != 0){
768                                                 // key at index -2 and value at index -1
769                                                 int rating = luaL_checkinteger(L, -2);
770                                                 float time = luaL_checknumber(L, -1);
771                                                 groupcap.times[rating] = time;
772                                                 // removes value, keeps key for next iteration
773                                                 lua_pop(L, 1);
774                                         }
775                                 }
776                                 lua_pop(L, 1);
777                                 // Insert groupcap into toolcap
778                                 toolcap.groupcaps[groupname] = groupcap;
779                         }
780                         // removes value, keeps key for next iteration
781                         lua_pop(L, 1);
782                 }
783         }
784         lua_pop(L, 1);
785         return toolcap;
786 }
787
788 static void set_tool_capabilities(lua_State *L, int table,
789                 const ToolCapabilities &toolcap)
790 {
791         setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
792         setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
793         // Create groupcaps table
794         lua_newtable(L);
795         // For each groupcap
796         for(std::map<std::string, ToolGroupCap>::const_iterator
797                         i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
798                 // Create groupcap table
799                 lua_newtable(L);
800                 const std::string &name = i->first;
801                 const ToolGroupCap &groupcap = i->second;
802                 // Create subtable "times"
803                 lua_newtable(L);
804                 for(std::map<int, float>::const_iterator
805                                 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
806                         int rating = i->first;
807                         float time = i->second;
808                         lua_pushinteger(L, rating);
809                         lua_pushnumber(L, time);
810                         lua_settable(L, -3);
811                 }
812                 // Set subtable "times"
813                 lua_setfield(L, -2, "times");
814                 // Set simple parameters
815                 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
816                 setintfield(L, -1, "uses", groupcap.uses);
817                 // Insert groupcap table into groupcaps table
818                 lua_setfield(L, -2, name.c_str());
819         }
820         // Set groupcaps table
821         lua_setfield(L, -2, "groupcaps");
822 }
823
824 static void push_tool_capabilities(lua_State *L,
825                 const ToolCapabilities &prop)
826 {
827         lua_newtable(L);
828         set_tool_capabilities(L, -1, prop);
829 }
830
831 /*
832         DigParams
833 */
834
835 static void set_dig_params(lua_State *L, int table,
836                 const DigParams &params)
837 {
838         setboolfield(L, table, "diggable", params.diggable);
839         setfloatfield(L, table, "time", params.time);
840         setintfield(L, table, "wear", params.wear);
841 }
842
843 static void push_dig_params(lua_State *L,
844                 const DigParams &params)
845 {
846         lua_newtable(L);
847         set_dig_params(L, -1, params);
848 }
849
850 /*
851         HitParams
852 */
853
854 static void set_hit_params(lua_State *L, int table,
855                 const HitParams &params)
856 {
857         setintfield(L, table, "hp", params.hp);
858         setintfield(L, table, "wear", params.wear);
859 }
860
861 static void push_hit_params(lua_State *L,
862                 const HitParams &params)
863 {
864         lua_newtable(L);
865         set_hit_params(L, -1, params);
866 }
867
868 /*
869         PointedThing
870 */
871
872 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
873 {
874         lua_newtable(L);
875         if(pointed.type == POINTEDTHING_NODE)
876         {
877                 lua_pushstring(L, "node");
878                 lua_setfield(L, -2, "type");
879                 push_v3s16(L, pointed.node_undersurface);
880                 lua_setfield(L, -2, "under");
881                 push_v3s16(L, pointed.node_abovesurface);
882                 lua_setfield(L, -2, "above");
883         }
884         else if(pointed.type == POINTEDTHING_OBJECT)
885         {
886                 lua_pushstring(L, "object");
887                 lua_setfield(L, -2, "type");
888                 objectref_get(L, pointed.object_id);
889                 lua_setfield(L, -2, "ref");
890         }
891         else
892         {
893                 lua_pushstring(L, "nothing");
894                 lua_setfield(L, -2, "type");
895         }
896 }
897
898 /*
899         SimpleSoundSpec
900 */
901
902 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
903 {
904         if(index < 0)
905                 index = lua_gettop(L) + 1 + index;
906         if(lua_isnil(L, index)){
907         } else if(lua_istable(L, index)){
908                 getstringfield(L, index, "name", spec.name);
909                 getfloatfield(L, index, "gain", spec.gain);
910         } else if(lua_isstring(L, index)){
911                 spec.name = lua_tostring(L, index);
912         }
913 }
914
915 /*
916         ObjectProperties
917 */
918
919 static void read_object_properties(lua_State *L, int index,
920                 ObjectProperties *prop)
921 {
922         if(index < 0)
923                 index = lua_gettop(L) + 1 + index;
924         if(!lua_istable(L, index))
925                 return;
926
927         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
928
929         getboolfield(L, -1, "physical", prop->physical);
930
931         getfloatfield(L, -1, "weight", prop->weight);
932
933         lua_getfield(L, -1, "collisionbox");
934         if(lua_istable(L, -1))
935                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
936         lua_pop(L, 1);
937
938         getstringfield(L, -1, "visual", prop->visual);
939         
940         lua_getfield(L, -1, "visual_size");
941         if(lua_istable(L, -1))
942                 prop->visual_size = read_v2f(L, -1);
943         lua_pop(L, 1);
944
945         lua_getfield(L, -1, "textures");
946         if(lua_istable(L, -1)){
947                 prop->textures.clear();
948                 int table = lua_gettop(L);
949                 lua_pushnil(L);
950                 while(lua_next(L, table) != 0){
951                         // key at index -2 and value at index -1
952                         if(lua_isstring(L, -1))
953                                 prop->textures.push_back(lua_tostring(L, -1));
954                         else
955                                 prop->textures.push_back("");
956                         // removes value, keeps key for next iteration
957                         lua_pop(L, 1);
958                 }
959         }
960         lua_pop(L, 1);
961         
962         lua_getfield(L, -1, "spritediv");
963         if(lua_istable(L, -1))
964                 prop->spritediv = read_v2s16(L, -1);
965         lua_pop(L, 1);
966
967         lua_getfield(L, -1, "initial_sprite_basepos");
968         if(lua_istable(L, -1))
969                 prop->initial_sprite_basepos = read_v2s16(L, -1);
970         lua_pop(L, 1);
971         
972         getboolfield(L, -1, "is_visible", prop->is_visible);
973         getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
974         getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
975 }
976
977 /*
978         ItemDefinition
979 */
980
981 static ItemDefinition read_item_definition(lua_State *L, int index,
982                 ItemDefinition default_def = ItemDefinition())
983 {
984         if(index < 0)
985                 index = lua_gettop(L) + 1 + index;
986
987         // Read the item definition
988         ItemDefinition def = default_def;
989
990         def.type = (ItemType)getenumfield(L, index, "type",
991                         es_ItemType, ITEM_NONE);
992         getstringfield(L, index, "name", def.name);
993         getstringfield(L, index, "description", def.description);
994         getstringfield(L, index, "inventory_image", def.inventory_image);
995         getstringfield(L, index, "wield_image", def.wield_image);
996
997         lua_getfield(L, index, "wield_scale");
998         if(lua_istable(L, -1)){
999                 def.wield_scale = check_v3f(L, -1);
1000         }
1001         lua_pop(L, 1);
1002
1003         def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1004         if(def.stack_max == 0)
1005                 def.stack_max = 1;
1006
1007         lua_getfield(L, index, "on_use");
1008         def.usable = lua_isfunction(L, -1);
1009         lua_pop(L, 1);
1010
1011         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1012
1013         warn_if_field_exists(L, index, "tool_digging_properties",
1014                         "deprecated: use tool_capabilities");
1015         
1016         lua_getfield(L, index, "tool_capabilities");
1017         if(lua_istable(L, -1)){
1018                 def.tool_capabilities = new ToolCapabilities(
1019                                 read_tool_capabilities(L, -1));
1020         }
1021
1022         // If name is "" (hand), ensure there are ToolCapabilities
1023         // because it will be looked up there whenever any other item has
1024         // no ToolCapabilities
1025         if(def.name == "" && def.tool_capabilities == NULL){
1026                 def.tool_capabilities = new ToolCapabilities();
1027         }
1028
1029         lua_getfield(L, index, "groups");
1030         read_groups(L, -1, def.groups);
1031         lua_pop(L, 1);
1032
1033         // Client shall immediately place this node when player places the item.
1034         // Server will update the precise end result a moment later.
1035         // "" = no prediction
1036         getstringfield(L, index, "node_placement_prediction",
1037                         def.node_placement_prediction);
1038
1039         return def;
1040 }
1041
1042 /*
1043         TileDef
1044 */
1045
1046 static TileDef read_tiledef(lua_State *L, int index)
1047 {
1048         if(index < 0)
1049                 index = lua_gettop(L) + 1 + index;
1050         
1051         TileDef tiledef;
1052
1053         // key at index -2 and value at index
1054         if(lua_isstring(L, index)){
1055                 // "default_lava.png"
1056                 tiledef.name = lua_tostring(L, index);
1057         }
1058         else if(lua_istable(L, index))
1059         {
1060                 // {name="default_lava.png", animation={}}
1061                 tiledef.name = "";
1062                 getstringfield(L, index, "name", tiledef.name);
1063                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1064                 tiledef.backface_culling = getboolfield_default(
1065                                         L, index, "backface_culling", true);
1066                 // animation = {}
1067                 lua_getfield(L, index, "animation");
1068                 if(lua_istable(L, -1)){
1069                         // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1070                         tiledef.animation.type = (TileAnimationType)
1071                                         getenumfield(L, -1, "type", es_TileAnimationType,
1072                                         TAT_NONE);
1073                         tiledef.animation.aspect_w =
1074                                         getintfield_default(L, -1, "aspect_w", 16);
1075                         tiledef.animation.aspect_h =
1076                                         getintfield_default(L, -1, "aspect_h", 16);
1077                         tiledef.animation.length =
1078                                         getfloatfield_default(L, -1, "length", 1.0);
1079                 }
1080                 lua_pop(L, 1);
1081         }
1082
1083         return tiledef;
1084 }
1085
1086 /*
1087         ContentFeatures
1088 */
1089
1090 static ContentFeatures read_content_features(lua_State *L, int index)
1091 {
1092         if(index < 0)
1093                 index = lua_gettop(L) + 1 + index;
1094
1095         ContentFeatures f;
1096         
1097         /* Cache existence of some callbacks */
1098         lua_getfield(L, index, "on_construct");
1099         if(!lua_isnil(L, -1)) f.has_on_construct = true;
1100         lua_pop(L, 1);
1101         lua_getfield(L, index, "on_destruct");
1102         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1103         lua_pop(L, 1);
1104         lua_getfield(L, index, "after_destruct");
1105         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1106         lua_pop(L, 1);
1107
1108         /* Name */
1109         getstringfield(L, index, "name", f.name);
1110
1111         /* Groups */
1112         lua_getfield(L, index, "groups");
1113         read_groups(L, -1, f.groups);
1114         lua_pop(L, 1);
1115
1116         /* Visual definition */
1117
1118         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1119                         NDT_NORMAL);
1120         getfloatfield(L, index, "visual_scale", f.visual_scale);
1121         
1122         // tiles = {}
1123         lua_getfield(L, index, "tiles");
1124         // If nil, try the deprecated name "tile_images" instead
1125         if(lua_isnil(L, -1)){
1126                 lua_pop(L, 1);
1127                 warn_if_field_exists(L, index, "tile_images",
1128                                 "Deprecated; new name is \"tiles\".");
1129                 lua_getfield(L, index, "tile_images");
1130         }
1131         if(lua_istable(L, -1)){
1132                 int table = lua_gettop(L);
1133                 lua_pushnil(L);
1134                 int i = 0;
1135                 while(lua_next(L, table) != 0){
1136                         // Read tiledef from value
1137                         f.tiledef[i] = read_tiledef(L, -1);
1138                         // removes value, keeps key for next iteration
1139                         lua_pop(L, 1);
1140                         i++;
1141                         if(i==6){
1142                                 lua_pop(L, 1);
1143                                 break;
1144                         }
1145                 }
1146                 // Copy last value to all remaining textures
1147                 if(i >= 1){
1148                         TileDef lasttile = f.tiledef[i-1];
1149                         while(i < 6){
1150                                 f.tiledef[i] = lasttile;
1151                                 i++;
1152                         }
1153                 }
1154         }
1155         lua_pop(L, 1);
1156         
1157         // special_tiles = {}
1158         lua_getfield(L, index, "special_tiles");
1159         // If nil, try the deprecated name "special_materials" instead
1160         if(lua_isnil(L, -1)){
1161                 lua_pop(L, 1);
1162                 warn_if_field_exists(L, index, "special_materials",
1163                                 "Deprecated; new name is \"special_tiles\".");
1164                 lua_getfield(L, index, "special_materials");
1165         }
1166         if(lua_istable(L, -1)){
1167                 int table = lua_gettop(L);
1168                 lua_pushnil(L);
1169                 int i = 0;
1170                 while(lua_next(L, table) != 0){
1171                         // Read tiledef from value
1172                         f.tiledef_special[i] = read_tiledef(L, -1);
1173                         // removes value, keeps key for next iteration
1174                         lua_pop(L, 1);
1175                         i++;
1176                         if(i==6){
1177                                 lua_pop(L, 1);
1178                                 break;
1179                         }
1180                 }
1181         }
1182         lua_pop(L, 1);
1183
1184         f.alpha = getintfield_default(L, index, "alpha", 255);
1185
1186         /* Other stuff */
1187         
1188         lua_getfield(L, index, "post_effect_color");
1189         if(!lua_isnil(L, -1))
1190                 f.post_effect_color = readARGB8(L, -1);
1191         lua_pop(L, 1);
1192
1193         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1194                         es_ContentParamType, CPT_NONE);
1195         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1196                         es_ContentParamType2, CPT2_NONE);
1197
1198         // Warn about some deprecated fields
1199         warn_if_field_exists(L, index, "wall_mounted",
1200                         "deprecated: use paramtype2 = 'wallmounted'");
1201         warn_if_field_exists(L, index, "light_propagates",
1202                         "deprecated: determined from paramtype");
1203         warn_if_field_exists(L, index, "dug_item",
1204                         "deprecated: use 'drop' field");
1205         warn_if_field_exists(L, index, "extra_dug_item",
1206                         "deprecated: use 'drop' field");
1207         warn_if_field_exists(L, index, "extra_dug_item_rarity",
1208                         "deprecated: use 'drop' field");
1209         warn_if_field_exists(L, index, "metadata_name",
1210                         "deprecated: use on_add and metadata callbacks");
1211         
1212         // True for all ground-like things like stone and mud, false for eg. trees
1213         getboolfield(L, index, "is_ground_content", f.is_ground_content);
1214         f.light_propagates = (f.param_type == CPT_LIGHT);
1215         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1216         // This is used for collision detection.
1217         // Also for general solidness queries.
1218         getboolfield(L, index, "walkable", f.walkable);
1219         // Player can point to these
1220         getboolfield(L, index, "pointable", f.pointable);
1221         // Player can dig these
1222         getboolfield(L, index, "diggable", f.diggable);
1223         // Player can climb these
1224         getboolfield(L, index, "climbable", f.climbable);
1225         // Player can build on these
1226         getboolfield(L, index, "buildable_to", f.buildable_to);
1227         // Whether the node is non-liquid, source liquid or flowing liquid
1228         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1229                         es_LiquidType, LIQUID_NONE);
1230         // If the content is liquid, this is the flowing version of the liquid.
1231         getstringfield(L, index, "liquid_alternative_flowing",
1232                         f.liquid_alternative_flowing);
1233         // If the content is liquid, this is the source version of the liquid.
1234         getstringfield(L, index, "liquid_alternative_source",
1235                         f.liquid_alternative_source);
1236         // Viscosity for fluid flow, ranging from 1 to 7, with
1237         // 1 giving almost instantaneous propagation and 7 being
1238         // the slowest possible
1239         f.liquid_viscosity = getintfield_default(L, index,
1240                         "liquid_viscosity", f.liquid_viscosity);
1241         // Amount of light the node emits
1242         f.light_source = getintfield_default(L, index,
1243                         "light_source", f.light_source);
1244         f.damage_per_second = getintfield_default(L, index,
1245                         "damage_per_second", f.damage_per_second);
1246         
1247         lua_getfield(L, index, "node_box");
1248         if(lua_istable(L, -1))
1249                 f.node_box = read_nodebox(L, -1);
1250         lua_pop(L, 1);
1251
1252         lua_getfield(L, index, "selection_box");
1253         if(lua_istable(L, -1))
1254                 f.selection_box = read_nodebox(L, -1);
1255         lua_pop(L, 1);
1256
1257         // Set to true if paramtype used to be 'facedir_simple'
1258         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1259         // Set to true if wall_mounted used to be set to true
1260         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1261         
1262         // Sound table
1263         lua_getfield(L, index, "sounds");
1264         if(lua_istable(L, -1)){
1265                 lua_getfield(L, -1, "footstep");
1266                 read_soundspec(L, -1, f.sound_footstep);
1267                 lua_pop(L, 1);
1268                 lua_getfield(L, -1, "dig");
1269                 read_soundspec(L, -1, f.sound_dig);
1270                 lua_pop(L, 1);
1271                 lua_getfield(L, -1, "dug");
1272                 read_soundspec(L, -1, f.sound_dug);
1273                 lua_pop(L, 1);
1274         }
1275         lua_pop(L, 1);
1276
1277         return f;
1278 }
1279
1280 /*
1281         Inventory stuff
1282 */
1283
1284 static ItemStack read_item(lua_State *L, int index);
1285 static std::vector<ItemStack> read_items(lua_State *L, int index);
1286 // creates a table of ItemStacks
1287 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1288
1289 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1290                 lua_State *L, int tableindex, int forcesize=-1)
1291 {
1292         if(tableindex < 0)
1293                 tableindex = lua_gettop(L) + 1 + tableindex;
1294         // If nil, delete list
1295         if(lua_isnil(L, tableindex)){
1296                 inv->deleteList(name);
1297                 return;
1298         }
1299         // Otherwise set list
1300         std::vector<ItemStack> items = read_items(L, tableindex);
1301         int listsize = (forcesize != -1) ? forcesize : items.size();
1302         InventoryList *invlist = inv->addList(name, listsize);
1303         int index = 0;
1304         for(std::vector<ItemStack>::const_iterator
1305                         i = items.begin(); i != items.end(); i++){
1306                 if(forcesize != -1 && index == forcesize)
1307                         break;
1308                 invlist->changeItem(index, *i);
1309                 index++;
1310         }
1311         while(forcesize != -1 && index < forcesize){
1312                 invlist->deleteItem(index);
1313                 index++;
1314         }
1315 }
1316
1317 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1318                 lua_State *L)
1319 {
1320         InventoryList *invlist = inv->getList(name);
1321         if(invlist == NULL){
1322                 lua_pushnil(L);
1323                 return;
1324         }
1325         std::vector<ItemStack> items;
1326         for(u32 i=0; i<invlist->getSize(); i++)
1327                 items.push_back(invlist->getItem(i));
1328         push_items(L, items);
1329 }
1330
1331 /*
1332         Helpful macros for userdata classes
1333 */
1334
1335 #define method(class, name) {#name, class::l_##name}
1336
1337 /*
1338         LuaItemStack
1339 */
1340
1341 class LuaItemStack
1342 {
1343 private:
1344         ItemStack m_stack;
1345
1346         static const char className[];
1347         static const luaL_reg methods[];
1348
1349         // Exported functions
1350         
1351         // garbage collector
1352         static int gc_object(lua_State *L)
1353         {
1354                 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1355                 delete o;
1356                 return 0;
1357         }
1358
1359         // is_empty(self) -> true/false
1360         static int l_is_empty(lua_State *L)
1361         {
1362                 LuaItemStack *o = checkobject(L, 1);
1363                 ItemStack &item = o->m_stack;
1364                 lua_pushboolean(L, item.empty());
1365                 return 1;
1366         }
1367
1368         // get_name(self) -> string
1369         static int l_get_name(lua_State *L)
1370         {
1371                 LuaItemStack *o = checkobject(L, 1);
1372                 ItemStack &item = o->m_stack;
1373                 lua_pushstring(L, item.name.c_str());
1374                 return 1;
1375         }
1376
1377         // get_count(self) -> number
1378         static int l_get_count(lua_State *L)
1379         {
1380                 LuaItemStack *o = checkobject(L, 1);
1381                 ItemStack &item = o->m_stack;
1382                 lua_pushinteger(L, item.count);
1383                 return 1;
1384         }
1385
1386         // get_wear(self) -> number
1387         static int l_get_wear(lua_State *L)
1388         {
1389                 LuaItemStack *o = checkobject(L, 1);
1390                 ItemStack &item = o->m_stack;
1391                 lua_pushinteger(L, item.wear);
1392                 return 1;
1393         }
1394
1395         // get_metadata(self) -> string
1396         static int l_get_metadata(lua_State *L)
1397         {
1398                 LuaItemStack *o = checkobject(L, 1);
1399                 ItemStack &item = o->m_stack;
1400                 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1401                 return 1;
1402         }
1403
1404         // clear(self) -> true
1405         static int l_clear(lua_State *L)
1406         {
1407                 LuaItemStack *o = checkobject(L, 1);
1408                 o->m_stack.clear();
1409                 lua_pushboolean(L, true);
1410                 return 1;
1411         }
1412
1413         // replace(self, itemstack or itemstring or table or nil) -> true
1414         static int l_replace(lua_State *L)
1415         {
1416                 LuaItemStack *o = checkobject(L, 1);
1417                 o->m_stack = read_item(L, 2);
1418                 lua_pushboolean(L, true);
1419                 return 1;
1420         }
1421
1422         // to_string(self) -> string
1423         static int l_to_string(lua_State *L)
1424         {
1425                 LuaItemStack *o = checkobject(L, 1);
1426                 std::string itemstring = o->m_stack.getItemString();
1427                 lua_pushstring(L, itemstring.c_str());
1428                 return 1;
1429         }
1430
1431         // to_table(self) -> table or nil
1432         static int l_to_table(lua_State *L)
1433         {
1434                 LuaItemStack *o = checkobject(L, 1);
1435                 const ItemStack &item = o->m_stack;
1436                 if(item.empty())
1437                 {
1438                         lua_pushnil(L);
1439                 }
1440                 else
1441                 {
1442                         lua_newtable(L);
1443                         lua_pushstring(L, item.name.c_str());
1444                         lua_setfield(L, -2, "name");
1445                         lua_pushinteger(L, item.count);
1446                         lua_setfield(L, -2, "count");
1447                         lua_pushinteger(L, item.wear);
1448                         lua_setfield(L, -2, "wear");
1449                         lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1450                         lua_setfield(L, -2, "metadata");
1451                 }
1452                 return 1;
1453         }
1454
1455         // get_stack_max(self) -> number
1456         static int l_get_stack_max(lua_State *L)
1457         {
1458                 LuaItemStack *o = checkobject(L, 1);
1459                 ItemStack &item = o->m_stack;
1460                 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1461                 return 1;
1462         }
1463
1464         // get_free_space(self) -> number
1465         static int l_get_free_space(lua_State *L)
1466         {
1467                 LuaItemStack *o = checkobject(L, 1);
1468                 ItemStack &item = o->m_stack;
1469                 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1470                 return 1;
1471         }
1472
1473         // is_known(self) -> true/false
1474         // Checks if the item is defined.
1475         static int l_is_known(lua_State *L)
1476         {
1477                 LuaItemStack *o = checkobject(L, 1);
1478                 ItemStack &item = o->m_stack;
1479                 bool is_known = item.isKnown(get_server(L)->idef());
1480                 lua_pushboolean(L, is_known);
1481                 return 1;
1482         }
1483
1484         // get_definition(self) -> table
1485         // Returns the item definition table from minetest.registered_items,
1486         // or a fallback one (name="unknown")
1487         static int l_get_definition(lua_State *L)
1488         {
1489                 LuaItemStack *o = checkobject(L, 1);
1490                 ItemStack &item = o->m_stack;
1491
1492                 // Get minetest.registered_items[name]
1493                 lua_getglobal(L, "minetest");
1494                 lua_getfield(L, -1, "registered_items");
1495                 luaL_checktype(L, -1, LUA_TTABLE);
1496                 lua_getfield(L, -1, item.name.c_str());
1497                 if(lua_isnil(L, -1))
1498                 {
1499                         lua_pop(L, 1);
1500                         lua_getfield(L, -1, "unknown");
1501                 }
1502                 return 1;
1503         }
1504
1505         // get_tool_capabilities(self) -> table
1506         // Returns the effective tool digging properties.
1507         // Returns those of the hand ("") if this item has none associated.
1508         static int l_get_tool_capabilities(lua_State *L)
1509         {
1510                 LuaItemStack *o = checkobject(L, 1);
1511                 ItemStack &item = o->m_stack;
1512                 const ToolCapabilities &prop =
1513                         item.getToolCapabilities(get_server(L)->idef());
1514                 push_tool_capabilities(L, prop);
1515                 return 1;
1516         }
1517
1518         // add_wear(self, amount) -> true/false
1519         // The range for "amount" is [0,65535]. Wear is only added if the item
1520         // is a tool. Adding wear might destroy the item.
1521         // Returns true if the item is (or was) a tool.
1522         static int l_add_wear(lua_State *L)
1523         {
1524                 LuaItemStack *o = checkobject(L, 1);
1525                 ItemStack &item = o->m_stack;
1526                 int amount = lua_tointeger(L, 2);
1527                 bool result = item.addWear(amount, get_server(L)->idef());
1528                 lua_pushboolean(L, result);
1529                 return 1;
1530         }
1531
1532         // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1533         // Returns leftover item stack
1534         static int l_add_item(lua_State *L)
1535         {
1536                 LuaItemStack *o = checkobject(L, 1);
1537                 ItemStack &item = o->m_stack;
1538                 ItemStack newitem = read_item(L, 2);
1539                 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1540                 create(L, leftover);
1541                 return 1;
1542         }
1543
1544         // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1545         // First return value is true iff the new item fits fully into the stack
1546         // Second return value is the would-be-left-over item stack
1547         static int l_item_fits(lua_State *L)
1548         {
1549                 LuaItemStack *o = checkobject(L, 1);
1550                 ItemStack &item = o->m_stack;
1551                 ItemStack newitem = read_item(L, 2);
1552                 ItemStack restitem;
1553                 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1554                 lua_pushboolean(L, fits);  // first return value
1555                 create(L, restitem);       // second return value
1556                 return 2;
1557         }
1558
1559         // take_item(self, takecount=1) -> itemstack
1560         static int l_take_item(lua_State *L)
1561         {
1562                 LuaItemStack *o = checkobject(L, 1);
1563                 ItemStack &item = o->m_stack;
1564                 u32 takecount = 1;
1565                 if(!lua_isnone(L, 2))
1566                         takecount = luaL_checkinteger(L, 2);
1567                 ItemStack taken = item.takeItem(takecount);
1568                 create(L, taken);
1569                 return 1;
1570         }
1571
1572         // peek_item(self, peekcount=1) -> itemstack
1573         static int l_peek_item(lua_State *L)
1574         {
1575                 LuaItemStack *o = checkobject(L, 1);
1576                 ItemStack &item = o->m_stack;
1577                 u32 peekcount = 1;
1578                 if(!lua_isnone(L, 2))
1579                         peekcount = lua_tointeger(L, 2);
1580                 ItemStack peekaboo = item.peekItem(peekcount);
1581                 create(L, peekaboo);
1582                 return 1;
1583         }
1584
1585 public:
1586         LuaItemStack(const ItemStack &item):
1587                 m_stack(item)
1588         {
1589         }
1590
1591         ~LuaItemStack()
1592         {
1593         }
1594
1595         const ItemStack& getItem() const
1596         {
1597                 return m_stack;
1598         }
1599         ItemStack& getItem()
1600         {
1601                 return m_stack;
1602         }
1603         
1604         // LuaItemStack(itemstack or itemstring or table or nil)
1605         // Creates an LuaItemStack and leaves it on top of stack
1606         static int create_object(lua_State *L)
1607         {
1608                 ItemStack item = read_item(L, 1);
1609                 LuaItemStack *o = new LuaItemStack(item);
1610                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1611                 luaL_getmetatable(L, className);
1612                 lua_setmetatable(L, -2);
1613                 return 1;
1614         }
1615         // Not callable from Lua
1616         static int create(lua_State *L, const ItemStack &item)
1617         {
1618                 LuaItemStack *o = new LuaItemStack(item);
1619                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1620                 luaL_getmetatable(L, className);
1621                 lua_setmetatable(L, -2);
1622                 return 1;
1623         }
1624
1625         static LuaItemStack* checkobject(lua_State *L, int narg)
1626         {
1627                 luaL_checktype(L, narg, LUA_TUSERDATA);
1628                 void *ud = luaL_checkudata(L, narg, className);
1629                 if(!ud) luaL_typerror(L, narg, className);
1630                 return *(LuaItemStack**)ud;  // unbox pointer
1631         }
1632
1633         static void Register(lua_State *L)
1634         {
1635                 lua_newtable(L);
1636                 int methodtable = lua_gettop(L);
1637                 luaL_newmetatable(L, className);
1638                 int metatable = lua_gettop(L);
1639
1640                 lua_pushliteral(L, "__metatable");
1641                 lua_pushvalue(L, methodtable);
1642                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
1643
1644                 lua_pushliteral(L, "__index");
1645                 lua_pushvalue(L, methodtable);
1646                 lua_settable(L, metatable);
1647
1648                 lua_pushliteral(L, "__gc");
1649                 lua_pushcfunction(L, gc_object);
1650                 lua_settable(L, metatable);
1651
1652                 lua_pop(L, 1);  // drop metatable
1653
1654                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
1655                 lua_pop(L, 1);  // drop methodtable
1656
1657                 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1658                 lua_register(L, className, create_object);
1659         }
1660 };
1661 const char LuaItemStack::className[] = "ItemStack";
1662 const luaL_reg LuaItemStack::methods[] = {
1663         method(LuaItemStack, is_empty),
1664         method(LuaItemStack, get_name),
1665         method(LuaItemStack, get_count),
1666         method(LuaItemStack, get_wear),
1667         method(LuaItemStack, get_metadata),
1668         method(LuaItemStack, clear),
1669         method(LuaItemStack, replace),
1670         method(LuaItemStack, to_string),
1671         method(LuaItemStack, to_table),
1672         method(LuaItemStack, get_stack_max),
1673         method(LuaItemStack, get_free_space),
1674         method(LuaItemStack, is_known),
1675         method(LuaItemStack, get_definition),
1676         method(LuaItemStack, get_tool_capabilities),
1677         method(LuaItemStack, add_wear),
1678         method(LuaItemStack, add_item),
1679         method(LuaItemStack, item_fits),
1680         method(LuaItemStack, take_item),
1681         method(LuaItemStack, peek_item),
1682         {0,0}
1683 };
1684
1685 static ItemStack read_item(lua_State *L, int index)
1686 {
1687         if(index < 0)
1688                 index = lua_gettop(L) + 1 + index;
1689
1690         if(lua_isnil(L, index))
1691         {
1692                 return ItemStack();
1693         }
1694         else if(lua_isuserdata(L, index))
1695         {
1696                 // Convert from LuaItemStack
1697                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1698                 return o->getItem();
1699         }
1700         else if(lua_isstring(L, index))
1701         {
1702                 // Convert from itemstring
1703                 std::string itemstring = lua_tostring(L, index);
1704                 IItemDefManager *idef = get_server(L)->idef();
1705                 try
1706                 {
1707                         ItemStack item;
1708                         item.deSerialize(itemstring, idef);
1709                         return item;
1710                 }
1711                 catch(SerializationError &e)
1712                 {
1713                         infostream<<"WARNING: unable to create item from itemstring"
1714                                         <<": "<<itemstring<<std::endl;
1715                         return ItemStack();
1716                 }
1717         }
1718         else if(lua_istable(L, index))
1719         {
1720                 // Convert from table
1721                 IItemDefManager *idef = get_server(L)->idef();
1722                 std::string name = getstringfield_default(L, index, "name", "");
1723                 int count = getintfield_default(L, index, "count", 1);
1724                 int wear = getintfield_default(L, index, "wear", 0);
1725                 std::string metadata = getstringfield_default(L, index, "metadata", "");
1726                 return ItemStack(name, count, wear, metadata, idef);
1727         }
1728         else
1729         {
1730                 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1731         }
1732 }
1733
1734 static std::vector<ItemStack> read_items(lua_State *L, int index)
1735 {
1736         if(index < 0)
1737                 index = lua_gettop(L) + 1 + index;
1738
1739         std::vector<ItemStack> items;
1740         luaL_checktype(L, index, LUA_TTABLE);
1741         lua_pushnil(L);
1742         while(lua_next(L, index) != 0){
1743                 // key at index -2 and value at index -1
1744                 items.push_back(read_item(L, -1));
1745                 // removes value, keeps key for next iteration
1746                 lua_pop(L, 1);
1747         }
1748         return items;
1749 }
1750
1751 // creates a table of ItemStacks
1752 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1753 {
1754         // Get the table insert function
1755         lua_getglobal(L, "table");
1756         lua_getfield(L, -1, "insert");
1757         int table_insert = lua_gettop(L);
1758         // Create and fill table
1759         lua_newtable(L);
1760         int table = lua_gettop(L);
1761         for(u32 i=0; i<items.size(); i++){
1762                 ItemStack item = items[i];
1763                 lua_pushvalue(L, table_insert);
1764                 lua_pushvalue(L, table);
1765                 LuaItemStack::create(L, item);
1766                 if(lua_pcall(L, 2, 0, 0))
1767                         script_error(L, "error: %s", lua_tostring(L, -1));
1768         }
1769         lua_remove(L, -2); // Remove table
1770         lua_remove(L, -2); // Remove insert
1771 }
1772
1773 /*
1774         InvRef
1775 */
1776
1777 class InvRef
1778 {
1779 private:
1780         InventoryLocation m_loc;
1781
1782         static const char className[];
1783         static const luaL_reg methods[];
1784
1785         static InvRef *checkobject(lua_State *L, int narg)
1786         {
1787                 luaL_checktype(L, narg, LUA_TUSERDATA);
1788                 void *ud = luaL_checkudata(L, narg, className);
1789                 if(!ud) luaL_typerror(L, narg, className);
1790                 return *(InvRef**)ud;  // unbox pointer
1791         }
1792         
1793         static Inventory* getinv(lua_State *L, InvRef *ref)
1794         {
1795                 return get_server(L)->getInventory(ref->m_loc);
1796         }
1797
1798         static InventoryList* getlist(lua_State *L, InvRef *ref,
1799                         const char *listname)
1800         {
1801                 Inventory *inv = getinv(L, ref);
1802                 if(!inv)
1803                         return NULL;
1804                 return inv->getList(listname);
1805         }
1806
1807         static void reportInventoryChange(lua_State *L, InvRef *ref)
1808         {
1809                 // Inform other things that the inventory has changed
1810                 get_server(L)->setInventoryModified(ref->m_loc);
1811         }
1812         
1813         // Exported functions
1814         
1815         // garbage collector
1816         static int gc_object(lua_State *L) {
1817                 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1818                 delete o;
1819                 return 0;
1820         }
1821
1822         // is_empty(self, listname) -> true/false
1823         static int l_is_empty(lua_State *L)
1824         {
1825                 InvRef *ref = checkobject(L, 1);
1826                 const char *listname = luaL_checkstring(L, 2);
1827                 InventoryList *list = getlist(L, ref, listname);
1828                 if(list && list->getUsedSlots() > 0){
1829                         lua_pushboolean(L, false);
1830                 } else {
1831                         lua_pushboolean(L, true);
1832                 }
1833                 return 1;
1834         }
1835
1836         // get_size(self, listname)
1837         static int l_get_size(lua_State *L)
1838         {
1839                 InvRef *ref = checkobject(L, 1);
1840                 const char *listname = luaL_checkstring(L, 2);
1841                 InventoryList *list = getlist(L, ref, listname);
1842                 if(list){
1843                         lua_pushinteger(L, list->getSize());
1844                 } else {
1845                         lua_pushinteger(L, 0);
1846                 }
1847                 return 1;
1848         }
1849
1850         // get_width(self, listname)
1851         static int l_get_width(lua_State *L)
1852         {
1853                 InvRef *ref = checkobject(L, 1);
1854                 const char *listname = luaL_checkstring(L, 2);
1855                 InventoryList *list = getlist(L, ref, listname);
1856                 if(list){
1857                         lua_pushinteger(L, list->getWidth());
1858                 } else {
1859                         lua_pushinteger(L, 0);
1860                 }
1861                 return 1;
1862         }
1863
1864         // set_size(self, listname, size)
1865         static int l_set_size(lua_State *L)
1866         {
1867                 InvRef *ref = checkobject(L, 1);
1868                 const char *listname = luaL_checkstring(L, 2);
1869                 int newsize = luaL_checknumber(L, 3);
1870                 Inventory *inv = getinv(L, ref);
1871                 if(newsize == 0){
1872                         inv->deleteList(listname);
1873                         reportInventoryChange(L, ref);
1874                         return 0;
1875                 }
1876                 InventoryList *list = inv->getList(listname);
1877                 if(list){
1878                         list->setSize(newsize);
1879                 } else {
1880                         list = inv->addList(listname, newsize);
1881                 }
1882                 reportInventoryChange(L, ref);
1883                 return 0;
1884         }
1885
1886         // set_width(self, listname, size)
1887         static int l_set_width(lua_State *L)
1888         {
1889                 InvRef *ref = checkobject(L, 1);
1890                 const char *listname = luaL_checkstring(L, 2);
1891                 int newwidth = luaL_checknumber(L, 3);
1892                 Inventory *inv = getinv(L, ref);
1893                 InventoryList *list = inv->getList(listname);
1894                 if(list){
1895                         list->setWidth(newwidth);
1896                 } else {
1897                         return 0;
1898                 }
1899                 reportInventoryChange(L, ref);
1900                 return 0;
1901         }
1902
1903         // get_stack(self, listname, i) -> itemstack
1904         static int l_get_stack(lua_State *L)
1905         {
1906                 InvRef *ref = checkobject(L, 1);
1907                 const char *listname = luaL_checkstring(L, 2);
1908                 int i = luaL_checknumber(L, 3) - 1;
1909                 InventoryList *list = getlist(L, ref, listname);
1910                 ItemStack item;
1911                 if(list != NULL && i >= 0 && i < (int) list->getSize())
1912                         item = list->getItem(i);
1913                 LuaItemStack::create(L, item);
1914                 return 1;
1915         }
1916
1917         // set_stack(self, listname, i, stack) -> true/false
1918         static int l_set_stack(lua_State *L)
1919         {
1920                 InvRef *ref = checkobject(L, 1);
1921                 const char *listname = luaL_checkstring(L, 2);
1922                 int i = luaL_checknumber(L, 3) - 1;
1923                 ItemStack newitem = read_item(L, 4);
1924                 InventoryList *list = getlist(L, ref, listname);
1925                 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1926                         list->changeItem(i, newitem);
1927                         reportInventoryChange(L, ref);
1928                         lua_pushboolean(L, true);
1929                 } else {
1930                         lua_pushboolean(L, false);
1931                 }
1932                 return 1;
1933         }
1934
1935         // get_list(self, listname) -> list or nil
1936         static int l_get_list(lua_State *L)
1937         {
1938                 InvRef *ref = checkobject(L, 1);
1939                 const char *listname = luaL_checkstring(L, 2);
1940                 Inventory *inv = getinv(L, ref);
1941                 inventory_get_list_to_lua(inv, listname, L);
1942                 return 1;
1943         }
1944
1945         // set_list(self, listname, list)
1946         static int l_set_list(lua_State *L)
1947         {
1948                 InvRef *ref = checkobject(L, 1);
1949                 const char *listname = luaL_checkstring(L, 2);
1950                 Inventory *inv = getinv(L, ref);
1951                 InventoryList *list = inv->getList(listname);
1952                 if(list)
1953                         inventory_set_list_from_lua(inv, listname, L, 3,
1954                                         list->getSize());
1955                 else
1956                         inventory_set_list_from_lua(inv, listname, L, 3);
1957                 reportInventoryChange(L, ref);
1958                 return 0;
1959         }
1960
1961         // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1962         // Returns the leftover stack
1963         static int l_add_item(lua_State *L)
1964         {
1965                 InvRef *ref = checkobject(L, 1);
1966                 const char *listname = luaL_checkstring(L, 2);
1967                 ItemStack item = read_item(L, 3);
1968                 InventoryList *list = getlist(L, ref, listname);
1969                 if(list){
1970                         ItemStack leftover = list->addItem(item);
1971                         if(leftover.count != item.count)
1972                                 reportInventoryChange(L, ref);
1973                         LuaItemStack::create(L, leftover);
1974                 } else {
1975                         LuaItemStack::create(L, item);
1976                 }
1977                 return 1;
1978         }
1979
1980         // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1981         // Returns true if the item completely fits into the list
1982         static int l_room_for_item(lua_State *L)
1983         {
1984                 InvRef *ref = checkobject(L, 1);
1985                 const char *listname = luaL_checkstring(L, 2);
1986                 ItemStack item = read_item(L, 3);
1987                 InventoryList *list = getlist(L, ref, listname);
1988                 if(list){
1989                         lua_pushboolean(L, list->roomForItem(item));
1990                 } else {
1991                         lua_pushboolean(L, false);
1992                 }
1993                 return 1;
1994         }
1995
1996         // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1997         // Returns true if the list contains the given count of the given item name
1998         static int l_contains_item(lua_State *L)
1999         {
2000                 InvRef *ref = checkobject(L, 1);
2001                 const char *listname = luaL_checkstring(L, 2);
2002                 ItemStack item = read_item(L, 3);
2003                 InventoryList *list = getlist(L, ref, listname);
2004                 if(list){
2005                         lua_pushboolean(L, list->containsItem(item));
2006                 } else {
2007                         lua_pushboolean(L, false);
2008                 }
2009                 return 1;
2010         }
2011
2012         // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2013         // Returns the items that were actually removed
2014         static int l_remove_item(lua_State *L)
2015         {
2016                 InvRef *ref = checkobject(L, 1);
2017                 const char *listname = luaL_checkstring(L, 2);
2018                 ItemStack item = read_item(L, 3);
2019                 InventoryList *list = getlist(L, ref, listname);
2020                 if(list){
2021                         ItemStack removed = list->removeItem(item);
2022                         if(!removed.empty())
2023                                 reportInventoryChange(L, ref);
2024                         LuaItemStack::create(L, removed);
2025                 } else {
2026                         LuaItemStack::create(L, ItemStack());
2027                 }
2028                 return 1;
2029         }
2030
2031 public:
2032         InvRef(const InventoryLocation &loc):
2033                 m_loc(loc)
2034         {
2035         }
2036
2037         ~InvRef()
2038         {
2039         }
2040
2041         // Creates an InvRef and leaves it on top of stack
2042         // Not callable from Lua; all references are created on the C side.
2043         static void create(lua_State *L, const InventoryLocation &loc)
2044         {
2045                 InvRef *o = new InvRef(loc);
2046                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2047                 luaL_getmetatable(L, className);
2048                 lua_setmetatable(L, -2);
2049         }
2050         static void createPlayer(lua_State *L, Player *player)
2051         {
2052                 InventoryLocation loc;
2053                 loc.setPlayer(player->getName());
2054                 create(L, loc);
2055         }
2056         static void createNodeMeta(lua_State *L, v3s16 p)
2057         {
2058                 InventoryLocation loc;
2059                 loc.setNodeMeta(p);
2060                 create(L, loc);
2061         }
2062
2063         static void Register(lua_State *L)
2064         {
2065                 lua_newtable(L);
2066                 int methodtable = lua_gettop(L);
2067                 luaL_newmetatable(L, className);
2068                 int metatable = lua_gettop(L);
2069
2070                 lua_pushliteral(L, "__metatable");
2071                 lua_pushvalue(L, methodtable);
2072                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2073
2074                 lua_pushliteral(L, "__index");
2075                 lua_pushvalue(L, methodtable);
2076                 lua_settable(L, metatable);
2077
2078                 lua_pushliteral(L, "__gc");
2079                 lua_pushcfunction(L, gc_object);
2080                 lua_settable(L, metatable);
2081
2082                 lua_pop(L, 1);  // drop metatable
2083
2084                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2085                 lua_pop(L, 1);  // drop methodtable
2086
2087                 // Cannot be created from Lua
2088                 //lua_register(L, className, create_object);
2089         }
2090 };
2091 const char InvRef::className[] = "InvRef";
2092 const luaL_reg InvRef::methods[] = {
2093         method(InvRef, is_empty),
2094         method(InvRef, get_size),
2095         method(InvRef, set_size),
2096         method(InvRef, get_width),
2097         method(InvRef, set_width),
2098         method(InvRef, get_stack),
2099         method(InvRef, set_stack),
2100         method(InvRef, get_list),
2101         method(InvRef, set_list),
2102         method(InvRef, add_item),
2103         method(InvRef, room_for_item),
2104         method(InvRef, contains_item),
2105         method(InvRef, remove_item),
2106         {0,0}
2107 };
2108
2109 /*
2110         NodeMetaRef
2111 */
2112
2113 class NodeMetaRef
2114 {
2115 private:
2116         v3s16 m_p;
2117         ServerEnvironment *m_env;
2118
2119         static const char className[];
2120         static const luaL_reg methods[];
2121
2122         static NodeMetaRef *checkobject(lua_State *L, int narg)
2123         {
2124                 luaL_checktype(L, narg, LUA_TUSERDATA);
2125                 void *ud = luaL_checkudata(L, narg, className);
2126                 if(!ud) luaL_typerror(L, narg, className);
2127                 return *(NodeMetaRef**)ud;  // unbox pointer
2128         }
2129         
2130         static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2131         {
2132                 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2133                 if(meta == NULL && auto_create)
2134                 {
2135                         meta = new NodeMetadata(ref->m_env->getGameDef());
2136                         ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2137                 }
2138                 return meta;
2139         }
2140
2141         static void reportMetadataChange(NodeMetaRef *ref)
2142         {
2143                 // NOTE: This same code is in rollback_interface.cpp
2144                 // Inform other things that the metadata has changed
2145                 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2146                 MapEditEvent event;
2147                 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2148                 event.p = blockpos;
2149                 ref->m_env->getMap().dispatchEvent(&event);
2150                 // Set the block to be saved
2151                 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2152                 if(block)
2153                         block->raiseModified(MOD_STATE_WRITE_NEEDED,
2154                                         "NodeMetaRef::reportMetadataChange");
2155         }
2156         
2157         // Exported functions
2158         
2159         // garbage collector
2160         static int gc_object(lua_State *L) {
2161                 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2162                 delete o;
2163                 return 0;
2164         }
2165
2166         // get_string(self, name)
2167         static int l_get_string(lua_State *L)
2168         {
2169                 NodeMetaRef *ref = checkobject(L, 1);
2170                 std::string name = luaL_checkstring(L, 2);
2171
2172                 NodeMetadata *meta = getmeta(ref, false);
2173                 if(meta == NULL){
2174                         lua_pushlstring(L, "", 0);
2175                         return 1;
2176                 }
2177                 std::string str = meta->getString(name);
2178                 lua_pushlstring(L, str.c_str(), str.size());
2179                 return 1;
2180         }
2181
2182         // set_string(self, name, var)
2183         static int l_set_string(lua_State *L)
2184         {
2185                 NodeMetaRef *ref = checkobject(L, 1);
2186                 std::string name = luaL_checkstring(L, 2);
2187                 size_t len = 0;
2188                 const char *s = lua_tolstring(L, 3, &len);
2189                 std::string str(s, len);
2190
2191                 NodeMetadata *meta = getmeta(ref, !str.empty());
2192                 if(meta == NULL || str == meta->getString(name))
2193                         return 0;
2194                 meta->setString(name, str);
2195                 reportMetadataChange(ref);
2196                 return 0;
2197         }
2198
2199         // get_int(self, name)
2200         static int l_get_int(lua_State *L)
2201         {
2202                 NodeMetaRef *ref = checkobject(L, 1);
2203                 std::string name = lua_tostring(L, 2);
2204
2205                 NodeMetadata *meta = getmeta(ref, false);
2206                 if(meta == NULL){
2207                         lua_pushnumber(L, 0);
2208                         return 1;
2209                 }
2210                 std::string str = meta->getString(name);
2211                 lua_pushnumber(L, stoi(str));
2212                 return 1;
2213         }
2214
2215         // set_int(self, name, var)
2216         static int l_set_int(lua_State *L)
2217         {
2218                 NodeMetaRef *ref = checkobject(L, 1);
2219                 std::string name = lua_tostring(L, 2);
2220                 int a = lua_tointeger(L, 3);
2221                 std::string str = itos(a);
2222
2223                 NodeMetadata *meta = getmeta(ref, true);
2224                 if(meta == NULL || str == meta->getString(name))
2225                         return 0;
2226                 meta->setString(name, str);
2227                 reportMetadataChange(ref);
2228                 return 0;
2229         }
2230
2231         // get_float(self, name)
2232         static int l_get_float(lua_State *L)
2233         {
2234                 NodeMetaRef *ref = checkobject(L, 1);
2235                 std::string name = lua_tostring(L, 2);
2236
2237                 NodeMetadata *meta = getmeta(ref, false);
2238                 if(meta == NULL){
2239                         lua_pushnumber(L, 0);
2240                         return 1;
2241                 }
2242                 std::string str = meta->getString(name);
2243                 lua_pushnumber(L, stof(str));
2244                 return 1;
2245         }
2246
2247         // set_float(self, name, var)
2248         static int l_set_float(lua_State *L)
2249         {
2250                 NodeMetaRef *ref = checkobject(L, 1);
2251                 std::string name = lua_tostring(L, 2);
2252                 float a = lua_tonumber(L, 3);
2253                 std::string str = ftos(a);
2254
2255                 NodeMetadata *meta = getmeta(ref, true);
2256                 if(meta == NULL || str == meta->getString(name))
2257                         return 0;
2258                 meta->setString(name, str);
2259                 reportMetadataChange(ref);
2260                 return 0;
2261         }
2262
2263         // get_inventory(self)
2264         static int l_get_inventory(lua_State *L)
2265         {
2266                 NodeMetaRef *ref = checkobject(L, 1);
2267                 getmeta(ref, true);  // try to ensure the metadata exists
2268                 InvRef::createNodeMeta(L, ref->m_p);
2269                 return 1;
2270         }
2271         
2272         // to_table(self)
2273         static int l_to_table(lua_State *L)
2274         {
2275                 NodeMetaRef *ref = checkobject(L, 1);
2276
2277                 NodeMetadata *meta = getmeta(ref, true);
2278                 if(meta == NULL){
2279                         lua_pushnil(L);
2280                         return 1;
2281                 }
2282                 lua_newtable(L);
2283                 // fields
2284                 lua_newtable(L);
2285                 {
2286                         std::map<std::string, std::string> fields = meta->getStrings();
2287                         for(std::map<std::string, std::string>::const_iterator
2288                                         i = fields.begin(); i != fields.end(); i++){
2289                                 const std::string &name = i->first;
2290                                 const std::string &value = i->second;
2291                                 lua_pushlstring(L, name.c_str(), name.size());
2292                                 lua_pushlstring(L, value.c_str(), value.size());
2293                                 lua_settable(L, -3);
2294                         }
2295                 }
2296                 lua_setfield(L, -2, "fields");
2297                 // inventory
2298                 lua_newtable(L);
2299                 Inventory *inv = meta->getInventory();
2300                 if(inv){
2301                         std::vector<const InventoryList*> lists = inv->getLists();
2302                         for(std::vector<const InventoryList*>::const_iterator
2303                                         i = lists.begin(); i != lists.end(); i++){
2304                                 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2305                                 lua_setfield(L, -2, (*i)->getName().c_str());
2306                         }
2307                 }
2308                 lua_setfield(L, -2, "inventory");
2309                 return 1;
2310         }
2311
2312         // from_table(self, table)
2313         static int l_from_table(lua_State *L)
2314         {
2315                 NodeMetaRef *ref = checkobject(L, 1);
2316                 int base = 2;
2317                 
2318                 if(lua_isnil(L, base)){
2319                         // No metadata
2320                         ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2321                         lua_pushboolean(L, true);
2322                         return 1;
2323                 }
2324
2325                 // Has metadata; clear old one first
2326                 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2327                 // Create new metadata
2328                 NodeMetadata *meta = getmeta(ref, true);
2329                 // Set fields
2330                 lua_getfield(L, base, "fields");
2331                 int fieldstable = lua_gettop(L);
2332                 lua_pushnil(L);
2333                 while(lua_next(L, fieldstable) != 0){
2334                         // key at index -2 and value at index -1
2335                         std::string name = lua_tostring(L, -2);
2336                         size_t cl;
2337                         const char *cs = lua_tolstring(L, -1, &cl);
2338                         std::string value(cs, cl);
2339                         meta->setString(name, value);
2340                         lua_pop(L, 1); // removes value, keeps key for next iteration
2341                 }
2342                 // Set inventory
2343                 Inventory *inv = meta->getInventory();
2344                 lua_getfield(L, base, "inventory");
2345                 int inventorytable = lua_gettop(L);
2346                 lua_pushnil(L);
2347                 while(lua_next(L, inventorytable) != 0){
2348                         // key at index -2 and value at index -1
2349                         std::string name = lua_tostring(L, -2);
2350                         inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2351                         lua_pop(L, 1); // removes value, keeps key for next iteration
2352                 }
2353                 reportMetadataChange(ref);
2354                 lua_pushboolean(L, true);
2355                 return 1;
2356         }
2357
2358 public:
2359         NodeMetaRef(v3s16 p, ServerEnvironment *env):
2360                 m_p(p),
2361                 m_env(env)
2362         {
2363         }
2364
2365         ~NodeMetaRef()
2366         {
2367         }
2368
2369         // Creates an NodeMetaRef and leaves it on top of stack
2370         // Not callable from Lua; all references are created on the C side.
2371         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2372         {
2373                 NodeMetaRef *o = new NodeMetaRef(p, env);
2374                 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2375                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2376                 luaL_getmetatable(L, className);
2377                 lua_setmetatable(L, -2);
2378         }
2379
2380         static void Register(lua_State *L)
2381         {
2382                 lua_newtable(L);
2383                 int methodtable = lua_gettop(L);
2384                 luaL_newmetatable(L, className);
2385                 int metatable = lua_gettop(L);
2386
2387                 lua_pushliteral(L, "__metatable");
2388                 lua_pushvalue(L, methodtable);
2389                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2390
2391                 lua_pushliteral(L, "__index");
2392                 lua_pushvalue(L, methodtable);
2393                 lua_settable(L, metatable);
2394
2395                 lua_pushliteral(L, "__gc");
2396                 lua_pushcfunction(L, gc_object);
2397                 lua_settable(L, metatable);
2398
2399                 lua_pop(L, 1);  // drop metatable
2400
2401                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2402                 lua_pop(L, 1);  // drop methodtable
2403
2404                 // Cannot be created from Lua
2405                 //lua_register(L, className, create_object);
2406         }
2407 };
2408 const char NodeMetaRef::className[] = "NodeMetaRef";
2409 const luaL_reg NodeMetaRef::methods[] = {
2410         method(NodeMetaRef, get_string),
2411         method(NodeMetaRef, set_string),
2412         method(NodeMetaRef, get_int),
2413         method(NodeMetaRef, set_int),
2414         method(NodeMetaRef, get_float),
2415         method(NodeMetaRef, set_float),
2416         method(NodeMetaRef, get_inventory),
2417         method(NodeMetaRef, to_table),
2418         method(NodeMetaRef, from_table),
2419         {0,0}
2420 };
2421
2422 /*
2423         ObjectRef
2424 */
2425
2426 class ObjectRef
2427 {
2428 private:
2429         ServerActiveObject *m_object;
2430
2431         static const char className[];
2432         static const luaL_reg methods[];
2433 public:
2434         static ObjectRef *checkobject(lua_State *L, int narg)
2435         {
2436                 luaL_checktype(L, narg, LUA_TUSERDATA);
2437                 void *ud = luaL_checkudata(L, narg, className);
2438                 if(!ud) luaL_typerror(L, narg, className);
2439                 return *(ObjectRef**)ud;  // unbox pointer
2440         }
2441         
2442         static ServerActiveObject* getobject(ObjectRef *ref)
2443         {
2444                 ServerActiveObject *co = ref->m_object;
2445                 return co;
2446         }
2447 private:
2448         static LuaEntitySAO* getluaobject(ObjectRef *ref)
2449         {
2450                 ServerActiveObject *obj = getobject(ref);
2451                 if(obj == NULL)
2452                         return NULL;
2453                 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2454                         return NULL;
2455                 return (LuaEntitySAO*)obj;
2456         }
2457         
2458         static PlayerSAO* getplayersao(ObjectRef *ref)
2459         {
2460                 ServerActiveObject *obj = getobject(ref);
2461                 if(obj == NULL)
2462                         return NULL;
2463                 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2464                         return NULL;
2465                 return (PlayerSAO*)obj;
2466         }
2467         
2468         static Player* getplayer(ObjectRef *ref)
2469         {
2470                 PlayerSAO *playersao = getplayersao(ref);
2471                 if(playersao == NULL)
2472                         return NULL;
2473                 return playersao->getPlayer();
2474         }
2475         
2476         // Exported functions
2477         
2478         // garbage collector
2479         static int gc_object(lua_State *L) {
2480                 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2481                 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2482                 delete o;
2483                 return 0;
2484         }
2485
2486         // remove(self)
2487         static int l_remove(lua_State *L)
2488         {
2489                 ObjectRef *ref = checkobject(L, 1);
2490                 ServerActiveObject *co = getobject(ref);
2491                 if(co == NULL) return 0;
2492                 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2493                 co->m_removed = true;
2494                 return 0;
2495         }
2496         
2497         // getpos(self)
2498         // returns: {x=num, y=num, z=num}
2499         static int l_getpos(lua_State *L)
2500         {
2501                 ObjectRef *ref = checkobject(L, 1);
2502                 ServerActiveObject *co = getobject(ref);
2503                 if(co == NULL) return 0;
2504                 v3f pos = co->getBasePosition() / BS;
2505                 lua_newtable(L);
2506                 lua_pushnumber(L, pos.X);
2507                 lua_setfield(L, -2, "x");
2508                 lua_pushnumber(L, pos.Y);
2509                 lua_setfield(L, -2, "y");
2510                 lua_pushnumber(L, pos.Z);
2511                 lua_setfield(L, -2, "z");
2512                 return 1;
2513         }
2514         
2515         // setpos(self, pos)
2516         static int l_setpos(lua_State *L)
2517         {
2518                 ObjectRef *ref = checkobject(L, 1);
2519                 //LuaEntitySAO *co = getluaobject(ref);
2520                 ServerActiveObject *co = getobject(ref);
2521                 if(co == NULL) return 0;
2522                 // pos
2523                 v3f pos = checkFloatPos(L, 2);
2524                 // Do it
2525                 co->setPos(pos);
2526                 return 0;
2527         }
2528         
2529         // moveto(self, pos, continuous=false)
2530         static int l_moveto(lua_State *L)
2531         {
2532                 ObjectRef *ref = checkobject(L, 1);
2533                 //LuaEntitySAO *co = getluaobject(ref);
2534                 ServerActiveObject *co = getobject(ref);
2535                 if(co == NULL) return 0;
2536                 // pos
2537                 v3f pos = checkFloatPos(L, 2);
2538                 // continuous
2539                 bool continuous = lua_toboolean(L, 3);
2540                 // Do it
2541                 co->moveTo(pos, continuous);
2542                 return 0;
2543         }
2544
2545         // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2546         static int l_punch(lua_State *L)
2547         {
2548                 ObjectRef *ref = checkobject(L, 1);
2549                 ObjectRef *puncher_ref = checkobject(L, 2);
2550                 ServerActiveObject *co = getobject(ref);
2551                 ServerActiveObject *puncher = getobject(puncher_ref);
2552                 if(co == NULL) return 0;
2553                 if(puncher == NULL) return 0;
2554                 v3f dir;
2555                 if(lua_type(L, 5) != LUA_TTABLE)
2556                         dir = co->getBasePosition() - puncher->getBasePosition();
2557                 else
2558                         dir = read_v3f(L, 5);
2559                 float time_from_last_punch = 1000000;
2560                 if(lua_isnumber(L, 3))
2561                         time_from_last_punch = lua_tonumber(L, 3);
2562                 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2563                 dir.normalize();
2564                 // Do it
2565                 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2566                 return 0;
2567         }
2568
2569         // right_click(self, clicker); clicker = an another ObjectRef
2570         static int l_right_click(lua_State *L)
2571         {
2572                 ObjectRef *ref = checkobject(L, 1);
2573                 ObjectRef *ref2 = checkobject(L, 2);
2574                 ServerActiveObject *co = getobject(ref);
2575                 ServerActiveObject *co2 = getobject(ref2);
2576                 if(co == NULL) return 0;
2577                 if(co2 == NULL) return 0;
2578                 // Do it
2579                 co->rightClick(co2);
2580                 return 0;
2581         }
2582
2583         // set_hp(self, hp)
2584         // hp = number of hitpoints (2 * number of hearts)
2585         // returns: nil
2586         static int l_set_hp(lua_State *L)
2587         {
2588                 ObjectRef *ref = checkobject(L, 1);
2589                 luaL_checknumber(L, 2);
2590                 ServerActiveObject *co = getobject(ref);
2591                 if(co == NULL) return 0;
2592                 int hp = lua_tonumber(L, 2);
2593                 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2594                                 <<" hp="<<hp<<std::endl;*/
2595                 // Do it
2596                 co->setHP(hp);
2597                 // Return
2598                 return 0;
2599         }
2600
2601         // get_hp(self)
2602         // returns: number of hitpoints (2 * number of hearts)
2603         // 0 if not applicable to this type of object
2604         static int l_get_hp(lua_State *L)
2605         {
2606                 ObjectRef *ref = checkobject(L, 1);
2607                 ServerActiveObject *co = getobject(ref);
2608                 if(co == NULL){
2609                         // Default hp is 1
2610                         lua_pushnumber(L, 1);
2611                         return 1;
2612                 }
2613                 int hp = co->getHP();
2614                 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2615                                 <<" hp="<<hp<<std::endl;*/
2616                 // Return
2617                 lua_pushnumber(L, hp);
2618                 return 1;
2619         }
2620
2621         // get_inventory(self)
2622         static int l_get_inventory(lua_State *L)
2623         {
2624                 ObjectRef *ref = checkobject(L, 1);
2625                 ServerActiveObject *co = getobject(ref);
2626                 if(co == NULL) return 0;
2627                 // Do it
2628                 InventoryLocation loc = co->getInventoryLocation();
2629                 if(get_server(L)->getInventory(loc) != NULL)
2630                         InvRef::create(L, loc);
2631                 else
2632                         lua_pushnil(L); // An object may have no inventory (nil)
2633                 return 1;
2634         }
2635
2636         // get_wield_list(self)
2637         static int l_get_wield_list(lua_State *L)
2638         {
2639                 ObjectRef *ref = checkobject(L, 1);
2640                 ServerActiveObject *co = getobject(ref);
2641                 if(co == NULL) return 0;
2642                 // Do it
2643                 lua_pushstring(L, co->getWieldList().c_str());
2644                 return 1;
2645         }
2646
2647         // get_wield_index(self)
2648         static int l_get_wield_index(lua_State *L)
2649         {
2650                 ObjectRef *ref = checkobject(L, 1);
2651                 ServerActiveObject *co = getobject(ref);
2652                 if(co == NULL) return 0;
2653                 // Do it
2654                 lua_pushinteger(L, co->getWieldIndex() + 1);
2655                 return 1;
2656         }
2657
2658         // get_wielded_item(self)
2659         static int l_get_wielded_item(lua_State *L)
2660         {
2661                 ObjectRef *ref = checkobject(L, 1);
2662                 ServerActiveObject *co = getobject(ref);
2663                 if(co == NULL){
2664                         // Empty ItemStack
2665                         LuaItemStack::create(L, ItemStack());
2666                         return 1;
2667                 }
2668                 // Do it
2669                 LuaItemStack::create(L, co->getWieldedItem());
2670                 return 1;
2671         }
2672
2673         // set_wielded_item(self, itemstack or itemstring or table or nil)
2674         static int l_set_wielded_item(lua_State *L)
2675         {
2676                 ObjectRef *ref = checkobject(L, 1);
2677                 ServerActiveObject *co = getobject(ref);
2678                 if(co == NULL) return 0;
2679                 // Do it
2680                 ItemStack item = read_item(L, 2);
2681                 bool success = co->setWieldedItem(item);
2682                 lua_pushboolean(L, success);
2683                 return 1;
2684         }
2685
2686         // set_armor_groups(self, groups)
2687         static int l_set_armor_groups(lua_State *L)
2688         {
2689                 ObjectRef *ref = checkobject(L, 1);
2690                 ServerActiveObject *co = getobject(ref);
2691                 if(co == NULL) return 0;
2692                 // Do it
2693                 ItemGroupList groups;
2694                 read_groups(L, 2, groups);
2695                 co->setArmorGroups(groups);
2696                 return 0;
2697         }
2698
2699         // set_properties(self, properties)
2700         static int l_set_properties(lua_State *L)
2701         {
2702                 ObjectRef *ref = checkobject(L, 1);
2703                 ServerActiveObject *co = getobject(ref);
2704                 if(co == NULL) return 0;
2705                 ObjectProperties *prop = co->accessObjectProperties();
2706                 if(!prop)
2707                         return 0;
2708                 read_object_properties(L, 2, prop);
2709                 co->notifyObjectPropertiesModified();
2710                 return 0;
2711         }
2712
2713         /* LuaEntitySAO-only */
2714
2715         // setvelocity(self, {x=num, y=num, z=num})
2716         static int l_setvelocity(lua_State *L)
2717         {
2718                 ObjectRef *ref = checkobject(L, 1);
2719                 LuaEntitySAO *co = getluaobject(ref);
2720                 if(co == NULL) return 0;
2721                 v3f pos = checkFloatPos(L, 2);
2722                 // Do it
2723                 co->setVelocity(pos);
2724                 return 0;
2725         }
2726         
2727         // getvelocity(self)
2728         static int l_getvelocity(lua_State *L)
2729         {
2730                 ObjectRef *ref = checkobject(L, 1);
2731                 LuaEntitySAO *co = getluaobject(ref);
2732                 if(co == NULL) return 0;
2733                 // Do it
2734                 v3f v = co->getVelocity();
2735                 pushFloatPos(L, v);
2736                 return 1;
2737         }
2738         
2739         // setacceleration(self, {x=num, y=num, z=num})
2740         static int l_setacceleration(lua_State *L)
2741         {
2742                 ObjectRef *ref = checkobject(L, 1);
2743                 LuaEntitySAO *co = getluaobject(ref);
2744                 if(co == NULL) return 0;
2745                 // pos
2746                 v3f pos = checkFloatPos(L, 2);
2747                 // Do it
2748                 co->setAcceleration(pos);
2749                 return 0;
2750         }
2751         
2752         // getacceleration(self)
2753         static int l_getacceleration(lua_State *L)
2754         {
2755                 ObjectRef *ref = checkobject(L, 1);
2756                 LuaEntitySAO *co = getluaobject(ref);
2757                 if(co == NULL) return 0;
2758                 // Do it
2759                 v3f v = co->getAcceleration();
2760                 pushFloatPos(L, v);
2761                 return 1;
2762         }
2763         
2764         // setyaw(self, radians)
2765         static int l_setyaw(lua_State *L)
2766         {
2767                 ObjectRef *ref = checkobject(L, 1);
2768                 LuaEntitySAO *co = getluaobject(ref);
2769                 if(co == NULL) return 0;
2770                 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2771                 // Do it
2772                 co->setYaw(yaw);
2773                 return 0;
2774         }
2775         
2776         // getyaw(self)
2777         static int l_getyaw(lua_State *L)
2778         {
2779                 ObjectRef *ref = checkobject(L, 1);
2780                 LuaEntitySAO *co = getluaobject(ref);
2781                 if(co == NULL) return 0;
2782                 // Do it
2783                 float yaw = co->getYaw() * core::DEGTORAD;
2784                 lua_pushnumber(L, yaw);
2785                 return 1;
2786         }
2787         
2788         // settexturemod(self, mod)
2789         static int l_settexturemod(lua_State *L)
2790         {
2791                 ObjectRef *ref = checkobject(L, 1);
2792                 LuaEntitySAO *co = getluaobject(ref);
2793                 if(co == NULL) return 0;
2794                 // Do it
2795                 std::string mod = luaL_checkstring(L, 2);
2796                 co->setTextureMod(mod);
2797                 return 0;
2798         }
2799         
2800         // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2801         //           select_horiz_by_yawpitch=false)
2802         static int l_setsprite(lua_State *L)
2803         {
2804                 ObjectRef *ref = checkobject(L, 1);
2805                 LuaEntitySAO *co = getluaobject(ref);
2806                 if(co == NULL) return 0;
2807                 // Do it
2808                 v2s16 p(0,0);
2809                 if(!lua_isnil(L, 2))
2810                         p = read_v2s16(L, 2);
2811                 int num_frames = 1;
2812                 if(!lua_isnil(L, 3))
2813                         num_frames = lua_tonumber(L, 3);
2814                 float framelength = 0.2;
2815                 if(!lua_isnil(L, 4))
2816                         framelength = lua_tonumber(L, 4);
2817                 bool select_horiz_by_yawpitch = false;
2818                 if(!lua_isnil(L, 5))
2819                         select_horiz_by_yawpitch = lua_toboolean(L, 5);
2820                 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2821                 return 0;
2822         }
2823
2824         // DEPRECATED
2825         // get_entity_name(self)
2826         static int l_get_entity_name(lua_State *L)
2827         {
2828                 ObjectRef *ref = checkobject(L, 1);
2829                 LuaEntitySAO *co = getluaobject(ref);
2830                 if(co == NULL) return 0;
2831                 // Do it
2832                 std::string name = co->getName();
2833                 lua_pushstring(L, name.c_str());
2834                 return 1;
2835         }
2836         
2837         // get_luaentity(self)
2838         static int l_get_luaentity(lua_State *L)
2839         {
2840                 ObjectRef *ref = checkobject(L, 1);
2841                 LuaEntitySAO *co = getluaobject(ref);
2842                 if(co == NULL) return 0;
2843                 // Do it
2844                 luaentity_get(L, co->getId());
2845                 return 1;
2846         }
2847         
2848         /* Player-only */
2849
2850         // is_player(self)
2851         static int l_is_player(lua_State *L)
2852         {
2853                 ObjectRef *ref = checkobject(L, 1);
2854                 Player *player = getplayer(ref);
2855                 lua_pushboolean(L, (player != NULL));
2856                 return 1;
2857         }
2858         
2859         // get_player_name(self)
2860         static int l_get_player_name(lua_State *L)
2861         {
2862                 ObjectRef *ref = checkobject(L, 1);
2863                 Player *player = getplayer(ref);
2864                 if(player == NULL){
2865                         lua_pushlstring(L, "", 0);
2866                         return 1;
2867                 }
2868                 // Do it
2869                 lua_pushstring(L, player->getName());
2870                 return 1;
2871         }
2872         
2873         // get_look_dir(self)
2874         static int l_get_look_dir(lua_State *L)
2875         {
2876                 ObjectRef *ref = checkobject(L, 1);
2877                 Player *player = getplayer(ref);
2878                 if(player == NULL) return 0;
2879                 // Do it
2880                 float pitch = player->getRadPitch();
2881                 float yaw = player->getRadYaw();
2882                 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2883                 push_v3f(L, v);
2884                 return 1;
2885         }
2886
2887         // get_look_pitch(self)
2888         static int l_get_look_pitch(lua_State *L)
2889         {
2890                 ObjectRef *ref = checkobject(L, 1);
2891                 Player *player = getplayer(ref);
2892                 if(player == NULL) return 0;
2893                 // Do it
2894                 lua_pushnumber(L, player->getRadPitch());
2895                 return 1;
2896         }
2897
2898         // get_look_yaw(self)
2899         static int l_get_look_yaw(lua_State *L)
2900         {
2901                 ObjectRef *ref = checkobject(L, 1);
2902                 Player *player = getplayer(ref);
2903                 if(player == NULL) return 0;
2904                 // Do it
2905                 lua_pushnumber(L, player->getRadYaw());
2906                 return 1;
2907         }
2908
2909         // set_inventory_formspec(self, formspec)
2910         static int l_set_inventory_formspec(lua_State *L)
2911         {
2912                 ObjectRef *ref = checkobject(L, 1);
2913                 Player *player = getplayer(ref);
2914                 if(player == NULL) return 0;
2915                 std::string formspec = luaL_checkstring(L, 2);
2916
2917                 player->inventory_formspec = formspec;
2918                 get_server(L)->reportInventoryFormspecModified(player->getName());
2919                 lua_pushboolean(L, true);
2920                 return 1;
2921         }
2922
2923         // get_inventory_formspec(self) -> formspec
2924         static int l_get_inventory_formspec(lua_State *L)
2925         {
2926                 ObjectRef *ref = checkobject(L, 1);
2927                 Player *player = getplayer(ref);
2928                 if(player == NULL) return 0;
2929
2930                 std::string formspec = player->inventory_formspec;
2931                 lua_pushlstring(L, formspec.c_str(), formspec.size());
2932                 return 1;
2933         }
2934
2935 public:
2936         ObjectRef(ServerActiveObject *object):
2937                 m_object(object)
2938         {
2939                 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2940         }
2941
2942         ~ObjectRef()
2943         {
2944                 /*if(m_object)
2945                         infostream<<"ObjectRef destructing for id="
2946                                         <<m_object->getId()<<std::endl;
2947                 else
2948                         infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2949         }
2950
2951         // Creates an ObjectRef and leaves it on top of stack
2952         // Not callable from Lua; all references are created on the C side.
2953         static void create(lua_State *L, ServerActiveObject *object)
2954         {
2955                 ObjectRef *o = new ObjectRef(object);
2956                 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2957                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2958                 luaL_getmetatable(L, className);
2959                 lua_setmetatable(L, -2);
2960         }
2961
2962         static void set_null(lua_State *L)
2963         {
2964                 ObjectRef *o = checkobject(L, -1);
2965                 o->m_object = NULL;
2966         }
2967         
2968         static void Register(lua_State *L)
2969         {
2970                 lua_newtable(L);
2971                 int methodtable = lua_gettop(L);
2972                 luaL_newmetatable(L, className);
2973                 int metatable = lua_gettop(L);
2974
2975                 lua_pushliteral(L, "__metatable");
2976                 lua_pushvalue(L, methodtable);
2977                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2978
2979                 lua_pushliteral(L, "__index");
2980                 lua_pushvalue(L, methodtable);
2981                 lua_settable(L, metatable);
2982
2983                 lua_pushliteral(L, "__gc");
2984                 lua_pushcfunction(L, gc_object);
2985                 lua_settable(L, metatable);
2986
2987                 lua_pop(L, 1);  // drop metatable
2988
2989                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2990                 lua_pop(L, 1);  // drop methodtable
2991
2992                 // Cannot be created from Lua
2993                 //lua_register(L, className, create_object);
2994         }
2995 };
2996 const char ObjectRef::className[] = "ObjectRef";
2997 const luaL_reg ObjectRef::methods[] = {
2998         // ServerActiveObject
2999         method(ObjectRef, remove),
3000         method(ObjectRef, getpos),
3001         method(ObjectRef, setpos),
3002         method(ObjectRef, moveto),
3003         method(ObjectRef, punch),
3004         method(ObjectRef, right_click),
3005         method(ObjectRef, set_hp),
3006         method(ObjectRef, get_hp),
3007         method(ObjectRef, get_inventory),
3008         method(ObjectRef, get_wield_list),
3009         method(ObjectRef, get_wield_index),
3010         method(ObjectRef, get_wielded_item),
3011         method(ObjectRef, set_wielded_item),
3012         method(ObjectRef, set_armor_groups),
3013         method(ObjectRef, set_properties),
3014         // LuaEntitySAO-only
3015         method(ObjectRef, setvelocity),
3016         method(ObjectRef, getvelocity),
3017         method(ObjectRef, setacceleration),
3018         method(ObjectRef, getacceleration),
3019         method(ObjectRef, setyaw),
3020         method(ObjectRef, getyaw),
3021         method(ObjectRef, settexturemod),
3022         method(ObjectRef, setsprite),
3023         method(ObjectRef, get_entity_name),
3024         method(ObjectRef, get_luaentity),
3025         // Player-only
3026         method(ObjectRef, is_player),
3027         method(ObjectRef, get_player_name),
3028         method(ObjectRef, get_look_dir),
3029         method(ObjectRef, get_look_pitch),
3030         method(ObjectRef, get_look_yaw),
3031         method(ObjectRef, set_inventory_formspec),
3032         method(ObjectRef, get_inventory_formspec),
3033         {0,0}
3034 };
3035
3036 // Creates a new anonymous reference if cobj=NULL or id=0
3037 static void objectref_get_or_create(lua_State *L,
3038                 ServerActiveObject *cobj)
3039 {
3040         if(cobj == NULL || cobj->getId() == 0){
3041                 ObjectRef::create(L, cobj);
3042         } else {
3043                 objectref_get(L, cobj->getId());
3044         }
3045 }
3046
3047
3048 /*
3049   PerlinNoise
3050  */
3051
3052 class LuaPerlinNoise
3053 {
3054 private:
3055         int seed;
3056         int octaves;
3057         double persistence;
3058         double scale;
3059         static const char className[];
3060         static const luaL_reg methods[];
3061
3062         // Exported functions
3063
3064         // garbage collector
3065         static int gc_object(lua_State *L)
3066         {
3067                 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3068                 delete o;
3069                 return 0;
3070         }
3071
3072         static int l_get2d(lua_State *L)
3073         {
3074                 LuaPerlinNoise *o = checkobject(L, 1);
3075                 v2f pos2d = read_v2f(L,2);
3076                 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3077                 lua_pushnumber(L, val);
3078                 return 1;
3079         }
3080         static int l_get3d(lua_State *L)
3081         {
3082                 LuaPerlinNoise *o = checkobject(L, 1);
3083                 v3f pos3d = read_v3f(L,2);
3084                 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3085                 lua_pushnumber(L, val);
3086                 return 1;
3087         }
3088
3089 public:
3090         LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3091                         double a_scale):
3092                 seed(a_seed),
3093                 octaves(a_octaves),
3094                 persistence(a_persistence),
3095                 scale(a_scale)
3096         {
3097         }
3098
3099         ~LuaPerlinNoise()
3100         {
3101         }
3102
3103         // LuaPerlinNoise(seed, octaves, persistence, scale)
3104         // Creates an LuaPerlinNoise and leaves it on top of stack
3105         static int create_object(lua_State *L)
3106         {
3107                 int seed = luaL_checkint(L, 1);
3108                 int octaves = luaL_checkint(L, 2);
3109                 double persistence = luaL_checknumber(L, 3);
3110                 double scale = luaL_checknumber(L, 4);
3111                 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3112                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3113                 luaL_getmetatable(L, className);
3114                 lua_setmetatable(L, -2);
3115                 return 1;
3116         }
3117
3118         static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3119         {
3120                 luaL_checktype(L, narg, LUA_TUSERDATA);
3121                 void *ud = luaL_checkudata(L, narg, className);
3122                 if(!ud) luaL_typerror(L, narg, className);
3123                 return *(LuaPerlinNoise**)ud;  // unbox pointer
3124         }
3125
3126         static void Register(lua_State *L)
3127         {
3128                 lua_newtable(L);
3129                 int methodtable = lua_gettop(L);
3130                 luaL_newmetatable(L, className);
3131                 int metatable = lua_gettop(L);
3132
3133                 lua_pushliteral(L, "__metatable");
3134                 lua_pushvalue(L, methodtable);
3135                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3136
3137                 lua_pushliteral(L, "__index");
3138                 lua_pushvalue(L, methodtable);
3139                 lua_settable(L, metatable);
3140
3141                 lua_pushliteral(L, "__gc");
3142                 lua_pushcfunction(L, gc_object);
3143                 lua_settable(L, metatable);
3144
3145                 lua_pop(L, 1);  // drop metatable
3146
3147                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3148                 lua_pop(L, 1);  // drop methodtable
3149
3150                 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3151                 lua_register(L, className, create_object);
3152         }
3153 };
3154 const char LuaPerlinNoise::className[] = "PerlinNoise";
3155 const luaL_reg LuaPerlinNoise::methods[] = {
3156         method(LuaPerlinNoise, get2d),
3157         method(LuaPerlinNoise, get3d),
3158         {0,0}
3159 };
3160
3161 /*
3162         NodeTimerRef
3163 */
3164
3165 class NodeTimerRef
3166 {
3167 private:
3168         v3s16 m_p;
3169         ServerEnvironment *m_env;
3170
3171         static const char className[];
3172         static const luaL_reg methods[];
3173
3174         static int gc_object(lua_State *L) {
3175                 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3176                 delete o;
3177                 return 0;
3178         }
3179
3180         static NodeTimerRef *checkobject(lua_State *L, int narg)
3181         {
3182                 luaL_checktype(L, narg, LUA_TUSERDATA);
3183                 void *ud = luaL_checkudata(L, narg, className);
3184                 if(!ud) luaL_typerror(L, narg, className);
3185                 return *(NodeTimerRef**)ud;  // unbox pointer
3186         }
3187         
3188         static int l_set(lua_State *L)
3189         {
3190                 NodeTimerRef *o = checkobject(L, 1);
3191                 ServerEnvironment *env = o->m_env;
3192                 if(env == NULL) return 0;
3193                 f32 t = luaL_checknumber(L,2);
3194                 f32 e = luaL_checknumber(L,3);
3195                 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3196                 return 0;
3197         }
3198         
3199         static int l_start(lua_State *L)
3200         {
3201                 NodeTimerRef *o = checkobject(L, 1);
3202                 ServerEnvironment *env = o->m_env;
3203                 if(env == NULL) return 0;
3204                 f32 t = luaL_checknumber(L,2);
3205                 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3206                 return 0;
3207         }
3208         
3209         static int l_stop(lua_State *L)
3210         {
3211                 NodeTimerRef *o = checkobject(L, 1);
3212                 ServerEnvironment *env = o->m_env;
3213                 if(env == NULL) return 0;
3214                 env->getMap().removeNodeTimer(o->m_p);
3215                 return 0;
3216         }
3217         
3218         static int l_is_started(lua_State *L)
3219         {
3220                 NodeTimerRef *o = checkobject(L, 1);
3221                 ServerEnvironment *env = o->m_env;
3222                 if(env == NULL) return 0;
3223
3224                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3225                 lua_pushboolean(L,(t.timeout != 0));
3226                 return 1;
3227         }
3228         
3229         static int l_get_timeout(lua_State *L)
3230         {
3231                 NodeTimerRef *o = checkobject(L, 1);
3232                 ServerEnvironment *env = o->m_env;
3233                 if(env == NULL) return 0;
3234
3235                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3236                 lua_pushnumber(L,t.timeout);
3237                 return 1;
3238         }
3239         
3240         static int l_get_elapsed(lua_State *L)
3241         {
3242                 NodeTimerRef *o = checkobject(L, 1);
3243                 ServerEnvironment *env = o->m_env;
3244                 if(env == NULL) return 0;
3245
3246                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3247                 lua_pushnumber(L,t.elapsed);
3248                 return 1;
3249         }
3250
3251 public:
3252         NodeTimerRef(v3s16 p, ServerEnvironment *env):
3253                 m_p(p),
3254                 m_env(env)
3255         {
3256         }
3257
3258         ~NodeTimerRef()
3259         {
3260         }
3261
3262         // Creates an NodeTimerRef and leaves it on top of stack
3263         // Not callable from Lua; all references are created on the C side.
3264         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3265         {
3266                 NodeTimerRef *o = new NodeTimerRef(p, env);
3267                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3268                 luaL_getmetatable(L, className);
3269                 lua_setmetatable(L, -2);
3270         }
3271
3272         static void set_null(lua_State *L)
3273         {
3274                 NodeTimerRef *o = checkobject(L, -1);
3275                 o->m_env = NULL;
3276         }
3277         
3278         static void Register(lua_State *L)
3279         {
3280                 lua_newtable(L);
3281                 int methodtable = lua_gettop(L);
3282                 luaL_newmetatable(L, className);
3283                 int metatable = lua_gettop(L);
3284
3285                 lua_pushliteral(L, "__metatable");
3286                 lua_pushvalue(L, methodtable);
3287                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3288
3289                 lua_pushliteral(L, "__index");
3290                 lua_pushvalue(L, methodtable);
3291                 lua_settable(L, metatable);
3292
3293                 lua_pushliteral(L, "__gc");
3294                 lua_pushcfunction(L, gc_object);
3295                 lua_settable(L, metatable);
3296
3297                 lua_pop(L, 1);  // drop metatable
3298
3299                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3300                 lua_pop(L, 1);  // drop methodtable
3301
3302                 // Cannot be created from Lua
3303                 //lua_register(L, className, create_object);
3304         }
3305 };
3306 const char NodeTimerRef::className[] = "NodeTimerRef";
3307 const luaL_reg NodeTimerRef::methods[] = {
3308         method(NodeTimerRef, start),
3309         method(NodeTimerRef, set),
3310         method(NodeTimerRef, stop),
3311         method(NodeTimerRef, is_started),
3312         method(NodeTimerRef, get_timeout),
3313         method(NodeTimerRef, get_elapsed),
3314         {0,0}
3315 };
3316
3317 /*
3318         EnvRef
3319 */
3320
3321 class EnvRef
3322 {
3323 private:
3324         ServerEnvironment *m_env;
3325
3326         static const char className[];
3327         static const luaL_reg methods[];
3328
3329         static int gc_object(lua_State *L) {
3330                 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3331                 delete o;
3332                 return 0;
3333         }
3334
3335         static EnvRef *checkobject(lua_State *L, int narg)
3336         {
3337                 luaL_checktype(L, narg, LUA_TUSERDATA);
3338                 void *ud = luaL_checkudata(L, narg, className);
3339                 if(!ud) luaL_typerror(L, narg, className);
3340                 return *(EnvRef**)ud;  // unbox pointer
3341         }
3342         
3343         // Exported functions
3344
3345         // EnvRef:set_node(pos, node)
3346         // pos = {x=num, y=num, z=num}
3347         static int l_set_node(lua_State *L)
3348         {
3349                 EnvRef *o = checkobject(L, 1);
3350                 ServerEnvironment *env = o->m_env;
3351                 if(env == NULL) return 0;
3352                 INodeDefManager *ndef = env->getGameDef()->ndef();
3353                 // parameters
3354                 v3s16 pos = read_v3s16(L, 2);
3355                 MapNode n = readnode(L, 3, ndef);
3356                 // Do it
3357                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3358                 // Call destructor
3359                 if(ndef->get(n_old).has_on_destruct)
3360                         scriptapi_node_on_destruct(L, pos, n_old);
3361                 // Replace node
3362                 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3363                 if(succeeded){
3364                         // Call post-destructor
3365                         if(ndef->get(n_old).has_after_destruct)
3366                                 scriptapi_node_after_destruct(L, pos, n_old);
3367                         // Call constructor
3368                         if(ndef->get(n).has_on_construct)
3369                                 scriptapi_node_on_construct(L, pos, n);
3370                 }
3371                 lua_pushboolean(L, succeeded);
3372                 return 1;
3373         }
3374
3375         static int l_add_node(lua_State *L)
3376         {
3377                 return l_set_node(L);
3378         }
3379
3380         // EnvRef:remove_node(pos)
3381         // pos = {x=num, y=num, z=num}
3382         static int l_remove_node(lua_State *L)
3383         {
3384                 EnvRef *o = checkobject(L, 1);
3385                 ServerEnvironment *env = o->m_env;
3386                 if(env == NULL) return 0;
3387                 INodeDefManager *ndef = env->getGameDef()->ndef();
3388                 // parameters
3389                 v3s16 pos = read_v3s16(L, 2);
3390                 // Do it
3391                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3392                 // Call destructor
3393                 if(ndef->get(n_old).has_on_destruct)
3394                         scriptapi_node_on_destruct(L, pos, n_old);
3395                 // Replace with air
3396                 // This is slightly optimized compared to addNodeWithEvent(air)
3397                 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3398                 if(succeeded){
3399                         // Call post-destructor
3400                         if(ndef->get(n_old).has_after_destruct)
3401                                 scriptapi_node_after_destruct(L, pos, n_old);
3402                 }
3403                 lua_pushboolean(L, succeeded);
3404                 // Air doesn't require constructor
3405                 return 1;
3406         }
3407
3408         // EnvRef:get_node(pos)
3409         // pos = {x=num, y=num, z=num}
3410         static int l_get_node(lua_State *L)
3411         {
3412                 EnvRef *o = checkobject(L, 1);
3413                 ServerEnvironment *env = o->m_env;
3414                 if(env == NULL) return 0;
3415                 // pos
3416                 v3s16 pos = read_v3s16(L, 2);
3417                 // Do it
3418                 MapNode n = env->getMap().getNodeNoEx(pos);
3419                 // Return node
3420                 pushnode(L, n, env->getGameDef()->ndef());
3421                 return 1;
3422         }
3423
3424         // EnvRef:get_node_or_nil(pos)
3425         // pos = {x=num, y=num, z=num}
3426         static int l_get_node_or_nil(lua_State *L)
3427         {
3428                 EnvRef *o = checkobject(L, 1);
3429                 ServerEnvironment *env = o->m_env;
3430                 if(env == NULL) return 0;
3431                 // pos
3432                 v3s16 pos = read_v3s16(L, 2);
3433                 // Do it
3434                 try{
3435                         MapNode n = env->getMap().getNode(pos);
3436                         // Return node
3437                         pushnode(L, n, env->getGameDef()->ndef());
3438                         return 1;
3439                 } catch(InvalidPositionException &e)
3440                 {
3441                         lua_pushnil(L);
3442                         return 1;
3443                 }
3444         }
3445
3446         // EnvRef:get_node_light(pos, timeofday)
3447         // pos = {x=num, y=num, z=num}
3448         // timeofday: nil = current time, 0 = night, 0.5 = day
3449         static int l_get_node_light(lua_State *L)
3450         {
3451                 EnvRef *o = checkobject(L, 1);
3452                 ServerEnvironment *env = o->m_env;
3453                 if(env == NULL) return 0;
3454                 // Do it
3455                 v3s16 pos = read_v3s16(L, 2);
3456                 u32 time_of_day = env->getTimeOfDay();
3457                 if(lua_isnumber(L, 3))
3458                         time_of_day = 24000.0 * lua_tonumber(L, 3);
3459                 time_of_day %= 24000;
3460                 u32 dnr = time_to_daynight_ratio(time_of_day);
3461                 MapNode n = env->getMap().getNodeNoEx(pos);
3462                 try{
3463                         MapNode n = env->getMap().getNode(pos);
3464                         INodeDefManager *ndef = env->getGameDef()->ndef();
3465                         lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3466                         return 1;
3467                 } catch(InvalidPositionException &e)
3468                 {
3469                         lua_pushnil(L);
3470                         return 1;
3471                 }
3472         }
3473
3474         // EnvRef:place_node(pos, node)
3475         // pos = {x=num, y=num, z=num}
3476         static int l_place_node(lua_State *L)
3477         {
3478                 EnvRef *o = checkobject(L, 1);
3479                 ServerEnvironment *env = o->m_env;
3480                 if(env == NULL) return 0;
3481                 v3s16 pos = read_v3s16(L, 2);
3482                 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3483
3484                 // Don't attempt to load non-loaded area as of now
3485                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3486                 if(n_old.getContent() == CONTENT_IGNORE){
3487                         lua_pushboolean(L, false);
3488                         return 1;
3489                 }
3490                 // Create item to place
3491                 INodeDefManager *ndef = get_server(L)->ndef();
3492                 IItemDefManager *idef = get_server(L)->idef();
3493                 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3494                 // Make pointed position
3495                 PointedThing pointed;
3496                 pointed.type = POINTEDTHING_NODE;
3497                 pointed.node_abovesurface = pos;
3498                 pointed.node_undersurface = pos + v3s16(0,-1,0);
3499                 // Place it with a NULL placer (appears in Lua as a non-functional
3500                 // ObjectRef)
3501                 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3502                 lua_pushboolean(L, success);
3503                 return 1;
3504         }
3505
3506         // EnvRef:dig_node(pos)
3507         // pos = {x=num, y=num, z=num}
3508         static int l_dig_node(lua_State *L)
3509         {
3510                 EnvRef *o = checkobject(L, 1);
3511                 ServerEnvironment *env = o->m_env;
3512                 if(env == NULL) return 0;
3513                 v3s16 pos = read_v3s16(L, 2);
3514
3515                 // Don't attempt to load non-loaded area as of now
3516                 MapNode n = env->getMap().getNodeNoEx(pos);
3517                 if(n.getContent() == CONTENT_IGNORE){
3518                         lua_pushboolean(L, false);
3519                         return 1;
3520                 }
3521                 // Dig it out with a NULL digger (appears in Lua as a
3522                 // non-functional ObjectRef)
3523                 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3524                 lua_pushboolean(L, success);
3525                 return 1;
3526         }
3527
3528         // EnvRef:punch_node(pos)
3529         // pos = {x=num, y=num, z=num}
3530         static int l_punch_node(lua_State *L)
3531         {
3532                 EnvRef *o = checkobject(L, 1);
3533                 ServerEnvironment *env = o->m_env;
3534                 if(env == NULL) return 0;
3535                 v3s16 pos = read_v3s16(L, 2);
3536
3537                 // Don't attempt to load non-loaded area as of now
3538                 MapNode n = env->getMap().getNodeNoEx(pos);
3539                 if(n.getContent() == CONTENT_IGNORE){
3540                         lua_pushboolean(L, false);
3541                         return 1;
3542                 }
3543                 // Punch it with a NULL puncher (appears in Lua as a non-functional
3544                 // ObjectRef)
3545                 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3546                 lua_pushboolean(L, success);
3547                 return 1;
3548         }
3549
3550         // EnvRef:get_meta(pos)
3551         static int l_get_meta(lua_State *L)
3552         {
3553                 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3554                 EnvRef *o = checkobject(L, 1);
3555                 ServerEnvironment *env = o->m_env;
3556                 if(env == NULL) return 0;
3557                 // Do it
3558                 v3s16 p = read_v3s16(L, 2);
3559                 NodeMetaRef::create(L, p, env);
3560                 return 1;
3561         }
3562
3563         // EnvRef:get_node_timer(pos)
3564         static int l_get_node_timer(lua_State *L)
3565         {
3566                 EnvRef *o = checkobject(L, 1);
3567                 ServerEnvironment *env = o->m_env;
3568                 if(env == NULL) return 0;
3569                 // Do it
3570                 v3s16 p = read_v3s16(L, 2);
3571                 NodeTimerRef::create(L, p, env);
3572                 return 1;
3573         }
3574
3575         // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3576         // pos = {x=num, y=num, z=num}
3577         static int l_add_entity(lua_State *L)
3578         {
3579                 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3580                 EnvRef *o = checkobject(L, 1);
3581                 ServerEnvironment *env = o->m_env;
3582                 if(env == NULL) return 0;
3583                 // pos
3584                 v3f pos = checkFloatPos(L, 2);
3585                 // content
3586                 const char *name = luaL_checkstring(L, 3);
3587                 // Do it
3588                 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3589                 int objectid = env->addActiveObject(obj);
3590                 // If failed to add, return nothing (reads as nil)
3591                 if(objectid == 0)
3592                         return 0;
3593                 // Return ObjectRef
3594                 objectref_get_or_create(L, obj);
3595                 return 1;
3596         }
3597
3598         // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3599         // pos = {x=num, y=num, z=num}
3600         static int l_add_item(lua_State *L)
3601         {
3602                 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3603                 EnvRef *o = checkobject(L, 1);
3604                 ServerEnvironment *env = o->m_env;
3605                 if(env == NULL) return 0;
3606                 // pos
3607                 v3f pos = checkFloatPos(L, 2);
3608                 // item
3609                 ItemStack item = read_item(L, 3);
3610                 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3611                         return 0;
3612                 // Use minetest.spawn_item to spawn a __builtin:item
3613                 lua_getglobal(L, "minetest");
3614                 lua_getfield(L, -1, "spawn_item");
3615                 if(lua_isnil(L, -1))
3616                         return 0;
3617                 lua_pushvalue(L, 2);
3618                 lua_pushstring(L, item.getItemString().c_str());
3619                 if(lua_pcall(L, 2, 1, 0))
3620                         script_error(L, "error: %s", lua_tostring(L, -1));
3621                 return 1;
3622                 /*lua_pushvalue(L, 1);
3623                 lua_pushstring(L, "__builtin:item");
3624                 lua_pushstring(L, item.getItemString().c_str());
3625                 return l_add_entity(L);*/
3626                 /*// Do it
3627                 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3628                 int objectid = env->addActiveObject(obj);
3629                 // If failed to add, return nothing (reads as nil)
3630                 if(objectid == 0)
3631                         return 0;
3632                 // Return ObjectRef
3633                 objectref_get_or_create(L, obj);
3634                 return 1;*/
3635         }
3636
3637         // EnvRef:add_rat(pos)
3638         // pos = {x=num, y=num, z=num}
3639         static int l_add_rat(lua_State *L)
3640         {
3641                 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3642                                 <<" Doing nothing."<<std::endl;
3643                 return 0;
3644         }
3645
3646         // EnvRef:add_firefly(pos)
3647         // pos = {x=num, y=num, z=num}
3648         static int l_add_firefly(lua_State *L)
3649         {
3650                 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3651                                 <<" Doing nothing."<<std::endl;
3652                 return 0;
3653         }
3654
3655         // EnvRef:get_player_by_name(name)
3656         static int l_get_player_by_name(lua_State *L)
3657         {
3658                 EnvRef *o = checkobject(L, 1);
3659                 ServerEnvironment *env = o->m_env;
3660                 if(env == NULL) return 0;
3661                 // Do it
3662                 const char *name = luaL_checkstring(L, 2);
3663                 Player *player = env->getPlayer(name);
3664                 if(player == NULL){
3665                         lua_pushnil(L);
3666                         return 1;
3667                 }
3668                 PlayerSAO *sao = player->getPlayerSAO();
3669                 if(sao == NULL){
3670                         lua_pushnil(L);
3671                         return 1;
3672                 }
3673                 // Put player on stack
3674                 objectref_get_or_create(L, sao);
3675                 return 1;
3676         }
3677
3678         // EnvRef:get_objects_inside_radius(pos, radius)
3679         static int l_get_objects_inside_radius(lua_State *L)
3680         {
3681                 // Get the table insert function
3682                 lua_getglobal(L, "table");
3683                 lua_getfield(L, -1, "insert");
3684                 int table_insert = lua_gettop(L);
3685                 // Get environemnt
3686                 EnvRef *o = checkobject(L, 1);
3687                 ServerEnvironment *env = o->m_env;
3688                 if(env == NULL) return 0;
3689                 // Do it
3690                 v3f pos = checkFloatPos(L, 2);
3691                 float radius = luaL_checknumber(L, 3) * BS;
3692                 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3693                 lua_newtable(L);
3694                 int table = lua_gettop(L);
3695                 for(std::set<u16>::const_iterator
3696                                 i = ids.begin(); i != ids.end(); i++){
3697                         ServerActiveObject *obj = env->getActiveObject(*i);
3698                         // Insert object reference into table
3699                         lua_pushvalue(L, table_insert);
3700                         lua_pushvalue(L, table);
3701                         objectref_get_or_create(L, obj);
3702                         if(lua_pcall(L, 2, 0, 0))
3703                                 script_error(L, "error: %s", lua_tostring(L, -1));
3704                 }
3705                 return 1;
3706         }
3707
3708         // EnvRef:set_timeofday(val)
3709         // val = 0...1
3710         static int l_set_timeofday(lua_State *L)
3711         {
3712                 EnvRef *o = checkobject(L, 1);
3713                 ServerEnvironment *env = o->m_env;
3714                 if(env == NULL) return 0;
3715                 // Do it
3716                 float timeofday_f = luaL_checknumber(L, 2);
3717                 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3718                 int timeofday_mh = (int)(timeofday_f * 24000.0);
3719                 // This should be set directly in the environment but currently
3720                 // such changes aren't immediately sent to the clients, so call
3721                 // the server instead.
3722                 //env->setTimeOfDay(timeofday_mh);
3723                 get_server(L)->setTimeOfDay(timeofday_mh);
3724                 return 0;
3725         }
3726
3727         // EnvRef:get_timeofday() -> 0...1
3728         static int l_get_timeofday(lua_State *L)
3729         {
3730                 EnvRef *o = checkobject(L, 1);
3731                 ServerEnvironment *env = o->m_env;
3732                 if(env == NULL) return 0;
3733                 // Do it
3734                 int timeofday_mh = env->getTimeOfDay();
3735                 float timeofday_f = (float)timeofday_mh / 24000.0;
3736                 lua_pushnumber(L, timeofday_f);
3737                 return 1;
3738         }
3739
3740
3741         // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3742         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3743         static int l_find_node_near(lua_State *L)
3744         {
3745                 EnvRef *o = checkobject(L, 1);
3746                 ServerEnvironment *env = o->m_env;
3747                 if(env == NULL) return 0;
3748                 INodeDefManager *ndef = get_server(L)->ndef();
3749                 v3s16 pos = read_v3s16(L, 2);
3750                 int radius = luaL_checkinteger(L, 3);
3751                 std::set<content_t> filter;
3752                 if(lua_istable(L, 4)){
3753                         int table = 4;
3754                         lua_pushnil(L);
3755                         while(lua_next(L, table) != 0){
3756                                 // key at index -2 and value at index -1
3757                                 luaL_checktype(L, -1, LUA_TSTRING);
3758                                 ndef->getIds(lua_tostring(L, -1), filter);
3759                                 // removes value, keeps key for next iteration
3760                                 lua_pop(L, 1);
3761                         }
3762                 } else if(lua_isstring(L, 4)){
3763                         ndef->getIds(lua_tostring(L, 4), filter);
3764                 }
3765
3766                 for(int d=1; d<=radius; d++){
3767                         core::list<v3s16> list;
3768                         getFacePositions(list, d);
3769                         for(core::list<v3s16>::Iterator i = list.begin();
3770                                         i != list.end(); i++){
3771                                 v3s16 p = pos + (*i);
3772                                 content_t c = env->getMap().getNodeNoEx(p).getContent();
3773                                 if(filter.count(c) != 0){
3774                                         push_v3s16(L, p);
3775                                         return 1;
3776                                 }
3777                         }
3778                 }
3779                 return 0;
3780         }
3781
3782         // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3783         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3784         static int l_find_nodes_in_area(lua_State *L)
3785         {
3786                 EnvRef *o = checkobject(L, 1);
3787                 ServerEnvironment *env = o->m_env;
3788                 if(env == NULL) return 0;
3789                 INodeDefManager *ndef = get_server(L)->ndef();
3790                 v3s16 minp = read_v3s16(L, 2);
3791                 v3s16 maxp = read_v3s16(L, 3);
3792                 std::set<content_t> filter;
3793                 if(lua_istable(L, 4)){
3794                         int table = 4;
3795                         lua_pushnil(L);
3796                         while(lua_next(L, table) != 0){
3797                                 // key at index -2 and value at index -1
3798                                 luaL_checktype(L, -1, LUA_TSTRING);
3799                                 ndef->getIds(lua_tostring(L, -1), filter);
3800                                 // removes value, keeps key for next iteration
3801                                 lua_pop(L, 1);
3802                         }
3803                 } else if(lua_isstring(L, 4)){
3804                         ndef->getIds(lua_tostring(L, 4), filter);
3805                 }
3806
3807                 // Get the table insert function
3808                 lua_getglobal(L, "table");
3809                 lua_getfield(L, -1, "insert");
3810                 int table_insert = lua_gettop(L);
3811                 
3812                 lua_newtable(L);
3813                 int table = lua_gettop(L);
3814                 for(s16 x=minp.X; x<=maxp.X; x++)
3815                 for(s16 y=minp.Y; y<=maxp.Y; y++)
3816                 for(s16 z=minp.Z; z<=maxp.Z; z++)
3817                 {
3818                         v3s16 p(x,y,z);
3819                         content_t c = env->getMap().getNodeNoEx(p).getContent();
3820                         if(filter.count(c) != 0){
3821                                 lua_pushvalue(L, table_insert);
3822                                 lua_pushvalue(L, table);
3823                                 push_v3s16(L, p);
3824                                 if(lua_pcall(L, 2, 0, 0))
3825                                         script_error(L, "error: %s", lua_tostring(L, -1));
3826                         }
3827                 }
3828                 return 1;
3829         }
3830
3831         //      EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3832         //  returns world-specific PerlinNoise
3833         static int l_get_perlin(lua_State *L)
3834         {
3835                 EnvRef *o = checkobject(L, 1);
3836                 ServerEnvironment *env = o->m_env;
3837                 if(env == NULL) return 0;
3838
3839                 int seeddiff = luaL_checkint(L, 2);
3840                 int octaves = luaL_checkint(L, 3);
3841                 double persistence = luaL_checknumber(L, 4);
3842                 double scale = luaL_checknumber(L, 5);
3843
3844                 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3845                 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3846                 luaL_getmetatable(L, "PerlinNoise");
3847                 lua_setmetatable(L, -2);
3848                 return 1;
3849         }
3850
3851         // EnvRef:clear_objects()
3852         // clear all objects in the environment
3853         static int l_clear_objects(lua_State *L)
3854         {
3855                 EnvRef *o = checkobject(L, 1);
3856                 o->m_env->clearAllObjects();
3857                 return 0;
3858         }
3859
3860 public:
3861         EnvRef(ServerEnvironment *env):
3862                 m_env(env)
3863         {
3864                 //infostream<<"EnvRef created"<<std::endl;
3865         }
3866
3867         ~EnvRef()
3868         {
3869                 //infostream<<"EnvRef destructing"<<std::endl;
3870         }
3871
3872         // Creates an EnvRef and leaves it on top of stack
3873         // Not callable from Lua; all references are created on the C side.
3874         static void create(lua_State *L, ServerEnvironment *env)
3875         {
3876                 EnvRef *o = new EnvRef(env);
3877                 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3878                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3879                 luaL_getmetatable(L, className);
3880                 lua_setmetatable(L, -2);
3881         }
3882
3883         static void set_null(lua_State *L)
3884         {
3885                 EnvRef *o = checkobject(L, -1);
3886                 o->m_env = NULL;
3887         }
3888         
3889         static void Register(lua_State *L)
3890         {
3891                 lua_newtable(L);
3892                 int methodtable = lua_gettop(L);
3893                 luaL_newmetatable(L, className);
3894                 int metatable = lua_gettop(L);
3895
3896                 lua_pushliteral(L, "__metatable");
3897                 lua_pushvalue(L, methodtable);
3898                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3899
3900                 lua_pushliteral(L, "__index");
3901                 lua_pushvalue(L, methodtable);
3902                 lua_settable(L, metatable);
3903
3904                 lua_pushliteral(L, "__gc");
3905                 lua_pushcfunction(L, gc_object);
3906                 lua_settable(L, metatable);
3907
3908                 lua_pop(L, 1);  // drop metatable
3909
3910                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3911                 lua_pop(L, 1);  // drop methodtable
3912
3913                 // Cannot be created from Lua
3914                 //lua_register(L, className, create_object);
3915         }
3916 };
3917 const char EnvRef::className[] = "EnvRef";
3918 const luaL_reg EnvRef::methods[] = {
3919         method(EnvRef, set_node),
3920         method(EnvRef, add_node),
3921         method(EnvRef, remove_node),
3922         method(EnvRef, get_node),
3923         method(EnvRef, get_node_or_nil),
3924         method(EnvRef, get_node_light),
3925         method(EnvRef, place_node),
3926         method(EnvRef, dig_node),
3927         method(EnvRef, punch_node),
3928         method(EnvRef, add_entity),
3929         method(EnvRef, add_item),
3930         method(EnvRef, add_rat),
3931         method(EnvRef, add_firefly),
3932         method(EnvRef, get_meta),
3933         method(EnvRef, get_node_timer),
3934         method(EnvRef, get_player_by_name),
3935         method(EnvRef, get_objects_inside_radius),
3936         method(EnvRef, set_timeofday),
3937         method(EnvRef, get_timeofday),
3938         method(EnvRef, find_node_near),
3939         method(EnvRef, find_nodes_in_area),
3940         method(EnvRef, get_perlin),
3941         method(EnvRef, clear_objects),
3942         {0,0}
3943 };
3944
3945 /*
3946         LuaPseudoRandom
3947 */
3948
3949
3950 class LuaPseudoRandom
3951 {
3952 private:
3953         PseudoRandom m_pseudo;
3954
3955         static const char className[];
3956         static const luaL_reg methods[];
3957
3958         // Exported functions
3959         
3960         // garbage collector
3961         static int gc_object(lua_State *L)
3962         {
3963                 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3964                 delete o;
3965                 return 0;
3966         }
3967
3968         // next(self, min=0, max=32767) -> get next value
3969         static int l_next(lua_State *L)
3970         {
3971                 LuaPseudoRandom *o = checkobject(L, 1);
3972                 int min = 0;
3973                 int max = 32767;
3974                 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3975                 if(!lua_isnil(L, 2))
3976                         min = luaL_checkinteger(L, 2);
3977                 if(!lua_isnil(L, 3))
3978                         max = luaL_checkinteger(L, 3);
3979                 if(max < min){
3980                         errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
3981                         throw LuaError(L, "PseudoRandom.next(): max < min");
3982                 }
3983                 if(max - min != 32767 && max - min > 32767/5)
3984                         throw LuaError(L, "PseudoRandom.next() max-min is not 32767 and is > 32768/5. This is disallowed due to the bad random distribution the implementation would otherwise make.");
3985                 PseudoRandom &pseudo = o->m_pseudo;
3986                 int val = pseudo.next();
3987                 val = (val % (max-min+1)) + min;
3988                 lua_pushinteger(L, val);
3989                 return 1;
3990         }
3991
3992 public:
3993         LuaPseudoRandom(int seed):
3994                 m_pseudo(seed)
3995         {
3996         }
3997
3998         ~LuaPseudoRandom()
3999         {
4000         }
4001
4002         const PseudoRandom& getItem() const
4003         {
4004                 return m_pseudo;
4005         }
4006         PseudoRandom& getItem()
4007         {
4008                 return m_pseudo;
4009         }
4010         
4011         // LuaPseudoRandom(seed)
4012         // Creates an LuaPseudoRandom and leaves it on top of stack
4013         static int create_object(lua_State *L)
4014         {
4015                 int seed = luaL_checknumber(L, 1);
4016                 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4017                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4018                 luaL_getmetatable(L, className);
4019                 lua_setmetatable(L, -2);
4020                 return 1;
4021         }
4022
4023         static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4024         {
4025                 luaL_checktype(L, narg, LUA_TUSERDATA);
4026                 void *ud = luaL_checkudata(L, narg, className);
4027                 if(!ud) luaL_typerror(L, narg, className);
4028                 return *(LuaPseudoRandom**)ud;  // unbox pointer
4029         }
4030
4031         static void Register(lua_State *L)
4032         {
4033                 lua_newtable(L);
4034                 int methodtable = lua_gettop(L);
4035                 luaL_newmetatable(L, className);
4036                 int metatable = lua_gettop(L);
4037
4038                 lua_pushliteral(L, "__metatable");
4039                 lua_pushvalue(L, methodtable);
4040                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
4041
4042                 lua_pushliteral(L, "__index");
4043                 lua_pushvalue(L, methodtable);
4044                 lua_settable(L, metatable);
4045
4046                 lua_pushliteral(L, "__gc");
4047                 lua_pushcfunction(L, gc_object);
4048                 lua_settable(L, metatable);
4049
4050                 lua_pop(L, 1);  // drop metatable
4051
4052                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
4053                 lua_pop(L, 1);  // drop methodtable
4054
4055                 // Can be created from Lua (LuaPseudoRandom(seed))
4056                 lua_register(L, className, create_object);
4057         }
4058 };
4059 const char LuaPseudoRandom::className[] = "PseudoRandom";
4060 const luaL_reg LuaPseudoRandom::methods[] = {
4061         method(LuaPseudoRandom, next),
4062         {0,0}
4063 };
4064
4065
4066
4067 /*
4068         LuaABM
4069 */
4070
4071 class LuaABM : public ActiveBlockModifier
4072 {
4073 private:
4074         lua_State *m_lua;
4075         int m_id;
4076
4077         std::set<std::string> m_trigger_contents;
4078         std::set<std::string> m_required_neighbors;
4079         float m_trigger_interval;
4080         u32 m_trigger_chance;
4081 public:
4082         LuaABM(lua_State *L, int id,
4083                         const std::set<std::string> &trigger_contents,
4084                         const std::set<std::string> &required_neighbors,
4085                         float trigger_interval, u32 trigger_chance):
4086                 m_lua(L),
4087                 m_id(id),
4088                 m_trigger_contents(trigger_contents),
4089                 m_required_neighbors(required_neighbors),
4090                 m_trigger_interval(trigger_interval),
4091                 m_trigger_chance(trigger_chance)
4092         {
4093         }
4094         virtual std::set<std::string> getTriggerContents()
4095         {
4096                 return m_trigger_contents;
4097         }
4098         virtual std::set<std::string> getRequiredNeighbors()
4099         {
4100                 return m_required_neighbors;
4101         }
4102         virtual float getTriggerInterval()
4103         {
4104                 return m_trigger_interval;
4105         }
4106         virtual u32 getTriggerChance()
4107         {
4108                 return m_trigger_chance;
4109         }
4110         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4111                         u32 active_object_count, u32 active_object_count_wider)
4112         {
4113                 lua_State *L = m_lua;
4114         
4115                 realitycheck(L);
4116                 assert(lua_checkstack(L, 20));
4117                 StackUnroller stack_unroller(L);
4118
4119                 // Get minetest.registered_abms
4120                 lua_getglobal(L, "minetest");
4121                 lua_getfield(L, -1, "registered_abms");
4122                 luaL_checktype(L, -1, LUA_TTABLE);
4123                 int registered_abms = lua_gettop(L);
4124
4125                 // Get minetest.registered_abms[m_id]
4126                 lua_pushnumber(L, m_id);
4127                 lua_gettable(L, registered_abms);
4128                 if(lua_isnil(L, -1))
4129                         assert(0);
4130                 
4131                 // Call action
4132                 luaL_checktype(L, -1, LUA_TTABLE);
4133                 lua_getfield(L, -1, "action");
4134                 luaL_checktype(L, -1, LUA_TFUNCTION);
4135                 push_v3s16(L, p);
4136                 pushnode(L, n, env->getGameDef()->ndef());
4137                 lua_pushnumber(L, active_object_count);
4138                 lua_pushnumber(L, active_object_count_wider);
4139                 if(lua_pcall(L, 4, 0, 0))
4140                         script_error(L, "error: %s", lua_tostring(L, -1));
4141         }
4142 };
4143
4144 /*
4145         ServerSoundParams
4146 */
4147
4148 static void read_server_sound_params(lua_State *L, int index,
4149                 ServerSoundParams &params)
4150 {
4151         if(index < 0)
4152                 index = lua_gettop(L) + 1 + index;
4153         // Clear
4154         params = ServerSoundParams();
4155         if(lua_istable(L, index)){
4156                 getfloatfield(L, index, "gain", params.gain);
4157                 getstringfield(L, index, "to_player", params.to_player);
4158                 lua_getfield(L, index, "pos");
4159                 if(!lua_isnil(L, -1)){
4160                         v3f p = read_v3f(L, -1)*BS;
4161                         params.pos = p;
4162                         params.type = ServerSoundParams::SSP_POSITIONAL;
4163                 }
4164                 lua_pop(L, 1);
4165                 lua_getfield(L, index, "object");
4166                 if(!lua_isnil(L, -1)){
4167                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
4168                         ServerActiveObject *sao = ObjectRef::getobject(ref);
4169                         if(sao){
4170                                 params.object = sao->getId();
4171                                 params.type = ServerSoundParams::SSP_OBJECT;
4172                         }
4173                 }
4174                 lua_pop(L, 1);
4175                 params.max_hear_distance = BS*getfloatfield_default(L, index,
4176                                 "max_hear_distance", params.max_hear_distance/BS);
4177                 getboolfield(L, index, "loop", params.loop);
4178         }
4179 }
4180
4181 /*
4182         Global functions
4183 */
4184
4185 // debug(text)
4186 // Writes a line to dstream
4187 static int l_debug(lua_State *L)
4188 {
4189         std::string text = lua_tostring(L, 1);
4190         dstream << text << std::endl;
4191         return 0;
4192 }
4193
4194 // log([level,] text)
4195 // Writes a line to the logger.
4196 // The one-argument version logs to infostream.
4197 // The two-argument version accept a log level: error, action, info, or verbose.
4198 static int l_log(lua_State *L)
4199 {
4200         std::string text;
4201         LogMessageLevel level = LMT_INFO;
4202         if(lua_isnone(L, 2))
4203         {
4204                 text = lua_tostring(L, 1);
4205         }
4206         else
4207         {
4208                 std::string levelname = lua_tostring(L, 1);
4209                 text = lua_tostring(L, 2);
4210                 if(levelname == "error")
4211                         level = LMT_ERROR;
4212                 else if(levelname == "action")
4213                         level = LMT_ACTION;
4214                 else if(levelname == "verbose")
4215                         level = LMT_VERBOSE;
4216         }
4217         log_printline(level, text);
4218         return 0;
4219 }
4220
4221 // request_shutdown()
4222 static int l_request_shutdown(lua_State *L)
4223 {
4224         get_server(L)->requestShutdown();
4225         return 0;
4226 }
4227
4228 // get_server_status()
4229 static int l_get_server_status(lua_State *L)
4230 {
4231         lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4232         return 1;
4233 }
4234
4235 // register_item_raw({lots of stuff})
4236 static int l_register_item_raw(lua_State *L)
4237 {
4238         luaL_checktype(L, 1, LUA_TTABLE);
4239         int table = 1;
4240
4241         // Get the writable item and node definition managers from the server
4242         IWritableItemDefManager *idef =
4243                         get_server(L)->getWritableItemDefManager();
4244         IWritableNodeDefManager *ndef =
4245                         get_server(L)->getWritableNodeDefManager();
4246
4247         // Check if name is defined
4248         std::string name;
4249         lua_getfield(L, table, "name");
4250         if(lua_isstring(L, -1)){
4251                 name = lua_tostring(L, -1);
4252                 verbosestream<<"register_item_raw: "<<name<<std::endl;
4253         } else {
4254                 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4255         }
4256
4257         // Check if on_use is defined
4258
4259         ItemDefinition def;
4260         // Set a distinctive default value to check if this is set
4261         def.node_placement_prediction = "__default";
4262
4263         // Read the item definition
4264         def = read_item_definition(L, table, def);
4265
4266         // Default to having client-side placement prediction for nodes
4267         // ("" in item definition sets it off)
4268         if(def.node_placement_prediction == "__default"){
4269                 if(def.type == ITEM_NODE)
4270                         def.node_placement_prediction = name;
4271                 else
4272                         def.node_placement_prediction = "";
4273         }
4274         
4275         // Register item definition
4276         idef->registerItem(def);
4277
4278         // Read the node definition (content features) and register it
4279         if(def.type == ITEM_NODE)
4280         {
4281                 ContentFeatures f = read_content_features(L, table);
4282                 ndef->set(f.name, f);
4283         }
4284
4285         return 0; /* number of results */
4286 }
4287
4288 // register_alias_raw(name, convert_to_name)
4289 static int l_register_alias_raw(lua_State *L)
4290 {
4291         std::string name = luaL_checkstring(L, 1);
4292         std::string convert_to = luaL_checkstring(L, 2);
4293
4294         // Get the writable item definition manager from the server
4295         IWritableItemDefManager *idef =
4296                         get_server(L)->getWritableItemDefManager();
4297         
4298         idef->registerAlias(name, convert_to);
4299         
4300         return 0; /* number of results */
4301 }
4302
4303 // helper for register_craft
4304 static bool read_craft_recipe_shaped(lua_State *L, int index,
4305                 int &width, std::vector<std::string> &recipe)
4306 {
4307         if(index < 0)
4308                 index = lua_gettop(L) + 1 + index;
4309
4310         if(!lua_istable(L, index))
4311                 return false;
4312
4313         lua_pushnil(L);
4314         int rowcount = 0;
4315         while(lua_next(L, index) != 0){
4316                 int colcount = 0;
4317                 // key at index -2 and value at index -1
4318                 if(!lua_istable(L, -1))
4319                         return false;
4320                 int table2 = lua_gettop(L);
4321                 lua_pushnil(L);
4322                 while(lua_next(L, table2) != 0){
4323                         // key at index -2 and value at index -1
4324                         if(!lua_isstring(L, -1))
4325                                 return false;
4326                         recipe.push_back(lua_tostring(L, -1));
4327                         // removes value, keeps key for next iteration
4328                         lua_pop(L, 1);
4329                         colcount++;
4330                 }
4331                 if(rowcount == 0){
4332                         width = colcount;
4333                 } else {
4334                         if(colcount != width)
4335                                 return false;
4336                 }
4337                 // removes value, keeps key for next iteration
4338                 lua_pop(L, 1);
4339                 rowcount++;
4340         }
4341         return width != 0;
4342 }
4343
4344 // helper for register_craft
4345 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4346                 std::vector<std::string> &recipe)
4347 {
4348         if(index < 0)
4349                 index = lua_gettop(L) + 1 + index;
4350
4351         if(!lua_istable(L, index))
4352                 return false;
4353
4354         lua_pushnil(L);
4355         while(lua_next(L, index) != 0){
4356                 // key at index -2 and value at index -1
4357                 if(!lua_isstring(L, -1))
4358                         return false;
4359                 recipe.push_back(lua_tostring(L, -1));
4360                 // removes value, keeps key for next iteration
4361                 lua_pop(L, 1);
4362         }
4363         return true;
4364 }
4365
4366 // helper for register_craft
4367 static bool read_craft_replacements(lua_State *L, int index,
4368                 CraftReplacements &replacements)
4369 {
4370         if(index < 0)
4371                 index = lua_gettop(L) + 1 + index;
4372
4373         if(!lua_istable(L, index))
4374                 return false;
4375
4376         lua_pushnil(L);
4377         while(lua_next(L, index) != 0){
4378                 // key at index -2 and value at index -1
4379                 if(!lua_istable(L, -1))
4380                         return false;
4381                 lua_rawgeti(L, -1, 1);
4382                 if(!lua_isstring(L, -1))
4383                         return false;
4384                 std::string replace_from = lua_tostring(L, -1);
4385                 lua_pop(L, 1);
4386                 lua_rawgeti(L, -1, 2);
4387                 if(!lua_isstring(L, -1))
4388                         return false;
4389                 std::string replace_to = lua_tostring(L, -1);
4390                 lua_pop(L, 1);
4391                 replacements.pairs.push_back(
4392                                 std::make_pair(replace_from, replace_to));
4393                 // removes value, keeps key for next iteration
4394                 lua_pop(L, 1);
4395         }
4396         return true;
4397 }
4398 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4399 static int l_register_craft(lua_State *L)
4400 {
4401         //infostream<<"register_craft"<<std::endl;
4402         luaL_checktype(L, 1, LUA_TTABLE);
4403         int table = 1;
4404
4405         // Get the writable craft definition manager from the server
4406         IWritableCraftDefManager *craftdef =
4407                         get_server(L)->getWritableCraftDefManager();
4408         
4409         std::string type = getstringfield_default(L, table, "type", "shaped");
4410
4411         /*
4412                 CraftDefinitionShaped
4413         */
4414         if(type == "shaped"){
4415                 std::string output = getstringfield_default(L, table, "output", "");
4416                 if(output == "")
4417                         throw LuaError(L, "Crafting definition is missing an output");
4418
4419                 int width = 0;
4420                 std::vector<std::string> recipe;
4421                 lua_getfield(L, table, "recipe");
4422                 if(lua_isnil(L, -1))
4423                         throw LuaError(L, "Crafting definition is missing a recipe"
4424                                         " (output=\"" + output + "\")");
4425                 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4426                         throw LuaError(L, "Invalid crafting recipe"
4427                                         " (output=\"" + output + "\")");
4428
4429                 CraftReplacements replacements;
4430                 lua_getfield(L, table, "replacements");
4431                 if(!lua_isnil(L, -1))
4432                 {
4433                         if(!read_craft_replacements(L, -1, replacements))
4434                                 throw LuaError(L, "Invalid replacements"
4435                                                 " (output=\"" + output + "\")");
4436                 }
4437
4438                 CraftDefinition *def = new CraftDefinitionShaped(
4439                                 output, width, recipe, replacements);
4440                 craftdef->registerCraft(def);
4441         }
4442         /*
4443                 CraftDefinitionShapeless
4444         */
4445         else if(type == "shapeless"){
4446                 std::string output = getstringfield_default(L, table, "output", "");
4447                 if(output == "")
4448                         throw LuaError(L, "Crafting definition (shapeless)"
4449                                         " is missing an output");
4450
4451                 std::vector<std::string> recipe;
4452                 lua_getfield(L, table, "recipe");
4453                 if(lua_isnil(L, -1))
4454                         throw LuaError(L, "Crafting definition (shapeless)"
4455                                         " is missing a recipe"
4456                                         " (output=\"" + output + "\")");
4457                 if(!read_craft_recipe_shapeless(L, -1, recipe))
4458                         throw LuaError(L, "Invalid crafting recipe"
4459                                         " (output=\"" + output + "\")");
4460
4461                 CraftReplacements replacements;
4462                 lua_getfield(L, table, "replacements");
4463                 if(!lua_isnil(L, -1))
4464                 {
4465                         if(!read_craft_replacements(L, -1, replacements))
4466                                 throw LuaError(L, "Invalid replacements"
4467                                                 " (output=\"" + output + "\")");
4468                 }
4469
4470                 CraftDefinition *def = new CraftDefinitionShapeless(
4471                                 output, recipe, replacements);
4472                 craftdef->registerCraft(def);
4473         }
4474         /*
4475                 CraftDefinitionToolRepair
4476         */
4477         else if(type == "toolrepair"){
4478                 float additional_wear = getfloatfield_default(L, table,
4479                                 "additional_wear", 0.0);
4480
4481                 CraftDefinition *def = new CraftDefinitionToolRepair(
4482                                 additional_wear);
4483                 craftdef->registerCraft(def);
4484         }
4485         /*
4486                 CraftDefinitionCooking
4487         */
4488         else if(type == "cooking"){
4489                 std::string output = getstringfield_default(L, table, "output", "");
4490                 if(output == "")
4491                         throw LuaError(L, "Crafting definition (cooking)"
4492                                         " is missing an output");
4493
4494                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4495                 if(recipe == "")
4496                         throw LuaError(L, "Crafting definition (cooking)"
4497                                         " is missing a recipe"
4498                                         " (output=\"" + output + "\")");
4499
4500                 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4501
4502                 CraftReplacements replacements;
4503                 lua_getfield(L, table, "replacements");
4504                 if(!lua_isnil(L, -1))
4505                 {
4506                         if(!read_craft_replacements(L, -1, replacements))
4507                                 throw LuaError(L, "Invalid replacements"
4508                                                 " (cooking output=\"" + output + "\")");
4509                 }
4510
4511                 CraftDefinition *def = new CraftDefinitionCooking(
4512                                 output, recipe, cooktime, replacements);
4513                 craftdef->registerCraft(def);
4514         }
4515         /*
4516                 CraftDefinitionFuel
4517         */
4518         else if(type == "fuel"){
4519                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4520                 if(recipe == "")
4521                         throw LuaError(L, "Crafting definition (fuel)"
4522                                         " is missing a recipe");
4523
4524                 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4525
4526                 CraftReplacements replacements;
4527                 lua_getfield(L, table, "replacements");
4528                 if(!lua_isnil(L, -1))
4529                 {
4530                         if(!read_craft_replacements(L, -1, replacements))
4531                                 throw LuaError(L, "Invalid replacements"
4532                                                 " (fuel recipe=\"" + recipe + "\")");
4533                 }
4534
4535                 CraftDefinition *def = new CraftDefinitionFuel(
4536                                 recipe, burntime, replacements);
4537                 craftdef->registerCraft(def);
4538         }
4539         else
4540         {
4541                 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4542         }
4543
4544         lua_pop(L, 1);
4545         return 0; /* number of results */
4546 }
4547
4548 // setting_set(name, value)
4549 static int l_setting_set(lua_State *L)
4550 {
4551         const char *name = luaL_checkstring(L, 1);
4552         const char *value = luaL_checkstring(L, 2);
4553         g_settings->set(name, value);
4554         return 0;
4555 }
4556
4557 // setting_get(name)
4558 static int l_setting_get(lua_State *L)
4559 {
4560         const char *name = luaL_checkstring(L, 1);
4561         try{
4562                 std::string value = g_settings->get(name);
4563                 lua_pushstring(L, value.c_str());
4564         } catch(SettingNotFoundException &e){
4565                 lua_pushnil(L);
4566         }
4567         return 1;
4568 }
4569
4570 // setting_getbool(name)
4571 static int l_setting_getbool(lua_State *L)
4572 {
4573         const char *name = luaL_checkstring(L, 1);
4574         try{
4575                 bool value = g_settings->getBool(name);
4576                 lua_pushboolean(L, value);
4577         } catch(SettingNotFoundException &e){
4578                 lua_pushnil(L);
4579         }
4580         return 1;
4581 }
4582
4583 // chat_send_all(text)
4584 static int l_chat_send_all(lua_State *L)
4585 {
4586         const char *text = luaL_checkstring(L, 1);
4587         // Get server from registry
4588         Server *server = get_server(L);
4589         // Send
4590         server->notifyPlayers(narrow_to_wide(text));
4591         return 0;
4592 }
4593
4594 // chat_send_player(name, text)
4595 static int l_chat_send_player(lua_State *L)
4596 {
4597         const char *name = luaL_checkstring(L, 1);
4598         const char *text = luaL_checkstring(L, 2);
4599         // Get server from registry
4600         Server *server = get_server(L);
4601         // Send
4602         server->notifyPlayer(name, narrow_to_wide(text));
4603         return 0;
4604 }
4605
4606 // get_player_privs(name, text)
4607 static int l_get_player_privs(lua_State *L)
4608 {
4609         const char *name = luaL_checkstring(L, 1);
4610         // Get server from registry
4611         Server *server = get_server(L);
4612         // Do it
4613         lua_newtable(L);
4614         int table = lua_gettop(L);
4615         std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4616         for(std::set<std::string>::const_iterator
4617                         i = privs_s.begin(); i != privs_s.end(); i++){
4618                 lua_pushboolean(L, true);
4619                 lua_setfield(L, table, i->c_str());
4620         }
4621         lua_pushvalue(L, table);
4622         return 1;
4623 }
4624
4625 // get_ban_list()
4626 static int l_get_ban_list(lua_State *L)
4627 {
4628         lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4629         return 1;
4630 }
4631
4632 // get_ban_description()
4633 static int l_get_ban_description(lua_State *L)
4634 {
4635         const char * ip_or_name = luaL_checkstring(L, 1);
4636         lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4637         return 1;
4638 }
4639
4640 // ban_player()
4641 static int l_ban_player(lua_State *L)
4642 {
4643         const char * name = luaL_checkstring(L, 1);
4644         Player *player = get_env(L)->getPlayer(name);
4645         if(player == NULL)
4646         {
4647                 lua_pushboolean(L, false); // no such player
4648                 return 1;
4649         }
4650         try
4651         {
4652                 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4653                 std::string ip_str = addr.serializeString();
4654                 get_server(L)->setIpBanned(ip_str, name);
4655         }
4656         catch(con::PeerNotFoundException) // unlikely
4657         {
4658                 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4659                 lua_pushboolean(L, false); // error
4660                 return 1;
4661         }
4662         lua_pushboolean(L, true);
4663         return 1;
4664 }
4665
4666 // unban_player_or_ip()
4667 static int l_unban_player_of_ip(lua_State *L)
4668 {
4669         const char * ip_or_name = luaL_checkstring(L, 1);
4670         get_server(L)->unsetIpBanned(ip_or_name);
4671         lua_pushboolean(L, true);
4672         return 1;
4673 }
4674
4675 // get_inventory(location)
4676 static int l_get_inventory(lua_State *L)
4677 {
4678         InventoryLocation loc;
4679
4680         std::string type = checkstringfield(L, 1, "type");
4681         if(type == "player"){
4682                 std::string name = checkstringfield(L, 1, "name");
4683                 loc.setPlayer(name);
4684         } else if(type == "node"){
4685                 lua_getfield(L, 1, "pos");
4686                 v3s16 pos = check_v3s16(L, -1);
4687                 loc.setNodeMeta(pos);
4688         } else if(type == "detached"){
4689                 std::string name = checkstringfield(L, 1, "name");
4690                 loc.setDetached(name);
4691         }
4692         
4693         if(get_server(L)->getInventory(loc) != NULL)
4694                 InvRef::create(L, loc);
4695         else
4696                 lua_pushnil(L);
4697         return 1;
4698 }
4699
4700 // create_detached_inventory_raw(name)
4701 static int l_create_detached_inventory_raw(lua_State *L)
4702 {
4703         const char *name = luaL_checkstring(L, 1);
4704         if(get_server(L)->createDetachedInventory(name) != NULL){
4705                 InventoryLocation loc;
4706                 loc.setDetached(name);
4707                 InvRef::create(L, loc);
4708         }else{
4709                 lua_pushnil(L);
4710         }
4711         return 1;
4712 }
4713
4714 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4715 static int l_get_dig_params(lua_State *L)
4716 {
4717         std::map<std::string, int> groups;
4718         read_groups(L, 1, groups);
4719         ToolCapabilities tp = read_tool_capabilities(L, 2);
4720         if(lua_isnoneornil(L, 3))
4721                 push_dig_params(L, getDigParams(groups, &tp));
4722         else
4723                 push_dig_params(L, getDigParams(groups, &tp,
4724                                         luaL_checknumber(L, 3)));
4725         return 1;
4726 }
4727
4728 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4729 static int l_get_hit_params(lua_State *L)
4730 {
4731         std::map<std::string, int> groups;
4732         read_groups(L, 1, groups);
4733         ToolCapabilities tp = read_tool_capabilities(L, 2);
4734         if(lua_isnoneornil(L, 3))
4735                 push_hit_params(L, getHitParams(groups, &tp));
4736         else
4737                 push_hit_params(L, getHitParams(groups, &tp,
4738                                         luaL_checknumber(L, 3)));
4739         return 1;
4740 }
4741
4742 // get_current_modname()
4743 static int l_get_current_modname(lua_State *L)
4744 {
4745         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4746         return 1;
4747 }
4748
4749 // get_modpath(modname)
4750 static int l_get_modpath(lua_State *L)
4751 {
4752         std::string modname = luaL_checkstring(L, 1);
4753         // Do it
4754         if(modname == "__builtin"){
4755                 std::string path = get_server(L)->getBuiltinLuaPath();
4756                 lua_pushstring(L, path.c_str());
4757                 return 1;
4758         }
4759         const ModSpec *mod = get_server(L)->getModSpec(modname);
4760         if(!mod){
4761                 lua_pushnil(L);
4762                 return 1;
4763         }
4764         lua_pushstring(L, mod->path.c_str());
4765         return 1;
4766 }
4767
4768 // get_modnames()
4769 // the returned list is sorted alphabetically for you
4770 static int l_get_modnames(lua_State *L)
4771 {
4772         // Get a list of mods
4773         core::list<std::string> mods_unsorted, mods_sorted;
4774         get_server(L)->getModNames(mods_unsorted);
4775
4776         // Take unsorted items from mods_unsorted and sort them into
4777         // mods_sorted; not great performance but the number of mods on a
4778         // server will likely be small.
4779         for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4780             i != mods_unsorted.end(); i++)
4781         {
4782                 bool added = false;
4783                 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4784                     x != mods_unsorted.end(); x++)
4785                 {
4786                         // I doubt anybody using Minetest will be using
4787                         // anything not ASCII based :)
4788                         if((*i).compare(*x) <= 0)
4789                         {
4790                                 mods_sorted.insert_before(x, *i);
4791                                 added = true;
4792                                 break;
4793                         }
4794                 }
4795                 if(!added)
4796                         mods_sorted.push_back(*i);
4797         }
4798
4799         // Get the table insertion function from Lua.
4800         lua_getglobal(L, "table");
4801         lua_getfield(L, -1, "insert");
4802         int insertion_func = lua_gettop(L);
4803
4804         // Package them up for Lua
4805         lua_newtable(L);
4806         int new_table = lua_gettop(L);
4807         core::list<std::string>::Iterator i = mods_sorted.begin();
4808         while(i != mods_sorted.end())
4809         {
4810                 lua_pushvalue(L, insertion_func);
4811                 lua_pushvalue(L, new_table);
4812                 lua_pushstring(L, (*i).c_str());
4813                 if(lua_pcall(L, 2, 0, 0) != 0)
4814                 {
4815                         script_error(L, "error: %s", lua_tostring(L, -1));
4816                 }
4817                 i++;
4818         }
4819         return 1;
4820 }
4821
4822 // get_worldpath()
4823 static int l_get_worldpath(lua_State *L)
4824 {
4825         std::string worldpath = get_server(L)->getWorldPath();
4826         lua_pushstring(L, worldpath.c_str());
4827         return 1;
4828 }
4829
4830 // sound_play(spec, parameters)
4831 static int l_sound_play(lua_State *L)
4832 {
4833         SimpleSoundSpec spec;
4834         read_soundspec(L, 1, spec);
4835         ServerSoundParams params;
4836         read_server_sound_params(L, 2, params);
4837         s32 handle = get_server(L)->playSound(spec, params);
4838         lua_pushinteger(L, handle);
4839         return 1;
4840 }
4841
4842 // sound_stop(handle)
4843 static int l_sound_stop(lua_State *L)
4844 {
4845         int handle = luaL_checkinteger(L, 1);
4846         get_server(L)->stopSound(handle);
4847         return 0;
4848 }
4849
4850 // is_singleplayer()
4851 static int l_is_singleplayer(lua_State *L)
4852 {
4853         lua_pushboolean(L, get_server(L)->isSingleplayer());
4854         return 1;
4855 }
4856
4857 // get_password_hash(name, raw_password)
4858 static int l_get_password_hash(lua_State *L)
4859 {
4860         std::string name = luaL_checkstring(L, 1);
4861         std::string raw_password = luaL_checkstring(L, 2);
4862         std::string hash = translatePassword(name,
4863                         narrow_to_wide(raw_password));
4864         lua_pushstring(L, hash.c_str());
4865         return 1;
4866 }
4867
4868 // notify_authentication_modified(name)
4869 static int l_notify_authentication_modified(lua_State *L)
4870 {
4871         std::string name = "";
4872         if(lua_isstring(L, 1))
4873                 name = lua_tostring(L, 1);
4874         get_server(L)->reportPrivsModified(name);
4875         return 0;
4876 }
4877
4878 // get_craft_result(input)
4879 static int l_get_craft_result(lua_State *L)
4880 {
4881         int input_i = 1;
4882         std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4883         enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4884                                 es_CraftMethod, CRAFT_METHOD_NORMAL);
4885         int width = 1;
4886         lua_getfield(L, input_i, "width");
4887         if(lua_isnumber(L, -1))
4888                 width = luaL_checkinteger(L, -1);
4889         lua_pop(L, 1);
4890         lua_getfield(L, input_i, "items");
4891         std::vector<ItemStack> items = read_items(L, -1);
4892         lua_pop(L, 1); // items
4893         
4894         IGameDef *gdef = get_server(L);
4895         ICraftDefManager *cdef = gdef->cdef();
4896         CraftInput input(method, width, items);
4897         CraftOutput output;
4898         bool got = cdef->getCraftResult(input, output, true, gdef);
4899         lua_newtable(L); // output table
4900         if(got){
4901                 ItemStack item;
4902                 item.deSerialize(output.item, gdef->idef());
4903                 LuaItemStack::create(L, item);
4904                 lua_setfield(L, -2, "item");
4905                 setintfield(L, -1, "time", output.time);
4906         } else {
4907                 LuaItemStack::create(L, ItemStack());
4908                 lua_setfield(L, -2, "item");
4909                 setintfield(L, -1, "time", 0);
4910         }
4911         lua_newtable(L); // decremented input table
4912         lua_pushstring(L, method_s.c_str());
4913         lua_setfield(L, -2, "method");
4914         lua_pushinteger(L, width);
4915         lua_setfield(L, -2, "width");
4916         push_items(L, input.items);
4917         lua_setfield(L, -2, "items");
4918         return 2;
4919 }
4920
4921 // get_craft_recipe(result item)
4922 static int l_get_craft_recipe(lua_State *L)
4923 {
4924         int k = 0;
4925         char tmp[20];
4926         int input_i = 1;
4927         std::string o_item = luaL_checkstring(L,input_i);
4928         
4929         IGameDef *gdef = get_server(L);
4930         ICraftDefManager *cdef = gdef->cdef();
4931         CraftInput input;
4932         CraftOutput output(o_item,0);
4933         bool got = cdef->getCraftRecipe(input, output, gdef);
4934         lua_newtable(L); // output table
4935         if(got){
4936                 lua_newtable(L);
4937                 for(std::vector<ItemStack>::const_iterator
4938                         i = input.items.begin();
4939                         i != input.items.end(); i++, k++)
4940                 {
4941                         if (i->empty())
4942                         {
4943                                 continue;
4944                         }
4945                         sprintf(tmp,"%d",k);
4946                         lua_pushstring(L,tmp);
4947                         lua_pushstring(L,i->name.c_str());
4948                         lua_settable(L, -3);
4949                 }
4950                 lua_setfield(L, -2, "items");
4951                 setintfield(L, -1, "width", input.width);
4952                 switch (input.method) {
4953                 case CRAFT_METHOD_NORMAL:
4954                         lua_pushstring(L,"normal");
4955                         break;
4956                 case CRAFT_METHOD_COOKING:
4957                         lua_pushstring(L,"cooking");
4958                         break;
4959                 case CRAFT_METHOD_FUEL:
4960                         lua_pushstring(L,"fuel");
4961                         break;
4962                 default:
4963                         lua_pushstring(L,"unknown");
4964                 }
4965                 lua_setfield(L, -2, "type");
4966         } else {
4967                 lua_pushnil(L);
4968                 lua_setfield(L, -2, "items");
4969                 setintfield(L, -1, "width", 0);
4970         }
4971         return 1;
4972 }
4973
4974 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
4975 static int l_rollback_get_last_node_actor(lua_State *L)
4976 {
4977         v3s16 p = read_v3s16(L, 1);
4978         int range = luaL_checknumber(L, 2);
4979         int seconds = luaL_checknumber(L, 3);
4980         Server *server = get_server(L);
4981         IRollbackManager *rollback = server->getRollbackManager();
4982         v3s16 act_p;
4983         int act_seconds = 0;
4984         std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
4985         lua_pushstring(L, actor.c_str());
4986         push_v3s16(L, act_p);
4987         lua_pushnumber(L, act_seconds);
4988         return 3;
4989 }
4990
4991 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
4992 static int l_rollback_revert_actions_by(lua_State *L)
4993 {
4994         std::string actor = luaL_checkstring(L, 1);
4995         int seconds = luaL_checknumber(L, 2);
4996         Server *server = get_server(L);
4997         IRollbackManager *rollback = server->getRollbackManager();
4998         std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
4999         std::list<std::string> log;
5000         bool success = server->rollbackRevertActions(actions, &log);
5001         // Push boolean result
5002         lua_pushboolean(L, success);
5003         // Get the table insert function and push the log table
5004         lua_getglobal(L, "table");
5005         lua_getfield(L, -1, "insert");
5006         int table_insert = lua_gettop(L);
5007         lua_newtable(L);
5008         int table = lua_gettop(L);
5009         for(std::list<std::string>::const_iterator i = log.begin();
5010                         i != log.end(); i++)
5011         {
5012                 lua_pushvalue(L, table_insert);
5013                 lua_pushvalue(L, table);
5014                 lua_pushstring(L, i->c_str());
5015                 if(lua_pcall(L, 2, 0, 0))
5016                         script_error(L, "error: %s", lua_tostring(L, -1));
5017         }
5018         lua_remove(L, -2); // Remove table
5019         lua_remove(L, -2); // Remove insert
5020         return 2;
5021 }
5022
5023 static const struct luaL_Reg minetest_f [] = {
5024         {"debug", l_debug},
5025         {"log", l_log},
5026         {"request_shutdown", l_request_shutdown},
5027         {"get_server_status", l_get_server_status},
5028         {"register_item_raw", l_register_item_raw},
5029         {"register_alias_raw", l_register_alias_raw},
5030         {"register_craft", l_register_craft},
5031         {"setting_set", l_setting_set},
5032         {"setting_get", l_setting_get},
5033         {"setting_getbool", l_setting_getbool},
5034         {"chat_send_all", l_chat_send_all},
5035         {"chat_send_player", l_chat_send_player},
5036         {"get_player_privs", l_get_player_privs},
5037         {"get_ban_list", l_get_ban_list},
5038         {"get_ban_description", l_get_ban_description},
5039         {"ban_player", l_ban_player},
5040         {"unban_player_or_ip", l_unban_player_of_ip},
5041         {"get_inventory", l_get_inventory},
5042         {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5043         {"get_dig_params", l_get_dig_params},
5044         {"get_hit_params", l_get_hit_params},
5045         {"get_current_modname", l_get_current_modname},
5046         {"get_modpath", l_get_modpath},
5047         {"get_modnames", l_get_modnames},
5048         {"get_worldpath", l_get_worldpath},
5049         {"sound_play", l_sound_play},
5050         {"sound_stop", l_sound_stop},
5051         {"is_singleplayer", l_is_singleplayer},
5052         {"get_password_hash", l_get_password_hash},
5053         {"notify_authentication_modified", l_notify_authentication_modified},
5054         {"get_craft_result", l_get_craft_result},
5055         {"get_craft_recipe", l_get_craft_recipe},
5056         {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5057         {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5058         {NULL, NULL}
5059 };
5060
5061 /*
5062         Main export function
5063 */
5064
5065 void scriptapi_export(lua_State *L, Server *server)
5066 {
5067         realitycheck(L);
5068         assert(lua_checkstack(L, 20));
5069         verbosestream<<"scriptapi_export()"<<std::endl;
5070         StackUnroller stack_unroller(L);
5071
5072         // Store server as light userdata in registry
5073         lua_pushlightuserdata(L, server);
5074         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5075
5076         // Register global functions in table minetest
5077         lua_newtable(L);
5078         luaL_register(L, NULL, minetest_f);
5079         lua_setglobal(L, "minetest");
5080         
5081         // Get the main minetest table
5082         lua_getglobal(L, "minetest");
5083
5084         // Add tables to minetest
5085         lua_newtable(L);
5086         lua_setfield(L, -2, "object_refs");
5087         lua_newtable(L);
5088         lua_setfield(L, -2, "luaentities");
5089
5090         // Register wrappers
5091         LuaItemStack::Register(L);
5092         InvRef::Register(L);
5093         NodeMetaRef::Register(L);
5094         NodeTimerRef::Register(L);
5095         ObjectRef::Register(L);
5096         EnvRef::Register(L);
5097         LuaPseudoRandom::Register(L);
5098         LuaPerlinNoise::Register(L);
5099 }
5100
5101 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5102                 const std::string &modname)
5103 {
5104         ModNameStorer modnamestorer(L, modname);
5105
5106         if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5107                         "0123456789_")){
5108                 errorstream<<"Error loading mod \""<<modname
5109                                 <<"\": modname does not follow naming conventions: "
5110                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5111                 return false;
5112         }
5113         
5114         bool success = false;
5115
5116         try{
5117                 success = script_load(L, scriptpath.c_str());
5118         }
5119         catch(LuaError &e){
5120                 errorstream<<"Error loading mod \""<<modname
5121                                 <<"\": "<<e.what()<<std::endl;
5122         }
5123
5124         return success;
5125 }
5126
5127 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5128 {
5129         realitycheck(L);
5130         assert(lua_checkstack(L, 20));
5131         verbosestream<<"scriptapi_add_environment"<<std::endl;
5132         StackUnroller stack_unroller(L);
5133
5134         // Create EnvRef on stack
5135         EnvRef::create(L, env);
5136         int envref = lua_gettop(L);
5137
5138         // minetest.env = envref
5139         lua_getglobal(L, "minetest");
5140         luaL_checktype(L, -1, LUA_TTABLE);
5141         lua_pushvalue(L, envref);
5142         lua_setfield(L, -2, "env");
5143
5144         // Store environment as light userdata in registry
5145         lua_pushlightuserdata(L, env);
5146         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5147
5148         /*
5149                 Add ActiveBlockModifiers to environment
5150         */
5151
5152         // Get minetest.registered_abms
5153         lua_getglobal(L, "minetest");
5154         lua_getfield(L, -1, "registered_abms");
5155         luaL_checktype(L, -1, LUA_TTABLE);
5156         int registered_abms = lua_gettop(L);
5157         
5158         if(lua_istable(L, registered_abms)){
5159                 int table = lua_gettop(L);
5160                 lua_pushnil(L);
5161                 while(lua_next(L, table) != 0){
5162                         // key at index -2 and value at index -1
5163                         int id = lua_tonumber(L, -2);
5164                         int current_abm = lua_gettop(L);
5165
5166                         std::set<std::string> trigger_contents;
5167                         lua_getfield(L, current_abm, "nodenames");
5168                         if(lua_istable(L, -1)){
5169                                 int table = lua_gettop(L);
5170                                 lua_pushnil(L);
5171                                 while(lua_next(L, table) != 0){
5172                                         // key at index -2 and value at index -1
5173                                         luaL_checktype(L, -1, LUA_TSTRING);
5174                                         trigger_contents.insert(lua_tostring(L, -1));
5175                                         // removes value, keeps key for next iteration
5176                                         lua_pop(L, 1);
5177                                 }
5178                         } else if(lua_isstring(L, -1)){
5179                                 trigger_contents.insert(lua_tostring(L, -1));
5180                         }
5181                         lua_pop(L, 1);
5182
5183                         std::set<std::string> required_neighbors;
5184                         lua_getfield(L, current_abm, "neighbors");
5185                         if(lua_istable(L, -1)){
5186                                 int table = lua_gettop(L);
5187                                 lua_pushnil(L);
5188                                 while(lua_next(L, table) != 0){
5189                                         // key at index -2 and value at index -1
5190                                         luaL_checktype(L, -1, LUA_TSTRING);
5191                                         required_neighbors.insert(lua_tostring(L, -1));
5192                                         // removes value, keeps key for next iteration
5193                                         lua_pop(L, 1);
5194                                 }
5195                         } else if(lua_isstring(L, -1)){
5196                                 required_neighbors.insert(lua_tostring(L, -1));
5197                         }
5198                         lua_pop(L, 1);
5199
5200                         float trigger_interval = 10.0;
5201                         getfloatfield(L, current_abm, "interval", trigger_interval);
5202
5203                         int trigger_chance = 50;
5204                         getintfield(L, current_abm, "chance", trigger_chance);
5205
5206                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
5207                                         required_neighbors, trigger_interval, trigger_chance);
5208                         
5209                         env->addActiveBlockModifier(abm);
5210
5211                         // removes value, keeps key for next iteration
5212                         lua_pop(L, 1);
5213                 }
5214         }
5215         lua_pop(L, 1);
5216 }
5217
5218 #if 0
5219 // Dump stack top with the dump2 function
5220 static void dump2(lua_State *L, const char *name)
5221 {
5222         // Dump object (debug)
5223         lua_getglobal(L, "dump2");
5224         luaL_checktype(L, -1, LUA_TFUNCTION);
5225         lua_pushvalue(L, -2); // Get previous stack top as first parameter
5226         lua_pushstring(L, name);
5227         if(lua_pcall(L, 2, 0, 0))
5228                 script_error(L, "error: %s", lua_tostring(L, -1));
5229 }
5230 #endif
5231
5232 /*
5233         object_reference
5234 */
5235
5236 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5237 {
5238         realitycheck(L);
5239         assert(lua_checkstack(L, 20));
5240         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5241         StackUnroller stack_unroller(L);
5242
5243         // Create object on stack
5244         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5245         int object = lua_gettop(L);
5246
5247         // Get minetest.object_refs table
5248         lua_getglobal(L, "minetest");
5249         lua_getfield(L, -1, "object_refs");
5250         luaL_checktype(L, -1, LUA_TTABLE);
5251         int objectstable = lua_gettop(L);
5252         
5253         // object_refs[id] = object
5254         lua_pushnumber(L, cobj->getId()); // Push id
5255         lua_pushvalue(L, object); // Copy object to top of stack
5256         lua_settable(L, objectstable);
5257 }
5258
5259 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5260 {
5261         realitycheck(L);
5262         assert(lua_checkstack(L, 20));
5263         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5264         StackUnroller stack_unroller(L);
5265
5266         // Get minetest.object_refs table
5267         lua_getglobal(L, "minetest");
5268         lua_getfield(L, -1, "object_refs");
5269         luaL_checktype(L, -1, LUA_TTABLE);
5270         int objectstable = lua_gettop(L);
5271         
5272         // Get object_refs[id]
5273         lua_pushnumber(L, cobj->getId()); // Push id
5274         lua_gettable(L, objectstable);
5275         // Set object reference to NULL
5276         ObjectRef::set_null(L);
5277         lua_pop(L, 1); // pop object
5278
5279         // Set object_refs[id] = nil
5280         lua_pushnumber(L, cobj->getId()); // Push id
5281         lua_pushnil(L);
5282         lua_settable(L, objectstable);
5283 }
5284
5285 /*
5286         misc
5287 */
5288
5289 // What scriptapi_run_callbacks does with the return values of callbacks.
5290 // Regardless of the mode, if only one callback is defined,
5291 // its return value is the total return value.
5292 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5293 enum RunCallbacksMode
5294 {
5295         // Returns the return value of the first callback
5296         // Returns nil if list of callbacks is empty
5297         RUN_CALLBACKS_MODE_FIRST,
5298         // Returns the return value of the last callback
5299         // Returns nil if list of callbacks is empty
5300         RUN_CALLBACKS_MODE_LAST,
5301         // If any callback returns a false value, the first such is returned
5302         // Otherwise, the first callback's return value (trueish) is returned
5303         // Returns true if list of callbacks is empty
5304         RUN_CALLBACKS_MODE_AND,
5305         // Like above, but stops calling callbacks (short circuit)
5306         // after seeing the first false value
5307         RUN_CALLBACKS_MODE_AND_SC,
5308         // If any callback returns a true value, the first such is returned
5309         // Otherwise, the first callback's return value (falseish) is returned
5310         // Returns false if list of callbacks is empty
5311         RUN_CALLBACKS_MODE_OR,
5312         // Like above, but stops calling callbacks (short circuit)
5313         // after seeing the first true value
5314         RUN_CALLBACKS_MODE_OR_SC,
5315         // Note: "a true value" and "a false value" refer to values that
5316         // are converted by lua_toboolean to true or false, respectively.
5317 };
5318
5319 // Push the list of callbacks (a lua table).
5320 // Then push nargs arguments.
5321 // Then call this function, which
5322 // - runs the callbacks
5323 // - removes the table and arguments from the lua stack
5324 // - pushes the return value, computed depending on mode
5325 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5326                 RunCallbacksMode mode)
5327 {
5328         // Insert the return value into the lua stack, below the table
5329         assert(lua_gettop(L) >= nargs + 1);
5330         lua_pushnil(L);
5331         lua_insert(L, -(nargs + 1) - 1);
5332         // Stack now looks like this:
5333         // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5334
5335         int rv = lua_gettop(L) - nargs - 1;
5336         int table = rv + 1;
5337         int arg = table + 1;
5338
5339         luaL_checktype(L, table, LUA_TTABLE);
5340
5341         // Foreach
5342         lua_pushnil(L);
5343         bool first_loop = true;
5344         while(lua_next(L, table) != 0){
5345                 // key at index -2 and value at index -1
5346                 luaL_checktype(L, -1, LUA_TFUNCTION);
5347                 // Call function
5348                 for(int i = 0; i < nargs; i++)
5349                         lua_pushvalue(L, arg+i);
5350                 if(lua_pcall(L, nargs, 1, 0))
5351                         script_error(L, "error: %s", lua_tostring(L, -1));
5352
5353                 // Move return value to designated space in stack
5354                 // Or pop it
5355                 if(first_loop){
5356                         // Result of first callback is always moved
5357                         lua_replace(L, rv);
5358                         first_loop = false;
5359                 } else {
5360                         // Otherwise, what happens depends on the mode
5361                         if(mode == RUN_CALLBACKS_MODE_FIRST)
5362                                 lua_pop(L, 1);
5363                         else if(mode == RUN_CALLBACKS_MODE_LAST)
5364                                 lua_replace(L, rv);
5365                         else if(mode == RUN_CALLBACKS_MODE_AND ||
5366                                         mode == RUN_CALLBACKS_MODE_AND_SC){
5367                                 if(lua_toboolean(L, rv) == true &&
5368                                                 lua_toboolean(L, -1) == false)
5369                                         lua_replace(L, rv);
5370                                 else
5371                                         lua_pop(L, 1);
5372                         }
5373                         else if(mode == RUN_CALLBACKS_MODE_OR ||
5374                                         mode == RUN_CALLBACKS_MODE_OR_SC){
5375                                 if(lua_toboolean(L, rv) == false &&
5376                                                 lua_toboolean(L, -1) == true)
5377                                         lua_replace(L, rv);
5378                                 else
5379                                         lua_pop(L, 1);
5380                         }
5381                         else
5382                                 assert(0);
5383                 }
5384
5385                 // Handle short circuit modes
5386                 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5387                                 lua_toboolean(L, rv) == false)
5388                         break;
5389                 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5390                                 lua_toboolean(L, rv) == true)
5391                         break;
5392
5393                 // value removed, keep key for next iteration
5394         }
5395
5396         // Remove stuff from stack, leaving only the return value
5397         lua_settop(L, rv);
5398
5399         // Fix return value in case no callbacks were called
5400         if(first_loop){
5401                 if(mode == RUN_CALLBACKS_MODE_AND ||
5402                                 mode == RUN_CALLBACKS_MODE_AND_SC){
5403                         lua_pop(L, 1);
5404                         lua_pushboolean(L, true);
5405                 }
5406                 else if(mode == RUN_CALLBACKS_MODE_OR ||
5407                                 mode == RUN_CALLBACKS_MODE_OR_SC){
5408                         lua_pop(L, 1);
5409                         lua_pushboolean(L, false);
5410                 }
5411         }
5412 }
5413
5414 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5415                 const std::string &message)
5416 {
5417         realitycheck(L);
5418         assert(lua_checkstack(L, 20));
5419         StackUnroller stack_unroller(L);
5420
5421         // Get minetest.registered_on_chat_messages
5422         lua_getglobal(L, "minetest");
5423         lua_getfield(L, -1, "registered_on_chat_messages");
5424         // Call callbacks
5425         lua_pushstring(L, name.c_str());
5426         lua_pushstring(L, message.c_str());
5427         scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5428         bool ate = lua_toboolean(L, -1);
5429         return ate;
5430 }
5431
5432 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5433 {
5434         realitycheck(L);
5435         assert(lua_checkstack(L, 20));
5436         StackUnroller stack_unroller(L);
5437
5438         // Get minetest.registered_on_newplayers
5439         lua_getglobal(L, "minetest");
5440         lua_getfield(L, -1, "registered_on_newplayers");
5441         // Call callbacks
5442         objectref_get_or_create(L, player);
5443         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5444 }
5445
5446 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5447 {
5448         realitycheck(L);
5449         assert(lua_checkstack(L, 20));
5450         StackUnroller stack_unroller(L);
5451
5452         // Get minetest.registered_on_dieplayers
5453         lua_getglobal(L, "minetest");
5454         lua_getfield(L, -1, "registered_on_dieplayers");
5455         // Call callbacks
5456         objectref_get_or_create(L, player);
5457         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5458 }
5459
5460 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5461 {
5462         realitycheck(L);
5463         assert(lua_checkstack(L, 20));
5464         StackUnroller stack_unroller(L);
5465
5466         // Get minetest.registered_on_respawnplayers
5467         lua_getglobal(L, "minetest");
5468         lua_getfield(L, -1, "registered_on_respawnplayers");
5469         // Call callbacks
5470         objectref_get_or_create(L, player);
5471         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5472         bool positioning_handled_by_some = lua_toboolean(L, -1);
5473         return positioning_handled_by_some;
5474 }
5475
5476 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5477 {
5478         realitycheck(L);
5479         assert(lua_checkstack(L, 20));
5480         StackUnroller stack_unroller(L);
5481
5482         // Get minetest.registered_on_joinplayers
5483         lua_getglobal(L, "minetest");
5484         lua_getfield(L, -1, "registered_on_joinplayers");
5485         // Call callbacks
5486         objectref_get_or_create(L, player);
5487         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5488 }
5489
5490 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5491 {
5492         realitycheck(L);
5493         assert(lua_checkstack(L, 20));
5494         StackUnroller stack_unroller(L);
5495
5496         // Get minetest.registered_on_leaveplayers
5497         lua_getglobal(L, "minetest");
5498         lua_getfield(L, -1, "registered_on_leaveplayers");
5499         // Call callbacks
5500         objectref_get_or_create(L, player);
5501         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5502 }
5503
5504 static void get_auth_handler(lua_State *L)
5505 {
5506         lua_getglobal(L, "minetest");
5507         lua_getfield(L, -1, "registered_auth_handler");
5508         if(lua_isnil(L, -1)){
5509                 lua_pop(L, 1);
5510                 lua_getfield(L, -1, "builtin_auth_handler");
5511         }
5512         if(lua_type(L, -1) != LUA_TTABLE)
5513                 throw LuaError(L, "Authentication handler table not valid");
5514 }
5515
5516 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5517                 std::string *dst_password, std::set<std::string> *dst_privs)
5518 {
5519         realitycheck(L);
5520         assert(lua_checkstack(L, 20));
5521         StackUnroller stack_unroller(L);
5522         
5523         get_auth_handler(L);
5524         lua_getfield(L, -1, "get_auth");
5525         if(lua_type(L, -1) != LUA_TFUNCTION)
5526                 throw LuaError(L, "Authentication handler missing get_auth");
5527         lua_pushstring(L, playername.c_str());
5528         if(lua_pcall(L, 1, 1, 0))
5529                 script_error(L, "error: %s", lua_tostring(L, -1));
5530         
5531         // nil = login not allowed
5532         if(lua_isnil(L, -1))
5533                 return false;
5534         luaL_checktype(L, -1, LUA_TTABLE);
5535         
5536         std::string password;
5537         bool found = getstringfield(L, -1, "password", password);
5538         if(!found)
5539                 throw LuaError(L, "Authentication handler didn't return password");
5540         if(dst_password)
5541                 *dst_password = password;
5542
5543         lua_getfield(L, -1, "privileges");
5544         if(!lua_istable(L, -1))
5545                 throw LuaError(L,
5546                                 "Authentication handler didn't return privilege table");
5547         if(dst_privs)
5548                 read_privileges(L, -1, *dst_privs);
5549         lua_pop(L, 1);
5550         
5551         return true;
5552 }
5553
5554 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5555                 const std::string &password)
5556 {
5557         realitycheck(L);
5558         assert(lua_checkstack(L, 20));
5559         StackUnroller stack_unroller(L);
5560         
5561         get_auth_handler(L);
5562         lua_getfield(L, -1, "create_auth");
5563         if(lua_type(L, -1) != LUA_TFUNCTION)
5564                 throw LuaError(L, "Authentication handler missing create_auth");
5565         lua_pushstring(L, playername.c_str());
5566         lua_pushstring(L, password.c_str());
5567         if(lua_pcall(L, 2, 0, 0))
5568                 script_error(L, "error: %s", lua_tostring(L, -1));
5569 }
5570
5571 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5572                 const std::string &password)
5573 {
5574         realitycheck(L);
5575         assert(lua_checkstack(L, 20));
5576         StackUnroller stack_unroller(L);
5577         
5578         get_auth_handler(L);
5579         lua_getfield(L, -1, "set_password");
5580         if(lua_type(L, -1) != LUA_TFUNCTION)
5581                 throw LuaError(L, "Authentication handler missing set_password");
5582         lua_pushstring(L, playername.c_str());
5583         lua_pushstring(L, password.c_str());
5584         if(lua_pcall(L, 2, 1, 0))
5585                 script_error(L, "error: %s", lua_tostring(L, -1));
5586         return lua_toboolean(L, -1);
5587 }
5588
5589 /*
5590         player
5591 */
5592
5593 void scriptapi_on_player_receive_fields(lua_State *L, 
5594                 ServerActiveObject *player,
5595                 const std::string &formname,
5596                 const std::map<std::string, std::string> &fields)
5597 {
5598         realitycheck(L);
5599         assert(lua_checkstack(L, 20));
5600         StackUnroller stack_unroller(L);
5601
5602         // Get minetest.registered_on_chat_messages
5603         lua_getglobal(L, "minetest");
5604         lua_getfield(L, -1, "registered_on_player_receive_fields");
5605         // Call callbacks
5606         // param 1
5607         objectref_get_or_create(L, player);
5608         // param 2
5609         lua_pushstring(L, formname.c_str());
5610         // param 3
5611         lua_newtable(L);
5612         for(std::map<std::string, std::string>::const_iterator
5613                         i = fields.begin(); i != fields.end(); i++){
5614                 const std::string &name = i->first;
5615                 const std::string &value = i->second;
5616                 lua_pushstring(L, name.c_str());
5617                 lua_pushlstring(L, value.c_str(), value.size());
5618                 lua_settable(L, -3);
5619         }
5620         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5621 }
5622
5623 /*
5624         item callbacks and node callbacks
5625 */
5626
5627 // Retrieves minetest.registered_items[name][callbackname]
5628 // If that is nil or on error, return false and stack is unchanged
5629 // If that is a function, returns true and pushes the
5630 // function onto the stack
5631 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5632 // is tried instead so unknown items can still be manipulated to some degree
5633 static bool get_item_callback(lua_State *L,
5634                 const char *name, const char *callbackname)
5635 {
5636         lua_getglobal(L, "minetest");
5637         lua_getfield(L, -1, "registered_items");
5638         lua_remove(L, -2);
5639         luaL_checktype(L, -1, LUA_TTABLE);
5640         lua_getfield(L, -1, name);
5641         lua_remove(L, -2);
5642         // Should be a table
5643         if(lua_type(L, -1) != LUA_TTABLE)
5644         {
5645                 // Report error and clean up
5646                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5647                 lua_pop(L, 1);
5648
5649                 // Try minetest.nodedef_default instead
5650                 lua_getglobal(L, "minetest");
5651                 lua_getfield(L, -1, "nodedef_default");
5652                 lua_remove(L, -2);
5653                 luaL_checktype(L, -1, LUA_TTABLE);
5654         }
5655         lua_getfield(L, -1, callbackname);
5656         lua_remove(L, -2);
5657         // Should be a function or nil
5658         if(lua_type(L, -1) == LUA_TFUNCTION)
5659         {
5660                 return true;
5661         }
5662         else if(lua_isnil(L, -1))
5663         {
5664                 lua_pop(L, 1);
5665                 return false;
5666         }
5667         else
5668         {
5669                 errorstream<<"Item \""<<name<<"\" callback \""
5670                         <<callbackname<<" is not a function"<<std::endl;
5671                 lua_pop(L, 1);
5672                 return false;
5673         }
5674 }
5675
5676 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5677                 ServerActiveObject *dropper, v3f pos)
5678 {
5679         realitycheck(L);
5680         assert(lua_checkstack(L, 20));
5681         StackUnroller stack_unroller(L);
5682
5683         // Push callback function on stack
5684         if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5685                 return false;
5686
5687         // Call function
5688         LuaItemStack::create(L, item);
5689         objectref_get_or_create(L, dropper);
5690         pushFloatPos(L, pos);
5691         if(lua_pcall(L, 3, 1, 0))
5692                 script_error(L, "error: %s", lua_tostring(L, -1));
5693         if(!lua_isnil(L, -1))
5694                 item = read_item(L, -1);
5695         return true;
5696 }
5697
5698 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5699                 ServerActiveObject *placer, const PointedThing &pointed)
5700 {
5701         realitycheck(L);
5702         assert(lua_checkstack(L, 20));
5703         StackUnroller stack_unroller(L);
5704
5705         // Push callback function on stack
5706         if(!get_item_callback(L, item.name.c_str(), "on_place"))
5707                 return false;
5708
5709         // Call function
5710         LuaItemStack::create(L, item);
5711         objectref_get_or_create(L, placer);
5712         push_pointed_thing(L, pointed);
5713         if(lua_pcall(L, 3, 1, 0))
5714                 script_error(L, "error: %s", lua_tostring(L, -1));
5715         if(!lua_isnil(L, -1))
5716                 item = read_item(L, -1);
5717         return true;
5718 }
5719
5720 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5721                 ServerActiveObject *user, const PointedThing &pointed)
5722 {
5723         realitycheck(L);
5724         assert(lua_checkstack(L, 20));
5725         StackUnroller stack_unroller(L);
5726
5727         // Push callback function on stack
5728         if(!get_item_callback(L, item.name.c_str(), "on_use"))
5729                 return false;
5730
5731         // Call function
5732         LuaItemStack::create(L, item);
5733         objectref_get_or_create(L, user);
5734         push_pointed_thing(L, pointed);
5735         if(lua_pcall(L, 3, 1, 0))
5736                 script_error(L, "error: %s", lua_tostring(L, -1));
5737         if(!lua_isnil(L, -1))
5738                 item = read_item(L, -1);
5739         return true;
5740 }
5741
5742 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5743                 ServerActiveObject *puncher)
5744 {
5745         realitycheck(L);
5746         assert(lua_checkstack(L, 20));
5747         StackUnroller stack_unroller(L);
5748
5749         INodeDefManager *ndef = get_server(L)->ndef();
5750
5751         // Push callback function on stack
5752         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5753                 return false;
5754
5755         // Call function
5756         push_v3s16(L, p);
5757         pushnode(L, node, ndef);
5758         objectref_get_or_create(L, puncher);
5759         if(lua_pcall(L, 3, 0, 0))
5760                 script_error(L, "error: %s", lua_tostring(L, -1));
5761         return true;
5762 }
5763
5764 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5765                 ServerActiveObject *digger)
5766 {
5767         realitycheck(L);
5768         assert(lua_checkstack(L, 20));
5769         StackUnroller stack_unroller(L);
5770
5771         INodeDefManager *ndef = get_server(L)->ndef();
5772
5773         // Push callback function on stack
5774         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5775                 return false;
5776
5777         // Call function
5778         push_v3s16(L, p);
5779         pushnode(L, node, ndef);
5780         objectref_get_or_create(L, digger);
5781         if(lua_pcall(L, 3, 0, 0))
5782                 script_error(L, "error: %s", lua_tostring(L, -1));
5783         return true;
5784 }
5785
5786 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5787 {
5788         realitycheck(L);
5789         assert(lua_checkstack(L, 20));
5790         StackUnroller stack_unroller(L);
5791
5792         INodeDefManager *ndef = get_server(L)->ndef();
5793
5794         // Push callback function on stack
5795         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5796                 return;
5797
5798         // Call function
5799         push_v3s16(L, p);
5800         if(lua_pcall(L, 1, 0, 0))
5801                 script_error(L, "error: %s", lua_tostring(L, -1));
5802 }
5803
5804 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5805 {
5806         realitycheck(L);
5807         assert(lua_checkstack(L, 20));
5808         StackUnroller stack_unroller(L);
5809
5810         INodeDefManager *ndef = get_server(L)->ndef();
5811
5812         // Push callback function on stack
5813         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5814                 return;
5815
5816         // Call function
5817         push_v3s16(L, p);
5818         if(lua_pcall(L, 1, 0, 0))
5819                 script_error(L, "error: %s", lua_tostring(L, -1));
5820 }
5821
5822 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5823 {
5824         realitycheck(L);
5825         assert(lua_checkstack(L, 20));
5826         StackUnroller stack_unroller(L);
5827
5828         INodeDefManager *ndef = get_server(L)->ndef();
5829
5830         // Push callback function on stack
5831         if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5832                 return;
5833
5834         // Call function
5835         push_v3s16(L, p);
5836         pushnode(L, node, ndef);
5837         if(lua_pcall(L, 2, 0, 0))
5838                 script_error(L, "error: %s", lua_tostring(L, -1));
5839 }
5840
5841 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5842 {
5843         realitycheck(L);
5844         assert(lua_checkstack(L, 20));
5845         StackUnroller stack_unroller(L);
5846
5847         INodeDefManager *ndef = get_server(L)->ndef();
5848
5849         // Push callback function on stack
5850         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5851                 return false;
5852
5853         // Call function
5854         push_v3s16(L, p);
5855         lua_pushnumber(L,dtime);
5856         if(lua_pcall(L, 2, 1, 0))
5857                 script_error(L, "error: %s", lua_tostring(L, -1));
5858         if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5859                 return true;
5860         
5861         return false;
5862 }
5863
5864 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5865                 const std::string &formname,
5866                 const std::map<std::string, std::string> &fields,
5867                 ServerActiveObject *sender)
5868 {
5869         realitycheck(L);
5870         assert(lua_checkstack(L, 20));
5871         StackUnroller stack_unroller(L);
5872
5873         INodeDefManager *ndef = get_server(L)->ndef();
5874         
5875         // If node doesn't exist, we don't know what callback to call
5876         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5877         if(node.getContent() == CONTENT_IGNORE)
5878                 return;
5879
5880         // Push callback function on stack
5881         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5882                 return;
5883
5884         // Call function
5885         // param 1
5886         push_v3s16(L, p);
5887         // param 2
5888         lua_pushstring(L, formname.c_str());
5889         // param 3
5890         lua_newtable(L);
5891         for(std::map<std::string, std::string>::const_iterator
5892                         i = fields.begin(); i != fields.end(); i++){
5893                 const std::string &name = i->first;
5894                 const std::string &value = i->second;
5895                 lua_pushstring(L, name.c_str());
5896                 lua_pushlstring(L, value.c_str(), value.size());
5897                 lua_settable(L, -3);
5898         }
5899         // param 4
5900         objectref_get_or_create(L, sender);
5901         if(lua_pcall(L, 4, 0, 0))
5902                 script_error(L, "error: %s", lua_tostring(L, -1));
5903 }
5904
5905 /*
5906         Node metadata inventory callbacks
5907 */
5908
5909 // Return number of accepted items to be moved
5910 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5911                 const std::string &from_list, int from_index,
5912                 const std::string &to_list, int to_index,
5913                 int count, ServerActiveObject *player)
5914 {
5915         realitycheck(L);
5916         assert(lua_checkstack(L, 20));
5917         StackUnroller stack_unroller(L);
5918
5919         INodeDefManager *ndef = get_server(L)->ndef();
5920
5921         // If node doesn't exist, we don't know what callback to call
5922         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5923         if(node.getContent() == CONTENT_IGNORE)
5924                 return 0;
5925
5926         // Push callback function on stack
5927         if(!get_item_callback(L, ndef->get(node).name.c_str(),
5928                         "allow_metadata_inventory_move"))
5929                 return count;
5930
5931         // function(pos, from_list, from_index, to_list, to_index, count, player)
5932         // pos
5933         push_v3s16(L, p);
5934         // from_list
5935         lua_pushstring(L, from_list.c_str());
5936         // from_index
5937         lua_pushinteger(L, from_index + 1);
5938         // to_list
5939         lua_pushstring(L, to_list.c_str());
5940         // to_index
5941         lua_pushinteger(L, to_index + 1);
5942         // count
5943         lua_pushinteger(L, count);
5944         // player
5945         objectref_get_or_create(L, player);
5946         if(lua_pcall(L, 7, 1, 0))
5947                 script_error(L, "error: %s", lua_tostring(L, -1));
5948         if(!lua_isnumber(L, -1))
5949                 throw LuaError(L, "allow_metadata_inventory_move should return a number");
5950         return luaL_checkinteger(L, -1);
5951 }
5952
5953 // Return number of accepted items to be put
5954 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
5955                 const std::string &listname, int index, ItemStack &stack,
5956                 ServerActiveObject *player)
5957 {
5958         realitycheck(L);
5959         assert(lua_checkstack(L, 20));
5960         StackUnroller stack_unroller(L);
5961
5962         INodeDefManager *ndef = get_server(L)->ndef();
5963
5964         // If node doesn't exist, we don't know what callback to call
5965         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5966         if(node.getContent() == CONTENT_IGNORE)
5967                 return 0;
5968
5969         // Push callback function on stack
5970         if(!get_item_callback(L, ndef->get(node).name.c_str(),
5971                         "allow_metadata_inventory_put"))
5972                 return stack.count;
5973
5974         // Call function(pos, listname, index, stack, player)
5975         // pos
5976         push_v3s16(L, p);
5977         // listname
5978         lua_pushstring(L, listname.c_str());
5979         // index
5980         lua_pushinteger(L, index + 1);
5981         // stack
5982         LuaItemStack::create(L, stack);
5983         // player
5984         objectref_get_or_create(L, player);
5985         if(lua_pcall(L, 5, 1, 0))
5986                 script_error(L, "error: %s", lua_tostring(L, -1));
5987         if(!lua_isnumber(L, -1))
5988                 throw LuaError(L, "allow_metadata_inventory_put should return a number");
5989         return luaL_checkinteger(L, -1);
5990 }
5991
5992 // Return number of accepted items to be taken
5993 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
5994                 const std::string &listname, int index, ItemStack &stack,
5995                 ServerActiveObject *player)
5996 {
5997         realitycheck(L);
5998         assert(lua_checkstack(L, 20));
5999         StackUnroller stack_unroller(L);
6000
6001         INodeDefManager *ndef = get_server(L)->ndef();
6002
6003         // If node doesn't exist, we don't know what callback to call
6004         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6005         if(node.getContent() == CONTENT_IGNORE)
6006                 return 0;
6007
6008         // Push callback function on stack
6009         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6010                         "allow_metadata_inventory_take"))
6011                 return stack.count;
6012
6013         // Call function(pos, listname, index, count, player)
6014         // pos
6015         push_v3s16(L, p);
6016         // listname
6017         lua_pushstring(L, listname.c_str());
6018         // index
6019         lua_pushinteger(L, index + 1);
6020         // stack
6021         LuaItemStack::create(L, stack);
6022         // player
6023         objectref_get_or_create(L, player);
6024         if(lua_pcall(L, 5, 1, 0))
6025                 script_error(L, "error: %s", lua_tostring(L, -1));
6026         if(!lua_isnumber(L, -1))
6027                 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6028         return luaL_checkinteger(L, -1);
6029 }
6030
6031 // Report moved items
6032 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6033                 const std::string &from_list, int from_index,
6034                 const std::string &to_list, int to_index,
6035                 int count, ServerActiveObject *player)
6036 {
6037         realitycheck(L);
6038         assert(lua_checkstack(L, 20));
6039         StackUnroller stack_unroller(L);
6040
6041         INodeDefManager *ndef = get_server(L)->ndef();
6042
6043         // If node doesn't exist, we don't know what callback to call
6044         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6045         if(node.getContent() == CONTENT_IGNORE)
6046                 return;
6047
6048         // Push callback function on stack
6049         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6050                         "on_metadata_inventory_move"))
6051                 return;
6052
6053         // function(pos, from_list, from_index, to_list, to_index, count, player)
6054         // pos
6055         push_v3s16(L, p);
6056         // from_list
6057         lua_pushstring(L, from_list.c_str());
6058         // from_index
6059         lua_pushinteger(L, from_index + 1);
6060         // to_list
6061         lua_pushstring(L, to_list.c_str());
6062         // to_index
6063         lua_pushinteger(L, to_index + 1);
6064         // count
6065         lua_pushinteger(L, count);
6066         // player
6067         objectref_get_or_create(L, player);
6068         if(lua_pcall(L, 7, 0, 0))
6069                 script_error(L, "error: %s", lua_tostring(L, -1));
6070 }
6071
6072 // Report put items
6073 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6074                 const std::string &listname, int index, ItemStack &stack,
6075                 ServerActiveObject *player)
6076 {
6077         realitycheck(L);
6078         assert(lua_checkstack(L, 20));
6079         StackUnroller stack_unroller(L);
6080
6081         INodeDefManager *ndef = get_server(L)->ndef();
6082
6083         // If node doesn't exist, we don't know what callback to call
6084         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6085         if(node.getContent() == CONTENT_IGNORE)
6086                 return;
6087
6088         // Push callback function on stack
6089         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6090                         "on_metadata_inventory_put"))
6091                 return;
6092
6093         // Call function(pos, listname, index, stack, player)
6094         // pos
6095         push_v3s16(L, p);
6096         // listname
6097         lua_pushstring(L, listname.c_str());
6098         // index
6099         lua_pushinteger(L, index + 1);
6100         // stack
6101         LuaItemStack::create(L, stack);
6102         // player
6103         objectref_get_or_create(L, player);
6104         if(lua_pcall(L, 5, 0, 0))
6105                 script_error(L, "error: %s", lua_tostring(L, -1));
6106 }
6107
6108 // Report taken items
6109 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6110                 const std::string &listname, int index, ItemStack &stack,
6111                 ServerActiveObject *player)
6112 {
6113         realitycheck(L);
6114         assert(lua_checkstack(L, 20));
6115         StackUnroller stack_unroller(L);
6116
6117         INodeDefManager *ndef = get_server(L)->ndef();
6118
6119         // If node doesn't exist, we don't know what callback to call
6120         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6121         if(node.getContent() == CONTENT_IGNORE)
6122                 return;
6123
6124         // Push callback function on stack
6125         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6126                         "on_metadata_inventory_take"))
6127                 return;
6128
6129         // Call function(pos, listname, index, stack, player)
6130         // pos
6131         push_v3s16(L, p);
6132         // listname
6133         lua_pushstring(L, listname.c_str());
6134         // index
6135         lua_pushinteger(L, index + 1);
6136         // stack
6137         LuaItemStack::create(L, stack);
6138         // player
6139         objectref_get_or_create(L, player);
6140         if(lua_pcall(L, 5, 0, 0))
6141                 script_error(L, "error: %s", lua_tostring(L, -1));
6142 }
6143
6144 /*
6145         Detached inventory callbacks
6146 */
6147
6148 // Retrieves minetest.detached_inventories[name][callbackname]
6149 // If that is nil or on error, return false and stack is unchanged
6150 // If that is a function, returns true and pushes the
6151 // function onto the stack
6152 static bool get_detached_inventory_callback(lua_State *L,
6153                 const std::string &name, const char *callbackname)
6154 {
6155         lua_getglobal(L, "minetest");
6156         lua_getfield(L, -1, "detached_inventories");
6157         lua_remove(L, -2);
6158         luaL_checktype(L, -1, LUA_TTABLE);
6159         lua_getfield(L, -1, name.c_str());
6160         lua_remove(L, -2);
6161         // Should be a table
6162         if(lua_type(L, -1) != LUA_TTABLE)
6163         {
6164                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6165                 lua_pop(L, 1);
6166                 return false;
6167         }
6168         lua_getfield(L, -1, callbackname);
6169         lua_remove(L, -2);
6170         // Should be a function or nil
6171         if(lua_type(L, -1) == LUA_TFUNCTION)
6172         {
6173                 return true;
6174         }
6175         else if(lua_isnil(L, -1))
6176         {
6177                 lua_pop(L, 1);
6178                 return false;
6179         }
6180         else
6181         {
6182                 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6183                         <<callbackname<<"\" is not a function"<<std::endl;
6184                 lua_pop(L, 1);
6185                 return false;
6186         }
6187 }
6188
6189 // Return number of accepted items to be moved
6190 int scriptapi_detached_inventory_allow_move(lua_State *L,
6191                 const std::string &name,
6192                 const std::string &from_list, int from_index,
6193                 const std::string &to_list, int to_index,
6194                 int count, ServerActiveObject *player)
6195 {
6196         realitycheck(L);
6197         assert(lua_checkstack(L, 20));
6198         StackUnroller stack_unroller(L);
6199
6200         // Push callback function on stack
6201         if(!get_detached_inventory_callback(L, name, "allow_move"))
6202                 return count;
6203
6204         // function(inv, from_list, from_index, to_list, to_index, count, player)
6205         // inv
6206         InventoryLocation loc;
6207         loc.setDetached(name);
6208         InvRef::create(L, loc);
6209         // from_list
6210         lua_pushstring(L, from_list.c_str());
6211         // from_index
6212         lua_pushinteger(L, from_index + 1);
6213         // to_list
6214         lua_pushstring(L, to_list.c_str());
6215         // to_index
6216         lua_pushinteger(L, to_index + 1);
6217         // count
6218         lua_pushinteger(L, count);
6219         // player
6220         objectref_get_or_create(L, player);
6221         if(lua_pcall(L, 7, 1, 0))
6222                 script_error(L, "error: %s", lua_tostring(L, -1));
6223         if(!lua_isnumber(L, -1))
6224                 throw LuaError(L, "allow_move should return a number");
6225         return luaL_checkinteger(L, -1);
6226 }
6227
6228 // Return number of accepted items to be put
6229 int scriptapi_detached_inventory_allow_put(lua_State *L,
6230                 const std::string &name,
6231                 const std::string &listname, int index, ItemStack &stack,
6232                 ServerActiveObject *player)
6233 {
6234         realitycheck(L);
6235         assert(lua_checkstack(L, 20));
6236         StackUnroller stack_unroller(L);
6237
6238         // Push callback function on stack
6239         if(!get_detached_inventory_callback(L, name, "allow_put"))
6240                 return stack.count; // All will be accepted
6241
6242         // Call function(inv, listname, index, stack, player)
6243         // inv
6244         InventoryLocation loc;
6245         loc.setDetached(name);
6246         InvRef::create(L, loc);
6247         // listname
6248         lua_pushstring(L, listname.c_str());
6249         // index
6250         lua_pushinteger(L, index + 1);
6251         // stack
6252         LuaItemStack::create(L, stack);
6253         // player
6254         objectref_get_or_create(L, player);
6255         if(lua_pcall(L, 5, 1, 0))
6256                 script_error(L, "error: %s", lua_tostring(L, -1));
6257         if(!lua_isnumber(L, -1))
6258                 throw LuaError(L, "allow_put should return a number");
6259         return luaL_checkinteger(L, -1);
6260 }
6261
6262 // Return number of accepted items to be taken
6263 int scriptapi_detached_inventory_allow_take(lua_State *L,
6264                 const std::string &name,
6265                 const std::string &listname, int index, ItemStack &stack,
6266                 ServerActiveObject *player)
6267 {
6268         realitycheck(L);
6269         assert(lua_checkstack(L, 20));
6270         StackUnroller stack_unroller(L);
6271
6272         // Push callback function on stack
6273         if(!get_detached_inventory_callback(L, name, "allow_take"))
6274                 return stack.count; // All will be accepted
6275
6276         // Call function(inv, listname, index, stack, player)
6277         // inv
6278         InventoryLocation loc;
6279         loc.setDetached(name);
6280         InvRef::create(L, loc);
6281         // listname
6282         lua_pushstring(L, listname.c_str());
6283         // index
6284         lua_pushinteger(L, index + 1);
6285         // stack
6286         LuaItemStack::create(L, stack);
6287         // player
6288         objectref_get_or_create(L, player);
6289         if(lua_pcall(L, 5, 1, 0))
6290                 script_error(L, "error: %s", lua_tostring(L, -1));
6291         if(!lua_isnumber(L, -1))
6292                 throw LuaError(L, "allow_take should return a number");
6293         return luaL_checkinteger(L, -1);
6294 }
6295
6296 // Report moved items
6297 void scriptapi_detached_inventory_on_move(lua_State *L,
6298                 const std::string &name,
6299                 const std::string &from_list, int from_index,
6300                 const std::string &to_list, int to_index,
6301                 int count, ServerActiveObject *player)
6302 {
6303         realitycheck(L);
6304         assert(lua_checkstack(L, 20));
6305         StackUnroller stack_unroller(L);
6306
6307         // Push callback function on stack
6308         if(!get_detached_inventory_callback(L, name, "on_move"))
6309                 return;
6310
6311         // function(inv, from_list, from_index, to_list, to_index, count, player)
6312         // inv
6313         InventoryLocation loc;
6314         loc.setDetached(name);
6315         InvRef::create(L, loc);
6316         // from_list
6317         lua_pushstring(L, from_list.c_str());
6318         // from_index
6319         lua_pushinteger(L, from_index + 1);
6320         // to_list
6321         lua_pushstring(L, to_list.c_str());
6322         // to_index
6323         lua_pushinteger(L, to_index + 1);
6324         // count
6325         lua_pushinteger(L, count);
6326         // player
6327         objectref_get_or_create(L, player);
6328         if(lua_pcall(L, 7, 0, 0))
6329                 script_error(L, "error: %s", lua_tostring(L, -1));
6330 }
6331
6332 // Report put items
6333 void scriptapi_detached_inventory_on_put(lua_State *L,
6334                 const std::string &name,
6335                 const std::string &listname, int index, ItemStack &stack,
6336                 ServerActiveObject *player)
6337 {
6338         realitycheck(L);
6339         assert(lua_checkstack(L, 20));
6340         StackUnroller stack_unroller(L);
6341
6342         // Push callback function on stack
6343         if(!get_detached_inventory_callback(L, name, "on_put"))
6344                 return;
6345
6346         // Call function(inv, listname, index, stack, player)
6347         // inv
6348         InventoryLocation loc;
6349         loc.setDetached(name);
6350         InvRef::create(L, loc);
6351         // listname
6352         lua_pushstring(L, listname.c_str());
6353         // index
6354         lua_pushinteger(L, index + 1);
6355         // stack
6356         LuaItemStack::create(L, stack);
6357         // player
6358         objectref_get_or_create(L, player);
6359         if(lua_pcall(L, 5, 0, 0))
6360                 script_error(L, "error: %s", lua_tostring(L, -1));
6361 }
6362
6363 // Report taken items
6364 void scriptapi_detached_inventory_on_take(lua_State *L,
6365                 const std::string &name,
6366                 const std::string &listname, int index, ItemStack &stack,
6367                 ServerActiveObject *player)
6368 {
6369         realitycheck(L);
6370         assert(lua_checkstack(L, 20));
6371         StackUnroller stack_unroller(L);
6372
6373         // Push callback function on stack
6374         if(!get_detached_inventory_callback(L, name, "on_take"))
6375                 return;
6376
6377         // Call function(inv, listname, index, stack, player)
6378         // inv
6379         InventoryLocation loc;
6380         loc.setDetached(name);
6381         InvRef::create(L, loc);
6382         // listname
6383         lua_pushstring(L, listname.c_str());
6384         // index
6385         lua_pushinteger(L, index + 1);
6386         // stack
6387         LuaItemStack::create(L, stack);
6388         // player
6389         objectref_get_or_create(L, player);
6390         if(lua_pcall(L, 5, 0, 0))
6391                 script_error(L, "error: %s", lua_tostring(L, -1));
6392 }
6393
6394 /*
6395         environment
6396 */
6397
6398 void scriptapi_environment_step(lua_State *L, float dtime)
6399 {
6400         realitycheck(L);
6401         assert(lua_checkstack(L, 20));
6402         //infostream<<"scriptapi_environment_step"<<std::endl;
6403         StackUnroller stack_unroller(L);
6404
6405         // Get minetest.registered_globalsteps
6406         lua_getglobal(L, "minetest");
6407         lua_getfield(L, -1, "registered_globalsteps");
6408         // Call callbacks
6409         lua_pushnumber(L, dtime);
6410         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6411 }
6412
6413 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6414                 u32 blockseed)
6415 {
6416         realitycheck(L);
6417         assert(lua_checkstack(L, 20));
6418         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6419         StackUnroller stack_unroller(L);
6420
6421         // Get minetest.registered_on_generateds
6422         lua_getglobal(L, "minetest");
6423         lua_getfield(L, -1, "registered_on_generateds");
6424         // Call callbacks
6425         push_v3s16(L, minp);
6426         push_v3s16(L, maxp);
6427         lua_pushnumber(L, blockseed);
6428         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6429 }
6430
6431 /*
6432         luaentity
6433 */
6434
6435 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6436 {
6437         realitycheck(L);
6438         assert(lua_checkstack(L, 20));
6439         verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6440                         <<name<<"\""<<std::endl;
6441         StackUnroller stack_unroller(L);
6442         
6443         // Get minetest.registered_entities[name]
6444         lua_getglobal(L, "minetest");
6445         lua_getfield(L, -1, "registered_entities");
6446         luaL_checktype(L, -1, LUA_TTABLE);
6447         lua_pushstring(L, name);
6448         lua_gettable(L, -2);
6449         // Should be a table, which we will use as a prototype
6450         //luaL_checktype(L, -1, LUA_TTABLE);
6451         if(lua_type(L, -1) != LUA_TTABLE){
6452                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6453                 return false;
6454         }
6455         int prototype_table = lua_gettop(L);
6456         //dump2(L, "prototype_table");
6457         
6458         // Create entity object
6459         lua_newtable(L);
6460         int object = lua_gettop(L);
6461
6462         // Set object metatable
6463         lua_pushvalue(L, prototype_table);
6464         lua_setmetatable(L, -2);
6465         
6466         // Add object reference
6467         // This should be userdata with metatable ObjectRef
6468         objectref_get(L, id);
6469         luaL_checktype(L, -1, LUA_TUSERDATA);
6470         if(!luaL_checkudata(L, -1, "ObjectRef"))
6471                 luaL_typerror(L, -1, "ObjectRef");
6472         lua_setfield(L, -2, "object");
6473
6474         // minetest.luaentities[id] = object
6475         lua_getglobal(L, "minetest");
6476         lua_getfield(L, -1, "luaentities");
6477         luaL_checktype(L, -1, LUA_TTABLE);
6478         lua_pushnumber(L, id); // Push id
6479         lua_pushvalue(L, object); // Copy object to top of stack
6480         lua_settable(L, -3);
6481         
6482         return true;
6483 }
6484
6485 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6486                 const std::string &staticdata, u32 dtime_s)
6487 {
6488         realitycheck(L);
6489         assert(lua_checkstack(L, 20));
6490         verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6491         StackUnroller stack_unroller(L);
6492         
6493         // Get minetest.luaentities[id]
6494         luaentity_get(L, id);
6495         int object = lua_gettop(L);
6496         
6497         // Get on_activate function
6498         lua_pushvalue(L, object);
6499         lua_getfield(L, -1, "on_activate");
6500         if(!lua_isnil(L, -1)){
6501                 luaL_checktype(L, -1, LUA_TFUNCTION);
6502                 lua_pushvalue(L, object); // self
6503                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6504                 lua_pushinteger(L, dtime_s);
6505                 // Call with 3 arguments, 0 results
6506                 if(lua_pcall(L, 3, 0, 0))
6507                         script_error(L, "error running function on_activate: %s\n",
6508                                         lua_tostring(L, -1));
6509         }
6510 }
6511
6512 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6513 {
6514         realitycheck(L);
6515         assert(lua_checkstack(L, 20));
6516         verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6517
6518         // Get minetest.luaentities table
6519         lua_getglobal(L, "minetest");
6520         lua_getfield(L, -1, "luaentities");
6521         luaL_checktype(L, -1, LUA_TTABLE);
6522         int objectstable = lua_gettop(L);
6523         
6524         // Set luaentities[id] = nil
6525         lua_pushnumber(L, id); // Push id
6526         lua_pushnil(L);
6527         lua_settable(L, objectstable);
6528         
6529         lua_pop(L, 2); // pop luaentities, minetest
6530 }
6531
6532 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6533 {
6534         realitycheck(L);
6535         assert(lua_checkstack(L, 20));
6536         //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6537         StackUnroller stack_unroller(L);
6538
6539         // Get minetest.luaentities[id]
6540         luaentity_get(L, id);
6541         int object = lua_gettop(L);
6542         
6543         // Get get_staticdata function
6544         lua_pushvalue(L, object);
6545         lua_getfield(L, -1, "get_staticdata");
6546         if(lua_isnil(L, -1))
6547                 return "";
6548         
6549         luaL_checktype(L, -1, LUA_TFUNCTION);
6550         lua_pushvalue(L, object); // self
6551         // Call with 1 arguments, 1 results
6552         if(lua_pcall(L, 1, 1, 0))
6553                 script_error(L, "error running function get_staticdata: %s\n",
6554                                 lua_tostring(L, -1));
6555         
6556         size_t len=0;
6557         const char *s = lua_tolstring(L, -1, &len);
6558         return std::string(s, len);
6559 }
6560
6561 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6562                 ObjectProperties *prop)
6563 {
6564         realitycheck(L);
6565         assert(lua_checkstack(L, 20));
6566         //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6567         StackUnroller stack_unroller(L);
6568
6569         // Get minetest.luaentities[id]
6570         luaentity_get(L, id);
6571         //int object = lua_gettop(L);
6572
6573         // Set default values that differ from ObjectProperties defaults
6574         prop->hp_max = 10;
6575         
6576         /* Read stuff */
6577         
6578         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6579
6580         getboolfield(L, -1, "physical", prop->physical);
6581
6582         getfloatfield(L, -1, "weight", prop->weight);
6583
6584         lua_getfield(L, -1, "collisionbox");
6585         if(lua_istable(L, -1))
6586                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6587         lua_pop(L, 1);
6588
6589         getstringfield(L, -1, "visual", prop->visual);
6590         
6591         // Deprecated: read object properties directly
6592         read_object_properties(L, -1, prop);
6593         
6594         // Read initial_properties
6595         lua_getfield(L, -1, "initial_properties");
6596         read_object_properties(L, -1, prop);
6597         lua_pop(L, 1);
6598 }
6599
6600 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6601 {
6602         realitycheck(L);
6603         assert(lua_checkstack(L, 20));
6604         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6605         StackUnroller stack_unroller(L);
6606
6607         // Get minetest.luaentities[id]
6608         luaentity_get(L, id);
6609         int object = lua_gettop(L);
6610         // State: object is at top of stack
6611         // Get step function
6612         lua_getfield(L, -1, "on_step");
6613         if(lua_isnil(L, -1))
6614                 return;
6615         luaL_checktype(L, -1, LUA_TFUNCTION);
6616         lua_pushvalue(L, object); // self
6617         lua_pushnumber(L, dtime); // dtime
6618         // Call with 2 arguments, 0 results
6619         if(lua_pcall(L, 2, 0, 0))
6620                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6621 }
6622
6623 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6624 //                       tool_capabilities, direction)
6625 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6626                 ServerActiveObject *puncher, float time_from_last_punch,
6627                 const ToolCapabilities *toolcap, v3f dir)
6628 {
6629         realitycheck(L);
6630         assert(lua_checkstack(L, 20));
6631         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6632         StackUnroller stack_unroller(L);
6633
6634         // Get minetest.luaentities[id]
6635         luaentity_get(L, id);
6636         int object = lua_gettop(L);
6637         // State: object is at top of stack
6638         // Get function
6639         lua_getfield(L, -1, "on_punch");
6640         if(lua_isnil(L, -1))
6641                 return;
6642         luaL_checktype(L, -1, LUA_TFUNCTION);
6643         lua_pushvalue(L, object); // self
6644         objectref_get_or_create(L, puncher); // Clicker reference
6645         lua_pushnumber(L, time_from_last_punch);
6646         push_tool_capabilities(L, *toolcap);
6647         push_v3f(L, dir);
6648         // Call with 5 arguments, 0 results
6649         if(lua_pcall(L, 5, 0, 0))
6650                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6651 }
6652
6653 // Calls entity:on_rightclick(ObjectRef clicker)
6654 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6655                 ServerActiveObject *clicker)
6656 {
6657         realitycheck(L);
6658         assert(lua_checkstack(L, 20));
6659         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6660         StackUnroller stack_unroller(L);
6661
6662         // Get minetest.luaentities[id]
6663         luaentity_get(L, id);
6664         int object = lua_gettop(L);
6665         // State: object is at top of stack
6666         // Get function
6667         lua_getfield(L, -1, "on_rightclick");
6668         if(lua_isnil(L, -1))
6669                 return;
6670         luaL_checktype(L, -1, LUA_TFUNCTION);
6671         lua_pushvalue(L, object); // self
6672         objectref_get_or_create(L, clicker); // Clicker reference
6673         // Call with 2 arguments, 0 results
6674         if(lua_pcall(L, 2, 0, 0))
6675                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
6676 }
6677