]> git.lizzy.rs Git - dragonfireclient.git/blob - src/scriptapi.cpp
Reshape inventory menu code
[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         // is_player(self)
2688         static int l_is_player(lua_State *L)
2689         {
2690                 ObjectRef *ref = checkobject(L, 1);
2691                 Player *player = getplayer(ref);
2692                 lua_pushboolean(L, (player != NULL));
2693                 return 1;
2694         }
2695         
2696         // get_player_name(self)
2697         static int l_get_player_name(lua_State *L)
2698         {
2699                 ObjectRef *ref = checkobject(L, 1);
2700                 Player *player = getplayer(ref);
2701                 if(player == NULL){
2702                         lua_pushlstring(L, "", 0);
2703                         return 1;
2704                 }
2705                 // Do it
2706                 lua_pushstring(L, player->getName());
2707                 return 1;
2708         }
2709         
2710         // get_look_dir(self)
2711         static int l_get_look_dir(lua_State *L)
2712         {
2713                 ObjectRef *ref = checkobject(L, 1);
2714                 Player *player = getplayer(ref);
2715                 if(player == NULL) return 0;
2716                 // Do it
2717                 float pitch = player->getRadPitch();
2718                 float yaw = player->getRadYaw();
2719                 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2720                 push_v3f(L, v);
2721                 return 1;
2722         }
2723
2724         // get_look_pitch(self)
2725         static int l_get_look_pitch(lua_State *L)
2726         {
2727                 ObjectRef *ref = checkobject(L, 1);
2728                 Player *player = getplayer(ref);
2729                 if(player == NULL) return 0;
2730                 // Do it
2731                 lua_pushnumber(L, player->getRadPitch());
2732                 return 1;
2733         }
2734
2735         // get_look_yaw(self)
2736         static int l_get_look_yaw(lua_State *L)
2737         {
2738                 ObjectRef *ref = checkobject(L, 1);
2739                 Player *player = getplayer(ref);
2740                 if(player == NULL) return 0;
2741                 // Do it
2742                 lua_pushnumber(L, player->getRadYaw());
2743                 return 1;
2744         }
2745
2746 public:
2747         ObjectRef(ServerActiveObject *object):
2748                 m_object(object)
2749         {
2750                 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2751         }
2752
2753         ~ObjectRef()
2754         {
2755                 /*if(m_object)
2756                         infostream<<"ObjectRef destructing for id="
2757                                         <<m_object->getId()<<std::endl;
2758                 else
2759                         infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2760         }
2761
2762         // Creates an ObjectRef and leaves it on top of stack
2763         // Not callable from Lua; all references are created on the C side.
2764         static void create(lua_State *L, ServerActiveObject *object)
2765         {
2766                 ObjectRef *o = new ObjectRef(object);
2767                 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2768                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2769                 luaL_getmetatable(L, className);
2770                 lua_setmetatable(L, -2);
2771         }
2772
2773         static void set_null(lua_State *L)
2774         {
2775                 ObjectRef *o = checkobject(L, -1);
2776                 o->m_object = NULL;
2777         }
2778         
2779         static void Register(lua_State *L)
2780         {
2781                 lua_newtable(L);
2782                 int methodtable = lua_gettop(L);
2783                 luaL_newmetatable(L, className);
2784                 int metatable = lua_gettop(L);
2785
2786                 lua_pushliteral(L, "__metatable");
2787                 lua_pushvalue(L, methodtable);
2788                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2789
2790                 lua_pushliteral(L, "__index");
2791                 lua_pushvalue(L, methodtable);
2792                 lua_settable(L, metatable);
2793
2794                 lua_pushliteral(L, "__gc");
2795                 lua_pushcfunction(L, gc_object);
2796                 lua_settable(L, metatable);
2797
2798                 lua_pop(L, 1);  // drop metatable
2799
2800                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2801                 lua_pop(L, 1);  // drop methodtable
2802
2803                 // Cannot be created from Lua
2804                 //lua_register(L, className, create_object);
2805         }
2806 };
2807 const char ObjectRef::className[] = "ObjectRef";
2808 const luaL_reg ObjectRef::methods[] = {
2809         // ServerActiveObject
2810         method(ObjectRef, remove),
2811         method(ObjectRef, getpos),
2812         method(ObjectRef, setpos),
2813         method(ObjectRef, moveto),
2814         method(ObjectRef, punch),
2815         method(ObjectRef, right_click),
2816         method(ObjectRef, set_hp),
2817         method(ObjectRef, get_hp),
2818         method(ObjectRef, get_inventory),
2819         method(ObjectRef, get_wield_list),
2820         method(ObjectRef, get_wield_index),
2821         method(ObjectRef, get_wielded_item),
2822         method(ObjectRef, set_wielded_item),
2823         method(ObjectRef, set_armor_groups),
2824         method(ObjectRef, set_properties),
2825         // LuaEntitySAO-only
2826         method(ObjectRef, setvelocity),
2827         method(ObjectRef, getvelocity),
2828         method(ObjectRef, setacceleration),
2829         method(ObjectRef, getacceleration),
2830         method(ObjectRef, setyaw),
2831         method(ObjectRef, getyaw),
2832         method(ObjectRef, settexturemod),
2833         method(ObjectRef, setsprite),
2834         method(ObjectRef, get_entity_name),
2835         method(ObjectRef, get_luaentity),
2836         // Player-only
2837         method(ObjectRef, get_player_name),
2838         method(ObjectRef, get_look_dir),
2839         method(ObjectRef, get_look_pitch),
2840         method(ObjectRef, get_look_yaw),
2841         {0,0}
2842 };
2843
2844 // Creates a new anonymous reference if id=0
2845 static void objectref_get_or_create(lua_State *L,
2846                 ServerActiveObject *cobj)
2847 {
2848         if(cobj->getId() == 0){
2849                 ObjectRef::create(L, cobj);
2850         } else {
2851                 objectref_get(L, cobj->getId());
2852         }
2853 }
2854
2855
2856 /*
2857   PerlinNoise
2858  */
2859
2860 class LuaPerlinNoise
2861 {
2862 private:
2863         int seed;
2864         int octaves;
2865         double persistence;
2866         double scale;
2867         static const char className[];
2868         static const luaL_reg methods[];
2869
2870         // Exported functions
2871
2872         // garbage collector
2873         static int gc_object(lua_State *L)
2874         {
2875                 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
2876                 delete o;
2877                 return 0;
2878         }
2879
2880         static int l_get2d(lua_State *L)
2881         {
2882                 LuaPerlinNoise *o = checkobject(L, 1);
2883                 v2f pos2d = read_v2f(L,2);
2884                 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
2885                 lua_pushnumber(L, val);
2886                 return 1;
2887         }
2888         static int l_get3d(lua_State *L)
2889         {
2890                 LuaPerlinNoise *o = checkobject(L, 1);
2891                 v3f pos3d = read_v3f(L,2);
2892                 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
2893                 lua_pushnumber(L, val);
2894                 return 1;
2895         }
2896
2897 public:
2898         LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
2899                         double a_scale):
2900                 seed(a_seed),
2901                 octaves(a_octaves),
2902                 persistence(a_persistence),
2903                 scale(a_scale)
2904         {
2905         }
2906
2907         ~LuaPerlinNoise()
2908         {
2909         }
2910
2911         // LuaPerlinNoise(seed, octaves, persistence, scale)
2912         // Creates an LuaPerlinNoise and leaves it on top of stack
2913         static int create_object(lua_State *L)
2914         {
2915                 int seed = luaL_checkint(L, 1);
2916                 int octaves = luaL_checkint(L, 2);
2917                 double persistence = luaL_checknumber(L, 3);
2918                 double scale = luaL_checknumber(L, 4);
2919                 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
2920                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2921                 luaL_getmetatable(L, className);
2922                 lua_setmetatable(L, -2);
2923                 return 1;
2924         }
2925
2926         static LuaPerlinNoise* checkobject(lua_State *L, int narg)
2927         {
2928                 luaL_checktype(L, narg, LUA_TUSERDATA);
2929                 void *ud = luaL_checkudata(L, narg, className);
2930                 if(!ud) luaL_typerror(L, narg, className);
2931                 return *(LuaPerlinNoise**)ud;  // unbox pointer
2932         }
2933
2934         static void Register(lua_State *L)
2935         {
2936                 lua_newtable(L);
2937                 int methodtable = lua_gettop(L);
2938                 luaL_newmetatable(L, className);
2939                 int metatable = lua_gettop(L);
2940
2941                 lua_pushliteral(L, "__metatable");
2942                 lua_pushvalue(L, methodtable);
2943                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2944
2945                 lua_pushliteral(L, "__index");
2946                 lua_pushvalue(L, methodtable);
2947                 lua_settable(L, metatable);
2948
2949                 lua_pushliteral(L, "__gc");
2950                 lua_pushcfunction(L, gc_object);
2951                 lua_settable(L, metatable);
2952
2953                 lua_pop(L, 1);  // drop metatable
2954
2955                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2956                 lua_pop(L, 1);  // drop methodtable
2957
2958                 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
2959                 lua_register(L, className, create_object);
2960         }
2961 };
2962 const char LuaPerlinNoise::className[] = "PerlinNoise";
2963 const luaL_reg LuaPerlinNoise::methods[] = {
2964         method(LuaPerlinNoise, get2d),
2965         method(LuaPerlinNoise, get3d),
2966         {0,0}
2967 };
2968
2969 /*
2970         EnvRef
2971 */
2972
2973 class EnvRef
2974 {
2975 private:
2976         ServerEnvironment *m_env;
2977
2978         static const char className[];
2979         static const luaL_reg methods[];
2980
2981         static int gc_object(lua_State *L) {
2982                 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
2983                 delete o;
2984                 return 0;
2985         }
2986
2987         static EnvRef *checkobject(lua_State *L, int narg)
2988         {
2989                 luaL_checktype(L, narg, LUA_TUSERDATA);
2990                 void *ud = luaL_checkudata(L, narg, className);
2991                 if(!ud) luaL_typerror(L, narg, className);
2992                 return *(EnvRef**)ud;  // unbox pointer
2993         }
2994         
2995         // Exported functions
2996
2997         // EnvRef:set_node(pos, node)
2998         // pos = {x=num, y=num, z=num}
2999         static int l_set_node(lua_State *L)
3000         {
3001                 //infostream<<"EnvRef::l_set_node()"<<std::endl;
3002                 EnvRef *o = checkobject(L, 1);
3003                 ServerEnvironment *env = o->m_env;
3004                 if(env == NULL) return 0;
3005                 // pos
3006                 v3s16 pos = read_v3s16(L, 2);
3007                 // content
3008                 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3009                 // Do it
3010                 // Call destructor
3011                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3012                 scriptapi_node_on_destruct(L, pos, n_old);
3013                 // Replace node
3014                 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3015                 lua_pushboolean(L, succeeded);
3016                 // Call constructor
3017                 if(succeeded)
3018                         scriptapi_node_on_construct(L, pos, n);
3019                 return 1;
3020         }
3021
3022         static int l_add_node(lua_State *L)
3023         {
3024                 return l_set_node(L);
3025         }
3026
3027         // EnvRef:remove_node(pos)
3028         // pos = {x=num, y=num, z=num}
3029         static int l_remove_node(lua_State *L)
3030         {
3031                 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
3032                 EnvRef *o = checkobject(L, 1);
3033                 ServerEnvironment *env = o->m_env;
3034                 if(env == NULL) return 0;
3035                 // pos
3036                 v3s16 pos = read_v3s16(L, 2);
3037                 // Do it
3038                 // Call destructor
3039                 MapNode n = env->getMap().getNodeNoEx(pos);
3040                 scriptapi_node_on_destruct(L, pos, n);
3041                 // Replace with air
3042                 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3043                 lua_pushboolean(L, succeeded);
3044                 // Air doesn't require constructor
3045                 return 1;
3046         }
3047
3048         // EnvRef:get_node(pos)
3049         // pos = {x=num, y=num, z=num}
3050         static int l_get_node(lua_State *L)
3051         {
3052                 //infostream<<"EnvRef::l_get_node()"<<std::endl;
3053                 EnvRef *o = checkobject(L, 1);
3054                 ServerEnvironment *env = o->m_env;
3055                 if(env == NULL) return 0;
3056                 // pos
3057                 v3s16 pos = read_v3s16(L, 2);
3058                 // Do it
3059                 MapNode n = env->getMap().getNodeNoEx(pos);
3060                 // Return node
3061                 pushnode(L, n, env->getGameDef()->ndef());
3062                 return 1;
3063         }
3064
3065         // EnvRef:get_node_or_nil(pos)
3066         // pos = {x=num, y=num, z=num}
3067         static int l_get_node_or_nil(lua_State *L)
3068         {
3069                 //infostream<<"EnvRef::l_get_node()"<<std::endl;
3070                 EnvRef *o = checkobject(L, 1);
3071                 ServerEnvironment *env = o->m_env;
3072                 if(env == NULL) return 0;
3073                 // pos
3074                 v3s16 pos = read_v3s16(L, 2);
3075                 // Do it
3076                 try{
3077                         MapNode n = env->getMap().getNode(pos);
3078                         // Return node
3079                         pushnode(L, n, env->getGameDef()->ndef());
3080                         return 1;
3081                 } catch(InvalidPositionException &e)
3082                 {
3083                         lua_pushnil(L);
3084                         return 1;
3085                 }
3086         }
3087
3088         // EnvRef:get_node_light(pos, timeofday)
3089         // pos = {x=num, y=num, z=num}
3090         // timeofday: nil = current time, 0 = night, 0.5 = day
3091         static int l_get_node_light(lua_State *L)
3092         {
3093                 EnvRef *o = checkobject(L, 1);
3094                 ServerEnvironment *env = o->m_env;
3095                 if(env == NULL) return 0;
3096                 // Do it
3097                 v3s16 pos = read_v3s16(L, 2);
3098                 u32 time_of_day = env->getTimeOfDay();
3099                 if(lua_isnumber(L, 3))
3100                         time_of_day = 24000.0 * lua_tonumber(L, 3);
3101                 time_of_day %= 24000;
3102                 u32 dnr = time_to_daynight_ratio(time_of_day);
3103                 MapNode n = env->getMap().getNodeNoEx(pos);
3104                 try{
3105                         MapNode n = env->getMap().getNode(pos);
3106                         INodeDefManager *ndef = env->getGameDef()->ndef();
3107                         lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3108                         return 1;
3109                 } catch(InvalidPositionException &e)
3110                 {
3111                         lua_pushnil(L);
3112                         return 1;
3113                 }
3114         }
3115
3116         // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3117         // pos = {x=num, y=num, z=num}
3118         static int l_add_entity(lua_State *L)
3119         {
3120                 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3121                 EnvRef *o = checkobject(L, 1);
3122                 ServerEnvironment *env = o->m_env;
3123                 if(env == NULL) return 0;
3124                 // pos
3125                 v3f pos = checkFloatPos(L, 2);
3126                 // content
3127                 const char *name = luaL_checkstring(L, 3);
3128                 // Do it
3129                 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3130                 int objectid = env->addActiveObject(obj);
3131                 // If failed to add, return nothing (reads as nil)
3132                 if(objectid == 0)
3133                         return 0;
3134                 // Return ObjectRef
3135                 objectref_get_or_create(L, obj);
3136                 return 1;
3137         }
3138
3139         // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3140         // pos = {x=num, y=num, z=num}
3141         static int l_add_item(lua_State *L)
3142         {
3143                 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3144                 EnvRef *o = checkobject(L, 1);
3145                 ServerEnvironment *env = o->m_env;
3146                 if(env == NULL) return 0;
3147                 // pos
3148                 v3f pos = checkFloatPos(L, 2);
3149                 // item
3150                 ItemStack item = read_item(L, 3);
3151                 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3152                         return 0;
3153                 // Use minetest.spawn_item to spawn a __builtin:item
3154                 lua_getglobal(L, "minetest");
3155                 lua_getfield(L, -1, "spawn_item");
3156                 if(lua_isnil(L, -1))
3157                         return 0;
3158                 lua_pushvalue(L, 2);
3159                 lua_pushstring(L, item.getItemString().c_str());
3160                 if(lua_pcall(L, 2, 1, 0))
3161                         script_error(L, "error: %s", lua_tostring(L, -1));
3162                 return 1;
3163                 /*lua_pushvalue(L, 1);
3164                 lua_pushstring(L, "__builtin:item");
3165                 lua_pushstring(L, item.getItemString().c_str());
3166                 return l_add_entity(L);*/
3167                 /*// Do it
3168                 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3169                 int objectid = env->addActiveObject(obj);
3170                 // If failed to add, return nothing (reads as nil)
3171                 if(objectid == 0)
3172                         return 0;
3173                 // Return ObjectRef
3174                 objectref_get_or_create(L, obj);
3175                 return 1;*/
3176         }
3177
3178         // EnvRef:add_rat(pos)
3179         // pos = {x=num, y=num, z=num}
3180         static int l_add_rat(lua_State *L)
3181         {
3182                 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3183                                 <<" Doing nothing."<<std::endl;
3184                 return 0;
3185         }
3186
3187         // EnvRef:add_firefly(pos)
3188         // pos = {x=num, y=num, z=num}
3189         static int l_add_firefly(lua_State *L)
3190         {
3191                 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3192                                 <<" Doing nothing."<<std::endl;
3193                 return 0;
3194         }
3195
3196         // EnvRef:get_meta(pos)
3197         static int l_get_meta(lua_State *L)
3198         {
3199                 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3200                 EnvRef *o = checkobject(L, 1);
3201                 ServerEnvironment *env = o->m_env;
3202                 if(env == NULL) return 0;
3203                 // Do it
3204                 v3s16 p = read_v3s16(L, 2);
3205                 NodeMetaRef::create(L, p, env);
3206                 return 1;
3207         }
3208
3209         // EnvRef:get_player_by_name(name)
3210         static int l_get_player_by_name(lua_State *L)
3211         {
3212                 EnvRef *o = checkobject(L, 1);
3213                 ServerEnvironment *env = o->m_env;
3214                 if(env == NULL) return 0;
3215                 // Do it
3216                 const char *name = luaL_checkstring(L, 2);
3217                 Player *player = env->getPlayer(name);
3218                 if(player == NULL){
3219                         lua_pushnil(L);
3220                         return 1;
3221                 }
3222                 PlayerSAO *sao = player->getPlayerSAO();
3223                 if(sao == NULL){
3224                         lua_pushnil(L);
3225                         return 1;
3226                 }
3227                 // Put player on stack
3228                 objectref_get_or_create(L, sao);
3229                 return 1;
3230         }
3231
3232         // EnvRef:get_objects_inside_radius(pos, radius)
3233         static int l_get_objects_inside_radius(lua_State *L)
3234         {
3235                 // Get the table insert function
3236                 lua_getglobal(L, "table");
3237                 lua_getfield(L, -1, "insert");
3238                 int table_insert = lua_gettop(L);
3239                 // Get environemnt
3240                 EnvRef *o = checkobject(L, 1);
3241                 ServerEnvironment *env = o->m_env;
3242                 if(env == NULL) return 0;
3243                 // Do it
3244                 v3f pos = checkFloatPos(L, 2);
3245                 float radius = luaL_checknumber(L, 3) * BS;
3246                 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3247                 lua_newtable(L);
3248                 int table = lua_gettop(L);
3249                 for(std::set<u16>::const_iterator
3250                                 i = ids.begin(); i != ids.end(); i++){
3251                         ServerActiveObject *obj = env->getActiveObject(*i);
3252                         // Insert object reference into table
3253                         lua_pushvalue(L, table_insert);
3254                         lua_pushvalue(L, table);
3255                         objectref_get_or_create(L, obj);
3256                         if(lua_pcall(L, 2, 0, 0))
3257                                 script_error(L, "error: %s", lua_tostring(L, -1));
3258                 }
3259                 return 1;
3260         }
3261
3262         // EnvRef:set_timeofday(val)
3263         // val = 0...1
3264         static int l_set_timeofday(lua_State *L)
3265         {
3266                 EnvRef *o = checkobject(L, 1);
3267                 ServerEnvironment *env = o->m_env;
3268                 if(env == NULL) return 0;
3269                 // Do it
3270                 float timeofday_f = luaL_checknumber(L, 2);
3271                 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3272                 int timeofday_mh = (int)(timeofday_f * 24000.0);
3273                 // This should be set directly in the environment but currently
3274                 // such changes aren't immediately sent to the clients, so call
3275                 // the server instead.
3276                 //env->setTimeOfDay(timeofday_mh);
3277                 get_server(L)->setTimeOfDay(timeofday_mh);
3278                 return 0;
3279         }
3280
3281         // EnvRef:get_timeofday() -> 0...1
3282         static int l_get_timeofday(lua_State *L)
3283         {
3284                 EnvRef *o = checkobject(L, 1);
3285                 ServerEnvironment *env = o->m_env;
3286                 if(env == NULL) return 0;
3287                 // Do it
3288                 int timeofday_mh = env->getTimeOfDay();
3289                 float timeofday_f = (float)timeofday_mh / 24000.0;
3290                 lua_pushnumber(L, timeofday_f);
3291                 return 1;
3292         }
3293
3294
3295         // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3296         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3297         static int l_find_node_near(lua_State *L)
3298         {
3299                 EnvRef *o = checkobject(L, 1);
3300                 ServerEnvironment *env = o->m_env;
3301                 if(env == NULL) return 0;
3302                 INodeDefManager *ndef = get_server(L)->ndef();
3303                 v3s16 pos = read_v3s16(L, 2);
3304                 int radius = luaL_checkinteger(L, 3);
3305                 std::set<content_t> filter;
3306                 if(lua_istable(L, 4)){
3307                         int table = 4;
3308                         lua_pushnil(L);
3309                         while(lua_next(L, table) != 0){
3310                                 // key at index -2 and value at index -1
3311                                 luaL_checktype(L, -1, LUA_TSTRING);
3312                                 ndef->getIds(lua_tostring(L, -1), filter);
3313                                 // removes value, keeps key for next iteration
3314                                 lua_pop(L, 1);
3315                         }
3316                 } else if(lua_isstring(L, 4)){
3317                         ndef->getIds(lua_tostring(L, 4), filter);
3318                 }
3319
3320                 for(int d=1; d<=radius; d++){
3321                         core::list<v3s16> list;
3322                         getFacePositions(list, d);
3323                         for(core::list<v3s16>::Iterator i = list.begin();
3324                                         i != list.end(); i++){
3325                                 v3s16 p = pos + (*i);
3326                                 content_t c = env->getMap().getNodeNoEx(p).getContent();
3327                                 if(filter.count(c) != 0){
3328                                         push_v3s16(L, p);
3329                                         return 1;
3330                                 }
3331                         }
3332                 }
3333                 return 0;
3334         }
3335
3336         // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3337         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3338         static int l_find_nodes_in_area(lua_State *L)
3339         {
3340                 EnvRef *o = checkobject(L, 1);
3341                 ServerEnvironment *env = o->m_env;
3342                 if(env == NULL) return 0;
3343                 INodeDefManager *ndef = get_server(L)->ndef();
3344                 v3s16 minp = read_v3s16(L, 2);
3345                 v3s16 maxp = read_v3s16(L, 3);
3346                 std::set<content_t> filter;
3347                 if(lua_istable(L, 4)){
3348                         int table = 4;
3349                         lua_pushnil(L);
3350                         while(lua_next(L, table) != 0){
3351                                 // key at index -2 and value at index -1
3352                                 luaL_checktype(L, -1, LUA_TSTRING);
3353                                 ndef->getIds(lua_tostring(L, -1), filter);
3354                                 // removes value, keeps key for next iteration
3355                                 lua_pop(L, 1);
3356                         }
3357                 } else if(lua_isstring(L, 4)){
3358                         ndef->getIds(lua_tostring(L, 4), filter);
3359                 }
3360
3361                 // Get the table insert function
3362                 lua_getglobal(L, "table");
3363                 lua_getfield(L, -1, "insert");
3364                 int table_insert = lua_gettop(L);
3365                 
3366                 lua_newtable(L);
3367                 int table = lua_gettop(L);
3368                 for(s16 x=minp.X; x<=maxp.X; x++)
3369                 for(s16 y=minp.Y; y<=maxp.Y; y++)
3370                 for(s16 z=minp.Z; z<=maxp.Z; z++)
3371                 {
3372                         v3s16 p(x,y,z);
3373                         content_t c = env->getMap().getNodeNoEx(p).getContent();
3374                         if(filter.count(c) != 0){
3375                                 lua_pushvalue(L, table_insert);
3376                                 lua_pushvalue(L, table);
3377                                 push_v3s16(L, p);
3378                                 if(lua_pcall(L, 2, 0, 0))
3379                                         script_error(L, "error: %s", lua_tostring(L, -1));
3380                         }
3381                 }
3382                 return 1;
3383         }
3384
3385         //      EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3386         //  returns world-specific PerlinNoise
3387         static int l_get_perlin(lua_State *L)
3388         {
3389                 EnvRef *o = checkobject(L, 1);
3390                 ServerEnvironment *env = o->m_env;
3391                 if(env == NULL) return 0;
3392
3393                 int seeddiff = luaL_checkint(L, 2);
3394                 int octaves = luaL_checkint(L, 3);
3395                 double persistence = luaL_checknumber(L, 4);
3396                 double scale = luaL_checknumber(L, 5);
3397
3398                 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3399                 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3400                 luaL_getmetatable(L, "PerlinNoise");
3401                 lua_setmetatable(L, -2);
3402                 return 1;
3403         }
3404
3405 public:
3406         EnvRef(ServerEnvironment *env):
3407                 m_env(env)
3408         {
3409                 //infostream<<"EnvRef created"<<std::endl;
3410         }
3411
3412         ~EnvRef()
3413         {
3414                 //infostream<<"EnvRef destructing"<<std::endl;
3415         }
3416
3417         // Creates an EnvRef and leaves it on top of stack
3418         // Not callable from Lua; all references are created on the C side.
3419         static void create(lua_State *L, ServerEnvironment *env)
3420         {
3421                 EnvRef *o = new EnvRef(env);
3422                 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3423                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3424                 luaL_getmetatable(L, className);
3425                 lua_setmetatable(L, -2);
3426         }
3427
3428         static void set_null(lua_State *L)
3429         {
3430                 EnvRef *o = checkobject(L, -1);
3431                 o->m_env = NULL;
3432         }
3433         
3434         static void Register(lua_State *L)
3435         {
3436                 lua_newtable(L);
3437                 int methodtable = lua_gettop(L);
3438                 luaL_newmetatable(L, className);
3439                 int metatable = lua_gettop(L);
3440
3441                 lua_pushliteral(L, "__metatable");
3442                 lua_pushvalue(L, methodtable);
3443                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3444
3445                 lua_pushliteral(L, "__index");
3446                 lua_pushvalue(L, methodtable);
3447                 lua_settable(L, metatable);
3448
3449                 lua_pushliteral(L, "__gc");
3450                 lua_pushcfunction(L, gc_object);
3451                 lua_settable(L, metatable);
3452
3453                 lua_pop(L, 1);  // drop metatable
3454
3455                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3456                 lua_pop(L, 1);  // drop methodtable
3457
3458                 // Cannot be created from Lua
3459                 //lua_register(L, className, create_object);
3460         }
3461 };
3462 const char EnvRef::className[] = "EnvRef";
3463 const luaL_reg EnvRef::methods[] = {
3464         method(EnvRef, set_node),
3465         method(EnvRef, add_node),
3466         method(EnvRef, remove_node),
3467         method(EnvRef, get_node),
3468         method(EnvRef, get_node_or_nil),
3469         method(EnvRef, get_node_light),
3470         method(EnvRef, add_entity),
3471         method(EnvRef, add_item),
3472         method(EnvRef, add_rat),
3473         method(EnvRef, add_firefly),
3474         method(EnvRef, get_meta),
3475         method(EnvRef, get_player_by_name),
3476         method(EnvRef, get_objects_inside_radius),
3477         method(EnvRef, set_timeofday),
3478         method(EnvRef, get_timeofday),
3479         method(EnvRef, find_node_near),
3480         method(EnvRef, find_nodes_in_area),
3481         method(EnvRef, get_perlin),
3482         {0,0}
3483 };
3484
3485 /*
3486         LuaPseudoRandom
3487 */
3488
3489
3490 class LuaPseudoRandom
3491 {
3492 private:
3493         PseudoRandom m_pseudo;
3494
3495         static const char className[];
3496         static const luaL_reg methods[];
3497
3498         // Exported functions
3499         
3500         // garbage collector
3501         static int gc_object(lua_State *L)
3502         {
3503                 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3504                 delete o;
3505                 return 0;
3506         }
3507
3508         // next(self, min=0, max=32767) -> get next value
3509         static int l_next(lua_State *L)
3510         {
3511                 LuaPseudoRandom *o = checkobject(L, 1);
3512                 int min = 0;
3513                 int max = 32767;
3514                 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3515                 if(!lua_isnil(L, 2))
3516                         min = luaL_checkinteger(L, 2);
3517                 if(!lua_isnil(L, 3))
3518                         max = luaL_checkinteger(L, 3);
3519                 if(max - min != 32767 && max - min > 32767/5)
3520                         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.");
3521                 PseudoRandom &pseudo = o->m_pseudo;
3522                 int val = pseudo.next();
3523                 val = (val % (max-min+1)) + min;
3524                 lua_pushinteger(L, val);
3525                 return 1;
3526         }
3527
3528 public:
3529         LuaPseudoRandom(int seed):
3530                 m_pseudo(seed)
3531         {
3532         }
3533
3534         ~LuaPseudoRandom()
3535         {
3536         }
3537
3538         const PseudoRandom& getItem() const
3539         {
3540                 return m_pseudo;
3541         }
3542         PseudoRandom& getItem()
3543         {
3544                 return m_pseudo;
3545         }
3546         
3547         // LuaPseudoRandom(seed)
3548         // Creates an LuaPseudoRandom and leaves it on top of stack
3549         static int create_object(lua_State *L)
3550         {
3551                 int seed = luaL_checknumber(L, 1);
3552                 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3553                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3554                 luaL_getmetatable(L, className);
3555                 lua_setmetatable(L, -2);
3556                 return 1;
3557         }
3558
3559         static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3560         {
3561                 luaL_checktype(L, narg, LUA_TUSERDATA);
3562                 void *ud = luaL_checkudata(L, narg, className);
3563                 if(!ud) luaL_typerror(L, narg, className);
3564                 return *(LuaPseudoRandom**)ud;  // unbox pointer
3565         }
3566
3567         static void Register(lua_State *L)
3568         {
3569                 lua_newtable(L);
3570                 int methodtable = lua_gettop(L);
3571                 luaL_newmetatable(L, className);
3572                 int metatable = lua_gettop(L);
3573
3574                 lua_pushliteral(L, "__metatable");
3575                 lua_pushvalue(L, methodtable);
3576                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3577
3578                 lua_pushliteral(L, "__index");
3579                 lua_pushvalue(L, methodtable);
3580                 lua_settable(L, metatable);
3581
3582                 lua_pushliteral(L, "__gc");
3583                 lua_pushcfunction(L, gc_object);
3584                 lua_settable(L, metatable);
3585
3586                 lua_pop(L, 1);  // drop metatable
3587
3588                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3589                 lua_pop(L, 1);  // drop methodtable
3590
3591                 // Can be created from Lua (LuaPseudoRandom(seed))
3592                 lua_register(L, className, create_object);
3593         }
3594 };
3595 const char LuaPseudoRandom::className[] = "PseudoRandom";
3596 const luaL_reg LuaPseudoRandom::methods[] = {
3597         method(LuaPseudoRandom, next),
3598         {0,0}
3599 };
3600
3601
3602
3603 /*
3604         LuaABM
3605 */
3606
3607 class LuaABM : public ActiveBlockModifier
3608 {
3609 private:
3610         lua_State *m_lua;
3611         int m_id;
3612
3613         std::set<std::string> m_trigger_contents;
3614         std::set<std::string> m_required_neighbors;
3615         float m_trigger_interval;
3616         u32 m_trigger_chance;
3617 public:
3618         LuaABM(lua_State *L, int id,
3619                         const std::set<std::string> &trigger_contents,
3620                         const std::set<std::string> &required_neighbors,
3621                         float trigger_interval, u32 trigger_chance):
3622                 m_lua(L),
3623                 m_id(id),
3624                 m_trigger_contents(trigger_contents),
3625                 m_required_neighbors(required_neighbors),
3626                 m_trigger_interval(trigger_interval),
3627                 m_trigger_chance(trigger_chance)
3628         {
3629         }
3630         virtual std::set<std::string> getTriggerContents()
3631         {
3632                 return m_trigger_contents;
3633         }
3634         virtual std::set<std::string> getRequiredNeighbors()
3635         {
3636                 return m_required_neighbors;
3637         }
3638         virtual float getTriggerInterval()
3639         {
3640                 return m_trigger_interval;
3641         }
3642         virtual u32 getTriggerChance()
3643         {
3644                 return m_trigger_chance;
3645         }
3646         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3647                         u32 active_object_count, u32 active_object_count_wider)
3648         {
3649                 lua_State *L = m_lua;
3650         
3651                 realitycheck(L);
3652                 assert(lua_checkstack(L, 20));
3653                 StackUnroller stack_unroller(L);
3654
3655                 // Get minetest.registered_abms
3656                 lua_getglobal(L, "minetest");
3657                 lua_getfield(L, -1, "registered_abms");
3658                 luaL_checktype(L, -1, LUA_TTABLE);
3659                 int registered_abms = lua_gettop(L);
3660
3661                 // Get minetest.registered_abms[m_id]
3662                 lua_pushnumber(L, m_id);
3663                 lua_gettable(L, registered_abms);
3664                 if(lua_isnil(L, -1))
3665                         assert(0);
3666                 
3667                 // Call action
3668                 luaL_checktype(L, -1, LUA_TTABLE);
3669                 lua_getfield(L, -1, "action");
3670                 luaL_checktype(L, -1, LUA_TFUNCTION);
3671                 push_v3s16(L, p);
3672                 pushnode(L, n, env->getGameDef()->ndef());
3673                 lua_pushnumber(L, active_object_count);
3674                 lua_pushnumber(L, active_object_count_wider);
3675                 if(lua_pcall(L, 4, 0, 0))
3676                         script_error(L, "error: %s", lua_tostring(L, -1));
3677         }
3678 };
3679
3680 /*
3681         ServerSoundParams
3682 */
3683
3684 static void read_server_sound_params(lua_State *L, int index,
3685                 ServerSoundParams &params)
3686 {
3687         if(index < 0)
3688                 index = lua_gettop(L) + 1 + index;
3689         // Clear
3690         params = ServerSoundParams();
3691         if(lua_istable(L, index)){
3692                 getfloatfield(L, index, "gain", params.gain);
3693                 getstringfield(L, index, "to_player", params.to_player);
3694                 lua_getfield(L, index, "pos");
3695                 if(!lua_isnil(L, -1)){
3696                         v3f p = read_v3f(L, -1)*BS;
3697                         params.pos = p;
3698                         params.type = ServerSoundParams::SSP_POSITIONAL;
3699                 }
3700                 lua_pop(L, 1);
3701                 lua_getfield(L, index, "object");
3702                 if(!lua_isnil(L, -1)){
3703                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
3704                         ServerActiveObject *sao = ObjectRef::getobject(ref);
3705                         if(sao){
3706                                 params.object = sao->getId();
3707                                 params.type = ServerSoundParams::SSP_OBJECT;
3708                         }
3709                 }
3710                 lua_pop(L, 1);
3711                 params.max_hear_distance = BS*getfloatfield_default(L, index,
3712                                 "max_hear_distance", params.max_hear_distance/BS);
3713                 getboolfield(L, index, "loop", params.loop);
3714         }
3715 }
3716
3717 /*
3718         Global functions
3719 */
3720
3721 // debug(text)
3722 // Writes a line to dstream
3723 static int l_debug(lua_State *L)
3724 {
3725         std::string text = lua_tostring(L, 1);
3726         dstream << text << std::endl;
3727         return 0;
3728 }
3729
3730 // log([level,] text)
3731 // Writes a line to the logger.
3732 // The one-argument version logs to infostream.
3733 // The two-argument version accept a log level: error, action, info, or verbose.
3734 static int l_log(lua_State *L)
3735 {
3736         std::string text;
3737         LogMessageLevel level = LMT_INFO;
3738         if(lua_isnone(L, 2))
3739         {
3740                 text = lua_tostring(L, 1);
3741         }
3742         else
3743         {
3744                 std::string levelname = lua_tostring(L, 1);
3745                 text = lua_tostring(L, 2);
3746                 if(levelname == "error")
3747                         level = LMT_ERROR;
3748                 else if(levelname == "action")
3749                         level = LMT_ACTION;
3750                 else if(levelname == "verbose")
3751                         level = LMT_VERBOSE;
3752         }
3753         log_printline(level, text);
3754         return 0;
3755 }
3756
3757 // register_item_raw({lots of stuff})
3758 static int l_register_item_raw(lua_State *L)
3759 {
3760         luaL_checktype(L, 1, LUA_TTABLE);
3761         int table = 1;
3762
3763         // Get the writable item and node definition managers from the server
3764         IWritableItemDefManager *idef =
3765                         get_server(L)->getWritableItemDefManager();
3766         IWritableNodeDefManager *ndef =
3767                         get_server(L)->getWritableNodeDefManager();
3768
3769         // Check if name is defined
3770         lua_getfield(L, table, "name");
3771         if(lua_isstring(L, -1)){
3772                 std::string name = lua_tostring(L, -1);
3773                 verbosestream<<"register_item_raw: "<<name<<std::endl;
3774         } else {
3775                 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3776         }
3777
3778         // Check if on_use is defined
3779
3780         // Read the item definition and register it
3781         ItemDefinition def = read_item_definition(L, table);
3782         idef->registerItem(def);
3783
3784         // Read the node definition (content features) and register it
3785         if(def.type == ITEM_NODE)
3786         {
3787                 ContentFeatures f = read_content_features(L, table);
3788                 ndef->set(f.name, f);
3789         }
3790
3791         return 0; /* number of results */
3792 }
3793
3794 // register_alias_raw(name, convert_to_name)
3795 static int l_register_alias_raw(lua_State *L)
3796 {
3797         std::string name = luaL_checkstring(L, 1);
3798         std::string convert_to = luaL_checkstring(L, 2);
3799
3800         // Get the writable item definition manager from the server
3801         IWritableItemDefManager *idef =
3802                         get_server(L)->getWritableItemDefManager();
3803         
3804         idef->registerAlias(name, convert_to);
3805         
3806         return 0; /* number of results */
3807 }
3808
3809 // helper for register_craft
3810 static bool read_craft_recipe_shaped(lua_State *L, int index,
3811                 int &width, std::vector<std::string> &recipe)
3812 {
3813         if(index < 0)
3814                 index = lua_gettop(L) + 1 + index;
3815
3816         if(!lua_istable(L, index))
3817                 return false;
3818
3819         lua_pushnil(L);
3820         int rowcount = 0;
3821         while(lua_next(L, index) != 0){
3822                 int colcount = 0;
3823                 // key at index -2 and value at index -1
3824                 if(!lua_istable(L, -1))
3825                         return false;
3826                 int table2 = lua_gettop(L);
3827                 lua_pushnil(L);
3828                 while(lua_next(L, table2) != 0){
3829                         // key at index -2 and value at index -1
3830                         if(!lua_isstring(L, -1))
3831                                 return false;
3832                         recipe.push_back(lua_tostring(L, -1));
3833                         // removes value, keeps key for next iteration
3834                         lua_pop(L, 1);
3835                         colcount++;
3836                 }
3837                 if(rowcount == 0){
3838                         width = colcount;
3839                 } else {
3840                         if(colcount != width)
3841                                 return false;
3842                 }
3843                 // removes value, keeps key for next iteration
3844                 lua_pop(L, 1);
3845                 rowcount++;
3846         }
3847         return width != 0;
3848 }
3849
3850 // helper for register_craft
3851 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3852                 std::vector<std::string> &recipe)
3853 {
3854         if(index < 0)
3855                 index = lua_gettop(L) + 1 + index;
3856
3857         if(!lua_istable(L, index))
3858                 return false;
3859
3860         lua_pushnil(L);
3861         while(lua_next(L, index) != 0){
3862                 // key at index -2 and value at index -1
3863                 if(!lua_isstring(L, -1))
3864                         return false;
3865                 recipe.push_back(lua_tostring(L, -1));
3866                 // removes value, keeps key for next iteration
3867                 lua_pop(L, 1);
3868         }
3869         return true;
3870 }
3871
3872 // helper for register_craft
3873 static bool read_craft_replacements(lua_State *L, int index,
3874                 CraftReplacements &replacements)
3875 {
3876         if(index < 0)
3877                 index = lua_gettop(L) + 1 + index;
3878
3879         if(!lua_istable(L, index))
3880                 return false;
3881
3882         lua_pushnil(L);
3883         while(lua_next(L, index) != 0){
3884                 // key at index -2 and value at index -1
3885                 if(!lua_istable(L, -1))
3886                         return false;
3887                 lua_rawgeti(L, -1, 1);
3888                 if(!lua_isstring(L, -1))
3889                         return false;
3890                 std::string replace_from = lua_tostring(L, -1);
3891                 lua_pop(L, 1);
3892                 lua_rawgeti(L, -1, 2);
3893                 if(!lua_isstring(L, -1))
3894                         return false;
3895                 std::string replace_to = lua_tostring(L, -1);
3896                 lua_pop(L, 1);
3897                 replacements.pairs.push_back(
3898                                 std::make_pair(replace_from, replace_to));
3899                 // removes value, keeps key for next iteration
3900                 lua_pop(L, 1);
3901         }
3902         return true;
3903 }
3904 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3905 static int l_register_craft(lua_State *L)
3906 {
3907         //infostream<<"register_craft"<<std::endl;
3908         luaL_checktype(L, 1, LUA_TTABLE);
3909         int table = 1;
3910
3911         // Get the writable craft definition manager from the server
3912         IWritableCraftDefManager *craftdef =
3913                         get_server(L)->getWritableCraftDefManager();
3914         
3915         std::string type = getstringfield_default(L, table, "type", "shaped");
3916
3917         /*
3918                 CraftDefinitionShaped
3919         */
3920         if(type == "shaped"){
3921                 std::string output = getstringfield_default(L, table, "output", "");
3922                 if(output == "")
3923                         throw LuaError(L, "Crafting definition is missing an output");
3924
3925                 int width = 0;
3926                 std::vector<std::string> recipe;
3927                 lua_getfield(L, table, "recipe");
3928                 if(lua_isnil(L, -1))
3929                         throw LuaError(L, "Crafting definition is missing a recipe"
3930                                         " (output=\"" + output + "\")");
3931                 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3932                         throw LuaError(L, "Invalid crafting recipe"
3933                                         " (output=\"" + output + "\")");
3934
3935                 CraftReplacements replacements;
3936                 lua_getfield(L, table, "replacements");
3937                 if(!lua_isnil(L, -1))
3938                 {
3939                         if(!read_craft_replacements(L, -1, replacements))
3940                                 throw LuaError(L, "Invalid replacements"
3941                                                 " (output=\"" + output + "\")");
3942                 }
3943
3944                 CraftDefinition *def = new CraftDefinitionShaped(
3945                                 output, width, recipe, replacements);
3946                 craftdef->registerCraft(def);
3947         }
3948         /*
3949                 CraftDefinitionShapeless
3950         */
3951         else if(type == "shapeless"){
3952                 std::string output = getstringfield_default(L, table, "output", "");
3953                 if(output == "")
3954                         throw LuaError(L, "Crafting definition (shapeless)"
3955                                         " is missing an output");
3956
3957                 std::vector<std::string> recipe;
3958                 lua_getfield(L, table, "recipe");
3959                 if(lua_isnil(L, -1))
3960                         throw LuaError(L, "Crafting definition (shapeless)"
3961                                         " is missing a recipe"
3962                                         " (output=\"" + output + "\")");
3963                 if(!read_craft_recipe_shapeless(L, -1, recipe))
3964                         throw LuaError(L, "Invalid crafting recipe"
3965                                         " (output=\"" + output + "\")");
3966
3967                 CraftReplacements replacements;
3968                 lua_getfield(L, table, "replacements");
3969                 if(!lua_isnil(L, -1))
3970                 {
3971                         if(!read_craft_replacements(L, -1, replacements))
3972                                 throw LuaError(L, "Invalid replacements"
3973                                                 " (output=\"" + output + "\")");
3974                 }
3975
3976                 CraftDefinition *def = new CraftDefinitionShapeless(
3977                                 output, recipe, replacements);
3978                 craftdef->registerCraft(def);
3979         }
3980         /*
3981                 CraftDefinitionToolRepair
3982         */
3983         else if(type == "toolrepair"){
3984                 float additional_wear = getfloatfield_default(L, table,
3985                                 "additional_wear", 0.0);
3986
3987                 CraftDefinition *def = new CraftDefinitionToolRepair(
3988                                 additional_wear);
3989                 craftdef->registerCraft(def);
3990         }
3991         /*
3992                 CraftDefinitionCooking
3993         */
3994         else if(type == "cooking"){
3995                 std::string output = getstringfield_default(L, table, "output", "");
3996                 if(output == "")
3997                         throw LuaError(L, "Crafting definition (cooking)"
3998                                         " is missing an output");
3999
4000                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4001                 if(recipe == "")
4002                         throw LuaError(L, "Crafting definition (cooking)"
4003                                         " is missing a recipe"
4004                                         " (output=\"" + output + "\")");
4005
4006                 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4007
4008                 CraftDefinition *def = new CraftDefinitionCooking(
4009                                 output, recipe, cooktime);
4010                 craftdef->registerCraft(def);
4011         }
4012         /*
4013                 CraftDefinitionFuel
4014         */
4015         else if(type == "fuel"){
4016                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4017                 if(recipe == "")
4018                         throw LuaError(L, "Crafting definition (fuel)"
4019                                         " is missing a recipe");
4020
4021                 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4022
4023                 CraftDefinition *def = new CraftDefinitionFuel(
4024                                 recipe, burntime);
4025                 craftdef->registerCraft(def);
4026         }
4027         else
4028         {
4029                 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4030         }
4031
4032         lua_pop(L, 1);
4033         return 0; /* number of results */
4034 }
4035
4036 // setting_set(name, value)
4037 static int l_setting_set(lua_State *L)
4038 {
4039         const char *name = luaL_checkstring(L, 1);
4040         const char *value = luaL_checkstring(L, 2);
4041         g_settings->set(name, value);
4042         return 0;
4043 }
4044
4045 // setting_get(name)
4046 static int l_setting_get(lua_State *L)
4047 {
4048         const char *name = luaL_checkstring(L, 1);
4049         try{
4050                 std::string value = g_settings->get(name);
4051                 lua_pushstring(L, value.c_str());
4052         } catch(SettingNotFoundException &e){
4053                 lua_pushnil(L);
4054         }
4055         return 1;
4056 }
4057
4058 // setting_getbool(name)
4059 static int l_setting_getbool(lua_State *L)
4060 {
4061         const char *name = luaL_checkstring(L, 1);
4062         try{
4063                 bool value = g_settings->getBool(name);
4064                 lua_pushboolean(L, value);
4065         } catch(SettingNotFoundException &e){
4066                 lua_pushnil(L);
4067         }
4068         return 1;
4069 }
4070
4071 // chat_send_all(text)
4072 static int l_chat_send_all(lua_State *L)
4073 {
4074         const char *text = luaL_checkstring(L, 1);
4075         // Get server from registry
4076         Server *server = get_server(L);
4077         // Send
4078         server->notifyPlayers(narrow_to_wide(text));
4079         return 0;
4080 }
4081
4082 // chat_send_player(name, text)
4083 static int l_chat_send_player(lua_State *L)
4084 {
4085         const char *name = luaL_checkstring(L, 1);
4086         const char *text = luaL_checkstring(L, 2);
4087         // Get server from registry
4088         Server *server = get_server(L);
4089         // Send
4090         server->notifyPlayer(name, narrow_to_wide(text));
4091         return 0;
4092 }
4093
4094 // get_player_privs(name, text)
4095 static int l_get_player_privs(lua_State *L)
4096 {
4097         const char *name = luaL_checkstring(L, 1);
4098         // Get server from registry
4099         Server *server = get_server(L);
4100         // Do it
4101         lua_newtable(L);
4102         int table = lua_gettop(L);
4103         std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4104         for(std::set<std::string>::const_iterator
4105                         i = privs_s.begin(); i != privs_s.end(); i++){
4106                 lua_pushboolean(L, true);
4107                 lua_setfield(L, table, i->c_str());
4108         }
4109         lua_pushvalue(L, table);
4110         return 1;
4111 }
4112
4113 // get_inventory(location)
4114 static int l_get_inventory(lua_State *L)
4115 {
4116         InventoryLocation loc;
4117
4118         std::string type = checkstringfield(L, 1, "type");
4119         if(type == "player"){
4120                 std::string name = checkstringfield(L, 1, "name");
4121                 loc.setPlayer(name);
4122         } else if(type == "node"){
4123                 lua_getfield(L, 1, "pos");
4124                 v3s16 pos = check_v3s16(L, -1);
4125                 loc.setNodeMeta(pos);
4126         }
4127         
4128         if(get_server(L)->getInventory(loc) != NULL)
4129                 InvRef::create(L, loc);
4130         else
4131                 lua_pushnil(L);
4132         return 1;
4133 }
4134
4135 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4136 static int l_get_dig_params(lua_State *L)
4137 {
4138         std::map<std::string, int> groups;
4139         read_groups(L, 1, groups);
4140         ToolCapabilities tp = read_tool_capabilities(L, 2);
4141         if(lua_isnoneornil(L, 3))
4142                 push_dig_params(L, getDigParams(groups, &tp));
4143         else
4144                 push_dig_params(L, getDigParams(groups, &tp,
4145                                         luaL_checknumber(L, 3)));
4146         return 1;
4147 }
4148
4149 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4150 static int l_get_hit_params(lua_State *L)
4151 {
4152         std::map<std::string, int> groups;
4153         read_groups(L, 1, groups);
4154         ToolCapabilities tp = read_tool_capabilities(L, 2);
4155         if(lua_isnoneornil(L, 3))
4156                 push_hit_params(L, getHitParams(groups, &tp));
4157         else
4158                 push_hit_params(L, getHitParams(groups, &tp,
4159                                         luaL_checknumber(L, 3)));
4160         return 1;
4161 }
4162
4163 // get_current_modname()
4164 static int l_get_current_modname(lua_State *L)
4165 {
4166         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4167         return 1;
4168 }
4169
4170 // get_modpath(modname)
4171 static int l_get_modpath(lua_State *L)
4172 {
4173         std::string modname = luaL_checkstring(L, 1);
4174         // Do it
4175         if(modname == "__builtin"){
4176                 std::string path = get_server(L)->getBuiltinLuaPath();
4177                 lua_pushstring(L, path.c_str());
4178                 return 1;
4179         }
4180         const ModSpec *mod = get_server(L)->getModSpec(modname);
4181         if(!mod){
4182                 lua_pushnil(L);
4183                 return 1;
4184         }
4185         lua_pushstring(L, mod->path.c_str());
4186         return 1;
4187 }
4188
4189 // get_worldpath()
4190 static int l_get_worldpath(lua_State *L)
4191 {
4192         std::string worldpath = get_server(L)->getWorldPath();
4193         lua_pushstring(L, worldpath.c_str());
4194         return 1;
4195 }
4196
4197 // sound_play(spec, parameters)
4198 static int l_sound_play(lua_State *L)
4199 {
4200         SimpleSoundSpec spec;
4201         read_soundspec(L, 1, spec);
4202         ServerSoundParams params;
4203         read_server_sound_params(L, 2, params);
4204         s32 handle = get_server(L)->playSound(spec, params);
4205         lua_pushinteger(L, handle);
4206         return 1;
4207 }
4208
4209 // sound_stop(handle)
4210 static int l_sound_stop(lua_State *L)
4211 {
4212         int handle = luaL_checkinteger(L, 1);
4213         get_server(L)->stopSound(handle);
4214         return 0;
4215 }
4216
4217 // is_singleplayer()
4218 static int l_is_singleplayer(lua_State *L)
4219 {
4220         lua_pushboolean(L, get_server(L)->isSingleplayer());
4221         return 1;
4222 }
4223
4224 // get_password_hash(name, raw_password)
4225 static int l_get_password_hash(lua_State *L)
4226 {
4227         std::string name = luaL_checkstring(L, 1);
4228         std::string raw_password = luaL_checkstring(L, 2);
4229         std::string hash = translatePassword(name,
4230                         narrow_to_wide(raw_password));
4231         lua_pushstring(L, hash.c_str());
4232         return 1;
4233 }
4234
4235 // notify_authentication_modified(name)
4236 static int l_notify_authentication_modified(lua_State *L)
4237 {
4238         std::string name = "";
4239         if(lua_isstring(L, 1))
4240                 name = lua_tostring(L, 1);
4241         get_server(L)->reportPrivsModified(name);
4242         return 0;
4243 }
4244
4245 // get_craft_result(input)
4246 static int l_get_craft_result(lua_State *L)
4247 {
4248         int input_i = 1;
4249         std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4250         enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4251                                 es_CraftMethod, CRAFT_METHOD_NORMAL);
4252         int width = 1;
4253         lua_getfield(L, input_i, "width");
4254         if(lua_isnumber(L, -1))
4255                 width = luaL_checkinteger(L, -1);
4256         lua_pop(L, 1);
4257         lua_getfield(L, input_i, "items");
4258         std::vector<ItemStack> items = read_items(L, -1);
4259         lua_pop(L, 1); // items
4260         
4261         IGameDef *gdef = get_server(L);
4262         ICraftDefManager *cdef = gdef->cdef();
4263         CraftInput input(method, width, items);
4264         CraftOutput output;
4265         bool got = cdef->getCraftResult(input, output, true, gdef);
4266         lua_newtable(L); // output table
4267         if(got){
4268                 ItemStack item;
4269                 item.deSerialize(output.item, gdef->idef());
4270                 LuaItemStack::create(L, item);
4271                 lua_setfield(L, -2, "item");
4272                 setintfield(L, -1, "time", output.time);
4273         } else {
4274                 LuaItemStack::create(L, ItemStack());
4275                 lua_setfield(L, -2, "item");
4276                 setintfield(L, -1, "time", 0);
4277         }
4278         lua_newtable(L); // decremented input table
4279         lua_pushstring(L, method_s.c_str());
4280         lua_setfield(L, -2, "method");
4281         lua_pushinteger(L, width);
4282         lua_setfield(L, -2, "width");
4283         push_items(L, input.items);
4284         lua_setfield(L, -2, "items");
4285         return 2;
4286 }
4287
4288 static const struct luaL_Reg minetest_f [] = {
4289         {"debug", l_debug},
4290         {"log", l_log},
4291         {"register_item_raw", l_register_item_raw},
4292         {"register_alias_raw", l_register_alias_raw},
4293         {"register_craft", l_register_craft},
4294         {"setting_set", l_setting_set},
4295         {"setting_get", l_setting_get},
4296         {"setting_getbool", l_setting_getbool},
4297         {"chat_send_all", l_chat_send_all},
4298         {"chat_send_player", l_chat_send_player},
4299         {"get_player_privs", l_get_player_privs},
4300         {"get_inventory", l_get_inventory},
4301         {"get_dig_params", l_get_dig_params},
4302         {"get_hit_params", l_get_hit_params},
4303         {"get_current_modname", l_get_current_modname},
4304         {"get_modpath", l_get_modpath},
4305         {"get_worldpath", l_get_worldpath},
4306         {"sound_play", l_sound_play},
4307         {"sound_stop", l_sound_stop},
4308         {"is_singleplayer", l_is_singleplayer},
4309         {"get_password_hash", l_get_password_hash},
4310         {"notify_authentication_modified", l_notify_authentication_modified},
4311         {"get_craft_result", l_get_craft_result},
4312         {NULL, NULL}
4313 };
4314
4315 /*
4316         Main export function
4317 */
4318
4319 void scriptapi_export(lua_State *L, Server *server)
4320 {
4321         realitycheck(L);
4322         assert(lua_checkstack(L, 20));
4323         verbosestream<<"scriptapi_export()"<<std::endl;
4324         StackUnroller stack_unroller(L);
4325
4326         // Store server as light userdata in registry
4327         lua_pushlightuserdata(L, server);
4328         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4329
4330         // Register global functions in table minetest
4331         lua_newtable(L);
4332         luaL_register(L, NULL, minetest_f);
4333         lua_setglobal(L, "minetest");
4334         
4335         // Get the main minetest table
4336         lua_getglobal(L, "minetest");
4337
4338         // Add tables to minetest
4339         
4340         lua_newtable(L);
4341         lua_setfield(L, -2, "object_refs");
4342         lua_newtable(L);
4343         lua_setfield(L, -2, "luaentities");
4344
4345         // Register wrappers
4346         LuaItemStack::Register(L);
4347         InvRef::Register(L);
4348         NodeMetaRef::Register(L);
4349         ObjectRef::Register(L);
4350         EnvRef::Register(L);
4351         LuaPseudoRandom::Register(L);
4352         LuaPerlinNoise::Register(L);
4353 }
4354
4355 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4356                 const std::string &modname)
4357 {
4358         ModNameStorer modnamestorer(L, modname);
4359
4360         if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4361                         "0123456789_")){
4362                 errorstream<<"Error loading mod \""<<modname
4363                                 <<"\": modname does not follow naming conventions: "
4364                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4365                 return false;
4366         }
4367         
4368         bool success = false;
4369
4370         try{
4371                 success = script_load(L, scriptpath.c_str());
4372         }
4373         catch(LuaError &e){
4374                 errorstream<<"Error loading mod \""<<modname
4375                                 <<"\": "<<e.what()<<std::endl;
4376         }
4377
4378         return success;
4379 }
4380
4381 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4382 {
4383         realitycheck(L);
4384         assert(lua_checkstack(L, 20));
4385         verbosestream<<"scriptapi_add_environment"<<std::endl;
4386         StackUnroller stack_unroller(L);
4387
4388         // Create EnvRef on stack
4389         EnvRef::create(L, env);
4390         int envref = lua_gettop(L);
4391
4392         // minetest.env = envref
4393         lua_getglobal(L, "minetest");
4394         luaL_checktype(L, -1, LUA_TTABLE);
4395         lua_pushvalue(L, envref);
4396         lua_setfield(L, -2, "env");
4397
4398         // Store environment as light userdata in registry
4399         lua_pushlightuserdata(L, env);
4400         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4401
4402         /*
4403                 Add ActiveBlockModifiers to environment
4404         */
4405
4406         // Get minetest.registered_abms
4407         lua_getglobal(L, "minetest");
4408         lua_getfield(L, -1, "registered_abms");
4409         luaL_checktype(L, -1, LUA_TTABLE);
4410         int registered_abms = lua_gettop(L);
4411         
4412         if(lua_istable(L, registered_abms)){
4413                 int table = lua_gettop(L);
4414                 lua_pushnil(L);
4415                 while(lua_next(L, table) != 0){
4416                         // key at index -2 and value at index -1
4417                         int id = lua_tonumber(L, -2);
4418                         int current_abm = lua_gettop(L);
4419
4420                         std::set<std::string> trigger_contents;
4421                         lua_getfield(L, current_abm, "nodenames");
4422                         if(lua_istable(L, -1)){
4423                                 int table = lua_gettop(L);
4424                                 lua_pushnil(L);
4425                                 while(lua_next(L, table) != 0){
4426                                         // key at index -2 and value at index -1
4427                                         luaL_checktype(L, -1, LUA_TSTRING);
4428                                         trigger_contents.insert(lua_tostring(L, -1));
4429                                         // removes value, keeps key for next iteration
4430                                         lua_pop(L, 1);
4431                                 }
4432                         } else if(lua_isstring(L, -1)){
4433                                 trigger_contents.insert(lua_tostring(L, -1));
4434                         }
4435                         lua_pop(L, 1);
4436
4437                         std::set<std::string> required_neighbors;
4438                         lua_getfield(L, current_abm, "neighbors");
4439                         if(lua_istable(L, -1)){
4440                                 int table = lua_gettop(L);
4441                                 lua_pushnil(L);
4442                                 while(lua_next(L, table) != 0){
4443                                         // key at index -2 and value at index -1
4444                                         luaL_checktype(L, -1, LUA_TSTRING);
4445                                         required_neighbors.insert(lua_tostring(L, -1));
4446                                         // removes value, keeps key for next iteration
4447                                         lua_pop(L, 1);
4448                                 }
4449                         } else if(lua_isstring(L, -1)){
4450                                 required_neighbors.insert(lua_tostring(L, -1));
4451                         }
4452                         lua_pop(L, 1);
4453
4454                         float trigger_interval = 10.0;
4455                         getfloatfield(L, current_abm, "interval", trigger_interval);
4456
4457                         int trigger_chance = 50;
4458                         getintfield(L, current_abm, "chance", trigger_chance);
4459
4460                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
4461                                         required_neighbors, trigger_interval, trigger_chance);
4462                         
4463                         env->addActiveBlockModifier(abm);
4464
4465                         // removes value, keeps key for next iteration
4466                         lua_pop(L, 1);
4467                 }
4468         }
4469         lua_pop(L, 1);
4470 }
4471
4472 #if 0
4473 // Dump stack top with the dump2 function
4474 static void dump2(lua_State *L, const char *name)
4475 {
4476         // Dump object (debug)
4477         lua_getglobal(L, "dump2");
4478         luaL_checktype(L, -1, LUA_TFUNCTION);
4479         lua_pushvalue(L, -2); // Get previous stack top as first parameter
4480         lua_pushstring(L, name);
4481         if(lua_pcall(L, 2, 0, 0))
4482                 script_error(L, "error: %s", lua_tostring(L, -1));
4483 }
4484 #endif
4485
4486 /*
4487         object_reference
4488 */
4489
4490 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4491 {
4492         realitycheck(L);
4493         assert(lua_checkstack(L, 20));
4494         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4495         StackUnroller stack_unroller(L);
4496
4497         // Create object on stack
4498         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4499         int object = lua_gettop(L);
4500
4501         // Get minetest.object_refs table
4502         lua_getglobal(L, "minetest");
4503         lua_getfield(L, -1, "object_refs");
4504         luaL_checktype(L, -1, LUA_TTABLE);
4505         int objectstable = lua_gettop(L);
4506         
4507         // object_refs[id] = object
4508         lua_pushnumber(L, cobj->getId()); // Push id
4509         lua_pushvalue(L, object); // Copy object to top of stack
4510         lua_settable(L, objectstable);
4511 }
4512
4513 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4514 {
4515         realitycheck(L);
4516         assert(lua_checkstack(L, 20));
4517         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4518         StackUnroller stack_unroller(L);
4519
4520         // Get minetest.object_refs table
4521         lua_getglobal(L, "minetest");
4522         lua_getfield(L, -1, "object_refs");
4523         luaL_checktype(L, -1, LUA_TTABLE);
4524         int objectstable = lua_gettop(L);
4525         
4526         // Get object_refs[id]
4527         lua_pushnumber(L, cobj->getId()); // Push id
4528         lua_gettable(L, objectstable);
4529         // Set object reference to NULL
4530         ObjectRef::set_null(L);
4531         lua_pop(L, 1); // pop object
4532
4533         // Set object_refs[id] = nil
4534         lua_pushnumber(L, cobj->getId()); // Push id
4535         lua_pushnil(L);
4536         lua_settable(L, objectstable);
4537 }
4538
4539 /*
4540         misc
4541 */
4542
4543 // What scriptapi_run_callbacks does with the return values of callbacks.
4544 // Regardless of the mode, if only one callback is defined,
4545 // its return value is the total return value.
4546 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4547 enum RunCallbacksMode
4548 {
4549         // Returns the return value of the first callback
4550         // Returns nil if list of callbacks is empty
4551         RUN_CALLBACKS_MODE_FIRST,
4552         // Returns the return value of the last callback
4553         // Returns nil if list of callbacks is empty
4554         RUN_CALLBACKS_MODE_LAST,
4555         // If any callback returns a false value, the first such is returned
4556         // Otherwise, the first callback's return value (trueish) is returned
4557         // Returns true if list of callbacks is empty
4558         RUN_CALLBACKS_MODE_AND,
4559         // Like above, but stops calling callbacks (short circuit)
4560         // after seeing the first false value
4561         RUN_CALLBACKS_MODE_AND_SC,
4562         // If any callback returns a true value, the first such is returned
4563         // Otherwise, the first callback's return value (falseish) is returned
4564         // Returns false if list of callbacks is empty
4565         RUN_CALLBACKS_MODE_OR,
4566         // Like above, but stops calling callbacks (short circuit)
4567         // after seeing the first true value
4568         RUN_CALLBACKS_MODE_OR_SC,
4569         // Note: "a true value" and "a false value" refer to values that
4570         // are converted by lua_toboolean to true or false, respectively.
4571 };
4572
4573 // Push the list of callbacks (a lua table).
4574 // Then push nargs arguments.
4575 // Then call this function, which
4576 // - runs the callbacks
4577 // - removes the table and arguments from the lua stack
4578 // - pushes the return value, computed depending on mode
4579 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4580                 RunCallbacksMode mode)
4581 {
4582         // Insert the return value into the lua stack, below the table
4583         assert(lua_gettop(L) >= nargs + 1);
4584         lua_pushnil(L);
4585         lua_insert(L, -(nargs + 1) - 1);
4586         // Stack now looks like this:
4587         // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4588
4589         int rv = lua_gettop(L) - nargs - 1;
4590         int table = rv + 1;
4591         int arg = table + 1;
4592
4593         luaL_checktype(L, table, LUA_TTABLE);
4594
4595         // Foreach
4596         lua_pushnil(L);
4597         bool first_loop = true;
4598         while(lua_next(L, table) != 0){
4599                 // key at index -2 and value at index -1
4600                 luaL_checktype(L, -1, LUA_TFUNCTION);
4601                 // Call function
4602                 for(int i = 0; i < nargs; i++)
4603                         lua_pushvalue(L, arg+i);
4604                 if(lua_pcall(L, nargs, 1, 0))
4605                         script_error(L, "error: %s", lua_tostring(L, -1));
4606
4607                 // Move return value to designated space in stack
4608                 // Or pop it
4609                 if(first_loop){
4610                         // Result of first callback is always moved
4611                         lua_replace(L, rv);
4612                         first_loop = false;
4613                 } else {
4614                         // Otherwise, what happens depends on the mode
4615                         if(mode == RUN_CALLBACKS_MODE_FIRST)
4616                                 lua_pop(L, 1);
4617                         else if(mode == RUN_CALLBACKS_MODE_LAST)
4618                                 lua_replace(L, rv);
4619                         else if(mode == RUN_CALLBACKS_MODE_AND ||
4620                                         mode == RUN_CALLBACKS_MODE_AND_SC){
4621                                 if(lua_toboolean(L, rv) == true &&
4622                                                 lua_toboolean(L, -1) == false)
4623                                         lua_replace(L, rv);
4624                                 else
4625                                         lua_pop(L, 1);
4626                         }
4627                         else if(mode == RUN_CALLBACKS_MODE_OR ||
4628                                         mode == RUN_CALLBACKS_MODE_OR_SC){
4629                                 if(lua_toboolean(L, rv) == false &&
4630                                                 lua_toboolean(L, -1) == true)
4631                                         lua_replace(L, rv);
4632                                 else
4633                                         lua_pop(L, 1);
4634                         }
4635                         else
4636                                 assert(0);
4637                 }
4638
4639                 // Handle short circuit modes
4640                 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4641                                 lua_toboolean(L, rv) == false)
4642                         break;
4643                 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4644                                 lua_toboolean(L, rv) == true)
4645                         break;
4646
4647                 // value removed, keep key for next iteration
4648         }
4649
4650         // Remove stuff from stack, leaving only the return value
4651         lua_settop(L, rv);
4652
4653         // Fix return value in case no callbacks were called
4654         if(first_loop){
4655                 if(mode == RUN_CALLBACKS_MODE_AND ||
4656                                 mode == RUN_CALLBACKS_MODE_AND_SC){
4657                         lua_pop(L, 1);
4658                         lua_pushboolean(L, true);
4659                 }
4660                 else if(mode == RUN_CALLBACKS_MODE_OR ||
4661                                 mode == RUN_CALLBACKS_MODE_OR_SC){
4662                         lua_pop(L, 1);
4663                         lua_pushboolean(L, false);
4664                 }
4665         }
4666 }
4667
4668 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4669                 const std::string &message)
4670 {
4671         realitycheck(L);
4672         assert(lua_checkstack(L, 20));
4673         StackUnroller stack_unroller(L);
4674
4675         // Get minetest.registered_on_chat_messages
4676         lua_getglobal(L, "minetest");
4677         lua_getfield(L, -1, "registered_on_chat_messages");
4678         // Call callbacks
4679         lua_pushstring(L, name.c_str());
4680         lua_pushstring(L, message.c_str());
4681         scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4682         bool ate = lua_toboolean(L, -1);
4683         return ate;
4684 }
4685
4686 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4687 {
4688         realitycheck(L);
4689         assert(lua_checkstack(L, 20));
4690         StackUnroller stack_unroller(L);
4691
4692         // Get minetest.registered_on_newplayers
4693         lua_getglobal(L, "minetest");
4694         lua_getfield(L, -1, "registered_on_newplayers");
4695         // Call callbacks
4696         objectref_get_or_create(L, player);
4697         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4698 }
4699
4700 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4701 {
4702         realitycheck(L);
4703         assert(lua_checkstack(L, 20));
4704         StackUnroller stack_unroller(L);
4705
4706         // Get minetest.registered_on_dieplayers
4707         lua_getglobal(L, "minetest");
4708         lua_getfield(L, -1, "registered_on_dieplayers");
4709         // Call callbacks
4710         objectref_get_or_create(L, player);
4711         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4712 }
4713
4714 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4715 {
4716         realitycheck(L);
4717         assert(lua_checkstack(L, 20));
4718         StackUnroller stack_unroller(L);
4719
4720         // Get minetest.registered_on_respawnplayers
4721         lua_getglobal(L, "minetest");
4722         lua_getfield(L, -1, "registered_on_respawnplayers");
4723         // Call callbacks
4724         objectref_get_or_create(L, player);
4725         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4726         bool positioning_handled_by_some = lua_toboolean(L, -1);
4727         return positioning_handled_by_some;
4728 }
4729
4730 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4731 {
4732         realitycheck(L);
4733         assert(lua_checkstack(L, 20));
4734         StackUnroller stack_unroller(L);
4735
4736         // Get minetest.registered_on_joinplayers
4737         lua_getglobal(L, "minetest");
4738         lua_getfield(L, -1, "registered_on_joinplayers");
4739         // Call callbacks
4740         objectref_get_or_create(L, player);
4741         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4742 }
4743
4744 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4745 {
4746         realitycheck(L);
4747         assert(lua_checkstack(L, 20));
4748         StackUnroller stack_unroller(L);
4749
4750         // Get minetest.registered_on_leaveplayers
4751         lua_getglobal(L, "minetest");
4752         lua_getfield(L, -1, "registered_on_leaveplayers");
4753         // Call callbacks
4754         objectref_get_or_create(L, player);
4755         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4756 }
4757
4758 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4759 {
4760         realitycheck(L);
4761         assert(lua_checkstack(L, 20));
4762         StackUnroller stack_unroller(L);
4763         
4764         Inventory *inv = player->getInventory();
4765         assert(inv);
4766
4767         lua_getglobal(L, "minetest");
4768         lua_getfield(L, -1, "creative_inventory");
4769         luaL_checktype(L, -1, LUA_TTABLE);
4770         inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4771 }
4772
4773 static void get_auth_handler(lua_State *L)
4774 {
4775         lua_getglobal(L, "minetest");
4776         lua_getfield(L, -1, "registered_auth_handler");
4777         if(lua_isnil(L, -1)){
4778                 lua_pop(L, 1);
4779                 lua_getfield(L, -1, "builtin_auth_handler");
4780         }
4781         if(lua_type(L, -1) != LUA_TTABLE)
4782                 throw LuaError(L, "Authentication handler table not valid");
4783 }
4784
4785 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
4786                 std::string *dst_password, std::set<std::string> *dst_privs)
4787 {
4788         realitycheck(L);
4789         assert(lua_checkstack(L, 20));
4790         StackUnroller stack_unroller(L);
4791         
4792         get_auth_handler(L);
4793         lua_getfield(L, -1, "get_auth");
4794         if(lua_type(L, -1) != LUA_TFUNCTION)
4795                 throw LuaError(L, "Authentication handler missing get_auth");
4796         lua_pushstring(L, playername.c_str());
4797         if(lua_pcall(L, 1, 1, 0))
4798                 script_error(L, "error: %s", lua_tostring(L, -1));
4799         
4800         // nil = login not allowed
4801         if(lua_isnil(L, -1))
4802                 return false;
4803         luaL_checktype(L, -1, LUA_TTABLE);
4804         
4805         std::string password;
4806         bool found = getstringfield(L, -1, "password", password);
4807         if(!found)
4808                 throw LuaError(L, "Authentication handler didn't return password");
4809         if(dst_password)
4810                 *dst_password = password;
4811
4812         lua_getfield(L, -1, "privileges");
4813         if(!lua_istable(L, -1))
4814                 throw LuaError(L,
4815                                 "Authentication handler didn't return privilege table");
4816         if(dst_privs)
4817                 read_privileges(L, -1, *dst_privs);
4818         lua_pop(L, 1);
4819         
4820         return true;
4821 }
4822
4823 void scriptapi_create_auth(lua_State *L, const std::string &playername,
4824                 const std::string &password)
4825 {
4826         realitycheck(L);
4827         assert(lua_checkstack(L, 20));
4828         StackUnroller stack_unroller(L);
4829         
4830         get_auth_handler(L);
4831         lua_getfield(L, -1, "create_auth");
4832         if(lua_type(L, -1) != LUA_TFUNCTION)
4833                 throw LuaError(L, "Authentication handler missing create_auth");
4834         lua_pushstring(L, playername.c_str());
4835         lua_pushstring(L, password.c_str());
4836         if(lua_pcall(L, 2, 0, 0))
4837                 script_error(L, "error: %s", lua_tostring(L, -1));
4838 }
4839
4840 bool scriptapi_set_password(lua_State *L, const std::string &playername,
4841                 const std::string &password)
4842 {
4843         realitycheck(L);
4844         assert(lua_checkstack(L, 20));
4845         StackUnroller stack_unroller(L);
4846         
4847         get_auth_handler(L);
4848         lua_getfield(L, -1, "set_password");
4849         if(lua_type(L, -1) != LUA_TFUNCTION)
4850                 throw LuaError(L, "Authentication handler missing set_password");
4851         lua_pushstring(L, playername.c_str());
4852         lua_pushstring(L, password.c_str());
4853         if(lua_pcall(L, 2, 1, 0))
4854                 script_error(L, "error: %s", lua_tostring(L, -1));
4855         return lua_toboolean(L, -1);
4856 }
4857
4858 /*
4859         item callbacks and node callbacks
4860 */
4861
4862 // Retrieves minetest.registered_items[name][callbackname]
4863 // If that is nil or on error, return false and stack is unchanged
4864 // If that is a function, returns true and pushes the
4865 // function onto the stack
4866 static bool get_item_callback(lua_State *L,
4867                 const char *name, const char *callbackname)
4868 {
4869         lua_getglobal(L, "minetest");
4870         lua_getfield(L, -1, "registered_items");
4871         lua_remove(L, -2);
4872         luaL_checktype(L, -1, LUA_TTABLE);
4873         lua_getfield(L, -1, name);
4874         lua_remove(L, -2);
4875         // Should be a table
4876         if(lua_type(L, -1) != LUA_TTABLE)
4877         {
4878                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4879                 lua_pop(L, 1);
4880                 return false;
4881         }
4882         lua_getfield(L, -1, callbackname);
4883         lua_remove(L, -2);
4884         // Should be a function or nil
4885         if(lua_type(L, -1) == LUA_TFUNCTION)
4886         {
4887                 return true;
4888         }
4889         else if(lua_isnil(L, -1))
4890         {
4891                 lua_pop(L, 1);
4892                 return false;
4893         }
4894         else
4895         {
4896                 errorstream<<"Item \""<<name<<"\" callback \""
4897                         <<callbackname<<" is not a function"<<std::endl;
4898                 lua_pop(L, 1);
4899                 return false;
4900         }
4901 }
4902
4903 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4904                 ServerActiveObject *dropper, v3f pos)
4905 {
4906         realitycheck(L);
4907         assert(lua_checkstack(L, 20));
4908         StackUnroller stack_unroller(L);
4909
4910         // Push callback function on stack
4911         if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4912                 return false;
4913
4914         // Call function
4915         LuaItemStack::create(L, item);
4916         objectref_get_or_create(L, dropper);
4917         pushFloatPos(L, pos);
4918         if(lua_pcall(L, 3, 1, 0))
4919                 script_error(L, "error: %s", lua_tostring(L, -1));
4920         if(!lua_isnil(L, -1))
4921                 item = read_item(L, -1);
4922         return true;
4923 }
4924
4925 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4926                 ServerActiveObject *placer, const PointedThing &pointed)
4927 {
4928         realitycheck(L);
4929         assert(lua_checkstack(L, 20));
4930         StackUnroller stack_unroller(L);
4931
4932         // Push callback function on stack
4933         if(!get_item_callback(L, item.name.c_str(), "on_place"))
4934                 return false;
4935
4936         // Call function
4937         LuaItemStack::create(L, item);
4938         objectref_get_or_create(L, placer);
4939         push_pointed_thing(L, pointed);
4940         if(lua_pcall(L, 3, 1, 0))
4941                 script_error(L, "error: %s", lua_tostring(L, -1));
4942         if(!lua_isnil(L, -1))
4943                 item = read_item(L, -1);
4944         return true;
4945 }
4946
4947 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4948                 ServerActiveObject *user, const PointedThing &pointed)
4949 {
4950         realitycheck(L);
4951         assert(lua_checkstack(L, 20));
4952         StackUnroller stack_unroller(L);
4953
4954         // Push callback function on stack
4955         if(!get_item_callback(L, item.name.c_str(), "on_use"))
4956                 return false;
4957
4958         // Call function
4959         LuaItemStack::create(L, item);
4960         objectref_get_or_create(L, user);
4961         push_pointed_thing(L, pointed);
4962         if(lua_pcall(L, 3, 1, 0))
4963                 script_error(L, "error: %s", lua_tostring(L, -1));
4964         if(!lua_isnil(L, -1))
4965                 item = read_item(L, -1);
4966         return true;
4967 }
4968
4969 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
4970                 ServerActiveObject *puncher)
4971 {
4972         realitycheck(L);
4973         assert(lua_checkstack(L, 20));
4974         StackUnroller stack_unroller(L);
4975
4976         INodeDefManager *ndef = get_server(L)->ndef();
4977
4978         // Push callback function on stack
4979         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4980                 return false;
4981
4982         // Call function
4983         push_v3s16(L, p);
4984         pushnode(L, node, ndef);
4985         objectref_get_or_create(L, puncher);
4986         if(lua_pcall(L, 3, 0, 0))
4987                 script_error(L, "error: %s", lua_tostring(L, -1));
4988         return true;
4989 }
4990
4991 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
4992                 ServerActiveObject *digger)
4993 {
4994         realitycheck(L);
4995         assert(lua_checkstack(L, 20));
4996         StackUnroller stack_unroller(L);
4997
4998         INodeDefManager *ndef = get_server(L)->ndef();
4999
5000         // Push callback function on stack
5001         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5002                 return false;
5003
5004         // Call function
5005         push_v3s16(L, p);
5006         pushnode(L, node, ndef);
5007         objectref_get_or_create(L, digger);
5008         if(lua_pcall(L, 3, 0, 0))
5009                 script_error(L, "error: %s", lua_tostring(L, -1));
5010         return true;
5011 }
5012
5013 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5014 {
5015         realitycheck(L);
5016         assert(lua_checkstack(L, 20));
5017         StackUnroller stack_unroller(L);
5018
5019         INodeDefManager *ndef = get_server(L)->ndef();
5020
5021         // Push callback function on stack
5022         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5023                 return;
5024
5025         // Call function
5026         push_v3s16(L, p);
5027         if(lua_pcall(L, 1, 0, 0))
5028                 script_error(L, "error: %s", lua_tostring(L, -1));
5029 }
5030
5031 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5032 {
5033         realitycheck(L);
5034         assert(lua_checkstack(L, 20));
5035         StackUnroller stack_unroller(L);
5036
5037         INodeDefManager *ndef = get_server(L)->ndef();
5038
5039         // Push callback function on stack
5040         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5041                 return;
5042
5043         // Call function
5044         push_v3s16(L, p);
5045         if(lua_pcall(L, 1, 0, 0))
5046                 script_error(L, "error: %s", lua_tostring(L, -1));
5047 }
5048
5049 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5050                 const std::string &formname,
5051                 const std::map<std::string, std::string> &fields,
5052                 ServerActiveObject *sender)
5053 {
5054         realitycheck(L);
5055         assert(lua_checkstack(L, 20));
5056         StackUnroller stack_unroller(L);
5057
5058         INodeDefManager *ndef = get_server(L)->ndef();
5059         
5060         // If node doesn't exist, we don't know what callback to call
5061         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5062         if(node.getContent() == CONTENT_IGNORE)
5063                 return;
5064
5065         // Push callback function on stack
5066         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5067                 return;
5068
5069         // Call function
5070         // param 1
5071         push_v3s16(L, p);
5072         // param 2
5073         lua_pushstring(L, formname.c_str());
5074         // param 3
5075         lua_newtable(L);
5076         for(std::map<std::string, std::string>::const_iterator
5077                         i = fields.begin(); i != fields.end(); i++){
5078                 const std::string &name = i->first;
5079                 const std::string &value = i->second;
5080                 lua_pushstring(L, name.c_str());
5081                 lua_pushlstring(L, value.c_str(), value.size());
5082                 lua_settable(L, -3);
5083         }
5084         // param 4
5085         objectref_get_or_create(L, sender);
5086         if(lua_pcall(L, 4, 0, 0))
5087                 script_error(L, "error: %s", lua_tostring(L, -1));
5088 }
5089
5090 void scriptapi_node_on_metadata_inventory_move(lua_State *L, v3s16 p,
5091                 const std::string &from_list, int from_index,
5092                 const std::string &to_list, int to_index,
5093                 int count, ServerActiveObject *player)
5094 {
5095         realitycheck(L);
5096         assert(lua_checkstack(L, 20));
5097         StackUnroller stack_unroller(L);
5098
5099         INodeDefManager *ndef = get_server(L)->ndef();
5100
5101         // If node doesn't exist, we don't know what callback to call
5102         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5103         if(node.getContent() == CONTENT_IGNORE)
5104                 return;
5105
5106         // Push callback function on stack
5107         if(!get_item_callback(L, ndef->get(node).name.c_str(),
5108                         "on_metadata_inventory_move"))
5109                 return;
5110
5111         // function(pos, from_list, from_index, to_list, to_index, count, player)
5112         push_v3s16(L, p);
5113         lua_pushstring(L, from_list.c_str());
5114         lua_pushinteger(L, from_index + 1);
5115         lua_pushstring(L, to_list.c_str());
5116         lua_pushinteger(L, to_index + 1);
5117         lua_pushinteger(L, count);
5118         objectref_get_or_create(L, player);
5119         if(lua_pcall(L, 7, 0, 0))
5120                 script_error(L, "error: %s", lua_tostring(L, -1));
5121 }
5122
5123 ItemStack scriptapi_node_on_metadata_inventory_offer(lua_State *L, v3s16 p,
5124                 const std::string &listname, int index, ItemStack &stack,
5125                 ServerActiveObject *player)
5126 {
5127         realitycheck(L);
5128         assert(lua_checkstack(L, 20));
5129         StackUnroller stack_unroller(L);
5130
5131         INodeDefManager *ndef = get_server(L)->ndef();
5132
5133         // If node doesn't exist, we don't know what callback to call
5134         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5135         if(node.getContent() == CONTENT_IGNORE)
5136                 return stack;
5137
5138         // Push callback function on stack
5139         if(!get_item_callback(L, ndef->get(node).name.c_str(),
5140                         "on_metadata_inventory_offer"))
5141                 return stack;
5142
5143         // Call function(pos, listname, index, stack, player)
5144         push_v3s16(L, p);
5145         lua_pushstring(L, listname.c_str());
5146         lua_pushinteger(L, index + 1);
5147         LuaItemStack::create(L, stack);
5148         objectref_get_or_create(L, player);
5149         if(lua_pcall(L, 5, 1, 0))
5150                 script_error(L, "error: %s", lua_tostring(L, -1));
5151         return read_item(L, -1);
5152 }
5153
5154 ItemStack scriptapi_node_on_metadata_inventory_take(lua_State *L, v3s16 p,
5155                 const std::string &listname, int index, int count,
5156                 ServerActiveObject *player)
5157 {
5158         realitycheck(L);
5159         assert(lua_checkstack(L, 20));
5160         StackUnroller stack_unroller(L);
5161
5162         INodeDefManager *ndef = get_server(L)->ndef();
5163
5164         // If node doesn't exist, we don't know what callback to call
5165         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5166         if(node.getContent() == CONTENT_IGNORE)
5167                 return ItemStack();
5168
5169         // Push callback function on stack
5170         if(!get_item_callback(L, ndef->get(node).name.c_str(),
5171                         "on_metadata_inventory_take"))
5172                 return ItemStack();
5173
5174         // Call function(pos, listname, index, count, player)
5175         push_v3s16(L, p);
5176         lua_pushstring(L, listname.c_str());
5177         lua_pushinteger(L, index + 1);
5178         lua_pushinteger(L, count);
5179         objectref_get_or_create(L, player);
5180         if(lua_pcall(L, 5, 1, 0))
5181                 script_error(L, "error: %s", lua_tostring(L, -1));
5182         return read_item(L, -1);
5183 }
5184
5185 /*
5186         environment
5187 */
5188
5189 void scriptapi_environment_step(lua_State *L, float dtime)
5190 {
5191         realitycheck(L);
5192         assert(lua_checkstack(L, 20));
5193         //infostream<<"scriptapi_environment_step"<<std::endl;
5194         StackUnroller stack_unroller(L);
5195
5196         // Get minetest.registered_globalsteps
5197         lua_getglobal(L, "minetest");
5198         lua_getfield(L, -1, "registered_globalsteps");
5199         // Call callbacks
5200         lua_pushnumber(L, dtime);
5201         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5202 }
5203
5204 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5205                 u32 blockseed)
5206 {
5207         realitycheck(L);
5208         assert(lua_checkstack(L, 20));
5209         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5210         StackUnroller stack_unroller(L);
5211
5212         // Get minetest.registered_on_generateds
5213         lua_getglobal(L, "minetest");
5214         lua_getfield(L, -1, "registered_on_generateds");
5215         // Call callbacks
5216         push_v3s16(L, minp);
5217         push_v3s16(L, maxp);
5218         lua_pushnumber(L, blockseed);
5219         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5220 }
5221
5222 /*
5223         luaentity
5224 */
5225
5226 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5227 {
5228         realitycheck(L);
5229         assert(lua_checkstack(L, 20));
5230         verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5231                         <<name<<"\""<<std::endl;
5232         StackUnroller stack_unroller(L);
5233         
5234         // Get minetest.registered_entities[name]
5235         lua_getglobal(L, "minetest");
5236         lua_getfield(L, -1, "registered_entities");
5237         luaL_checktype(L, -1, LUA_TTABLE);
5238         lua_pushstring(L, name);
5239         lua_gettable(L, -2);
5240         // Should be a table, which we will use as a prototype
5241         //luaL_checktype(L, -1, LUA_TTABLE);
5242         if(lua_type(L, -1) != LUA_TTABLE){
5243                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5244                 return false;
5245         }
5246         int prototype_table = lua_gettop(L);
5247         //dump2(L, "prototype_table");
5248         
5249         // Create entity object
5250         lua_newtable(L);
5251         int object = lua_gettop(L);
5252
5253         // Set object metatable
5254         lua_pushvalue(L, prototype_table);
5255         lua_setmetatable(L, -2);
5256         
5257         // Add object reference
5258         // This should be userdata with metatable ObjectRef
5259         objectref_get(L, id);
5260         luaL_checktype(L, -1, LUA_TUSERDATA);
5261         if(!luaL_checkudata(L, -1, "ObjectRef"))
5262                 luaL_typerror(L, -1, "ObjectRef");
5263         lua_setfield(L, -2, "object");
5264
5265         // minetest.luaentities[id] = object
5266         lua_getglobal(L, "minetest");
5267         lua_getfield(L, -1, "luaentities");
5268         luaL_checktype(L, -1, LUA_TTABLE);
5269         lua_pushnumber(L, id); // Push id
5270         lua_pushvalue(L, object); // Copy object to top of stack
5271         lua_settable(L, -3);
5272         
5273         return true;
5274 }
5275
5276 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5277                 const std::string &staticdata)
5278 {
5279         realitycheck(L);
5280         assert(lua_checkstack(L, 20));
5281         verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5282         StackUnroller stack_unroller(L);
5283         
5284         // Get minetest.luaentities[id]
5285         luaentity_get(L, id);
5286         int object = lua_gettop(L);
5287         
5288         // Get on_activate function
5289         lua_pushvalue(L, object);
5290         lua_getfield(L, -1, "on_activate");
5291         if(!lua_isnil(L, -1)){
5292                 luaL_checktype(L, -1, LUA_TFUNCTION);
5293                 lua_pushvalue(L, object); // self
5294                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5295                 // Call with 2 arguments, 0 results
5296                 if(lua_pcall(L, 2, 0, 0))
5297                         script_error(L, "error running function on_activate: %s\n",
5298                                         lua_tostring(L, -1));
5299         }
5300 }
5301
5302 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5303 {
5304         realitycheck(L);
5305         assert(lua_checkstack(L, 20));
5306         verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5307
5308         // Get minetest.luaentities table
5309         lua_getglobal(L, "minetest");
5310         lua_getfield(L, -1, "luaentities");
5311         luaL_checktype(L, -1, LUA_TTABLE);
5312         int objectstable = lua_gettop(L);
5313         
5314         // Set luaentities[id] = nil
5315         lua_pushnumber(L, id); // Push id
5316         lua_pushnil(L);
5317         lua_settable(L, objectstable);
5318         
5319         lua_pop(L, 2); // pop luaentities, minetest
5320 }
5321
5322 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5323 {
5324         realitycheck(L);
5325         assert(lua_checkstack(L, 20));
5326         //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5327         StackUnroller stack_unroller(L);
5328
5329         // Get minetest.luaentities[id]
5330         luaentity_get(L, id);
5331         int object = lua_gettop(L);
5332         
5333         // Get get_staticdata function
5334         lua_pushvalue(L, object);
5335         lua_getfield(L, -1, "get_staticdata");
5336         if(lua_isnil(L, -1))
5337                 return "";
5338         
5339         luaL_checktype(L, -1, LUA_TFUNCTION);
5340         lua_pushvalue(L, object); // self
5341         // Call with 1 arguments, 1 results
5342         if(lua_pcall(L, 1, 1, 0))
5343                 script_error(L, "error running function get_staticdata: %s\n",
5344                                 lua_tostring(L, -1));
5345         
5346         size_t len=0;
5347         const char *s = lua_tolstring(L, -1, &len);
5348         return std::string(s, len);
5349 }
5350
5351 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5352                 ObjectProperties *prop)
5353 {
5354         realitycheck(L);
5355         assert(lua_checkstack(L, 20));
5356         //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5357         StackUnroller stack_unroller(L);
5358
5359         // Get minetest.luaentities[id]
5360         luaentity_get(L, id);
5361         //int object = lua_gettop(L);
5362
5363         // Set default values that differ from ObjectProperties defaults
5364         prop->hp_max = 10;
5365         
5366         // Deprecated: read object properties directly
5367         read_object_properties(L, -1, prop);
5368         
5369         // Read initial_properties
5370         lua_getfield(L, -1, "initial_properties");
5371         read_object_properties(L, -1, prop);
5372         lua_pop(L, 1);
5373 }
5374
5375 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5376 {
5377         realitycheck(L);
5378         assert(lua_checkstack(L, 20));
5379         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5380         StackUnroller stack_unroller(L);
5381
5382         // Get minetest.luaentities[id]
5383         luaentity_get(L, id);
5384         int object = lua_gettop(L);
5385         // State: object is at top of stack
5386         // Get step function
5387         lua_getfield(L, -1, "on_step");
5388         if(lua_isnil(L, -1))
5389                 return;
5390         luaL_checktype(L, -1, LUA_TFUNCTION);
5391         lua_pushvalue(L, object); // self
5392         lua_pushnumber(L, dtime); // dtime
5393         // Call with 2 arguments, 0 results
5394         if(lua_pcall(L, 2, 0, 0))
5395                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5396 }
5397
5398 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5399 //                       tool_capabilities, direction)
5400 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5401                 ServerActiveObject *puncher, float time_from_last_punch,
5402                 const ToolCapabilities *toolcap, v3f dir)
5403 {
5404         realitycheck(L);
5405         assert(lua_checkstack(L, 20));
5406         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5407         StackUnroller stack_unroller(L);
5408
5409         // Get minetest.luaentities[id]
5410         luaentity_get(L, id);
5411         int object = lua_gettop(L);
5412         // State: object is at top of stack
5413         // Get function
5414         lua_getfield(L, -1, "on_punch");
5415         if(lua_isnil(L, -1))
5416                 return;
5417         luaL_checktype(L, -1, LUA_TFUNCTION);
5418         lua_pushvalue(L, object); // self
5419         objectref_get_or_create(L, puncher); // Clicker reference
5420         lua_pushnumber(L, time_from_last_punch);
5421         push_tool_capabilities(L, *toolcap);
5422         push_v3f(L, dir);
5423         // Call with 5 arguments, 0 results
5424         if(lua_pcall(L, 5, 0, 0))
5425                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5426 }
5427
5428 // Calls entity:on_rightclick(ObjectRef clicker)
5429 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5430                 ServerActiveObject *clicker)
5431 {
5432         realitycheck(L);
5433         assert(lua_checkstack(L, 20));
5434         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5435         StackUnroller stack_unroller(L);
5436
5437         // Get minetest.luaentities[id]
5438         luaentity_get(L, id);
5439         int object = lua_gettop(L);
5440         // State: object is at top of stack
5441         // Get function
5442         lua_getfield(L, -1, "on_rightclick");
5443         if(lua_isnil(L, -1))
5444                 return;
5445         luaL_checktype(L, -1, LUA_TFUNCTION);
5446         lua_pushvalue(L, object); // self
5447         objectref_get_or_create(L, clicker); // Clicker reference
5448         // Call with 2 arguments, 0 results
5449         if(lua_pcall(L, 2, 0, 0))
5450                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
5451 }
5452