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