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