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