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