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