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