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