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