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