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