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