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