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