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