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