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