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