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