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