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