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