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