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