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