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