]> git.lizzy.rs Git - minetest.git/blob - src/scriptapi.cpp
Fix crash when no world is selected and configure button is pressed.
[minetest.git] / src / scriptapi.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "scriptapi.h"
21
22 #include <iostream>
23 #include <list>
24 extern "C" {
25 #include <lua.h>
26 #include <lualib.h>
27 #include <lauxlib.h>
28 }
29
30 #include "log.h"
31 #include "server.h"
32 #include "porting.h"
33 #include "filesys.h"
34 #include "serverobject.h"
35 #include "script.h"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
38 #include "itemdef.h"
39 #include "nodedef.h"
40 #include "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 // setting_save()
4885 static int l_setting_save(lua_State *L)
4886 {
4887         get_server(L)->saveConfig();
4888         return 0;
4889 }
4890
4891 // chat_send_all(text)
4892 static int l_chat_send_all(lua_State *L)
4893 {
4894         const char *text = luaL_checkstring(L, 1);
4895         // Get server from registry
4896         Server *server = get_server(L);
4897         // Send
4898         server->notifyPlayers(narrow_to_wide(text));
4899         return 0;
4900 }
4901
4902 // chat_send_player(name, text)
4903 static int l_chat_send_player(lua_State *L)
4904 {
4905         const char *name = luaL_checkstring(L, 1);
4906         const char *text = luaL_checkstring(L, 2);
4907         // Get server from registry
4908         Server *server = get_server(L);
4909         // Send
4910         server->notifyPlayer(name, narrow_to_wide(text));
4911         return 0;
4912 }
4913
4914 // get_player_privs(name, text)
4915 static int l_get_player_privs(lua_State *L)
4916 {
4917         const char *name = luaL_checkstring(L, 1);
4918         // Get server from registry
4919         Server *server = get_server(L);
4920         // Do it
4921         lua_newtable(L);
4922         int table = lua_gettop(L);
4923         std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4924         for(std::set<std::string>::const_iterator
4925                         i = privs_s.begin(); i != privs_s.end(); i++){
4926                 lua_pushboolean(L, true);
4927                 lua_setfield(L, table, i->c_str());
4928         }
4929         lua_pushvalue(L, table);
4930         return 1;
4931 }
4932
4933 // get_ban_list()
4934 static int l_get_ban_list(lua_State *L)
4935 {
4936         lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4937         return 1;
4938 }
4939
4940 // get_ban_description()
4941 static int l_get_ban_description(lua_State *L)
4942 {
4943         const char * ip_or_name = luaL_checkstring(L, 1);
4944         lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4945         return 1;
4946 }
4947
4948 // ban_player()
4949 static int l_ban_player(lua_State *L)
4950 {
4951         const char * name = luaL_checkstring(L, 1);
4952         Player *player = get_env(L)->getPlayer(name);
4953         if(player == NULL)
4954         {
4955                 lua_pushboolean(L, false); // no such player
4956                 return 1;
4957         }
4958         try
4959         {
4960                 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4961                 std::string ip_str = addr.serializeString();
4962                 get_server(L)->setIpBanned(ip_str, name);
4963         }
4964         catch(con::PeerNotFoundException) // unlikely
4965         {
4966                 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4967                 lua_pushboolean(L, false); // error
4968                 return 1;
4969         }
4970         lua_pushboolean(L, true);
4971         return 1;
4972 }
4973
4974 // unban_player_or_ip()
4975 static int l_unban_player_of_ip(lua_State *L)
4976 {
4977         const char * ip_or_name = luaL_checkstring(L, 1);
4978         get_server(L)->unsetIpBanned(ip_or_name);
4979         lua_pushboolean(L, true);
4980         return 1;
4981 }
4982
4983 // get_inventory(location)
4984 static int l_get_inventory(lua_State *L)
4985 {
4986         InventoryLocation loc;
4987
4988         std::string type = checkstringfield(L, 1, "type");
4989         if(type == "player"){
4990                 std::string name = checkstringfield(L, 1, "name");
4991                 loc.setPlayer(name);
4992         } else if(type == "node"){
4993                 lua_getfield(L, 1, "pos");
4994                 v3s16 pos = check_v3s16(L, -1);
4995                 loc.setNodeMeta(pos);
4996         } else if(type == "detached"){
4997                 std::string name = checkstringfield(L, 1, "name");
4998                 loc.setDetached(name);
4999         }
5000
5001         if(get_server(L)->getInventory(loc) != NULL)
5002                 InvRef::create(L, loc);
5003         else
5004                 lua_pushnil(L);
5005         return 1;
5006 }
5007
5008 // create_detached_inventory_raw(name)
5009 static int l_create_detached_inventory_raw(lua_State *L)
5010 {
5011         const char *name = luaL_checkstring(L, 1);
5012         if(get_server(L)->createDetachedInventory(name) != NULL){
5013                 InventoryLocation loc;
5014                 loc.setDetached(name);
5015                 InvRef::create(L, loc);
5016         }else{
5017                 lua_pushnil(L);
5018         }
5019         return 1;
5020 }
5021
5022 // show_formspec(playername,formname,formspec)
5023 static int l_show_formspec(lua_State *L)
5024 {
5025         const char *playername = luaL_checkstring(L, 1);
5026         const char *formname = luaL_checkstring(L, 2);
5027         const char *formspec = luaL_checkstring(L, 3);
5028
5029         if(get_server(L)->showFormspec(playername,formspec,formname))
5030         {
5031                 lua_pushboolean(L, true);
5032         }else{
5033                 lua_pushboolean(L, false);
5034         }
5035         return 1;
5036 }
5037
5038 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5039 static int l_get_dig_params(lua_State *L)
5040 {
5041         std::map<std::string, int> groups;
5042         read_groups(L, 1, groups);
5043         ToolCapabilities tp = read_tool_capabilities(L, 2);
5044         if(lua_isnoneornil(L, 3))
5045                 push_dig_params(L, getDigParams(groups, &tp));
5046         else
5047                 push_dig_params(L, getDigParams(groups, &tp,
5048                                         luaL_checknumber(L, 3)));
5049         return 1;
5050 }
5051
5052 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5053 static int l_get_hit_params(lua_State *L)
5054 {
5055         std::map<std::string, int> groups;
5056         read_groups(L, 1, groups);
5057         ToolCapabilities tp = read_tool_capabilities(L, 2);
5058         if(lua_isnoneornil(L, 3))
5059                 push_hit_params(L, getHitParams(groups, &tp));
5060         else
5061                 push_hit_params(L, getHitParams(groups, &tp,
5062                                         luaL_checknumber(L, 3)));
5063         return 1;
5064 }
5065
5066 // get_current_modname()
5067 static int l_get_current_modname(lua_State *L)
5068 {
5069         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5070         return 1;
5071 }
5072
5073 // get_modpath(modname)
5074 static int l_get_modpath(lua_State *L)
5075 {
5076         std::string modname = luaL_checkstring(L, 1);
5077         // Do it
5078         if(modname == "__builtin"){
5079                 std::string path = get_server(L)->getBuiltinLuaPath();
5080                 lua_pushstring(L, path.c_str());
5081                 return 1;
5082         }
5083         const ModSpec *mod = get_server(L)->getModSpec(modname);
5084         if(!mod){
5085                 lua_pushnil(L);
5086                 return 1;
5087         }
5088         lua_pushstring(L, mod->path.c_str());
5089         return 1;
5090 }
5091
5092 // get_modnames()
5093 // the returned list is sorted alphabetically for you
5094 static int l_get_modnames(lua_State *L)
5095 {
5096         // Get a list of mods
5097         core::list<std::string> mods_unsorted, mods_sorted;
5098         get_server(L)->getModNames(mods_unsorted);
5099
5100         // Take unsorted items from mods_unsorted and sort them into
5101         // mods_sorted; not great performance but the number of mods on a
5102         // server will likely be small.
5103         for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5104             i != mods_unsorted.end(); i++)
5105         {
5106                 bool added = false;
5107                 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5108                     x != mods_unsorted.end(); x++)
5109                 {
5110                         // I doubt anybody using Minetest will be using
5111                         // anything not ASCII based :)
5112                         if((*i).compare(*x) <= 0)
5113                         {
5114                                 mods_sorted.insert_before(x, *i);
5115                                 added = true;
5116                                 break;
5117                         }
5118                 }
5119                 if(!added)
5120                         mods_sorted.push_back(*i);
5121         }
5122
5123         // Get the table insertion function from Lua.
5124         lua_getglobal(L, "table");
5125         lua_getfield(L, -1, "insert");
5126         int insertion_func = lua_gettop(L);
5127
5128         // Package them up for Lua
5129         lua_newtable(L);
5130         int new_table = lua_gettop(L);
5131         core::list<std::string>::Iterator i = mods_sorted.begin();
5132         while(i != mods_sorted.end())
5133         {
5134                 lua_pushvalue(L, insertion_func);
5135                 lua_pushvalue(L, new_table);
5136                 lua_pushstring(L, (*i).c_str());
5137                 if(lua_pcall(L, 2, 0, 0) != 0)
5138                 {
5139                         script_error(L, "error: %s", lua_tostring(L, -1));
5140                 }
5141                 i++;
5142         }
5143         return 1;
5144 }
5145
5146 // get_worldpath()
5147 static int l_get_worldpath(lua_State *L)
5148 {
5149         std::string worldpath = get_server(L)->getWorldPath();
5150         lua_pushstring(L, worldpath.c_str());
5151         return 1;
5152 }
5153
5154 // sound_play(spec, parameters)
5155 static int l_sound_play(lua_State *L)
5156 {
5157         SimpleSoundSpec spec;
5158         read_soundspec(L, 1, spec);
5159         ServerSoundParams params;
5160         read_server_sound_params(L, 2, params);
5161         s32 handle = get_server(L)->playSound(spec, params);
5162         lua_pushinteger(L, handle);
5163         return 1;
5164 }
5165
5166 // sound_stop(handle)
5167 static int l_sound_stop(lua_State *L)
5168 {
5169         int handle = luaL_checkinteger(L, 1);
5170         get_server(L)->stopSound(handle);
5171         return 0;
5172 }
5173
5174 // is_singleplayer()
5175 static int l_is_singleplayer(lua_State *L)
5176 {
5177         lua_pushboolean(L, get_server(L)->isSingleplayer());
5178         return 1;
5179 }
5180
5181 // get_password_hash(name, raw_password)
5182 static int l_get_password_hash(lua_State *L)
5183 {
5184         std::string name = luaL_checkstring(L, 1);
5185         std::string raw_password = luaL_checkstring(L, 2);
5186         std::string hash = translatePassword(name,
5187                         narrow_to_wide(raw_password));
5188         lua_pushstring(L, hash.c_str());
5189         return 1;
5190 }
5191
5192 // notify_authentication_modified(name)
5193 static int l_notify_authentication_modified(lua_State *L)
5194 {
5195         std::string name = "";
5196         if(lua_isstring(L, 1))
5197                 name = lua_tostring(L, 1);
5198         get_server(L)->reportPrivsModified(name);
5199         return 0;
5200 }
5201
5202 // get_craft_result(input)
5203 static int l_get_craft_result(lua_State *L)
5204 {
5205         int input_i = 1;
5206         std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5207         enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5208                                 es_CraftMethod, CRAFT_METHOD_NORMAL);
5209         int width = 1;
5210         lua_getfield(L, input_i, "width");
5211         if(lua_isnumber(L, -1))
5212                 width = luaL_checkinteger(L, -1);
5213         lua_pop(L, 1);
5214         lua_getfield(L, input_i, "items");
5215         std::vector<ItemStack> items = read_items(L, -1);
5216         lua_pop(L, 1); // items
5217
5218         IGameDef *gdef = get_server(L);
5219         ICraftDefManager *cdef = gdef->cdef();
5220         CraftInput input(method, width, items);
5221         CraftOutput output;
5222         bool got = cdef->getCraftResult(input, output, true, gdef);
5223         lua_newtable(L); // output table
5224         if(got){
5225                 ItemStack item;
5226                 item.deSerialize(output.item, gdef->idef());
5227                 LuaItemStack::create(L, item);
5228                 lua_setfield(L, -2, "item");
5229                 setintfield(L, -1, "time", output.time);
5230         } else {
5231                 LuaItemStack::create(L, ItemStack());
5232                 lua_setfield(L, -2, "item");
5233                 setintfield(L, -1, "time", 0);
5234         }
5235         lua_newtable(L); // decremented input table
5236         lua_pushstring(L, method_s.c_str());
5237         lua_setfield(L, -2, "method");
5238         lua_pushinteger(L, width);
5239         lua_setfield(L, -2, "width");
5240         push_items(L, input.items);
5241         lua_setfield(L, -2, "items");
5242         return 2;
5243 }
5244
5245 // get_craft_recipe(result item)
5246 static int l_get_craft_recipe(lua_State *L)
5247 {
5248         int k = 0;
5249         char tmp[20];
5250         int input_i = 1;
5251         std::string o_item = luaL_checkstring(L,input_i);
5252
5253         IGameDef *gdef = get_server(L);
5254         ICraftDefManager *cdef = gdef->cdef();
5255         CraftInput input;
5256         CraftOutput output(o_item,0);
5257         bool got = cdef->getCraftRecipe(input, output, gdef);
5258         lua_newtable(L); // output table
5259         if(got){
5260                 lua_newtable(L);
5261                 for(std::vector<ItemStack>::const_iterator
5262                         i = input.items.begin();
5263                         i != input.items.end(); i++, k++)
5264                 {
5265                         if (i->empty())
5266                         {
5267                                 continue;
5268                         }
5269                         sprintf(tmp,"%d",k);
5270                         lua_pushstring(L,tmp);
5271                         lua_pushstring(L,i->name.c_str());
5272                         lua_settable(L, -3);
5273                 }
5274                 lua_setfield(L, -2, "items");
5275                 setintfield(L, -1, "width", input.width);
5276                 switch (input.method) {
5277                 case CRAFT_METHOD_NORMAL:
5278                         lua_pushstring(L,"normal");
5279                         break;
5280                 case CRAFT_METHOD_COOKING:
5281                         lua_pushstring(L,"cooking");
5282                         break;
5283                 case CRAFT_METHOD_FUEL:
5284                         lua_pushstring(L,"fuel");
5285                         break;
5286                 default:
5287                         lua_pushstring(L,"unknown");
5288                 }
5289                 lua_setfield(L, -2, "type");
5290         } else {
5291                 lua_pushnil(L);
5292                 lua_setfield(L, -2, "items");
5293                 setintfield(L, -1, "width", 0);
5294         }
5295         return 1;
5296 }
5297
5298 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5299 static int l_rollback_get_last_node_actor(lua_State *L)
5300 {
5301         v3s16 p = read_v3s16(L, 1);
5302         int range = luaL_checknumber(L, 2);
5303         int seconds = luaL_checknumber(L, 3);
5304         Server *server = get_server(L);
5305         IRollbackManager *rollback = server->getRollbackManager();
5306         v3s16 act_p;
5307         int act_seconds = 0;
5308         std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5309         lua_pushstring(L, actor.c_str());
5310         push_v3s16(L, act_p);
5311         lua_pushnumber(L, act_seconds);
5312         return 3;
5313 }
5314
5315 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5316 static int l_rollback_revert_actions_by(lua_State *L)
5317 {
5318         std::string actor = luaL_checkstring(L, 1);
5319         int seconds = luaL_checknumber(L, 2);
5320         Server *server = get_server(L);
5321         IRollbackManager *rollback = server->getRollbackManager();
5322         std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5323         std::list<std::string> log;
5324         bool success = server->rollbackRevertActions(actions, &log);
5325         // Push boolean result
5326         lua_pushboolean(L, success);
5327         // Get the table insert function and push the log table
5328         lua_getglobal(L, "table");
5329         lua_getfield(L, -1, "insert");
5330         int table_insert = lua_gettop(L);
5331         lua_newtable(L);
5332         int table = lua_gettop(L);
5333         for(std::list<std::string>::const_iterator i = log.begin();
5334                         i != log.end(); i++)
5335         {
5336                 lua_pushvalue(L, table_insert);
5337                 lua_pushvalue(L, table);
5338                 lua_pushstring(L, i->c_str());
5339                 if(lua_pcall(L, 2, 0, 0))
5340                         script_error(L, "error: %s", lua_tostring(L, -1));
5341         }
5342         lua_remove(L, -2); // Remove table
5343         lua_remove(L, -2); // Remove insert
5344         return 2;
5345 }
5346
5347 static const struct luaL_Reg minetest_f [] = {
5348         {"debug", l_debug},
5349         {"log", l_log},
5350         {"request_shutdown", l_request_shutdown},
5351         {"get_server_status", l_get_server_status},
5352         {"register_item_raw", l_register_item_raw},
5353         {"register_alias_raw", l_register_alias_raw},
5354         {"register_craft", l_register_craft},
5355         {"register_biome", l_register_biome},
5356         {"register_biome_groups", l_register_biome_groups},
5357         {"setting_set", l_setting_set},
5358         {"setting_get", l_setting_get},
5359         {"setting_getbool", l_setting_getbool},
5360         {"setting_save",l_setting_save},
5361         {"chat_send_all", l_chat_send_all},
5362         {"chat_send_player", l_chat_send_player},
5363         {"get_player_privs", l_get_player_privs},
5364         {"get_ban_list", l_get_ban_list},
5365         {"get_ban_description", l_get_ban_description},
5366         {"ban_player", l_ban_player},
5367         {"unban_player_or_ip", l_unban_player_of_ip},
5368         {"get_inventory", l_get_inventory},
5369         {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5370         {"show_formspec", l_show_formspec},
5371         {"get_dig_params", l_get_dig_params},
5372         {"get_hit_params", l_get_hit_params},
5373         {"get_current_modname", l_get_current_modname},
5374         {"get_modpath", l_get_modpath},
5375         {"get_modnames", l_get_modnames},
5376         {"get_worldpath", l_get_worldpath},
5377         {"sound_play", l_sound_play},
5378         {"sound_stop", l_sound_stop},
5379         {"is_singleplayer", l_is_singleplayer},
5380         {"get_password_hash", l_get_password_hash},
5381         {"notify_authentication_modified", l_notify_authentication_modified},
5382         {"get_craft_result", l_get_craft_result},
5383         {"get_craft_recipe", l_get_craft_recipe},
5384         {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5385         {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5386         {NULL, NULL}
5387 };
5388
5389 /*
5390         Main export function
5391 */
5392
5393 void scriptapi_export(lua_State *L, Server *server)
5394 {
5395         realitycheck(L);
5396         assert(lua_checkstack(L, 20));
5397         verbosestream<<"scriptapi_export()"<<std::endl;
5398         StackUnroller stack_unroller(L);
5399
5400         // Store server as light userdata in registry
5401         lua_pushlightuserdata(L, server);
5402         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5403
5404         // Register global functions in table minetest
5405         lua_newtable(L);
5406         luaL_register(L, NULL, minetest_f);
5407         lua_setglobal(L, "minetest");
5408
5409         // Get the main minetest table
5410         lua_getglobal(L, "minetest");
5411
5412         // Add tables to minetest
5413         lua_newtable(L);
5414         lua_setfield(L, -2, "object_refs");
5415         lua_newtable(L);
5416         lua_setfield(L, -2, "luaentities");
5417
5418         // Register wrappers
5419         LuaItemStack::Register(L);
5420         InvRef::Register(L);
5421         NodeMetaRef::Register(L);
5422         NodeTimerRef::Register(L);
5423         ObjectRef::Register(L);
5424         EnvRef::Register(L);
5425         LuaPseudoRandom::Register(L);
5426         LuaPerlinNoise::Register(L);
5427 }
5428
5429 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5430                 const std::string &modname)
5431 {
5432         ModNameStorer modnamestorer(L, modname);
5433
5434         if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5435                         "0123456789_")){
5436                 errorstream<<"Error loading mod \""<<modname
5437                                 <<"\": modname does not follow naming conventions: "
5438                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5439                 return false;
5440         }
5441
5442         bool success = false;
5443
5444         try{
5445                 success = script_load(L, scriptpath.c_str());
5446         }
5447         catch(LuaError &e){
5448                 errorstream<<"Error loading mod \""<<modname
5449                                 <<"\": "<<e.what()<<std::endl;
5450         }
5451
5452         return success;
5453 }
5454
5455 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5456 {
5457         realitycheck(L);
5458         assert(lua_checkstack(L, 20));
5459         verbosestream<<"scriptapi_add_environment"<<std::endl;
5460         StackUnroller stack_unroller(L);
5461
5462         // Create EnvRef on stack
5463         EnvRef::create(L, env);
5464         int envref = lua_gettop(L);
5465
5466         // minetest.env = envref
5467         lua_getglobal(L, "minetest");
5468         luaL_checktype(L, -1, LUA_TTABLE);
5469         lua_pushvalue(L, envref);
5470         lua_setfield(L, -2, "env");
5471
5472         // Store environment as light userdata in registry
5473         lua_pushlightuserdata(L, env);
5474         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5475
5476         /*
5477                 Add ActiveBlockModifiers to environment
5478         */
5479
5480         // Get minetest.registered_abms
5481         lua_getglobal(L, "minetest");
5482         lua_getfield(L, -1, "registered_abms");
5483         luaL_checktype(L, -1, LUA_TTABLE);
5484         int registered_abms = lua_gettop(L);
5485
5486         if(lua_istable(L, registered_abms)){
5487                 int table = lua_gettop(L);
5488                 lua_pushnil(L);
5489                 while(lua_next(L, table) != 0){
5490                         // key at index -2 and value at index -1
5491                         int id = lua_tonumber(L, -2);
5492                         int current_abm = lua_gettop(L);
5493
5494                         std::set<std::string> trigger_contents;
5495                         lua_getfield(L, current_abm, "nodenames");
5496                         if(lua_istable(L, -1)){
5497                                 int table = lua_gettop(L);
5498                                 lua_pushnil(L);
5499                                 while(lua_next(L, table) != 0){
5500                                         // key at index -2 and value at index -1
5501                                         luaL_checktype(L, -1, LUA_TSTRING);
5502                                         trigger_contents.insert(lua_tostring(L, -1));
5503                                         // removes value, keeps key for next iteration
5504                                         lua_pop(L, 1);
5505                                 }
5506                         } else if(lua_isstring(L, -1)){
5507                                 trigger_contents.insert(lua_tostring(L, -1));
5508                         }
5509                         lua_pop(L, 1);
5510
5511                         std::set<std::string> required_neighbors;
5512                         lua_getfield(L, current_abm, "neighbors");
5513                         if(lua_istable(L, -1)){
5514                                 int table = lua_gettop(L);
5515                                 lua_pushnil(L);
5516                                 while(lua_next(L, table) != 0){
5517                                         // key at index -2 and value at index -1
5518                                         luaL_checktype(L, -1, LUA_TSTRING);
5519                                         required_neighbors.insert(lua_tostring(L, -1));
5520                                         // removes value, keeps key for next iteration
5521                                         lua_pop(L, 1);
5522                                 }
5523                         } else if(lua_isstring(L, -1)){
5524                                 required_neighbors.insert(lua_tostring(L, -1));
5525                         }
5526                         lua_pop(L, 1);
5527
5528                         float trigger_interval = 10.0;
5529                         getfloatfield(L, current_abm, "interval", trigger_interval);
5530
5531                         int trigger_chance = 50;
5532                         getintfield(L, current_abm, "chance", trigger_chance);
5533
5534                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
5535                                         required_neighbors, trigger_interval, trigger_chance);
5536
5537                         env->addActiveBlockModifier(abm);
5538
5539                         // removes value, keeps key for next iteration
5540                         lua_pop(L, 1);
5541                 }
5542         }
5543         lua_pop(L, 1);
5544 }
5545
5546 #if 0
5547 // Dump stack top with the dump2 function
5548 static void dump2(lua_State *L, const char *name)
5549 {
5550         // Dump object (debug)
5551         lua_getglobal(L, "dump2");
5552         luaL_checktype(L, -1, LUA_TFUNCTION);
5553         lua_pushvalue(L, -2); // Get previous stack top as first parameter
5554         lua_pushstring(L, name);
5555         if(lua_pcall(L, 2, 0, 0))
5556                 script_error(L, "error: %s", lua_tostring(L, -1));
5557 }
5558 #endif
5559
5560 /*
5561         object_reference
5562 */
5563
5564 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5565 {
5566         realitycheck(L);
5567         assert(lua_checkstack(L, 20));
5568         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5569         StackUnroller stack_unroller(L);
5570
5571         // Create object on stack
5572         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5573         int object = lua_gettop(L);
5574
5575         // Get minetest.object_refs table
5576         lua_getglobal(L, "minetest");
5577         lua_getfield(L, -1, "object_refs");
5578         luaL_checktype(L, -1, LUA_TTABLE);
5579         int objectstable = lua_gettop(L);
5580
5581         // object_refs[id] = object
5582         lua_pushnumber(L, cobj->getId()); // Push id
5583         lua_pushvalue(L, object); // Copy object to top of stack
5584         lua_settable(L, objectstable);
5585 }
5586
5587 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5588 {
5589         realitycheck(L);
5590         assert(lua_checkstack(L, 20));
5591         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5592         StackUnroller stack_unroller(L);
5593
5594         // Get minetest.object_refs table
5595         lua_getglobal(L, "minetest");
5596         lua_getfield(L, -1, "object_refs");
5597         luaL_checktype(L, -1, LUA_TTABLE);
5598         int objectstable = lua_gettop(L);
5599
5600         // Get object_refs[id]
5601         lua_pushnumber(L, cobj->getId()); // Push id
5602         lua_gettable(L, objectstable);
5603         // Set object reference to NULL
5604         ObjectRef::set_null(L);
5605         lua_pop(L, 1); // pop object
5606
5607         // Set object_refs[id] = nil
5608         lua_pushnumber(L, cobj->getId()); // Push id
5609         lua_pushnil(L);
5610         lua_settable(L, objectstable);
5611 }
5612
5613 /*
5614         misc
5615 */
5616
5617 // What scriptapi_run_callbacks does with the return values of callbacks.
5618 // Regardless of the mode, if only one callback is defined,
5619 // its return value is the total return value.
5620 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5621 enum RunCallbacksMode
5622 {
5623         // Returns the return value of the first callback
5624         // Returns nil if list of callbacks is empty
5625         RUN_CALLBACKS_MODE_FIRST,
5626         // Returns the return value of the last callback
5627         // Returns nil if list of callbacks is empty
5628         RUN_CALLBACKS_MODE_LAST,
5629         // If any callback returns a false value, the first such is returned
5630         // Otherwise, the first callback's return value (trueish) is returned
5631         // Returns true if list of callbacks is empty
5632         RUN_CALLBACKS_MODE_AND,
5633         // Like above, but stops calling callbacks (short circuit)
5634         // after seeing the first false value
5635         RUN_CALLBACKS_MODE_AND_SC,
5636         // If any callback returns a true value, the first such is returned
5637         // Otherwise, the first callback's return value (falseish) is returned
5638         // Returns false if list of callbacks is empty
5639         RUN_CALLBACKS_MODE_OR,
5640         // Like above, but stops calling callbacks (short circuit)
5641         // after seeing the first true value
5642         RUN_CALLBACKS_MODE_OR_SC,
5643         // Note: "a true value" and "a false value" refer to values that
5644         // are converted by lua_toboolean to true or false, respectively.
5645 };
5646
5647 // Push the list of callbacks (a lua table).
5648 // Then push nargs arguments.
5649 // Then call this function, which
5650 // - runs the callbacks
5651 // - removes the table and arguments from the lua stack
5652 // - pushes the return value, computed depending on mode
5653 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5654                 RunCallbacksMode mode)
5655 {
5656         // Insert the return value into the lua stack, below the table
5657         assert(lua_gettop(L) >= nargs + 1);
5658         lua_pushnil(L);
5659         lua_insert(L, -(nargs + 1) - 1);
5660         // Stack now looks like this:
5661         // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5662
5663         int rv = lua_gettop(L) - nargs - 1;
5664         int table = rv + 1;
5665         int arg = table + 1;
5666
5667         luaL_checktype(L, table, LUA_TTABLE);
5668
5669         // Foreach
5670         lua_pushnil(L);
5671         bool first_loop = true;
5672         while(lua_next(L, table) != 0){
5673                 // key at index -2 and value at index -1
5674                 luaL_checktype(L, -1, LUA_TFUNCTION);
5675                 // Call function
5676                 for(int i = 0; i < nargs; i++)
5677                         lua_pushvalue(L, arg+i);
5678                 if(lua_pcall(L, nargs, 1, 0))
5679                         script_error(L, "error: %s", lua_tostring(L, -1));
5680
5681                 // Move return value to designated space in stack
5682                 // Or pop it
5683                 if(first_loop){
5684                         // Result of first callback is always moved
5685                         lua_replace(L, rv);
5686                         first_loop = false;
5687                 } else {
5688                         // Otherwise, what happens depends on the mode
5689                         if(mode == RUN_CALLBACKS_MODE_FIRST)
5690                                 lua_pop(L, 1);
5691                         else if(mode == RUN_CALLBACKS_MODE_LAST)
5692                                 lua_replace(L, rv);
5693                         else if(mode == RUN_CALLBACKS_MODE_AND ||
5694                                         mode == RUN_CALLBACKS_MODE_AND_SC){
5695                                 if((bool)lua_toboolean(L, rv) == true &&
5696                                                 (bool)lua_toboolean(L, -1) == false)
5697                                         lua_replace(L, rv);
5698                                 else
5699                                         lua_pop(L, 1);
5700                         }
5701                         else if(mode == RUN_CALLBACKS_MODE_OR ||
5702                                         mode == RUN_CALLBACKS_MODE_OR_SC){
5703                                 if((bool)lua_toboolean(L, rv) == false &&
5704                                                 (bool)lua_toboolean(L, -1) == true)
5705                                         lua_replace(L, rv);
5706                                 else
5707                                         lua_pop(L, 1);
5708                         }
5709                         else
5710                                 assert(0);
5711                 }
5712
5713                 // Handle short circuit modes
5714                 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5715                                 (bool)lua_toboolean(L, rv) == false)
5716                         break;
5717                 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5718                                 (bool)lua_toboolean(L, rv) == true)
5719                         break;
5720
5721                 // value removed, keep key for next iteration
5722         }
5723
5724         // Remove stuff from stack, leaving only the return value
5725         lua_settop(L, rv);
5726
5727         // Fix return value in case no callbacks were called
5728         if(first_loop){
5729                 if(mode == RUN_CALLBACKS_MODE_AND ||
5730                                 mode == RUN_CALLBACKS_MODE_AND_SC){
5731                         lua_pop(L, 1);
5732                         lua_pushboolean(L, true);
5733                 }
5734                 else if(mode == RUN_CALLBACKS_MODE_OR ||
5735                                 mode == RUN_CALLBACKS_MODE_OR_SC){
5736                         lua_pop(L, 1);
5737                         lua_pushboolean(L, false);
5738                 }
5739         }
5740 }
5741
5742 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5743                 const std::string &message)
5744 {
5745         realitycheck(L);
5746         assert(lua_checkstack(L, 20));
5747         StackUnroller stack_unroller(L);
5748
5749         // Get minetest.registered_on_chat_messages
5750         lua_getglobal(L, "minetest");
5751         lua_getfield(L, -1, "registered_on_chat_messages");
5752         // Call callbacks
5753         lua_pushstring(L, name.c_str());
5754         lua_pushstring(L, message.c_str());
5755         scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5756         bool ate = lua_toboolean(L, -1);
5757         return ate;
5758 }
5759
5760 void scriptapi_on_shutdown(lua_State *L)
5761 {
5762         realitycheck(L);
5763         assert(lua_checkstack(L, 20));
5764         StackUnroller stack_unroller(L);
5765
5766         // Get registered shutdown hooks
5767         lua_getglobal(L, "minetest");
5768         lua_getfield(L, -1, "registered_on_shutdown");
5769         // Call callbacks
5770         scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5771 }
5772
5773 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5774 {
5775         realitycheck(L);
5776         assert(lua_checkstack(L, 20));
5777         StackUnroller stack_unroller(L);
5778
5779         // Get minetest.registered_on_newplayers
5780         lua_getglobal(L, "minetest");
5781         lua_getfield(L, -1, "registered_on_newplayers");
5782         // Call callbacks
5783         objectref_get_or_create(L, player);
5784         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5785 }
5786
5787 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5788 {
5789         realitycheck(L);
5790         assert(lua_checkstack(L, 20));
5791         StackUnroller stack_unroller(L);
5792
5793         // Get minetest.registered_on_dieplayers
5794         lua_getglobal(L, "minetest");
5795         lua_getfield(L, -1, "registered_on_dieplayers");
5796         // Call callbacks
5797         objectref_get_or_create(L, player);
5798         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5799 }
5800
5801 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5802 {
5803         realitycheck(L);
5804         assert(lua_checkstack(L, 20));
5805         StackUnroller stack_unroller(L);
5806
5807         // Get minetest.registered_on_respawnplayers
5808         lua_getglobal(L, "minetest");
5809         lua_getfield(L, -1, "registered_on_respawnplayers");
5810         // Call callbacks
5811         objectref_get_or_create(L, player);
5812         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5813         bool positioning_handled_by_some = lua_toboolean(L, -1);
5814         return positioning_handled_by_some;
5815 }
5816
5817 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5818 {
5819         realitycheck(L);
5820         assert(lua_checkstack(L, 20));
5821         StackUnroller stack_unroller(L);
5822
5823         // Get minetest.registered_on_joinplayers
5824         lua_getglobal(L, "minetest");
5825         lua_getfield(L, -1, "registered_on_joinplayers");
5826         // Call callbacks
5827         objectref_get_or_create(L, player);
5828         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5829 }
5830
5831 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5832 {
5833         realitycheck(L);
5834         assert(lua_checkstack(L, 20));
5835         StackUnroller stack_unroller(L);
5836
5837         // Get minetest.registered_on_leaveplayers
5838         lua_getglobal(L, "minetest");
5839         lua_getfield(L, -1, "registered_on_leaveplayers");
5840         // Call callbacks
5841         objectref_get_or_create(L, player);
5842         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5843 }
5844
5845 static void get_auth_handler(lua_State *L)
5846 {
5847         lua_getglobal(L, "minetest");
5848         lua_getfield(L, -1, "registered_auth_handler");
5849         if(lua_isnil(L, -1)){
5850                 lua_pop(L, 1);
5851                 lua_getfield(L, -1, "builtin_auth_handler");
5852         }
5853         if(lua_type(L, -1) != LUA_TTABLE)
5854                 throw LuaError(L, "Authentication handler table not valid");
5855 }
5856
5857 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5858                 std::string *dst_password, std::set<std::string> *dst_privs)
5859 {
5860         realitycheck(L);
5861         assert(lua_checkstack(L, 20));
5862         StackUnroller stack_unroller(L);
5863
5864         get_auth_handler(L);
5865         lua_getfield(L, -1, "get_auth");
5866         if(lua_type(L, -1) != LUA_TFUNCTION)
5867                 throw LuaError(L, "Authentication handler missing get_auth");
5868         lua_pushstring(L, playername.c_str());
5869         if(lua_pcall(L, 1, 1, 0))
5870                 script_error(L, "error: %s", lua_tostring(L, -1));
5871
5872         // nil = login not allowed
5873         if(lua_isnil(L, -1))
5874                 return false;
5875         luaL_checktype(L, -1, LUA_TTABLE);
5876
5877         std::string password;
5878         bool found = getstringfield(L, -1, "password", password);
5879         if(!found)
5880                 throw LuaError(L, "Authentication handler didn't return password");
5881         if(dst_password)
5882                 *dst_password = password;
5883
5884         lua_getfield(L, -1, "privileges");
5885         if(!lua_istable(L, -1))
5886                 throw LuaError(L,
5887                                 "Authentication handler didn't return privilege table");
5888         if(dst_privs)
5889                 read_privileges(L, -1, *dst_privs);
5890         lua_pop(L, 1);
5891
5892         return true;
5893 }
5894
5895 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5896                 const std::string &password)
5897 {
5898         realitycheck(L);
5899         assert(lua_checkstack(L, 20));
5900         StackUnroller stack_unroller(L);
5901
5902         get_auth_handler(L);
5903         lua_getfield(L, -1, "create_auth");
5904         if(lua_type(L, -1) != LUA_TFUNCTION)
5905                 throw LuaError(L, "Authentication handler missing create_auth");
5906         lua_pushstring(L, playername.c_str());
5907         lua_pushstring(L, password.c_str());
5908         if(lua_pcall(L, 2, 0, 0))
5909                 script_error(L, "error: %s", lua_tostring(L, -1));
5910 }
5911
5912 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5913                 const std::string &password)
5914 {
5915         realitycheck(L);
5916         assert(lua_checkstack(L, 20));
5917         StackUnroller stack_unroller(L);
5918
5919         get_auth_handler(L);
5920         lua_getfield(L, -1, "set_password");
5921         if(lua_type(L, -1) != LUA_TFUNCTION)
5922                 throw LuaError(L, "Authentication handler missing set_password");
5923         lua_pushstring(L, playername.c_str());
5924         lua_pushstring(L, password.c_str());
5925         if(lua_pcall(L, 2, 1, 0))
5926                 script_error(L, "error: %s", lua_tostring(L, -1));
5927         return lua_toboolean(L, -1);
5928 }
5929
5930 /*
5931         player
5932 */
5933
5934 void scriptapi_on_player_receive_fields(lua_State *L,
5935                 ServerActiveObject *player,
5936                 const std::string &formname,
5937                 const std::map<std::string, std::string> &fields)
5938 {
5939         realitycheck(L);
5940         assert(lua_checkstack(L, 20));
5941         StackUnroller stack_unroller(L);
5942
5943         // Get minetest.registered_on_chat_messages
5944         lua_getglobal(L, "minetest");
5945         lua_getfield(L, -1, "registered_on_player_receive_fields");
5946         // Call callbacks
5947         // param 1
5948         objectref_get_or_create(L, player);
5949         // param 2
5950         lua_pushstring(L, formname.c_str());
5951         // param 3
5952         lua_newtable(L);
5953         for(std::map<std::string, std::string>::const_iterator
5954                         i = fields.begin(); i != fields.end(); i++){
5955                 const std::string &name = i->first;
5956                 const std::string &value = i->second;
5957                 lua_pushstring(L, name.c_str());
5958                 lua_pushlstring(L, value.c_str(), value.size());
5959                 lua_settable(L, -3);
5960         }
5961         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5962 }
5963
5964 /*
5965         item callbacks and node callbacks
5966 */
5967
5968 // Retrieves minetest.registered_items[name][callbackname]
5969 // If that is nil or on error, return false and stack is unchanged
5970 // If that is a function, returns true and pushes the
5971 // function onto the stack
5972 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5973 // is tried instead so unknown items can still be manipulated to some degree
5974 static bool get_item_callback(lua_State *L,
5975                 const char *name, const char *callbackname)
5976 {
5977         lua_getglobal(L, "minetest");
5978         lua_getfield(L, -1, "registered_items");
5979         lua_remove(L, -2);
5980         luaL_checktype(L, -1, LUA_TTABLE);
5981         lua_getfield(L, -1, name);
5982         lua_remove(L, -2);
5983         // Should be a table
5984         if(lua_type(L, -1) != LUA_TTABLE)
5985         {
5986                 // Report error and clean up
5987                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5988                 lua_pop(L, 1);
5989
5990                 // Try minetest.nodedef_default instead
5991                 lua_getglobal(L, "minetest");
5992                 lua_getfield(L, -1, "nodedef_default");
5993                 lua_remove(L, -2);
5994                 luaL_checktype(L, -1, LUA_TTABLE);
5995         }
5996         lua_getfield(L, -1, callbackname);
5997         lua_remove(L, -2);
5998         // Should be a function or nil
5999         if(lua_type(L, -1) == LUA_TFUNCTION)
6000         {
6001                 return true;
6002         }
6003         else if(lua_isnil(L, -1))
6004         {
6005                 lua_pop(L, 1);
6006                 return false;
6007         }
6008         else
6009         {
6010                 errorstream<<"Item \""<<name<<"\" callback \""
6011                         <<callbackname<<" is not a function"<<std::endl;
6012                 lua_pop(L, 1);
6013                 return false;
6014         }
6015 }
6016
6017 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6018                 ServerActiveObject *dropper, v3f pos)
6019 {
6020         realitycheck(L);
6021         assert(lua_checkstack(L, 20));
6022         StackUnroller stack_unroller(L);
6023
6024         // Push callback function on stack
6025         if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6026                 return false;
6027
6028         // Call function
6029         LuaItemStack::create(L, item);
6030         objectref_get_or_create(L, dropper);
6031         pushFloatPos(L, pos);
6032         if(lua_pcall(L, 3, 1, 0))
6033                 script_error(L, "error: %s", lua_tostring(L, -1));
6034         if(!lua_isnil(L, -1))
6035                 item = read_item(L, -1);
6036         return true;
6037 }
6038
6039 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6040                 ServerActiveObject *placer, const PointedThing &pointed)
6041 {
6042         realitycheck(L);
6043         assert(lua_checkstack(L, 20));
6044         StackUnroller stack_unroller(L);
6045
6046         // Push callback function on stack
6047         if(!get_item_callback(L, item.name.c_str(), "on_place"))
6048                 return false;
6049
6050         // Call function
6051         LuaItemStack::create(L, item);
6052         objectref_get_or_create(L, placer);
6053         push_pointed_thing(L, pointed);
6054         if(lua_pcall(L, 3, 1, 0))
6055                 script_error(L, "error: %s", lua_tostring(L, -1));
6056         if(!lua_isnil(L, -1))
6057                 item = read_item(L, -1);
6058         return true;
6059 }
6060
6061 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6062                 ServerActiveObject *user, const PointedThing &pointed)
6063 {
6064         realitycheck(L);
6065         assert(lua_checkstack(L, 20));
6066         StackUnroller stack_unroller(L);
6067
6068         // Push callback function on stack
6069         if(!get_item_callback(L, item.name.c_str(), "on_use"))
6070                 return false;
6071
6072         // Call function
6073         LuaItemStack::create(L, item);
6074         objectref_get_or_create(L, user);
6075         push_pointed_thing(L, pointed);
6076         if(lua_pcall(L, 3, 1, 0))
6077                 script_error(L, "error: %s", lua_tostring(L, -1));
6078         if(!lua_isnil(L, -1))
6079                 item = read_item(L, -1);
6080         return true;
6081 }
6082
6083 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6084                 ServerActiveObject *puncher)
6085 {
6086         realitycheck(L);
6087         assert(lua_checkstack(L, 20));
6088         StackUnroller stack_unroller(L);
6089
6090         INodeDefManager *ndef = get_server(L)->ndef();
6091
6092         // Push callback function on stack
6093         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6094                 return false;
6095
6096         // Call function
6097         push_v3s16(L, p);
6098         pushnode(L, node, ndef);
6099         objectref_get_or_create(L, puncher);
6100         if(lua_pcall(L, 3, 0, 0))
6101                 script_error(L, "error: %s", lua_tostring(L, -1));
6102         return true;
6103 }
6104
6105 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6106                 ServerActiveObject *digger)
6107 {
6108         realitycheck(L);
6109         assert(lua_checkstack(L, 20));
6110         StackUnroller stack_unroller(L);
6111
6112         INodeDefManager *ndef = get_server(L)->ndef();
6113
6114         // Push callback function on stack
6115         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6116                 return false;
6117
6118         // Call function
6119         push_v3s16(L, p);
6120         pushnode(L, node, ndef);
6121         objectref_get_or_create(L, digger);
6122         if(lua_pcall(L, 3, 0, 0))
6123                 script_error(L, "error: %s", lua_tostring(L, -1));
6124         return true;
6125 }
6126
6127 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6128 {
6129         realitycheck(L);
6130         assert(lua_checkstack(L, 20));
6131         StackUnroller stack_unroller(L);
6132
6133         INodeDefManager *ndef = get_server(L)->ndef();
6134
6135         // Push callback function on stack
6136         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6137                 return;
6138
6139         // Call function
6140         push_v3s16(L, p);
6141         if(lua_pcall(L, 1, 0, 0))
6142                 script_error(L, "error: %s", lua_tostring(L, -1));
6143 }
6144
6145 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6146 {
6147         realitycheck(L);
6148         assert(lua_checkstack(L, 20));
6149         StackUnroller stack_unroller(L);
6150
6151         INodeDefManager *ndef = get_server(L)->ndef();
6152
6153         // Push callback function on stack
6154         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6155                 return;
6156
6157         // Call function
6158         push_v3s16(L, p);
6159         if(lua_pcall(L, 1, 0, 0))
6160                 script_error(L, "error: %s", lua_tostring(L, -1));
6161 }
6162
6163 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6164 {
6165         realitycheck(L);
6166         assert(lua_checkstack(L, 20));
6167         StackUnroller stack_unroller(L);
6168
6169         INodeDefManager *ndef = get_server(L)->ndef();
6170
6171         // Push callback function on stack
6172         if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6173                 return;
6174
6175         // Call function
6176         push_v3s16(L, p);
6177         pushnode(L, node, ndef);
6178         if(lua_pcall(L, 2, 0, 0))
6179                 script_error(L, "error: %s", lua_tostring(L, -1));
6180 }
6181
6182 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6183 {
6184         realitycheck(L);
6185         assert(lua_checkstack(L, 20));
6186         StackUnroller stack_unroller(L);
6187
6188         INodeDefManager *ndef = get_server(L)->ndef();
6189
6190         // Push callback function on stack
6191         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6192                 return false;
6193
6194         // Call function
6195         push_v3s16(L, p);
6196         lua_pushnumber(L,dtime);
6197         if(lua_pcall(L, 2, 1, 0))
6198                 script_error(L, "error: %s", lua_tostring(L, -1));
6199         if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6200                 return true;
6201
6202         return false;
6203 }
6204
6205 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6206                 const std::string &formname,
6207                 const std::map<std::string, std::string> &fields,
6208                 ServerActiveObject *sender)
6209 {
6210         realitycheck(L);
6211         assert(lua_checkstack(L, 20));
6212         StackUnroller stack_unroller(L);
6213
6214         INodeDefManager *ndef = get_server(L)->ndef();
6215
6216         // If node doesn't exist, we don't know what callback to call
6217         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6218         if(node.getContent() == CONTENT_IGNORE)
6219                 return;
6220
6221         // Push callback function on stack
6222         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6223                 return;
6224
6225         // Call function
6226         // param 1
6227         push_v3s16(L, p);
6228         // param 2
6229         lua_pushstring(L, formname.c_str());
6230         // param 3
6231         lua_newtable(L);
6232         for(std::map<std::string, std::string>::const_iterator
6233                         i = fields.begin(); i != fields.end(); i++){
6234                 const std::string &name = i->first;
6235                 const std::string &value = i->second;
6236                 lua_pushstring(L, name.c_str());
6237                 lua_pushlstring(L, value.c_str(), value.size());
6238                 lua_settable(L, -3);
6239         }
6240         // param 4
6241         objectref_get_or_create(L, sender);
6242         if(lua_pcall(L, 4, 0, 0))
6243                 script_error(L, "error: %s", lua_tostring(L, -1));
6244 }
6245
6246 /*
6247         Node metadata inventory callbacks
6248 */
6249
6250 // Return number of accepted items to be moved
6251 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6252                 const std::string &from_list, int from_index,
6253                 const std::string &to_list, int to_index,
6254                 int count, ServerActiveObject *player)
6255 {
6256         realitycheck(L);
6257         assert(lua_checkstack(L, 20));
6258         StackUnroller stack_unroller(L);
6259
6260         INodeDefManager *ndef = get_server(L)->ndef();
6261
6262         // If node doesn't exist, we don't know what callback to call
6263         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6264         if(node.getContent() == CONTENT_IGNORE)
6265                 return 0;
6266
6267         // Push callback function on stack
6268         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6269                         "allow_metadata_inventory_move"))
6270                 return count;
6271
6272         // function(pos, from_list, from_index, to_list, to_index, count, player)
6273         // pos
6274         push_v3s16(L, p);
6275         // from_list
6276         lua_pushstring(L, from_list.c_str());
6277         // from_index
6278         lua_pushinteger(L, from_index + 1);
6279         // to_list
6280         lua_pushstring(L, to_list.c_str());
6281         // to_index
6282         lua_pushinteger(L, to_index + 1);
6283         // count
6284         lua_pushinteger(L, count);
6285         // player
6286         objectref_get_or_create(L, player);
6287         if(lua_pcall(L, 7, 1, 0))
6288                 script_error(L, "error: %s", lua_tostring(L, -1));
6289         if(!lua_isnumber(L, -1))
6290                 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6291         return luaL_checkinteger(L, -1);
6292 }
6293
6294 // Return number of accepted items to be put
6295 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6296                 const std::string &listname, int index, ItemStack &stack,
6297                 ServerActiveObject *player)
6298 {
6299         realitycheck(L);
6300         assert(lua_checkstack(L, 20));
6301         StackUnroller stack_unroller(L);
6302
6303         INodeDefManager *ndef = get_server(L)->ndef();
6304
6305         // If node doesn't exist, we don't know what callback to call
6306         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6307         if(node.getContent() == CONTENT_IGNORE)
6308                 return 0;
6309
6310         // Push callback function on stack
6311         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6312                         "allow_metadata_inventory_put"))
6313                 return stack.count;
6314
6315         // Call function(pos, listname, index, stack, player)
6316         // pos
6317         push_v3s16(L, p);
6318         // listname
6319         lua_pushstring(L, listname.c_str());
6320         // index
6321         lua_pushinteger(L, index + 1);
6322         // stack
6323         LuaItemStack::create(L, stack);
6324         // player
6325         objectref_get_or_create(L, player);
6326         if(lua_pcall(L, 5, 1, 0))
6327                 script_error(L, "error: %s", lua_tostring(L, -1));
6328         if(!lua_isnumber(L, -1))
6329                 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6330         return luaL_checkinteger(L, -1);
6331 }
6332
6333 // Return number of accepted items to be taken
6334 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6335                 const std::string &listname, int index, ItemStack &stack,
6336                 ServerActiveObject *player)
6337 {
6338         realitycheck(L);
6339         assert(lua_checkstack(L, 20));
6340         StackUnroller stack_unroller(L);
6341
6342         INodeDefManager *ndef = get_server(L)->ndef();
6343
6344         // If node doesn't exist, we don't know what callback to call
6345         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6346         if(node.getContent() == CONTENT_IGNORE)
6347                 return 0;
6348
6349         // Push callback function on stack
6350         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6351                         "allow_metadata_inventory_take"))
6352                 return stack.count;
6353
6354         // Call function(pos, listname, index, count, player)
6355         // pos
6356         push_v3s16(L, p);
6357         // listname
6358         lua_pushstring(L, listname.c_str());
6359         // index
6360         lua_pushinteger(L, index + 1);
6361         // stack
6362         LuaItemStack::create(L, stack);
6363         // player
6364         objectref_get_or_create(L, player);
6365         if(lua_pcall(L, 5, 1, 0))
6366                 script_error(L, "error: %s", lua_tostring(L, -1));
6367         if(!lua_isnumber(L, -1))
6368                 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6369         return luaL_checkinteger(L, -1);
6370 }
6371
6372 // Report moved items
6373 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6374                 const std::string &from_list, int from_index,
6375                 const std::string &to_list, int to_index,
6376                 int count, ServerActiveObject *player)
6377 {
6378         realitycheck(L);
6379         assert(lua_checkstack(L, 20));
6380         StackUnroller stack_unroller(L);
6381
6382         INodeDefManager *ndef = get_server(L)->ndef();
6383
6384         // If node doesn't exist, we don't know what callback to call
6385         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6386         if(node.getContent() == CONTENT_IGNORE)
6387                 return;
6388
6389         // Push callback function on stack
6390         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6391                         "on_metadata_inventory_move"))
6392                 return;
6393
6394         // function(pos, from_list, from_index, to_list, to_index, count, player)
6395         // pos
6396         push_v3s16(L, p);
6397         // from_list
6398         lua_pushstring(L, from_list.c_str());
6399         // from_index
6400         lua_pushinteger(L, from_index + 1);
6401         // to_list
6402         lua_pushstring(L, to_list.c_str());
6403         // to_index
6404         lua_pushinteger(L, to_index + 1);
6405         // count
6406         lua_pushinteger(L, count);
6407         // player
6408         objectref_get_or_create(L, player);
6409         if(lua_pcall(L, 7, 0, 0))
6410                 script_error(L, "error: %s", lua_tostring(L, -1));
6411 }
6412
6413 // Report put items
6414 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6415                 const std::string &listname, int index, ItemStack &stack,
6416                 ServerActiveObject *player)
6417 {
6418         realitycheck(L);
6419         assert(lua_checkstack(L, 20));
6420         StackUnroller stack_unroller(L);
6421
6422         INodeDefManager *ndef = get_server(L)->ndef();
6423
6424         // If node doesn't exist, we don't know what callback to call
6425         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6426         if(node.getContent() == CONTENT_IGNORE)
6427                 return;
6428
6429         // Push callback function on stack
6430         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6431                         "on_metadata_inventory_put"))
6432                 return;
6433
6434         // Call function(pos, listname, index, stack, player)
6435         // pos
6436         push_v3s16(L, p);
6437         // listname
6438         lua_pushstring(L, listname.c_str());
6439         // index
6440         lua_pushinteger(L, index + 1);
6441         // stack
6442         LuaItemStack::create(L, stack);
6443         // player
6444         objectref_get_or_create(L, player);
6445         if(lua_pcall(L, 5, 0, 0))
6446                 script_error(L, "error: %s", lua_tostring(L, -1));
6447 }
6448
6449 // Report taken items
6450 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6451                 const std::string &listname, int index, ItemStack &stack,
6452                 ServerActiveObject *player)
6453 {
6454         realitycheck(L);
6455         assert(lua_checkstack(L, 20));
6456         StackUnroller stack_unroller(L);
6457
6458         INodeDefManager *ndef = get_server(L)->ndef();
6459
6460         // If node doesn't exist, we don't know what callback to call
6461         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6462         if(node.getContent() == CONTENT_IGNORE)
6463                 return;
6464
6465         // Push callback function on stack
6466         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6467                         "on_metadata_inventory_take"))
6468                 return;
6469
6470         // Call function(pos, listname, index, stack, player)
6471         // pos
6472         push_v3s16(L, p);
6473         // listname
6474         lua_pushstring(L, listname.c_str());
6475         // index
6476         lua_pushinteger(L, index + 1);
6477         // stack
6478         LuaItemStack::create(L, stack);
6479         // player
6480         objectref_get_or_create(L, player);
6481         if(lua_pcall(L, 5, 0, 0))
6482                 script_error(L, "error: %s", lua_tostring(L, -1));
6483 }
6484
6485 /*
6486         Detached inventory callbacks
6487 */
6488
6489 // Retrieves minetest.detached_inventories[name][callbackname]
6490 // If that is nil or on error, return false and stack is unchanged
6491 // If that is a function, returns true and pushes the
6492 // function onto the stack
6493 static bool get_detached_inventory_callback(lua_State *L,
6494                 const std::string &name, const char *callbackname)
6495 {
6496         lua_getglobal(L, "minetest");
6497         lua_getfield(L, -1, "detached_inventories");
6498         lua_remove(L, -2);
6499         luaL_checktype(L, -1, LUA_TTABLE);
6500         lua_getfield(L, -1, name.c_str());
6501         lua_remove(L, -2);
6502         // Should be a table
6503         if(lua_type(L, -1) != LUA_TTABLE)
6504         {
6505                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6506                 lua_pop(L, 1);
6507                 return false;
6508         }
6509         lua_getfield(L, -1, callbackname);
6510         lua_remove(L, -2);
6511         // Should be a function or nil
6512         if(lua_type(L, -1) == LUA_TFUNCTION)
6513         {
6514                 return true;
6515         }
6516         else if(lua_isnil(L, -1))
6517         {
6518                 lua_pop(L, 1);
6519                 return false;
6520         }
6521         else
6522         {
6523                 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6524                         <<callbackname<<"\" is not a function"<<std::endl;
6525                 lua_pop(L, 1);
6526                 return false;
6527         }
6528 }
6529
6530 // Return number of accepted items to be moved
6531 int scriptapi_detached_inventory_allow_move(lua_State *L,
6532                 const std::string &name,
6533                 const std::string &from_list, int from_index,
6534                 const std::string &to_list, int to_index,
6535                 int count, ServerActiveObject *player)
6536 {
6537         realitycheck(L);
6538         assert(lua_checkstack(L, 20));
6539         StackUnroller stack_unroller(L);
6540
6541         // Push callback function on stack
6542         if(!get_detached_inventory_callback(L, name, "allow_move"))
6543                 return count;
6544
6545         // function(inv, from_list, from_index, to_list, to_index, count, player)
6546         // inv
6547         InventoryLocation loc;
6548         loc.setDetached(name);
6549         InvRef::create(L, loc);
6550         // from_list
6551         lua_pushstring(L, from_list.c_str());
6552         // from_index
6553         lua_pushinteger(L, from_index + 1);
6554         // to_list
6555         lua_pushstring(L, to_list.c_str());
6556         // to_index
6557         lua_pushinteger(L, to_index + 1);
6558         // count
6559         lua_pushinteger(L, count);
6560         // player
6561         objectref_get_or_create(L, player);
6562         if(lua_pcall(L, 7, 1, 0))
6563                 script_error(L, "error: %s", lua_tostring(L, -1));
6564         if(!lua_isnumber(L, -1))
6565                 throw LuaError(L, "allow_move should return a number");
6566         return luaL_checkinteger(L, -1);
6567 }
6568
6569 // Return number of accepted items to be put
6570 int scriptapi_detached_inventory_allow_put(lua_State *L,
6571                 const std::string &name,
6572                 const std::string &listname, int index, ItemStack &stack,
6573                 ServerActiveObject *player)
6574 {
6575         realitycheck(L);
6576         assert(lua_checkstack(L, 20));
6577         StackUnroller stack_unroller(L);
6578
6579         // Push callback function on stack
6580         if(!get_detached_inventory_callback(L, name, "allow_put"))
6581                 return stack.count; // All will be accepted
6582
6583         // Call function(inv, listname, index, stack, player)
6584         // inv
6585         InventoryLocation loc;
6586         loc.setDetached(name);
6587         InvRef::create(L, loc);
6588         // listname
6589         lua_pushstring(L, listname.c_str());
6590         // index
6591         lua_pushinteger(L, index + 1);
6592         // stack
6593         LuaItemStack::create(L, stack);
6594         // player
6595         objectref_get_or_create(L, player);
6596         if(lua_pcall(L, 5, 1, 0))
6597                 script_error(L, "error: %s", lua_tostring(L, -1));
6598         if(!lua_isnumber(L, -1))
6599                 throw LuaError(L, "allow_put should return a number");
6600         return luaL_checkinteger(L, -1);
6601 }
6602
6603 // Return number of accepted items to be taken
6604 int scriptapi_detached_inventory_allow_take(lua_State *L,
6605                 const std::string &name,
6606                 const std::string &listname, int index, ItemStack &stack,
6607                 ServerActiveObject *player)
6608 {
6609         realitycheck(L);
6610         assert(lua_checkstack(L, 20));
6611         StackUnroller stack_unroller(L);
6612
6613         // Push callback function on stack
6614         if(!get_detached_inventory_callback(L, name, "allow_take"))
6615                 return stack.count; // All will be accepted
6616
6617         // Call function(inv, listname, index, stack, player)
6618         // inv
6619         InventoryLocation loc;
6620         loc.setDetached(name);
6621         InvRef::create(L, loc);
6622         // listname
6623         lua_pushstring(L, listname.c_str());
6624         // index
6625         lua_pushinteger(L, index + 1);
6626         // stack
6627         LuaItemStack::create(L, stack);
6628         // player
6629         objectref_get_or_create(L, player);
6630         if(lua_pcall(L, 5, 1, 0))
6631                 script_error(L, "error: %s", lua_tostring(L, -1));
6632         if(!lua_isnumber(L, -1))
6633                 throw LuaError(L, "allow_take should return a number");
6634         return luaL_checkinteger(L, -1);
6635 }
6636
6637 // Report moved items
6638 void scriptapi_detached_inventory_on_move(lua_State *L,
6639                 const std::string &name,
6640                 const std::string &from_list, int from_index,
6641                 const std::string &to_list, int to_index,
6642                 int count, ServerActiveObject *player)
6643 {
6644         realitycheck(L);
6645         assert(lua_checkstack(L, 20));
6646         StackUnroller stack_unroller(L);
6647
6648         // Push callback function on stack
6649         if(!get_detached_inventory_callback(L, name, "on_move"))
6650                 return;
6651
6652         // function(inv, from_list, from_index, to_list, to_index, count, player)
6653         // inv
6654         InventoryLocation loc;
6655         loc.setDetached(name);
6656         InvRef::create(L, loc);
6657         // from_list
6658         lua_pushstring(L, from_list.c_str());
6659         // from_index
6660         lua_pushinteger(L, from_index + 1);
6661         // to_list
6662         lua_pushstring(L, to_list.c_str());
6663         // to_index
6664         lua_pushinteger(L, to_index + 1);
6665         // count
6666         lua_pushinteger(L, count);
6667         // player
6668         objectref_get_or_create(L, player);
6669         if(lua_pcall(L, 7, 0, 0))
6670                 script_error(L, "error: %s", lua_tostring(L, -1));
6671 }
6672
6673 // Report put items
6674 void scriptapi_detached_inventory_on_put(lua_State *L,
6675                 const std::string &name,
6676                 const std::string &listname, int index, ItemStack &stack,
6677                 ServerActiveObject *player)
6678 {
6679         realitycheck(L);
6680         assert(lua_checkstack(L, 20));
6681         StackUnroller stack_unroller(L);
6682
6683         // Push callback function on stack
6684         if(!get_detached_inventory_callback(L, name, "on_put"))
6685                 return;
6686
6687         // Call function(inv, listname, index, stack, player)
6688         // inv
6689         InventoryLocation loc;
6690         loc.setDetached(name);
6691         InvRef::create(L, loc);
6692         // listname
6693         lua_pushstring(L, listname.c_str());
6694         // index
6695         lua_pushinteger(L, index + 1);
6696         // stack
6697         LuaItemStack::create(L, stack);
6698         // player
6699         objectref_get_or_create(L, player);
6700         if(lua_pcall(L, 5, 0, 0))
6701                 script_error(L, "error: %s", lua_tostring(L, -1));
6702 }
6703
6704 // Report taken items
6705 void scriptapi_detached_inventory_on_take(lua_State *L,
6706                 const std::string &name,
6707                 const std::string &listname, int index, ItemStack &stack,
6708                 ServerActiveObject *player)
6709 {
6710         realitycheck(L);
6711         assert(lua_checkstack(L, 20));
6712         StackUnroller stack_unroller(L);
6713
6714         // Push callback function on stack
6715         if(!get_detached_inventory_callback(L, name, "on_take"))
6716                 return;
6717
6718         // Call function(inv, listname, index, stack, player)
6719         // inv
6720         InventoryLocation loc;
6721         loc.setDetached(name);
6722         InvRef::create(L, loc);
6723         // listname
6724         lua_pushstring(L, listname.c_str());
6725         // index
6726         lua_pushinteger(L, index + 1);
6727         // stack
6728         LuaItemStack::create(L, stack);
6729         // player
6730         objectref_get_or_create(L, player);
6731         if(lua_pcall(L, 5, 0, 0))
6732                 script_error(L, "error: %s", lua_tostring(L, -1));
6733 }
6734
6735 /*
6736         environment
6737 */
6738
6739 void scriptapi_environment_step(lua_State *L, float dtime)
6740 {
6741         realitycheck(L);
6742         assert(lua_checkstack(L, 20));
6743         //infostream<<"scriptapi_environment_step"<<std::endl;
6744         StackUnroller stack_unroller(L);
6745
6746         // Get minetest.registered_globalsteps
6747         lua_getglobal(L, "minetest");
6748         lua_getfield(L, -1, "registered_globalsteps");
6749         // Call callbacks
6750         lua_pushnumber(L, dtime);
6751         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6752 }
6753
6754 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6755                 u32 blockseed)
6756 {
6757         realitycheck(L);
6758         assert(lua_checkstack(L, 20));
6759         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6760         StackUnroller stack_unroller(L);
6761
6762         // Get minetest.registered_on_generateds
6763         lua_getglobal(L, "minetest");
6764         lua_getfield(L, -1, "registered_on_generateds");
6765         // Call callbacks
6766         push_v3s16(L, minp);
6767         push_v3s16(L, maxp);
6768         lua_pushnumber(L, blockseed);
6769         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6770 }
6771
6772 /*
6773         luaentity
6774 */
6775
6776 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6777 {
6778         realitycheck(L);
6779         assert(lua_checkstack(L, 20));
6780         verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6781                         <<name<<"\""<<std::endl;
6782         StackUnroller stack_unroller(L);
6783
6784         // Get minetest.registered_entities[name]
6785         lua_getglobal(L, "minetest");
6786         lua_getfield(L, -1, "registered_entities");
6787         luaL_checktype(L, -1, LUA_TTABLE);
6788         lua_pushstring(L, name);
6789         lua_gettable(L, -2);
6790         // Should be a table, which we will use as a prototype
6791         //luaL_checktype(L, -1, LUA_TTABLE);
6792         if(lua_type(L, -1) != LUA_TTABLE){
6793                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6794                 return false;
6795         }
6796         int prototype_table = lua_gettop(L);
6797         //dump2(L, "prototype_table");
6798
6799         // Create entity object
6800         lua_newtable(L);
6801         int object = lua_gettop(L);
6802
6803         // Set object metatable
6804         lua_pushvalue(L, prototype_table);
6805         lua_setmetatable(L, -2);
6806
6807         // Add object reference
6808         // This should be userdata with metatable ObjectRef
6809         objectref_get(L, id);
6810         luaL_checktype(L, -1, LUA_TUSERDATA);
6811         if(!luaL_checkudata(L, -1, "ObjectRef"))
6812                 luaL_typerror(L, -1, "ObjectRef");
6813         lua_setfield(L, -2, "object");
6814
6815         // minetest.luaentities[id] = object
6816         lua_getglobal(L, "minetest");
6817         lua_getfield(L, -1, "luaentities");
6818         luaL_checktype(L, -1, LUA_TTABLE);
6819         lua_pushnumber(L, id); // Push id
6820         lua_pushvalue(L, object); // Copy object to top of stack
6821         lua_settable(L, -3);
6822
6823         return true;
6824 }
6825
6826 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6827                 const std::string &staticdata, u32 dtime_s)
6828 {
6829         realitycheck(L);
6830         assert(lua_checkstack(L, 20));
6831         verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6832         StackUnroller stack_unroller(L);
6833
6834         // Get minetest.luaentities[id]
6835         luaentity_get(L, id);
6836         int object = lua_gettop(L);
6837
6838         // Get on_activate function
6839         lua_pushvalue(L, object);
6840         lua_getfield(L, -1, "on_activate");
6841         if(!lua_isnil(L, -1)){
6842                 luaL_checktype(L, -1, LUA_TFUNCTION);
6843                 lua_pushvalue(L, object); // self
6844                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6845                 lua_pushinteger(L, dtime_s);
6846                 // Call with 3 arguments, 0 results
6847                 if(lua_pcall(L, 3, 0, 0))
6848                         script_error(L, "error running function on_activate: %s\n",
6849                                         lua_tostring(L, -1));
6850         }
6851 }
6852
6853 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6854 {
6855         realitycheck(L);
6856         assert(lua_checkstack(L, 20));
6857         verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6858
6859         // Get minetest.luaentities table
6860         lua_getglobal(L, "minetest");
6861         lua_getfield(L, -1, "luaentities");
6862         luaL_checktype(L, -1, LUA_TTABLE);
6863         int objectstable = lua_gettop(L);
6864
6865         // Set luaentities[id] = nil
6866         lua_pushnumber(L, id); // Push id
6867         lua_pushnil(L);
6868         lua_settable(L, objectstable);
6869
6870         lua_pop(L, 2); // pop luaentities, minetest
6871 }
6872
6873 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6874 {
6875         realitycheck(L);
6876         assert(lua_checkstack(L, 20));
6877         //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6878         StackUnroller stack_unroller(L);
6879
6880         // Get minetest.luaentities[id]
6881         luaentity_get(L, id);
6882         int object = lua_gettop(L);
6883
6884         // Get get_staticdata function
6885         lua_pushvalue(L, object);
6886         lua_getfield(L, -1, "get_staticdata");
6887         if(lua_isnil(L, -1))
6888                 return "";
6889
6890         luaL_checktype(L, -1, LUA_TFUNCTION);
6891         lua_pushvalue(L, object); // self
6892         // Call with 1 arguments, 1 results
6893         if(lua_pcall(L, 1, 1, 0))
6894                 script_error(L, "error running function get_staticdata: %s\n",
6895                                 lua_tostring(L, -1));
6896
6897         size_t len=0;
6898         const char *s = lua_tolstring(L, -1, &len);
6899         return std::string(s, len);
6900 }
6901
6902 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6903                 ObjectProperties *prop)
6904 {
6905         realitycheck(L);
6906         assert(lua_checkstack(L, 20));
6907         //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6908         StackUnroller stack_unroller(L);
6909
6910         // Get minetest.luaentities[id]
6911         luaentity_get(L, id);
6912         //int object = lua_gettop(L);
6913
6914         // Set default values that differ from ObjectProperties defaults
6915         prop->hp_max = 10;
6916
6917         /* Read stuff */
6918
6919         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6920
6921         getboolfield(L, -1, "physical", prop->physical);
6922
6923         getfloatfield(L, -1, "weight", prop->weight);
6924
6925         lua_getfield(L, -1, "collisionbox");
6926         if(lua_istable(L, -1))
6927                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6928         lua_pop(L, 1);
6929
6930         getstringfield(L, -1, "visual", prop->visual);
6931
6932         getstringfield(L, -1, "mesh", prop->mesh);
6933
6934         // Deprecated: read object properties directly
6935         read_object_properties(L, -1, prop);
6936
6937         // Read initial_properties
6938         lua_getfield(L, -1, "initial_properties");
6939         read_object_properties(L, -1, prop);
6940         lua_pop(L, 1);
6941 }
6942
6943 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6944 {
6945         realitycheck(L);
6946         assert(lua_checkstack(L, 20));
6947         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6948         StackUnroller stack_unroller(L);
6949
6950         // Get minetest.luaentities[id]
6951         luaentity_get(L, id);
6952         int object = lua_gettop(L);
6953         // State: object is at top of stack
6954         // Get step function
6955         lua_getfield(L, -1, "on_step");
6956         if(lua_isnil(L, -1))
6957                 return;
6958         luaL_checktype(L, -1, LUA_TFUNCTION);
6959         lua_pushvalue(L, object); // self
6960         lua_pushnumber(L, dtime); // dtime
6961         // Call with 2 arguments, 0 results
6962         if(lua_pcall(L, 2, 0, 0))
6963                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6964 }
6965
6966 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6967 //                       tool_capabilities, direction)
6968 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6969                 ServerActiveObject *puncher, float time_from_last_punch,
6970                 const ToolCapabilities *toolcap, v3f dir)
6971 {
6972         realitycheck(L);
6973         assert(lua_checkstack(L, 20));
6974         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6975         StackUnroller stack_unroller(L);
6976
6977         // Get minetest.luaentities[id]
6978         luaentity_get(L, id);
6979         int object = lua_gettop(L);
6980         // State: object is at top of stack
6981         // Get function
6982         lua_getfield(L, -1, "on_punch");
6983         if(lua_isnil(L, -1))
6984                 return;
6985         luaL_checktype(L, -1, LUA_TFUNCTION);
6986         lua_pushvalue(L, object); // self
6987         objectref_get_or_create(L, puncher); // Clicker reference
6988         lua_pushnumber(L, time_from_last_punch);
6989         push_tool_capabilities(L, *toolcap);
6990         push_v3f(L, dir);
6991         // Call with 5 arguments, 0 results
6992         if(lua_pcall(L, 5, 0, 0))
6993                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6994 }
6995
6996 // Calls entity:on_rightclick(ObjectRef clicker)
6997 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6998                 ServerActiveObject *clicker)
6999 {
7000         realitycheck(L);
7001         assert(lua_checkstack(L, 20));
7002         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7003         StackUnroller stack_unroller(L);
7004
7005         // Get minetest.luaentities[id]
7006         luaentity_get(L, id);
7007         int object = lua_gettop(L);
7008         // State: object is at top of stack
7009         // Get function
7010         lua_getfield(L, -1, "on_rightclick");
7011         if(lua_isnil(L, -1))
7012                 return;
7013         luaL_checktype(L, -1, LUA_TFUNCTION);
7014         lua_pushvalue(L, object); // self
7015         objectref_get_or_create(L, clicker); // Clicker reference
7016         // Call with 2 arguments, 0 results
7017         if(lua_pcall(L, 2, 0, 0))
7018                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
7019 }
7020