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