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