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