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