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