]> git.lizzy.rs Git - minetest-m13.git/blob - src/scriptapi.cpp
5d68793e248a619ab8802cc024860f19b0161c54
[minetest-m13.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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "luna.h"
37 #include "luaentity_common.h"
38 #include "content_sao.h" // For LuaEntitySAO
39 #include "itemdef.h"
40 #include "nodedef.h"
41 #include "craftdef.h"
42 #include "main.h" // For g_settings
43 #include "settings.h" // For accessing g_settings
44 #include "nodemetadata.h"
45 #include "mapblock.h" // For getNodeBlockPos
46 #include "content_nodemeta.h"
47 #include "utility.h"
48
49 static void stackDump(lua_State *L, std::ostream &o)
50 {
51   int i;
52   int top = lua_gettop(L);
53   for (i = 1; i <= top; i++) {  /* repeat for each level */
54         int t = lua_type(L, i);
55         switch (t) {
56
57           case LUA_TSTRING:  /* strings */
58                 o<<"\""<<lua_tostring(L, i)<<"\"";
59                 break;
60
61           case LUA_TBOOLEAN:  /* booleans */
62                 o<<(lua_toboolean(L, i) ? "true" : "false");
63                 break;
64
65           case LUA_TNUMBER:  /* numbers */ {
66                 char buf[10];
67                 snprintf(buf, 10, "%g", lua_tonumber(L, i));
68                 o<<buf;
69                 break; }
70
71           default:  /* other values */
72                 o<<lua_typename(L, t);
73                 break;
74
75         }
76         o<<" ";
77   }
78   o<<std::endl;
79 }
80
81 static void realitycheck(lua_State *L)
82 {
83         int top = lua_gettop(L);
84         if(top >= 30){
85                 dstream<<"Stack is over 30:"<<std::endl;
86                 stackDump(L, dstream);
87                 script_error(L, "Stack is over 30 (reality check)");
88         }
89 }
90
91 class StackUnroller
92 {
93 private:
94         lua_State *m_lua;
95         int m_original_top;
96 public:
97         StackUnroller(lua_State *L):
98                 m_lua(L),
99                 m_original_top(-1)
100         {
101                 m_original_top = lua_gettop(m_lua); // store stack height
102         }
103         ~StackUnroller()
104         {
105                 lua_settop(m_lua, m_original_top); // restore stack height
106         }
107 };
108
109 class ModNameStorer
110 {
111 private:
112         lua_State *L;
113 public:
114         ModNameStorer(lua_State *L_, const std::string modname):
115                 L(L_)
116         {
117                 // Store current modname in registry
118                 lua_pushstring(L, modname.c_str());
119                 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
120         }
121         ~ModNameStorer()
122         {
123                 // Clear current modname in registry
124                 lua_pushnil(L);
125                 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
126         }
127 };
128
129 /*
130         Getters for stuff in main tables
131 */
132
133 static Server* get_server(lua_State *L)
134 {
135         // Get server from registry
136         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
137         Server *server = (Server*)lua_touserdata(L, -1);
138         lua_pop(L, 1);
139         return server;
140 }
141
142 static ServerEnvironment* get_env(lua_State *L)
143 {
144         // Get environment from registry
145         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
146         ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
147         lua_pop(L, 1);
148         return env;
149 }
150
151 static void objectref_get(lua_State *L, u16 id)
152 {
153         // Get minetest.object_refs[i]
154         lua_getglobal(L, "minetest");
155         lua_getfield(L, -1, "object_refs");
156         luaL_checktype(L, -1, LUA_TTABLE);
157         lua_pushnumber(L, id);
158         lua_gettable(L, -2);
159         lua_remove(L, -2); // object_refs
160         lua_remove(L, -2); // minetest
161 }
162
163 static void luaentity_get(lua_State *L, u16 id)
164 {
165         // Get minetest.luaentities[i]
166         lua_getglobal(L, "minetest");
167         lua_getfield(L, -1, "luaentities");
168         luaL_checktype(L, -1, LUA_TTABLE);
169         lua_pushnumber(L, id);
170         lua_gettable(L, -2);
171         lua_remove(L, -2); // luaentities
172         lua_remove(L, -2); // minetest
173 }
174
175 /*
176         Table field getters
177 */
178
179 static bool getstringfield(lua_State *L, int table,
180                 const char *fieldname, std::string &result)
181 {
182         lua_getfield(L, table, fieldname);
183         bool got = false;
184         if(lua_isstring(L, -1)){
185                 size_t len = 0;
186                 const char *ptr = lua_tolstring(L, -1, &len);
187                 result.assign(ptr, len);
188                 got = true;
189         }
190         lua_pop(L, 1);
191         return got;
192 }
193
194 static bool getintfield(lua_State *L, int table,
195                 const char *fieldname, int &result)
196 {
197         lua_getfield(L, table, fieldname);
198         bool got = false;
199         if(lua_isnumber(L, -1)){
200                 result = lua_tonumber(L, -1);
201                 got = true;
202         }
203         lua_pop(L, 1);
204         return got;
205 }
206
207 static bool getfloatfield(lua_State *L, int table,
208                 const char *fieldname, float &result)
209 {
210         lua_getfield(L, table, fieldname);
211         bool got = false;
212         if(lua_isnumber(L, -1)){
213                 result = lua_tonumber(L, -1);
214                 got = true;
215         }
216         lua_pop(L, 1);
217         return got;
218 }
219
220 static bool getboolfield(lua_State *L, int table,
221                 const char *fieldname, bool &result)
222 {
223         lua_getfield(L, table, fieldname);
224         bool got = false;
225         if(lua_isboolean(L, -1)){
226                 result = lua_toboolean(L, -1);
227                 got = true;
228         }
229         lua_pop(L, 1);
230         return got;
231 }
232
233 static std::string checkstringfield(lua_State *L, int table,
234                 const char *fieldname)
235 {
236         lua_getfield(L, table, fieldname);
237         std::string s = luaL_checkstring(L, -1);
238         lua_pop(L, 1);
239         return s;
240 }
241
242 static std::string getstringfield_default(lua_State *L, int table,
243                 const char *fieldname, const std::string &default_)
244 {
245         std::string result = default_;
246         getstringfield(L, table, fieldname, result);
247         return result;
248 }
249
250 static int getintfield_default(lua_State *L, int table,
251                 const char *fieldname, int default_)
252 {
253         int result = default_;
254         getintfield(L, table, fieldname, result);
255         return result;
256 }
257
258 static float getfloatfield_default(lua_State *L, int table,
259                 const char *fieldname, float default_)
260 {
261         float result = default_;
262         getfloatfield(L, table, fieldname, result);
263         return result;
264 }
265
266 static bool getboolfield_default(lua_State *L, int table,
267                 const char *fieldname, bool default_)
268 {
269         bool result = default_;
270         getboolfield(L, table, fieldname, result);
271         return result;
272 }
273
274 struct EnumString
275 {
276         int num;
277         const char *str;
278 };
279
280 static bool string_to_enum(const EnumString *spec, int &result,
281                 const std::string &str)
282 {
283         const EnumString *esp = spec;
284         while(esp->str){
285                 if(str == std::string(esp->str)){
286                         result = esp->num;
287                         return true;
288                 }
289                 esp++;
290         }
291         return false;
292 }
293
294 /*static bool enum_to_string(const EnumString *spec, std::string &result,
295                 int num)
296 {
297         const EnumString *esp = spec;
298         while(esp){
299                 if(num == esp->num){
300                         result = esp->str;
301                         return true;
302                 }
303                 esp++;
304         }
305         return false;
306 }*/
307
308 static int getenumfield(lua_State *L, int table,
309                 const char *fieldname, const EnumString *spec, int default_)
310 {
311         int result = default_;
312         string_to_enum(spec, result,
313                         getstringfield_default(L, table, fieldname, ""));
314         return result;
315 }
316
317 static void setintfield(lua_State *L, int table,
318                 const char *fieldname, int value)
319 {
320         lua_pushinteger(L, value);
321         if(table < 0)
322                 table -= 1;
323         lua_setfield(L, table, fieldname);
324 }
325
326 static void setfloatfield(lua_State *L, int table,
327                 const char *fieldname, float value)
328 {
329         lua_pushnumber(L, value);
330         if(table < 0)
331                 table -= 1;
332         lua_setfield(L, table, fieldname);
333 }
334
335 static void setboolfield(lua_State *L, int table,
336                 const char *fieldname, bool value)
337 {
338         lua_pushboolean(L, value);
339         if(table < 0)
340                 table -= 1;
341         lua_setfield(L, table, fieldname);
342 }
343
344 static void warn_if_field_exists(lua_State *L, int table,
345                 const char *fieldname, const std::string &message)
346 {
347         lua_getfield(L, table, fieldname);
348         if(!lua_isnil(L, -1)){
349                 infostream<<script_get_backtrace(L)<<std::endl;
350                 infostream<<"WARNING: field \""<<fieldname<<"\": "
351                                 <<message<<std::endl;
352         }
353         lua_pop(L, 1);
354 }
355
356 /*
357         EnumString definitions
358 */
359
360 struct EnumString es_ItemType[] =
361 {
362         {ITEM_NONE, "none"},
363         {ITEM_NODE, "node"},
364         {ITEM_CRAFT, "craft"},
365         {ITEM_TOOL, "tool"},
366         {0, NULL},
367 };
368
369 struct EnumString es_DrawType[] =
370 {
371         {NDT_NORMAL, "normal"},
372         {NDT_AIRLIKE, "airlike"},
373         {NDT_LIQUID, "liquid"},
374         {NDT_FLOWINGLIQUID, "flowingliquid"},
375         {NDT_GLASSLIKE, "glasslike"},
376         {NDT_ALLFACES, "allfaces"},
377         {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
378         {NDT_TORCHLIKE, "torchlike"},
379         {NDT_SIGNLIKE, "signlike"},
380         {NDT_PLANTLIKE, "plantlike"},
381         {NDT_FENCELIKE, "fencelike"},
382         {NDT_RAILLIKE, "raillike"},
383         {0, NULL},
384 };
385
386 struct EnumString es_ContentParamType[] =
387 {
388         {CPT_NONE, "none"},
389         {CPT_LIGHT, "light"},
390         {0, NULL},
391 };
392
393 struct EnumString es_ContentParamType2[] =
394 {
395         {CPT2_NONE, "none"},
396         {CPT2_FULL, "full"},
397         {CPT2_FLOWINGLIQUID, "flowingliquid"},
398         {CPT2_FACEDIR, "facedir"},
399         {CPT2_WALLMOUNTED, "wallmounted"},
400         {0, NULL},
401 };
402
403 struct EnumString es_LiquidType[] =
404 {
405         {LIQUID_NONE, "none"},
406         {LIQUID_FLOWING, "flowing"},
407         {LIQUID_SOURCE, "source"},
408         {0, NULL},
409 };
410
411 struct EnumString es_NodeBoxType[] =
412 {
413         {NODEBOX_REGULAR, "regular"},
414         {NODEBOX_FIXED, "fixed"},
415         {NODEBOX_WALLMOUNTED, "wallmounted"},
416         {0, NULL},
417 };
418
419 struct EnumString es_Diggability[] =
420 {
421         {DIGGABLE_NOT, "not"},
422         {DIGGABLE_NORMAL, "normal"},
423         {DIGGABLE_CONSTANT, "constant"},
424         {0, NULL},
425 };
426
427 /*
428         C struct <-> Lua table converter functions
429 */
430
431 static void push_v3f(lua_State *L, v3f p)
432 {
433         lua_newtable(L);
434         lua_pushnumber(L, p.X);
435         lua_setfield(L, -2, "x");
436         lua_pushnumber(L, p.Y);
437         lua_setfield(L, -2, "y");
438         lua_pushnumber(L, p.Z);
439         lua_setfield(L, -2, "z");
440 }
441
442 static v2s16 read_v2s16(lua_State *L, int index)
443 {
444         v2s16 p;
445         luaL_checktype(L, index, LUA_TTABLE);
446         lua_getfield(L, index, "x");
447         p.X = lua_tonumber(L, -1);
448         lua_pop(L, 1);
449         lua_getfield(L, index, "y");
450         p.Y = lua_tonumber(L, -1);
451         lua_pop(L, 1);
452         return p;
453 }
454
455 static v2f read_v2f(lua_State *L, int index)
456 {
457         v2f p;
458         luaL_checktype(L, index, LUA_TTABLE);
459         lua_getfield(L, index, "x");
460         p.X = lua_tonumber(L, -1);
461         lua_pop(L, 1);
462         lua_getfield(L, index, "y");
463         p.Y = lua_tonumber(L, -1);
464         lua_pop(L, 1);
465         return p;
466 }
467
468 static v3f read_v3f(lua_State *L, int index)
469 {
470         v3f pos;
471         luaL_checktype(L, index, LUA_TTABLE);
472         lua_getfield(L, index, "x");
473         pos.X = lua_tonumber(L, -1);
474         lua_pop(L, 1);
475         lua_getfield(L, index, "y");
476         pos.Y = lua_tonumber(L, -1);
477         lua_pop(L, 1);
478         lua_getfield(L, index, "z");
479         pos.Z = lua_tonumber(L, -1);
480         lua_pop(L, 1);
481         return pos;
482 }
483
484 static v3f check_v3f(lua_State *L, int index)
485 {
486         v3f pos;
487         luaL_checktype(L, index, LUA_TTABLE);
488         lua_getfield(L, index, "x");
489         pos.X = luaL_checknumber(L, -1);
490         lua_pop(L, 1);
491         lua_getfield(L, index, "y");
492         pos.Y = luaL_checknumber(L, -1);
493         lua_pop(L, 1);
494         lua_getfield(L, index, "z");
495         pos.Z = luaL_checknumber(L, -1);
496         lua_pop(L, 1);
497         return pos;
498 }
499
500 static void pushFloatPos(lua_State *L, v3f p)
501 {
502         p /= BS;
503         push_v3f(L, p);
504 }
505
506 static v3f checkFloatPos(lua_State *L, int index)
507 {
508         return check_v3f(L, index) * BS;
509 }
510
511 static void push_v3s16(lua_State *L, v3s16 p)
512 {
513         lua_newtable(L);
514         lua_pushnumber(L, p.X);
515         lua_setfield(L, -2, "x");
516         lua_pushnumber(L, p.Y);
517         lua_setfield(L, -2, "y");
518         lua_pushnumber(L, p.Z);
519         lua_setfield(L, -2, "z");
520 }
521
522 static v3s16 read_v3s16(lua_State *L, int index)
523 {
524         // Correct rounding at <0
525         v3f pf = read_v3f(L, index);
526         return floatToInt(pf, 1.0);
527 }
528
529 static v3s16 check_v3s16(lua_State *L, int index)
530 {
531         // Correct rounding at <0
532         v3f pf = check_v3f(L, index);
533         return floatToInt(pf, 1.0);
534 }
535
536 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
537 {
538         lua_newtable(L);
539         lua_pushstring(L, ndef->get(n).name.c_str());
540         lua_setfield(L, -2, "name");
541         lua_pushnumber(L, n.getParam1());
542         lua_setfield(L, -2, "param1");
543         lua_pushnumber(L, n.getParam2());
544         lua_setfield(L, -2, "param2");
545 }
546
547 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
548 {
549         lua_getfield(L, index, "name");
550         const char *name = luaL_checkstring(L, -1);
551         lua_pop(L, 1);
552         u8 param1;
553         lua_getfield(L, index, "param1");
554         if(lua_isnil(L, -1))
555                 param1 = 0;
556         else
557                 param1 = lua_tonumber(L, -1);
558         lua_pop(L, 1);
559         u8 param2;
560         lua_getfield(L, index, "param2");
561         if(lua_isnil(L, -1))
562                 param2 = 0;
563         else
564                 param2 = lua_tonumber(L, -1);
565         lua_pop(L, 1);
566         return MapNode(ndef, name, param1, param2);
567 }
568
569 static video::SColor readARGB8(lua_State *L, int index)
570 {
571         video::SColor color;
572         luaL_checktype(L, index, LUA_TTABLE);
573         lua_getfield(L, index, "a");
574         if(lua_isnumber(L, -1))
575                 color.setAlpha(lua_tonumber(L, -1));
576         lua_pop(L, 1);
577         lua_getfield(L, index, "r");
578         color.setRed(lua_tonumber(L, -1));
579         lua_pop(L, 1);
580         lua_getfield(L, index, "g");
581         color.setGreen(lua_tonumber(L, -1));
582         lua_pop(L, 1);
583         lua_getfield(L, index, "b");
584         color.setBlue(lua_tonumber(L, -1));
585         lua_pop(L, 1);
586         return color;
587 }
588
589 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
590 {
591         core::aabbox3d<f32> box;
592         if(lua_istable(L, -1)){
593                 lua_rawgeti(L, -1, 1);
594                 box.MinEdge.X = lua_tonumber(L, -1) * scale;
595                 lua_pop(L, 1);
596                 lua_rawgeti(L, -1, 2);
597                 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
598                 lua_pop(L, 1);
599                 lua_rawgeti(L, -1, 3);
600                 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
601                 lua_pop(L, 1);
602                 lua_rawgeti(L, -1, 4);
603                 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
604                 lua_pop(L, 1);
605                 lua_rawgeti(L, -1, 5);
606                 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
607                 lua_pop(L, 1);
608                 lua_rawgeti(L, -1, 6);
609                 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
610                 lua_pop(L, 1);
611         }
612         return box;
613 }
614
615 /*
616         MaterialProperties
617 */
618
619 static MaterialProperties read_material_properties(
620                 lua_State *L, int table)
621 {
622         MaterialProperties prop;
623         prop.diggability = (Diggability)getenumfield(L, -1, "diggability",
624                         es_Diggability, DIGGABLE_NORMAL);
625         getfloatfield(L, -1, "constant_time", prop.constant_time);
626         getfloatfield(L, -1, "weight", prop.weight);
627         getfloatfield(L, -1, "crackiness", prop.crackiness);
628         getfloatfield(L, -1, "crumbliness", prop.crumbliness);
629         getfloatfield(L, -1, "cuttability", prop.cuttability);
630         getfloatfield(L, -1, "flammability", prop.flammability);
631         return prop;
632 }
633
634 /*
635         ToolDiggingProperties
636 */
637
638 static ToolDiggingProperties read_tool_digging_properties(
639                 lua_State *L, int table)
640 {
641         ToolDiggingProperties prop;
642         getfloatfield(L, table, "full_punch_interval", prop.full_punch_interval);
643         getfloatfield(L, table, "basetime", prop.basetime);
644         getfloatfield(L, table, "dt_weight", prop.dt_weight);
645         getfloatfield(L, table, "dt_crackiness", prop.dt_crackiness);
646         getfloatfield(L, table, "dt_crumbliness", prop.dt_crumbliness);
647         getfloatfield(L, table, "dt_cuttability", prop.dt_cuttability);
648         getfloatfield(L, table, "basedurability", prop.basedurability);
649         getfloatfield(L, table, "dd_weight", prop.dd_weight);
650         getfloatfield(L, table, "dd_crackiness", prop.dd_crackiness);
651         getfloatfield(L, table, "dd_crumbliness", prop.dd_crumbliness);
652         getfloatfield(L, table, "dd_cuttability", prop.dd_cuttability);
653         return prop;
654 }
655
656 static void set_tool_digging_properties(lua_State *L, int table,
657                 const ToolDiggingProperties &prop)
658 {
659         setfloatfield(L, table, "full_punch_interval", prop.full_punch_interval);
660         setfloatfield(L, table, "basetime", prop.basetime);
661         setfloatfield(L, table, "dt_weight", prop.dt_weight);
662         setfloatfield(L, table, "dt_crackiness", prop.dt_crackiness);
663         setfloatfield(L, table, "dt_crumbliness", prop.dt_crumbliness);
664         setfloatfield(L, table, "dt_cuttability", prop.dt_cuttability);
665         setfloatfield(L, table, "basedurability", prop.basedurability);
666         setfloatfield(L, table, "dd_weight", prop.dd_weight);
667         setfloatfield(L, table, "dd_crackiness", prop.dd_crackiness);
668         setfloatfield(L, table, "dd_crumbliness", prop.dd_crumbliness);
669         setfloatfield(L, table, "dd_cuttability", prop.dd_cuttability);
670 }
671
672 static void push_tool_digging_properties(lua_State *L,
673                 const ToolDiggingProperties &prop)
674 {
675         lua_newtable(L);
676         set_tool_digging_properties(L, -1, prop);
677 }
678
679 /*
680         DiggingProperties
681 */
682
683 static void set_digging_properties(lua_State *L, int table,
684                 const DiggingProperties &prop)
685 {
686         setboolfield(L, table, "diggable", prop.diggable);
687         setfloatfield(L, table, "time", prop.time);
688         setintfield(L, table, "wear", prop.wear);
689 }
690
691 static void push_digging_properties(lua_State *L,
692                 const DiggingProperties &prop)
693 {
694         lua_newtable(L);
695         set_digging_properties(L, -1, prop);
696 }
697
698 /*
699         HittingProperties
700 */
701
702 static void set_hitting_properties(lua_State *L, int table,
703                 const HittingProperties &prop)
704 {
705         setintfield(L, table, "hp", prop.hp);
706         setintfield(L, table, "wear", prop.wear);
707 }
708
709 static void push_hitting_properties(lua_State *L,
710                 const HittingProperties &prop)
711 {
712         lua_newtable(L);
713         set_hitting_properties(L, -1, prop);
714 }
715
716 /*
717         PointedThing
718 */
719
720 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
721 {
722         lua_newtable(L);
723         if(pointed.type == POINTEDTHING_NODE)
724         {
725                 lua_pushstring(L, "node");
726                 lua_setfield(L, -2, "type");
727                 push_v3s16(L, pointed.node_undersurface);
728                 lua_setfield(L, -2, "under");
729                 push_v3s16(L, pointed.node_abovesurface);
730                 lua_setfield(L, -2, "above");
731         }
732         else if(pointed.type == POINTEDTHING_OBJECT)
733         {
734                 lua_pushstring(L, "object");
735                 lua_setfield(L, -2, "type");
736                 objectref_get(L, pointed.object_id);
737                 lua_setfield(L, -2, "ref");
738         }
739         else
740         {
741                 lua_pushstring(L, "nothing");
742                 lua_setfield(L, -2, "type");
743         }
744 }
745
746 /*
747         ItemDefinition
748 */
749
750 static ItemDefinition read_item_definition(lua_State *L, int index)
751 {
752         if(index < 0)
753                 index = lua_gettop(L) + 1 + index;
754
755         // Read the item definition
756         ItemDefinition def;
757
758         def.type = (ItemType)getenumfield(L, index, "type",
759                         es_ItemType, ITEM_NONE);
760         getstringfield(L, index, "name", def.name);
761         getstringfield(L, index, "description", def.description);
762         getstringfield(L, index, "inventory_image", def.inventory_image);
763         getstringfield(L, index, "wield_image", def.wield_image);
764
765         lua_getfield(L, index, "wield_scale");
766         if(lua_istable(L, -1)){
767                 def.wield_scale = check_v3f(L, -1);
768         }
769         lua_pop(L, 1);
770
771         def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
772         if(def.stack_max == 0)
773                 def.stack_max = 1;
774
775         lua_getfield(L, index, "on_use");
776         def.usable = lua_isfunction(L, -1);
777         lua_pop(L, 1);
778
779         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
780
781         lua_getfield(L, index, "tool_digging_properties");
782         if(lua_istable(L, -1)){
783                 def.tool_digging_properties = new ToolDiggingProperties(
784                                 read_tool_digging_properties(L, -1));
785         }
786         lua_pop(L, 1);
787
788         // If name is "" (hand), ensure there are ToolDiggingProperties
789         // because it will be looked up there whenever any other item has
790         // no ToolDiggingProperties
791         if(def.name == "" && def.tool_digging_properties == NULL){
792                 def.tool_digging_properties = new ToolDiggingProperties();
793         }
794
795         return def;
796 }
797
798 /*
799         ContentFeatures
800 */
801
802 static ContentFeatures read_content_features(lua_State *L, int index)
803 {
804         if(index < 0)
805                 index = lua_gettop(L) + 1 + index;
806
807         ContentFeatures f;
808         getstringfield(L, index, "name", f.name);
809
810         /* Visual definition */
811
812         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
813                         NDT_NORMAL);
814         getfloatfield(L, index, "visual_scale", f.visual_scale);
815
816         lua_getfield(L, index, "tile_images");
817         if(lua_istable(L, -1)){
818                 int table = lua_gettop(L);
819                 lua_pushnil(L);
820                 int i = 0;
821                 while(lua_next(L, table) != 0){
822                         // key at index -2 and value at index -1
823                         if(lua_isstring(L, -1))
824                                 f.tname_tiles[i] = lua_tostring(L, -1);
825                         else
826                                 f.tname_tiles[i] = "";
827                         // removes value, keeps key for next iteration
828                         lua_pop(L, 1);
829                         i++;
830                         if(i==6){
831                                 lua_pop(L, 1);
832                                 break;
833                         }
834                 }
835                 // Copy last value to all remaining textures
836                 if(i >= 1){
837                         std::string lastname = f.tname_tiles[i-1];
838                         while(i < 6){
839                                 f.tname_tiles[i] = lastname;
840                                 i++;
841                         }
842                 }
843         }
844         lua_pop(L, 1);
845
846         lua_getfield(L, index, "special_materials");
847         if(lua_istable(L, -1)){
848                 int table = lua_gettop(L);
849                 lua_pushnil(L);
850                 int i = 0;
851                 while(lua_next(L, table) != 0){
852                         // key at index -2 and value at index -1
853                         int smtable = lua_gettop(L);
854                         std::string tname = getstringfield_default(
855                                         L, smtable, "image", "");
856                         bool backface_culling = getboolfield_default(
857                                         L, smtable, "backface_culling", true);
858                         MaterialSpec mspec(tname, backface_culling);
859                         f.mspec_special[i] = mspec;
860                         // removes value, keeps key for next iteration
861                         lua_pop(L, 1);
862                         i++;
863                         if(i==6){
864                                 lua_pop(L, 1);
865                                 break;
866                         }
867                 }
868         }
869         lua_pop(L, 1);
870
871         f.alpha = getintfield_default(L, index, "alpha", 255);
872
873         /* Other stuff */
874         
875         lua_getfield(L, index, "post_effect_color");
876         if(!lua_isnil(L, -1))
877                 f.post_effect_color = readARGB8(L, -1);
878         lua_pop(L, 1);
879
880         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
881                         es_ContentParamType, CPT_NONE);
882         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
883                         es_ContentParamType2, CPT2_NONE);
884
885         // Warn about some deprecated fields
886         warn_if_field_exists(L, index, "wall_mounted",
887                         "deprecated: use paramtype2 = 'wallmounted'");
888         warn_if_field_exists(L, index, "light_propagates",
889                         "deprecated: determined from paramtype");
890         warn_if_field_exists(L, index, "dug_item",
891                         "deprecated: use 'drop' field");
892         warn_if_field_exists(L, index, "extra_dug_item",
893                         "deprecated: use 'drop' field");
894         warn_if_field_exists(L, index, "extra_dug_item_rarity",
895                         "deprecated: use 'drop' field");
896         
897         // True for all ground-like things like stone and mud, false for eg. trees
898         getboolfield(L, index, "is_ground_content", f.is_ground_content);
899         f.light_propagates = (f.param_type == CPT_LIGHT);
900         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
901         // This is used for collision detection.
902         // Also for general solidness queries.
903         getboolfield(L, index, "walkable", f.walkable);
904         // Player can point to these
905         getboolfield(L, index, "pointable", f.pointable);
906         // Player can dig these
907         getboolfield(L, index, "diggable", f.diggable);
908         // Player can climb these
909         getboolfield(L, index, "climbable", f.climbable);
910         // Player can build on these
911         getboolfield(L, index, "buildable_to", f.buildable_to);
912         // Metadata name of node (eg. "furnace")
913         getstringfield(L, index, "metadata_name", f.metadata_name);
914         // Whether the node is non-liquid, source liquid or flowing liquid
915         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
916                         es_LiquidType, LIQUID_NONE);
917         // If the content is liquid, this is the flowing version of the liquid.
918         getstringfield(L, index, "liquid_alternative_flowing",
919                         f.liquid_alternative_flowing);
920         // If the content is liquid, this is the source version of the liquid.
921         getstringfield(L, index, "liquid_alternative_source",
922                         f.liquid_alternative_source);
923         // Viscosity for fluid flow, ranging from 1 to 7, with
924         // 1 giving almost instantaneous propagation and 7 being
925         // the slowest possible
926         f.liquid_viscosity = getintfield_default(L, index,
927                         "liquid_viscosity", f.liquid_viscosity);
928         // Amount of light the node emits
929         f.light_source = getintfield_default(L, index,
930                         "light_source", f.light_source);
931         f.damage_per_second = getintfield_default(L, index,
932                         "damage_per_second", f.damage_per_second);
933         
934         lua_getfield(L, index, "selection_box");
935         if(lua_istable(L, -1)){
936                 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
937                                 es_NodeBoxType, NODEBOX_REGULAR);
938
939                 lua_getfield(L, -1, "fixed");
940                 if(lua_istable(L, -1))
941                         f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
942                 lua_pop(L, 1);
943
944                 lua_getfield(L, -1, "wall_top");
945                 if(lua_istable(L, -1))
946                         f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
947                 lua_pop(L, 1);
948
949                 lua_getfield(L, -1, "wall_bottom");
950                 if(lua_istable(L, -1))
951                         f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
952                 lua_pop(L, 1);
953
954                 lua_getfield(L, -1, "wall_side");
955                 if(lua_istable(L, -1))
956                         f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
957                 lua_pop(L, 1);
958         }
959         lua_pop(L, 1);
960
961         lua_getfield(L, index, "material");
962         if(lua_istable(L, -1)){
963                 f.material = read_material_properties(L, -1);
964         }
965         lua_pop(L, 1);
966
967         // Set to true if paramtype used to be 'facedir_simple'
968         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
969         // Set to true if wall_mounted used to be set to true
970         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
971
972         return f;
973 }
974
975 /*
976         Inventory stuff
977 */
978
979 static ItemStack read_item(lua_State *L, int index);
980
981 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
982                 lua_State *L, int tableindex, int forcesize=-1)
983 {
984         dstream<<"inventory_set_list_from_lua\n";
985         if(tableindex < 0)
986                 tableindex = lua_gettop(L) + 1 + tableindex;
987         // If nil, delete list
988         if(lua_isnil(L, tableindex)){
989                 inv->deleteList(name);
990                 return;
991         }
992         // Otherwise set list
993         std::vector<ItemStack> items;
994         luaL_checktype(L, tableindex, LUA_TTABLE);
995         lua_pushnil(L);
996         while(lua_next(L, tableindex) != 0){
997                 // key at index -2 and value at index -1
998                 items.push_back(read_item(L, -1));
999                 // removes value, keeps key for next iteration
1000                 lua_pop(L, 1);
1001         }
1002         int listsize = (forcesize != -1) ? forcesize : items.size();
1003         InventoryList *invlist = inv->addList(name, listsize);
1004         int index = 0;
1005         for(std::vector<ItemStack>::const_iterator
1006                         i = items.begin(); i != items.end(); i++){
1007                 if(forcesize != -1 && index == forcesize)
1008                         break;
1009                 invlist->changeItem(index, *i);
1010                 index++;
1011         }
1012         while(forcesize != -1 && index < forcesize){
1013                 invlist->deleteItem(index);
1014                 index++;
1015         }
1016         dstream<<"inventory_set_list_from_lua done\n";
1017 }
1018
1019 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1020                 lua_State *L)
1021 {
1022         InventoryList *invlist = inv->getList(name);
1023         if(invlist == NULL){
1024                 lua_pushnil(L);
1025                 return;
1026         }
1027         // Get the table insert function
1028         lua_getglobal(L, "table");
1029         lua_getfield(L, -1, "insert");
1030         int table_insert = lua_gettop(L);
1031         // Create and fill table
1032         lua_newtable(L);
1033         int table = lua_gettop(L);
1034         for(u32 i=0; i<invlist->getSize(); i++){
1035                 ItemStack item = invlist->getItem(i);
1036                 lua_pushvalue(L, table_insert);
1037                 lua_pushvalue(L, table);
1038                 lua_pushstring(L, item.getItemString().c_str());
1039                 if(lua_pcall(L, 2, 0, 0))
1040                         script_error(L, "error: %s", lua_tostring(L, -1));
1041         }
1042 }
1043
1044 /*
1045         Helpful macros for userdata classes
1046 */
1047
1048 #define method(class, name) {#name, class::l_##name}
1049
1050 /*
1051         LuaItemStack
1052 */
1053
1054 class LuaItemStack
1055 {
1056 private:
1057         ItemStack m_stack;
1058
1059         static const char className[];
1060         static const luaL_reg methods[];
1061
1062         // Exported functions
1063         
1064         // garbage collector
1065         static int gc_object(lua_State *L)
1066         {
1067                 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1068                 delete o;
1069                 return 0;
1070         }
1071
1072         // is_empty(self) -> true/false
1073         static int l_is_empty(lua_State *L)
1074         {
1075                 LuaItemStack *o = checkobject(L, 1);
1076                 ItemStack &item = o->m_stack;
1077                 lua_pushboolean(L, item.empty());
1078                 return 1;
1079         }
1080
1081         // get_name(self) -> string
1082         static int l_get_name(lua_State *L)
1083         {
1084                 LuaItemStack *o = checkobject(L, 1);
1085                 ItemStack &item = o->m_stack;
1086                 lua_pushstring(L, item.name.c_str());
1087                 return 1;
1088         }
1089
1090         // get_count(self) -> number
1091         static int l_get_count(lua_State *L)
1092         {
1093                 LuaItemStack *o = checkobject(L, 1);
1094                 ItemStack &item = o->m_stack;
1095                 lua_pushinteger(L, item.count);
1096                 return 1;
1097         }
1098
1099         // get_wear(self) -> number
1100         static int l_get_wear(lua_State *L)
1101         {
1102                 LuaItemStack *o = checkobject(L, 1);
1103                 ItemStack &item = o->m_stack;
1104                 lua_pushinteger(L, item.wear);
1105                 return 1;
1106         }
1107
1108         // get_metadata(self) -> string
1109         static int l_get_metadata(lua_State *L)
1110         {
1111                 LuaItemStack *o = checkobject(L, 1);
1112                 ItemStack &item = o->m_stack;
1113                 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1114                 return 1;
1115         }
1116
1117         // clear(self) -> true
1118         static int l_clear(lua_State *L)
1119         {
1120                 LuaItemStack *o = checkobject(L, 1);
1121                 o->m_stack.clear();
1122                 lua_pushboolean(L, true);
1123                 return 1;
1124         }
1125
1126         // replace(self, itemstack or itemstring or table or nil) -> true
1127         static int l_replace(lua_State *L)
1128         {
1129                 LuaItemStack *o = checkobject(L, 1);
1130                 o->m_stack = read_item(L, 2);
1131                 lua_pushboolean(L, true);
1132                 return 1;
1133         }
1134
1135         // to_string(self) -> string
1136         static int l_to_string(lua_State *L)
1137         {
1138                 LuaItemStack *o = checkobject(L, 1);
1139                 std::string itemstring = o->m_stack.getItemString();
1140                 lua_pushstring(L, itemstring.c_str());
1141                 return 1;
1142         }
1143
1144         // to_table(self) -> table or nil
1145         static int l_to_table(lua_State *L)
1146         {
1147                 LuaItemStack *o = checkobject(L, 1);
1148                 const ItemStack &item = o->m_stack;
1149                 if(item.empty())
1150                 {
1151                         lua_pushnil(L);
1152                 }
1153                 else
1154                 {
1155                         lua_newtable(L);
1156                         lua_pushstring(L, item.name.c_str());
1157                         lua_setfield(L, -2, "name");
1158                         lua_pushinteger(L, item.count);
1159                         lua_setfield(L, -2, "count");
1160                         lua_pushinteger(L, item.wear);
1161                         lua_setfield(L, -2, "wear");
1162                         lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1163                         lua_setfield(L, -2, "metadata");
1164                 }
1165                 return 1;
1166         }
1167
1168         // get_stack_max(self) -> number
1169         static int l_get_stack_max(lua_State *L)
1170         {
1171                 LuaItemStack *o = checkobject(L, 1);
1172                 ItemStack &item = o->m_stack;
1173                 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1174                 return 1;
1175         }
1176
1177         // get_free_space(self) -> number
1178         static int l_get_free_space(lua_State *L)
1179         {
1180                 LuaItemStack *o = checkobject(L, 1);
1181                 ItemStack &item = o->m_stack;
1182                 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1183                 return 1;
1184         }
1185
1186         // is_known(self) -> true/false
1187         // Checks if the item is defined.
1188         static int l_is_known(lua_State *L)
1189         {
1190                 LuaItemStack *o = checkobject(L, 1);
1191                 ItemStack &item = o->m_stack;
1192                 bool is_known = item.isKnown(get_server(L)->idef());
1193                 lua_pushboolean(L, is_known);
1194                 return 1;
1195         }
1196
1197         // get_definition(self) -> table
1198         // Returns the item definition table from minetest.registered_items,
1199         // or a fallback one (name="unknown")
1200         static int l_get_definition(lua_State *L)
1201         {
1202                 LuaItemStack *o = checkobject(L, 1);
1203                 ItemStack &item = o->m_stack;
1204
1205                 // Get minetest.registered_items[name]
1206                 lua_getglobal(L, "minetest");
1207                 lua_getfield(L, -1, "registered_items");
1208                 luaL_checktype(L, -1, LUA_TTABLE);
1209                 lua_getfield(L, -1, item.name.c_str());
1210                 if(lua_isnil(L, -1))
1211                 {
1212                         lua_pop(L, 1);
1213                         lua_getfield(L, -1, "unknown");
1214                 }
1215                 return 1;
1216         }
1217
1218         // get_tool_digging_properties(self) -> table
1219         // Returns the effective tool digging properties.
1220         // Returns those of the hand ("") if this item has none associated.
1221         static int l_get_tool_digging_properties(lua_State *L)
1222         {
1223                 LuaItemStack *o = checkobject(L, 1);
1224                 ItemStack &item = o->m_stack;
1225                 const ToolDiggingProperties &prop =
1226                         item.getToolDiggingProperties(get_server(L)->idef());
1227                 push_tool_digging_properties(L, prop);
1228                 return 1;
1229         }
1230
1231         // add_wear(self, amount) -> true/false
1232         // The range for "amount" is [0,65535]. Wear is only added if the item
1233         // is a tool. Adding wear might destroy the item.
1234         // Returns true if the item is (or was) a tool.
1235         static int l_add_wear(lua_State *L)
1236         {
1237                 LuaItemStack *o = checkobject(L, 1);
1238                 ItemStack &item = o->m_stack;
1239                 int amount = lua_tointeger(L, 2);
1240                 bool result = item.addWear(amount, get_server(L)->idef());
1241                 lua_pushboolean(L, result);
1242                 return 1;
1243         }
1244
1245         // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1246         // Returns leftover item stack
1247         static int l_add_item(lua_State *L)
1248         {
1249                 LuaItemStack *o = checkobject(L, 1);
1250                 ItemStack &item = o->m_stack;
1251                 ItemStack newitem = read_item(L, 2);
1252                 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1253                 create(L, leftover);
1254                 return 1;
1255         }
1256
1257         // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1258         // First return value is true iff the new item fits fully into the stack
1259         // Second return value is the would-be-left-over item stack
1260         static int l_item_fits(lua_State *L)
1261         {
1262                 LuaItemStack *o = checkobject(L, 1);
1263                 ItemStack &item = o->m_stack;
1264                 ItemStack newitem = read_item(L, 2);
1265                 ItemStack restitem;
1266                 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1267                 lua_pushboolean(L, fits);  // first return value
1268                 create(L, restitem);       // second return value
1269                 return 2;
1270         }
1271
1272         // take_item(self, takecount=1) -> itemstack
1273         static int l_take_item(lua_State *L)
1274         {
1275                 LuaItemStack *o = checkobject(L, 1);
1276                 ItemStack &item = o->m_stack;
1277                 u32 takecount = 1;
1278                 if(!lua_isnone(L, 2))
1279                         takecount = lua_tointeger(L, 2);
1280                 ItemStack taken = item.takeItem(takecount);
1281                 create(L, taken);
1282                 return 1;
1283         }
1284
1285         // peek_item(self, peekcount=1) -> itemstack
1286         static int l_peek_item(lua_State *L)
1287         {
1288                 LuaItemStack *o = checkobject(L, 1);
1289                 ItemStack &item = o->m_stack;
1290                 u32 peekcount = 1;
1291                 if(!lua_isnone(L, 2))
1292                         peekcount = lua_tointeger(L, 2);
1293                 ItemStack peekaboo = item.peekItem(peekcount);
1294                 create(L, peekaboo);
1295                 return 1;
1296         }
1297
1298 public:
1299         LuaItemStack(const ItemStack &item):
1300                 m_stack(item)
1301         {
1302         }
1303
1304         ~LuaItemStack()
1305         {
1306         }
1307
1308         const ItemStack& getItem() const
1309         {
1310                 return m_stack;
1311         }
1312         ItemStack& getItem()
1313         {
1314                 return m_stack;
1315         }
1316         
1317         // LuaItemStack(itemstack or itemstring or table or nil)
1318         // Creates an LuaItemStack and leaves it on top of stack
1319         static int create_object(lua_State *L)
1320         {
1321                 ItemStack item = read_item(L, 1);
1322                 LuaItemStack *o = new LuaItemStack(item);
1323                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1324                 luaL_getmetatable(L, className);
1325                 lua_setmetatable(L, -2);
1326                 return 1;
1327         }
1328         // Not callable from Lua
1329         static int create(lua_State *L, const ItemStack &item)
1330         {
1331                 LuaItemStack *o = new LuaItemStack(item);
1332                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1333                 luaL_getmetatable(L, className);
1334                 lua_setmetatable(L, -2);
1335                 return 1;
1336         }
1337
1338         static LuaItemStack* checkobject(lua_State *L, int narg)
1339         {
1340                 luaL_checktype(L, narg, LUA_TUSERDATA);
1341                 void *ud = luaL_checkudata(L, narg, className);
1342                 if(!ud) luaL_typerror(L, narg, className);
1343                 return *(LuaItemStack**)ud;  // unbox pointer
1344         }
1345
1346         static void Register(lua_State *L)
1347         {
1348                 lua_newtable(L);
1349                 int methodtable = lua_gettop(L);
1350                 luaL_newmetatable(L, className);
1351                 int metatable = lua_gettop(L);
1352
1353                 lua_pushliteral(L, "__metatable");
1354                 lua_pushvalue(L, methodtable);
1355                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
1356
1357                 lua_pushliteral(L, "__index");
1358                 lua_pushvalue(L, methodtable);
1359                 lua_settable(L, metatable);
1360
1361                 lua_pushliteral(L, "__gc");
1362                 lua_pushcfunction(L, gc_object);
1363                 lua_settable(L, metatable);
1364
1365                 lua_pop(L, 1);  // drop metatable
1366
1367                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
1368                 lua_pop(L, 1);  // drop methodtable
1369
1370                 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1371                 lua_register(L, className, create_object);
1372         }
1373 };
1374 const char LuaItemStack::className[] = "ItemStack";
1375 const luaL_reg LuaItemStack::methods[] = {
1376         method(LuaItemStack, is_empty),
1377         method(LuaItemStack, get_name),
1378         method(LuaItemStack, get_count),
1379         method(LuaItemStack, get_wear),
1380         method(LuaItemStack, get_metadata),
1381         method(LuaItemStack, clear),
1382         method(LuaItemStack, replace),
1383         method(LuaItemStack, to_string),
1384         method(LuaItemStack, to_table),
1385         method(LuaItemStack, get_stack_max),
1386         method(LuaItemStack, get_free_space),
1387         method(LuaItemStack, is_known),
1388         method(LuaItemStack, get_definition),
1389         method(LuaItemStack, get_tool_digging_properties),
1390         method(LuaItemStack, add_wear),
1391         method(LuaItemStack, add_item),
1392         method(LuaItemStack, item_fits),
1393         method(LuaItemStack, take_item),
1394         method(LuaItemStack, peek_item),
1395         {0,0}
1396 };
1397
1398 static ItemStack read_item(lua_State *L, int index)
1399 {
1400         if(index < 0)
1401                 index = lua_gettop(L) + 1 + index;
1402
1403         if(lua_isnil(L, index))
1404         {
1405                 return ItemStack();
1406         }
1407         else if(lua_isuserdata(L, index))
1408         {
1409                 // Convert from LuaItemStack
1410                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1411                 return o->getItem();
1412         }
1413         else if(lua_isstring(L, index))
1414         {
1415                 // Convert from itemstring
1416                 std::string itemstring = lua_tostring(L, index);
1417                 IItemDefManager *idef = get_server(L)->idef();
1418                 try
1419                 {
1420                         ItemStack item;
1421                         item.deSerialize(itemstring, idef);
1422                         return item;
1423                 }
1424                 catch(SerializationError &e)
1425                 {
1426                         infostream<<"WARNING: unable to create item from itemstring"
1427                                         <<": "<<itemstring<<std::endl;
1428                         return ItemStack();
1429                 }
1430         }
1431         else if(lua_istable(L, index))
1432         {
1433                 // Convert from table
1434                 IItemDefManager *idef = get_server(L)->idef();
1435                 std::string name = getstringfield_default(L, index, "name", "");
1436                 int count = getintfield_default(L, index, "count", 1);
1437                 int wear = getintfield_default(L, index, "wear", 0);
1438                 std::string metadata = getstringfield_default(L, index, "metadata", "");
1439                 return ItemStack(name, count, wear, metadata, idef);
1440         }
1441         else
1442         {
1443                 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1444         }
1445 }
1446
1447 /*
1448         InvRef
1449 */
1450
1451 class InvRef
1452 {
1453 private:
1454         InventoryLocation m_loc;
1455
1456         static const char className[];
1457         static const luaL_reg methods[];
1458
1459         static InvRef *checkobject(lua_State *L, int narg)
1460         {
1461                 luaL_checktype(L, narg, LUA_TUSERDATA);
1462                 void *ud = luaL_checkudata(L, narg, className);
1463                 if(!ud) luaL_typerror(L, narg, className);
1464                 return *(InvRef**)ud;  // unbox pointer
1465         }
1466         
1467         static Inventory* getinv(lua_State *L, InvRef *ref)
1468         {
1469                 return get_server(L)->getInventory(ref->m_loc);
1470         }
1471
1472         static InventoryList* getlist(lua_State *L, InvRef *ref,
1473                         const char *listname)
1474         {
1475                 Inventory *inv = getinv(L, ref);
1476                 if(!inv)
1477                         return NULL;
1478                 return inv->getList(listname);
1479         }
1480
1481         static void reportInventoryChange(lua_State *L, InvRef *ref)
1482         {
1483                 // Inform other things that the inventory has changed
1484                 get_server(L)->setInventoryModified(ref->m_loc);
1485         }
1486         
1487         // Exported functions
1488         
1489         // garbage collector
1490         static int gc_object(lua_State *L) {
1491                 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1492                 delete o;
1493                 return 0;
1494         }
1495
1496         // get_size(self, listname)
1497         static int l_get_size(lua_State *L)
1498         {
1499                 InvRef *ref = checkobject(L, 1);
1500                 const char *listname = luaL_checkstring(L, 2);
1501                 InventoryList *list = getlist(L, ref, listname);
1502                 if(list){
1503                         lua_pushinteger(L, list->getSize());
1504                 } else {
1505                         lua_pushinteger(L, 0);
1506                 }
1507                 return 1;
1508         }
1509
1510         // set_size(self, listname, size)
1511         static int l_set_size(lua_State *L)
1512         {
1513                 InvRef *ref = checkobject(L, 1);
1514                 const char *listname = luaL_checkstring(L, 2);
1515                 int newsize = luaL_checknumber(L, 3);
1516                 Inventory *inv = getinv(L, ref);
1517                 if(newsize == 0){
1518                         inv->deleteList(listname);
1519                         reportInventoryChange(L, ref);
1520                         return 0;
1521                 }
1522                 InventoryList *list = inv->getList(listname);
1523                 if(list){
1524                         list->setSize(newsize);
1525                 } else {
1526                         list = inv->addList(listname, newsize);
1527                 }
1528                 reportInventoryChange(L, ref);
1529                 return 0;
1530         }
1531
1532         // get_stack(self, listname, i) -> itemstack
1533         static int l_get_stack(lua_State *L)
1534         {
1535                 InvRef *ref = checkobject(L, 1);
1536                 const char *listname = luaL_checkstring(L, 2);
1537                 int i = luaL_checknumber(L, 3) - 1;
1538                 InventoryList *list = getlist(L, ref, listname);
1539                 ItemStack item;
1540                 if(list != NULL && i >= 0 && i < (int) list->getSize())
1541                         item = list->getItem(i);
1542                 LuaItemStack::create(L, item);
1543                 return 1;
1544         }
1545
1546         // set_stack(self, listname, i, stack) -> true/false
1547         static int l_set_stack(lua_State *L)
1548         {
1549                 InvRef *ref = checkobject(L, 1);
1550                 const char *listname = luaL_checkstring(L, 2);
1551                 int i = luaL_checknumber(L, 3) - 1;
1552                 ItemStack newitem = read_item(L, 4);
1553                 InventoryList *list = getlist(L, ref, listname);
1554                 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1555                         list->changeItem(i, newitem);
1556                         reportInventoryChange(L, ref);
1557                         lua_pushboolean(L, true);
1558                 } else {
1559                         lua_pushboolean(L, false);
1560                 }
1561                 return 1;
1562         }
1563
1564         // get_list(self, listname) -> list or nil
1565         static int l_get_list(lua_State *L)
1566         {
1567                 InvRef *ref = checkobject(L, 1);
1568                 const char *listname = luaL_checkstring(L, 2);
1569                 Inventory *inv = getinv(L, ref);
1570                 inventory_get_list_to_lua(inv, listname, L);
1571                 return 1;
1572         }
1573
1574         // set_list(self, listname, list)
1575         static int l_set_list(lua_State *L)
1576         {
1577                 InvRef *ref = checkobject(L, 1);
1578                 const char *listname = luaL_checkstring(L, 2);
1579                 Inventory *inv = getinv(L, ref);
1580                 InventoryList *list = inv->getList(listname);
1581                 if(list)
1582                         inventory_set_list_from_lua(inv, listname, L, 3,
1583                                         list->getSize());
1584                 else
1585                         inventory_set_list_from_lua(inv, listname, L, 3);
1586                 reportInventoryChange(L, ref);
1587                 return 0;
1588         }
1589
1590         // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1591         // Returns the leftover stack
1592         static int l_add_item(lua_State *L)
1593         {
1594                 InvRef *ref = checkobject(L, 1);
1595                 const char *listname = luaL_checkstring(L, 2);
1596                 ItemStack item = read_item(L, 3);
1597                 InventoryList *list = getlist(L, ref, listname);
1598                 if(list){
1599                         ItemStack leftover = list->addItem(item);
1600                         if(leftover.count != item.count)
1601                                 reportInventoryChange(L, ref);
1602                         LuaItemStack::create(L, leftover);
1603                 } else {
1604                         LuaItemStack::create(L, item);
1605                 }
1606                 return 1;
1607         }
1608
1609         // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1610         // Returns true if the item completely fits into the list
1611         static int l_room_for_item(lua_State *L)
1612         {
1613                 InvRef *ref = checkobject(L, 1);
1614                 const char *listname = luaL_checkstring(L, 2);
1615                 ItemStack item = read_item(L, 3);
1616                 InventoryList *list = getlist(L, ref, listname);
1617                 if(list){
1618                         lua_pushboolean(L, list->roomForItem(item));
1619                 } else {
1620                         lua_pushboolean(L, false);
1621                 }
1622                 return 1;
1623         }
1624
1625         // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1626         // Returns true if the list contains the given count of the given item name
1627         static int l_contains_item(lua_State *L)
1628         {
1629                 InvRef *ref = checkobject(L, 1);
1630                 const char *listname = luaL_checkstring(L, 2);
1631                 ItemStack item = read_item(L, 3);
1632                 InventoryList *list = getlist(L, ref, listname);
1633                 if(list){
1634                         lua_pushboolean(L, list->containsItem(item));
1635                 } else {
1636                         lua_pushboolean(L, false);
1637                 }
1638                 return 1;
1639         }
1640
1641         // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1642         // Returns the items that were actually removed
1643         static int l_remove_item(lua_State *L)
1644         {
1645                 InvRef *ref = checkobject(L, 1);
1646                 const char *listname = luaL_checkstring(L, 2);
1647                 ItemStack item = read_item(L, 3);
1648                 InventoryList *list = getlist(L, ref, listname);
1649                 if(list){
1650                         ItemStack removed = list->removeItem(item);
1651                         if(!removed.empty())
1652                                 reportInventoryChange(L, ref);
1653                         LuaItemStack::create(L, removed);
1654                 } else {
1655                         LuaItemStack::create(L, ItemStack());
1656                 }
1657                 return 1;
1658         }
1659
1660 public:
1661         InvRef(const InventoryLocation &loc):
1662                 m_loc(loc)
1663         {
1664         }
1665
1666         ~InvRef()
1667         {
1668         }
1669
1670         // Creates an InvRef and leaves it on top of stack
1671         // Not callable from Lua; all references are created on the C side.
1672         static void create(lua_State *L, const InventoryLocation &loc)
1673         {
1674                 InvRef *o = new InvRef(loc);
1675                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1676                 luaL_getmetatable(L, className);
1677                 lua_setmetatable(L, -2);
1678         }
1679         static void createPlayer(lua_State *L, Player *player)
1680         {
1681                 InventoryLocation loc;
1682                 loc.setPlayer(player->getName());
1683                 create(L, loc);
1684         }
1685         static void createNodeMeta(lua_State *L, v3s16 p)
1686         {
1687                 InventoryLocation loc;
1688                 loc.setNodeMeta(p);
1689                 create(L, loc);
1690         }
1691
1692         static void Register(lua_State *L)
1693         {
1694                 lua_newtable(L);
1695                 int methodtable = lua_gettop(L);
1696                 luaL_newmetatable(L, className);
1697                 int metatable = lua_gettop(L);
1698
1699                 lua_pushliteral(L, "__metatable");
1700                 lua_pushvalue(L, methodtable);
1701                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
1702
1703                 lua_pushliteral(L, "__index");
1704                 lua_pushvalue(L, methodtable);
1705                 lua_settable(L, metatable);
1706
1707                 lua_pushliteral(L, "__gc");
1708                 lua_pushcfunction(L, gc_object);
1709                 lua_settable(L, metatable);
1710
1711                 lua_pop(L, 1);  // drop metatable
1712
1713                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
1714                 lua_pop(L, 1);  // drop methodtable
1715
1716                 // Cannot be created from Lua
1717                 //lua_register(L, className, create_object);
1718         }
1719 };
1720 const char InvRef::className[] = "InvRef";
1721 const luaL_reg InvRef::methods[] = {
1722         method(InvRef, get_size),
1723         method(InvRef, set_size),
1724         method(InvRef, get_stack),
1725         method(InvRef, set_stack),
1726         method(InvRef, get_list),
1727         method(InvRef, set_list),
1728         method(InvRef, add_item),
1729         method(InvRef, room_for_item),
1730         method(InvRef, contains_item),
1731         method(InvRef, remove_item),
1732         {0,0}
1733 };
1734
1735 /*
1736         NodeMetaRef
1737 */
1738
1739 class NodeMetaRef
1740 {
1741 private:
1742         v3s16 m_p;
1743         ServerEnvironment *m_env;
1744
1745         static const char className[];
1746         static const luaL_reg methods[];
1747
1748         static NodeMetaRef *checkobject(lua_State *L, int narg)
1749         {
1750                 luaL_checktype(L, narg, LUA_TUSERDATA);
1751                 void *ud = luaL_checkudata(L, narg, className);
1752                 if(!ud) luaL_typerror(L, narg, className);
1753                 return *(NodeMetaRef**)ud;  // unbox pointer
1754         }
1755         
1756         static NodeMetadata* getmeta(NodeMetaRef *ref)
1757         {
1758                 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1759                 return meta;
1760         }
1761
1762         /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1763         {
1764                 NodeMetadata *meta = getmeta(ref);
1765                 if(meta == NULL)
1766                         return NULL;
1767                 if(meta->typeId() != NODEMETA_GENERIC)
1768                         return NULL;
1769                 return (IGenericNodeMetadata*)meta;
1770         }*/
1771
1772         static void reportMetadataChange(NodeMetaRef *ref)
1773         {
1774                 // Inform other things that the metadata has changed
1775                 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1776                 MapEditEvent event;
1777                 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1778                 event.p = blockpos;
1779                 ref->m_env->getMap().dispatchEvent(&event);
1780                 // Set the block to be saved
1781                 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1782                 if(block)
1783                         block->raiseModified(MOD_STATE_WRITE_NEEDED,
1784                                         "NodeMetaRef::reportMetadataChange");
1785         }
1786         
1787         // Exported functions
1788         
1789         // garbage collector
1790         static int gc_object(lua_State *L) {
1791                 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1792                 delete o;
1793                 return 0;
1794         }
1795
1796         // get_type(self)
1797         static int l_get_type(lua_State *L)
1798         {
1799                 NodeMetaRef *ref = checkobject(L, 1);
1800                 NodeMetadata *meta = getmeta(ref);
1801                 if(meta == NULL){
1802                         lua_pushnil(L);
1803                         return 1;
1804                 }
1805                 // Do it
1806                 lua_pushstring(L, meta->typeName());
1807                 return 1;
1808         }
1809
1810         // allows_text_input(self)
1811         static int l_allows_text_input(lua_State *L)
1812         {
1813                 NodeMetaRef *ref = checkobject(L, 1);
1814                 NodeMetadata *meta = getmeta(ref);
1815                 if(meta == NULL) return 0;
1816                 // Do it
1817                 lua_pushboolean(L, meta->allowsTextInput());
1818                 return 1;
1819         }
1820
1821         // set_text(self, text)
1822         static int l_set_text(lua_State *L)
1823         {
1824                 NodeMetaRef *ref = checkobject(L, 1);
1825                 NodeMetadata *meta = getmeta(ref);
1826                 if(meta == NULL) return 0;
1827                 // Do it
1828                 std::string text = luaL_checkstring(L, 2);
1829                 meta->setText(text);
1830                 reportMetadataChange(ref);
1831                 return 0;
1832         }
1833
1834         // get_text(self)
1835         static int l_get_text(lua_State *L)
1836         {
1837                 NodeMetaRef *ref = checkobject(L, 1);
1838                 NodeMetadata *meta = getmeta(ref);
1839                 if(meta == NULL) return 0;
1840                 // Do it
1841                 std::string text = meta->getText();
1842                 lua_pushstring(L, text.c_str());
1843                 return 1;
1844         }
1845
1846         // get_owner(self)
1847         static int l_get_owner(lua_State *L)
1848         {
1849                 NodeMetaRef *ref = checkobject(L, 1);
1850                 NodeMetadata *meta = getmeta(ref);
1851                 if(meta == NULL) return 0;
1852                 // Do it
1853                 std::string owner = meta->getOwner();
1854                 lua_pushstring(L, owner.c_str());
1855                 return 1;
1856         }
1857
1858         // set_owner(self, string)
1859         static int l_set_owner(lua_State *L)
1860         {
1861                 NodeMetaRef *ref = checkobject(L, 1);
1862                 NodeMetadata *meta = getmeta(ref);
1863                 if(meta == NULL) return 0;
1864                 // Do it
1865                 std::string owner = luaL_checkstring(L, 2);
1866                 meta->setOwner(owner);
1867                 reportMetadataChange(ref);
1868                 return 1;
1869         }
1870
1871         // get_allow_removal(self)
1872         static int l_get_allow_removal(lua_State *L)
1873         {
1874                 NodeMetaRef *ref = checkobject(L, 1);
1875                 NodeMetadata *meta = getmeta(ref);
1876                 if(meta == NULL){
1877                         lua_pushboolean(L, true);
1878                         return 1;
1879                 }
1880                 // Do it
1881                 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1882                 return 1;
1883         }
1884
1885         /* IGenericNodeMetadata interface */
1886         
1887         // set_infotext(self, text)
1888         static int l_set_infotext(lua_State *L)
1889         {
1890                 NodeMetaRef *ref = checkobject(L, 1);
1891                 NodeMetadata *meta = getmeta(ref);
1892                 if(meta == NULL) return 0;
1893                 // Do it
1894                 std::string text = luaL_checkstring(L, 2);
1895                 meta->setInfoText(text);
1896                 reportMetadataChange(ref);
1897                 return 0;
1898         }
1899
1900         // get_inventory(self)
1901         static int l_get_inventory(lua_State *L)
1902         {
1903                 NodeMetaRef *ref = checkobject(L, 1);
1904                 NodeMetadata *meta = getmeta(ref);
1905                 if(meta == NULL) return 0;
1906                 // Do it
1907                 InvRef::createNodeMeta(L, ref->m_p);
1908                 return 1;
1909         }
1910
1911         // set_inventory_draw_spec(self, text)
1912         static int l_set_inventory_draw_spec(lua_State *L)
1913         {
1914                 NodeMetaRef *ref = checkobject(L, 1);
1915                 NodeMetadata *meta = getmeta(ref);
1916                 if(meta == NULL) return 0;
1917                 // Do it
1918                 std::string text = luaL_checkstring(L, 2);
1919                 meta->setInventoryDrawSpec(text);
1920                 reportMetadataChange(ref);
1921                 return 0;
1922         }
1923
1924         // set_allow_text_input(self, text)
1925         static int l_set_allow_text_input(lua_State *L)
1926         {
1927                 NodeMetaRef *ref = checkobject(L, 1);
1928                 NodeMetadata *meta = getmeta(ref);
1929                 if(meta == NULL) return 0;
1930                 // Do it
1931                 bool b = lua_toboolean(L, 2);
1932                 meta->setAllowTextInput(b);
1933                 reportMetadataChange(ref);
1934                 return 0;
1935         }
1936
1937         // set_allow_removal(self, text)
1938         static int l_set_allow_removal(lua_State *L)
1939         {
1940                 NodeMetaRef *ref = checkobject(L, 1);
1941                 NodeMetadata *meta = getmeta(ref);
1942                 if(meta == NULL) return 0;
1943                 // Do it
1944                 bool b = lua_toboolean(L, 2);
1945                 meta->setRemovalDisabled(!b);
1946                 reportMetadataChange(ref);
1947                 return 0;
1948         }
1949
1950         // set_enforce_owner(self, text)
1951         static int l_set_enforce_owner(lua_State *L)
1952         {
1953                 NodeMetaRef *ref = checkobject(L, 1);
1954                 NodeMetadata *meta = getmeta(ref);
1955                 if(meta == NULL) return 0;
1956                 // Do it
1957                 bool b = lua_toboolean(L, 2);
1958                 meta->setEnforceOwner(b);
1959                 reportMetadataChange(ref);
1960                 return 0;
1961         }
1962
1963         // is_inventory_modified(self)
1964         static int l_is_inventory_modified(lua_State *L)
1965         {
1966                 NodeMetaRef *ref = checkobject(L, 1);
1967                 NodeMetadata *meta = getmeta(ref);
1968                 if(meta == NULL) return 0;
1969                 // Do it
1970                 lua_pushboolean(L, meta->isInventoryModified());
1971                 return 1;
1972         }
1973
1974         // reset_inventory_modified(self)
1975         static int l_reset_inventory_modified(lua_State *L)
1976         {
1977                 NodeMetaRef *ref = checkobject(L, 1);
1978                 NodeMetadata *meta = getmeta(ref);
1979                 if(meta == NULL) return 0;
1980                 // Do it
1981                 meta->resetInventoryModified();
1982                 reportMetadataChange(ref);
1983                 return 0;
1984         }
1985
1986         // is_text_modified(self)
1987         static int l_is_text_modified(lua_State *L)
1988         {
1989                 NodeMetaRef *ref = checkobject(L, 1);
1990                 NodeMetadata *meta = getmeta(ref);
1991                 if(meta == NULL) return 0;
1992                 // Do it
1993                 lua_pushboolean(L, meta->isTextModified());
1994                 return 1;
1995         }
1996
1997         // reset_text_modified(self)
1998         static int l_reset_text_modified(lua_State *L)
1999         {
2000                 NodeMetaRef *ref = checkobject(L, 1);
2001                 NodeMetadata *meta = getmeta(ref);
2002                 if(meta == NULL) return 0;
2003                 // Do it
2004                 meta->resetTextModified();
2005                 reportMetadataChange(ref);
2006                 return 0;
2007         }
2008
2009         // set_string(self, name, var)
2010         static int l_set_string(lua_State *L)
2011         {
2012                 NodeMetaRef *ref = checkobject(L, 1);
2013                 NodeMetadata *meta = getmeta(ref);
2014                 if(meta == NULL) return 0;
2015                 // Do it
2016                 std::string name = luaL_checkstring(L, 2);
2017                 size_t len = 0;
2018                 const char *s = lua_tolstring(L, 3, &len);
2019                 std::string str(s, len);
2020                 meta->setString(name, str);
2021                 reportMetadataChange(ref);
2022                 return 0;
2023         }
2024
2025         // get_string(self, name)
2026         static int l_get_string(lua_State *L)
2027         {
2028                 NodeMetaRef *ref = checkobject(L, 1);
2029                 NodeMetadata *meta = getmeta(ref);
2030                 if(meta == NULL) return 0;
2031                 // Do it
2032                 std::string name = luaL_checkstring(L, 2);
2033                 std::string str = meta->getString(name);
2034                 lua_pushlstring(L, str.c_str(), str.size());
2035                 return 1;
2036         }
2037
2038 public:
2039         NodeMetaRef(v3s16 p, ServerEnvironment *env):
2040                 m_p(p),
2041                 m_env(env)
2042         {
2043         }
2044
2045         ~NodeMetaRef()
2046         {
2047         }
2048
2049         // Creates an NodeMetaRef and leaves it on top of stack
2050         // Not callable from Lua; all references are created on the C side.
2051         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2052         {
2053                 NodeMetaRef *o = new NodeMetaRef(p, env);
2054                 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2055                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2056                 luaL_getmetatable(L, className);
2057                 lua_setmetatable(L, -2);
2058         }
2059
2060         static void Register(lua_State *L)
2061         {
2062                 lua_newtable(L);
2063                 int methodtable = lua_gettop(L);
2064                 luaL_newmetatable(L, className);
2065                 int metatable = lua_gettop(L);
2066
2067                 lua_pushliteral(L, "__metatable");
2068                 lua_pushvalue(L, methodtable);
2069                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2070
2071                 lua_pushliteral(L, "__index");
2072                 lua_pushvalue(L, methodtable);
2073                 lua_settable(L, metatable);
2074
2075                 lua_pushliteral(L, "__gc");
2076                 lua_pushcfunction(L, gc_object);
2077                 lua_settable(L, metatable);
2078
2079                 lua_pop(L, 1);  // drop metatable
2080
2081                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2082                 lua_pop(L, 1);  // drop methodtable
2083
2084                 // Cannot be created from Lua
2085                 //lua_register(L, className, create_object);
2086         }
2087 };
2088 const char NodeMetaRef::className[] = "NodeMetaRef";
2089 const luaL_reg NodeMetaRef::methods[] = {
2090         method(NodeMetaRef, get_type),
2091         method(NodeMetaRef, allows_text_input),
2092         method(NodeMetaRef, set_text),
2093         method(NodeMetaRef, get_text),
2094         method(NodeMetaRef, get_owner),
2095         method(NodeMetaRef, set_owner),
2096         method(NodeMetaRef, get_allow_removal),
2097         method(NodeMetaRef, set_infotext),
2098         method(NodeMetaRef, get_inventory),
2099         method(NodeMetaRef, set_inventory_draw_spec),
2100         method(NodeMetaRef, set_allow_text_input),
2101         method(NodeMetaRef, set_allow_removal),
2102         method(NodeMetaRef, set_enforce_owner),
2103         method(NodeMetaRef, is_inventory_modified),
2104         method(NodeMetaRef, reset_inventory_modified),
2105         method(NodeMetaRef, is_text_modified),
2106         method(NodeMetaRef, reset_text_modified),
2107         method(NodeMetaRef, set_string),
2108         method(NodeMetaRef, get_string),
2109         {0,0}
2110 };
2111
2112 /*
2113         ObjectRef
2114 */
2115
2116 class ObjectRef
2117 {
2118 private:
2119         ServerActiveObject *m_object;
2120
2121         static const char className[];
2122         static const luaL_reg methods[];
2123
2124         static ObjectRef *checkobject(lua_State *L, int narg)
2125         {
2126                 luaL_checktype(L, narg, LUA_TUSERDATA);
2127                 void *ud = luaL_checkudata(L, narg, className);
2128                 if(!ud) luaL_typerror(L, narg, className);
2129                 return *(ObjectRef**)ud;  // unbox pointer
2130         }
2131         
2132         static ServerActiveObject* getobject(ObjectRef *ref)
2133         {
2134                 ServerActiveObject *co = ref->m_object;
2135                 return co;
2136         }
2137         
2138         static LuaEntitySAO* getluaobject(ObjectRef *ref)
2139         {
2140                 ServerActiveObject *obj = getobject(ref);
2141                 if(obj == NULL)
2142                         return NULL;
2143                 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2144                         return NULL;
2145                 return (LuaEntitySAO*)obj;
2146         }
2147         
2148         static ServerRemotePlayer* getplayer(ObjectRef *ref)
2149         {
2150                 ServerActiveObject *obj = getobject(ref);
2151                 if(obj == NULL)
2152                         return NULL;
2153                 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2154                         return NULL;
2155                 return static_cast<ServerRemotePlayer*>(obj);
2156         }
2157         
2158         // Exported functions
2159         
2160         // garbage collector
2161         static int gc_object(lua_State *L) {
2162                 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2163                 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2164                 delete o;
2165                 return 0;
2166         }
2167
2168         // remove(self)
2169         static int l_remove(lua_State *L)
2170         {
2171                 ObjectRef *ref = checkobject(L, 1);
2172                 ServerActiveObject *co = getobject(ref);
2173                 if(co == NULL) return 0;
2174                 infostream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2175                 co->m_removed = true;
2176                 return 0;
2177         }
2178         
2179         // getpos(self)
2180         // returns: {x=num, y=num, z=num}
2181         static int l_getpos(lua_State *L)
2182         {
2183                 ObjectRef *ref = checkobject(L, 1);
2184                 ServerActiveObject *co = getobject(ref);
2185                 if(co == NULL) return 0;
2186                 v3f pos = co->getBasePosition() / BS;
2187                 lua_newtable(L);
2188                 lua_pushnumber(L, pos.X);
2189                 lua_setfield(L, -2, "x");
2190                 lua_pushnumber(L, pos.Y);
2191                 lua_setfield(L, -2, "y");
2192                 lua_pushnumber(L, pos.Z);
2193                 lua_setfield(L, -2, "z");
2194                 return 1;
2195         }
2196         
2197         // setpos(self, pos)
2198         static int l_setpos(lua_State *L)
2199         {
2200                 ObjectRef *ref = checkobject(L, 1);
2201                 //LuaEntitySAO *co = getluaobject(ref);
2202                 ServerActiveObject *co = getobject(ref);
2203                 if(co == NULL) return 0;
2204                 // pos
2205                 v3f pos = checkFloatPos(L, 2);
2206                 // Do it
2207                 co->setPos(pos);
2208                 // Move player if applicable
2209                 ServerRemotePlayer *player = getplayer(ref);
2210                 if(player != NULL)
2211                         get_server(L)->SendMovePlayer(player);
2212                 return 0;
2213         }
2214         
2215         // moveto(self, pos, continuous=false)
2216         static int l_moveto(lua_State *L)
2217         {
2218                 ObjectRef *ref = checkobject(L, 1);
2219                 //LuaEntitySAO *co = getluaobject(ref);
2220                 ServerActiveObject *co = getobject(ref);
2221                 if(co == NULL) return 0;
2222                 // pos
2223                 v3f pos = checkFloatPos(L, 2);
2224                 // continuous
2225                 bool continuous = lua_toboolean(L, 3);
2226                 // Do it
2227                 co->moveTo(pos, continuous);
2228                 return 0;
2229         }
2230
2231         // punch(self, puncher); puncher = an another ObjectRef
2232         static int l_punch(lua_State *L)
2233         {
2234                 ObjectRef *ref = checkobject(L, 1);
2235                 ObjectRef *ref2 = checkobject(L, 2);
2236                 ServerActiveObject *co = getobject(ref);
2237                 ServerActiveObject *co2 = getobject(ref2);
2238                 if(co == NULL) return 0;
2239                 if(co2 == NULL) return 0;
2240                 // Do it
2241                 co->punch(co2);
2242                 return 0;
2243         }
2244
2245         // right_click(self, clicker); clicker = an another ObjectRef
2246         static int l_right_click(lua_State *L)
2247         {
2248                 ObjectRef *ref = checkobject(L, 1);
2249                 ObjectRef *ref2 = checkobject(L, 2);
2250                 ServerActiveObject *co = getobject(ref);
2251                 ServerActiveObject *co2 = getobject(ref2);
2252                 if(co == NULL) return 0;
2253                 if(co2 == NULL) return 0;
2254                 // Do it
2255                 co->rightClick(co2);
2256                 return 0;
2257         }
2258
2259         // set_hp(self, hp)
2260         // hp = number of hitpoints (2 * number of hearts)
2261         // returns: nil
2262         static int l_set_hp(lua_State *L)
2263         {
2264                 ObjectRef *ref = checkobject(L, 1);
2265                 luaL_checknumber(L, 2);
2266                 ServerActiveObject *co = getobject(ref);
2267                 if(co == NULL) return 0;
2268                 int hp = lua_tonumber(L, 2);
2269                 infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2270                                 <<" hp="<<hp<<std::endl;
2271                 // Do it
2272                 co->setHP(hp);
2273                 // Return
2274                 return 0;
2275         }
2276
2277         // get_hp(self)
2278         // returns: number of hitpoints (2 * number of hearts)
2279         // 0 if not applicable to this type of object
2280         static int l_get_hp(lua_State *L)
2281         {
2282                 ObjectRef *ref = checkobject(L, 1);
2283                 ServerActiveObject *co = getobject(ref);
2284                 if(co == NULL) return 0;
2285                 int hp = co->getHP();
2286                 infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2287                                 <<" hp="<<hp<<std::endl;
2288                 // Return
2289                 lua_pushnumber(L, hp);
2290                 return 1;
2291         }
2292
2293         // get_inventory(self)
2294         static int l_get_inventory(lua_State *L)
2295         {
2296                 ObjectRef *ref = checkobject(L, 1);
2297                 ServerActiveObject *co = getobject(ref);
2298                 if(co == NULL) return 0;
2299                 // Do it
2300                 InventoryLocation loc = co->getInventoryLocation();
2301                 if(get_server(L)->getInventory(loc) != NULL)
2302                         InvRef::create(L, loc);
2303                 else
2304                         lua_pushnil(L);
2305                 return 1;
2306         }
2307
2308         // get_wield_list(self)
2309         static int l_get_wield_list(lua_State *L)
2310         {
2311                 ObjectRef *ref = checkobject(L, 1);
2312                 ServerActiveObject *co = getobject(ref);
2313                 if(co == NULL) return 0;
2314                 // Do it
2315                 lua_pushstring(L, co->getWieldList().c_str());
2316                 return 1;
2317         }
2318
2319         // get_wield_index(self)
2320         static int l_get_wield_index(lua_State *L)
2321         {
2322                 ObjectRef *ref = checkobject(L, 1);
2323                 ServerActiveObject *co = getobject(ref);
2324                 if(co == NULL) return 0;
2325                 // Do it
2326                 lua_pushinteger(L, co->getWieldIndex() + 1);
2327                 return 1;
2328         }
2329
2330         // get_wielded_item(self)
2331         static int l_get_wielded_item(lua_State *L)
2332         {
2333                 ObjectRef *ref = checkobject(L, 1);
2334                 ServerActiveObject *co = getobject(ref);
2335                 if(co == NULL) return 0;
2336                 // Do it
2337                 LuaItemStack::create(L, co->getWieldedItem());
2338                 return 1;
2339         }
2340
2341         // set_wielded_item(self, itemstack or itemstring or table or nil)
2342         static int l_set_wielded_item(lua_State *L)
2343         {
2344                 ObjectRef *ref = checkobject(L, 1);
2345                 ServerActiveObject *co = getobject(ref);
2346                 if(co == NULL) return 0;
2347                 // Do it
2348                 ItemStack item = read_item(L, 2);
2349                 bool success = co->setWieldedItem(item);
2350                 lua_pushboolean(L, success);
2351                 return 1;
2352         }
2353
2354         /* LuaEntitySAO-only */
2355
2356         // setvelocity(self, {x=num, y=num, z=num})
2357         static int l_setvelocity(lua_State *L)
2358         {
2359                 ObjectRef *ref = checkobject(L, 1);
2360                 LuaEntitySAO *co = getluaobject(ref);
2361                 if(co == NULL) return 0;
2362                 // pos
2363                 v3f pos = checkFloatPos(L, 2);
2364                 // Do it
2365                 co->setVelocity(pos);
2366                 return 0;
2367         }
2368         
2369         // getvelocity(self)
2370         static int l_getvelocity(lua_State *L)
2371         {
2372                 ObjectRef *ref = checkobject(L, 1);
2373                 LuaEntitySAO *co = getluaobject(ref);
2374                 if(co == NULL) return 0;
2375                 // Do it
2376                 v3f v = co->getVelocity();
2377                 pushFloatPos(L, v);
2378                 return 1;
2379         }
2380         
2381         // setacceleration(self, {x=num, y=num, z=num})
2382         static int l_setacceleration(lua_State *L)
2383         {
2384                 ObjectRef *ref = checkobject(L, 1);
2385                 LuaEntitySAO *co = getluaobject(ref);
2386                 if(co == NULL) return 0;
2387                 // pos
2388                 v3f pos = checkFloatPos(L, 2);
2389                 // Do it
2390                 co->setAcceleration(pos);
2391                 return 0;
2392         }
2393         
2394         // getacceleration(self)
2395         static int l_getacceleration(lua_State *L)
2396         {
2397                 ObjectRef *ref = checkobject(L, 1);
2398                 LuaEntitySAO *co = getluaobject(ref);
2399                 if(co == NULL) return 0;
2400                 // Do it
2401                 v3f v = co->getAcceleration();
2402                 pushFloatPos(L, v);
2403                 return 1;
2404         }
2405         
2406         // setyaw(self, radians)
2407         static int l_setyaw(lua_State *L)
2408         {
2409                 ObjectRef *ref = checkobject(L, 1);
2410                 LuaEntitySAO *co = getluaobject(ref);
2411                 if(co == NULL) return 0;
2412                 // pos
2413                 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2414                 // Do it
2415                 co->setYaw(yaw);
2416                 return 0;
2417         }
2418         
2419         // getyaw(self)
2420         static int l_getyaw(lua_State *L)
2421         {
2422                 ObjectRef *ref = checkobject(L, 1);
2423                 LuaEntitySAO *co = getluaobject(ref);
2424                 if(co == NULL) return 0;
2425                 // Do it
2426                 float yaw = co->getYaw() * core::DEGTORAD;
2427                 lua_pushnumber(L, yaw);
2428                 return 1;
2429         }
2430         
2431         // settexturemod(self, mod)
2432         static int l_settexturemod(lua_State *L)
2433         {
2434                 ObjectRef *ref = checkobject(L, 1);
2435                 LuaEntitySAO *co = getluaobject(ref);
2436                 if(co == NULL) return 0;
2437                 // Do it
2438                 std::string mod = luaL_checkstring(L, 2);
2439                 co->setTextureMod(mod);
2440                 return 0;
2441         }
2442         
2443         // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2444         //           select_horiz_by_yawpitch=false)
2445         static int l_setsprite(lua_State *L)
2446         {
2447                 ObjectRef *ref = checkobject(L, 1);
2448                 LuaEntitySAO *co = getluaobject(ref);
2449                 if(co == NULL) return 0;
2450                 // Do it
2451                 v2s16 p(0,0);
2452                 if(!lua_isnil(L, 2))
2453                         p = read_v2s16(L, 2);
2454                 int num_frames = 1;
2455                 if(!lua_isnil(L, 3))
2456                         num_frames = lua_tonumber(L, 3);
2457                 float framelength = 0.2;
2458                 if(!lua_isnil(L, 4))
2459                         framelength = lua_tonumber(L, 4);
2460                 bool select_horiz_by_yawpitch = false;
2461                 if(!lua_isnil(L, 5))
2462                         select_horiz_by_yawpitch = lua_toboolean(L, 5);
2463                 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2464                 return 0;
2465         }
2466
2467         // DEPRECATED
2468         // get_entity_name(self)
2469         static int l_get_entity_name(lua_State *L)
2470         {
2471                 ObjectRef *ref = checkobject(L, 1);
2472                 LuaEntitySAO *co = getluaobject(ref);
2473                 if(co == NULL) return 0;
2474                 // Do it
2475                 std::string name = co->getName();
2476                 lua_pushstring(L, name.c_str());
2477                 return 1;
2478         }
2479         
2480         // get_luaentity(self)
2481         static int l_get_luaentity(lua_State *L)
2482         {
2483                 ObjectRef *ref = checkobject(L, 1);
2484                 LuaEntitySAO *co = getluaobject(ref);
2485                 if(co == NULL) return 0;
2486                 // Do it
2487                 luaentity_get(L, co->getId());
2488                 return 1;
2489         }
2490         
2491         /* Player-only */
2492         
2493         // get_player_name(self)
2494         static int l_get_player_name(lua_State *L)
2495         {
2496                 ObjectRef *ref = checkobject(L, 1);
2497                 ServerRemotePlayer *player = getplayer(ref);
2498                 if(player == NULL){
2499                         lua_pushnil(L);
2500                         return 1;
2501                 }
2502                 // Do it
2503                 lua_pushstring(L, player->getName());
2504                 return 1;
2505         }
2506         
2507         // get_look_dir(self)
2508         static int l_get_look_dir(lua_State *L)
2509         {
2510                 ObjectRef *ref = checkobject(L, 1);
2511                 ServerRemotePlayer *player = getplayer(ref);
2512                 if(player == NULL) return 0;
2513                 // Do it
2514                 float pitch = player->getRadPitch();
2515                 float yaw = player->getRadYaw();
2516                 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2517                 push_v3f(L, v);
2518                 return 1;
2519         }
2520
2521         // get_look_pitch(self)
2522         static int l_get_look_pitch(lua_State *L)
2523         {
2524                 ObjectRef *ref = checkobject(L, 1);
2525                 ServerRemotePlayer *player = getplayer(ref);
2526                 if(player == NULL) return 0;
2527                 // Do it
2528                 lua_pushnumber(L, player->getRadPitch());
2529                 return 1;
2530         }
2531
2532         // get_look_yaw(self)
2533         static int l_get_look_yaw(lua_State *L)
2534         {
2535                 ObjectRef *ref = checkobject(L, 1);
2536                 ServerRemotePlayer *player = getplayer(ref);
2537                 if(player == NULL) return 0;
2538                 // Do it
2539                 lua_pushnumber(L, player->getRadYaw());
2540                 return 1;
2541         }
2542
2543 public:
2544         ObjectRef(ServerActiveObject *object):
2545                 m_object(object)
2546         {
2547                 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2548         }
2549
2550         ~ObjectRef()
2551         {
2552                 /*if(m_object)
2553                         infostream<<"ObjectRef destructing for id="
2554                                         <<m_object->getId()<<std::endl;
2555                 else
2556                         infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2557         }
2558
2559         // Creates an ObjectRef and leaves it on top of stack
2560         // Not callable from Lua; all references are created on the C side.
2561         static void create(lua_State *L, ServerActiveObject *object)
2562         {
2563                 ObjectRef *o = new ObjectRef(object);
2564                 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2565                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2566                 luaL_getmetatable(L, className);
2567                 lua_setmetatable(L, -2);
2568         }
2569
2570         static void set_null(lua_State *L)
2571         {
2572                 ObjectRef *o = checkobject(L, -1);
2573                 o->m_object = NULL;
2574         }
2575         
2576         static void Register(lua_State *L)
2577         {
2578                 lua_newtable(L);
2579                 int methodtable = lua_gettop(L);
2580                 luaL_newmetatable(L, className);
2581                 int metatable = lua_gettop(L);
2582
2583                 lua_pushliteral(L, "__metatable");
2584                 lua_pushvalue(L, methodtable);
2585                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2586
2587                 lua_pushliteral(L, "__index");
2588                 lua_pushvalue(L, methodtable);
2589                 lua_settable(L, metatable);
2590
2591                 lua_pushliteral(L, "__gc");
2592                 lua_pushcfunction(L, gc_object);
2593                 lua_settable(L, metatable);
2594
2595                 lua_pop(L, 1);  // drop metatable
2596
2597                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2598                 lua_pop(L, 1);  // drop methodtable
2599
2600                 // Cannot be created from Lua
2601                 //lua_register(L, className, create_object);
2602         }
2603 };
2604 const char ObjectRef::className[] = "ObjectRef";
2605 const luaL_reg ObjectRef::methods[] = {
2606         // ServerActiveObject
2607         method(ObjectRef, remove),
2608         method(ObjectRef, getpos),
2609         method(ObjectRef, setpos),
2610         method(ObjectRef, moveto),
2611         method(ObjectRef, punch),
2612         method(ObjectRef, right_click),
2613         method(ObjectRef, set_hp),
2614         method(ObjectRef, get_hp),
2615         method(ObjectRef, get_inventory),
2616         method(ObjectRef, get_wield_list),
2617         method(ObjectRef, get_wield_index),
2618         method(ObjectRef, get_wielded_item),
2619         method(ObjectRef, set_wielded_item),
2620         // LuaEntitySAO-only
2621         method(ObjectRef, setvelocity),
2622         method(ObjectRef, getvelocity),
2623         method(ObjectRef, setacceleration),
2624         method(ObjectRef, getacceleration),
2625         method(ObjectRef, setyaw),
2626         method(ObjectRef, getyaw),
2627         method(ObjectRef, settexturemod),
2628         method(ObjectRef, setsprite),
2629         method(ObjectRef, get_entity_name),
2630         method(ObjectRef, get_luaentity),
2631         // Player-only
2632         method(ObjectRef, get_player_name),
2633         method(ObjectRef, get_look_dir),
2634         method(ObjectRef, get_look_pitch),
2635         method(ObjectRef, get_look_yaw),
2636         {0,0}
2637 };
2638
2639 // Creates a new anonymous reference if id=0
2640 static void objectref_get_or_create(lua_State *L,
2641                 ServerActiveObject *cobj)
2642 {
2643         if(cobj->getId() == 0){
2644                 ObjectRef::create(L, cobj);
2645         } else {
2646                 objectref_get(L, cobj->getId());
2647         }
2648 }
2649
2650 /*
2651         EnvRef
2652 */
2653
2654 class EnvRef
2655 {
2656 private:
2657         ServerEnvironment *m_env;
2658
2659         static const char className[];
2660         static const luaL_reg methods[];
2661
2662         static EnvRef *checkobject(lua_State *L, int narg)
2663         {
2664                 luaL_checktype(L, narg, LUA_TUSERDATA);
2665                 void *ud = luaL_checkudata(L, narg, className);
2666                 if(!ud) luaL_typerror(L, narg, className);
2667                 return *(EnvRef**)ud;  // unbox pointer
2668         }
2669         
2670         // Exported functions
2671
2672         // EnvRef:add_node(pos, node)
2673         // pos = {x=num, y=num, z=num}
2674         static int l_add_node(lua_State *L)
2675         {
2676                 //infostream<<"EnvRef::l_add_node()"<<std::endl;
2677                 EnvRef *o = checkobject(L, 1);
2678                 ServerEnvironment *env = o->m_env;
2679                 if(env == NULL) return 0;
2680                 // pos
2681                 v3s16 pos = read_v3s16(L, 2);
2682                 // content
2683                 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2684                 // Do it
2685                 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2686                 lua_pushboolean(L, succeeded);
2687                 return 1;
2688         }
2689
2690         // EnvRef:remove_node(pos)
2691         // pos = {x=num, y=num, z=num}
2692         static int l_remove_node(lua_State *L)
2693         {
2694                 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2695                 EnvRef *o = checkobject(L, 1);
2696                 ServerEnvironment *env = o->m_env;
2697                 if(env == NULL) return 0;
2698                 // pos
2699                 v3s16 pos = read_v3s16(L, 2);
2700                 // Do it
2701                 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2702                 lua_pushboolean(L, succeeded);
2703                 return 1;
2704         }
2705
2706         // EnvRef:get_node(pos)
2707         // pos = {x=num, y=num, z=num}
2708         static int l_get_node(lua_State *L)
2709         {
2710                 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2711                 EnvRef *o = checkobject(L, 1);
2712                 ServerEnvironment *env = o->m_env;
2713                 if(env == NULL) return 0;
2714                 // pos
2715                 v3s16 pos = read_v3s16(L, 2);
2716                 // Do it
2717                 MapNode n = env->getMap().getNodeNoEx(pos);
2718                 // Return node
2719                 pushnode(L, n, env->getGameDef()->ndef());
2720                 return 1;
2721         }
2722
2723         // EnvRef:get_node_or_nil(pos)
2724         // pos = {x=num, y=num, z=num}
2725         static int l_get_node_or_nil(lua_State *L)
2726         {
2727                 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2728                 EnvRef *o = checkobject(L, 1);
2729                 ServerEnvironment *env = o->m_env;
2730                 if(env == NULL) return 0;
2731                 // pos
2732                 v3s16 pos = read_v3s16(L, 2);
2733                 // Do it
2734                 try{
2735                         MapNode n = env->getMap().getNode(pos);
2736                         // Return node
2737                         pushnode(L, n, env->getGameDef()->ndef());
2738                         return 1;
2739                 } catch(InvalidPositionException &e)
2740                 {
2741                         lua_pushnil(L);
2742                         return 1;
2743                 }
2744         }
2745
2746         // EnvRef:get_node_light(pos, timeofday)
2747         // pos = {x=num, y=num, z=num}
2748         // timeofday: nil = current time, 0 = night, 0.5 = day
2749         static int l_get_node_light(lua_State *L)
2750         {
2751                 EnvRef *o = checkobject(L, 1);
2752                 ServerEnvironment *env = o->m_env;
2753                 if(env == NULL) return 0;
2754                 // Do it
2755                 v3s16 pos = read_v3s16(L, 2);
2756                 u32 time_of_day = env->getTimeOfDay();
2757                 if(lua_isnumber(L, 3))
2758                         time_of_day = 24000.0 * lua_tonumber(L, 3);
2759                 time_of_day %= 24000;
2760                 u32 dnr = time_to_daynight_ratio(time_of_day);
2761                 MapNode n = env->getMap().getNodeNoEx(pos);
2762                 try{
2763                         MapNode n = env->getMap().getNode(pos);
2764                         INodeDefManager *ndef = env->getGameDef()->ndef();
2765                         lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2766                         return 1;
2767                 } catch(InvalidPositionException &e)
2768                 {
2769                         lua_pushnil(L);
2770                         return 1;
2771                 }
2772         }
2773
2774         // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2775         // pos = {x=num, y=num, z=num}
2776         static int l_add_entity(lua_State *L)
2777         {
2778                 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2779                 EnvRef *o = checkobject(L, 1);
2780                 ServerEnvironment *env = o->m_env;
2781                 if(env == NULL) return 0;
2782                 // pos
2783                 v3f pos = checkFloatPos(L, 2);
2784                 // content
2785                 const char *name = luaL_checkstring(L, 3);
2786                 // Do it
2787                 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2788                 int objectid = env->addActiveObject(obj);
2789                 // If failed to add, return nothing (reads as nil)
2790                 if(objectid == 0)
2791                         return 0;
2792                 // Return ObjectRef
2793                 objectref_get_or_create(L, obj);
2794                 return 1;
2795         }
2796
2797         // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2798         // pos = {x=num, y=num, z=num}
2799         static int l_add_item(lua_State *L)
2800         {
2801                 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2802                 EnvRef *o = checkobject(L, 1);
2803                 ServerEnvironment *env = o->m_env;
2804                 if(env == NULL) return 0;
2805                 // pos
2806                 v3f pos = checkFloatPos(L, 2);
2807                 // item
2808                 ItemStack item = read_item(L, 3);
2809                 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2810                         return 0;
2811                 // Do it
2812                 ServerActiveObject *obj = new ItemSAO(env, pos, item.getItemString());
2813                 int objectid = env->addActiveObject(obj);
2814                 // If failed to add, return nothing (reads as nil)
2815                 if(objectid == 0)
2816                         return 0;
2817                 // Return ObjectRef
2818                 objectref_get_or_create(L, obj);
2819                 return 1;
2820         }
2821
2822         // EnvRef:add_rat(pos)
2823         // pos = {x=num, y=num, z=num}
2824         static int l_add_rat(lua_State *L)
2825         {
2826                 infostream<<"EnvRef::l_add_rat()"<<std::endl;
2827                 EnvRef *o = checkobject(L, 1);
2828                 ServerEnvironment *env = o->m_env;
2829                 if(env == NULL) return 0;
2830                 // pos
2831                 v3f pos = checkFloatPos(L, 2);
2832                 // Do it
2833                 ServerActiveObject *obj = new RatSAO(env, pos);
2834                 env->addActiveObject(obj);
2835                 return 0;
2836         }
2837
2838         // EnvRef:add_firefly(pos)
2839         // pos = {x=num, y=num, z=num}
2840         static int l_add_firefly(lua_State *L)
2841         {
2842                 infostream<<"EnvRef::l_add_firefly()"<<std::endl;
2843                 EnvRef *o = checkobject(L, 1);
2844                 ServerEnvironment *env = o->m_env;
2845                 if(env == NULL) return 0;
2846                 // pos
2847                 v3f pos = checkFloatPos(L, 2);
2848                 // Do it
2849                 ServerActiveObject *obj = new FireflySAO(env, pos);
2850                 env->addActiveObject(obj);
2851                 return 0;
2852         }
2853
2854         // EnvRef:get_meta(pos)
2855         static int l_get_meta(lua_State *L)
2856         {
2857                 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2858                 EnvRef *o = checkobject(L, 1);
2859                 ServerEnvironment *env = o->m_env;
2860                 if(env == NULL) return 0;
2861                 // Do it
2862                 v3s16 p = read_v3s16(L, 2);
2863                 NodeMetaRef::create(L, p, env);
2864                 return 1;
2865         }
2866
2867         // EnvRef:get_player_by_name(name)
2868         static int l_get_player_by_name(lua_State *L)
2869         {
2870                 EnvRef *o = checkobject(L, 1);
2871                 ServerEnvironment *env = o->m_env;
2872                 if(env == NULL) return 0;
2873                 // Do it
2874                 const char *name = luaL_checkstring(L, 2);
2875                 ServerRemotePlayer *player =
2876                                 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2877                 if(player == NULL){
2878                         lua_pushnil(L);
2879                         return 1;
2880                 }
2881                 // Put player on stack
2882                 objectref_get_or_create(L, player);
2883                 return 1;
2884         }
2885
2886         // EnvRef:get_objects_inside_radius(pos, radius)
2887         static int l_get_objects_inside_radius(lua_State *L)
2888         {
2889                 // Get the table insert function
2890                 lua_getglobal(L, "table");
2891                 lua_getfield(L, -1, "insert");
2892                 int table_insert = lua_gettop(L);
2893                 // Get environemnt
2894                 EnvRef *o = checkobject(L, 1);
2895                 ServerEnvironment *env = o->m_env;
2896                 if(env == NULL) return 0;
2897                 // Do it
2898                 v3f pos = checkFloatPos(L, 2);
2899                 float radius = luaL_checknumber(L, 3) * BS;
2900                 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
2901                 lua_newtable(L);
2902                 int table = lua_gettop(L);
2903                 for(std::set<u16>::const_iterator
2904                                 i = ids.begin(); i != ids.end(); i++){
2905                         ServerActiveObject *obj = env->getActiveObject(*i);
2906                         // Insert object reference into table
2907                         lua_pushvalue(L, table_insert);
2908                         lua_pushvalue(L, table);
2909                         objectref_get_or_create(L, obj);
2910                         if(lua_pcall(L, 2, 0, 0))
2911                                 script_error(L, "error: %s", lua_tostring(L, -1));
2912                 }
2913                 return 1;
2914         }
2915
2916         static int gc_object(lua_State *L) {
2917                 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
2918                 delete o;
2919                 return 0;
2920         }
2921
2922 public:
2923         EnvRef(ServerEnvironment *env):
2924                 m_env(env)
2925         {
2926                 infostream<<"EnvRef created"<<std::endl;
2927         }
2928
2929         ~EnvRef()
2930         {
2931                 infostream<<"EnvRef destructing"<<std::endl;
2932         }
2933
2934         // Creates an EnvRef and leaves it on top of stack
2935         // Not callable from Lua; all references are created on the C side.
2936         static void create(lua_State *L, ServerEnvironment *env)
2937         {
2938                 EnvRef *o = new EnvRef(env);
2939                 //infostream<<"EnvRef::create: o="<<o<<std::endl;
2940                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2941                 luaL_getmetatable(L, className);
2942                 lua_setmetatable(L, -2);
2943         }
2944
2945         static void set_null(lua_State *L)
2946         {
2947                 EnvRef *o = checkobject(L, -1);
2948                 o->m_env = NULL;
2949         }
2950         
2951         static void Register(lua_State *L)
2952         {
2953                 lua_newtable(L);
2954                 int methodtable = lua_gettop(L);
2955                 luaL_newmetatable(L, className);
2956                 int metatable = lua_gettop(L);
2957
2958                 lua_pushliteral(L, "__metatable");
2959                 lua_pushvalue(L, methodtable);
2960                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2961
2962                 lua_pushliteral(L, "__index");
2963                 lua_pushvalue(L, methodtable);
2964                 lua_settable(L, metatable);
2965
2966                 lua_pushliteral(L, "__gc");
2967                 lua_pushcfunction(L, gc_object);
2968                 lua_settable(L, metatable);
2969
2970                 lua_pop(L, 1);  // drop metatable
2971
2972                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2973                 lua_pop(L, 1);  // drop methodtable
2974
2975                 // Cannot be created from Lua
2976                 //lua_register(L, className, create_object);
2977         }
2978 };
2979 const char EnvRef::className[] = "EnvRef";
2980 const luaL_reg EnvRef::methods[] = {
2981         method(EnvRef, add_node),
2982         method(EnvRef, remove_node),
2983         method(EnvRef, get_node),
2984         method(EnvRef, get_node_or_nil),
2985         method(EnvRef, get_node_light),
2986         method(EnvRef, add_entity),
2987         method(EnvRef, add_item),
2988         method(EnvRef, add_rat),
2989         method(EnvRef, add_firefly),
2990         method(EnvRef, get_meta),
2991         method(EnvRef, get_player_by_name),
2992         method(EnvRef, get_objects_inside_radius),
2993         {0,0}
2994 };
2995
2996 /*
2997         Global functions
2998 */
2999
3000 class LuaABM : public ActiveBlockModifier
3001 {
3002 private:
3003         lua_State *m_lua;
3004         int m_id;
3005
3006         std::set<std::string> m_trigger_contents;
3007         std::set<std::string> m_required_neighbors;
3008         float m_trigger_interval;
3009         u32 m_trigger_chance;
3010 public:
3011         LuaABM(lua_State *L, int id,
3012                         const std::set<std::string> &trigger_contents,
3013                         const std::set<std::string> &required_neighbors,
3014                         float trigger_interval, u32 trigger_chance):
3015                 m_lua(L),
3016                 m_id(id),
3017                 m_trigger_contents(trigger_contents),
3018                 m_required_neighbors(required_neighbors),
3019                 m_trigger_interval(trigger_interval),
3020                 m_trigger_chance(trigger_chance)
3021         {
3022         }
3023         virtual std::set<std::string> getTriggerContents()
3024         {
3025                 return m_trigger_contents;
3026         }
3027         virtual std::set<std::string> getRequiredNeighbors()
3028         {
3029                 return m_required_neighbors;
3030         }
3031         virtual float getTriggerInterval()
3032         {
3033                 return m_trigger_interval;
3034         }
3035         virtual u32 getTriggerChance()
3036         {
3037                 return m_trigger_chance;
3038         }
3039         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3040                         u32 active_object_count, u32 active_object_count_wider)
3041         {
3042                 lua_State *L = m_lua;
3043         
3044                 realitycheck(L);
3045                 assert(lua_checkstack(L, 20));
3046                 StackUnroller stack_unroller(L);
3047
3048                 // Get minetest.registered_abms
3049                 lua_getglobal(L, "minetest");
3050                 lua_getfield(L, -1, "registered_abms");
3051                 luaL_checktype(L, -1, LUA_TTABLE);
3052                 int registered_abms = lua_gettop(L);
3053
3054                 // Get minetest.registered_abms[m_id]
3055                 lua_pushnumber(L, m_id);
3056                 lua_gettable(L, registered_abms);
3057                 if(lua_isnil(L, -1))
3058                         assert(0);
3059                 
3060                 // Call action
3061                 luaL_checktype(L, -1, LUA_TTABLE);
3062                 lua_getfield(L, -1, "action");
3063                 luaL_checktype(L, -1, LUA_TFUNCTION);
3064                 push_v3s16(L, p);
3065                 pushnode(L, n, env->getGameDef()->ndef());
3066                 lua_pushnumber(L, active_object_count);
3067                 lua_pushnumber(L, active_object_count_wider);
3068                 if(lua_pcall(L, 4, 0, 0))
3069                         script_error(L, "error: %s", lua_tostring(L, -1));
3070         }
3071 };
3072
3073 // debug(text)
3074 // Writes a line to dstream
3075 static int l_debug(lua_State *L)
3076 {
3077         std::string text = lua_tostring(L, 1);
3078         dstream << text << std::endl;
3079         return 0;
3080 }
3081
3082 // log([level,] text)
3083 // Writes a line to the logger.
3084 // The one-argument version logs to infostream.
3085 // The two-argument version accept a log level: error, action, info, or verbose.
3086 static int l_log(lua_State *L)
3087 {
3088         std::string text;
3089         LogMessageLevel level = LMT_INFO;
3090         if(lua_isnone(L, 2))
3091         {
3092                 text = lua_tostring(L, 1);
3093         }
3094         else
3095         {
3096                 std::string levelname = lua_tostring(L, 1);
3097                 text = lua_tostring(L, 2);
3098                 if(levelname == "error")
3099                         level = LMT_ERROR;
3100                 else if(levelname == "action")
3101                         level = LMT_ACTION;
3102                 else if(levelname == "verbose")
3103                         level = LMT_VERBOSE;
3104         }
3105         log_printline(level, text);
3106         return 0;
3107 }
3108
3109 // register_item_raw({lots of stuff})
3110 static int l_register_item_raw(lua_State *L)
3111 {
3112         luaL_checktype(L, 1, LUA_TTABLE);
3113         int table = 1;
3114
3115         // Get the writable item and node definition managers from the server
3116         IWritableItemDefManager *idef =
3117                         get_server(L)->getWritableItemDefManager();
3118         IWritableNodeDefManager *ndef =
3119                         get_server(L)->getWritableNodeDefManager();
3120
3121         // Check if name is defined
3122         lua_getfield(L, table, "name");
3123         if(lua_isstring(L, -1)){
3124                 std::string name = lua_tostring(L, -1);
3125                 infostream<<"register_item_raw: "<<name<<std::endl;
3126         } else {
3127                 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3128         }
3129
3130         // Check if on_use is defined
3131
3132         // Read the item definition and register it
3133         ItemDefinition def = read_item_definition(L, table);
3134         idef->registerItem(def);
3135
3136         // Read the node definition (content features) and register it
3137         if(def.type == ITEM_NODE)
3138         {
3139                 ContentFeatures f = read_content_features(L, table);
3140                 ndef->set(f.name, f);
3141         }
3142
3143         return 0; /* number of results */
3144 }
3145
3146 // register_alias_raw(name, convert_to_name)
3147 static int l_register_alias_raw(lua_State *L)
3148 {
3149         std::string name = luaL_checkstring(L, 1);
3150         std::string convert_to = luaL_checkstring(L, 2);
3151
3152         // Get the writable item definition manager from the server
3153         IWritableItemDefManager *idef =
3154                         get_server(L)->getWritableItemDefManager();
3155         
3156         idef->registerAlias(name, convert_to);
3157         
3158         return 0; /* number of results */
3159 }
3160
3161 // helper for register_craft
3162 static bool read_craft_recipe_shaped(lua_State *L, int index,
3163                 int &width, std::vector<std::string> &recipe)
3164 {
3165         if(index < 0)
3166                 index = lua_gettop(L) + 1 + index;
3167
3168         if(!lua_istable(L, index))
3169                 return false;
3170
3171         lua_pushnil(L);
3172         int rowcount = 0;
3173         while(lua_next(L, index) != 0){
3174                 int colcount = 0;
3175                 // key at index -2 and value at index -1
3176                 if(!lua_istable(L, -1))
3177                         return false;
3178                 int table2 = lua_gettop(L);
3179                 lua_pushnil(L);
3180                 while(lua_next(L, table2) != 0){
3181                         // key at index -2 and value at index -1
3182                         if(!lua_isstring(L, -1))
3183                                 return false;
3184                         recipe.push_back(lua_tostring(L, -1));
3185                         // removes value, keeps key for next iteration
3186                         lua_pop(L, 1);
3187                         colcount++;
3188                 }
3189                 if(rowcount == 0){
3190                         width = colcount;
3191                 } else {
3192                         if(colcount != width)
3193                                 return false;
3194                 }
3195                 // removes value, keeps key for next iteration
3196                 lua_pop(L, 1);
3197                 rowcount++;
3198         }
3199         return width != 0;
3200 }
3201
3202 // helper for register_craft
3203 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3204                 std::vector<std::string> &recipe)
3205 {
3206         if(index < 0)
3207                 index = lua_gettop(L) + 1 + index;
3208
3209         if(!lua_istable(L, index))
3210                 return false;
3211
3212         lua_pushnil(L);
3213         while(lua_next(L, index) != 0){
3214                 // key at index -2 and value at index -1
3215                 if(!lua_isstring(L, -1))
3216                         return false;
3217                 recipe.push_back(lua_tostring(L, -1));
3218                 // removes value, keeps key for next iteration
3219                 lua_pop(L, 1);
3220         }
3221         return true;
3222 }
3223
3224 // helper for register_craft
3225 static bool read_craft_replacements(lua_State *L, int index,
3226                 CraftReplacements &replacements)
3227 {
3228         if(index < 0)
3229                 index = lua_gettop(L) + 1 + index;
3230
3231         if(!lua_istable(L, index))
3232                 return false;
3233
3234         lua_pushnil(L);
3235         while(lua_next(L, index) != 0){
3236                 // key at index -2 and value at index -1
3237                 if(!lua_istable(L, -1))
3238                         return false;
3239                 lua_rawgeti(L, -1, 1);
3240                 if(!lua_isstring(L, -1))
3241                         return false;
3242                 std::string replace_from = lua_tostring(L, -1);
3243                 lua_pop(L, 1);
3244                 lua_rawgeti(L, -1, 2);
3245                 if(!lua_isstring(L, -1))
3246                         return false;
3247                 std::string replace_to = lua_tostring(L, -1);
3248                 lua_pop(L, 1);
3249                 replacements.pairs.push_back(
3250                                 std::make_pair(replace_from, replace_to));
3251                 // removes value, keeps key for next iteration
3252                 lua_pop(L, 1);
3253         }
3254         return true;
3255 }
3256 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3257 static int l_register_craft(lua_State *L)
3258 {
3259         //infostream<<"register_craft"<<std::endl;
3260         luaL_checktype(L, 1, LUA_TTABLE);
3261         int table = 1;
3262
3263         // Get the writable craft definition manager from the server
3264         IWritableCraftDefManager *craftdef =
3265                         get_server(L)->getWritableCraftDefManager();
3266         
3267         std::string type = getstringfield_default(L, table, "type", "shaped");
3268
3269         /*
3270                 CraftDefinitionShaped
3271         */
3272         if(type == "shaped"){
3273                 std::string output = getstringfield_default(L, table, "output", "");
3274                 if(output == "")
3275                         throw LuaError(L, "Crafting definition is missing an output");
3276
3277                 int width = 0;
3278                 std::vector<std::string> recipe;
3279                 lua_getfield(L, table, "recipe");
3280                 if(lua_isnil(L, -1))
3281                         throw LuaError(L, "Crafting definition is missing a recipe"
3282                                         " (output=\"" + output + "\")");
3283                 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3284                         throw LuaError(L, "Invalid crafting recipe"
3285                                         " (output=\"" + output + "\")");
3286
3287                 CraftReplacements replacements;
3288                 lua_getfield(L, table, "replacements");
3289                 if(!lua_isnil(L, -1))
3290                 {
3291                         if(!read_craft_replacements(L, -1, replacements))
3292                                 throw LuaError(L, "Invalid replacements"
3293                                                 " (output=\"" + output + "\")");
3294                 }
3295
3296                 CraftDefinition *def = new CraftDefinitionShaped(
3297                                 output, width, recipe, replacements);
3298                 craftdef->registerCraft(def);
3299         }
3300         /*
3301                 CraftDefinitionShapeless
3302         */
3303         else if(type == "shapeless"){
3304                 std::string output = getstringfield_default(L, table, "output", "");
3305                 if(output == "")
3306                         throw LuaError(L, "Crafting definition (shapeless)"
3307                                         " is missing an output");
3308
3309                 std::vector<std::string> recipe;
3310                 lua_getfield(L, table, "recipe");
3311                 if(lua_isnil(L, -1))
3312                         throw LuaError(L, "Crafting definition (shapeless)"
3313                                         " is missing a recipe"
3314                                         " (output=\"" + output + "\")");
3315                 if(!read_craft_recipe_shapeless(L, -1, recipe))
3316                         throw LuaError(L, "Invalid crafting recipe"
3317                                         " (output=\"" + output + "\")");
3318
3319                 CraftReplacements replacements;
3320                 lua_getfield(L, table, "replacements");
3321                 if(!lua_isnil(L, -1))
3322                 {
3323                         if(!read_craft_replacements(L, -1, replacements))
3324                                 throw LuaError(L, "Invalid replacements"
3325                                                 " (output=\"" + output + "\")");
3326                 }
3327
3328                 CraftDefinition *def = new CraftDefinitionShapeless(
3329                                 output, recipe, replacements);
3330                 craftdef->registerCraft(def);
3331         }
3332         /*
3333                 CraftDefinitionToolRepair
3334         */
3335         else if(type == "toolrepair"){
3336                 float additional_wear = getfloatfield_default(L, table,
3337                                 "additional_wear", 0.0);
3338
3339                 CraftDefinition *def = new CraftDefinitionToolRepair(
3340                                 additional_wear);
3341                 craftdef->registerCraft(def);
3342         }
3343         /*
3344                 CraftDefinitionCooking
3345         */
3346         else if(type == "cooking"){
3347                 std::string output = getstringfield_default(L, table, "output", "");
3348                 if(output == "")
3349                         throw LuaError(L, "Crafting definition (cooking)"
3350                                         " is missing an output");
3351
3352                 std::string recipe = getstringfield_default(L, table, "recipe", "");
3353                 if(recipe == "")
3354                         throw LuaError(L, "Crafting definition (cooking)"
3355                                         " is missing a recipe"
3356                                         " (output=\"" + output + "\")");
3357
3358                 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3359
3360                 CraftDefinition *def = new CraftDefinitionCooking(
3361                                 output, recipe, cooktime);
3362                 craftdef->registerCraft(def);
3363         }
3364         /*
3365                 CraftDefinitionFuel
3366         */
3367         else if(type == "fuel"){
3368                 std::string recipe = getstringfield_default(L, table, "recipe", "");
3369                 if(recipe == "")
3370                         throw LuaError(L, "Crafting definition (fuel)"
3371                                         " is missing a recipe");
3372
3373                 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3374
3375                 CraftDefinition *def = new CraftDefinitionFuel(
3376                                 recipe, burntime);
3377                 craftdef->registerCraft(def);
3378         }
3379         else
3380         {
3381                 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3382         }
3383
3384         lua_pop(L, 1);
3385         return 0; /* number of results */
3386 }
3387
3388 // setting_get(name)
3389 static int l_setting_get(lua_State *L)
3390 {
3391         const char *name = luaL_checkstring(L, 1);
3392         try{
3393                 std::string value = g_settings->get(name);
3394                 lua_pushstring(L, value.c_str());
3395         } catch(SettingNotFoundException &e){
3396                 lua_pushnil(L);
3397         }
3398         return 1;
3399 }
3400
3401 // setting_getbool(name)
3402 static int l_setting_getbool(lua_State *L)
3403 {
3404         const char *name = luaL_checkstring(L, 1);
3405         try{
3406                 bool value = g_settings->getBool(name);
3407                 lua_pushboolean(L, value);
3408         } catch(SettingNotFoundException &e){
3409                 lua_pushnil(L);
3410         }
3411         return 1;
3412 }
3413
3414 // chat_send_all(text)
3415 static int l_chat_send_all(lua_State *L)
3416 {
3417         const char *text = luaL_checkstring(L, 1);
3418         // Get server from registry
3419         Server *server = get_server(L);
3420         // Send
3421         server->notifyPlayers(narrow_to_wide(text));
3422         return 0;
3423 }
3424
3425 // chat_send_player(name, text)
3426 static int l_chat_send_player(lua_State *L)
3427 {
3428         const char *name = luaL_checkstring(L, 1);
3429         const char *text = luaL_checkstring(L, 2);
3430         // Get server from registry
3431         Server *server = get_server(L);
3432         // Send
3433         server->notifyPlayer(name, narrow_to_wide(text));
3434         return 0;
3435 }
3436
3437 // get_player_privs(name, text)
3438 static int l_get_player_privs(lua_State *L)
3439 {
3440         const char *name = luaL_checkstring(L, 1);
3441         // Get server from registry
3442         Server *server = get_server(L);
3443         // Do it
3444         lua_newtable(L);
3445         int table = lua_gettop(L);
3446         u64 privs_i = server->getPlayerAuthPrivs(name);
3447         // Special case for the "name" setting (local player / server owner)
3448         if(name == g_settings->get("name"))
3449                 privs_i = PRIV_ALL;
3450         std::set<std::string> privs_s = privsToSet(privs_i);
3451         for(std::set<std::string>::const_iterator
3452                         i = privs_s.begin(); i != privs_s.end(); i++){
3453                 lua_pushboolean(L, true);
3454                 lua_setfield(L, table, i->c_str());
3455         }
3456         lua_pushvalue(L, table);
3457         return 1;
3458 }
3459
3460 // get_inventory(location)
3461 static int l_get_inventory(lua_State *L)
3462 {
3463         InventoryLocation loc;
3464
3465         std::string type = checkstringfield(L, 1, "type");
3466         if(type == "player"){
3467                 std::string name = checkstringfield(L, 1, "name");
3468                 loc.setPlayer(name);
3469         } else if(type == "node"){
3470                 lua_getfield(L, 1, "pos");
3471                 v3s16 pos = check_v3s16(L, -1);
3472                 loc.setNodeMeta(pos);
3473         }
3474         
3475         if(get_server(L)->getInventory(loc) != NULL)
3476                 InvRef::create(L, loc);
3477         else
3478                 lua_pushnil(L);
3479         return 1;
3480 }
3481
3482 // get_digging_properties(material_properties, tool_digging_properties[, time_from_last_punch])
3483 static int l_get_digging_properties(lua_State *L)
3484 {
3485         MaterialProperties mp = read_material_properties(L, 1);
3486         ToolDiggingProperties tp = read_tool_digging_properties(L, 2);
3487         if(lua_isnoneornil(L, 3))
3488                 push_digging_properties(L, getDiggingProperties(&mp, &tp));
3489         else
3490                 push_digging_properties(L, getDiggingProperties(&mp, &tp,
3491                                         luaL_checknumber(L, 3)));
3492         return 1;
3493 }
3494
3495 // get_hitting_properties(material_properties, tool_digging_properties[, time_from_last_punch])
3496 static int l_get_hitting_properties(lua_State *L)
3497 {
3498         MaterialProperties mp = read_material_properties(L, 1);
3499         ToolDiggingProperties tp = read_tool_digging_properties(L, 2);
3500         if(lua_isnoneornil(L, 3))
3501                 push_hitting_properties(L, getHittingProperties(&mp, &tp));
3502         else
3503                 push_hitting_properties(L, getHittingProperties(&mp, &tp,
3504                                         luaL_checknumber(L, 3)));
3505         return 1;
3506 }
3507
3508 // get_current_modname()
3509 static int l_get_current_modname(lua_State *L)
3510 {
3511         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3512         return 1;
3513 }
3514
3515 // get_modpath(modname)
3516 static int l_get_modpath(lua_State *L)
3517 {
3518         const char *modname = luaL_checkstring(L, 1);
3519         // Do it
3520         const ModSpec *mod = get_server(L)->getModSpec(modname);
3521         if(!mod){
3522                 lua_pushnil(L);
3523                 return 1;
3524         }
3525         lua_pushstring(L, mod->path.c_str());
3526         return 1;
3527 }
3528
3529 static const struct luaL_Reg minetest_f [] = {
3530         {"debug", l_debug},
3531         {"log", l_log},
3532         {"register_item_raw", l_register_item_raw},
3533         {"register_alias_raw", l_register_alias_raw},
3534         {"register_craft", l_register_craft},
3535         {"setting_get", l_setting_get},
3536         {"setting_getbool", l_setting_getbool},
3537         {"chat_send_all", l_chat_send_all},
3538         {"chat_send_player", l_chat_send_player},
3539         {"get_player_privs", l_get_player_privs},
3540         {"get_inventory", l_get_inventory},
3541         {"get_digging_properties", l_get_digging_properties},
3542         {"get_hitting_properties", l_get_hitting_properties},
3543         {"get_current_modname", l_get_current_modname},
3544         {"get_modpath", l_get_modpath},
3545         {NULL, NULL}
3546 };
3547
3548 /*
3549         Main export function
3550 */
3551
3552 void scriptapi_export(lua_State *L, Server *server)
3553 {
3554         realitycheck(L);
3555         assert(lua_checkstack(L, 20));
3556         infostream<<"scriptapi_export"<<std::endl;
3557         StackUnroller stack_unroller(L);
3558
3559         // Store server as light userdata in registry
3560         lua_pushlightuserdata(L, server);
3561         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3562
3563         // Register global functions in table minetest
3564         lua_newtable(L);
3565         luaL_register(L, NULL, minetest_f);
3566         lua_setglobal(L, "minetest");
3567         
3568         // Get the main minetest table
3569         lua_getglobal(L, "minetest");
3570
3571         // Add tables to minetest
3572         
3573         lua_newtable(L);
3574         lua_setfield(L, -2, "object_refs");
3575         lua_newtable(L);
3576         lua_setfield(L, -2, "luaentities");
3577
3578         // Register wrappers
3579         LuaItemStack::Register(L);
3580         InvRef::Register(L);
3581         NodeMetaRef::Register(L);
3582         ObjectRef::Register(L);
3583         EnvRef::Register(L);
3584 }
3585
3586 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3587                 const std::string &modname)
3588 {
3589         ModNameStorer modnamestorer(L, modname);
3590
3591         if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3592                         "0123456789_")){
3593                 errorstream<<"Error loading mod \""<<modname
3594                                 <<"\": modname does not follow naming conventions: "
3595                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3596                 return false;
3597         }
3598         
3599         bool success = false;
3600
3601         try{
3602                 success = script_load(L, scriptpath.c_str());
3603         }
3604         catch(LuaError &e){
3605                 errorstream<<"Error loading mod \""<<modname
3606                                 <<"\": "<<e.what()<<std::endl;
3607         }
3608
3609         return success;
3610 }
3611
3612 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3613 {
3614         realitycheck(L);
3615         assert(lua_checkstack(L, 20));
3616         infostream<<"scriptapi_add_environment"<<std::endl;
3617         StackUnroller stack_unroller(L);
3618
3619         // Create EnvRef on stack
3620         EnvRef::create(L, env);
3621         int envref = lua_gettop(L);
3622
3623         // minetest.env = envref
3624         lua_getglobal(L, "minetest");
3625         luaL_checktype(L, -1, LUA_TTABLE);
3626         lua_pushvalue(L, envref);
3627         lua_setfield(L, -2, "env");
3628
3629         // Store environment as light userdata in registry
3630         lua_pushlightuserdata(L, env);
3631         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3632
3633         /*
3634                 Add ActiveBlockModifiers to environment
3635         */
3636
3637         // Get minetest.registered_abms
3638         lua_getglobal(L, "minetest");
3639         lua_getfield(L, -1, "registered_abms");
3640         luaL_checktype(L, -1, LUA_TTABLE);
3641         int registered_abms = lua_gettop(L);
3642         
3643         if(lua_istable(L, registered_abms)){
3644                 int table = lua_gettop(L);
3645                 lua_pushnil(L);
3646                 while(lua_next(L, table) != 0){
3647                         // key at index -2 and value at index -1
3648                         int id = lua_tonumber(L, -2);
3649                         int current_abm = lua_gettop(L);
3650
3651                         std::set<std::string> trigger_contents;
3652                         lua_getfield(L, current_abm, "nodenames");
3653                         if(lua_istable(L, -1)){
3654                                 int table = lua_gettop(L);
3655                                 lua_pushnil(L);
3656                                 while(lua_next(L, table) != 0){
3657                                         // key at index -2 and value at index -1
3658                                         luaL_checktype(L, -1, LUA_TSTRING);
3659                                         trigger_contents.insert(lua_tostring(L, -1));
3660                                         // removes value, keeps key for next iteration
3661                                         lua_pop(L, 1);
3662                                 }
3663                         } else if(lua_isstring(L, -1)){
3664                                 trigger_contents.insert(lua_tostring(L, -1));
3665                         }
3666                         lua_pop(L, 1);
3667
3668                         std::set<std::string> required_neighbors;
3669                         lua_getfield(L, current_abm, "neighbors");
3670                         if(lua_istable(L, -1)){
3671                                 int table = lua_gettop(L);
3672                                 lua_pushnil(L);
3673                                 while(lua_next(L, table) != 0){
3674                                         // key at index -2 and value at index -1
3675                                         luaL_checktype(L, -1, LUA_TSTRING);
3676                                         required_neighbors.insert(lua_tostring(L, -1));
3677                                         // removes value, keeps key for next iteration
3678                                         lua_pop(L, 1);
3679                                 }
3680                         } else if(lua_isstring(L, -1)){
3681                                 required_neighbors.insert(lua_tostring(L, -1));
3682                         }
3683                         lua_pop(L, 1);
3684
3685                         float trigger_interval = 10.0;
3686                         getfloatfield(L, current_abm, "interval", trigger_interval);
3687
3688                         int trigger_chance = 50;
3689                         getintfield(L, current_abm, "chance", trigger_chance);
3690
3691                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
3692                                         required_neighbors, trigger_interval, trigger_chance);
3693                         
3694                         env->addActiveBlockModifier(abm);
3695
3696                         // removes value, keeps key for next iteration
3697                         lua_pop(L, 1);
3698                 }
3699         }
3700         lua_pop(L, 1);
3701 }
3702
3703 #if 0
3704 // Dump stack top with the dump2 function
3705 static void dump2(lua_State *L, const char *name)
3706 {
3707         // Dump object (debug)
3708         lua_getglobal(L, "dump2");
3709         luaL_checktype(L, -1, LUA_TFUNCTION);
3710         lua_pushvalue(L, -2); // Get previous stack top as first parameter
3711         lua_pushstring(L, name);
3712         if(lua_pcall(L, 2, 0, 0))
3713                 script_error(L, "error: %s", lua_tostring(L, -1));
3714 }
3715 #endif
3716
3717 /*
3718         object_reference
3719 */
3720
3721 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
3722 {
3723         realitycheck(L);
3724         assert(lua_checkstack(L, 20));
3725         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
3726         StackUnroller stack_unroller(L);
3727
3728         // Create object on stack
3729         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
3730         int object = lua_gettop(L);
3731
3732         // Get minetest.object_refs table
3733         lua_getglobal(L, "minetest");
3734         lua_getfield(L, -1, "object_refs");
3735         luaL_checktype(L, -1, LUA_TTABLE);
3736         int objectstable = lua_gettop(L);
3737         
3738         // object_refs[id] = object
3739         lua_pushnumber(L, cobj->getId()); // Push id
3740         lua_pushvalue(L, object); // Copy object to top of stack
3741         lua_settable(L, objectstable);
3742 }
3743
3744 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
3745 {
3746         realitycheck(L);
3747         assert(lua_checkstack(L, 20));
3748         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
3749         StackUnroller stack_unroller(L);
3750
3751         // Get minetest.object_refs table
3752         lua_getglobal(L, "minetest");
3753         lua_getfield(L, -1, "object_refs");
3754         luaL_checktype(L, -1, LUA_TTABLE);
3755         int objectstable = lua_gettop(L);
3756         
3757         // Get object_refs[id]
3758         lua_pushnumber(L, cobj->getId()); // Push id
3759         lua_gettable(L, objectstable);
3760         // Set object reference to NULL
3761         ObjectRef::set_null(L);
3762         lua_pop(L, 1); // pop object
3763
3764         // Set object_refs[id] = nil
3765         lua_pushnumber(L, cobj->getId()); // Push id
3766         lua_pushnil(L);
3767         lua_settable(L, objectstable);
3768 }
3769
3770 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
3771                 const std::string &message)
3772 {
3773         realitycheck(L);
3774         assert(lua_checkstack(L, 20));
3775         StackUnroller stack_unroller(L);
3776
3777         // Get minetest.registered_on_chat_messages
3778         lua_getglobal(L, "minetest");
3779         lua_getfield(L, -1, "registered_on_chat_messages");
3780         luaL_checktype(L, -1, LUA_TTABLE);
3781         int table = lua_gettop(L);
3782         // Foreach
3783         lua_pushnil(L);
3784         while(lua_next(L, table) != 0){
3785                 // key at index -2 and value at index -1
3786                 luaL_checktype(L, -1, LUA_TFUNCTION);
3787                 // Call function
3788                 lua_pushstring(L, name.c_str());
3789                 lua_pushstring(L, message.c_str());
3790                 if(lua_pcall(L, 2, 1, 0))
3791                         script_error(L, "error: %s", lua_tostring(L, -1));
3792                 bool ate = lua_toboolean(L, -1);
3793                 lua_pop(L, 1);
3794                 if(ate)
3795                         return true;
3796                 // value removed, keep key for next iteration
3797         }
3798         return false;
3799 }
3800
3801 /*
3802         misc
3803 */
3804
3805 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
3806 {
3807         realitycheck(L);
3808         assert(lua_checkstack(L, 20));
3809         StackUnroller stack_unroller(L);
3810
3811         // Get minetest.registered_on_newplayers
3812         lua_getglobal(L, "minetest");
3813         lua_getfield(L, -1, "registered_on_newplayers");
3814         luaL_checktype(L, -1, LUA_TTABLE);
3815         int table = lua_gettop(L);
3816         // Foreach
3817         lua_pushnil(L);
3818         while(lua_next(L, table) != 0){
3819                 // key at index -2 and value at index -1
3820                 luaL_checktype(L, -1, LUA_TFUNCTION);
3821                 // Call function
3822                 objectref_get_or_create(L, player);
3823                 if(lua_pcall(L, 1, 0, 0))
3824                         script_error(L, "error: %s", lua_tostring(L, -1));
3825                 // value removed, keep key for next iteration
3826         }
3827 }
3828
3829 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
3830 {
3831     realitycheck(L);
3832     assert(lua_checkstack(L, 20));
3833     StackUnroller stack_unroller(L);
3834     
3835     // Get minetest.registered_on_dieplayers
3836     lua_getglobal(L, "minetest");
3837     lua_getfield(L, -1, "registered_on_dieplayers");
3838     luaL_checktype(L, -1, LUA_TTABLE);
3839     int table = lua_gettop(L);
3840     // Foreach
3841     lua_pushnil(L);
3842     while(lua_next(L, table) != 0){
3843         // key at index -2 and value at index -1
3844        luaL_checktype(L, -1, LUA_TFUNCTION);
3845         // Call function
3846        objectref_get_or_create(L, player);
3847         if(lua_pcall(L, 1, 0, 0))
3848             script_error(L, "error: %s", lua_tostring(L, -1));
3849         // value removed, keep key for next iteration
3850     }
3851 }
3852
3853
3854 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
3855 {
3856         realitycheck(L);
3857         assert(lua_checkstack(L, 20));
3858         StackUnroller stack_unroller(L);
3859
3860         dstream<<"player: "<<player<<"   id: "<<player->getId()<<std::endl;
3861
3862         bool positioning_handled_by_some = false;
3863
3864         // Get minetest.registered_on_respawnplayers
3865         lua_getglobal(L, "minetest");
3866         lua_getfield(L, -1, "registered_on_respawnplayers");
3867         luaL_checktype(L, -1, LUA_TTABLE);
3868         int table = lua_gettop(L);
3869         // Foreach
3870         lua_pushnil(L);
3871         while(lua_next(L, table) != 0){
3872                 // key at index -2 and value at index -1
3873                 luaL_checktype(L, -1, LUA_TFUNCTION);
3874                 // Call function
3875                 objectref_get_or_create(L, player);
3876                 if(lua_pcall(L, 1, 1, 0))
3877                         script_error(L, "error: %s", lua_tostring(L, -1));
3878                 bool positioning_handled = lua_toboolean(L, -1);
3879                 lua_pop(L, 1);
3880                 if(positioning_handled)
3881                         positioning_handled_by_some = true;
3882                 // value removed, keep key for next iteration
3883         }
3884         return positioning_handled_by_some;
3885 }
3886
3887 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
3888 {
3889         lua_getglobal(L, "minetest");
3890         lua_getfield(L, -1, "creative_inventory");
3891         luaL_checktype(L, -1, LUA_TTABLE);
3892         inventory_set_list_from_lua(&player->inventory, "main", L, -1,
3893                         PLAYER_INVENTORY_SIZE);
3894 }
3895
3896 /*
3897         item callbacks and node callbacks
3898 */
3899
3900 // Retrieves minetest.registered_items[name][callbackname]
3901 // If that is nil or on error, return false and stack is unchanged
3902 // If that is a function, returns true and pushes the
3903 // function onto the stack
3904 static bool get_item_callback(lua_State *L,
3905                 const char *name, const char *callbackname)
3906 {
3907         lua_getglobal(L, "minetest");
3908         lua_getfield(L, -1, "registered_items");
3909         lua_remove(L, -2);
3910         luaL_checktype(L, -1, LUA_TTABLE);
3911         lua_getfield(L, -1, name);
3912         lua_remove(L, -2);
3913         // Should be a table
3914         if(lua_type(L, -1) != LUA_TTABLE)
3915         {
3916                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
3917                 lua_pop(L, 1);
3918                 return false;
3919         }
3920         lua_getfield(L, -1, callbackname);
3921         lua_remove(L, -2);
3922         // Should be a function or nil
3923         if(lua_type(L, -1) == LUA_TFUNCTION)
3924         {
3925                 return true;
3926         }
3927         else if(lua_isnil(L, -1))
3928         {
3929                 lua_pop(L, 1);
3930                 return false;
3931         }
3932         else
3933         {
3934                 errorstream<<"Item \""<<name<<"\" callback \""
3935                         <<callbackname<<" is not a function"<<std::endl;
3936                 lua_pop(L, 1);
3937                 return false;
3938         }
3939 }
3940
3941 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
3942                 ServerActiveObject *dropper, v3f pos)
3943 {
3944         realitycheck(L);
3945         assert(lua_checkstack(L, 20));
3946         StackUnroller stack_unroller(L);
3947
3948         // Push callback function on stack
3949         if(!get_item_callback(L, item.name.c_str(), "on_drop"))
3950                 return false;
3951
3952         // Call function
3953         LuaItemStack::create(L, item);
3954         objectref_get_or_create(L, dropper);
3955         pushFloatPos(L, pos);
3956         if(lua_pcall(L, 3, 1, 0))
3957                 script_error(L, "error: %s", lua_tostring(L, -1));
3958         if(!lua_isnil(L, -1))
3959                 item = read_item(L, -1);
3960         return true;
3961 }
3962
3963 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
3964                 ServerActiveObject *placer, const PointedThing &pointed)
3965 {
3966         realitycheck(L);
3967         assert(lua_checkstack(L, 20));
3968         StackUnroller stack_unroller(L);
3969
3970         // Push callback function on stack
3971         if(!get_item_callback(L, item.name.c_str(), "on_place"))
3972                 return false;
3973
3974         // Call function
3975         LuaItemStack::create(L, item);
3976         objectref_get_or_create(L, placer);
3977         push_pointed_thing(L, pointed);
3978         if(lua_pcall(L, 3, 1, 0))
3979                 script_error(L, "error: %s", lua_tostring(L, -1));
3980         if(!lua_isnil(L, -1))
3981                 item = read_item(L, -1);
3982         return true;
3983 }
3984
3985 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
3986                 ServerActiveObject *user, const PointedThing &pointed)
3987 {
3988         realitycheck(L);
3989         assert(lua_checkstack(L, 20));
3990         StackUnroller stack_unroller(L);
3991
3992         // Push callback function on stack
3993         if(!get_item_callback(L, item.name.c_str(), "on_use"))
3994                 return false;
3995
3996         // Call function
3997         LuaItemStack::create(L, item);
3998         objectref_get_or_create(L, user);
3999         push_pointed_thing(L, pointed);
4000         if(lua_pcall(L, 3, 1, 0))
4001                 script_error(L, "error: %s", lua_tostring(L, -1));
4002         if(!lua_isnil(L, -1))
4003                 item = read_item(L, -1);
4004         return true;
4005 }
4006
4007 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4008                 ServerActiveObject *puncher)
4009 {
4010         realitycheck(L);
4011         assert(lua_checkstack(L, 20));
4012         StackUnroller stack_unroller(L);
4013
4014         INodeDefManager *ndef = get_server(L)->ndef();
4015
4016         // Push callback function on stack
4017         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4018                 return false;
4019
4020         // Call function
4021         push_v3s16(L, pos);
4022         pushnode(L, node, ndef);
4023         objectref_get_or_create(L, puncher);
4024         if(lua_pcall(L, 3, 0, 0))
4025                 script_error(L, "error: %s", lua_tostring(L, -1));
4026         return true;
4027 }
4028
4029 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4030                 ServerActiveObject *digger)
4031 {
4032         realitycheck(L);
4033         assert(lua_checkstack(L, 20));
4034         StackUnroller stack_unroller(L);
4035
4036         INodeDefManager *ndef = get_server(L)->ndef();
4037
4038         // Push callback function on stack
4039         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4040                 return false;
4041
4042         // Call function
4043         push_v3s16(L, pos);
4044         pushnode(L, node, ndef);
4045         objectref_get_or_create(L, digger);
4046         if(lua_pcall(L, 3, 0, 0))
4047                 script_error(L, "error: %s", lua_tostring(L, -1));
4048         return true;
4049 }
4050
4051 /*
4052         environment
4053 */
4054
4055 void scriptapi_environment_step(lua_State *L, float dtime)
4056 {
4057         realitycheck(L);
4058         assert(lua_checkstack(L, 20));
4059         //infostream<<"scriptapi_environment_step"<<std::endl;
4060         StackUnroller stack_unroller(L);
4061
4062         // Get minetest.registered_globalsteps
4063         lua_getglobal(L, "minetest");
4064         lua_getfield(L, -1, "registered_globalsteps");
4065         luaL_checktype(L, -1, LUA_TTABLE);
4066         int table = lua_gettop(L);
4067         // Foreach
4068         lua_pushnil(L);
4069         while(lua_next(L, table) != 0){
4070                 // key at index -2 and value at index -1
4071                 luaL_checktype(L, -1, LUA_TFUNCTION);
4072                 // Call function
4073                 lua_pushnumber(L, dtime);
4074                 if(lua_pcall(L, 1, 0, 0))
4075                         script_error(L, "error: %s", lua_tostring(L, -1));
4076                 // value removed, keep key for next iteration
4077         }
4078 }
4079
4080 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
4081 {
4082         realitycheck(L);
4083         assert(lua_checkstack(L, 20));
4084         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4085         StackUnroller stack_unroller(L);
4086
4087         // Get minetest.registered_on_generateds
4088         lua_getglobal(L, "minetest");
4089         lua_getfield(L, -1, "registered_on_generateds");
4090         luaL_checktype(L, -1, LUA_TTABLE);
4091         int table = lua_gettop(L);
4092         // Foreach
4093         lua_pushnil(L);
4094         while(lua_next(L, table) != 0){
4095                 // key at index -2 and value at index -1
4096                 luaL_checktype(L, -1, LUA_TFUNCTION);
4097                 // Call function
4098                 push_v3s16(L, minp);
4099                 push_v3s16(L, maxp);
4100                 if(lua_pcall(L, 2, 0, 0))
4101                         script_error(L, "error: %s", lua_tostring(L, -1));
4102                 // value removed, keep key for next iteration
4103         }
4104 }
4105
4106 /*
4107         luaentity
4108 */
4109
4110 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name,
4111                 const std::string &staticdata)
4112 {
4113         realitycheck(L);
4114         assert(lua_checkstack(L, 20));
4115         infostream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4116                         <<name<<"\""<<std::endl;
4117         StackUnroller stack_unroller(L);
4118         
4119         // Get minetest.registered_entities[name]
4120         lua_getglobal(L, "minetest");
4121         lua_getfield(L, -1, "registered_entities");
4122         luaL_checktype(L, -1, LUA_TTABLE);
4123         lua_pushstring(L, name);
4124         lua_gettable(L, -2);
4125         // Should be a table, which we will use as a prototype
4126         //luaL_checktype(L, -1, LUA_TTABLE);
4127         if(lua_type(L, -1) != LUA_TTABLE){
4128                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4129                 return false;
4130         }
4131         int prototype_table = lua_gettop(L);
4132         //dump2(L, "prototype_table");
4133         
4134         // Create entity object
4135         lua_newtable(L);
4136         int object = lua_gettop(L);
4137
4138         // Set object metatable
4139         lua_pushvalue(L, prototype_table);
4140         lua_setmetatable(L, -2);
4141         
4142         // Add object reference
4143         // This should be userdata with metatable ObjectRef
4144         objectref_get(L, id);
4145         luaL_checktype(L, -1, LUA_TUSERDATA);
4146         if(!luaL_checkudata(L, -1, "ObjectRef"))
4147                 luaL_typerror(L, -1, "ObjectRef");
4148         lua_setfield(L, -2, "object");
4149
4150         // minetest.luaentities[id] = object
4151         lua_getglobal(L, "minetest");
4152         lua_getfield(L, -1, "luaentities");
4153         luaL_checktype(L, -1, LUA_TTABLE);
4154         lua_pushnumber(L, id); // Push id
4155         lua_pushvalue(L, object); // Copy object to top of stack
4156         lua_settable(L, -3);
4157         
4158         // Get on_activate function
4159         lua_pushvalue(L, object);
4160         lua_getfield(L, -1, "on_activate");
4161         if(!lua_isnil(L, -1)){
4162                 luaL_checktype(L, -1, LUA_TFUNCTION);
4163                 lua_pushvalue(L, object); // self
4164                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4165                 // Call with 2 arguments, 0 results
4166                 if(lua_pcall(L, 2, 0, 0))
4167                         script_error(L, "error running function %s:on_activate: %s\n",
4168                                         name, lua_tostring(L, -1));
4169         }
4170         
4171         return true;
4172 }
4173
4174 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4175 {
4176         realitycheck(L);
4177         assert(lua_checkstack(L, 20));
4178         infostream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4179
4180         // Get minetest.luaentities table
4181         lua_getglobal(L, "minetest");
4182         lua_getfield(L, -1, "luaentities");
4183         luaL_checktype(L, -1, LUA_TTABLE);
4184         int objectstable = lua_gettop(L);
4185         
4186         // Set luaentities[id] = nil
4187         lua_pushnumber(L, id); // Push id
4188         lua_pushnil(L);
4189         lua_settable(L, objectstable);
4190         
4191         lua_pop(L, 2); // pop luaentities, minetest
4192 }
4193
4194 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4195 {
4196         realitycheck(L);
4197         assert(lua_checkstack(L, 20));
4198         infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4199         StackUnroller stack_unroller(L);
4200
4201         // Get minetest.luaentities[id]
4202         luaentity_get(L, id);
4203         int object = lua_gettop(L);
4204         
4205         // Get get_staticdata function
4206         lua_pushvalue(L, object);
4207         lua_getfield(L, -1, "get_staticdata");
4208         if(lua_isnil(L, -1))
4209                 return "";
4210         
4211         luaL_checktype(L, -1, LUA_TFUNCTION);
4212         lua_pushvalue(L, object); // self
4213         // Call with 1 arguments, 1 results
4214         if(lua_pcall(L, 1, 1, 0))
4215                 script_error(L, "error running function get_staticdata: %s\n",
4216                                 lua_tostring(L, -1));
4217         
4218         size_t len=0;
4219         const char *s = lua_tolstring(L, -1, &len);
4220         return std::string(s, len);
4221 }
4222
4223 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4224                 LuaEntityProperties *prop)
4225 {
4226         realitycheck(L);
4227         assert(lua_checkstack(L, 20));
4228         infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4229         StackUnroller stack_unroller(L);
4230
4231         // Get minetest.luaentities[id]
4232         luaentity_get(L, id);
4233         //int object = lua_gettop(L);
4234
4235         /* Read stuff */
4236         
4237         getboolfield(L, -1, "physical", prop->physical);
4238
4239         getfloatfield(L, -1, "weight", prop->weight);
4240
4241         lua_getfield(L, -1, "collisionbox");
4242         if(lua_istable(L, -1))
4243                 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4244         lua_pop(L, 1);
4245
4246         getstringfield(L, -1, "visual", prop->visual);
4247         
4248         lua_getfield(L, -1, "visual_size");
4249         if(lua_istable(L, -1))
4250                 prop->visual_size = read_v2f(L, -1);
4251         lua_pop(L, 1);
4252
4253         lua_getfield(L, -1, "textures");
4254         if(lua_istable(L, -1)){
4255                 prop->textures.clear();
4256                 int table = lua_gettop(L);
4257                 lua_pushnil(L);
4258                 while(lua_next(L, table) != 0){
4259                         // key at index -2 and value at index -1
4260                         if(lua_isstring(L, -1))
4261                                 prop->textures.push_back(lua_tostring(L, -1));
4262                         else
4263                                 prop->textures.push_back("");
4264                         // removes value, keeps key for next iteration
4265                         lua_pop(L, 1);
4266                 }
4267         }
4268         lua_pop(L, 1);
4269         
4270         lua_getfield(L, -1, "spritediv");
4271         if(lua_istable(L, -1))
4272                 prop->spritediv = read_v2s16(L, -1);
4273         lua_pop(L, 1);
4274
4275         lua_getfield(L, -1, "initial_sprite_basepos");
4276         if(lua_istable(L, -1))
4277                 prop->initial_sprite_basepos = read_v2s16(L, -1);
4278         lua_pop(L, 1);
4279 }
4280
4281 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4282 {
4283         realitycheck(L);
4284         assert(lua_checkstack(L, 20));
4285         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4286         StackUnroller stack_unroller(L);
4287
4288         // Get minetest.luaentities[id]
4289         luaentity_get(L, id);
4290         int object = lua_gettop(L);
4291         // State: object is at top of stack
4292         // Get step function
4293         lua_getfield(L, -1, "on_step");
4294         if(lua_isnil(L, -1))
4295                 return;
4296         luaL_checktype(L, -1, LUA_TFUNCTION);
4297         lua_pushvalue(L, object); // self
4298         lua_pushnumber(L, dtime); // dtime
4299         // Call with 2 arguments, 0 results
4300         if(lua_pcall(L, 2, 0, 0))
4301                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4302 }
4303
4304 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch)
4305 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4306                 ServerActiveObject *puncher, float time_from_last_punch)
4307 {
4308         realitycheck(L);
4309         assert(lua_checkstack(L, 20));
4310         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4311         StackUnroller stack_unroller(L);
4312
4313         // Get minetest.luaentities[id]
4314         luaentity_get(L, id);
4315         int object = lua_gettop(L);
4316         // State: object is at top of stack
4317         // Get function
4318         lua_getfield(L, -1, "on_punch");
4319         if(lua_isnil(L, -1))
4320                 return;
4321         luaL_checktype(L, -1, LUA_TFUNCTION);
4322         lua_pushvalue(L, object); // self
4323         objectref_get_or_create(L, puncher); // Clicker reference
4324         lua_pushnumber(L, time_from_last_punch);
4325         // Call with 2 arguments, 0 results
4326         if(lua_pcall(L, 3, 0, 0))
4327                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4328 }
4329
4330 // Calls entity:on_rightclick(ObjectRef clicker)
4331 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4332                 ServerActiveObject *clicker)
4333 {
4334         realitycheck(L);
4335         assert(lua_checkstack(L, 20));
4336         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4337         StackUnroller stack_unroller(L);
4338
4339         // Get minetest.luaentities[id]
4340         luaentity_get(L, id);
4341         int object = lua_gettop(L);
4342         // State: object is at top of stack
4343         // Get function
4344         lua_getfield(L, -1, "on_rightclick");
4345         if(lua_isnil(L, -1))
4346                 return;
4347         luaL_checktype(L, -1, LUA_TFUNCTION);
4348         lua_pushvalue(L, object); // self
4349         objectref_get_or_create(L, clicker); // Clicker reference
4350         // Call with 2 arguments, 0 results
4351         if(lua_pcall(L, 2, 0, 0))
4352                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
4353 }
4354