]> git.lizzy.rs Git - minetest.git/blob - src/scriptapi.cpp
Add InvRef:get_location()
[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         // get_location() -> location (like minetest.get_inventory(location))
2053         static int l_get_location(lua_State *L)
2054         {
2055                 InvRef *ref = checkobject(L, 1);
2056                 const InventoryLocation &loc = ref->m_loc;
2057                 switch(loc.type){
2058                 case InventoryLocation::PLAYER:
2059                         lua_newtable(L);
2060                         lua_pushstring(L, "player");
2061                         lua_setfield(L, -2, "type");
2062                         lua_pushstring(L, loc.name.c_str());
2063                         lua_setfield(L, -2, "name");
2064                         return 1;
2065                 case InventoryLocation::NODEMETA:
2066                         lua_newtable(L);
2067                         lua_pushstring(L, "nodemeta");
2068                         lua_setfield(L, -2, "type");
2069                         push_v3s16(L, loc.p);
2070                         lua_setfield(L, -2, "name");
2071                         return 1;
2072                 case InventoryLocation::DETACHED:
2073                         lua_newtable(L);
2074                         lua_pushstring(L, "detached");
2075                         lua_setfield(L, -2, "type");
2076                         lua_pushstring(L, loc.name.c_str());
2077                         lua_setfield(L, -2, "name");
2078                         return 1;
2079                 case InventoryLocation::UNDEFINED:
2080                 case InventoryLocation::CURRENT_PLAYER:
2081                         break;
2082                 }
2083                 lua_newtable(L);
2084                 lua_pushstring(L, "undefined");
2085                 lua_setfield(L, -2, "type");
2086                 return 1;
2087         }
2088
2089 public:
2090         InvRef(const InventoryLocation &loc):
2091                 m_loc(loc)
2092         {
2093         }
2094
2095         ~InvRef()
2096         {
2097         }
2098
2099         // Creates an InvRef and leaves it on top of stack
2100         // Not callable from Lua; all references are created on the C side.
2101         static void create(lua_State *L, const InventoryLocation &loc)
2102         {
2103                 InvRef *o = new InvRef(loc);
2104                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2105                 luaL_getmetatable(L, className);
2106                 lua_setmetatable(L, -2);
2107         }
2108         static void createPlayer(lua_State *L, Player *player)
2109         {
2110                 InventoryLocation loc;
2111                 loc.setPlayer(player->getName());
2112                 create(L, loc);
2113         }
2114         static void createNodeMeta(lua_State *L, v3s16 p)
2115         {
2116                 InventoryLocation loc;
2117                 loc.setNodeMeta(p);
2118                 create(L, loc);
2119         }
2120
2121         static void Register(lua_State *L)
2122         {
2123                 lua_newtable(L);
2124                 int methodtable = lua_gettop(L);
2125                 luaL_newmetatable(L, className);
2126                 int metatable = lua_gettop(L);
2127
2128                 lua_pushliteral(L, "__metatable");
2129                 lua_pushvalue(L, methodtable);
2130                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2131
2132                 lua_pushliteral(L, "__index");
2133                 lua_pushvalue(L, methodtable);
2134                 lua_settable(L, metatable);
2135
2136                 lua_pushliteral(L, "__gc");
2137                 lua_pushcfunction(L, gc_object);
2138                 lua_settable(L, metatable);
2139
2140                 lua_pop(L, 1);  // drop metatable
2141
2142                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2143                 lua_pop(L, 1);  // drop methodtable
2144
2145                 // Cannot be created from Lua
2146                 //lua_register(L, className, create_object);
2147         }
2148 };
2149 const char InvRef::className[] = "InvRef";
2150 const luaL_reg InvRef::methods[] = {
2151         method(InvRef, is_empty),
2152         method(InvRef, get_size),
2153         method(InvRef, set_size),
2154         method(InvRef, get_width),
2155         method(InvRef, set_width),
2156         method(InvRef, get_stack),
2157         method(InvRef, set_stack),
2158         method(InvRef, get_list),
2159         method(InvRef, set_list),
2160         method(InvRef, add_item),
2161         method(InvRef, room_for_item),
2162         method(InvRef, contains_item),
2163         method(InvRef, remove_item),
2164         method(InvRef, get_location),
2165         {0,0}
2166 };
2167
2168 /*
2169         NodeMetaRef
2170 */
2171
2172 class NodeMetaRef
2173 {
2174 private:
2175         v3s16 m_p;
2176         ServerEnvironment *m_env;
2177
2178         static const char className[];
2179         static const luaL_reg methods[];
2180
2181         static NodeMetaRef *checkobject(lua_State *L, int narg)
2182         {
2183                 luaL_checktype(L, narg, LUA_TUSERDATA);
2184                 void *ud = luaL_checkudata(L, narg, className);
2185                 if(!ud) luaL_typerror(L, narg, className);
2186                 return *(NodeMetaRef**)ud;  // unbox pointer
2187         }
2188         
2189         static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2190         {
2191                 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2192                 if(meta == NULL && auto_create)
2193                 {
2194                         meta = new NodeMetadata(ref->m_env->getGameDef());
2195                         ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2196                 }
2197                 return meta;
2198         }
2199
2200         static void reportMetadataChange(NodeMetaRef *ref)
2201         {
2202                 // NOTE: This same code is in rollback_interface.cpp
2203                 // Inform other things that the metadata has changed
2204                 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2205                 MapEditEvent event;
2206                 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2207                 event.p = blockpos;
2208                 ref->m_env->getMap().dispatchEvent(&event);
2209                 // Set the block to be saved
2210                 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2211                 if(block)
2212                         block->raiseModified(MOD_STATE_WRITE_NEEDED,
2213                                         "NodeMetaRef::reportMetadataChange");
2214         }
2215         
2216         // Exported functions
2217         
2218         // garbage collector
2219         static int gc_object(lua_State *L) {
2220                 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2221                 delete o;
2222                 return 0;
2223         }
2224
2225         // get_string(self, name)
2226         static int l_get_string(lua_State *L)
2227         {
2228                 NodeMetaRef *ref = checkobject(L, 1);
2229                 std::string name = luaL_checkstring(L, 2);
2230
2231                 NodeMetadata *meta = getmeta(ref, false);
2232                 if(meta == NULL){
2233                         lua_pushlstring(L, "", 0);
2234                         return 1;
2235                 }
2236                 std::string str = meta->getString(name);
2237                 lua_pushlstring(L, str.c_str(), str.size());
2238                 return 1;
2239         }
2240
2241         // set_string(self, name, var)
2242         static int l_set_string(lua_State *L)
2243         {
2244                 NodeMetaRef *ref = checkobject(L, 1);
2245                 std::string name = luaL_checkstring(L, 2);
2246                 size_t len = 0;
2247                 const char *s = lua_tolstring(L, 3, &len);
2248                 std::string str(s, len);
2249
2250                 NodeMetadata *meta = getmeta(ref, !str.empty());
2251                 if(meta == NULL || str == meta->getString(name))
2252                         return 0;
2253                 meta->setString(name, str);
2254                 reportMetadataChange(ref);
2255                 return 0;
2256         }
2257
2258         // get_int(self, name)
2259         static int l_get_int(lua_State *L)
2260         {
2261                 NodeMetaRef *ref = checkobject(L, 1);
2262                 std::string name = lua_tostring(L, 2);
2263
2264                 NodeMetadata *meta = getmeta(ref, false);
2265                 if(meta == NULL){
2266                         lua_pushnumber(L, 0);
2267                         return 1;
2268                 }
2269                 std::string str = meta->getString(name);
2270                 lua_pushnumber(L, stoi(str));
2271                 return 1;
2272         }
2273
2274         // set_int(self, name, var)
2275         static int l_set_int(lua_State *L)
2276         {
2277                 NodeMetaRef *ref = checkobject(L, 1);
2278                 std::string name = lua_tostring(L, 2);
2279                 int a = lua_tointeger(L, 3);
2280                 std::string str = itos(a);
2281
2282                 NodeMetadata *meta = getmeta(ref, true);
2283                 if(meta == NULL || str == meta->getString(name))
2284                         return 0;
2285                 meta->setString(name, str);
2286                 reportMetadataChange(ref);
2287                 return 0;
2288         }
2289
2290         // get_float(self, name)
2291         static int l_get_float(lua_State *L)
2292         {
2293                 NodeMetaRef *ref = checkobject(L, 1);
2294                 std::string name = lua_tostring(L, 2);
2295
2296                 NodeMetadata *meta = getmeta(ref, false);
2297                 if(meta == NULL){
2298                         lua_pushnumber(L, 0);
2299                         return 1;
2300                 }
2301                 std::string str = meta->getString(name);
2302                 lua_pushnumber(L, stof(str));
2303                 return 1;
2304         }
2305
2306         // set_float(self, name, var)
2307         static int l_set_float(lua_State *L)
2308         {
2309                 NodeMetaRef *ref = checkobject(L, 1);
2310                 std::string name = lua_tostring(L, 2);
2311                 float a = lua_tonumber(L, 3);
2312                 std::string str = ftos(a);
2313
2314                 NodeMetadata *meta = getmeta(ref, true);
2315                 if(meta == NULL || str == meta->getString(name))
2316                         return 0;
2317                 meta->setString(name, str);
2318                 reportMetadataChange(ref);
2319                 return 0;
2320         }
2321
2322         // get_inventory(self)
2323         static int l_get_inventory(lua_State *L)
2324         {
2325                 NodeMetaRef *ref = checkobject(L, 1);
2326                 getmeta(ref, true);  // try to ensure the metadata exists
2327                 InvRef::createNodeMeta(L, ref->m_p);
2328                 return 1;
2329         }
2330         
2331         // to_table(self)
2332         static int l_to_table(lua_State *L)
2333         {
2334                 NodeMetaRef *ref = checkobject(L, 1);
2335
2336                 NodeMetadata *meta = getmeta(ref, true);
2337                 if(meta == NULL){
2338                         lua_pushnil(L);
2339                         return 1;
2340                 }
2341                 lua_newtable(L);
2342                 // fields
2343                 lua_newtable(L);
2344                 {
2345                         std::map<std::string, std::string> fields = meta->getStrings();
2346                         for(std::map<std::string, std::string>::const_iterator
2347                                         i = fields.begin(); i != fields.end(); i++){
2348                                 const std::string &name = i->first;
2349                                 const std::string &value = i->second;
2350                                 lua_pushlstring(L, name.c_str(), name.size());
2351                                 lua_pushlstring(L, value.c_str(), value.size());
2352                                 lua_settable(L, -3);
2353                         }
2354                 }
2355                 lua_setfield(L, -2, "fields");
2356                 // inventory
2357                 lua_newtable(L);
2358                 Inventory *inv = meta->getInventory();
2359                 if(inv){
2360                         std::vector<const InventoryList*> lists = inv->getLists();
2361                         for(std::vector<const InventoryList*>::const_iterator
2362                                         i = lists.begin(); i != lists.end(); i++){
2363                                 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2364                                 lua_setfield(L, -2, (*i)->getName().c_str());
2365                         }
2366                 }
2367                 lua_setfield(L, -2, "inventory");
2368                 return 1;
2369         }
2370
2371         // from_table(self, table)
2372         static int l_from_table(lua_State *L)
2373         {
2374                 NodeMetaRef *ref = checkobject(L, 1);
2375                 int base = 2;
2376                 
2377                 if(lua_isnil(L, base)){
2378                         // No metadata
2379                         ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2380                         lua_pushboolean(L, true);
2381                         return 1;
2382                 }
2383
2384                 // Has metadata; clear old one first
2385                 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2386                 // Create new metadata
2387                 NodeMetadata *meta = getmeta(ref, true);
2388                 // Set fields
2389                 lua_getfield(L, base, "fields");
2390                 int fieldstable = lua_gettop(L);
2391                 lua_pushnil(L);
2392                 while(lua_next(L, fieldstable) != 0){
2393                         // key at index -2 and value at index -1
2394                         std::string name = lua_tostring(L, -2);
2395                         size_t cl;
2396                         const char *cs = lua_tolstring(L, -1, &cl);
2397                         std::string value(cs, cl);
2398                         meta->setString(name, value);
2399                         lua_pop(L, 1); // removes value, keeps key for next iteration
2400                 }
2401                 // Set inventory
2402                 Inventory *inv = meta->getInventory();
2403                 lua_getfield(L, base, "inventory");
2404                 int inventorytable = lua_gettop(L);
2405                 lua_pushnil(L);
2406                 while(lua_next(L, inventorytable) != 0){
2407                         // key at index -2 and value at index -1
2408                         std::string name = lua_tostring(L, -2);
2409                         inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2410                         lua_pop(L, 1); // removes value, keeps key for next iteration
2411                 }
2412                 reportMetadataChange(ref);
2413                 lua_pushboolean(L, true);
2414                 return 1;
2415         }
2416
2417 public:
2418         NodeMetaRef(v3s16 p, ServerEnvironment *env):
2419                 m_p(p),
2420                 m_env(env)
2421         {
2422         }
2423
2424         ~NodeMetaRef()
2425         {
2426         }
2427
2428         // Creates an NodeMetaRef and leaves it on top of stack
2429         // Not callable from Lua; all references are created on the C side.
2430         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2431         {
2432                 NodeMetaRef *o = new NodeMetaRef(p, env);
2433                 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2434                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2435                 luaL_getmetatable(L, className);
2436                 lua_setmetatable(L, -2);
2437         }
2438
2439         static void Register(lua_State *L)
2440         {
2441                 lua_newtable(L);
2442                 int methodtable = lua_gettop(L);
2443                 luaL_newmetatable(L, className);
2444                 int metatable = lua_gettop(L);
2445
2446                 lua_pushliteral(L, "__metatable");
2447                 lua_pushvalue(L, methodtable);
2448                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2449
2450                 lua_pushliteral(L, "__index");
2451                 lua_pushvalue(L, methodtable);
2452                 lua_settable(L, metatable);
2453
2454                 lua_pushliteral(L, "__gc");
2455                 lua_pushcfunction(L, gc_object);
2456                 lua_settable(L, metatable);
2457
2458                 lua_pop(L, 1);  // drop metatable
2459
2460                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2461                 lua_pop(L, 1);  // drop methodtable
2462
2463                 // Cannot be created from Lua
2464                 //lua_register(L, className, create_object);
2465         }
2466 };
2467 const char NodeMetaRef::className[] = "NodeMetaRef";
2468 const luaL_reg NodeMetaRef::methods[] = {
2469         method(NodeMetaRef, get_string),
2470         method(NodeMetaRef, set_string),
2471         method(NodeMetaRef, get_int),
2472         method(NodeMetaRef, set_int),
2473         method(NodeMetaRef, get_float),
2474         method(NodeMetaRef, set_float),
2475         method(NodeMetaRef, get_inventory),
2476         method(NodeMetaRef, to_table),
2477         method(NodeMetaRef, from_table),
2478         {0,0}
2479 };
2480
2481 /*
2482         ObjectRef
2483 */
2484
2485 class ObjectRef
2486 {
2487 private:
2488         ServerActiveObject *m_object;
2489
2490         static const char className[];
2491         static const luaL_reg methods[];
2492 public:
2493         static ObjectRef *checkobject(lua_State *L, int narg)
2494         {
2495                 luaL_checktype(L, narg, LUA_TUSERDATA);
2496                 void *ud = luaL_checkudata(L, narg, className);
2497                 if(!ud) luaL_typerror(L, narg, className);
2498                 return *(ObjectRef**)ud;  // unbox pointer
2499         }
2500         
2501         static ServerActiveObject* getobject(ObjectRef *ref)
2502         {
2503                 ServerActiveObject *co = ref->m_object;
2504                 return co;
2505         }
2506 private:
2507         static LuaEntitySAO* getluaobject(ObjectRef *ref)
2508         {
2509                 ServerActiveObject *obj = getobject(ref);
2510                 if(obj == NULL)
2511                         return NULL;
2512                 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2513                         return NULL;
2514                 return (LuaEntitySAO*)obj;
2515         }
2516         
2517         static PlayerSAO* getplayersao(ObjectRef *ref)
2518         {
2519                 ServerActiveObject *obj = getobject(ref);
2520                 if(obj == NULL)
2521                         return NULL;
2522                 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2523                         return NULL;
2524                 return (PlayerSAO*)obj;
2525         }
2526         
2527         static Player* getplayer(ObjectRef *ref)
2528         {
2529                 PlayerSAO *playersao = getplayersao(ref);
2530                 if(playersao == NULL)
2531                         return NULL;
2532                 return playersao->getPlayer();
2533         }
2534         
2535         // Exported functions
2536         
2537         // garbage collector
2538         static int gc_object(lua_State *L) {
2539                 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2540                 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2541                 delete o;
2542                 return 0;
2543         }
2544
2545         // remove(self)
2546         static int l_remove(lua_State *L)
2547         {
2548                 ObjectRef *ref = checkobject(L, 1);
2549                 ServerActiveObject *co = getobject(ref);
2550                 if(co == NULL) return 0;
2551                 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2552                 co->m_removed = true;
2553                 return 0;
2554         }
2555         
2556         // getpos(self)
2557         // returns: {x=num, y=num, z=num}
2558         static int l_getpos(lua_State *L)
2559         {
2560                 ObjectRef *ref = checkobject(L, 1);
2561                 ServerActiveObject *co = getobject(ref);
2562                 if(co == NULL) return 0;
2563                 v3f pos = co->getBasePosition() / BS;
2564                 lua_newtable(L);
2565                 lua_pushnumber(L, pos.X);
2566                 lua_setfield(L, -2, "x");
2567                 lua_pushnumber(L, pos.Y);
2568                 lua_setfield(L, -2, "y");
2569                 lua_pushnumber(L, pos.Z);
2570                 lua_setfield(L, -2, "z");
2571                 return 1;
2572         }
2573         
2574         // setpos(self, pos)
2575         static int l_setpos(lua_State *L)
2576         {
2577                 ObjectRef *ref = checkobject(L, 1);
2578                 //LuaEntitySAO *co = getluaobject(ref);
2579                 ServerActiveObject *co = getobject(ref);
2580                 if(co == NULL) return 0;
2581                 // pos
2582                 v3f pos = checkFloatPos(L, 2);
2583                 // Do it
2584                 co->setPos(pos);
2585                 return 0;
2586         }
2587         
2588         // moveto(self, pos, continuous=false)
2589         static int l_moveto(lua_State *L)
2590         {
2591                 ObjectRef *ref = checkobject(L, 1);
2592                 //LuaEntitySAO *co = getluaobject(ref);
2593                 ServerActiveObject *co = getobject(ref);
2594                 if(co == NULL) return 0;
2595                 // pos
2596                 v3f pos = checkFloatPos(L, 2);
2597                 // continuous
2598                 bool continuous = lua_toboolean(L, 3);
2599                 // Do it
2600                 co->moveTo(pos, continuous);
2601                 return 0;
2602         }
2603
2604         // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2605         static int l_punch(lua_State *L)
2606         {
2607                 ObjectRef *ref = checkobject(L, 1);
2608                 ObjectRef *puncher_ref = checkobject(L, 2);
2609                 ServerActiveObject *co = getobject(ref);
2610                 ServerActiveObject *puncher = getobject(puncher_ref);
2611                 if(co == NULL) return 0;
2612                 if(puncher == NULL) return 0;
2613                 v3f dir;
2614                 if(lua_type(L, 5) != LUA_TTABLE)
2615                         dir = co->getBasePosition() - puncher->getBasePosition();
2616                 else
2617                         dir = read_v3f(L, 5);
2618                 float time_from_last_punch = 1000000;
2619                 if(lua_isnumber(L, 3))
2620                         time_from_last_punch = lua_tonumber(L, 3);
2621                 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2622                 dir.normalize();
2623                 // Do it
2624                 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2625                 return 0;
2626         }
2627
2628         // right_click(self, clicker); clicker = an another ObjectRef
2629         static int l_right_click(lua_State *L)
2630         {
2631                 ObjectRef *ref = checkobject(L, 1);
2632                 ObjectRef *ref2 = checkobject(L, 2);
2633                 ServerActiveObject *co = getobject(ref);
2634                 ServerActiveObject *co2 = getobject(ref2);
2635                 if(co == NULL) return 0;
2636                 if(co2 == NULL) return 0;
2637                 // Do it
2638                 co->rightClick(co2);
2639                 return 0;
2640         }
2641
2642         // set_hp(self, hp)
2643         // hp = number of hitpoints (2 * number of hearts)
2644         // returns: nil
2645         static int l_set_hp(lua_State *L)
2646         {
2647                 ObjectRef *ref = checkobject(L, 1);
2648                 luaL_checknumber(L, 2);
2649                 ServerActiveObject *co = getobject(ref);
2650                 if(co == NULL) return 0;
2651                 int hp = lua_tonumber(L, 2);
2652                 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2653                                 <<" hp="<<hp<<std::endl;*/
2654                 // Do it
2655                 co->setHP(hp);
2656                 // Return
2657                 return 0;
2658         }
2659
2660         // get_hp(self)
2661         // returns: number of hitpoints (2 * number of hearts)
2662         // 0 if not applicable to this type of object
2663         static int l_get_hp(lua_State *L)
2664         {
2665                 ObjectRef *ref = checkobject(L, 1);
2666                 ServerActiveObject *co = getobject(ref);
2667                 if(co == NULL){
2668                         // Default hp is 1
2669                         lua_pushnumber(L, 1);
2670                         return 1;
2671                 }
2672                 int hp = co->getHP();
2673                 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2674                                 <<" hp="<<hp<<std::endl;*/
2675                 // Return
2676                 lua_pushnumber(L, hp);
2677                 return 1;
2678         }
2679
2680         // get_inventory(self)
2681         static int l_get_inventory(lua_State *L)
2682         {
2683                 ObjectRef *ref = checkobject(L, 1);
2684                 ServerActiveObject *co = getobject(ref);
2685                 if(co == NULL) return 0;
2686                 // Do it
2687                 InventoryLocation loc = co->getInventoryLocation();
2688                 if(get_server(L)->getInventory(loc) != NULL)
2689                         InvRef::create(L, loc);
2690                 else
2691                         lua_pushnil(L); // An object may have no inventory (nil)
2692                 return 1;
2693         }
2694
2695         // get_wield_list(self)
2696         static int l_get_wield_list(lua_State *L)
2697         {
2698                 ObjectRef *ref = checkobject(L, 1);
2699                 ServerActiveObject *co = getobject(ref);
2700                 if(co == NULL) return 0;
2701                 // Do it
2702                 lua_pushstring(L, co->getWieldList().c_str());
2703                 return 1;
2704         }
2705
2706         // get_wield_index(self)
2707         static int l_get_wield_index(lua_State *L)
2708         {
2709                 ObjectRef *ref = checkobject(L, 1);
2710                 ServerActiveObject *co = getobject(ref);
2711                 if(co == NULL) return 0;
2712                 // Do it
2713                 lua_pushinteger(L, co->getWieldIndex() + 1);
2714                 return 1;
2715         }
2716
2717         // get_wielded_item(self)
2718         static int l_get_wielded_item(lua_State *L)
2719         {
2720                 ObjectRef *ref = checkobject(L, 1);
2721                 ServerActiveObject *co = getobject(ref);
2722                 if(co == NULL){
2723                         // Empty ItemStack
2724                         LuaItemStack::create(L, ItemStack());
2725                         return 1;
2726                 }
2727                 // Do it
2728                 LuaItemStack::create(L, co->getWieldedItem());
2729                 return 1;
2730         }
2731
2732         // set_wielded_item(self, itemstack or itemstring or table or nil)
2733         static int l_set_wielded_item(lua_State *L)
2734         {
2735                 ObjectRef *ref = checkobject(L, 1);
2736                 ServerActiveObject *co = getobject(ref);
2737                 if(co == NULL) return 0;
2738                 // Do it
2739                 ItemStack item = read_item(L, 2);
2740                 bool success = co->setWieldedItem(item);
2741                 lua_pushboolean(L, success);
2742                 return 1;
2743         }
2744
2745         // set_armor_groups(self, groups)
2746         static int l_set_armor_groups(lua_State *L)
2747         {
2748                 ObjectRef *ref = checkobject(L, 1);
2749                 ServerActiveObject *co = getobject(ref);
2750                 if(co == NULL) return 0;
2751                 // Do it
2752                 ItemGroupList groups;
2753                 read_groups(L, 2, groups);
2754                 co->setArmorGroups(groups);
2755                 return 0;
2756         }
2757
2758         // set_animation(self, frame_range, frame_speed, frame_blend)
2759         static int l_set_animation(lua_State *L)
2760         {
2761                 ObjectRef *ref = checkobject(L, 1);
2762                 ServerActiveObject *co = getobject(ref);
2763                 if(co == NULL) return 0;
2764                 // Do it
2765                 v2f frames = v2f(1, 1);
2766                 if(!lua_isnil(L, 2))
2767                         frames = read_v2f(L, 2);
2768                 float frame_speed = 15;
2769                 if(!lua_isnil(L, 3))
2770                         frame_speed = lua_tonumber(L, 3);
2771                 float frame_blend = 0;
2772                 if(!lua_isnil(L, 4))
2773                         frame_blend = lua_tonumber(L, 4);
2774                 co->setAnimation(frames, frame_speed, frame_blend);
2775                 return 0;
2776         }
2777
2778         // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2779         static int l_set_bone_position(lua_State *L)
2780         {
2781                 ObjectRef *ref = checkobject(L, 1);
2782                 ServerActiveObject *co = getobject(ref);
2783                 if(co == NULL) return 0;
2784                 // Do it
2785                 std::string bone = "";
2786                 if(!lua_isnil(L, 2))
2787                         bone = lua_tostring(L, 2);
2788                 v3f position = v3f(0, 0, 0);
2789                 if(!lua_isnil(L, 3))
2790                         position = read_v3f(L, 3);
2791                 v3f rotation = v3f(0, 0, 0);
2792                 if(!lua_isnil(L, 4))
2793                         rotation = read_v3f(L, 4);
2794                 co->setBonePosition(bone, position, rotation);
2795                 return 0;
2796         }
2797
2798         // set_attach(self, parent, bone, position, rotation)
2799         static int l_set_attach(lua_State *L)
2800         {
2801                 ObjectRef *ref = checkobject(L, 1);
2802                 ObjectRef *parent_ref = checkobject(L, 2);
2803                 ServerActiveObject *co = getobject(ref);
2804                 ServerActiveObject *parent = getobject(parent_ref);
2805                 if(co == NULL) return 0;
2806                 if(parent == NULL) return 0;
2807                 // Do it
2808                 std::string bone = "";
2809                 if(!lua_isnil(L, 3))
2810                         bone = lua_tostring(L, 3);
2811                 v3f position = v3f(0, 0, 0);
2812                 if(!lua_isnil(L, 4))
2813                         position = read_v3f(L, 4);
2814                 v3f rotation = v3f(0, 0, 0);
2815                 if(!lua_isnil(L, 5))
2816                         rotation = read_v3f(L, 5);
2817                 co->setAttachment(parent->getId(), bone, position, rotation);
2818                 return 0;
2819         }
2820
2821         // set_detach(self)
2822         static int l_set_detach(lua_State *L)
2823         {
2824                 ObjectRef *ref = checkobject(L, 1);
2825                 ServerActiveObject *co = getobject(ref);
2826                 if(co == NULL) return 0;
2827                 // Do it
2828                 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2829                 return 0;
2830         }
2831
2832         // set_properties(self, properties)
2833         static int l_set_properties(lua_State *L)
2834         {
2835                 ObjectRef *ref = checkobject(L, 1);
2836                 ServerActiveObject *co = getobject(ref);
2837                 if(co == NULL) return 0;
2838                 ObjectProperties *prop = co->accessObjectProperties();
2839                 if(!prop)
2840                         return 0;
2841                 read_object_properties(L, 2, prop);
2842                 co->notifyObjectPropertiesModified();
2843                 return 0;
2844         }
2845
2846         /* LuaEntitySAO-only */
2847
2848         // setvelocity(self, {x=num, y=num, z=num})
2849         static int l_setvelocity(lua_State *L)
2850         {
2851                 ObjectRef *ref = checkobject(L, 1);
2852                 LuaEntitySAO *co = getluaobject(ref);
2853                 if(co == NULL) return 0;
2854                 v3f pos = checkFloatPos(L, 2);
2855                 // Do it
2856                 co->setVelocity(pos);
2857                 return 0;
2858         }
2859         
2860         // getvelocity(self)
2861         static int l_getvelocity(lua_State *L)
2862         {
2863                 ObjectRef *ref = checkobject(L, 1);
2864                 LuaEntitySAO *co = getluaobject(ref);
2865                 if(co == NULL) return 0;
2866                 // Do it
2867                 v3f v = co->getVelocity();
2868                 pushFloatPos(L, v);
2869                 return 1;
2870         }
2871         
2872         // setacceleration(self, {x=num, y=num, z=num})
2873         static int l_setacceleration(lua_State *L)
2874         {
2875                 ObjectRef *ref = checkobject(L, 1);
2876                 LuaEntitySAO *co = getluaobject(ref);
2877                 if(co == NULL) return 0;
2878                 // pos
2879                 v3f pos = checkFloatPos(L, 2);
2880                 // Do it
2881                 co->setAcceleration(pos);
2882                 return 0;
2883         }
2884         
2885         // getacceleration(self)
2886         static int l_getacceleration(lua_State *L)
2887         {
2888                 ObjectRef *ref = checkobject(L, 1);
2889                 LuaEntitySAO *co = getluaobject(ref);
2890                 if(co == NULL) return 0;
2891                 // Do it
2892                 v3f v = co->getAcceleration();
2893                 pushFloatPos(L, v);
2894                 return 1;
2895         }
2896         
2897         // setyaw(self, radians)
2898         static int l_setyaw(lua_State *L)
2899         {
2900                 ObjectRef *ref = checkobject(L, 1);
2901                 LuaEntitySAO *co = getluaobject(ref);
2902                 if(co == NULL) return 0;
2903                 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2904                 // Do it
2905                 co->setYaw(yaw);
2906                 return 0;
2907         }
2908         
2909         // getyaw(self)
2910         static int l_getyaw(lua_State *L)
2911         {
2912                 ObjectRef *ref = checkobject(L, 1);
2913                 LuaEntitySAO *co = getluaobject(ref);
2914                 if(co == NULL) return 0;
2915                 // Do it
2916                 float yaw = co->getYaw() * core::DEGTORAD;
2917                 lua_pushnumber(L, yaw);
2918                 return 1;
2919         }
2920         
2921         // settexturemod(self, mod)
2922         static int l_settexturemod(lua_State *L)
2923         {
2924                 ObjectRef *ref = checkobject(L, 1);
2925                 LuaEntitySAO *co = getluaobject(ref);
2926                 if(co == NULL) return 0;
2927                 // Do it
2928                 std::string mod = luaL_checkstring(L, 2);
2929                 co->setTextureMod(mod);
2930                 return 0;
2931         }
2932         
2933         // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2934         //           select_horiz_by_yawpitch=false)
2935         static int l_setsprite(lua_State *L)
2936         {
2937                 ObjectRef *ref = checkobject(L, 1);
2938                 LuaEntitySAO *co = getluaobject(ref);
2939                 if(co == NULL) return 0;
2940                 // Do it
2941                 v2s16 p(0,0);
2942                 if(!lua_isnil(L, 2))
2943                         p = read_v2s16(L, 2);
2944                 int num_frames = 1;
2945                 if(!lua_isnil(L, 3))
2946                         num_frames = lua_tonumber(L, 3);
2947                 float framelength = 0.2;
2948                 if(!lua_isnil(L, 4))
2949                         framelength = lua_tonumber(L, 4);
2950                 bool select_horiz_by_yawpitch = false;
2951                 if(!lua_isnil(L, 5))
2952                         select_horiz_by_yawpitch = lua_toboolean(L, 5);
2953                 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2954                 return 0;
2955         }
2956
2957         // DEPRECATED
2958         // get_entity_name(self)
2959         static int l_get_entity_name(lua_State *L)
2960         {
2961                 ObjectRef *ref = checkobject(L, 1);
2962                 LuaEntitySAO *co = getluaobject(ref);
2963                 if(co == NULL) return 0;
2964                 // Do it
2965                 std::string name = co->getName();
2966                 lua_pushstring(L, name.c_str());
2967                 return 1;
2968         }
2969         
2970         // get_luaentity(self)
2971         static int l_get_luaentity(lua_State *L)
2972         {
2973                 ObjectRef *ref = checkobject(L, 1);
2974                 LuaEntitySAO *co = getluaobject(ref);
2975                 if(co == NULL) return 0;
2976                 // Do it
2977                 luaentity_get(L, co->getId());
2978                 return 1;
2979         }
2980         
2981         /* Player-only */
2982
2983         // is_player(self)
2984         static int l_is_player(lua_State *L)
2985         {
2986                 ObjectRef *ref = checkobject(L, 1);
2987                 Player *player = getplayer(ref);
2988                 lua_pushboolean(L, (player != NULL));
2989                 return 1;
2990         }
2991         
2992         // get_player_name(self)
2993         static int l_get_player_name(lua_State *L)
2994         {
2995                 ObjectRef *ref = checkobject(L, 1);
2996                 Player *player = getplayer(ref);
2997                 if(player == NULL){
2998                         lua_pushlstring(L, "", 0);
2999                         return 1;
3000                 }
3001                 // Do it
3002                 lua_pushstring(L, player->getName());
3003                 return 1;
3004         }
3005         
3006         // get_look_dir(self)
3007         static int l_get_look_dir(lua_State *L)
3008         {
3009                 ObjectRef *ref = checkobject(L, 1);
3010                 Player *player = getplayer(ref);
3011                 if(player == NULL) return 0;
3012                 // Do it
3013                 float pitch = player->getRadPitch();
3014                 float yaw = player->getRadYaw();
3015                 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
3016                 push_v3f(L, v);
3017                 return 1;
3018         }
3019
3020         // get_look_pitch(self)
3021         static int l_get_look_pitch(lua_State *L)
3022         {
3023                 ObjectRef *ref = checkobject(L, 1);
3024                 Player *player = getplayer(ref);
3025                 if(player == NULL) return 0;
3026                 // Do it
3027                 lua_pushnumber(L, player->getRadPitch());
3028                 return 1;
3029         }
3030
3031         // get_look_yaw(self)
3032         static int l_get_look_yaw(lua_State *L)
3033         {
3034                 ObjectRef *ref = checkobject(L, 1);
3035                 Player *player = getplayer(ref);
3036                 if(player == NULL) return 0;
3037                 // Do it
3038                 lua_pushnumber(L, player->getRadYaw());
3039                 return 1;
3040         }
3041
3042         // set_inventory_formspec(self, formspec)
3043         static int l_set_inventory_formspec(lua_State *L)
3044         {
3045                 ObjectRef *ref = checkobject(L, 1);
3046                 Player *player = getplayer(ref);
3047                 if(player == NULL) return 0;
3048                 std::string formspec = luaL_checkstring(L, 2);
3049
3050                 player->inventory_formspec = formspec;
3051                 get_server(L)->reportInventoryFormspecModified(player->getName());
3052                 lua_pushboolean(L, true);
3053                 return 1;
3054         }
3055
3056         // get_inventory_formspec(self) -> formspec
3057         static int l_get_inventory_formspec(lua_State *L)
3058         {
3059                 ObjectRef *ref = checkobject(L, 1);
3060                 Player *player = getplayer(ref);
3061                 if(player == NULL) return 0;
3062
3063                 std::string formspec = player->inventory_formspec;
3064                 lua_pushlstring(L, formspec.c_str(), formspec.size());
3065                 return 1;
3066         }
3067         
3068         // get_player_control(self)
3069         static int l_get_player_control(lua_State *L)
3070         {
3071                 ObjectRef *ref = checkobject(L, 1);
3072                 Player *player = getplayer(ref);
3073                 if(player == NULL){
3074                         lua_pushlstring(L, "", 0);
3075                         return 1;
3076                 }
3077                 // Do it
3078                 PlayerControl control = player->getPlayerControl();
3079                 lua_newtable(L);
3080                 lua_pushboolean(L, control.up);
3081                 lua_setfield(L, -2, "up");
3082                 lua_pushboolean(L, control.down);
3083                 lua_setfield(L, -2, "down");
3084                 lua_pushboolean(L, control.left);
3085                 lua_setfield(L, -2, "left");
3086                 lua_pushboolean(L, control.right);
3087                 lua_setfield(L, -2, "right");
3088                 lua_pushboolean(L, control.jump);
3089                 lua_setfield(L, -2, "jump");
3090                 lua_pushboolean(L, control.aux1);
3091                 lua_setfield(L, -2, "aux1");
3092                 lua_pushboolean(L, control.sneak);
3093                 lua_setfield(L, -2, "sneak");
3094                 lua_pushboolean(L, control.LMB);
3095                 lua_setfield(L, -2, "LMB");
3096                 lua_pushboolean(L, control.RMB);
3097                 lua_setfield(L, -2, "RMB");
3098                 return 1;
3099         }
3100         
3101         // get_player_control_bits(self)
3102         static int l_get_player_control_bits(lua_State *L)
3103         {
3104                 ObjectRef *ref = checkobject(L, 1);
3105                 Player *player = getplayer(ref);
3106                 if(player == NULL){
3107                         lua_pushlstring(L, "", 0);
3108                         return 1;
3109                 }
3110                 // Do it        
3111                 lua_pushnumber(L, player->keyPressed);
3112                 return 1;
3113         }
3114         
3115 public:
3116         ObjectRef(ServerActiveObject *object):
3117                 m_object(object)
3118         {
3119                 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3120         }
3121
3122         ~ObjectRef()
3123         {
3124                 /*if(m_object)
3125                         infostream<<"ObjectRef destructing for id="
3126                                         <<m_object->getId()<<std::endl;
3127                 else
3128                         infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3129         }
3130
3131         // Creates an ObjectRef and leaves it on top of stack
3132         // Not callable from Lua; all references are created on the C side.
3133         static void create(lua_State *L, ServerActiveObject *object)
3134         {
3135                 ObjectRef *o = new ObjectRef(object);
3136                 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3137                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3138                 luaL_getmetatable(L, className);
3139                 lua_setmetatable(L, -2);
3140         }
3141
3142         static void set_null(lua_State *L)
3143         {
3144                 ObjectRef *o = checkobject(L, -1);
3145                 o->m_object = NULL;
3146         }
3147         
3148         static void Register(lua_State *L)
3149         {
3150                 lua_newtable(L);
3151                 int methodtable = lua_gettop(L);
3152                 luaL_newmetatable(L, className);
3153                 int metatable = lua_gettop(L);
3154
3155                 lua_pushliteral(L, "__metatable");
3156                 lua_pushvalue(L, methodtable);
3157                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3158
3159                 lua_pushliteral(L, "__index");
3160                 lua_pushvalue(L, methodtable);
3161                 lua_settable(L, metatable);
3162
3163                 lua_pushliteral(L, "__gc");
3164                 lua_pushcfunction(L, gc_object);
3165                 lua_settable(L, metatable);
3166
3167                 lua_pop(L, 1);  // drop metatable
3168
3169                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3170                 lua_pop(L, 1);  // drop methodtable
3171
3172                 // Cannot be created from Lua
3173                 //lua_register(L, className, create_object);
3174         }
3175 };
3176 const char ObjectRef::className[] = "ObjectRef";
3177 const luaL_reg ObjectRef::methods[] = {
3178         // ServerActiveObject
3179         method(ObjectRef, remove),
3180         method(ObjectRef, getpos),
3181         method(ObjectRef, setpos),
3182         method(ObjectRef, moveto),
3183         method(ObjectRef, punch),
3184         method(ObjectRef, right_click),
3185         method(ObjectRef, set_hp),
3186         method(ObjectRef, get_hp),
3187         method(ObjectRef, get_inventory),
3188         method(ObjectRef, get_wield_list),
3189         method(ObjectRef, get_wield_index),
3190         method(ObjectRef, get_wielded_item),
3191         method(ObjectRef, set_wielded_item),
3192         method(ObjectRef, set_armor_groups),
3193         method(ObjectRef, set_animation),
3194         method(ObjectRef, set_bone_position),
3195         method(ObjectRef, set_attach),
3196         method(ObjectRef, set_detach),
3197         method(ObjectRef, set_properties),
3198         // LuaEntitySAO-only
3199         method(ObjectRef, setvelocity),
3200         method(ObjectRef, getvelocity),
3201         method(ObjectRef, setacceleration),
3202         method(ObjectRef, getacceleration),
3203         method(ObjectRef, setyaw),
3204         method(ObjectRef, getyaw),
3205         method(ObjectRef, settexturemod),
3206         method(ObjectRef, setsprite),
3207         method(ObjectRef, get_entity_name),
3208         method(ObjectRef, get_luaentity),
3209         // Player-only
3210         method(ObjectRef, is_player),
3211         method(ObjectRef, get_player_name),
3212         method(ObjectRef, get_look_dir),
3213         method(ObjectRef, get_look_pitch),
3214         method(ObjectRef, get_look_yaw),
3215         method(ObjectRef, set_inventory_formspec),
3216         method(ObjectRef, get_inventory_formspec),
3217         method(ObjectRef, get_player_control),
3218         method(ObjectRef, get_player_control_bits),
3219         {0,0}
3220 };
3221
3222 // Creates a new anonymous reference if cobj=NULL or id=0
3223 static void objectref_get_or_create(lua_State *L,
3224                 ServerActiveObject *cobj)
3225 {
3226         if(cobj == NULL || cobj->getId() == 0){
3227                 ObjectRef::create(L, cobj);
3228         } else {
3229                 objectref_get(L, cobj->getId());
3230         }
3231 }
3232
3233
3234 /*
3235   PerlinNoise
3236  */
3237
3238 class LuaPerlinNoise
3239 {
3240 private:
3241         int seed;
3242         int octaves;
3243         double persistence;
3244         double scale;
3245         static const char className[];
3246         static const luaL_reg methods[];
3247
3248         // Exported functions
3249
3250         // garbage collector
3251         static int gc_object(lua_State *L)
3252         {
3253                 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3254                 delete o;
3255                 return 0;
3256         }
3257
3258         static int l_get2d(lua_State *L)
3259         {
3260                 LuaPerlinNoise *o = checkobject(L, 1);
3261                 v2f pos2d = read_v2f(L,2);
3262                 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3263                 lua_pushnumber(L, val);
3264                 return 1;
3265         }
3266         static int l_get3d(lua_State *L)
3267         {
3268                 LuaPerlinNoise *o = checkobject(L, 1);
3269                 v3f pos3d = read_v3f(L,2);
3270                 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3271                 lua_pushnumber(L, val);
3272                 return 1;
3273         }
3274
3275 public:
3276         LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3277                         double a_scale):
3278                 seed(a_seed),
3279                 octaves(a_octaves),
3280                 persistence(a_persistence),
3281                 scale(a_scale)
3282         {
3283         }
3284
3285         ~LuaPerlinNoise()
3286         {
3287         }
3288
3289         // LuaPerlinNoise(seed, octaves, persistence, scale)
3290         // Creates an LuaPerlinNoise and leaves it on top of stack
3291         static int create_object(lua_State *L)
3292         {
3293                 int seed = luaL_checkint(L, 1);
3294                 int octaves = luaL_checkint(L, 2);
3295                 double persistence = luaL_checknumber(L, 3);
3296                 double scale = luaL_checknumber(L, 4);
3297                 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3298                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3299                 luaL_getmetatable(L, className);
3300                 lua_setmetatable(L, -2);
3301                 return 1;
3302         }
3303
3304         static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3305         {
3306                 luaL_checktype(L, narg, LUA_TUSERDATA);
3307                 void *ud = luaL_checkudata(L, narg, className);
3308                 if(!ud) luaL_typerror(L, narg, className);
3309                 return *(LuaPerlinNoise**)ud;  // unbox pointer
3310         }
3311
3312         static void Register(lua_State *L)
3313         {
3314                 lua_newtable(L);
3315                 int methodtable = lua_gettop(L);
3316                 luaL_newmetatable(L, className);
3317                 int metatable = lua_gettop(L);
3318
3319                 lua_pushliteral(L, "__metatable");
3320                 lua_pushvalue(L, methodtable);
3321                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3322
3323                 lua_pushliteral(L, "__index");
3324                 lua_pushvalue(L, methodtable);
3325                 lua_settable(L, metatable);
3326
3327                 lua_pushliteral(L, "__gc");
3328                 lua_pushcfunction(L, gc_object);
3329                 lua_settable(L, metatable);
3330
3331                 lua_pop(L, 1);  // drop metatable
3332
3333                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3334                 lua_pop(L, 1);  // drop methodtable
3335
3336                 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3337                 lua_register(L, className, create_object);
3338         }
3339 };
3340 const char LuaPerlinNoise::className[] = "PerlinNoise";
3341 const luaL_reg LuaPerlinNoise::methods[] = {
3342         method(LuaPerlinNoise, get2d),
3343         method(LuaPerlinNoise, get3d),
3344         {0,0}
3345 };
3346
3347 /*
3348         NodeTimerRef
3349 */
3350
3351 class NodeTimerRef
3352 {
3353 private:
3354         v3s16 m_p;
3355         ServerEnvironment *m_env;
3356
3357         static const char className[];
3358         static const luaL_reg methods[];
3359
3360         static int gc_object(lua_State *L) {
3361                 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3362                 delete o;
3363                 return 0;
3364         }
3365
3366         static NodeTimerRef *checkobject(lua_State *L, int narg)
3367         {
3368                 luaL_checktype(L, narg, LUA_TUSERDATA);
3369                 void *ud = luaL_checkudata(L, narg, className);
3370                 if(!ud) luaL_typerror(L, narg, className);
3371                 return *(NodeTimerRef**)ud;  // unbox pointer
3372         }
3373         
3374         static int l_set(lua_State *L)
3375         {
3376                 NodeTimerRef *o = checkobject(L, 1);
3377                 ServerEnvironment *env = o->m_env;
3378                 if(env == NULL) return 0;
3379                 f32 t = luaL_checknumber(L,2);
3380                 f32 e = luaL_checknumber(L,3);
3381                 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3382                 return 0;
3383         }
3384         
3385         static int l_start(lua_State *L)
3386         {
3387                 NodeTimerRef *o = checkobject(L, 1);
3388                 ServerEnvironment *env = o->m_env;
3389                 if(env == NULL) return 0;
3390                 f32 t = luaL_checknumber(L,2);
3391                 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3392                 return 0;
3393         }
3394         
3395         static int l_stop(lua_State *L)
3396         {
3397                 NodeTimerRef *o = checkobject(L, 1);
3398                 ServerEnvironment *env = o->m_env;
3399                 if(env == NULL) return 0;
3400                 env->getMap().removeNodeTimer(o->m_p);
3401                 return 0;
3402         }
3403         
3404         static int l_is_started(lua_State *L)
3405         {
3406                 NodeTimerRef *o = checkobject(L, 1);
3407                 ServerEnvironment *env = o->m_env;
3408                 if(env == NULL) return 0;
3409
3410                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3411                 lua_pushboolean(L,(t.timeout != 0));
3412                 return 1;
3413         }
3414         
3415         static int l_get_timeout(lua_State *L)
3416         {
3417                 NodeTimerRef *o = checkobject(L, 1);
3418                 ServerEnvironment *env = o->m_env;
3419                 if(env == NULL) return 0;
3420
3421                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3422                 lua_pushnumber(L,t.timeout);
3423                 return 1;
3424         }
3425         
3426         static int l_get_elapsed(lua_State *L)
3427         {
3428                 NodeTimerRef *o = checkobject(L, 1);
3429                 ServerEnvironment *env = o->m_env;
3430                 if(env == NULL) return 0;
3431
3432                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3433                 lua_pushnumber(L,t.elapsed);
3434                 return 1;
3435         }
3436
3437 public:
3438         NodeTimerRef(v3s16 p, ServerEnvironment *env):
3439                 m_p(p),
3440                 m_env(env)
3441         {
3442         }
3443
3444         ~NodeTimerRef()
3445         {
3446         }
3447
3448         // Creates an NodeTimerRef and leaves it on top of stack
3449         // Not callable from Lua; all references are created on the C side.
3450         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3451         {
3452                 NodeTimerRef *o = new NodeTimerRef(p, env);
3453                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3454                 luaL_getmetatable(L, className);
3455                 lua_setmetatable(L, -2);
3456         }
3457
3458         static void set_null(lua_State *L)
3459         {
3460                 NodeTimerRef *o = checkobject(L, -1);
3461                 o->m_env = NULL;
3462         }
3463         
3464         static void Register(lua_State *L)
3465         {
3466                 lua_newtable(L);
3467                 int methodtable = lua_gettop(L);
3468                 luaL_newmetatable(L, className);
3469                 int metatable = lua_gettop(L);
3470
3471                 lua_pushliteral(L, "__metatable");
3472                 lua_pushvalue(L, methodtable);
3473                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3474
3475                 lua_pushliteral(L, "__index");
3476                 lua_pushvalue(L, methodtable);
3477                 lua_settable(L, metatable);
3478
3479                 lua_pushliteral(L, "__gc");
3480                 lua_pushcfunction(L, gc_object);
3481                 lua_settable(L, metatable);
3482
3483                 lua_pop(L, 1);  // drop metatable
3484
3485                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3486                 lua_pop(L, 1);  // drop methodtable
3487
3488                 // Cannot be created from Lua
3489                 //lua_register(L, className, create_object);
3490         }
3491 };
3492 const char NodeTimerRef::className[] = "NodeTimerRef";
3493 const luaL_reg NodeTimerRef::methods[] = {
3494         method(NodeTimerRef, start),
3495         method(NodeTimerRef, set),
3496         method(NodeTimerRef, stop),
3497         method(NodeTimerRef, is_started),
3498         method(NodeTimerRef, get_timeout),
3499         method(NodeTimerRef, get_elapsed),
3500         {0,0}
3501 };
3502
3503 /*
3504         EnvRef
3505 */
3506
3507 class EnvRef
3508 {
3509 private:
3510         ServerEnvironment *m_env;
3511
3512         static const char className[];
3513         static const luaL_reg methods[];
3514
3515         static int gc_object(lua_State *L) {
3516                 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3517                 delete o;
3518                 return 0;
3519         }
3520
3521         static EnvRef *checkobject(lua_State *L, int narg)
3522         {
3523                 luaL_checktype(L, narg, LUA_TUSERDATA);
3524                 void *ud = luaL_checkudata(L, narg, className);
3525                 if(!ud) luaL_typerror(L, narg, className);
3526                 return *(EnvRef**)ud;  // unbox pointer
3527         }
3528         
3529         // Exported functions
3530
3531         // EnvRef:set_node(pos, node)
3532         // pos = {x=num, y=num, z=num}
3533         static int l_set_node(lua_State *L)
3534         {
3535                 EnvRef *o = checkobject(L, 1);
3536                 ServerEnvironment *env = o->m_env;
3537                 if(env == NULL) return 0;
3538                 INodeDefManager *ndef = env->getGameDef()->ndef();
3539                 // parameters
3540                 v3s16 pos = read_v3s16(L, 2);
3541                 MapNode n = readnode(L, 3, ndef);
3542                 // Do it
3543                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3544                 // Call destructor
3545                 if(ndef->get(n_old).has_on_destruct)
3546                         scriptapi_node_on_destruct(L, pos, n_old);
3547                 // Replace node
3548                 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3549                 if(succeeded){
3550                         // Call post-destructor
3551                         if(ndef->get(n_old).has_after_destruct)
3552                                 scriptapi_node_after_destruct(L, pos, n_old);
3553                         // Call constructor
3554                         if(ndef->get(n).has_on_construct)
3555                                 scriptapi_node_on_construct(L, pos, n);
3556                 }
3557                 lua_pushboolean(L, succeeded);
3558                 return 1;
3559         }
3560
3561         static int l_add_node(lua_State *L)
3562         {
3563                 return l_set_node(L);
3564         }
3565
3566         // EnvRef:remove_node(pos)
3567         // pos = {x=num, y=num, z=num}
3568         static int l_remove_node(lua_State *L)
3569         {
3570                 EnvRef *o = checkobject(L, 1);
3571                 ServerEnvironment *env = o->m_env;
3572                 if(env == NULL) return 0;
3573                 INodeDefManager *ndef = env->getGameDef()->ndef();
3574                 // parameters
3575                 v3s16 pos = read_v3s16(L, 2);
3576                 // Do it
3577                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3578                 // Call destructor
3579                 if(ndef->get(n_old).has_on_destruct)
3580                         scriptapi_node_on_destruct(L, pos, n_old);
3581                 // Replace with air
3582                 // This is slightly optimized compared to addNodeWithEvent(air)
3583                 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3584                 if(succeeded){
3585                         // Call post-destructor
3586                         if(ndef->get(n_old).has_after_destruct)
3587                                 scriptapi_node_after_destruct(L, pos, n_old);
3588                 }
3589                 lua_pushboolean(L, succeeded);
3590                 // Air doesn't require constructor
3591                 return 1;
3592         }
3593
3594         // EnvRef:get_node(pos)
3595         // pos = {x=num, y=num, z=num}
3596         static int l_get_node(lua_State *L)
3597         {
3598                 EnvRef *o = checkobject(L, 1);
3599                 ServerEnvironment *env = o->m_env;
3600                 if(env == NULL) return 0;
3601                 // pos
3602                 v3s16 pos = read_v3s16(L, 2);
3603                 // Do it
3604                 MapNode n = env->getMap().getNodeNoEx(pos);
3605                 // Return node
3606                 pushnode(L, n, env->getGameDef()->ndef());
3607                 return 1;
3608         }
3609
3610         // EnvRef:get_node_or_nil(pos)
3611         // pos = {x=num, y=num, z=num}
3612         static int l_get_node_or_nil(lua_State *L)
3613         {
3614                 EnvRef *o = checkobject(L, 1);
3615                 ServerEnvironment *env = o->m_env;
3616                 if(env == NULL) return 0;
3617                 // pos
3618                 v3s16 pos = read_v3s16(L, 2);
3619                 // Do it
3620                 try{
3621                         MapNode n = env->getMap().getNode(pos);
3622                         // Return node
3623                         pushnode(L, n, env->getGameDef()->ndef());
3624                         return 1;
3625                 } catch(InvalidPositionException &e)
3626                 {
3627                         lua_pushnil(L);
3628                         return 1;
3629                 }
3630         }
3631
3632         // EnvRef:get_node_light(pos, timeofday)
3633         // pos = {x=num, y=num, z=num}
3634         // timeofday: nil = current time, 0 = night, 0.5 = day
3635         static int l_get_node_light(lua_State *L)
3636         {
3637                 EnvRef *o = checkobject(L, 1);
3638                 ServerEnvironment *env = o->m_env;
3639                 if(env == NULL) return 0;
3640                 // Do it
3641                 v3s16 pos = read_v3s16(L, 2);
3642                 u32 time_of_day = env->getTimeOfDay();
3643                 if(lua_isnumber(L, 3))
3644                         time_of_day = 24000.0 * lua_tonumber(L, 3);
3645                 time_of_day %= 24000;
3646                 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3647                 MapNode n = env->getMap().getNodeNoEx(pos);
3648                 try{
3649                         MapNode n = env->getMap().getNode(pos);
3650                         INodeDefManager *ndef = env->getGameDef()->ndef();
3651                         lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3652                         return 1;
3653                 } catch(InvalidPositionException &e)
3654                 {
3655                         lua_pushnil(L);
3656                         return 1;
3657                 }
3658         }
3659
3660         // EnvRef:place_node(pos, node)
3661         // pos = {x=num, y=num, z=num}
3662         static int l_place_node(lua_State *L)
3663         {
3664                 EnvRef *o = checkobject(L, 1);
3665                 ServerEnvironment *env = o->m_env;
3666                 if(env == NULL) return 0;
3667                 v3s16 pos = read_v3s16(L, 2);
3668                 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3669
3670                 // Don't attempt to load non-loaded area as of now
3671                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3672                 if(n_old.getContent() == CONTENT_IGNORE){
3673                         lua_pushboolean(L, false);
3674                         return 1;
3675                 }
3676                 // Create item to place
3677                 INodeDefManager *ndef = get_server(L)->ndef();
3678                 IItemDefManager *idef = get_server(L)->idef();
3679                 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3680                 // Make pointed position
3681                 PointedThing pointed;
3682                 pointed.type = POINTEDTHING_NODE;
3683                 pointed.node_abovesurface = pos;
3684                 pointed.node_undersurface = pos + v3s16(0,-1,0);
3685                 // Place it with a NULL placer (appears in Lua as a non-functional
3686                 // ObjectRef)
3687                 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3688                 lua_pushboolean(L, success);
3689                 return 1;
3690         }
3691
3692         // EnvRef:dig_node(pos)
3693         // pos = {x=num, y=num, z=num}
3694         static int l_dig_node(lua_State *L)
3695         {
3696                 EnvRef *o = checkobject(L, 1);
3697                 ServerEnvironment *env = o->m_env;
3698                 if(env == NULL) return 0;
3699                 v3s16 pos = read_v3s16(L, 2);
3700
3701                 // Don't attempt to load non-loaded area as of now
3702                 MapNode n = env->getMap().getNodeNoEx(pos);
3703                 if(n.getContent() == CONTENT_IGNORE){
3704                         lua_pushboolean(L, false);
3705                         return 1;
3706                 }
3707                 // Dig it out with a NULL digger (appears in Lua as a
3708                 // non-functional ObjectRef)
3709                 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3710                 lua_pushboolean(L, success);
3711                 return 1;
3712         }
3713
3714         // EnvRef:punch_node(pos)
3715         // pos = {x=num, y=num, z=num}
3716         static int l_punch_node(lua_State *L)
3717         {
3718                 EnvRef *o = checkobject(L, 1);
3719                 ServerEnvironment *env = o->m_env;
3720                 if(env == NULL) return 0;
3721                 v3s16 pos = read_v3s16(L, 2);
3722
3723                 // Don't attempt to load non-loaded area as of now
3724                 MapNode n = env->getMap().getNodeNoEx(pos);
3725                 if(n.getContent() == CONTENT_IGNORE){
3726                         lua_pushboolean(L, false);
3727                         return 1;
3728                 }
3729                 // Punch it with a NULL puncher (appears in Lua as a non-functional
3730                 // ObjectRef)
3731                 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3732                 lua_pushboolean(L, success);
3733                 return 1;
3734         }
3735
3736         // EnvRef:get_meta(pos)
3737         static int l_get_meta(lua_State *L)
3738         {
3739                 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3740                 EnvRef *o = checkobject(L, 1);
3741                 ServerEnvironment *env = o->m_env;
3742                 if(env == NULL) return 0;
3743                 // Do it
3744                 v3s16 p = read_v3s16(L, 2);
3745                 NodeMetaRef::create(L, p, env);
3746                 return 1;
3747         }
3748
3749         // EnvRef:get_node_timer(pos)
3750         static int l_get_node_timer(lua_State *L)
3751         {
3752                 EnvRef *o = checkobject(L, 1);
3753                 ServerEnvironment *env = o->m_env;
3754                 if(env == NULL) return 0;
3755                 // Do it
3756                 v3s16 p = read_v3s16(L, 2);
3757                 NodeTimerRef::create(L, p, env);
3758                 return 1;
3759         }
3760
3761         // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3762         // pos = {x=num, y=num, z=num}
3763         static int l_add_entity(lua_State *L)
3764         {
3765                 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3766                 EnvRef *o = checkobject(L, 1);
3767                 ServerEnvironment *env = o->m_env;
3768                 if(env == NULL) return 0;
3769                 // pos
3770                 v3f pos = checkFloatPos(L, 2);
3771                 // content
3772                 const char *name = luaL_checkstring(L, 3);
3773                 // Do it
3774                 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3775                 int objectid = env->addActiveObject(obj);
3776                 // If failed to add, return nothing (reads as nil)
3777                 if(objectid == 0)
3778                         return 0;
3779                 // Return ObjectRef
3780                 objectref_get_or_create(L, obj);
3781                 return 1;
3782         }
3783
3784         // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3785         // pos = {x=num, y=num, z=num}
3786         static int l_add_item(lua_State *L)
3787         {
3788                 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3789                 EnvRef *o = checkobject(L, 1);
3790                 ServerEnvironment *env = o->m_env;
3791                 if(env == NULL) return 0;
3792                 // pos
3793                 v3f pos = checkFloatPos(L, 2);
3794                 // item
3795                 ItemStack item = read_item(L, 3);
3796                 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3797                         return 0;
3798                 // Use minetest.spawn_item to spawn a __builtin:item
3799                 lua_getglobal(L, "minetest");
3800                 lua_getfield(L, -1, "spawn_item");
3801                 if(lua_isnil(L, -1))
3802                         return 0;
3803                 lua_pushvalue(L, 2);
3804                 lua_pushstring(L, item.getItemString().c_str());
3805                 if(lua_pcall(L, 2, 1, 0))
3806                         script_error(L, "error: %s", lua_tostring(L, -1));
3807                 return 1;
3808                 /*lua_pushvalue(L, 1);
3809                 lua_pushstring(L, "__builtin:item");
3810                 lua_pushstring(L, item.getItemString().c_str());
3811                 return l_add_entity(L);*/
3812                 /*// Do it
3813                 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3814                 int objectid = env->addActiveObject(obj);
3815                 // If failed to add, return nothing (reads as nil)
3816                 if(objectid == 0)
3817                         return 0;
3818                 // Return ObjectRef
3819                 objectref_get_or_create(L, obj);
3820                 return 1;*/
3821         }
3822
3823         // EnvRef:add_rat(pos)
3824         // pos = {x=num, y=num, z=num}
3825         static int l_add_rat(lua_State *L)
3826         {
3827                 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3828                                 <<" Doing nothing."<<std::endl;
3829                 return 0;
3830         }
3831
3832         // EnvRef:add_firefly(pos)
3833         // pos = {x=num, y=num, z=num}
3834         static int l_add_firefly(lua_State *L)
3835         {
3836                 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3837                                 <<" Doing nothing."<<std::endl;
3838                 return 0;
3839         }
3840
3841         // EnvRef:get_player_by_name(name)
3842         static int l_get_player_by_name(lua_State *L)
3843         {
3844                 EnvRef *o = checkobject(L, 1);
3845                 ServerEnvironment *env = o->m_env;
3846                 if(env == NULL) return 0;
3847                 // Do it
3848                 const char *name = luaL_checkstring(L, 2);
3849                 Player *player = env->getPlayer(name);
3850                 if(player == NULL){
3851                         lua_pushnil(L);
3852                         return 1;
3853                 }
3854                 PlayerSAO *sao = player->getPlayerSAO();
3855                 if(sao == NULL){
3856                         lua_pushnil(L);
3857                         return 1;
3858                 }
3859                 // Put player on stack
3860                 objectref_get_or_create(L, sao);
3861                 return 1;
3862         }
3863
3864         // EnvRef:get_objects_inside_radius(pos, radius)
3865         static int l_get_objects_inside_radius(lua_State *L)
3866         {
3867                 // Get the table insert function
3868                 lua_getglobal(L, "table");
3869                 lua_getfield(L, -1, "insert");
3870                 int table_insert = lua_gettop(L);
3871                 // Get environemnt
3872                 EnvRef *o = checkobject(L, 1);
3873                 ServerEnvironment *env = o->m_env;
3874                 if(env == NULL) return 0;
3875                 // Do it
3876                 v3f pos = checkFloatPos(L, 2);
3877                 float radius = luaL_checknumber(L, 3) * BS;
3878                 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3879                 lua_newtable(L);
3880                 int table = lua_gettop(L);
3881                 for(std::set<u16>::const_iterator
3882                                 i = ids.begin(); i != ids.end(); i++){
3883                         ServerActiveObject *obj = env->getActiveObject(*i);
3884                         // Insert object reference into table
3885                         lua_pushvalue(L, table_insert);
3886                         lua_pushvalue(L, table);
3887                         objectref_get_or_create(L, obj);
3888                         if(lua_pcall(L, 2, 0, 0))
3889                                 script_error(L, "error: %s", lua_tostring(L, -1));
3890                 }
3891                 return 1;
3892         }
3893
3894         // EnvRef:set_timeofday(val)
3895         // val = 0...1
3896         static int l_set_timeofday(lua_State *L)
3897         {
3898                 EnvRef *o = checkobject(L, 1);
3899                 ServerEnvironment *env = o->m_env;
3900                 if(env == NULL) return 0;
3901                 // Do it
3902                 float timeofday_f = luaL_checknumber(L, 2);
3903                 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3904                 int timeofday_mh = (int)(timeofday_f * 24000.0);
3905                 // This should be set directly in the environment but currently
3906                 // such changes aren't immediately sent to the clients, so call
3907                 // the server instead.
3908                 //env->setTimeOfDay(timeofday_mh);
3909                 get_server(L)->setTimeOfDay(timeofday_mh);
3910                 return 0;
3911         }
3912
3913         // EnvRef:get_timeofday() -> 0...1
3914         static int l_get_timeofday(lua_State *L)
3915         {
3916                 EnvRef *o = checkobject(L, 1);
3917                 ServerEnvironment *env = o->m_env;
3918                 if(env == NULL) return 0;
3919                 // Do it
3920                 int timeofday_mh = env->getTimeOfDay();
3921                 float timeofday_f = (float)timeofday_mh / 24000.0;
3922                 lua_pushnumber(L, timeofday_f);
3923                 return 1;
3924         }
3925
3926
3927         // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3928         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3929         static int l_find_node_near(lua_State *L)
3930         {
3931                 EnvRef *o = checkobject(L, 1);
3932                 ServerEnvironment *env = o->m_env;
3933                 if(env == NULL) return 0;
3934                 INodeDefManager *ndef = get_server(L)->ndef();
3935                 v3s16 pos = read_v3s16(L, 2);
3936                 int radius = luaL_checkinteger(L, 3);
3937                 std::set<content_t> filter;
3938                 if(lua_istable(L, 4)){
3939                         int table = 4;
3940                         lua_pushnil(L);
3941                         while(lua_next(L, table) != 0){
3942                                 // key at index -2 and value at index -1
3943                                 luaL_checktype(L, -1, LUA_TSTRING);
3944                                 ndef->getIds(lua_tostring(L, -1), filter);
3945                                 // removes value, keeps key for next iteration
3946                                 lua_pop(L, 1);
3947                         }
3948                 } else if(lua_isstring(L, 4)){
3949                         ndef->getIds(lua_tostring(L, 4), filter);
3950                 }
3951
3952                 for(int d=1; d<=radius; d++){
3953                         core::list<v3s16> list;
3954                         getFacePositions(list, d);
3955                         for(core::list<v3s16>::Iterator i = list.begin();
3956                                         i != list.end(); i++){
3957                                 v3s16 p = pos + (*i);
3958                                 content_t c = env->getMap().getNodeNoEx(p).getContent();
3959                                 if(filter.count(c) != 0){
3960                                         push_v3s16(L, p);
3961                                         return 1;
3962                                 }
3963                         }
3964                 }
3965                 return 0;
3966         }
3967
3968         // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3969         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3970         static int l_find_nodes_in_area(lua_State *L)
3971         {
3972                 EnvRef *o = checkobject(L, 1);
3973                 ServerEnvironment *env = o->m_env;
3974                 if(env == NULL) return 0;
3975                 INodeDefManager *ndef = get_server(L)->ndef();
3976                 v3s16 minp = read_v3s16(L, 2);
3977                 v3s16 maxp = read_v3s16(L, 3);
3978                 std::set<content_t> filter;
3979                 if(lua_istable(L, 4)){
3980                         int table = 4;
3981                         lua_pushnil(L);
3982                         while(lua_next(L, table) != 0){
3983                                 // key at index -2 and value at index -1
3984                                 luaL_checktype(L, -1, LUA_TSTRING);
3985                                 ndef->getIds(lua_tostring(L, -1), filter);
3986                                 // removes value, keeps key for next iteration
3987                                 lua_pop(L, 1);
3988                         }
3989                 } else if(lua_isstring(L, 4)){
3990                         ndef->getIds(lua_tostring(L, 4), filter);
3991                 }
3992
3993                 // Get the table insert function
3994                 lua_getglobal(L, "table");
3995                 lua_getfield(L, -1, "insert");
3996                 int table_insert = lua_gettop(L);
3997                 
3998                 lua_newtable(L);
3999                 int table = lua_gettop(L);
4000                 for(s16 x=minp.X; x<=maxp.X; x++)
4001                 for(s16 y=minp.Y; y<=maxp.Y; y++)
4002                 for(s16 z=minp.Z; z<=maxp.Z; z++)
4003                 {
4004                         v3s16 p(x,y,z);
4005                         content_t c = env->getMap().getNodeNoEx(p).getContent();
4006                         if(filter.count(c) != 0){
4007                                 lua_pushvalue(L, table_insert);
4008                                 lua_pushvalue(L, table);
4009                                 push_v3s16(L, p);
4010                                 if(lua_pcall(L, 2, 0, 0))
4011                                         script_error(L, "error: %s", lua_tostring(L, -1));
4012                         }
4013                 }
4014                 return 1;
4015         }
4016
4017         //      EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
4018         //  returns world-specific PerlinNoise
4019         static int l_get_perlin(lua_State *L)
4020         {
4021                 EnvRef *o = checkobject(L, 1);
4022                 ServerEnvironment *env = o->m_env;
4023                 if(env == NULL) return 0;
4024
4025                 int seeddiff = luaL_checkint(L, 2);
4026                 int octaves = luaL_checkint(L, 3);
4027                 double persistence = luaL_checknumber(L, 4);
4028                 double scale = luaL_checknumber(L, 5);
4029
4030                 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
4031                 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4032                 luaL_getmetatable(L, "PerlinNoise");
4033                 lua_setmetatable(L, -2);
4034                 return 1;
4035         }
4036
4037         // EnvRef:clear_objects()
4038         // clear all objects in the environment
4039         static int l_clear_objects(lua_State *L)
4040         {
4041                 EnvRef *o = checkobject(L, 1);
4042                 o->m_env->clearAllObjects();
4043                 return 0;
4044         }
4045
4046         static int l_spawn_tree(lua_State *L)
4047         {
4048                 EnvRef *o = checkobject(L, 1);
4049                 ServerEnvironment *env = o->m_env;
4050                 if(env == NULL) return 0;
4051                 v3s16 p0 = read_v3s16(L, 2);
4052
4053                 treegen::TreeDef tree_def;
4054                 std::string trunk,leaves,fruit;
4055                 INodeDefManager *ndef = env->getGameDef()->ndef();
4056
4057                 if(lua_istable(L, 3))
4058                 {
4059                         getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4060                         getstringfield(L, 3, "rules_a", tree_def.rules_a);
4061                         getstringfield(L, 3, "rules_b", tree_def.rules_b);
4062                         getstringfield(L, 3, "rules_c", tree_def.rules_a);
4063                         getstringfield(L, 3, "rules_d", tree_def.rules_b);
4064                         getstringfield(L, 3, "trunk", trunk);
4065                         tree_def.trunknode=ndef->getId(trunk);
4066                         getstringfield(L, 3, "leaves", leaves);
4067                         tree_def.leavesnode=ndef->getId(leaves);
4068                         getintfield(L, 3, "angle", tree_def.angle);
4069                         getintfield(L, 3, "iterations", tree_def.iterations);
4070                         getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4071                         getboolfield(L, 3, "thin_trunks", tree_def.thin_trunks);
4072                         getboolfield(L, 3, "fruit_tree", tree_def.fruit_tree);
4073                         if (tree_def.fruit_tree)
4074                         {
4075                                 getstringfield(L, 3, "fruit", fruit);
4076                                 tree_def.fruitnode=ndef->getId(fruit);
4077                         }
4078                 }
4079                 else
4080                         return 0;
4081                 treegen::spawn_ltree (env, p0, ndef, tree_def);
4082                 return 1;
4083         }
4084
4085 public:
4086         EnvRef(ServerEnvironment *env):
4087                 m_env(env)
4088         {
4089                 //infostream<<"EnvRef created"<<std::endl;
4090         }
4091
4092         ~EnvRef()
4093         {
4094                 //infostream<<"EnvRef destructing"<<std::endl;
4095         }
4096
4097         // Creates an EnvRef and leaves it on top of stack
4098         // Not callable from Lua; all references are created on the C side.
4099         static void create(lua_State *L, ServerEnvironment *env)
4100         {
4101                 EnvRef *o = new EnvRef(env);
4102                 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4103                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4104                 luaL_getmetatable(L, className);
4105                 lua_setmetatable(L, -2);
4106         }
4107
4108         static void set_null(lua_State *L)
4109         {
4110                 EnvRef *o = checkobject(L, -1);
4111                 o->m_env = NULL;
4112         }
4113         
4114         static void Register(lua_State *L)
4115         {
4116                 lua_newtable(L);
4117                 int methodtable = lua_gettop(L);
4118                 luaL_newmetatable(L, className);
4119                 int metatable = lua_gettop(L);
4120
4121                 lua_pushliteral(L, "__metatable");
4122                 lua_pushvalue(L, methodtable);
4123                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
4124
4125                 lua_pushliteral(L, "__index");
4126                 lua_pushvalue(L, methodtable);
4127                 lua_settable(L, metatable);
4128
4129                 lua_pushliteral(L, "__gc");
4130                 lua_pushcfunction(L, gc_object);
4131                 lua_settable(L, metatable);
4132
4133                 lua_pop(L, 1);  // drop metatable
4134
4135                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
4136                 lua_pop(L, 1);  // drop methodtable
4137
4138                 // Cannot be created from Lua
4139                 //lua_register(L, className, create_object);
4140         }
4141 };
4142 const char EnvRef::className[] = "EnvRef";
4143 const luaL_reg EnvRef::methods[] = {
4144         method(EnvRef, set_node),
4145         method(EnvRef, add_node),
4146         method(EnvRef, remove_node),
4147         method(EnvRef, get_node),
4148         method(EnvRef, get_node_or_nil),
4149         method(EnvRef, get_node_light),
4150         method(EnvRef, place_node),
4151         method(EnvRef, dig_node),
4152         method(EnvRef, punch_node),
4153         method(EnvRef, add_entity),
4154         method(EnvRef, add_item),
4155         method(EnvRef, add_rat),
4156         method(EnvRef, add_firefly),
4157         method(EnvRef, get_meta),
4158         method(EnvRef, get_node_timer),
4159         method(EnvRef, get_player_by_name),
4160         method(EnvRef, get_objects_inside_radius),
4161         method(EnvRef, set_timeofday),
4162         method(EnvRef, get_timeofday),
4163         method(EnvRef, find_node_near),
4164         method(EnvRef, find_nodes_in_area),
4165         method(EnvRef, get_perlin),
4166         method(EnvRef, clear_objects),
4167         method(EnvRef, spawn_tree),
4168         {0,0}
4169 };
4170
4171 /*
4172         LuaPseudoRandom
4173 */
4174
4175
4176 class LuaPseudoRandom
4177 {
4178 private:
4179         PseudoRandom m_pseudo;
4180
4181         static const char className[];
4182         static const luaL_reg methods[];
4183
4184         // Exported functions
4185         
4186         // garbage collector
4187         static int gc_object(lua_State *L)
4188         {
4189                 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4190                 delete o;
4191                 return 0;
4192         }
4193
4194         // next(self, min=0, max=32767) -> get next value
4195         static int l_next(lua_State *L)
4196         {
4197                 LuaPseudoRandom *o = checkobject(L, 1);
4198                 int min = 0;
4199                 int max = 32767;
4200                 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4201                 if(!lua_isnil(L, 2))
4202                         min = luaL_checkinteger(L, 2);
4203                 if(!lua_isnil(L, 3))
4204                         max = luaL_checkinteger(L, 3);
4205                 if(max < min){
4206                         errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4207                         throw LuaError(L, "PseudoRandom.next(): max < min");
4208                 }
4209                 if(max - min != 32767 && max - min > 32767/5)
4210                         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.");
4211                 PseudoRandom &pseudo = o->m_pseudo;
4212                 int val = pseudo.next();
4213                 val = (val % (max-min+1)) + min;
4214                 lua_pushinteger(L, val);
4215                 return 1;
4216         }
4217
4218 public:
4219         LuaPseudoRandom(int seed):
4220                 m_pseudo(seed)
4221         {
4222         }
4223
4224         ~LuaPseudoRandom()
4225         {
4226         }
4227
4228         const PseudoRandom& getItem() const
4229         {
4230                 return m_pseudo;
4231         }
4232         PseudoRandom& getItem()
4233         {
4234                 return m_pseudo;
4235         }
4236         
4237         // LuaPseudoRandom(seed)
4238         // Creates an LuaPseudoRandom and leaves it on top of stack
4239         static int create_object(lua_State *L)
4240         {
4241                 int seed = luaL_checknumber(L, 1);
4242                 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4243                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4244                 luaL_getmetatable(L, className);
4245                 lua_setmetatable(L, -2);
4246                 return 1;
4247         }
4248
4249         static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4250         {
4251                 luaL_checktype(L, narg, LUA_TUSERDATA);
4252                 void *ud = luaL_checkudata(L, narg, className);
4253                 if(!ud) luaL_typerror(L, narg, className);
4254                 return *(LuaPseudoRandom**)ud;  // unbox pointer
4255         }
4256
4257         static void Register(lua_State *L)
4258         {
4259                 lua_newtable(L);
4260                 int methodtable = lua_gettop(L);
4261                 luaL_newmetatable(L, className);
4262                 int metatable = lua_gettop(L);
4263
4264                 lua_pushliteral(L, "__metatable");
4265                 lua_pushvalue(L, methodtable);
4266                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
4267
4268                 lua_pushliteral(L, "__index");
4269                 lua_pushvalue(L, methodtable);
4270                 lua_settable(L, metatable);
4271
4272                 lua_pushliteral(L, "__gc");
4273                 lua_pushcfunction(L, gc_object);
4274                 lua_settable(L, metatable);
4275
4276                 lua_pop(L, 1);  // drop metatable
4277
4278                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
4279                 lua_pop(L, 1);  // drop methodtable
4280
4281                 // Can be created from Lua (LuaPseudoRandom(seed))
4282                 lua_register(L, className, create_object);
4283         }
4284 };
4285 const char LuaPseudoRandom::className[] = "PseudoRandom";
4286 const luaL_reg LuaPseudoRandom::methods[] = {
4287         method(LuaPseudoRandom, next),
4288         {0,0}
4289 };
4290
4291
4292
4293 /*
4294         LuaABM
4295 */
4296
4297 class LuaABM : public ActiveBlockModifier
4298 {
4299 private:
4300         lua_State *m_lua;
4301         int m_id;
4302
4303         std::set<std::string> m_trigger_contents;
4304         std::set<std::string> m_required_neighbors;
4305         float m_trigger_interval;
4306         u32 m_trigger_chance;
4307 public:
4308         LuaABM(lua_State *L, int id,
4309                         const std::set<std::string> &trigger_contents,
4310                         const std::set<std::string> &required_neighbors,
4311                         float trigger_interval, u32 trigger_chance):
4312                 m_lua(L),
4313                 m_id(id),
4314                 m_trigger_contents(trigger_contents),
4315                 m_required_neighbors(required_neighbors),
4316                 m_trigger_interval(trigger_interval),
4317                 m_trigger_chance(trigger_chance)
4318         {
4319         }
4320         virtual std::set<std::string> getTriggerContents()
4321         {
4322                 return m_trigger_contents;
4323         }
4324         virtual std::set<std::string> getRequiredNeighbors()
4325         {
4326                 return m_required_neighbors;
4327         }
4328         virtual float getTriggerInterval()
4329         {
4330                 return m_trigger_interval;
4331         }
4332         virtual u32 getTriggerChance()
4333         {
4334                 return m_trigger_chance;
4335         }
4336         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4337                         u32 active_object_count, u32 active_object_count_wider)
4338         {
4339                 lua_State *L = m_lua;
4340         
4341                 realitycheck(L);
4342                 assert(lua_checkstack(L, 20));
4343                 StackUnroller stack_unroller(L);
4344
4345                 // Get minetest.registered_abms
4346                 lua_getglobal(L, "minetest");
4347                 lua_getfield(L, -1, "registered_abms");
4348                 luaL_checktype(L, -1, LUA_TTABLE);
4349                 int registered_abms = lua_gettop(L);
4350
4351                 // Get minetest.registered_abms[m_id]
4352                 lua_pushnumber(L, m_id);
4353                 lua_gettable(L, registered_abms);
4354                 if(lua_isnil(L, -1))
4355                         assert(0);
4356                 
4357                 // Call action
4358                 luaL_checktype(L, -1, LUA_TTABLE);
4359                 lua_getfield(L, -1, "action");
4360                 luaL_checktype(L, -1, LUA_TFUNCTION);
4361                 push_v3s16(L, p);
4362                 pushnode(L, n, env->getGameDef()->ndef());
4363                 lua_pushnumber(L, active_object_count);
4364                 lua_pushnumber(L, active_object_count_wider);
4365                 if(lua_pcall(L, 4, 0, 0))
4366                         script_error(L, "error: %s", lua_tostring(L, -1));
4367         }
4368 };
4369
4370 /*
4371         ServerSoundParams
4372 */
4373
4374 static void read_server_sound_params(lua_State *L, int index,
4375                 ServerSoundParams &params)
4376 {
4377         if(index < 0)
4378                 index = lua_gettop(L) + 1 + index;
4379         // Clear
4380         params = ServerSoundParams();
4381         if(lua_istable(L, index)){
4382                 getfloatfield(L, index, "gain", params.gain);
4383                 getstringfield(L, index, "to_player", params.to_player);
4384                 lua_getfield(L, index, "pos");
4385                 if(!lua_isnil(L, -1)){
4386                         v3f p = read_v3f(L, -1)*BS;
4387                         params.pos = p;
4388                         params.type = ServerSoundParams::SSP_POSITIONAL;
4389                 }
4390                 lua_pop(L, 1);
4391                 lua_getfield(L, index, "object");
4392                 if(!lua_isnil(L, -1)){
4393                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
4394                         ServerActiveObject *sao = ObjectRef::getobject(ref);
4395                         if(sao){
4396                                 params.object = sao->getId();
4397                                 params.type = ServerSoundParams::SSP_OBJECT;
4398                         }
4399                 }
4400                 lua_pop(L, 1);
4401                 params.max_hear_distance = BS*getfloatfield_default(L, index,
4402                                 "max_hear_distance", params.max_hear_distance/BS);
4403                 getboolfield(L, index, "loop", params.loop);
4404         }
4405 }
4406
4407 /*
4408         Global functions
4409 */
4410
4411 // debug(text)
4412 // Writes a line to dstream
4413 static int l_debug(lua_State *L)
4414 {
4415         std::string text = lua_tostring(L, 1);
4416         dstream << text << std::endl;
4417         return 0;
4418 }
4419
4420 // log([level,] text)
4421 // Writes a line to the logger.
4422 // The one-argument version logs to infostream.
4423 // The two-argument version accept a log level: error, action, info, or verbose.
4424 static int l_log(lua_State *L)
4425 {
4426         std::string text;
4427         LogMessageLevel level = LMT_INFO;
4428         if(lua_isnone(L, 2))
4429         {
4430                 text = lua_tostring(L, 1);
4431         }
4432         else
4433         {
4434                 std::string levelname = lua_tostring(L, 1);
4435                 text = lua_tostring(L, 2);
4436                 if(levelname == "error")
4437                         level = LMT_ERROR;
4438                 else if(levelname == "action")
4439                         level = LMT_ACTION;
4440                 else if(levelname == "verbose")
4441                         level = LMT_VERBOSE;
4442         }
4443         log_printline(level, text);
4444         return 0;
4445 }
4446
4447 // request_shutdown()
4448 static int l_request_shutdown(lua_State *L)
4449 {
4450         get_server(L)->requestShutdown();
4451         return 0;
4452 }
4453
4454 // get_server_status()
4455 static int l_get_server_status(lua_State *L)
4456 {
4457         lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4458         return 1;
4459 }
4460
4461 // register_item_raw({lots of stuff})
4462 static int l_register_item_raw(lua_State *L)
4463 {
4464         luaL_checktype(L, 1, LUA_TTABLE);
4465         int table = 1;
4466
4467         // Get the writable item and node definition managers from the server
4468         IWritableItemDefManager *idef =
4469                         get_server(L)->getWritableItemDefManager();
4470         IWritableNodeDefManager *ndef =
4471                         get_server(L)->getWritableNodeDefManager();
4472
4473         // Check if name is defined
4474         std::string name;
4475         lua_getfield(L, table, "name");
4476         if(lua_isstring(L, -1)){
4477                 name = lua_tostring(L, -1);
4478                 verbosestream<<"register_item_raw: "<<name<<std::endl;
4479         } else {
4480                 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4481         }
4482
4483         // Check if on_use is defined
4484
4485         ItemDefinition def;
4486         // Set a distinctive default value to check if this is set
4487         def.node_placement_prediction = "__default";
4488
4489         // Read the item definition
4490         def = read_item_definition(L, table, def);
4491
4492         // Default to having client-side placement prediction for nodes
4493         // ("" in item definition sets it off)
4494         if(def.node_placement_prediction == "__default"){
4495                 if(def.type == ITEM_NODE)
4496                         def.node_placement_prediction = name;
4497                 else
4498                         def.node_placement_prediction = "";
4499         }
4500         
4501         // Register item definition
4502         idef->registerItem(def);
4503
4504         // Read the node definition (content features) and register it
4505         if(def.type == ITEM_NODE)
4506         {
4507                 ContentFeatures f = read_content_features(L, table);
4508                 ndef->set(f.name, f);
4509         }
4510
4511         return 0; /* number of results */
4512 }
4513
4514 // register_alias_raw(name, convert_to_name)
4515 static int l_register_alias_raw(lua_State *L)
4516 {
4517         std::string name = luaL_checkstring(L, 1);
4518         std::string convert_to = luaL_checkstring(L, 2);
4519
4520         // Get the writable item definition manager from the server
4521         IWritableItemDefManager *idef =
4522                         get_server(L)->getWritableItemDefManager();
4523         
4524         idef->registerAlias(name, convert_to);
4525         
4526         return 0; /* number of results */
4527 }
4528
4529 // helper for register_craft
4530 static bool read_craft_recipe_shaped(lua_State *L, int index,
4531                 int &width, std::vector<std::string> &recipe)
4532 {
4533         if(index < 0)
4534                 index = lua_gettop(L) + 1 + index;
4535
4536         if(!lua_istable(L, index))
4537                 return false;
4538
4539         lua_pushnil(L);
4540         int rowcount = 0;
4541         while(lua_next(L, index) != 0){
4542                 int colcount = 0;
4543                 // key at index -2 and value at index -1
4544                 if(!lua_istable(L, -1))
4545                         return false;
4546                 int table2 = lua_gettop(L);
4547                 lua_pushnil(L);
4548                 while(lua_next(L, table2) != 0){
4549                         // key at index -2 and value at index -1
4550                         if(!lua_isstring(L, -1))
4551                                 return false;
4552                         recipe.push_back(lua_tostring(L, -1));
4553                         // removes value, keeps key for next iteration
4554                         lua_pop(L, 1);
4555                         colcount++;
4556                 }
4557                 if(rowcount == 0){
4558                         width = colcount;
4559                 } else {
4560                         if(colcount != width)
4561                                 return false;
4562                 }
4563                 // removes value, keeps key for next iteration
4564                 lua_pop(L, 1);
4565                 rowcount++;
4566         }
4567         return width != 0;
4568 }
4569
4570 // helper for register_craft
4571 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4572                 std::vector<std::string> &recipe)
4573 {
4574         if(index < 0)
4575                 index = lua_gettop(L) + 1 + index;
4576
4577         if(!lua_istable(L, index))
4578                 return false;
4579
4580         lua_pushnil(L);
4581         while(lua_next(L, index) != 0){
4582                 // key at index -2 and value at index -1
4583                 if(!lua_isstring(L, -1))
4584                         return false;
4585                 recipe.push_back(lua_tostring(L, -1));
4586                 // removes value, keeps key for next iteration
4587                 lua_pop(L, 1);
4588         }
4589         return true;
4590 }
4591
4592 // helper for register_craft
4593 static bool read_craft_replacements(lua_State *L, int index,
4594                 CraftReplacements &replacements)
4595 {
4596         if(index < 0)
4597                 index = lua_gettop(L) + 1 + index;
4598
4599         if(!lua_istable(L, index))
4600                 return false;
4601
4602         lua_pushnil(L);
4603         while(lua_next(L, index) != 0){
4604                 // key at index -2 and value at index -1
4605                 if(!lua_istable(L, -1))
4606                         return false;
4607                 lua_rawgeti(L, -1, 1);
4608                 if(!lua_isstring(L, -1))
4609                         return false;
4610                 std::string replace_from = lua_tostring(L, -1);
4611                 lua_pop(L, 1);
4612                 lua_rawgeti(L, -1, 2);
4613                 if(!lua_isstring(L, -1))
4614                         return false;
4615                 std::string replace_to = lua_tostring(L, -1);
4616                 lua_pop(L, 1);
4617                 replacements.pairs.push_back(
4618                                 std::make_pair(replace_from, replace_to));
4619                 // removes value, keeps key for next iteration
4620                 lua_pop(L, 1);
4621         }
4622         return true;
4623 }
4624 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4625 static int l_register_craft(lua_State *L)
4626 {
4627         //infostream<<"register_craft"<<std::endl;
4628         luaL_checktype(L, 1, LUA_TTABLE);
4629         int table = 1;
4630
4631         // Get the writable craft definition manager from the server
4632         IWritableCraftDefManager *craftdef =
4633                         get_server(L)->getWritableCraftDefManager();
4634         
4635         std::string type = getstringfield_default(L, table, "type", "shaped");
4636
4637         /*
4638                 CraftDefinitionShaped
4639         */
4640         if(type == "shaped"){
4641                 std::string output = getstringfield_default(L, table, "output", "");
4642                 if(output == "")
4643                         throw LuaError(L, "Crafting definition is missing an output");
4644
4645                 int width = 0;
4646                 std::vector<std::string> recipe;
4647                 lua_getfield(L, table, "recipe");
4648                 if(lua_isnil(L, -1))
4649                         throw LuaError(L, "Crafting definition is missing a recipe"
4650                                         " (output=\"" + output + "\")");
4651                 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4652                         throw LuaError(L, "Invalid crafting recipe"
4653                                         " (output=\"" + output + "\")");
4654
4655                 CraftReplacements replacements;
4656                 lua_getfield(L, table, "replacements");
4657                 if(!lua_isnil(L, -1))
4658                 {
4659                         if(!read_craft_replacements(L, -1, replacements))
4660                                 throw LuaError(L, "Invalid replacements"
4661                                                 " (output=\"" + output + "\")");
4662                 }
4663
4664                 CraftDefinition *def = new CraftDefinitionShaped(
4665                                 output, width, recipe, replacements);
4666                 craftdef->registerCraft(def);
4667         }
4668         /*
4669                 CraftDefinitionShapeless
4670         */
4671         else if(type == "shapeless"){
4672                 std::string output = getstringfield_default(L, table, "output", "");
4673                 if(output == "")
4674                         throw LuaError(L, "Crafting definition (shapeless)"
4675                                         " is missing an output");
4676
4677                 std::vector<std::string> recipe;
4678                 lua_getfield(L, table, "recipe");
4679                 if(lua_isnil(L, -1))
4680                         throw LuaError(L, "Crafting definition (shapeless)"
4681                                         " is missing a recipe"
4682                                         " (output=\"" + output + "\")");
4683                 if(!read_craft_recipe_shapeless(L, -1, recipe))
4684                         throw LuaError(L, "Invalid crafting recipe"
4685                                         " (output=\"" + output + "\")");
4686
4687                 CraftReplacements replacements;
4688                 lua_getfield(L, table, "replacements");
4689                 if(!lua_isnil(L, -1))
4690                 {
4691                         if(!read_craft_replacements(L, -1, replacements))
4692                                 throw LuaError(L, "Invalid replacements"
4693                                                 " (output=\"" + output + "\")");
4694                 }
4695
4696                 CraftDefinition *def = new CraftDefinitionShapeless(
4697                                 output, recipe, replacements);
4698                 craftdef->registerCraft(def);
4699         }
4700         /*
4701                 CraftDefinitionToolRepair
4702         */
4703         else if(type == "toolrepair"){
4704                 float additional_wear = getfloatfield_default(L, table,
4705                                 "additional_wear", 0.0);
4706
4707                 CraftDefinition *def = new CraftDefinitionToolRepair(
4708                                 additional_wear);
4709                 craftdef->registerCraft(def);
4710         }
4711         /*
4712                 CraftDefinitionCooking
4713         */
4714         else if(type == "cooking"){
4715                 std::string output = getstringfield_default(L, table, "output", "");
4716                 if(output == "")
4717                         throw LuaError(L, "Crafting definition (cooking)"
4718                                         " is missing an output");
4719
4720                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4721                 if(recipe == "")
4722                         throw LuaError(L, "Crafting definition (cooking)"
4723                                         " is missing a recipe"
4724                                         " (output=\"" + output + "\")");
4725
4726                 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4727
4728                 CraftReplacements replacements;
4729                 lua_getfield(L, table, "replacements");
4730                 if(!lua_isnil(L, -1))
4731                 {
4732                         if(!read_craft_replacements(L, -1, replacements))
4733                                 throw LuaError(L, "Invalid replacements"
4734                                                 " (cooking output=\"" + output + "\")");
4735                 }
4736
4737                 CraftDefinition *def = new CraftDefinitionCooking(
4738                                 output, recipe, cooktime, replacements);
4739                 craftdef->registerCraft(def);
4740         }
4741         /*
4742                 CraftDefinitionFuel
4743         */
4744         else if(type == "fuel"){
4745                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4746                 if(recipe == "")
4747                         throw LuaError(L, "Crafting definition (fuel)"
4748                                         " is missing a recipe");
4749
4750                 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4751
4752                 CraftReplacements replacements;
4753                 lua_getfield(L, table, "replacements");
4754                 if(!lua_isnil(L, -1))
4755                 {
4756                         if(!read_craft_replacements(L, -1, replacements))
4757                                 throw LuaError(L, "Invalid replacements"
4758                                                 " (fuel recipe=\"" + recipe + "\")");
4759                 }
4760
4761                 CraftDefinition *def = new CraftDefinitionFuel(
4762                                 recipe, burntime, replacements);
4763                 craftdef->registerCraft(def);
4764         }
4765         else
4766         {
4767                 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4768         }
4769
4770         lua_pop(L, 1);
4771         return 0; /* number of results */
4772 }
4773
4774 // setting_set(name, value)
4775 static int l_setting_set(lua_State *L)
4776 {
4777         const char *name = luaL_checkstring(L, 1);
4778         const char *value = luaL_checkstring(L, 2);
4779         g_settings->set(name, value);
4780         return 0;
4781 }
4782
4783 // setting_get(name)
4784 static int l_setting_get(lua_State *L)
4785 {
4786         const char *name = luaL_checkstring(L, 1);
4787         try{
4788                 std::string value = g_settings->get(name);
4789                 lua_pushstring(L, value.c_str());
4790         } catch(SettingNotFoundException &e){
4791                 lua_pushnil(L);
4792         }
4793         return 1;
4794 }
4795
4796 // setting_getbool(name)
4797 static int l_setting_getbool(lua_State *L)
4798 {
4799         const char *name = luaL_checkstring(L, 1);
4800         try{
4801                 bool value = g_settings->getBool(name);
4802                 lua_pushboolean(L, value);
4803         } catch(SettingNotFoundException &e){
4804                 lua_pushnil(L);
4805         }
4806         return 1;
4807 }
4808
4809 // chat_send_all(text)
4810 static int l_chat_send_all(lua_State *L)
4811 {
4812         const char *text = luaL_checkstring(L, 1);
4813         // Get server from registry
4814         Server *server = get_server(L);
4815         // Send
4816         server->notifyPlayers(narrow_to_wide(text));
4817         return 0;
4818 }
4819
4820 // chat_send_player(name, text)
4821 static int l_chat_send_player(lua_State *L)
4822 {
4823         const char *name = luaL_checkstring(L, 1);
4824         const char *text = luaL_checkstring(L, 2);
4825         // Get server from registry
4826         Server *server = get_server(L);
4827         // Send
4828         server->notifyPlayer(name, narrow_to_wide(text));
4829         return 0;
4830 }
4831
4832 // get_player_privs(name, text)
4833 static int l_get_player_privs(lua_State *L)
4834 {
4835         const char *name = luaL_checkstring(L, 1);
4836         // Get server from registry
4837         Server *server = get_server(L);
4838         // Do it
4839         lua_newtable(L);
4840         int table = lua_gettop(L);
4841         std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4842         for(std::set<std::string>::const_iterator
4843                         i = privs_s.begin(); i != privs_s.end(); i++){
4844                 lua_pushboolean(L, true);
4845                 lua_setfield(L, table, i->c_str());
4846         }
4847         lua_pushvalue(L, table);
4848         return 1;
4849 }
4850
4851 // get_ban_list()
4852 static int l_get_ban_list(lua_State *L)
4853 {
4854         lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4855         return 1;
4856 }
4857
4858 // get_ban_description()
4859 static int l_get_ban_description(lua_State *L)
4860 {
4861         const char * ip_or_name = luaL_checkstring(L, 1);
4862         lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4863         return 1;
4864 }
4865
4866 // ban_player()
4867 static int l_ban_player(lua_State *L)
4868 {
4869         const char * name = luaL_checkstring(L, 1);
4870         Player *player = get_env(L)->getPlayer(name);
4871         if(player == NULL)
4872         {
4873                 lua_pushboolean(L, false); // no such player
4874                 return 1;
4875         }
4876         try
4877         {
4878                 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4879                 std::string ip_str = addr.serializeString();
4880                 get_server(L)->setIpBanned(ip_str, name);
4881         }
4882         catch(con::PeerNotFoundException) // unlikely
4883         {
4884                 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4885                 lua_pushboolean(L, false); // error
4886                 return 1;
4887         }
4888         lua_pushboolean(L, true);
4889         return 1;
4890 }
4891
4892 // unban_player_or_ip()
4893 static int l_unban_player_of_ip(lua_State *L)
4894 {
4895         const char * ip_or_name = luaL_checkstring(L, 1);
4896         get_server(L)->unsetIpBanned(ip_or_name);
4897         lua_pushboolean(L, true);
4898         return 1;
4899 }
4900
4901 // get_inventory(location)
4902 static int l_get_inventory(lua_State *L)
4903 {
4904         InventoryLocation loc;
4905
4906         std::string type = checkstringfield(L, 1, "type");
4907         if(type == "player"){
4908                 std::string name = checkstringfield(L, 1, "name");
4909                 loc.setPlayer(name);
4910         } else if(type == "node"){
4911                 lua_getfield(L, 1, "pos");
4912                 v3s16 pos = check_v3s16(L, -1);
4913                 loc.setNodeMeta(pos);
4914         } else if(type == "detached"){
4915                 std::string name = checkstringfield(L, 1, "name");
4916                 loc.setDetached(name);
4917         }
4918         
4919         if(get_server(L)->getInventory(loc) != NULL)
4920                 InvRef::create(L, loc);
4921         else
4922                 lua_pushnil(L);
4923         return 1;
4924 }
4925
4926 // create_detached_inventory_raw(name)
4927 static int l_create_detached_inventory_raw(lua_State *L)
4928 {
4929         const char *name = luaL_checkstring(L, 1);
4930         if(get_server(L)->createDetachedInventory(name) != NULL){
4931                 InventoryLocation loc;
4932                 loc.setDetached(name);
4933                 InvRef::create(L, loc);
4934         }else{
4935                 lua_pushnil(L);
4936         }
4937         return 1;
4938 }
4939
4940 // create_detached_formspec_raw(name)
4941 static int l_show_formspec(lua_State *L)
4942 {
4943         const char *playername = luaL_checkstring(L, 1);
4944         const char *formspec = luaL_checkstring(L, 2);
4945
4946         if(get_server(L)->showFormspec(playername,formspec))
4947         {
4948                 lua_pushboolean(L, true);
4949         }else{
4950                 lua_pushboolean(L, false);
4951         }
4952         return 1;
4953 }
4954
4955 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4956 static int l_get_dig_params(lua_State *L)
4957 {
4958         std::map<std::string, int> groups;
4959         read_groups(L, 1, groups);
4960         ToolCapabilities tp = read_tool_capabilities(L, 2);
4961         if(lua_isnoneornil(L, 3))
4962                 push_dig_params(L, getDigParams(groups, &tp));
4963         else
4964                 push_dig_params(L, getDigParams(groups, &tp,
4965                                         luaL_checknumber(L, 3)));
4966         return 1;
4967 }
4968
4969 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4970 static int l_get_hit_params(lua_State *L)
4971 {
4972         std::map<std::string, int> groups;
4973         read_groups(L, 1, groups);
4974         ToolCapabilities tp = read_tool_capabilities(L, 2);
4975         if(lua_isnoneornil(L, 3))
4976                 push_hit_params(L, getHitParams(groups, &tp));
4977         else
4978                 push_hit_params(L, getHitParams(groups, &tp,
4979                                         luaL_checknumber(L, 3)));
4980         return 1;
4981 }
4982
4983 // get_current_modname()
4984 static int l_get_current_modname(lua_State *L)
4985 {
4986         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4987         return 1;
4988 }
4989
4990 // get_modpath(modname)
4991 static int l_get_modpath(lua_State *L)
4992 {
4993         std::string modname = luaL_checkstring(L, 1);
4994         // Do it
4995         if(modname == "__builtin"){
4996                 std::string path = get_server(L)->getBuiltinLuaPath();
4997                 lua_pushstring(L, path.c_str());
4998                 return 1;
4999         }
5000         const ModSpec *mod = get_server(L)->getModSpec(modname);
5001         if(!mod){
5002                 lua_pushnil(L);
5003                 return 1;
5004         }
5005         lua_pushstring(L, mod->path.c_str());
5006         return 1;
5007 }
5008
5009 // get_modnames()
5010 // the returned list is sorted alphabetically for you
5011 static int l_get_modnames(lua_State *L)
5012 {
5013         // Get a list of mods
5014         core::list<std::string> mods_unsorted, mods_sorted;
5015         get_server(L)->getModNames(mods_unsorted);
5016
5017         // Take unsorted items from mods_unsorted and sort them into
5018         // mods_sorted; not great performance but the number of mods on a
5019         // server will likely be small.
5020         for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5021             i != mods_unsorted.end(); i++)
5022         {
5023                 bool added = false;
5024                 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5025                     x != mods_unsorted.end(); x++)
5026                 {
5027                         // I doubt anybody using Minetest will be using
5028                         // anything not ASCII based :)
5029                         if((*i).compare(*x) <= 0)
5030                         {
5031                                 mods_sorted.insert_before(x, *i);
5032                                 added = true;
5033                                 break;
5034                         }
5035                 }
5036                 if(!added)
5037                         mods_sorted.push_back(*i);
5038         }
5039
5040         // Get the table insertion function from Lua.
5041         lua_getglobal(L, "table");
5042         lua_getfield(L, -1, "insert");
5043         int insertion_func = lua_gettop(L);
5044
5045         // Package them up for Lua
5046         lua_newtable(L);
5047         int new_table = lua_gettop(L);
5048         core::list<std::string>::Iterator i = mods_sorted.begin();
5049         while(i != mods_sorted.end())
5050         {
5051                 lua_pushvalue(L, insertion_func);
5052                 lua_pushvalue(L, new_table);
5053                 lua_pushstring(L, (*i).c_str());
5054                 if(lua_pcall(L, 2, 0, 0) != 0)
5055                 {
5056                         script_error(L, "error: %s", lua_tostring(L, -1));
5057                 }
5058                 i++;
5059         }
5060         return 1;
5061 }
5062
5063 // get_worldpath()
5064 static int l_get_worldpath(lua_State *L)
5065 {
5066         std::string worldpath = get_server(L)->getWorldPath();
5067         lua_pushstring(L, worldpath.c_str());
5068         return 1;
5069 }
5070
5071 // sound_play(spec, parameters)
5072 static int l_sound_play(lua_State *L)
5073 {
5074         SimpleSoundSpec spec;
5075         read_soundspec(L, 1, spec);
5076         ServerSoundParams params;
5077         read_server_sound_params(L, 2, params);
5078         s32 handle = get_server(L)->playSound(spec, params);
5079         lua_pushinteger(L, handle);
5080         return 1;
5081 }
5082
5083 // sound_stop(handle)
5084 static int l_sound_stop(lua_State *L)
5085 {
5086         int handle = luaL_checkinteger(L, 1);
5087         get_server(L)->stopSound(handle);
5088         return 0;
5089 }
5090
5091 // is_singleplayer()
5092 static int l_is_singleplayer(lua_State *L)
5093 {
5094         lua_pushboolean(L, get_server(L)->isSingleplayer());
5095         return 1;
5096 }
5097
5098 // get_password_hash(name, raw_password)
5099 static int l_get_password_hash(lua_State *L)
5100 {
5101         std::string name = luaL_checkstring(L, 1);
5102         std::string raw_password = luaL_checkstring(L, 2);
5103         std::string hash = translatePassword(name,
5104                         narrow_to_wide(raw_password));
5105         lua_pushstring(L, hash.c_str());
5106         return 1;
5107 }
5108
5109 // notify_authentication_modified(name)
5110 static int l_notify_authentication_modified(lua_State *L)
5111 {
5112         std::string name = "";
5113         if(lua_isstring(L, 1))
5114                 name = lua_tostring(L, 1);
5115         get_server(L)->reportPrivsModified(name);
5116         return 0;
5117 }
5118
5119 // get_craft_result(input)
5120 static int l_get_craft_result(lua_State *L)
5121 {
5122         int input_i = 1;
5123         std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5124         enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5125                                 es_CraftMethod, CRAFT_METHOD_NORMAL);
5126         int width = 1;
5127         lua_getfield(L, input_i, "width");
5128         if(lua_isnumber(L, -1))
5129                 width = luaL_checkinteger(L, -1);
5130         lua_pop(L, 1);
5131         lua_getfield(L, input_i, "items");
5132         std::vector<ItemStack> items = read_items(L, -1);
5133         lua_pop(L, 1); // items
5134         
5135         IGameDef *gdef = get_server(L);
5136         ICraftDefManager *cdef = gdef->cdef();
5137         CraftInput input(method, width, items);
5138         CraftOutput output;
5139         bool got = cdef->getCraftResult(input, output, true, gdef);
5140         lua_newtable(L); // output table
5141         if(got){
5142                 ItemStack item;
5143                 item.deSerialize(output.item, gdef->idef());
5144                 LuaItemStack::create(L, item);
5145                 lua_setfield(L, -2, "item");
5146                 setintfield(L, -1, "time", output.time);
5147         } else {
5148                 LuaItemStack::create(L, ItemStack());
5149                 lua_setfield(L, -2, "item");
5150                 setintfield(L, -1, "time", 0);
5151         }
5152         lua_newtable(L); // decremented input table
5153         lua_pushstring(L, method_s.c_str());
5154         lua_setfield(L, -2, "method");
5155         lua_pushinteger(L, width);
5156         lua_setfield(L, -2, "width");
5157         push_items(L, input.items);
5158         lua_setfield(L, -2, "items");
5159         return 2;
5160 }
5161
5162 // get_craft_recipe(result item)
5163 static int l_get_craft_recipe(lua_State *L)
5164 {
5165         int k = 0;
5166         char tmp[20];
5167         int input_i = 1;
5168         std::string o_item = luaL_checkstring(L,input_i);
5169         
5170         IGameDef *gdef = get_server(L);
5171         ICraftDefManager *cdef = gdef->cdef();
5172         CraftInput input;
5173         CraftOutput output(o_item,0);
5174         bool got = cdef->getCraftRecipe(input, output, gdef);
5175         lua_newtable(L); // output table
5176         if(got){
5177                 lua_newtable(L);
5178                 for(std::vector<ItemStack>::const_iterator
5179                         i = input.items.begin();
5180                         i != input.items.end(); i++, k++)
5181                 {
5182                         if (i->empty())
5183                         {
5184                                 continue;
5185                         }
5186                         sprintf(tmp,"%d",k);
5187                         lua_pushstring(L,tmp);
5188                         lua_pushstring(L,i->name.c_str());
5189                         lua_settable(L, -3);
5190                 }
5191                 lua_setfield(L, -2, "items");
5192                 setintfield(L, -1, "width", input.width);
5193                 switch (input.method) {
5194                 case CRAFT_METHOD_NORMAL:
5195                         lua_pushstring(L,"normal");
5196                         break;
5197                 case CRAFT_METHOD_COOKING:
5198                         lua_pushstring(L,"cooking");
5199                         break;
5200                 case CRAFT_METHOD_FUEL:
5201                         lua_pushstring(L,"fuel");
5202                         break;
5203                 default:
5204                         lua_pushstring(L,"unknown");
5205                 }
5206                 lua_setfield(L, -2, "type");
5207         } else {
5208                 lua_pushnil(L);
5209                 lua_setfield(L, -2, "items");
5210                 setintfield(L, -1, "width", 0);
5211         }
5212         return 1;
5213 }
5214
5215 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5216 static int l_rollback_get_last_node_actor(lua_State *L)
5217 {
5218         v3s16 p = read_v3s16(L, 1);
5219         int range = luaL_checknumber(L, 2);
5220         int seconds = luaL_checknumber(L, 3);
5221         Server *server = get_server(L);
5222         IRollbackManager *rollback = server->getRollbackManager();
5223         v3s16 act_p;
5224         int act_seconds = 0;
5225         std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5226         lua_pushstring(L, actor.c_str());
5227         push_v3s16(L, act_p);
5228         lua_pushnumber(L, act_seconds);
5229         return 3;
5230 }
5231
5232 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5233 static int l_rollback_revert_actions_by(lua_State *L)
5234 {
5235         std::string actor = luaL_checkstring(L, 1);
5236         int seconds = luaL_checknumber(L, 2);
5237         Server *server = get_server(L);
5238         IRollbackManager *rollback = server->getRollbackManager();
5239         std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5240         std::list<std::string> log;
5241         bool success = server->rollbackRevertActions(actions, &log);
5242         // Push boolean result
5243         lua_pushboolean(L, success);
5244         // Get the table insert function and push the log table
5245         lua_getglobal(L, "table");
5246         lua_getfield(L, -1, "insert");
5247         int table_insert = lua_gettop(L);
5248         lua_newtable(L);
5249         int table = lua_gettop(L);
5250         for(std::list<std::string>::const_iterator i = log.begin();
5251                         i != log.end(); i++)
5252         {
5253                 lua_pushvalue(L, table_insert);
5254                 lua_pushvalue(L, table);
5255                 lua_pushstring(L, i->c_str());
5256                 if(lua_pcall(L, 2, 0, 0))
5257                         script_error(L, "error: %s", lua_tostring(L, -1));
5258         }
5259         lua_remove(L, -2); // Remove table
5260         lua_remove(L, -2); // Remove insert
5261         return 2;
5262 }
5263
5264 static const struct luaL_Reg minetest_f [] = {
5265         {"debug", l_debug},
5266         {"log", l_log},
5267         {"request_shutdown", l_request_shutdown},
5268         {"get_server_status", l_get_server_status},
5269         {"register_item_raw", l_register_item_raw},
5270         {"register_alias_raw", l_register_alias_raw},
5271         {"register_craft", l_register_craft},
5272         {"setting_set", l_setting_set},
5273         {"setting_get", l_setting_get},
5274         {"setting_getbool", l_setting_getbool},
5275         {"chat_send_all", l_chat_send_all},
5276         {"chat_send_player", l_chat_send_player},
5277         {"get_player_privs", l_get_player_privs},
5278         {"get_ban_list", l_get_ban_list},
5279         {"get_ban_description", l_get_ban_description},
5280         {"ban_player", l_ban_player},
5281         {"unban_player_or_ip", l_unban_player_of_ip},
5282         {"get_inventory", l_get_inventory},
5283         {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5284         {"show_formspec", l_show_formspec},
5285         {"get_dig_params", l_get_dig_params},
5286         {"get_hit_params", l_get_hit_params},
5287         {"get_current_modname", l_get_current_modname},
5288         {"get_modpath", l_get_modpath},
5289         {"get_modnames", l_get_modnames},
5290         {"get_worldpath", l_get_worldpath},
5291         {"sound_play", l_sound_play},
5292         {"sound_stop", l_sound_stop},
5293         {"is_singleplayer", l_is_singleplayer},
5294         {"get_password_hash", l_get_password_hash},
5295         {"notify_authentication_modified", l_notify_authentication_modified},
5296         {"get_craft_result", l_get_craft_result},
5297         {"get_craft_recipe", l_get_craft_recipe},
5298         {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5299         {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5300         {NULL, NULL}
5301 };
5302
5303 /*
5304         Main export function
5305 */
5306
5307 void scriptapi_export(lua_State *L, Server *server)
5308 {
5309         realitycheck(L);
5310         assert(lua_checkstack(L, 20));
5311         verbosestream<<"scriptapi_export()"<<std::endl;
5312         StackUnroller stack_unroller(L);
5313
5314         // Store server as light userdata in registry
5315         lua_pushlightuserdata(L, server);
5316         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5317
5318         // Register global functions in table minetest
5319         lua_newtable(L);
5320         luaL_register(L, NULL, minetest_f);
5321         lua_setglobal(L, "minetest");
5322         
5323         // Get the main minetest table
5324         lua_getglobal(L, "minetest");
5325
5326         // Add tables to minetest
5327         lua_newtable(L);
5328         lua_setfield(L, -2, "object_refs");
5329         lua_newtable(L);
5330         lua_setfield(L, -2, "luaentities");
5331
5332         // Register wrappers
5333         LuaItemStack::Register(L);
5334         InvRef::Register(L);
5335         NodeMetaRef::Register(L);
5336         NodeTimerRef::Register(L);
5337         ObjectRef::Register(L);
5338         EnvRef::Register(L);
5339         LuaPseudoRandom::Register(L);
5340         LuaPerlinNoise::Register(L);
5341 }
5342
5343 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5344                 const std::string &modname)
5345 {
5346         ModNameStorer modnamestorer(L, modname);
5347
5348         if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5349                         "0123456789_")){
5350                 errorstream<<"Error loading mod \""<<modname
5351                                 <<"\": modname does not follow naming conventions: "
5352                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5353                 return false;
5354         }
5355         
5356         bool success = false;
5357
5358         try{
5359                 success = script_load(L, scriptpath.c_str());
5360         }
5361         catch(LuaError &e){
5362                 errorstream<<"Error loading mod \""<<modname
5363                                 <<"\": "<<e.what()<<std::endl;
5364         }
5365
5366         return success;
5367 }
5368
5369 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5370 {
5371         realitycheck(L);
5372         assert(lua_checkstack(L, 20));
5373         verbosestream<<"scriptapi_add_environment"<<std::endl;
5374         StackUnroller stack_unroller(L);
5375
5376         // Create EnvRef on stack
5377         EnvRef::create(L, env);
5378         int envref = lua_gettop(L);
5379
5380         // minetest.env = envref
5381         lua_getglobal(L, "minetest");
5382         luaL_checktype(L, -1, LUA_TTABLE);
5383         lua_pushvalue(L, envref);
5384         lua_setfield(L, -2, "env");
5385
5386         // Store environment as light userdata in registry
5387         lua_pushlightuserdata(L, env);
5388         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5389
5390         /*
5391                 Add ActiveBlockModifiers to environment
5392         */
5393
5394         // Get minetest.registered_abms
5395         lua_getglobal(L, "minetest");
5396         lua_getfield(L, -1, "registered_abms");
5397         luaL_checktype(L, -1, LUA_TTABLE);
5398         int registered_abms = lua_gettop(L);
5399         
5400         if(lua_istable(L, registered_abms)){
5401                 int table = lua_gettop(L);
5402                 lua_pushnil(L);
5403                 while(lua_next(L, table) != 0){
5404                         // key at index -2 and value at index -1
5405                         int id = lua_tonumber(L, -2);
5406                         int current_abm = lua_gettop(L);
5407
5408                         std::set<std::string> trigger_contents;
5409                         lua_getfield(L, current_abm, "nodenames");
5410                         if(lua_istable(L, -1)){
5411                                 int table = lua_gettop(L);
5412                                 lua_pushnil(L);
5413                                 while(lua_next(L, table) != 0){
5414                                         // key at index -2 and value at index -1
5415                                         luaL_checktype(L, -1, LUA_TSTRING);
5416                                         trigger_contents.insert(lua_tostring(L, -1));
5417                                         // removes value, keeps key for next iteration
5418                                         lua_pop(L, 1);
5419                                 }
5420                         } else if(lua_isstring(L, -1)){
5421                                 trigger_contents.insert(lua_tostring(L, -1));
5422                         }
5423                         lua_pop(L, 1);
5424
5425                         std::set<std::string> required_neighbors;
5426                         lua_getfield(L, current_abm, "neighbors");
5427                         if(lua_istable(L, -1)){
5428                                 int table = lua_gettop(L);
5429                                 lua_pushnil(L);
5430                                 while(lua_next(L, table) != 0){
5431                                         // key at index -2 and value at index -1
5432                                         luaL_checktype(L, -1, LUA_TSTRING);
5433                                         required_neighbors.insert(lua_tostring(L, -1));
5434                                         // removes value, keeps key for next iteration
5435                                         lua_pop(L, 1);
5436                                 }
5437                         } else if(lua_isstring(L, -1)){
5438                                 required_neighbors.insert(lua_tostring(L, -1));
5439                         }
5440                         lua_pop(L, 1);
5441
5442                         float trigger_interval = 10.0;
5443                         getfloatfield(L, current_abm, "interval", trigger_interval);
5444
5445                         int trigger_chance = 50;
5446                         getintfield(L, current_abm, "chance", trigger_chance);
5447
5448                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
5449                                         required_neighbors, trigger_interval, trigger_chance);
5450                         
5451                         env->addActiveBlockModifier(abm);
5452
5453                         // removes value, keeps key for next iteration
5454                         lua_pop(L, 1);
5455                 }
5456         }
5457         lua_pop(L, 1);
5458 }
5459
5460 #if 0
5461 // Dump stack top with the dump2 function
5462 static void dump2(lua_State *L, const char *name)
5463 {
5464         // Dump object (debug)
5465         lua_getglobal(L, "dump2");
5466         luaL_checktype(L, -1, LUA_TFUNCTION);
5467         lua_pushvalue(L, -2); // Get previous stack top as first parameter
5468         lua_pushstring(L, name);
5469         if(lua_pcall(L, 2, 0, 0))
5470                 script_error(L, "error: %s", lua_tostring(L, -1));
5471 }
5472 #endif
5473
5474 /*
5475         object_reference
5476 */
5477
5478 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5479 {
5480         realitycheck(L);
5481         assert(lua_checkstack(L, 20));
5482         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5483         StackUnroller stack_unroller(L);
5484
5485         // Create object on stack
5486         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5487         int object = lua_gettop(L);
5488
5489         // Get minetest.object_refs table
5490         lua_getglobal(L, "minetest");
5491         lua_getfield(L, -1, "object_refs");
5492         luaL_checktype(L, -1, LUA_TTABLE);
5493         int objectstable = lua_gettop(L);
5494         
5495         // object_refs[id] = object
5496         lua_pushnumber(L, cobj->getId()); // Push id
5497         lua_pushvalue(L, object); // Copy object to top of stack
5498         lua_settable(L, objectstable);
5499 }
5500
5501 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5502 {
5503         realitycheck(L);
5504         assert(lua_checkstack(L, 20));
5505         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5506         StackUnroller stack_unroller(L);
5507
5508         // Get minetest.object_refs table
5509         lua_getglobal(L, "minetest");
5510         lua_getfield(L, -1, "object_refs");
5511         luaL_checktype(L, -1, LUA_TTABLE);
5512         int objectstable = lua_gettop(L);
5513         
5514         // Get object_refs[id]
5515         lua_pushnumber(L, cobj->getId()); // Push id
5516         lua_gettable(L, objectstable);
5517         // Set object reference to NULL
5518         ObjectRef::set_null(L);
5519         lua_pop(L, 1); // pop object
5520
5521         // Set object_refs[id] = nil
5522         lua_pushnumber(L, cobj->getId()); // Push id
5523         lua_pushnil(L);
5524         lua_settable(L, objectstable);
5525 }
5526
5527 /*
5528         misc
5529 */
5530
5531 // What scriptapi_run_callbacks does with the return values of callbacks.
5532 // Regardless of the mode, if only one callback is defined,
5533 // its return value is the total return value.
5534 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5535 enum RunCallbacksMode
5536 {
5537         // Returns the return value of the first callback
5538         // Returns nil if list of callbacks is empty
5539         RUN_CALLBACKS_MODE_FIRST,
5540         // Returns the return value of the last callback
5541         // Returns nil if list of callbacks is empty
5542         RUN_CALLBACKS_MODE_LAST,
5543         // If any callback returns a false value, the first such is returned
5544         // Otherwise, the first callback's return value (trueish) is returned
5545         // Returns true if list of callbacks is empty
5546         RUN_CALLBACKS_MODE_AND,
5547         // Like above, but stops calling callbacks (short circuit)
5548         // after seeing the first false value
5549         RUN_CALLBACKS_MODE_AND_SC,
5550         // If any callback returns a true value, the first such is returned
5551         // Otherwise, the first callback's return value (falseish) is returned
5552         // Returns false if list of callbacks is empty
5553         RUN_CALLBACKS_MODE_OR,
5554         // Like above, but stops calling callbacks (short circuit)
5555         // after seeing the first true value
5556         RUN_CALLBACKS_MODE_OR_SC,
5557         // Note: "a true value" and "a false value" refer to values that
5558         // are converted by lua_toboolean to true or false, respectively.
5559 };
5560
5561 // Push the list of callbacks (a lua table).
5562 // Then push nargs arguments.
5563 // Then call this function, which
5564 // - runs the callbacks
5565 // - removes the table and arguments from the lua stack
5566 // - pushes the return value, computed depending on mode
5567 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5568                 RunCallbacksMode mode)
5569 {
5570         // Insert the return value into the lua stack, below the table
5571         assert(lua_gettop(L) >= nargs + 1);
5572         lua_pushnil(L);
5573         lua_insert(L, -(nargs + 1) - 1);
5574         // Stack now looks like this:
5575         // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5576
5577         int rv = lua_gettop(L) - nargs - 1;
5578         int table = rv + 1;
5579         int arg = table + 1;
5580
5581         luaL_checktype(L, table, LUA_TTABLE);
5582
5583         // Foreach
5584         lua_pushnil(L);
5585         bool first_loop = true;
5586         while(lua_next(L, table) != 0){
5587                 // key at index -2 and value at index -1
5588                 luaL_checktype(L, -1, LUA_TFUNCTION);
5589                 // Call function
5590                 for(int i = 0; i < nargs; i++)
5591                         lua_pushvalue(L, arg+i);
5592                 if(lua_pcall(L, nargs, 1, 0))
5593                         script_error(L, "error: %s", lua_tostring(L, -1));
5594
5595                 // Move return value to designated space in stack
5596                 // Or pop it
5597                 if(first_loop){
5598                         // Result of first callback is always moved
5599                         lua_replace(L, rv);
5600                         first_loop = false;
5601                 } else {
5602                         // Otherwise, what happens depends on the mode
5603                         if(mode == RUN_CALLBACKS_MODE_FIRST)
5604                                 lua_pop(L, 1);
5605                         else if(mode == RUN_CALLBACKS_MODE_LAST)
5606                                 lua_replace(L, rv);
5607                         else if(mode == RUN_CALLBACKS_MODE_AND ||
5608                                         mode == RUN_CALLBACKS_MODE_AND_SC){
5609                                 if(lua_toboolean(L, rv) == true &&
5610                                                 lua_toboolean(L, -1) == false)
5611                                         lua_replace(L, rv);
5612                                 else
5613                                         lua_pop(L, 1);
5614                         }
5615                         else if(mode == RUN_CALLBACKS_MODE_OR ||
5616                                         mode == RUN_CALLBACKS_MODE_OR_SC){
5617                                 if(lua_toboolean(L, rv) == false &&
5618                                                 lua_toboolean(L, -1) == true)
5619                                         lua_replace(L, rv);
5620                                 else
5621                                         lua_pop(L, 1);
5622                         }
5623                         else
5624                                 assert(0);
5625                 }
5626
5627                 // Handle short circuit modes
5628                 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5629                                 lua_toboolean(L, rv) == false)
5630                         break;
5631                 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5632                                 lua_toboolean(L, rv) == true)
5633                         break;
5634
5635                 // value removed, keep key for next iteration
5636         }
5637
5638         // Remove stuff from stack, leaving only the return value
5639         lua_settop(L, rv);
5640
5641         // Fix return value in case no callbacks were called
5642         if(first_loop){
5643                 if(mode == RUN_CALLBACKS_MODE_AND ||
5644                                 mode == RUN_CALLBACKS_MODE_AND_SC){
5645                         lua_pop(L, 1);
5646                         lua_pushboolean(L, true);
5647                 }
5648                 else if(mode == RUN_CALLBACKS_MODE_OR ||
5649                                 mode == RUN_CALLBACKS_MODE_OR_SC){
5650                         lua_pop(L, 1);
5651                         lua_pushboolean(L, false);
5652                 }
5653         }
5654 }
5655
5656 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5657                 const std::string &message)
5658 {
5659         realitycheck(L);
5660         assert(lua_checkstack(L, 20));
5661         StackUnroller stack_unroller(L);
5662
5663         // Get minetest.registered_on_chat_messages
5664         lua_getglobal(L, "minetest");
5665         lua_getfield(L, -1, "registered_on_chat_messages");
5666         // Call callbacks
5667         lua_pushstring(L, name.c_str());
5668         lua_pushstring(L, message.c_str());
5669         scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5670         bool ate = lua_toboolean(L, -1);
5671         return ate;
5672 }
5673
5674 void scriptapi_on_shutdown(lua_State *L)
5675 {
5676         realitycheck(L);
5677         assert(lua_checkstack(L, 20));
5678         StackUnroller stack_unroller(L);
5679
5680         // Get registered shutdown hooks
5681         lua_getglobal(L, "minetest");
5682         lua_getfield(L, -1, "registered_on_shutdown");
5683         // Call callbacks
5684         scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5685 }
5686
5687 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5688 {
5689         realitycheck(L);
5690         assert(lua_checkstack(L, 20));
5691         StackUnroller stack_unroller(L);
5692
5693         // Get minetest.registered_on_newplayers
5694         lua_getglobal(L, "minetest");
5695         lua_getfield(L, -1, "registered_on_newplayers");
5696         // Call callbacks
5697         objectref_get_or_create(L, player);
5698         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5699 }
5700
5701 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5702 {
5703         realitycheck(L);
5704         assert(lua_checkstack(L, 20));
5705         StackUnroller stack_unroller(L);
5706
5707         // Get minetest.registered_on_dieplayers
5708         lua_getglobal(L, "minetest");
5709         lua_getfield(L, -1, "registered_on_dieplayers");
5710         // Call callbacks
5711         objectref_get_or_create(L, player);
5712         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5713 }
5714
5715 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5716 {
5717         realitycheck(L);
5718         assert(lua_checkstack(L, 20));
5719         StackUnroller stack_unroller(L);
5720
5721         // Get minetest.registered_on_respawnplayers
5722         lua_getglobal(L, "minetest");
5723         lua_getfield(L, -1, "registered_on_respawnplayers");
5724         // Call callbacks
5725         objectref_get_or_create(L, player);
5726         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5727         bool positioning_handled_by_some = lua_toboolean(L, -1);
5728         return positioning_handled_by_some;
5729 }
5730
5731 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5732 {
5733         realitycheck(L);
5734         assert(lua_checkstack(L, 20));
5735         StackUnroller stack_unroller(L);
5736
5737         // Get minetest.registered_on_joinplayers
5738         lua_getglobal(L, "minetest");
5739         lua_getfield(L, -1, "registered_on_joinplayers");
5740         // Call callbacks
5741         objectref_get_or_create(L, player);
5742         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5743 }
5744
5745 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5746 {
5747         realitycheck(L);
5748         assert(lua_checkstack(L, 20));
5749         StackUnroller stack_unroller(L);
5750
5751         // Get minetest.registered_on_leaveplayers
5752         lua_getglobal(L, "minetest");
5753         lua_getfield(L, -1, "registered_on_leaveplayers");
5754         // Call callbacks
5755         objectref_get_or_create(L, player);
5756         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5757 }
5758
5759 static void get_auth_handler(lua_State *L)
5760 {
5761         lua_getglobal(L, "minetest");
5762         lua_getfield(L, -1, "registered_auth_handler");
5763         if(lua_isnil(L, -1)){
5764                 lua_pop(L, 1);
5765                 lua_getfield(L, -1, "builtin_auth_handler");
5766         }
5767         if(lua_type(L, -1) != LUA_TTABLE)
5768                 throw LuaError(L, "Authentication handler table not valid");
5769 }
5770
5771 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5772                 std::string *dst_password, std::set<std::string> *dst_privs)
5773 {
5774         realitycheck(L);
5775         assert(lua_checkstack(L, 20));
5776         StackUnroller stack_unroller(L);
5777         
5778         get_auth_handler(L);
5779         lua_getfield(L, -1, "get_auth");
5780         if(lua_type(L, -1) != LUA_TFUNCTION)
5781                 throw LuaError(L, "Authentication handler missing get_auth");
5782         lua_pushstring(L, playername.c_str());
5783         if(lua_pcall(L, 1, 1, 0))
5784                 script_error(L, "error: %s", lua_tostring(L, -1));
5785         
5786         // nil = login not allowed
5787         if(lua_isnil(L, -1))
5788                 return false;
5789         luaL_checktype(L, -1, LUA_TTABLE);
5790         
5791         std::string password;
5792         bool found = getstringfield(L, -1, "password", password);
5793         if(!found)
5794                 throw LuaError(L, "Authentication handler didn't return password");
5795         if(dst_password)
5796                 *dst_password = password;
5797
5798         lua_getfield(L, -1, "privileges");
5799         if(!lua_istable(L, -1))
5800                 throw LuaError(L,
5801                                 "Authentication handler didn't return privilege table");
5802         if(dst_privs)
5803                 read_privileges(L, -1, *dst_privs);
5804         lua_pop(L, 1);
5805         
5806         return true;
5807 }
5808
5809 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5810                 const std::string &password)
5811 {
5812         realitycheck(L);
5813         assert(lua_checkstack(L, 20));
5814         StackUnroller stack_unroller(L);
5815         
5816         get_auth_handler(L);
5817         lua_getfield(L, -1, "create_auth");
5818         if(lua_type(L, -1) != LUA_TFUNCTION)
5819                 throw LuaError(L, "Authentication handler missing create_auth");
5820         lua_pushstring(L, playername.c_str());
5821         lua_pushstring(L, password.c_str());
5822         if(lua_pcall(L, 2, 0, 0))
5823                 script_error(L, "error: %s", lua_tostring(L, -1));
5824 }
5825
5826 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5827                 const std::string &password)
5828 {
5829         realitycheck(L);
5830         assert(lua_checkstack(L, 20));
5831         StackUnroller stack_unroller(L);
5832         
5833         get_auth_handler(L);
5834         lua_getfield(L, -1, "set_password");
5835         if(lua_type(L, -1) != LUA_TFUNCTION)
5836                 throw LuaError(L, "Authentication handler missing set_password");
5837         lua_pushstring(L, playername.c_str());
5838         lua_pushstring(L, password.c_str());
5839         if(lua_pcall(L, 2, 1, 0))
5840                 script_error(L, "error: %s", lua_tostring(L, -1));
5841         return lua_toboolean(L, -1);
5842 }
5843
5844 /*
5845         player
5846 */
5847
5848 void scriptapi_on_player_receive_fields(lua_State *L, 
5849                 ServerActiveObject *player,
5850                 const std::string &formname,
5851                 const std::map<std::string, std::string> &fields)
5852 {
5853         realitycheck(L);
5854         assert(lua_checkstack(L, 20));
5855         StackUnroller stack_unroller(L);
5856
5857         // Get minetest.registered_on_chat_messages
5858         lua_getglobal(L, "minetest");
5859         lua_getfield(L, -1, "registered_on_player_receive_fields");
5860         // Call callbacks
5861         // param 1
5862         objectref_get_or_create(L, player);
5863         // param 2
5864         lua_pushstring(L, formname.c_str());
5865         // param 3
5866         lua_newtable(L);
5867         for(std::map<std::string, std::string>::const_iterator
5868                         i = fields.begin(); i != fields.end(); i++){
5869                 const std::string &name = i->first;
5870                 const std::string &value = i->second;
5871                 lua_pushstring(L, name.c_str());
5872                 lua_pushlstring(L, value.c_str(), value.size());
5873                 lua_settable(L, -3);
5874         }
5875         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5876 }
5877
5878 /*
5879         item callbacks and node callbacks
5880 */
5881
5882 // Retrieves minetest.registered_items[name][callbackname]
5883 // If that is nil or on error, return false and stack is unchanged
5884 // If that is a function, returns true and pushes the
5885 // function onto the stack
5886 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5887 // is tried instead so unknown items can still be manipulated to some degree
5888 static bool get_item_callback(lua_State *L,
5889                 const char *name, const char *callbackname)
5890 {
5891         lua_getglobal(L, "minetest");
5892         lua_getfield(L, -1, "registered_items");
5893         lua_remove(L, -2);
5894         luaL_checktype(L, -1, LUA_TTABLE);
5895         lua_getfield(L, -1, name);
5896         lua_remove(L, -2);
5897         // Should be a table
5898         if(lua_type(L, -1) != LUA_TTABLE)
5899         {
5900                 // Report error and clean up
5901                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5902                 lua_pop(L, 1);
5903
5904                 // Try minetest.nodedef_default instead
5905                 lua_getglobal(L, "minetest");
5906                 lua_getfield(L, -1, "nodedef_default");
5907                 lua_remove(L, -2);
5908                 luaL_checktype(L, -1, LUA_TTABLE);
5909         }
5910         lua_getfield(L, -1, callbackname);
5911         lua_remove(L, -2);
5912         // Should be a function or nil
5913         if(lua_type(L, -1) == LUA_TFUNCTION)
5914         {
5915                 return true;
5916         }
5917         else if(lua_isnil(L, -1))
5918         {
5919                 lua_pop(L, 1);
5920                 return false;
5921         }
5922         else
5923         {
5924                 errorstream<<"Item \""<<name<<"\" callback \""
5925                         <<callbackname<<" is not a function"<<std::endl;
5926                 lua_pop(L, 1);
5927                 return false;
5928         }
5929 }
5930
5931 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5932                 ServerActiveObject *dropper, v3f pos)
5933 {
5934         realitycheck(L);
5935         assert(lua_checkstack(L, 20));
5936         StackUnroller stack_unroller(L);
5937
5938         // Push callback function on stack
5939         if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5940                 return false;
5941
5942         // Call function
5943         LuaItemStack::create(L, item);
5944         objectref_get_or_create(L, dropper);
5945         pushFloatPos(L, pos);
5946         if(lua_pcall(L, 3, 1, 0))
5947                 script_error(L, "error: %s", lua_tostring(L, -1));
5948         if(!lua_isnil(L, -1))
5949                 item = read_item(L, -1);
5950         return true;
5951 }
5952
5953 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5954                 ServerActiveObject *placer, const PointedThing &pointed)
5955 {
5956         realitycheck(L);
5957         assert(lua_checkstack(L, 20));
5958         StackUnroller stack_unroller(L);
5959
5960         // Push callback function on stack
5961         if(!get_item_callback(L, item.name.c_str(), "on_place"))
5962                 return false;
5963
5964         // Call function
5965         LuaItemStack::create(L, item);
5966         objectref_get_or_create(L, placer);
5967         push_pointed_thing(L, pointed);
5968         if(lua_pcall(L, 3, 1, 0))
5969                 script_error(L, "error: %s", lua_tostring(L, -1));
5970         if(!lua_isnil(L, -1))
5971                 item = read_item(L, -1);
5972         return true;
5973 }
5974
5975 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5976                 ServerActiveObject *user, const PointedThing &pointed)
5977 {
5978         realitycheck(L);
5979         assert(lua_checkstack(L, 20));
5980         StackUnroller stack_unroller(L);
5981
5982         // Push callback function on stack
5983         if(!get_item_callback(L, item.name.c_str(), "on_use"))
5984                 return false;
5985
5986         // Call function
5987         LuaItemStack::create(L, item);
5988         objectref_get_or_create(L, user);
5989         push_pointed_thing(L, pointed);
5990         if(lua_pcall(L, 3, 1, 0))
5991                 script_error(L, "error: %s", lua_tostring(L, -1));
5992         if(!lua_isnil(L, -1))
5993                 item = read_item(L, -1);
5994         return true;
5995 }
5996
5997 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5998                 ServerActiveObject *puncher)
5999 {
6000         realitycheck(L);
6001         assert(lua_checkstack(L, 20));
6002         StackUnroller stack_unroller(L);
6003
6004         INodeDefManager *ndef = get_server(L)->ndef();
6005
6006         // Push callback function on stack
6007         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6008                 return false;
6009
6010         // Call function
6011         push_v3s16(L, p);
6012         pushnode(L, node, ndef);
6013         objectref_get_or_create(L, puncher);
6014         if(lua_pcall(L, 3, 0, 0))
6015                 script_error(L, "error: %s", lua_tostring(L, -1));
6016         return true;
6017 }
6018
6019 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6020                 ServerActiveObject *digger)
6021 {
6022         realitycheck(L);
6023         assert(lua_checkstack(L, 20));
6024         StackUnroller stack_unroller(L);
6025
6026         INodeDefManager *ndef = get_server(L)->ndef();
6027
6028         // Push callback function on stack
6029         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6030                 return false;
6031
6032         // Call function
6033         push_v3s16(L, p);
6034         pushnode(L, node, ndef);
6035         objectref_get_or_create(L, digger);
6036         if(lua_pcall(L, 3, 0, 0))
6037                 script_error(L, "error: %s", lua_tostring(L, -1));
6038         return true;
6039 }
6040
6041 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6042 {
6043         realitycheck(L);
6044         assert(lua_checkstack(L, 20));
6045         StackUnroller stack_unroller(L);
6046
6047         INodeDefManager *ndef = get_server(L)->ndef();
6048
6049         // Push callback function on stack
6050         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6051                 return;
6052
6053         // Call function
6054         push_v3s16(L, p);
6055         if(lua_pcall(L, 1, 0, 0))
6056                 script_error(L, "error: %s", lua_tostring(L, -1));
6057 }
6058
6059 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6060 {
6061         realitycheck(L);
6062         assert(lua_checkstack(L, 20));
6063         StackUnroller stack_unroller(L);
6064
6065         INodeDefManager *ndef = get_server(L)->ndef();
6066
6067         // Push callback function on stack
6068         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6069                 return;
6070
6071         // Call function
6072         push_v3s16(L, p);
6073         if(lua_pcall(L, 1, 0, 0))
6074                 script_error(L, "error: %s", lua_tostring(L, -1));
6075 }
6076
6077 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6078 {
6079         realitycheck(L);
6080         assert(lua_checkstack(L, 20));
6081         StackUnroller stack_unroller(L);
6082
6083         INodeDefManager *ndef = get_server(L)->ndef();
6084
6085         // Push callback function on stack
6086         if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6087                 return;
6088
6089         // Call function
6090         push_v3s16(L, p);
6091         pushnode(L, node, ndef);
6092         if(lua_pcall(L, 2, 0, 0))
6093                 script_error(L, "error: %s", lua_tostring(L, -1));
6094 }
6095
6096 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6097 {
6098         realitycheck(L);
6099         assert(lua_checkstack(L, 20));
6100         StackUnroller stack_unroller(L);
6101
6102         INodeDefManager *ndef = get_server(L)->ndef();
6103
6104         // Push callback function on stack
6105         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6106                 return false;
6107
6108         // Call function
6109         push_v3s16(L, p);
6110         lua_pushnumber(L,dtime);
6111         if(lua_pcall(L, 2, 1, 0))
6112                 script_error(L, "error: %s", lua_tostring(L, -1));
6113         if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
6114                 return true;
6115         
6116         return false;
6117 }
6118
6119 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6120                 const std::string &formname,
6121                 const std::map<std::string, std::string> &fields,
6122                 ServerActiveObject *sender)
6123 {
6124         realitycheck(L);
6125         assert(lua_checkstack(L, 20));
6126         StackUnroller stack_unroller(L);
6127
6128         INodeDefManager *ndef = get_server(L)->ndef();
6129         
6130         // If node doesn't exist, we don't know what callback to call
6131         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6132         if(node.getContent() == CONTENT_IGNORE)
6133                 return;
6134
6135         // Push callback function on stack
6136         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6137                 return;
6138
6139         // Call function
6140         // param 1
6141         push_v3s16(L, p);
6142         // param 2
6143         lua_pushstring(L, formname.c_str());
6144         // param 3
6145         lua_newtable(L);
6146         for(std::map<std::string, std::string>::const_iterator
6147                         i = fields.begin(); i != fields.end(); i++){
6148                 const std::string &name = i->first;
6149                 const std::string &value = i->second;
6150                 lua_pushstring(L, name.c_str());
6151                 lua_pushlstring(L, value.c_str(), value.size());
6152                 lua_settable(L, -3);
6153         }
6154         // param 4
6155         objectref_get_or_create(L, sender);
6156         if(lua_pcall(L, 4, 0, 0))
6157                 script_error(L, "error: %s", lua_tostring(L, -1));
6158 }
6159
6160 /*
6161         Node metadata inventory callbacks
6162 */
6163
6164 // Return number of accepted items to be moved
6165 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6166                 const std::string &from_list, int from_index,
6167                 const std::string &to_list, int to_index,
6168                 int count, ServerActiveObject *player)
6169 {
6170         realitycheck(L);
6171         assert(lua_checkstack(L, 20));
6172         StackUnroller stack_unroller(L);
6173
6174         INodeDefManager *ndef = get_server(L)->ndef();
6175
6176         // If node doesn't exist, we don't know what callback to call
6177         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6178         if(node.getContent() == CONTENT_IGNORE)
6179                 return 0;
6180
6181         // Push callback function on stack
6182         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6183                         "allow_metadata_inventory_move"))
6184                 return count;
6185
6186         // function(pos, from_list, from_index, to_list, to_index, count, player)
6187         // pos
6188         push_v3s16(L, p);
6189         // from_list
6190         lua_pushstring(L, from_list.c_str());
6191         // from_index
6192         lua_pushinteger(L, from_index + 1);
6193         // to_list
6194         lua_pushstring(L, to_list.c_str());
6195         // to_index
6196         lua_pushinteger(L, to_index + 1);
6197         // count
6198         lua_pushinteger(L, count);
6199         // player
6200         objectref_get_or_create(L, player);
6201         if(lua_pcall(L, 7, 1, 0))
6202                 script_error(L, "error: %s", lua_tostring(L, -1));
6203         if(!lua_isnumber(L, -1))
6204                 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6205         return luaL_checkinteger(L, -1);
6206 }
6207
6208 // Return number of accepted items to be put
6209 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6210                 const std::string &listname, int index, ItemStack &stack,
6211                 ServerActiveObject *player)
6212 {
6213         realitycheck(L);
6214         assert(lua_checkstack(L, 20));
6215         StackUnroller stack_unroller(L);
6216
6217         INodeDefManager *ndef = get_server(L)->ndef();
6218
6219         // If node doesn't exist, we don't know what callback to call
6220         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6221         if(node.getContent() == CONTENT_IGNORE)
6222                 return 0;
6223
6224         // Push callback function on stack
6225         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6226                         "allow_metadata_inventory_put"))
6227                 return stack.count;
6228
6229         // Call function(pos, listname, index, stack, player)
6230         // pos
6231         push_v3s16(L, p);
6232         // listname
6233         lua_pushstring(L, listname.c_str());
6234         // index
6235         lua_pushinteger(L, index + 1);
6236         // stack
6237         LuaItemStack::create(L, stack);
6238         // player
6239         objectref_get_or_create(L, player);
6240         if(lua_pcall(L, 5, 1, 0))
6241                 script_error(L, "error: %s", lua_tostring(L, -1));
6242         if(!lua_isnumber(L, -1))
6243                 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6244         return luaL_checkinteger(L, -1);
6245 }
6246
6247 // Return number of accepted items to be taken
6248 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6249                 const std::string &listname, int index, ItemStack &stack,
6250                 ServerActiveObject *player)
6251 {
6252         realitycheck(L);
6253         assert(lua_checkstack(L, 20));
6254         StackUnroller stack_unroller(L);
6255
6256         INodeDefManager *ndef = get_server(L)->ndef();
6257
6258         // If node doesn't exist, we don't know what callback to call
6259         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6260         if(node.getContent() == CONTENT_IGNORE)
6261                 return 0;
6262
6263         // Push callback function on stack
6264         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6265                         "allow_metadata_inventory_take"))
6266                 return stack.count;
6267
6268         // Call function(pos, listname, index, count, player)
6269         // pos
6270         push_v3s16(L, p);
6271         // listname
6272         lua_pushstring(L, listname.c_str());
6273         // index
6274         lua_pushinteger(L, index + 1);
6275         // stack
6276         LuaItemStack::create(L, stack);
6277         // player
6278         objectref_get_or_create(L, player);
6279         if(lua_pcall(L, 5, 1, 0))
6280                 script_error(L, "error: %s", lua_tostring(L, -1));
6281         if(!lua_isnumber(L, -1))
6282                 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6283         return luaL_checkinteger(L, -1);
6284 }
6285
6286 // Report moved items
6287 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6288                 const std::string &from_list, int from_index,
6289                 const std::string &to_list, int to_index,
6290                 int count, ServerActiveObject *player)
6291 {
6292         realitycheck(L);
6293         assert(lua_checkstack(L, 20));
6294         StackUnroller stack_unroller(L);
6295
6296         INodeDefManager *ndef = get_server(L)->ndef();
6297
6298         // If node doesn't exist, we don't know what callback to call
6299         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6300         if(node.getContent() == CONTENT_IGNORE)
6301                 return;
6302
6303         // Push callback function on stack
6304         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6305                         "on_metadata_inventory_move"))
6306                 return;
6307
6308         // function(pos, from_list, from_index, to_list, to_index, count, player)
6309         // pos
6310         push_v3s16(L, p);
6311         // from_list
6312         lua_pushstring(L, from_list.c_str());
6313         // from_index
6314         lua_pushinteger(L, from_index + 1);
6315         // to_list
6316         lua_pushstring(L, to_list.c_str());
6317         // to_index
6318         lua_pushinteger(L, to_index + 1);
6319         // count
6320         lua_pushinteger(L, count);
6321         // player
6322         objectref_get_or_create(L, player);
6323         if(lua_pcall(L, 7, 0, 0))
6324                 script_error(L, "error: %s", lua_tostring(L, -1));
6325 }
6326
6327 // Report put items
6328 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6329                 const std::string &listname, int index, ItemStack &stack,
6330                 ServerActiveObject *player)
6331 {
6332         realitycheck(L);
6333         assert(lua_checkstack(L, 20));
6334         StackUnroller stack_unroller(L);
6335
6336         INodeDefManager *ndef = get_server(L)->ndef();
6337
6338         // If node doesn't exist, we don't know what callback to call
6339         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6340         if(node.getContent() == CONTENT_IGNORE)
6341                 return;
6342
6343         // Push callback function on stack
6344         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6345                         "on_metadata_inventory_put"))
6346                 return;
6347
6348         // Call function(pos, listname, index, stack, player)
6349         // pos
6350         push_v3s16(L, p);
6351         // listname
6352         lua_pushstring(L, listname.c_str());
6353         // index
6354         lua_pushinteger(L, index + 1);
6355         // stack
6356         LuaItemStack::create(L, stack);
6357         // player
6358         objectref_get_or_create(L, player);
6359         if(lua_pcall(L, 5, 0, 0))
6360                 script_error(L, "error: %s", lua_tostring(L, -1));
6361 }
6362
6363 // Report taken items
6364 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6365                 const std::string &listname, int index, ItemStack &stack,
6366                 ServerActiveObject *player)
6367 {
6368         realitycheck(L);
6369         assert(lua_checkstack(L, 20));
6370         StackUnroller stack_unroller(L);
6371
6372         INodeDefManager *ndef = get_server(L)->ndef();
6373
6374         // If node doesn't exist, we don't know what callback to call
6375         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6376         if(node.getContent() == CONTENT_IGNORE)
6377                 return;
6378
6379         // Push callback function on stack
6380         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6381                         "on_metadata_inventory_take"))
6382                 return;
6383
6384         // Call function(pos, listname, index, stack, player)
6385         // pos
6386         push_v3s16(L, p);
6387         // listname
6388         lua_pushstring(L, listname.c_str());
6389         // index
6390         lua_pushinteger(L, index + 1);
6391         // stack
6392         LuaItemStack::create(L, stack);
6393         // player
6394         objectref_get_or_create(L, player);
6395         if(lua_pcall(L, 5, 0, 0))
6396                 script_error(L, "error: %s", lua_tostring(L, -1));
6397 }
6398
6399 /*
6400         Detached inventory callbacks
6401 */
6402
6403 // Retrieves minetest.detached_inventories[name][callbackname]
6404 // If that is nil or on error, return false and stack is unchanged
6405 // If that is a function, returns true and pushes the
6406 // function onto the stack
6407 static bool get_detached_inventory_callback(lua_State *L,
6408                 const std::string &name, const char *callbackname)
6409 {
6410         lua_getglobal(L, "minetest");
6411         lua_getfield(L, -1, "detached_inventories");
6412         lua_remove(L, -2);
6413         luaL_checktype(L, -1, LUA_TTABLE);
6414         lua_getfield(L, -1, name.c_str());
6415         lua_remove(L, -2);
6416         // Should be a table
6417         if(lua_type(L, -1) != LUA_TTABLE)
6418         {
6419                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6420                 lua_pop(L, 1);
6421                 return false;
6422         }
6423         lua_getfield(L, -1, callbackname);
6424         lua_remove(L, -2);
6425         // Should be a function or nil
6426         if(lua_type(L, -1) == LUA_TFUNCTION)
6427         {
6428                 return true;
6429         }
6430         else if(lua_isnil(L, -1))
6431         {
6432                 lua_pop(L, 1);
6433                 return false;
6434         }
6435         else
6436         {
6437                 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6438                         <<callbackname<<"\" is not a function"<<std::endl;
6439                 lua_pop(L, 1);
6440                 return false;
6441         }
6442 }
6443
6444 // Return number of accepted items to be moved
6445 int scriptapi_detached_inventory_allow_move(lua_State *L,
6446                 const std::string &name,
6447                 const std::string &from_list, int from_index,
6448                 const std::string &to_list, int to_index,
6449                 int count, ServerActiveObject *player)
6450 {
6451         realitycheck(L);
6452         assert(lua_checkstack(L, 20));
6453         StackUnroller stack_unroller(L);
6454
6455         // Push callback function on stack
6456         if(!get_detached_inventory_callback(L, name, "allow_move"))
6457                 return count;
6458
6459         // function(inv, from_list, from_index, to_list, to_index, count, player)
6460         // inv
6461         InventoryLocation loc;
6462         loc.setDetached(name);
6463         InvRef::create(L, loc);
6464         // from_list
6465         lua_pushstring(L, from_list.c_str());
6466         // from_index
6467         lua_pushinteger(L, from_index + 1);
6468         // to_list
6469         lua_pushstring(L, to_list.c_str());
6470         // to_index
6471         lua_pushinteger(L, to_index + 1);
6472         // count
6473         lua_pushinteger(L, count);
6474         // player
6475         objectref_get_or_create(L, player);
6476         if(lua_pcall(L, 7, 1, 0))
6477                 script_error(L, "error: %s", lua_tostring(L, -1));
6478         if(!lua_isnumber(L, -1))
6479                 throw LuaError(L, "allow_move should return a number");
6480         return luaL_checkinteger(L, -1);
6481 }
6482
6483 // Return number of accepted items to be put
6484 int scriptapi_detached_inventory_allow_put(lua_State *L,
6485                 const std::string &name,
6486                 const std::string &listname, int index, ItemStack &stack,
6487                 ServerActiveObject *player)
6488 {
6489         realitycheck(L);
6490         assert(lua_checkstack(L, 20));
6491         StackUnroller stack_unroller(L);
6492
6493         // Push callback function on stack
6494         if(!get_detached_inventory_callback(L, name, "allow_put"))
6495                 return stack.count; // All will be accepted
6496
6497         // Call function(inv, listname, index, stack, player)
6498         // inv
6499         InventoryLocation loc;
6500         loc.setDetached(name);
6501         InvRef::create(L, loc);
6502         // listname
6503         lua_pushstring(L, listname.c_str());
6504         // index
6505         lua_pushinteger(L, index + 1);
6506         // stack
6507         LuaItemStack::create(L, stack);
6508         // player
6509         objectref_get_or_create(L, player);
6510         if(lua_pcall(L, 5, 1, 0))
6511                 script_error(L, "error: %s", lua_tostring(L, -1));
6512         if(!lua_isnumber(L, -1))
6513                 throw LuaError(L, "allow_put should return a number");
6514         return luaL_checkinteger(L, -1);
6515 }
6516
6517 // Return number of accepted items to be taken
6518 int scriptapi_detached_inventory_allow_take(lua_State *L,
6519                 const std::string &name,
6520                 const std::string &listname, int index, ItemStack &stack,
6521                 ServerActiveObject *player)
6522 {
6523         realitycheck(L);
6524         assert(lua_checkstack(L, 20));
6525         StackUnroller stack_unroller(L);
6526
6527         // Push callback function on stack
6528         if(!get_detached_inventory_callback(L, name, "allow_take"))
6529                 return stack.count; // All will be accepted
6530
6531         // Call function(inv, listname, index, stack, player)
6532         // inv
6533         InventoryLocation loc;
6534         loc.setDetached(name);
6535         InvRef::create(L, loc);
6536         // listname
6537         lua_pushstring(L, listname.c_str());
6538         // index
6539         lua_pushinteger(L, index + 1);
6540         // stack
6541         LuaItemStack::create(L, stack);
6542         // player
6543         objectref_get_or_create(L, player);
6544         if(lua_pcall(L, 5, 1, 0))
6545                 script_error(L, "error: %s", lua_tostring(L, -1));
6546         if(!lua_isnumber(L, -1))
6547                 throw LuaError(L, "allow_take should return a number");
6548         return luaL_checkinteger(L, -1);
6549 }
6550
6551 // Report moved items
6552 void scriptapi_detached_inventory_on_move(lua_State *L,
6553                 const std::string &name,
6554                 const std::string &from_list, int from_index,
6555                 const std::string &to_list, int to_index,
6556                 int count, ServerActiveObject *player)
6557 {
6558         realitycheck(L);
6559         assert(lua_checkstack(L, 20));
6560         StackUnroller stack_unroller(L);
6561
6562         // Push callback function on stack
6563         if(!get_detached_inventory_callback(L, name, "on_move"))
6564                 return;
6565
6566         // function(inv, from_list, from_index, to_list, to_index, count, player)
6567         // inv
6568         InventoryLocation loc;
6569         loc.setDetached(name);
6570         InvRef::create(L, loc);
6571         // from_list
6572         lua_pushstring(L, from_list.c_str());
6573         // from_index
6574         lua_pushinteger(L, from_index + 1);
6575         // to_list
6576         lua_pushstring(L, to_list.c_str());
6577         // to_index
6578         lua_pushinteger(L, to_index + 1);
6579         // count
6580         lua_pushinteger(L, count);
6581         // player
6582         objectref_get_or_create(L, player);
6583         if(lua_pcall(L, 7, 0, 0))
6584                 script_error(L, "error: %s", lua_tostring(L, -1));
6585 }
6586
6587 // Report put items
6588 void scriptapi_detached_inventory_on_put(lua_State *L,
6589                 const std::string &name,
6590                 const std::string &listname, int index, ItemStack &stack,
6591                 ServerActiveObject *player)
6592 {
6593         realitycheck(L);
6594         assert(lua_checkstack(L, 20));
6595         StackUnroller stack_unroller(L);
6596
6597         // Push callback function on stack
6598         if(!get_detached_inventory_callback(L, name, "on_put"))
6599                 return;
6600
6601         // Call function(inv, listname, index, stack, player)
6602         // inv
6603         InventoryLocation loc;
6604         loc.setDetached(name);
6605         InvRef::create(L, loc);
6606         // listname
6607         lua_pushstring(L, listname.c_str());
6608         // index
6609         lua_pushinteger(L, index + 1);
6610         // stack
6611         LuaItemStack::create(L, stack);
6612         // player
6613         objectref_get_or_create(L, player);
6614         if(lua_pcall(L, 5, 0, 0))
6615                 script_error(L, "error: %s", lua_tostring(L, -1));
6616 }
6617
6618 // Report taken items
6619 void scriptapi_detached_inventory_on_take(lua_State *L,
6620                 const std::string &name,
6621                 const std::string &listname, int index, ItemStack &stack,
6622                 ServerActiveObject *player)
6623 {
6624         realitycheck(L);
6625         assert(lua_checkstack(L, 20));
6626         StackUnroller stack_unroller(L);
6627
6628         // Push callback function on stack
6629         if(!get_detached_inventory_callback(L, name, "on_take"))
6630                 return;
6631
6632         // Call function(inv, listname, index, stack, player)
6633         // inv
6634         InventoryLocation loc;
6635         loc.setDetached(name);
6636         InvRef::create(L, loc);
6637         // listname
6638         lua_pushstring(L, listname.c_str());
6639         // index
6640         lua_pushinteger(L, index + 1);
6641         // stack
6642         LuaItemStack::create(L, stack);
6643         // player
6644         objectref_get_or_create(L, player);
6645         if(lua_pcall(L, 5, 0, 0))
6646                 script_error(L, "error: %s", lua_tostring(L, -1));
6647 }
6648
6649 /*
6650         environment
6651 */
6652
6653 void scriptapi_environment_step(lua_State *L, float dtime)
6654 {
6655         realitycheck(L);
6656         assert(lua_checkstack(L, 20));
6657         //infostream<<"scriptapi_environment_step"<<std::endl;
6658         StackUnroller stack_unroller(L);
6659
6660         // Get minetest.registered_globalsteps
6661         lua_getglobal(L, "minetest");
6662         lua_getfield(L, -1, "registered_globalsteps");
6663         // Call callbacks
6664         lua_pushnumber(L, dtime);
6665         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6666 }
6667
6668 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6669                 u32 blockseed)
6670 {
6671         realitycheck(L);
6672         assert(lua_checkstack(L, 20));
6673         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6674         StackUnroller stack_unroller(L);
6675
6676         // Get minetest.registered_on_generateds
6677         lua_getglobal(L, "minetest");
6678         lua_getfield(L, -1, "registered_on_generateds");
6679         // Call callbacks
6680         push_v3s16(L, minp);
6681         push_v3s16(L, maxp);
6682         lua_pushnumber(L, blockseed);
6683         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6684 }
6685
6686 /*
6687         luaentity
6688 */
6689
6690 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6691 {
6692         realitycheck(L);
6693         assert(lua_checkstack(L, 20));
6694         verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6695                         <<name<<"\""<<std::endl;
6696         StackUnroller stack_unroller(L);
6697         
6698         // Get minetest.registered_entities[name]
6699         lua_getglobal(L, "minetest");
6700         lua_getfield(L, -1, "registered_entities");
6701         luaL_checktype(L, -1, LUA_TTABLE);
6702         lua_pushstring(L, name);
6703         lua_gettable(L, -2);
6704         // Should be a table, which we will use as a prototype
6705         //luaL_checktype(L, -1, LUA_TTABLE);
6706         if(lua_type(L, -1) != LUA_TTABLE){
6707                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6708                 return false;
6709         }
6710         int prototype_table = lua_gettop(L);
6711         //dump2(L, "prototype_table");
6712         
6713         // Create entity object
6714         lua_newtable(L);
6715         int object = lua_gettop(L);
6716
6717         // Set object metatable
6718         lua_pushvalue(L, prototype_table);
6719         lua_setmetatable(L, -2);
6720         
6721         // Add object reference
6722         // This should be userdata with metatable ObjectRef
6723         objectref_get(L, id);
6724         luaL_checktype(L, -1, LUA_TUSERDATA);
6725         if(!luaL_checkudata(L, -1, "ObjectRef"))
6726                 luaL_typerror(L, -1, "ObjectRef");
6727         lua_setfield(L, -2, "object");
6728
6729         // minetest.luaentities[id] = object
6730         lua_getglobal(L, "minetest");
6731         lua_getfield(L, -1, "luaentities");
6732         luaL_checktype(L, -1, LUA_TTABLE);
6733         lua_pushnumber(L, id); // Push id
6734         lua_pushvalue(L, object); // Copy object to top of stack
6735         lua_settable(L, -3);
6736         
6737         return true;
6738 }
6739
6740 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6741                 const std::string &staticdata, u32 dtime_s)
6742 {
6743         realitycheck(L);
6744         assert(lua_checkstack(L, 20));
6745         verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6746         StackUnroller stack_unroller(L);
6747         
6748         // Get minetest.luaentities[id]
6749         luaentity_get(L, id);
6750         int object = lua_gettop(L);
6751         
6752         // Get on_activate function
6753         lua_pushvalue(L, object);
6754         lua_getfield(L, -1, "on_activate");
6755         if(!lua_isnil(L, -1)){
6756                 luaL_checktype(L, -1, LUA_TFUNCTION);
6757                 lua_pushvalue(L, object); // self
6758                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6759                 lua_pushinteger(L, dtime_s);
6760                 // Call with 3 arguments, 0 results
6761                 if(lua_pcall(L, 3, 0, 0))
6762                         script_error(L, "error running function on_activate: %s\n",
6763                                         lua_tostring(L, -1));
6764         }
6765 }
6766
6767 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6768 {
6769         realitycheck(L);
6770         assert(lua_checkstack(L, 20));
6771         verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6772
6773         // Get minetest.luaentities table
6774         lua_getglobal(L, "minetest");
6775         lua_getfield(L, -1, "luaentities");
6776         luaL_checktype(L, -1, LUA_TTABLE);
6777         int objectstable = lua_gettop(L);
6778         
6779         // Set luaentities[id] = nil
6780         lua_pushnumber(L, id); // Push id
6781         lua_pushnil(L);
6782         lua_settable(L, objectstable);
6783         
6784         lua_pop(L, 2); // pop luaentities, minetest
6785 }
6786
6787 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6788 {
6789         realitycheck(L);
6790         assert(lua_checkstack(L, 20));
6791         //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6792         StackUnroller stack_unroller(L);
6793
6794         // Get minetest.luaentities[id]
6795         luaentity_get(L, id);
6796         int object = lua_gettop(L);
6797         
6798         // Get get_staticdata function
6799         lua_pushvalue(L, object);
6800         lua_getfield(L, -1, "get_staticdata");
6801         if(lua_isnil(L, -1))
6802                 return "";
6803         
6804         luaL_checktype(L, -1, LUA_TFUNCTION);
6805         lua_pushvalue(L, object); // self
6806         // Call with 1 arguments, 1 results
6807         if(lua_pcall(L, 1, 1, 0))
6808                 script_error(L, "error running function get_staticdata: %s\n",
6809                                 lua_tostring(L, -1));
6810         
6811         size_t len=0;
6812         const char *s = lua_tolstring(L, -1, &len);
6813         return std::string(s, len);
6814 }
6815
6816 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6817                 ObjectProperties *prop)
6818 {
6819         realitycheck(L);
6820         assert(lua_checkstack(L, 20));
6821         //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6822         StackUnroller stack_unroller(L);
6823
6824         // Get minetest.luaentities[id]
6825         luaentity_get(L, id);
6826         //int object = lua_gettop(L);
6827
6828         // Set default values that differ from ObjectProperties defaults
6829         prop->hp_max = 10;
6830         
6831         /* Read stuff */
6832         
6833         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6834
6835         getboolfield(L, -1, "physical", prop->physical);
6836
6837         getfloatfield(L, -1, "weight", prop->weight);
6838
6839         lua_getfield(L, -1, "collisionbox");
6840         if(lua_istable(L, -1))
6841                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6842         lua_pop(L, 1);
6843
6844         getstringfield(L, -1, "visual", prop->visual);
6845
6846         getstringfield(L, -1, "mesh", prop->mesh);
6847         
6848         // Deprecated: read object properties directly
6849         read_object_properties(L, -1, prop);
6850         
6851         // Read initial_properties
6852         lua_getfield(L, -1, "initial_properties");
6853         read_object_properties(L, -1, prop);
6854         lua_pop(L, 1);
6855 }
6856
6857 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6858 {
6859         realitycheck(L);
6860         assert(lua_checkstack(L, 20));
6861         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6862         StackUnroller stack_unroller(L);
6863
6864         // Get minetest.luaentities[id]
6865         luaentity_get(L, id);
6866         int object = lua_gettop(L);
6867         // State: object is at top of stack
6868         // Get step function
6869         lua_getfield(L, -1, "on_step");
6870         if(lua_isnil(L, -1))
6871                 return;
6872         luaL_checktype(L, -1, LUA_TFUNCTION);
6873         lua_pushvalue(L, object); // self
6874         lua_pushnumber(L, dtime); // dtime
6875         // Call with 2 arguments, 0 results
6876         if(lua_pcall(L, 2, 0, 0))
6877                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6878 }
6879
6880 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6881 //                       tool_capabilities, direction)
6882 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6883                 ServerActiveObject *puncher, float time_from_last_punch,
6884                 const ToolCapabilities *toolcap, v3f dir)
6885 {
6886         realitycheck(L);
6887         assert(lua_checkstack(L, 20));
6888         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6889         StackUnroller stack_unroller(L);
6890
6891         // Get minetest.luaentities[id]
6892         luaentity_get(L, id);
6893         int object = lua_gettop(L);
6894         // State: object is at top of stack
6895         // Get function
6896         lua_getfield(L, -1, "on_punch");
6897         if(lua_isnil(L, -1))
6898                 return;
6899         luaL_checktype(L, -1, LUA_TFUNCTION);
6900         lua_pushvalue(L, object); // self
6901         objectref_get_or_create(L, puncher); // Clicker reference
6902         lua_pushnumber(L, time_from_last_punch);
6903         push_tool_capabilities(L, *toolcap);
6904         push_v3f(L, dir);
6905         // Call with 5 arguments, 0 results
6906         if(lua_pcall(L, 5, 0, 0))
6907                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6908 }
6909
6910 // Calls entity:on_rightclick(ObjectRef clicker)
6911 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6912                 ServerActiveObject *clicker)
6913 {
6914         realitycheck(L);
6915         assert(lua_checkstack(L, 20));
6916         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6917         StackUnroller stack_unroller(L);
6918
6919         // Get minetest.luaentities[id]
6920         luaentity_get(L, id);
6921         int object = lua_gettop(L);
6922         // State: object is at top of stack
6923         // Get function
6924         lua_getfield(L, -1, "on_rightclick");
6925         if(lua_isnil(L, -1))
6926                 return;
6927         luaL_checktype(L, -1, LUA_TFUNCTION);
6928         lua_pushvalue(L, object); // self
6929         objectref_get_or_create(L, clicker); // Clicker reference
6930         // Call with 2 arguments, 0 results
6931         if(lua_pcall(L, 2, 0, 0))
6932                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
6933 }
6934