3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "scriptapi.h"
34 #include "serverobject.h"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
41 #include "main.h" // For g_settings
42 #include "settings.h" // For accessing g_settings
43 #include "nodemetadata.h"
44 #include "mapblock.h" // For getNodeBlockPos
45 #include "content_nodemeta.h"
47 #include "daynightratio.h"
48 #include "noise.h" // PseudoRandom for LuaPseudoRandom
49 #include "util/pointedthing.h"
52 static void stackDump(lua_State *L, std::ostream &o)
55 int top = lua_gettop(L);
56 for (i = 1; i <= top; i++) { /* repeat for each level */
57 int t = lua_type(L, i);
60 case LUA_TSTRING: /* strings */
61 o<<"\""<<lua_tostring(L, i)<<"\"";
64 case LUA_TBOOLEAN: /* booleans */
65 o<<(lua_toboolean(L, i) ? "true" : "false");
68 case LUA_TNUMBER: /* numbers */ {
70 snprintf(buf, 10, "%g", lua_tonumber(L, i));
74 default: /* other values */
75 o<<lua_typename(L, t);
84 static void realitycheck(lua_State *L)
86 int top = lua_gettop(L);
88 dstream<<"Stack is over 30:"<<std::endl;
89 stackDump(L, dstream);
90 script_error(L, "Stack is over 30 (reality check)");
100 StackUnroller(lua_State *L):
104 m_original_top = lua_gettop(m_lua); // store stack height
108 lua_settop(m_lua, m_original_top); // restore stack height
117 ModNameStorer(lua_State *L_, const std::string modname):
120 // Store current modname in registry
121 lua_pushstring(L, modname.c_str());
122 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
126 // Clear current modname in registry
128 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
133 Getters for stuff in main tables
136 static Server* get_server(lua_State *L)
138 // Get server from registry
139 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
140 Server *server = (Server*)lua_touserdata(L, -1);
145 static ServerEnvironment* get_env(lua_State *L)
147 // Get environment from registry
148 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
149 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
154 static void objectref_get(lua_State *L, u16 id)
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);
162 lua_remove(L, -2); // object_refs
163 lua_remove(L, -2); // minetest
166 static void luaentity_get(lua_State *L, u16 id)
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);
174 lua_remove(L, -2); // luaentities
175 lua_remove(L, -2); // minetest
182 static bool getstringfield(lua_State *L, int table,
183 const char *fieldname, std::string &result)
185 lua_getfield(L, table, fieldname);
187 if(lua_isstring(L, -1)){
189 const char *ptr = lua_tolstring(L, -1, &len);
190 result.assign(ptr, len);
197 static bool getintfield(lua_State *L, int table,
198 const char *fieldname, int &result)
200 lua_getfield(L, table, fieldname);
202 if(lua_isnumber(L, -1)){
203 result = lua_tonumber(L, -1);
210 static bool getfloatfield(lua_State *L, int table,
211 const char *fieldname, float &result)
213 lua_getfield(L, table, fieldname);
215 if(lua_isnumber(L, -1)){
216 result = lua_tonumber(L, -1);
223 static bool getboolfield(lua_State *L, int table,
224 const char *fieldname, bool &result)
226 lua_getfield(L, table, fieldname);
228 if(lua_isboolean(L, -1)){
229 result = lua_toboolean(L, -1);
236 static std::string checkstringfield(lua_State *L, int table,
237 const char *fieldname)
239 lua_getfield(L, table, fieldname);
240 std::string s = luaL_checkstring(L, -1);
245 static std::string getstringfield_default(lua_State *L, int table,
246 const char *fieldname, const std::string &default_)
248 std::string result = default_;
249 getstringfield(L, table, fieldname, result);
253 static int getintfield_default(lua_State *L, int table,
254 const char *fieldname, int default_)
256 int result = default_;
257 getintfield(L, table, fieldname, result);
261 static float getfloatfield_default(lua_State *L, int table,
262 const char *fieldname, float default_)
264 float result = default_;
265 getfloatfield(L, table, fieldname, result);
269 static bool getboolfield_default(lua_State *L, int table,
270 const char *fieldname, bool default_)
272 bool result = default_;
273 getboolfield(L, table, fieldname, result);
283 static bool string_to_enum(const EnumString *spec, int &result,
284 const std::string &str)
286 const EnumString *esp = spec;
288 if(str == std::string(esp->str)){
297 /*static bool enum_to_string(const EnumString *spec, std::string &result,
300 const EnumString *esp = spec;
311 static int getenumfield(lua_State *L, int table,
312 const char *fieldname, const EnumString *spec, int default_)
314 int result = default_;
315 string_to_enum(spec, result,
316 getstringfield_default(L, table, fieldname, ""));
320 static void setintfield(lua_State *L, int table,
321 const char *fieldname, int value)
323 lua_pushinteger(L, value);
326 lua_setfield(L, table, fieldname);
329 static void setfloatfield(lua_State *L, int table,
330 const char *fieldname, float value)
332 lua_pushnumber(L, value);
335 lua_setfield(L, table, fieldname);
338 static void setboolfield(lua_State *L, int table,
339 const char *fieldname, bool value)
341 lua_pushboolean(L, value);
344 lua_setfield(L, table, fieldname);
347 static void warn_if_field_exists(lua_State *L, int table,
348 const char *fieldname, const std::string &message)
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;
360 EnumString definitions
363 struct EnumString es_ItemType[] =
367 {ITEM_CRAFT, "craft"},
372 struct EnumString es_DrawType[] =
374 {NDT_NORMAL, "normal"},
375 {NDT_AIRLIKE, "airlike"},
376 {NDT_LIQUID, "liquid"},
377 {NDT_FLOWINGLIQUID, "flowingliquid"},
378 {NDT_GLASSLIKE, "glasslike"},
379 {NDT_ALLFACES, "allfaces"},
380 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
381 {NDT_TORCHLIKE, "torchlike"},
382 {NDT_SIGNLIKE, "signlike"},
383 {NDT_PLANTLIKE, "plantlike"},
384 {NDT_FENCELIKE, "fencelike"},
385 {NDT_RAILLIKE, "raillike"},
386 {NDT_NODEBOX, "nodebox"},
390 struct EnumString es_ContentParamType[] =
393 {CPT_LIGHT, "light"},
397 struct EnumString es_ContentParamType2[] =
401 {CPT2_FLOWINGLIQUID, "flowingliquid"},
402 {CPT2_FACEDIR, "facedir"},
403 {CPT2_WALLMOUNTED, "wallmounted"},
407 struct EnumString es_LiquidType[] =
409 {LIQUID_NONE, "none"},
410 {LIQUID_FLOWING, "flowing"},
411 {LIQUID_SOURCE, "source"},
415 struct EnumString es_NodeBoxType[] =
417 {NODEBOX_REGULAR, "regular"},
418 {NODEBOX_FIXED, "fixed"},
419 {NODEBOX_WALLMOUNTED, "wallmounted"},
423 struct EnumString es_CraftMethod[] =
425 {CRAFT_METHOD_NORMAL, "normal"},
426 {CRAFT_METHOD_COOKING, "cooking"},
427 {CRAFT_METHOD_FUEL, "fuel"},
431 struct EnumString es_TileAnimationType[] =
434 {TAT_VERTICAL_FRAMES, "vertical_frames"},
439 C struct <-> Lua table converter functions
442 static void push_v3f(lua_State *L, v3f p)
445 lua_pushnumber(L, p.X);
446 lua_setfield(L, -2, "x");
447 lua_pushnumber(L, p.Y);
448 lua_setfield(L, -2, "y");
449 lua_pushnumber(L, p.Z);
450 lua_setfield(L, -2, "z");
453 static v2s16 read_v2s16(lua_State *L, int index)
456 luaL_checktype(L, index, LUA_TTABLE);
457 lua_getfield(L, index, "x");
458 p.X = lua_tonumber(L, -1);
460 lua_getfield(L, index, "y");
461 p.Y = lua_tonumber(L, -1);
466 static v2f read_v2f(lua_State *L, int index)
469 luaL_checktype(L, index, LUA_TTABLE);
470 lua_getfield(L, index, "x");
471 p.X = lua_tonumber(L, -1);
473 lua_getfield(L, index, "y");
474 p.Y = lua_tonumber(L, -1);
479 static v3f read_v3f(lua_State *L, int index)
482 luaL_checktype(L, index, LUA_TTABLE);
483 lua_getfield(L, index, "x");
484 pos.X = lua_tonumber(L, -1);
486 lua_getfield(L, index, "y");
487 pos.Y = lua_tonumber(L, -1);
489 lua_getfield(L, index, "z");
490 pos.Z = lua_tonumber(L, -1);
495 static v3f check_v3f(lua_State *L, int index)
498 luaL_checktype(L, index, LUA_TTABLE);
499 lua_getfield(L, index, "x");
500 pos.X = luaL_checknumber(L, -1);
502 lua_getfield(L, index, "y");
503 pos.Y = luaL_checknumber(L, -1);
505 lua_getfield(L, index, "z");
506 pos.Z = luaL_checknumber(L, -1);
511 static void pushFloatPos(lua_State *L, v3f p)
517 static v3f checkFloatPos(lua_State *L, int index)
519 return check_v3f(L, index) * BS;
522 static void push_v3s16(lua_State *L, v3s16 p)
525 lua_pushnumber(L, p.X);
526 lua_setfield(L, -2, "x");
527 lua_pushnumber(L, p.Y);
528 lua_setfield(L, -2, "y");
529 lua_pushnumber(L, p.Z);
530 lua_setfield(L, -2, "z");
533 static v3s16 read_v3s16(lua_State *L, int index)
535 // Correct rounding at <0
536 v3f pf = read_v3f(L, index);
537 return floatToInt(pf, 1.0);
540 static v3s16 check_v3s16(lua_State *L, int index)
542 // Correct rounding at <0
543 v3f pf = check_v3f(L, index);
544 return floatToInt(pf, 1.0);
547 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
550 lua_pushstring(L, ndef->get(n).name.c_str());
551 lua_setfield(L, -2, "name");
552 lua_pushnumber(L, n.getParam1());
553 lua_setfield(L, -2, "param1");
554 lua_pushnumber(L, n.getParam2());
555 lua_setfield(L, -2, "param2");
558 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
560 lua_getfield(L, index, "name");
561 const char *name = luaL_checkstring(L, -1);
564 lua_getfield(L, index, "param1");
568 param1 = lua_tonumber(L, -1);
571 lua_getfield(L, index, "param2");
575 param2 = lua_tonumber(L, -1);
577 return MapNode(ndef, name, param1, param2);
580 static video::SColor readARGB8(lua_State *L, int index)
583 luaL_checktype(L, index, LUA_TTABLE);
584 lua_getfield(L, index, "a");
585 if(lua_isnumber(L, -1))
586 color.setAlpha(lua_tonumber(L, -1));
588 lua_getfield(L, index, "r");
589 color.setRed(lua_tonumber(L, -1));
591 lua_getfield(L, index, "g");
592 color.setGreen(lua_tonumber(L, -1));
594 lua_getfield(L, index, "b");
595 color.setBlue(lua_tonumber(L, -1));
600 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
603 if(lua_istable(L, index)){
604 lua_rawgeti(L, index, 1);
605 box.MinEdge.X = lua_tonumber(L, -1) * scale;
607 lua_rawgeti(L, index, 2);
608 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
610 lua_rawgeti(L, index, 3);
611 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
613 lua_rawgeti(L, index, 4);
614 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
616 lua_rawgeti(L, index, 5);
617 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
619 lua_rawgeti(L, index, 6);
620 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
626 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
628 std::vector<aabb3f> boxes;
629 if(lua_istable(L, index)){
630 int n = lua_objlen(L, index);
631 // Check if it's a single box or a list of boxes
632 bool possibly_single_box = (n == 6);
633 for(int i = 1; i <= n && possibly_single_box; i++){
634 lua_rawgeti(L, index, i);
635 if(!lua_isnumber(L, -1))
636 possibly_single_box = false;
639 if(possibly_single_box){
641 boxes.push_back(read_aabb3f(L, index, scale));
643 // Read a list of boxes
644 for(int i = 1; i <= n; i++){
645 lua_rawgeti(L, index, i);
646 boxes.push_back(read_aabb3f(L, -1, scale));
654 static NodeBox read_nodebox(lua_State *L, int index)
657 if(lua_istable(L, -1)){
658 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
659 es_NodeBoxType, NODEBOX_REGULAR);
661 lua_getfield(L, index, "fixed");
662 if(lua_istable(L, -1))
663 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
666 lua_getfield(L, index, "wall_top");
667 if(lua_istable(L, -1))
668 nodebox.wall_top = read_aabb3f(L, -1, BS);
671 lua_getfield(L, index, "wall_bottom");
672 if(lua_istable(L, -1))
673 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
676 lua_getfield(L, index, "wall_side");
677 if(lua_istable(L, -1))
678 nodebox.wall_side = read_aabb3f(L, -1, BS);
687 static void read_groups(lua_State *L, int index,
688 std::map<std::string, int> &result)
690 if (!lua_istable(L,index))
696 while(lua_next(L, index) != 0){
697 // key at index -2 and value at index -1
698 std::string name = luaL_checkstring(L, -2);
699 int rating = luaL_checkinteger(L, -1);
700 result[name] = rating;
701 // removes value, keeps key for next iteration
709 static void read_privileges(lua_State *L, int index,
710 std::set<std::string> &result)
716 while(lua_next(L, index) != 0){
717 // key at index -2 and value at index -1
718 std::string key = luaL_checkstring(L, -2);
719 bool value = lua_toboolean(L, -1);
722 // removes value, keeps key for next iteration
731 static ToolCapabilities read_tool_capabilities(
732 lua_State *L, int table)
734 ToolCapabilities toolcap;
735 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
736 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
737 lua_getfield(L, table, "groupcaps");
738 if(lua_istable(L, -1)){
739 int table_groupcaps = lua_gettop(L);
741 while(lua_next(L, table_groupcaps) != 0){
742 // key at index -2 and value at index -1
743 std::string groupname = luaL_checkstring(L, -2);
744 if(lua_istable(L, -1)){
745 int table_groupcap = lua_gettop(L);
746 // This will be created
747 ToolGroupCap groupcap;
748 // Read simple parameters
749 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
750 getintfield(L, table_groupcap, "uses", groupcap.uses);
751 // DEPRECATED: maxwear
753 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
755 groupcap.uses = 1.0/maxwear;
758 infostream<<script_get_backtrace(L)<<std::endl;
759 infostream<<"WARNING: field \"maxwear\" is deprecated; "
760 <<"should replace with uses=1/maxwear"<<std::endl;
762 // Read "times" table
763 lua_getfield(L, table_groupcap, "times");
764 if(lua_istable(L, -1)){
765 int table_times = lua_gettop(L);
767 while(lua_next(L, table_times) != 0){
768 // key at index -2 and value at index -1
769 int rating = luaL_checkinteger(L, -2);
770 float time = luaL_checknumber(L, -1);
771 groupcap.times[rating] = time;
772 // removes value, keeps key for next iteration
777 // Insert groupcap into toolcap
778 toolcap.groupcaps[groupname] = groupcap;
780 // removes value, keeps key for next iteration
788 static void set_tool_capabilities(lua_State *L, int table,
789 const ToolCapabilities &toolcap)
791 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
792 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
793 // Create groupcaps table
796 for(std::map<std::string, ToolGroupCap>::const_iterator
797 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
798 // Create groupcap table
800 const std::string &name = i->first;
801 const ToolGroupCap &groupcap = i->second;
802 // Create subtable "times"
804 for(std::map<int, float>::const_iterator
805 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
806 int rating = i->first;
807 float time = i->second;
808 lua_pushinteger(L, rating);
809 lua_pushnumber(L, time);
812 // Set subtable "times"
813 lua_setfield(L, -2, "times");
814 // Set simple parameters
815 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
816 setintfield(L, -1, "uses", groupcap.uses);
817 // Insert groupcap table into groupcaps table
818 lua_setfield(L, -2, name.c_str());
820 // Set groupcaps table
821 lua_setfield(L, -2, "groupcaps");
824 static void push_tool_capabilities(lua_State *L,
825 const ToolCapabilities &prop)
828 set_tool_capabilities(L, -1, prop);
835 static void set_dig_params(lua_State *L, int table,
836 const DigParams ¶ms)
838 setboolfield(L, table, "diggable", params.diggable);
839 setfloatfield(L, table, "time", params.time);
840 setintfield(L, table, "wear", params.wear);
843 static void push_dig_params(lua_State *L,
844 const DigParams ¶ms)
847 set_dig_params(L, -1, params);
854 static void set_hit_params(lua_State *L, int table,
855 const HitParams ¶ms)
857 setintfield(L, table, "hp", params.hp);
858 setintfield(L, table, "wear", params.wear);
861 static void push_hit_params(lua_State *L,
862 const HitParams ¶ms)
865 set_hit_params(L, -1, params);
872 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
875 if(pointed.type == POINTEDTHING_NODE)
877 lua_pushstring(L, "node");
878 lua_setfield(L, -2, "type");
879 push_v3s16(L, pointed.node_undersurface);
880 lua_setfield(L, -2, "under");
881 push_v3s16(L, pointed.node_abovesurface);
882 lua_setfield(L, -2, "above");
884 else if(pointed.type == POINTEDTHING_OBJECT)
886 lua_pushstring(L, "object");
887 lua_setfield(L, -2, "type");
888 objectref_get(L, pointed.object_id);
889 lua_setfield(L, -2, "ref");
893 lua_pushstring(L, "nothing");
894 lua_setfield(L, -2, "type");
902 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
905 index = lua_gettop(L) + 1 + index;
906 if(lua_isnil(L, index)){
907 } else if(lua_istable(L, index)){
908 getstringfield(L, index, "name", spec.name);
909 getfloatfield(L, index, "gain", spec.gain);
910 } else if(lua_isstring(L, index)){
911 spec.name = lua_tostring(L, index);
919 static void read_object_properties(lua_State *L, int index,
920 ObjectProperties *prop)
923 index = lua_gettop(L) + 1 + index;
924 if(!lua_istable(L, index))
927 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
929 getboolfield(L, -1, "physical", prop->physical);
931 getfloatfield(L, -1, "weight", prop->weight);
933 lua_getfield(L, -1, "collisionbox");
934 if(lua_istable(L, -1))
935 prop->collisionbox = read_aabb3f(L, -1, 1.0);
938 getstringfield(L, -1, "visual", prop->visual);
940 getstringfield(L, -1, "mesh", prop->mesh);
942 lua_getfield(L, -1, "visual_size");
943 if(lua_istable(L, -1))
944 prop->visual_size = read_v2f(L, -1);
947 lua_getfield(L, -1, "textures");
948 if(lua_istable(L, -1)){
949 prop->textures.clear();
950 int table = lua_gettop(L);
952 while(lua_next(L, table) != 0){
953 // key at index -2 and value at index -1
954 if(lua_isstring(L, -1))
955 prop->textures.push_back(lua_tostring(L, -1));
957 prop->textures.push_back("");
958 // removes value, keeps key for next iteration
964 lua_getfield(L, -1, "spritediv");
965 if(lua_istable(L, -1))
966 prop->spritediv = read_v2s16(L, -1);
969 lua_getfield(L, -1, "initial_sprite_basepos");
970 if(lua_istable(L, -1))
971 prop->initial_sprite_basepos = read_v2s16(L, -1);
974 getboolfield(L, -1, "is_visible", prop->is_visible);
975 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
976 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
983 static ItemDefinition read_item_definition(lua_State *L, int index,
984 ItemDefinition default_def = ItemDefinition())
987 index = lua_gettop(L) + 1 + index;
989 // Read the item definition
990 ItemDefinition def = default_def;
992 def.type = (ItemType)getenumfield(L, index, "type",
993 es_ItemType, ITEM_NONE);
994 getstringfield(L, index, "name", def.name);
995 getstringfield(L, index, "description", def.description);
996 getstringfield(L, index, "inventory_image", def.inventory_image);
997 getstringfield(L, index, "wield_image", def.wield_image);
999 lua_getfield(L, index, "wield_scale");
1000 if(lua_istable(L, -1)){
1001 def.wield_scale = check_v3f(L, -1);
1005 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1006 if(def.stack_max == 0)
1009 lua_getfield(L, index, "on_use");
1010 def.usable = lua_isfunction(L, -1);
1013 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1015 warn_if_field_exists(L, index, "tool_digging_properties",
1016 "deprecated: use tool_capabilities");
1018 lua_getfield(L, index, "tool_capabilities");
1019 if(lua_istable(L, -1)){
1020 def.tool_capabilities = new ToolCapabilities(
1021 read_tool_capabilities(L, -1));
1024 // If name is "" (hand), ensure there are ToolCapabilities
1025 // because it will be looked up there whenever any other item has
1026 // no ToolCapabilities
1027 if(def.name == "" && def.tool_capabilities == NULL){
1028 def.tool_capabilities = new ToolCapabilities();
1031 lua_getfield(L, index, "groups");
1032 read_groups(L, -1, def.groups);
1035 // Client shall immediately place this node when player places the item.
1036 // Server will update the precise end result a moment later.
1037 // "" = no prediction
1038 getstringfield(L, index, "node_placement_prediction",
1039 def.node_placement_prediction);
1048 static TileDef read_tiledef(lua_State *L, int index)
1051 index = lua_gettop(L) + 1 + index;
1055 // key at index -2 and value at index
1056 if(lua_isstring(L, index)){
1057 // "default_lava.png"
1058 tiledef.name = lua_tostring(L, index);
1060 else if(lua_istable(L, index))
1062 // {name="default_lava.png", animation={}}
1064 getstringfield(L, index, "name", tiledef.name);
1065 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1066 tiledef.backface_culling = getboolfield_default(
1067 L, index, "backface_culling", true);
1069 lua_getfield(L, index, "animation");
1070 if(lua_istable(L, -1)){
1071 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1072 tiledef.animation.type = (TileAnimationType)
1073 getenumfield(L, -1, "type", es_TileAnimationType,
1075 tiledef.animation.aspect_w =
1076 getintfield_default(L, -1, "aspect_w", 16);
1077 tiledef.animation.aspect_h =
1078 getintfield_default(L, -1, "aspect_h", 16);
1079 tiledef.animation.length =
1080 getfloatfield_default(L, -1, "length", 1.0);
1092 static ContentFeatures read_content_features(lua_State *L, int index)
1095 index = lua_gettop(L) + 1 + index;
1099 /* Cache existence of some callbacks */
1100 lua_getfield(L, index, "on_construct");
1101 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1103 lua_getfield(L, index, "on_destruct");
1104 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1106 lua_getfield(L, index, "after_destruct");
1107 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1111 getstringfield(L, index, "name", f.name);
1114 lua_getfield(L, index, "groups");
1115 read_groups(L, -1, f.groups);
1118 /* Visual definition */
1120 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1122 getfloatfield(L, index, "visual_scale", f.visual_scale);
1125 lua_getfield(L, index, "tiles");
1126 // If nil, try the deprecated name "tile_images" instead
1127 if(lua_isnil(L, -1)){
1129 warn_if_field_exists(L, index, "tile_images",
1130 "Deprecated; new name is \"tiles\".");
1131 lua_getfield(L, index, "tile_images");
1133 if(lua_istable(L, -1)){
1134 int table = lua_gettop(L);
1137 while(lua_next(L, table) != 0){
1138 // Read tiledef from value
1139 f.tiledef[i] = read_tiledef(L, -1);
1140 // removes value, keeps key for next iteration
1148 // Copy last value to all remaining textures
1150 TileDef lasttile = f.tiledef[i-1];
1152 f.tiledef[i] = lasttile;
1159 // special_tiles = {}
1160 lua_getfield(L, index, "special_tiles");
1161 // If nil, try the deprecated name "special_materials" instead
1162 if(lua_isnil(L, -1)){
1164 warn_if_field_exists(L, index, "special_materials",
1165 "Deprecated; new name is \"special_tiles\".");
1166 lua_getfield(L, index, "special_materials");
1168 if(lua_istable(L, -1)){
1169 int table = lua_gettop(L);
1172 while(lua_next(L, table) != 0){
1173 // Read tiledef from value
1174 f.tiledef_special[i] = read_tiledef(L, -1);
1175 // removes value, keeps key for next iteration
1186 f.alpha = getintfield_default(L, index, "alpha", 255);
1190 lua_getfield(L, index, "post_effect_color");
1191 if(!lua_isnil(L, -1))
1192 f.post_effect_color = readARGB8(L, -1);
1195 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1196 es_ContentParamType, CPT_NONE);
1197 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1198 es_ContentParamType2, CPT2_NONE);
1200 // Warn about some deprecated fields
1201 warn_if_field_exists(L, index, "wall_mounted",
1202 "deprecated: use paramtype2 = 'wallmounted'");
1203 warn_if_field_exists(L, index, "light_propagates",
1204 "deprecated: determined from paramtype");
1205 warn_if_field_exists(L, index, "dug_item",
1206 "deprecated: use 'drop' field");
1207 warn_if_field_exists(L, index, "extra_dug_item",
1208 "deprecated: use 'drop' field");
1209 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1210 "deprecated: use 'drop' field");
1211 warn_if_field_exists(L, index, "metadata_name",
1212 "deprecated: use on_add and metadata callbacks");
1214 // True for all ground-like things like stone and mud, false for eg. trees
1215 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1216 f.light_propagates = (f.param_type == CPT_LIGHT);
1217 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1218 // This is used for collision detection.
1219 // Also for general solidness queries.
1220 getboolfield(L, index, "walkable", f.walkable);
1221 // Player can point to these
1222 getboolfield(L, index, "pointable", f.pointable);
1223 // Player can dig these
1224 getboolfield(L, index, "diggable", f.diggable);
1225 // Player can climb these
1226 getboolfield(L, index, "climbable", f.climbable);
1227 // Player can build on these
1228 getboolfield(L, index, "buildable_to", f.buildable_to);
1229 // Whether the node is non-liquid, source liquid or flowing liquid
1230 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1231 es_LiquidType, LIQUID_NONE);
1232 // If the content is liquid, this is the flowing version of the liquid.
1233 getstringfield(L, index, "liquid_alternative_flowing",
1234 f.liquid_alternative_flowing);
1235 // If the content is liquid, this is the source version of the liquid.
1236 getstringfield(L, index, "liquid_alternative_source",
1237 f.liquid_alternative_source);
1238 // Viscosity for fluid flow, ranging from 1 to 7, with
1239 // 1 giving almost instantaneous propagation and 7 being
1240 // the slowest possible
1241 f.liquid_viscosity = getintfield_default(L, index,
1242 "liquid_viscosity", f.liquid_viscosity);
1243 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1244 // Amount of light the node emits
1245 f.light_source = getintfield_default(L, index,
1246 "light_source", f.light_source);
1247 f.damage_per_second = getintfield_default(L, index,
1248 "damage_per_second", f.damage_per_second);
1250 lua_getfield(L, index, "node_box");
1251 if(lua_istable(L, -1))
1252 f.node_box = read_nodebox(L, -1);
1255 lua_getfield(L, index, "selection_box");
1256 if(lua_istable(L, -1))
1257 f.selection_box = read_nodebox(L, -1);
1260 // Set to true if paramtype used to be 'facedir_simple'
1261 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1262 // Set to true if wall_mounted used to be set to true
1263 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1266 lua_getfield(L, index, "sounds");
1267 if(lua_istable(L, -1)){
1268 lua_getfield(L, -1, "footstep");
1269 read_soundspec(L, -1, f.sound_footstep);
1271 lua_getfield(L, -1, "dig");
1272 read_soundspec(L, -1, f.sound_dig);
1274 lua_getfield(L, -1, "dug");
1275 read_soundspec(L, -1, f.sound_dug);
1287 static ItemStack read_item(lua_State *L, int index);
1288 static std::vector<ItemStack> read_items(lua_State *L, int index);
1289 // creates a table of ItemStacks
1290 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1292 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1293 lua_State *L, int tableindex, int forcesize=-1)
1296 tableindex = lua_gettop(L) + 1 + tableindex;
1297 // If nil, delete list
1298 if(lua_isnil(L, tableindex)){
1299 inv->deleteList(name);
1302 // Otherwise set list
1303 std::vector<ItemStack> items = read_items(L, tableindex);
1304 int listsize = (forcesize != -1) ? forcesize : items.size();
1305 InventoryList *invlist = inv->addList(name, listsize);
1307 for(std::vector<ItemStack>::const_iterator
1308 i = items.begin(); i != items.end(); i++){
1309 if(forcesize != -1 && index == forcesize)
1311 invlist->changeItem(index, *i);
1314 while(forcesize != -1 && index < forcesize){
1315 invlist->deleteItem(index);
1320 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1323 InventoryList *invlist = inv->getList(name);
1324 if(invlist == NULL){
1328 std::vector<ItemStack> items;
1329 for(u32 i=0; i<invlist->getSize(); i++)
1330 items.push_back(invlist->getItem(i));
1331 push_items(L, items);
1335 Helpful macros for userdata classes
1338 #define method(class, name) {#name, class::l_##name}
1349 static const char className[];
1350 static const luaL_reg methods[];
1352 // Exported functions
1354 // garbage collector
1355 static int gc_object(lua_State *L)
1357 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1362 // is_empty(self) -> true/false
1363 static int l_is_empty(lua_State *L)
1365 LuaItemStack *o = checkobject(L, 1);
1366 ItemStack &item = o->m_stack;
1367 lua_pushboolean(L, item.empty());
1371 // get_name(self) -> string
1372 static int l_get_name(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1376 lua_pushstring(L, item.name.c_str());
1380 // get_count(self) -> number
1381 static int l_get_count(lua_State *L)
1383 LuaItemStack *o = checkobject(L, 1);
1384 ItemStack &item = o->m_stack;
1385 lua_pushinteger(L, item.count);
1389 // get_wear(self) -> number
1390 static int l_get_wear(lua_State *L)
1392 LuaItemStack *o = checkobject(L, 1);
1393 ItemStack &item = o->m_stack;
1394 lua_pushinteger(L, item.wear);
1398 // get_metadata(self) -> string
1399 static int l_get_metadata(lua_State *L)
1401 LuaItemStack *o = checkobject(L, 1);
1402 ItemStack &item = o->m_stack;
1403 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1407 // clear(self) -> true
1408 static int l_clear(lua_State *L)
1410 LuaItemStack *o = checkobject(L, 1);
1412 lua_pushboolean(L, true);
1416 // replace(self, itemstack or itemstring or table or nil) -> true
1417 static int l_replace(lua_State *L)
1419 LuaItemStack *o = checkobject(L, 1);
1420 o->m_stack = read_item(L, 2);
1421 lua_pushboolean(L, true);
1425 // to_string(self) -> string
1426 static int l_to_string(lua_State *L)
1428 LuaItemStack *o = checkobject(L, 1);
1429 std::string itemstring = o->m_stack.getItemString();
1430 lua_pushstring(L, itemstring.c_str());
1434 // to_table(self) -> table or nil
1435 static int l_to_table(lua_State *L)
1437 LuaItemStack *o = checkobject(L, 1);
1438 const ItemStack &item = o->m_stack;
1446 lua_pushstring(L, item.name.c_str());
1447 lua_setfield(L, -2, "name");
1448 lua_pushinteger(L, item.count);
1449 lua_setfield(L, -2, "count");
1450 lua_pushinteger(L, item.wear);
1451 lua_setfield(L, -2, "wear");
1452 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1453 lua_setfield(L, -2, "metadata");
1458 // get_stack_max(self) -> number
1459 static int l_get_stack_max(lua_State *L)
1461 LuaItemStack *o = checkobject(L, 1);
1462 ItemStack &item = o->m_stack;
1463 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1467 // get_free_space(self) -> number
1468 static int l_get_free_space(lua_State *L)
1470 LuaItemStack *o = checkobject(L, 1);
1471 ItemStack &item = o->m_stack;
1472 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1476 // is_known(self) -> true/false
1477 // Checks if the item is defined.
1478 static int l_is_known(lua_State *L)
1480 LuaItemStack *o = checkobject(L, 1);
1481 ItemStack &item = o->m_stack;
1482 bool is_known = item.isKnown(get_server(L)->idef());
1483 lua_pushboolean(L, is_known);
1487 // get_definition(self) -> table
1488 // Returns the item definition table from minetest.registered_items,
1489 // or a fallback one (name="unknown")
1490 static int l_get_definition(lua_State *L)
1492 LuaItemStack *o = checkobject(L, 1);
1493 ItemStack &item = o->m_stack;
1495 // Get minetest.registered_items[name]
1496 lua_getglobal(L, "minetest");
1497 lua_getfield(L, -1, "registered_items");
1498 luaL_checktype(L, -1, LUA_TTABLE);
1499 lua_getfield(L, -1, item.name.c_str());
1500 if(lua_isnil(L, -1))
1503 lua_getfield(L, -1, "unknown");
1508 // get_tool_capabilities(self) -> table
1509 // Returns the effective tool digging properties.
1510 // Returns those of the hand ("") if this item has none associated.
1511 static int l_get_tool_capabilities(lua_State *L)
1513 LuaItemStack *o = checkobject(L, 1);
1514 ItemStack &item = o->m_stack;
1515 const ToolCapabilities &prop =
1516 item.getToolCapabilities(get_server(L)->idef());
1517 push_tool_capabilities(L, prop);
1521 // add_wear(self, amount) -> true/false
1522 // The range for "amount" is [0,65535]. Wear is only added if the item
1523 // is a tool. Adding wear might destroy the item.
1524 // Returns true if the item is (or was) a tool.
1525 static int l_add_wear(lua_State *L)
1527 LuaItemStack *o = checkobject(L, 1);
1528 ItemStack &item = o->m_stack;
1529 int amount = lua_tointeger(L, 2);
1530 bool result = item.addWear(amount, get_server(L)->idef());
1531 lua_pushboolean(L, result);
1535 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1536 // Returns leftover item stack
1537 static int l_add_item(lua_State *L)
1539 LuaItemStack *o = checkobject(L, 1);
1540 ItemStack &item = o->m_stack;
1541 ItemStack newitem = read_item(L, 2);
1542 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1543 create(L, leftover);
1547 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1548 // First return value is true iff the new item fits fully into the stack
1549 // Second return value is the would-be-left-over item stack
1550 static int l_item_fits(lua_State *L)
1552 LuaItemStack *o = checkobject(L, 1);
1553 ItemStack &item = o->m_stack;
1554 ItemStack newitem = read_item(L, 2);
1556 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1557 lua_pushboolean(L, fits); // first return value
1558 create(L, restitem); // second return value
1562 // take_item(self, takecount=1) -> itemstack
1563 static int l_take_item(lua_State *L)
1565 LuaItemStack *o = checkobject(L, 1);
1566 ItemStack &item = o->m_stack;
1568 if(!lua_isnone(L, 2))
1569 takecount = luaL_checkinteger(L, 2);
1570 ItemStack taken = item.takeItem(takecount);
1575 // peek_item(self, peekcount=1) -> itemstack
1576 static int l_peek_item(lua_State *L)
1578 LuaItemStack *o = checkobject(L, 1);
1579 ItemStack &item = o->m_stack;
1581 if(!lua_isnone(L, 2))
1582 peekcount = lua_tointeger(L, 2);
1583 ItemStack peekaboo = item.peekItem(peekcount);
1584 create(L, peekaboo);
1589 LuaItemStack(const ItemStack &item):
1598 const ItemStack& getItem() const
1602 ItemStack& getItem()
1607 // LuaItemStack(itemstack or itemstring or table or nil)
1608 // Creates an LuaItemStack and leaves it on top of stack
1609 static int create_object(lua_State *L)
1611 ItemStack item = read_item(L, 1);
1612 LuaItemStack *o = new LuaItemStack(item);
1613 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1614 luaL_getmetatable(L, className);
1615 lua_setmetatable(L, -2);
1618 // Not callable from Lua
1619 static int create(lua_State *L, const ItemStack &item)
1621 LuaItemStack *o = new LuaItemStack(item);
1622 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1623 luaL_getmetatable(L, className);
1624 lua_setmetatable(L, -2);
1628 static LuaItemStack* checkobject(lua_State *L, int narg)
1630 luaL_checktype(L, narg, LUA_TUSERDATA);
1631 void *ud = luaL_checkudata(L, narg, className);
1632 if(!ud) luaL_typerror(L, narg, className);
1633 return *(LuaItemStack**)ud; // unbox pointer
1636 static void Register(lua_State *L)
1639 int methodtable = lua_gettop(L);
1640 luaL_newmetatable(L, className);
1641 int metatable = lua_gettop(L);
1643 lua_pushliteral(L, "__metatable");
1644 lua_pushvalue(L, methodtable);
1645 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1647 lua_pushliteral(L, "__index");
1648 lua_pushvalue(L, methodtable);
1649 lua_settable(L, metatable);
1651 lua_pushliteral(L, "__gc");
1652 lua_pushcfunction(L, gc_object);
1653 lua_settable(L, metatable);
1655 lua_pop(L, 1); // drop metatable
1657 luaL_openlib(L, 0, methods, 0); // fill methodtable
1658 lua_pop(L, 1); // drop methodtable
1660 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1661 lua_register(L, className, create_object);
1664 const char LuaItemStack::className[] = "ItemStack";
1665 const luaL_reg LuaItemStack::methods[] = {
1666 method(LuaItemStack, is_empty),
1667 method(LuaItemStack, get_name),
1668 method(LuaItemStack, get_count),
1669 method(LuaItemStack, get_wear),
1670 method(LuaItemStack, get_metadata),
1671 method(LuaItemStack, clear),
1672 method(LuaItemStack, replace),
1673 method(LuaItemStack, to_string),
1674 method(LuaItemStack, to_table),
1675 method(LuaItemStack, get_stack_max),
1676 method(LuaItemStack, get_free_space),
1677 method(LuaItemStack, is_known),
1678 method(LuaItemStack, get_definition),
1679 method(LuaItemStack, get_tool_capabilities),
1680 method(LuaItemStack, add_wear),
1681 method(LuaItemStack, add_item),
1682 method(LuaItemStack, item_fits),
1683 method(LuaItemStack, take_item),
1684 method(LuaItemStack, peek_item),
1688 static ItemStack read_item(lua_State *L, int index)
1691 index = lua_gettop(L) + 1 + index;
1693 if(lua_isnil(L, index))
1697 else if(lua_isuserdata(L, index))
1699 // Convert from LuaItemStack
1700 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1701 return o->getItem();
1703 else if(lua_isstring(L, index))
1705 // Convert from itemstring
1706 std::string itemstring = lua_tostring(L, index);
1707 IItemDefManager *idef = get_server(L)->idef();
1711 item.deSerialize(itemstring, idef);
1714 catch(SerializationError &e)
1716 infostream<<"WARNING: unable to create item from itemstring"
1717 <<": "<<itemstring<<std::endl;
1721 else if(lua_istable(L, index))
1723 // Convert from table
1724 IItemDefManager *idef = get_server(L)->idef();
1725 std::string name = getstringfield_default(L, index, "name", "");
1726 int count = getintfield_default(L, index, "count", 1);
1727 int wear = getintfield_default(L, index, "wear", 0);
1728 std::string metadata = getstringfield_default(L, index, "metadata", "");
1729 return ItemStack(name, count, wear, metadata, idef);
1733 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1737 static std::vector<ItemStack> read_items(lua_State *L, int index)
1740 index = lua_gettop(L) + 1 + index;
1742 std::vector<ItemStack> items;
1743 luaL_checktype(L, index, LUA_TTABLE);
1745 while(lua_next(L, index) != 0){
1746 // key at index -2 and value at index -1
1747 items.push_back(read_item(L, -1));
1748 // removes value, keeps key for next iteration
1754 // creates a table of ItemStacks
1755 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1757 // Get the table insert function
1758 lua_getglobal(L, "table");
1759 lua_getfield(L, -1, "insert");
1760 int table_insert = lua_gettop(L);
1761 // Create and fill table
1763 int table = lua_gettop(L);
1764 for(u32 i=0; i<items.size(); i++){
1765 ItemStack item = items[i];
1766 lua_pushvalue(L, table_insert);
1767 lua_pushvalue(L, table);
1768 LuaItemStack::create(L, item);
1769 if(lua_pcall(L, 2, 0, 0))
1770 script_error(L, "error: %s", lua_tostring(L, -1));
1772 lua_remove(L, -2); // Remove table
1773 lua_remove(L, -2); // Remove insert
1783 InventoryLocation m_loc;
1785 static const char className[];
1786 static const luaL_reg methods[];
1788 static InvRef *checkobject(lua_State *L, int narg)
1790 luaL_checktype(L, narg, LUA_TUSERDATA);
1791 void *ud = luaL_checkudata(L, narg, className);
1792 if(!ud) luaL_typerror(L, narg, className);
1793 return *(InvRef**)ud; // unbox pointer
1796 static Inventory* getinv(lua_State *L, InvRef *ref)
1798 return get_server(L)->getInventory(ref->m_loc);
1801 static InventoryList* getlist(lua_State *L, InvRef *ref,
1802 const char *listname)
1804 Inventory *inv = getinv(L, ref);
1807 return inv->getList(listname);
1810 static void reportInventoryChange(lua_State *L, InvRef *ref)
1812 // Inform other things that the inventory has changed
1813 get_server(L)->setInventoryModified(ref->m_loc);
1816 // Exported functions
1818 // garbage collector
1819 static int gc_object(lua_State *L) {
1820 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1825 // is_empty(self, listname) -> true/false
1826 static int l_is_empty(lua_State *L)
1828 InvRef *ref = checkobject(L, 1);
1829 const char *listname = luaL_checkstring(L, 2);
1830 InventoryList *list = getlist(L, ref, listname);
1831 if(list && list->getUsedSlots() > 0){
1832 lua_pushboolean(L, false);
1834 lua_pushboolean(L, true);
1839 // get_size(self, listname)
1840 static int l_get_size(lua_State *L)
1842 InvRef *ref = checkobject(L, 1);
1843 const char *listname = luaL_checkstring(L, 2);
1844 InventoryList *list = getlist(L, ref, listname);
1846 lua_pushinteger(L, list->getSize());
1848 lua_pushinteger(L, 0);
1853 // get_width(self, listname)
1854 static int l_get_width(lua_State *L)
1856 InvRef *ref = checkobject(L, 1);
1857 const char *listname = luaL_checkstring(L, 2);
1858 InventoryList *list = getlist(L, ref, listname);
1860 lua_pushinteger(L, list->getWidth());
1862 lua_pushinteger(L, 0);
1867 // set_size(self, listname, size)
1868 static int l_set_size(lua_State *L)
1870 InvRef *ref = checkobject(L, 1);
1871 const char *listname = luaL_checkstring(L, 2);
1872 int newsize = luaL_checknumber(L, 3);
1873 Inventory *inv = getinv(L, ref);
1875 inv->deleteList(listname);
1876 reportInventoryChange(L, ref);
1879 InventoryList *list = inv->getList(listname);
1881 list->setSize(newsize);
1883 list = inv->addList(listname, newsize);
1885 reportInventoryChange(L, ref);
1889 // set_width(self, listname, size)
1890 static int l_set_width(lua_State *L)
1892 InvRef *ref = checkobject(L, 1);
1893 const char *listname = luaL_checkstring(L, 2);
1894 int newwidth = luaL_checknumber(L, 3);
1895 Inventory *inv = getinv(L, ref);
1896 InventoryList *list = inv->getList(listname);
1898 list->setWidth(newwidth);
1902 reportInventoryChange(L, ref);
1906 // get_stack(self, listname, i) -> itemstack
1907 static int l_get_stack(lua_State *L)
1909 InvRef *ref = checkobject(L, 1);
1910 const char *listname = luaL_checkstring(L, 2);
1911 int i = luaL_checknumber(L, 3) - 1;
1912 InventoryList *list = getlist(L, ref, listname);
1914 if(list != NULL && i >= 0 && i < (int) list->getSize())
1915 item = list->getItem(i);
1916 LuaItemStack::create(L, item);
1920 // set_stack(self, listname, i, stack) -> true/false
1921 static int l_set_stack(lua_State *L)
1923 InvRef *ref = checkobject(L, 1);
1924 const char *listname = luaL_checkstring(L, 2);
1925 int i = luaL_checknumber(L, 3) - 1;
1926 ItemStack newitem = read_item(L, 4);
1927 InventoryList *list = getlist(L, ref, listname);
1928 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1929 list->changeItem(i, newitem);
1930 reportInventoryChange(L, ref);
1931 lua_pushboolean(L, true);
1933 lua_pushboolean(L, false);
1938 // get_list(self, listname) -> list or nil
1939 static int l_get_list(lua_State *L)
1941 InvRef *ref = checkobject(L, 1);
1942 const char *listname = luaL_checkstring(L, 2);
1943 Inventory *inv = getinv(L, ref);
1944 inventory_get_list_to_lua(inv, listname, L);
1948 // set_list(self, listname, list)
1949 static int l_set_list(lua_State *L)
1951 InvRef *ref = checkobject(L, 1);
1952 const char *listname = luaL_checkstring(L, 2);
1953 Inventory *inv = getinv(L, ref);
1954 InventoryList *list = inv->getList(listname);
1956 inventory_set_list_from_lua(inv, listname, L, 3,
1959 inventory_set_list_from_lua(inv, listname, L, 3);
1960 reportInventoryChange(L, ref);
1964 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1965 // Returns the leftover stack
1966 static int l_add_item(lua_State *L)
1968 InvRef *ref = checkobject(L, 1);
1969 const char *listname = luaL_checkstring(L, 2);
1970 ItemStack item = read_item(L, 3);
1971 InventoryList *list = getlist(L, ref, listname);
1973 ItemStack leftover = list->addItem(item);
1974 if(leftover.count != item.count)
1975 reportInventoryChange(L, ref);
1976 LuaItemStack::create(L, leftover);
1978 LuaItemStack::create(L, item);
1983 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1984 // Returns true if the item completely fits into the list
1985 static int l_room_for_item(lua_State *L)
1987 InvRef *ref = checkobject(L, 1);
1988 const char *listname = luaL_checkstring(L, 2);
1989 ItemStack item = read_item(L, 3);
1990 InventoryList *list = getlist(L, ref, listname);
1992 lua_pushboolean(L, list->roomForItem(item));
1994 lua_pushboolean(L, false);
1999 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2000 // Returns true if the list contains the given count of the given item name
2001 static int l_contains_item(lua_State *L)
2003 InvRef *ref = checkobject(L, 1);
2004 const char *listname = luaL_checkstring(L, 2);
2005 ItemStack item = read_item(L, 3);
2006 InventoryList *list = getlist(L, ref, listname);
2008 lua_pushboolean(L, list->containsItem(item));
2010 lua_pushboolean(L, false);
2015 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2016 // Returns the items that were actually removed
2017 static int l_remove_item(lua_State *L)
2019 InvRef *ref = checkobject(L, 1);
2020 const char *listname = luaL_checkstring(L, 2);
2021 ItemStack item = read_item(L, 3);
2022 InventoryList *list = getlist(L, ref, listname);
2024 ItemStack removed = list->removeItem(item);
2025 if(!removed.empty())
2026 reportInventoryChange(L, ref);
2027 LuaItemStack::create(L, removed);
2029 LuaItemStack::create(L, ItemStack());
2035 InvRef(const InventoryLocation &loc):
2044 // Creates an InvRef and leaves it on top of stack
2045 // Not callable from Lua; all references are created on the C side.
2046 static void create(lua_State *L, const InventoryLocation &loc)
2048 InvRef *o = new InvRef(loc);
2049 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2050 luaL_getmetatable(L, className);
2051 lua_setmetatable(L, -2);
2053 static void createPlayer(lua_State *L, Player *player)
2055 InventoryLocation loc;
2056 loc.setPlayer(player->getName());
2059 static void createNodeMeta(lua_State *L, v3s16 p)
2061 InventoryLocation loc;
2066 static void Register(lua_State *L)
2069 int methodtable = lua_gettop(L);
2070 luaL_newmetatable(L, className);
2071 int metatable = lua_gettop(L);
2073 lua_pushliteral(L, "__metatable");
2074 lua_pushvalue(L, methodtable);
2075 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2077 lua_pushliteral(L, "__index");
2078 lua_pushvalue(L, methodtable);
2079 lua_settable(L, metatable);
2081 lua_pushliteral(L, "__gc");
2082 lua_pushcfunction(L, gc_object);
2083 lua_settable(L, metatable);
2085 lua_pop(L, 1); // drop metatable
2087 luaL_openlib(L, 0, methods, 0); // fill methodtable
2088 lua_pop(L, 1); // drop methodtable
2090 // Cannot be created from Lua
2091 //lua_register(L, className, create_object);
2094 const char InvRef::className[] = "InvRef";
2095 const luaL_reg InvRef::methods[] = {
2096 method(InvRef, is_empty),
2097 method(InvRef, get_size),
2098 method(InvRef, set_size),
2099 method(InvRef, get_width),
2100 method(InvRef, set_width),
2101 method(InvRef, get_stack),
2102 method(InvRef, set_stack),
2103 method(InvRef, get_list),
2104 method(InvRef, set_list),
2105 method(InvRef, add_item),
2106 method(InvRef, room_for_item),
2107 method(InvRef, contains_item),
2108 method(InvRef, remove_item),
2120 ServerEnvironment *m_env;
2122 static const char className[];
2123 static const luaL_reg methods[];
2125 static NodeMetaRef *checkobject(lua_State *L, int narg)
2127 luaL_checktype(L, narg, LUA_TUSERDATA);
2128 void *ud = luaL_checkudata(L, narg, className);
2129 if(!ud) luaL_typerror(L, narg, className);
2130 return *(NodeMetaRef**)ud; // unbox pointer
2133 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2135 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2136 if(meta == NULL && auto_create)
2138 meta = new NodeMetadata(ref->m_env->getGameDef());
2139 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2144 static void reportMetadataChange(NodeMetaRef *ref)
2146 // NOTE: This same code is in rollback_interface.cpp
2147 // Inform other things that the metadata has changed
2148 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2150 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2152 ref->m_env->getMap().dispatchEvent(&event);
2153 // Set the block to be saved
2154 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2156 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2157 "NodeMetaRef::reportMetadataChange");
2160 // Exported functions
2162 // garbage collector
2163 static int gc_object(lua_State *L) {
2164 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2169 // get_string(self, name)
2170 static int l_get_string(lua_State *L)
2172 NodeMetaRef *ref = checkobject(L, 1);
2173 std::string name = luaL_checkstring(L, 2);
2175 NodeMetadata *meta = getmeta(ref, false);
2177 lua_pushlstring(L, "", 0);
2180 std::string str = meta->getString(name);
2181 lua_pushlstring(L, str.c_str(), str.size());
2185 // set_string(self, name, var)
2186 static int l_set_string(lua_State *L)
2188 NodeMetaRef *ref = checkobject(L, 1);
2189 std::string name = luaL_checkstring(L, 2);
2191 const char *s = lua_tolstring(L, 3, &len);
2192 std::string str(s, len);
2194 NodeMetadata *meta = getmeta(ref, !str.empty());
2195 if(meta == NULL || str == meta->getString(name))
2197 meta->setString(name, str);
2198 reportMetadataChange(ref);
2202 // get_int(self, name)
2203 static int l_get_int(lua_State *L)
2205 NodeMetaRef *ref = checkobject(L, 1);
2206 std::string name = lua_tostring(L, 2);
2208 NodeMetadata *meta = getmeta(ref, false);
2210 lua_pushnumber(L, 0);
2213 std::string str = meta->getString(name);
2214 lua_pushnumber(L, stoi(str));
2218 // set_int(self, name, var)
2219 static int l_set_int(lua_State *L)
2221 NodeMetaRef *ref = checkobject(L, 1);
2222 std::string name = lua_tostring(L, 2);
2223 int a = lua_tointeger(L, 3);
2224 std::string str = itos(a);
2226 NodeMetadata *meta = getmeta(ref, true);
2227 if(meta == NULL || str == meta->getString(name))
2229 meta->setString(name, str);
2230 reportMetadataChange(ref);
2234 // get_float(self, name)
2235 static int l_get_float(lua_State *L)
2237 NodeMetaRef *ref = checkobject(L, 1);
2238 std::string name = lua_tostring(L, 2);
2240 NodeMetadata *meta = getmeta(ref, false);
2242 lua_pushnumber(L, 0);
2245 std::string str = meta->getString(name);
2246 lua_pushnumber(L, stof(str));
2250 // set_float(self, name, var)
2251 static int l_set_float(lua_State *L)
2253 NodeMetaRef *ref = checkobject(L, 1);
2254 std::string name = lua_tostring(L, 2);
2255 float a = lua_tonumber(L, 3);
2256 std::string str = ftos(a);
2258 NodeMetadata *meta = getmeta(ref, true);
2259 if(meta == NULL || str == meta->getString(name))
2261 meta->setString(name, str);
2262 reportMetadataChange(ref);
2266 // get_inventory(self)
2267 static int l_get_inventory(lua_State *L)
2269 NodeMetaRef *ref = checkobject(L, 1);
2270 getmeta(ref, true); // try to ensure the metadata exists
2271 InvRef::createNodeMeta(L, ref->m_p);
2276 static int l_to_table(lua_State *L)
2278 NodeMetaRef *ref = checkobject(L, 1);
2280 NodeMetadata *meta = getmeta(ref, true);
2289 std::map<std::string, std::string> fields = meta->getStrings();
2290 for(std::map<std::string, std::string>::const_iterator
2291 i = fields.begin(); i != fields.end(); i++){
2292 const std::string &name = i->first;
2293 const std::string &value = i->second;
2294 lua_pushlstring(L, name.c_str(), name.size());
2295 lua_pushlstring(L, value.c_str(), value.size());
2296 lua_settable(L, -3);
2299 lua_setfield(L, -2, "fields");
2302 Inventory *inv = meta->getInventory();
2304 std::vector<const InventoryList*> lists = inv->getLists();
2305 for(std::vector<const InventoryList*>::const_iterator
2306 i = lists.begin(); i != lists.end(); i++){
2307 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2308 lua_setfield(L, -2, (*i)->getName().c_str());
2311 lua_setfield(L, -2, "inventory");
2315 // from_table(self, table)
2316 static int l_from_table(lua_State *L)
2318 NodeMetaRef *ref = checkobject(L, 1);
2321 if(lua_isnil(L, base)){
2323 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2324 lua_pushboolean(L, true);
2328 // Has metadata; clear old one first
2329 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2330 // Create new metadata
2331 NodeMetadata *meta = getmeta(ref, true);
2333 lua_getfield(L, base, "fields");
2334 int fieldstable = lua_gettop(L);
2336 while(lua_next(L, fieldstable) != 0){
2337 // key at index -2 and value at index -1
2338 std::string name = lua_tostring(L, -2);
2340 const char *cs = lua_tolstring(L, -1, &cl);
2341 std::string value(cs, cl);
2342 meta->setString(name, value);
2343 lua_pop(L, 1); // removes value, keeps key for next iteration
2346 Inventory *inv = meta->getInventory();
2347 lua_getfield(L, base, "inventory");
2348 int inventorytable = lua_gettop(L);
2350 while(lua_next(L, inventorytable) != 0){
2351 // key at index -2 and value at index -1
2352 std::string name = lua_tostring(L, -2);
2353 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2354 lua_pop(L, 1); // removes value, keeps key for next iteration
2356 reportMetadataChange(ref);
2357 lua_pushboolean(L, true);
2362 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2372 // Creates an NodeMetaRef and leaves it on top of stack
2373 // Not callable from Lua; all references are created on the C side.
2374 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2376 NodeMetaRef *o = new NodeMetaRef(p, env);
2377 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2378 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2379 luaL_getmetatable(L, className);
2380 lua_setmetatable(L, -2);
2383 static void Register(lua_State *L)
2386 int methodtable = lua_gettop(L);
2387 luaL_newmetatable(L, className);
2388 int metatable = lua_gettop(L);
2390 lua_pushliteral(L, "__metatable");
2391 lua_pushvalue(L, methodtable);
2392 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2394 lua_pushliteral(L, "__index");
2395 lua_pushvalue(L, methodtable);
2396 lua_settable(L, metatable);
2398 lua_pushliteral(L, "__gc");
2399 lua_pushcfunction(L, gc_object);
2400 lua_settable(L, metatable);
2402 lua_pop(L, 1); // drop metatable
2404 luaL_openlib(L, 0, methods, 0); // fill methodtable
2405 lua_pop(L, 1); // drop methodtable
2407 // Cannot be created from Lua
2408 //lua_register(L, className, create_object);
2411 const char NodeMetaRef::className[] = "NodeMetaRef";
2412 const luaL_reg NodeMetaRef::methods[] = {
2413 method(NodeMetaRef, get_string),
2414 method(NodeMetaRef, set_string),
2415 method(NodeMetaRef, get_int),
2416 method(NodeMetaRef, set_int),
2417 method(NodeMetaRef, get_float),
2418 method(NodeMetaRef, set_float),
2419 method(NodeMetaRef, get_inventory),
2420 method(NodeMetaRef, to_table),
2421 method(NodeMetaRef, from_table),
2432 ServerActiveObject *m_object;
2434 static const char className[];
2435 static const luaL_reg methods[];
2437 static ObjectRef *checkobject(lua_State *L, int narg)
2439 luaL_checktype(L, narg, LUA_TUSERDATA);
2440 void *ud = luaL_checkudata(L, narg, className);
2441 if(!ud) luaL_typerror(L, narg, className);
2442 return *(ObjectRef**)ud; // unbox pointer
2445 static ServerActiveObject* getobject(ObjectRef *ref)
2447 ServerActiveObject *co = ref->m_object;
2451 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2453 ServerActiveObject *obj = getobject(ref);
2456 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2458 return (LuaEntitySAO*)obj;
2461 static PlayerSAO* getplayersao(ObjectRef *ref)
2463 ServerActiveObject *obj = getobject(ref);
2466 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2468 return (PlayerSAO*)obj;
2471 static Player* getplayer(ObjectRef *ref)
2473 PlayerSAO *playersao = getplayersao(ref);
2474 if(playersao == NULL)
2476 return playersao->getPlayer();
2479 // Exported functions
2481 // garbage collector
2482 static int gc_object(lua_State *L) {
2483 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2484 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2490 static int l_remove(lua_State *L)
2492 ObjectRef *ref = checkobject(L, 1);
2493 ServerActiveObject *co = getobject(ref);
2494 if(co == NULL) return 0;
2495 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2496 co->m_removed = true;
2501 // returns: {x=num, y=num, z=num}
2502 static int l_getpos(lua_State *L)
2504 ObjectRef *ref = checkobject(L, 1);
2505 ServerActiveObject *co = getobject(ref);
2506 if(co == NULL) return 0;
2507 v3f pos = co->getBasePosition() / BS;
2509 lua_pushnumber(L, pos.X);
2510 lua_setfield(L, -2, "x");
2511 lua_pushnumber(L, pos.Y);
2512 lua_setfield(L, -2, "y");
2513 lua_pushnumber(L, pos.Z);
2514 lua_setfield(L, -2, "z");
2518 // setpos(self, pos)
2519 static int l_setpos(lua_State *L)
2521 ObjectRef *ref = checkobject(L, 1);
2522 //LuaEntitySAO *co = getluaobject(ref);
2523 ServerActiveObject *co = getobject(ref);
2524 if(co == NULL) return 0;
2526 v3f pos = checkFloatPos(L, 2);
2532 // moveto(self, pos, continuous=false)
2533 static int l_moveto(lua_State *L)
2535 ObjectRef *ref = checkobject(L, 1);
2536 //LuaEntitySAO *co = getluaobject(ref);
2537 ServerActiveObject *co = getobject(ref);
2538 if(co == NULL) return 0;
2540 v3f pos = checkFloatPos(L, 2);
2542 bool continuous = lua_toboolean(L, 3);
2544 co->moveTo(pos, continuous);
2548 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2549 static int l_punch(lua_State *L)
2551 ObjectRef *ref = checkobject(L, 1);
2552 ObjectRef *puncher_ref = checkobject(L, 2);
2553 ServerActiveObject *co = getobject(ref);
2554 ServerActiveObject *puncher = getobject(puncher_ref);
2555 if(co == NULL) return 0;
2556 if(puncher == NULL) return 0;
2558 if(lua_type(L, 5) != LUA_TTABLE)
2559 dir = co->getBasePosition() - puncher->getBasePosition();
2561 dir = read_v3f(L, 5);
2562 float time_from_last_punch = 1000000;
2563 if(lua_isnumber(L, 3))
2564 time_from_last_punch = lua_tonumber(L, 3);
2565 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2568 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2572 // right_click(self, clicker); clicker = an another ObjectRef
2573 static int l_right_click(lua_State *L)
2575 ObjectRef *ref = checkobject(L, 1);
2576 ObjectRef *ref2 = checkobject(L, 2);
2577 ServerActiveObject *co = getobject(ref);
2578 ServerActiveObject *co2 = getobject(ref2);
2579 if(co == NULL) return 0;
2580 if(co2 == NULL) return 0;
2582 co->rightClick(co2);
2587 // hp = number of hitpoints (2 * number of hearts)
2589 static int l_set_hp(lua_State *L)
2591 ObjectRef *ref = checkobject(L, 1);
2592 luaL_checknumber(L, 2);
2593 ServerActiveObject *co = getobject(ref);
2594 if(co == NULL) return 0;
2595 int hp = lua_tonumber(L, 2);
2596 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2597 <<" hp="<<hp<<std::endl;*/
2605 // returns: number of hitpoints (2 * number of hearts)
2606 // 0 if not applicable to this type of object
2607 static int l_get_hp(lua_State *L)
2609 ObjectRef *ref = checkobject(L, 1);
2610 ServerActiveObject *co = getobject(ref);
2613 lua_pushnumber(L, 1);
2616 int hp = co->getHP();
2617 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2618 <<" hp="<<hp<<std::endl;*/
2620 lua_pushnumber(L, hp);
2624 // get_inventory(self)
2625 static int l_get_inventory(lua_State *L)
2627 ObjectRef *ref = checkobject(L, 1);
2628 ServerActiveObject *co = getobject(ref);
2629 if(co == NULL) return 0;
2631 InventoryLocation loc = co->getInventoryLocation();
2632 if(get_server(L)->getInventory(loc) != NULL)
2633 InvRef::create(L, loc);
2635 lua_pushnil(L); // An object may have no inventory (nil)
2639 // get_wield_list(self)
2640 static int l_get_wield_list(lua_State *L)
2642 ObjectRef *ref = checkobject(L, 1);
2643 ServerActiveObject *co = getobject(ref);
2644 if(co == NULL) return 0;
2646 lua_pushstring(L, co->getWieldList().c_str());
2650 // get_wield_index(self)
2651 static int l_get_wield_index(lua_State *L)
2653 ObjectRef *ref = checkobject(L, 1);
2654 ServerActiveObject *co = getobject(ref);
2655 if(co == NULL) return 0;
2657 lua_pushinteger(L, co->getWieldIndex() + 1);
2661 // get_wielded_item(self)
2662 static int l_get_wielded_item(lua_State *L)
2664 ObjectRef *ref = checkobject(L, 1);
2665 ServerActiveObject *co = getobject(ref);
2668 LuaItemStack::create(L, ItemStack());
2672 LuaItemStack::create(L, co->getWieldedItem());
2676 // set_wielded_item(self, itemstack or itemstring or table or nil)
2677 static int l_set_wielded_item(lua_State *L)
2679 ObjectRef *ref = checkobject(L, 1);
2680 ServerActiveObject *co = getobject(ref);
2681 if(co == NULL) return 0;
2683 ItemStack item = read_item(L, 2);
2684 bool success = co->setWieldedItem(item);
2685 lua_pushboolean(L, success);
2689 // set_armor_groups(self, groups)
2690 static int l_set_armor_groups(lua_State *L)
2692 ObjectRef *ref = checkobject(L, 1);
2693 ServerActiveObject *co = getobject(ref);
2694 if(co == NULL) return 0;
2696 ItemGroupList groups;
2697 read_groups(L, 2, groups);
2698 co->setArmorGroups(groups);
2702 // set_properties(self, properties)
2703 static int l_set_properties(lua_State *L)
2705 ObjectRef *ref = checkobject(L, 1);
2706 ServerActiveObject *co = getobject(ref);
2707 if(co == NULL) return 0;
2708 ObjectProperties *prop = co->accessObjectProperties();
2711 read_object_properties(L, 2, prop);
2712 co->notifyObjectPropertiesModified();
2716 /* LuaEntitySAO-only */
2718 // setvelocity(self, {x=num, y=num, z=num})
2719 static int l_setvelocity(lua_State *L)
2721 ObjectRef *ref = checkobject(L, 1);
2722 LuaEntitySAO *co = getluaobject(ref);
2723 if(co == NULL) return 0;
2724 v3f pos = checkFloatPos(L, 2);
2726 co->setVelocity(pos);
2730 // getvelocity(self)
2731 static int l_getvelocity(lua_State *L)
2733 ObjectRef *ref = checkobject(L, 1);
2734 LuaEntitySAO *co = getluaobject(ref);
2735 if(co == NULL) return 0;
2737 v3f v = co->getVelocity();
2742 // setacceleration(self, {x=num, y=num, z=num})
2743 static int l_setacceleration(lua_State *L)
2745 ObjectRef *ref = checkobject(L, 1);
2746 LuaEntitySAO *co = getluaobject(ref);
2747 if(co == NULL) return 0;
2749 v3f pos = checkFloatPos(L, 2);
2751 co->setAcceleration(pos);
2755 // getacceleration(self)
2756 static int l_getacceleration(lua_State *L)
2758 ObjectRef *ref = checkobject(L, 1);
2759 LuaEntitySAO *co = getluaobject(ref);
2760 if(co == NULL) return 0;
2762 v3f v = co->getAcceleration();
2767 // setyaw(self, radians)
2768 static int l_setyaw(lua_State *L)
2770 ObjectRef *ref = checkobject(L, 1);
2771 LuaEntitySAO *co = getluaobject(ref);
2772 if(co == NULL) return 0;
2773 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2780 static int l_getyaw(lua_State *L)
2782 ObjectRef *ref = checkobject(L, 1);
2783 LuaEntitySAO *co = getluaobject(ref);
2784 if(co == NULL) return 0;
2786 float yaw = co->getYaw() * core::DEGTORAD;
2787 lua_pushnumber(L, yaw);
2791 // settexturemod(self, mod)
2792 static int l_settexturemod(lua_State *L)
2794 ObjectRef *ref = checkobject(L, 1);
2795 LuaEntitySAO *co = getluaobject(ref);
2796 if(co == NULL) return 0;
2798 std::string mod = luaL_checkstring(L, 2);
2799 co->setTextureMod(mod);
2803 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2804 // select_horiz_by_yawpitch=false)
2805 static int l_setsprite(lua_State *L)
2807 ObjectRef *ref = checkobject(L, 1);
2808 LuaEntitySAO *co = getluaobject(ref);
2809 if(co == NULL) return 0;
2812 if(!lua_isnil(L, 2))
2813 p = read_v2s16(L, 2);
2815 if(!lua_isnil(L, 3))
2816 num_frames = lua_tonumber(L, 3);
2817 float framelength = 0.2;
2818 if(!lua_isnil(L, 4))
2819 framelength = lua_tonumber(L, 4);
2820 bool select_horiz_by_yawpitch = false;
2821 if(!lua_isnil(L, 5))
2822 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2823 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2828 // get_entity_name(self)
2829 static int l_get_entity_name(lua_State *L)
2831 ObjectRef *ref = checkobject(L, 1);
2832 LuaEntitySAO *co = getluaobject(ref);
2833 if(co == NULL) return 0;
2835 std::string name = co->getName();
2836 lua_pushstring(L, name.c_str());
2840 // get_luaentity(self)
2841 static int l_get_luaentity(lua_State *L)
2843 ObjectRef *ref = checkobject(L, 1);
2844 LuaEntitySAO *co = getluaobject(ref);
2845 if(co == NULL) return 0;
2847 luaentity_get(L, co->getId());
2854 static int l_is_player(lua_State *L)
2856 ObjectRef *ref = checkobject(L, 1);
2857 Player *player = getplayer(ref);
2858 lua_pushboolean(L, (player != NULL));
2862 // get_player_name(self)
2863 static int l_get_player_name(lua_State *L)
2865 ObjectRef *ref = checkobject(L, 1);
2866 Player *player = getplayer(ref);
2868 lua_pushlstring(L, "", 0);
2872 lua_pushstring(L, player->getName());
2876 // get_look_dir(self)
2877 static int l_get_look_dir(lua_State *L)
2879 ObjectRef *ref = checkobject(L, 1);
2880 Player *player = getplayer(ref);
2881 if(player == NULL) return 0;
2883 float pitch = player->getRadPitch();
2884 float yaw = player->getRadYaw();
2885 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2890 // get_look_pitch(self)
2891 static int l_get_look_pitch(lua_State *L)
2893 ObjectRef *ref = checkobject(L, 1);
2894 Player *player = getplayer(ref);
2895 if(player == NULL) return 0;
2897 lua_pushnumber(L, player->getRadPitch());
2901 // get_look_yaw(self)
2902 static int l_get_look_yaw(lua_State *L)
2904 ObjectRef *ref = checkobject(L, 1);
2905 Player *player = getplayer(ref);
2906 if(player == NULL) return 0;
2908 lua_pushnumber(L, player->getRadYaw());
2912 // set_inventory_formspec(self, formspec)
2913 static int l_set_inventory_formspec(lua_State *L)
2915 ObjectRef *ref = checkobject(L, 1);
2916 Player *player = getplayer(ref);
2917 if(player == NULL) return 0;
2918 std::string formspec = luaL_checkstring(L, 2);
2920 player->inventory_formspec = formspec;
2921 get_server(L)->reportInventoryFormspecModified(player->getName());
2922 lua_pushboolean(L, true);
2926 // get_inventory_formspec(self) -> formspec
2927 static int l_get_inventory_formspec(lua_State *L)
2929 ObjectRef *ref = checkobject(L, 1);
2930 Player *player = getplayer(ref);
2931 if(player == NULL) return 0;
2933 std::string formspec = player->inventory_formspec;
2934 lua_pushlstring(L, formspec.c_str(), formspec.size());
2939 ObjectRef(ServerActiveObject *object):
2942 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2948 infostream<<"ObjectRef destructing for id="
2949 <<m_object->getId()<<std::endl;
2951 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2954 // Creates an ObjectRef and leaves it on top of stack
2955 // Not callable from Lua; all references are created on the C side.
2956 static void create(lua_State *L, ServerActiveObject *object)
2958 ObjectRef *o = new ObjectRef(object);
2959 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2960 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2961 luaL_getmetatable(L, className);
2962 lua_setmetatable(L, -2);
2965 static void set_null(lua_State *L)
2967 ObjectRef *o = checkobject(L, -1);
2971 static void Register(lua_State *L)
2974 int methodtable = lua_gettop(L);
2975 luaL_newmetatable(L, className);
2976 int metatable = lua_gettop(L);
2978 lua_pushliteral(L, "__metatable");
2979 lua_pushvalue(L, methodtable);
2980 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2982 lua_pushliteral(L, "__index");
2983 lua_pushvalue(L, methodtable);
2984 lua_settable(L, metatable);
2986 lua_pushliteral(L, "__gc");
2987 lua_pushcfunction(L, gc_object);
2988 lua_settable(L, metatable);
2990 lua_pop(L, 1); // drop metatable
2992 luaL_openlib(L, 0, methods, 0); // fill methodtable
2993 lua_pop(L, 1); // drop methodtable
2995 // Cannot be created from Lua
2996 //lua_register(L, className, create_object);
2999 const char ObjectRef::className[] = "ObjectRef";
3000 const luaL_reg ObjectRef::methods[] = {
3001 // ServerActiveObject
3002 method(ObjectRef, remove),
3003 method(ObjectRef, getpos),
3004 method(ObjectRef, setpos),
3005 method(ObjectRef, moveto),
3006 method(ObjectRef, punch),
3007 method(ObjectRef, right_click),
3008 method(ObjectRef, set_hp),
3009 method(ObjectRef, get_hp),
3010 method(ObjectRef, get_inventory),
3011 method(ObjectRef, get_wield_list),
3012 method(ObjectRef, get_wield_index),
3013 method(ObjectRef, get_wielded_item),
3014 method(ObjectRef, set_wielded_item),
3015 method(ObjectRef, set_armor_groups),
3016 method(ObjectRef, set_properties),
3017 // LuaEntitySAO-only
3018 method(ObjectRef, setvelocity),
3019 method(ObjectRef, getvelocity),
3020 method(ObjectRef, setacceleration),
3021 method(ObjectRef, getacceleration),
3022 method(ObjectRef, setyaw),
3023 method(ObjectRef, getyaw),
3024 method(ObjectRef, settexturemod),
3025 method(ObjectRef, setsprite),
3026 method(ObjectRef, get_entity_name),
3027 method(ObjectRef, get_luaentity),
3029 method(ObjectRef, is_player),
3030 method(ObjectRef, get_player_name),
3031 method(ObjectRef, get_look_dir),
3032 method(ObjectRef, get_look_pitch),
3033 method(ObjectRef, get_look_yaw),
3034 method(ObjectRef, set_inventory_formspec),
3035 method(ObjectRef, get_inventory_formspec),
3039 // Creates a new anonymous reference if cobj=NULL or id=0
3040 static void objectref_get_or_create(lua_State *L,
3041 ServerActiveObject *cobj)
3043 if(cobj == NULL || cobj->getId() == 0){
3044 ObjectRef::create(L, cobj);
3046 objectref_get(L, cobj->getId());
3055 class LuaPerlinNoise
3062 static const char className[];
3063 static const luaL_reg methods[];
3065 // Exported functions
3067 // garbage collector
3068 static int gc_object(lua_State *L)
3070 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3075 static int l_get2d(lua_State *L)
3077 LuaPerlinNoise *o = checkobject(L, 1);
3078 v2f pos2d = read_v2f(L,2);
3079 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3080 lua_pushnumber(L, val);
3083 static int l_get3d(lua_State *L)
3085 LuaPerlinNoise *o = checkobject(L, 1);
3086 v3f pos3d = read_v3f(L,2);
3087 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3088 lua_pushnumber(L, val);
3093 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3097 persistence(a_persistence),
3106 // LuaPerlinNoise(seed, octaves, persistence, scale)
3107 // Creates an LuaPerlinNoise and leaves it on top of stack
3108 static int create_object(lua_State *L)
3110 int seed = luaL_checkint(L, 1);
3111 int octaves = luaL_checkint(L, 2);
3112 double persistence = luaL_checknumber(L, 3);
3113 double scale = luaL_checknumber(L, 4);
3114 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3115 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3116 luaL_getmetatable(L, className);
3117 lua_setmetatable(L, -2);
3121 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3123 luaL_checktype(L, narg, LUA_TUSERDATA);
3124 void *ud = luaL_checkudata(L, narg, className);
3125 if(!ud) luaL_typerror(L, narg, className);
3126 return *(LuaPerlinNoise**)ud; // unbox pointer
3129 static void Register(lua_State *L)
3132 int methodtable = lua_gettop(L);
3133 luaL_newmetatable(L, className);
3134 int metatable = lua_gettop(L);
3136 lua_pushliteral(L, "__metatable");
3137 lua_pushvalue(L, methodtable);
3138 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3140 lua_pushliteral(L, "__index");
3141 lua_pushvalue(L, methodtable);
3142 lua_settable(L, metatable);
3144 lua_pushliteral(L, "__gc");
3145 lua_pushcfunction(L, gc_object);
3146 lua_settable(L, metatable);
3148 lua_pop(L, 1); // drop metatable
3150 luaL_openlib(L, 0, methods, 0); // fill methodtable
3151 lua_pop(L, 1); // drop methodtable
3153 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3154 lua_register(L, className, create_object);
3157 const char LuaPerlinNoise::className[] = "PerlinNoise";
3158 const luaL_reg LuaPerlinNoise::methods[] = {
3159 method(LuaPerlinNoise, get2d),
3160 method(LuaPerlinNoise, get3d),
3172 ServerEnvironment *m_env;
3174 static const char className[];
3175 static const luaL_reg methods[];
3177 static int gc_object(lua_State *L) {
3178 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3183 static NodeTimerRef *checkobject(lua_State *L, int narg)
3185 luaL_checktype(L, narg, LUA_TUSERDATA);
3186 void *ud = luaL_checkudata(L, narg, className);
3187 if(!ud) luaL_typerror(L, narg, className);
3188 return *(NodeTimerRef**)ud; // unbox pointer
3191 static int l_set(lua_State *L)
3193 NodeTimerRef *o = checkobject(L, 1);
3194 ServerEnvironment *env = o->m_env;
3195 if(env == NULL) return 0;
3196 f32 t = luaL_checknumber(L,2);
3197 f32 e = luaL_checknumber(L,3);
3198 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3202 static int l_start(lua_State *L)
3204 NodeTimerRef *o = checkobject(L, 1);
3205 ServerEnvironment *env = o->m_env;
3206 if(env == NULL) return 0;
3207 f32 t = luaL_checknumber(L,2);
3208 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3212 static int l_stop(lua_State *L)
3214 NodeTimerRef *o = checkobject(L, 1);
3215 ServerEnvironment *env = o->m_env;
3216 if(env == NULL) return 0;
3217 env->getMap().removeNodeTimer(o->m_p);
3221 static int l_is_started(lua_State *L)
3223 NodeTimerRef *o = checkobject(L, 1);
3224 ServerEnvironment *env = o->m_env;
3225 if(env == NULL) return 0;
3227 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3228 lua_pushboolean(L,(t.timeout != 0));
3232 static int l_get_timeout(lua_State *L)
3234 NodeTimerRef *o = checkobject(L, 1);
3235 ServerEnvironment *env = o->m_env;
3236 if(env == NULL) return 0;
3238 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3239 lua_pushnumber(L,t.timeout);
3243 static int l_get_elapsed(lua_State *L)
3245 NodeTimerRef *o = checkobject(L, 1);
3246 ServerEnvironment *env = o->m_env;
3247 if(env == NULL) return 0;
3249 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3250 lua_pushnumber(L,t.elapsed);
3255 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3265 // Creates an NodeTimerRef and leaves it on top of stack
3266 // Not callable from Lua; all references are created on the C side.
3267 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3269 NodeTimerRef *o = new NodeTimerRef(p, env);
3270 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3271 luaL_getmetatable(L, className);
3272 lua_setmetatable(L, -2);
3275 static void set_null(lua_State *L)
3277 NodeTimerRef *o = checkobject(L, -1);
3281 static void Register(lua_State *L)
3284 int methodtable = lua_gettop(L);
3285 luaL_newmetatable(L, className);
3286 int metatable = lua_gettop(L);
3288 lua_pushliteral(L, "__metatable");
3289 lua_pushvalue(L, methodtable);
3290 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3292 lua_pushliteral(L, "__index");
3293 lua_pushvalue(L, methodtable);
3294 lua_settable(L, metatable);
3296 lua_pushliteral(L, "__gc");
3297 lua_pushcfunction(L, gc_object);
3298 lua_settable(L, metatable);
3300 lua_pop(L, 1); // drop metatable
3302 luaL_openlib(L, 0, methods, 0); // fill methodtable
3303 lua_pop(L, 1); // drop methodtable
3305 // Cannot be created from Lua
3306 //lua_register(L, className, create_object);
3309 const char NodeTimerRef::className[] = "NodeTimerRef";
3310 const luaL_reg NodeTimerRef::methods[] = {
3311 method(NodeTimerRef, start),
3312 method(NodeTimerRef, set),
3313 method(NodeTimerRef, stop),
3314 method(NodeTimerRef, is_started),
3315 method(NodeTimerRef, get_timeout),
3316 method(NodeTimerRef, get_elapsed),
3327 ServerEnvironment *m_env;
3329 static const char className[];
3330 static const luaL_reg methods[];
3332 static int gc_object(lua_State *L) {
3333 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3338 static EnvRef *checkobject(lua_State *L, int narg)
3340 luaL_checktype(L, narg, LUA_TUSERDATA);
3341 void *ud = luaL_checkudata(L, narg, className);
3342 if(!ud) luaL_typerror(L, narg, className);
3343 return *(EnvRef**)ud; // unbox pointer
3346 // Exported functions
3348 // EnvRef:set_node(pos, node)
3349 // pos = {x=num, y=num, z=num}
3350 static int l_set_node(lua_State *L)
3352 EnvRef *o = checkobject(L, 1);
3353 ServerEnvironment *env = o->m_env;
3354 if(env == NULL) return 0;
3355 INodeDefManager *ndef = env->getGameDef()->ndef();
3357 v3s16 pos = read_v3s16(L, 2);
3358 MapNode n = readnode(L, 3, ndef);
3360 MapNode n_old = env->getMap().getNodeNoEx(pos);
3362 if(ndef->get(n_old).has_on_destruct)
3363 scriptapi_node_on_destruct(L, pos, n_old);
3365 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3367 // Call post-destructor
3368 if(ndef->get(n_old).has_after_destruct)
3369 scriptapi_node_after_destruct(L, pos, n_old);
3371 if(ndef->get(n).has_on_construct)
3372 scriptapi_node_on_construct(L, pos, n);
3374 lua_pushboolean(L, succeeded);
3378 static int l_add_node(lua_State *L)
3380 return l_set_node(L);
3383 // EnvRef:remove_node(pos)
3384 // pos = {x=num, y=num, z=num}
3385 static int l_remove_node(lua_State *L)
3387 EnvRef *o = checkobject(L, 1);
3388 ServerEnvironment *env = o->m_env;
3389 if(env == NULL) return 0;
3390 INodeDefManager *ndef = env->getGameDef()->ndef();
3392 v3s16 pos = read_v3s16(L, 2);
3394 MapNode n_old = env->getMap().getNodeNoEx(pos);
3396 if(ndef->get(n_old).has_on_destruct)
3397 scriptapi_node_on_destruct(L, pos, n_old);
3399 // This is slightly optimized compared to addNodeWithEvent(air)
3400 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3402 // Call post-destructor
3403 if(ndef->get(n_old).has_after_destruct)
3404 scriptapi_node_after_destruct(L, pos, n_old);
3406 lua_pushboolean(L, succeeded);
3407 // Air doesn't require constructor
3411 // EnvRef:get_node(pos)
3412 // pos = {x=num, y=num, z=num}
3413 static int l_get_node(lua_State *L)
3415 EnvRef *o = checkobject(L, 1);
3416 ServerEnvironment *env = o->m_env;
3417 if(env == NULL) return 0;
3419 v3s16 pos = read_v3s16(L, 2);
3421 MapNode n = env->getMap().getNodeNoEx(pos);
3423 pushnode(L, n, env->getGameDef()->ndef());
3427 // EnvRef:get_node_or_nil(pos)
3428 // pos = {x=num, y=num, z=num}
3429 static int l_get_node_or_nil(lua_State *L)
3431 EnvRef *o = checkobject(L, 1);
3432 ServerEnvironment *env = o->m_env;
3433 if(env == NULL) return 0;
3435 v3s16 pos = read_v3s16(L, 2);
3438 MapNode n = env->getMap().getNode(pos);
3440 pushnode(L, n, env->getGameDef()->ndef());
3442 } catch(InvalidPositionException &e)
3449 // EnvRef:get_node_light(pos, timeofday)
3450 // pos = {x=num, y=num, z=num}
3451 // timeofday: nil = current time, 0 = night, 0.5 = day
3452 static int l_get_node_light(lua_State *L)
3454 EnvRef *o = checkobject(L, 1);
3455 ServerEnvironment *env = o->m_env;
3456 if(env == NULL) return 0;
3458 v3s16 pos = read_v3s16(L, 2);
3459 u32 time_of_day = env->getTimeOfDay();
3460 if(lua_isnumber(L, 3))
3461 time_of_day = 24000.0 * lua_tonumber(L, 3);
3462 time_of_day %= 24000;
3463 u32 dnr = time_to_daynight_ratio(time_of_day);
3464 MapNode n = env->getMap().getNodeNoEx(pos);
3466 MapNode n = env->getMap().getNode(pos);
3467 INodeDefManager *ndef = env->getGameDef()->ndef();
3468 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3470 } catch(InvalidPositionException &e)
3477 // EnvRef:place_node(pos, node)
3478 // pos = {x=num, y=num, z=num}
3479 static int l_place_node(lua_State *L)
3481 EnvRef *o = checkobject(L, 1);
3482 ServerEnvironment *env = o->m_env;
3483 if(env == NULL) return 0;
3484 v3s16 pos = read_v3s16(L, 2);
3485 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3487 // Don't attempt to load non-loaded area as of now
3488 MapNode n_old = env->getMap().getNodeNoEx(pos);
3489 if(n_old.getContent() == CONTENT_IGNORE){
3490 lua_pushboolean(L, false);
3493 // Create item to place
3494 INodeDefManager *ndef = get_server(L)->ndef();
3495 IItemDefManager *idef = get_server(L)->idef();
3496 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3497 // Make pointed position
3498 PointedThing pointed;
3499 pointed.type = POINTEDTHING_NODE;
3500 pointed.node_abovesurface = pos;
3501 pointed.node_undersurface = pos + v3s16(0,-1,0);
3502 // Place it with a NULL placer (appears in Lua as a non-functional
3504 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3505 lua_pushboolean(L, success);
3509 // EnvRef:dig_node(pos)
3510 // pos = {x=num, y=num, z=num}
3511 static int l_dig_node(lua_State *L)
3513 EnvRef *o = checkobject(L, 1);
3514 ServerEnvironment *env = o->m_env;
3515 if(env == NULL) return 0;
3516 v3s16 pos = read_v3s16(L, 2);
3518 // Don't attempt to load non-loaded area as of now
3519 MapNode n = env->getMap().getNodeNoEx(pos);
3520 if(n.getContent() == CONTENT_IGNORE){
3521 lua_pushboolean(L, false);
3524 // Dig it out with a NULL digger (appears in Lua as a
3525 // non-functional ObjectRef)
3526 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3527 lua_pushboolean(L, success);
3531 // EnvRef:punch_node(pos)
3532 // pos = {x=num, y=num, z=num}
3533 static int l_punch_node(lua_State *L)
3535 EnvRef *o = checkobject(L, 1);
3536 ServerEnvironment *env = o->m_env;
3537 if(env == NULL) return 0;
3538 v3s16 pos = read_v3s16(L, 2);
3540 // Don't attempt to load non-loaded area as of now
3541 MapNode n = env->getMap().getNodeNoEx(pos);
3542 if(n.getContent() == CONTENT_IGNORE){
3543 lua_pushboolean(L, false);
3546 // Punch it with a NULL puncher (appears in Lua as a non-functional
3548 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3549 lua_pushboolean(L, success);
3553 // EnvRef:get_meta(pos)
3554 static int l_get_meta(lua_State *L)
3556 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3557 EnvRef *o = checkobject(L, 1);
3558 ServerEnvironment *env = o->m_env;
3559 if(env == NULL) return 0;
3561 v3s16 p = read_v3s16(L, 2);
3562 NodeMetaRef::create(L, p, env);
3566 // EnvRef:get_node_timer(pos)
3567 static int l_get_node_timer(lua_State *L)
3569 EnvRef *o = checkobject(L, 1);
3570 ServerEnvironment *env = o->m_env;
3571 if(env == NULL) return 0;
3573 v3s16 p = read_v3s16(L, 2);
3574 NodeTimerRef::create(L, p, env);
3578 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3579 // pos = {x=num, y=num, z=num}
3580 static int l_add_entity(lua_State *L)
3582 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3583 EnvRef *o = checkobject(L, 1);
3584 ServerEnvironment *env = o->m_env;
3585 if(env == NULL) return 0;
3587 v3f pos = checkFloatPos(L, 2);
3589 const char *name = luaL_checkstring(L, 3);
3591 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3592 int objectid = env->addActiveObject(obj);
3593 // If failed to add, return nothing (reads as nil)
3597 objectref_get_or_create(L, obj);
3601 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3602 // pos = {x=num, y=num, z=num}
3603 static int l_add_item(lua_State *L)
3605 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3606 EnvRef *o = checkobject(L, 1);
3607 ServerEnvironment *env = o->m_env;
3608 if(env == NULL) return 0;
3610 v3f pos = checkFloatPos(L, 2);
3612 ItemStack item = read_item(L, 3);
3613 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3615 // Use minetest.spawn_item to spawn a __builtin:item
3616 lua_getglobal(L, "minetest");
3617 lua_getfield(L, -1, "spawn_item");
3618 if(lua_isnil(L, -1))
3620 lua_pushvalue(L, 2);
3621 lua_pushstring(L, item.getItemString().c_str());
3622 if(lua_pcall(L, 2, 1, 0))
3623 script_error(L, "error: %s", lua_tostring(L, -1));
3625 /*lua_pushvalue(L, 1);
3626 lua_pushstring(L, "__builtin:item");
3627 lua_pushstring(L, item.getItemString().c_str());
3628 return l_add_entity(L);*/
3630 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3631 int objectid = env->addActiveObject(obj);
3632 // If failed to add, return nothing (reads as nil)
3636 objectref_get_or_create(L, obj);
3640 // EnvRef:add_rat(pos)
3641 // pos = {x=num, y=num, z=num}
3642 static int l_add_rat(lua_State *L)
3644 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3645 <<" Doing nothing."<<std::endl;
3649 // EnvRef:add_firefly(pos)
3650 // pos = {x=num, y=num, z=num}
3651 static int l_add_firefly(lua_State *L)
3653 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3654 <<" Doing nothing."<<std::endl;
3658 // EnvRef:get_player_by_name(name)
3659 static int l_get_player_by_name(lua_State *L)
3661 EnvRef *o = checkobject(L, 1);
3662 ServerEnvironment *env = o->m_env;
3663 if(env == NULL) return 0;
3665 const char *name = luaL_checkstring(L, 2);
3666 Player *player = env->getPlayer(name);
3671 PlayerSAO *sao = player->getPlayerSAO();
3676 // Put player on stack
3677 objectref_get_or_create(L, sao);
3681 // EnvRef:get_objects_inside_radius(pos, radius)
3682 static int l_get_objects_inside_radius(lua_State *L)
3684 // Get the table insert function
3685 lua_getglobal(L, "table");
3686 lua_getfield(L, -1, "insert");
3687 int table_insert = lua_gettop(L);
3689 EnvRef *o = checkobject(L, 1);
3690 ServerEnvironment *env = o->m_env;
3691 if(env == NULL) return 0;
3693 v3f pos = checkFloatPos(L, 2);
3694 float radius = luaL_checknumber(L, 3) * BS;
3695 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3697 int table = lua_gettop(L);
3698 for(std::set<u16>::const_iterator
3699 i = ids.begin(); i != ids.end(); i++){
3700 ServerActiveObject *obj = env->getActiveObject(*i);
3701 // Insert object reference into table
3702 lua_pushvalue(L, table_insert);
3703 lua_pushvalue(L, table);
3704 objectref_get_or_create(L, obj);
3705 if(lua_pcall(L, 2, 0, 0))
3706 script_error(L, "error: %s", lua_tostring(L, -1));
3711 // EnvRef:set_timeofday(val)
3713 static int l_set_timeofday(lua_State *L)
3715 EnvRef *o = checkobject(L, 1);
3716 ServerEnvironment *env = o->m_env;
3717 if(env == NULL) return 0;
3719 float timeofday_f = luaL_checknumber(L, 2);
3720 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3721 int timeofday_mh = (int)(timeofday_f * 24000.0);
3722 // This should be set directly in the environment but currently
3723 // such changes aren't immediately sent to the clients, so call
3724 // the server instead.
3725 //env->setTimeOfDay(timeofday_mh);
3726 get_server(L)->setTimeOfDay(timeofday_mh);
3730 // EnvRef:get_timeofday() -> 0...1
3731 static int l_get_timeofday(lua_State *L)
3733 EnvRef *o = checkobject(L, 1);
3734 ServerEnvironment *env = o->m_env;
3735 if(env == NULL) return 0;
3737 int timeofday_mh = env->getTimeOfDay();
3738 float timeofday_f = (float)timeofday_mh / 24000.0;
3739 lua_pushnumber(L, timeofday_f);
3744 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3745 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3746 static int l_find_node_near(lua_State *L)
3748 EnvRef *o = checkobject(L, 1);
3749 ServerEnvironment *env = o->m_env;
3750 if(env == NULL) return 0;
3751 INodeDefManager *ndef = get_server(L)->ndef();
3752 v3s16 pos = read_v3s16(L, 2);
3753 int radius = luaL_checkinteger(L, 3);
3754 std::set<content_t> filter;
3755 if(lua_istable(L, 4)){
3758 while(lua_next(L, table) != 0){
3759 // key at index -2 and value at index -1
3760 luaL_checktype(L, -1, LUA_TSTRING);
3761 ndef->getIds(lua_tostring(L, -1), filter);
3762 // removes value, keeps key for next iteration
3765 } else if(lua_isstring(L, 4)){
3766 ndef->getIds(lua_tostring(L, 4), filter);
3769 for(int d=1; d<=radius; d++){
3770 core::list<v3s16> list;
3771 getFacePositions(list, d);
3772 for(core::list<v3s16>::Iterator i = list.begin();
3773 i != list.end(); i++){
3774 v3s16 p = pos + (*i);
3775 content_t c = env->getMap().getNodeNoEx(p).getContent();
3776 if(filter.count(c) != 0){
3785 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3786 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3787 static int l_find_nodes_in_area(lua_State *L)
3789 EnvRef *o = checkobject(L, 1);
3790 ServerEnvironment *env = o->m_env;
3791 if(env == NULL) return 0;
3792 INodeDefManager *ndef = get_server(L)->ndef();
3793 v3s16 minp = read_v3s16(L, 2);
3794 v3s16 maxp = read_v3s16(L, 3);
3795 std::set<content_t> filter;
3796 if(lua_istable(L, 4)){
3799 while(lua_next(L, table) != 0){
3800 // key at index -2 and value at index -1
3801 luaL_checktype(L, -1, LUA_TSTRING);
3802 ndef->getIds(lua_tostring(L, -1), filter);
3803 // removes value, keeps key for next iteration
3806 } else if(lua_isstring(L, 4)){
3807 ndef->getIds(lua_tostring(L, 4), filter);
3810 // Get the table insert function
3811 lua_getglobal(L, "table");
3812 lua_getfield(L, -1, "insert");
3813 int table_insert = lua_gettop(L);
3816 int table = lua_gettop(L);
3817 for(s16 x=minp.X; x<=maxp.X; x++)
3818 for(s16 y=minp.Y; y<=maxp.Y; y++)
3819 for(s16 z=minp.Z; z<=maxp.Z; z++)
3822 content_t c = env->getMap().getNodeNoEx(p).getContent();
3823 if(filter.count(c) != 0){
3824 lua_pushvalue(L, table_insert);
3825 lua_pushvalue(L, table);
3827 if(lua_pcall(L, 2, 0, 0))
3828 script_error(L, "error: %s", lua_tostring(L, -1));
3834 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3835 // returns world-specific PerlinNoise
3836 static int l_get_perlin(lua_State *L)
3838 EnvRef *o = checkobject(L, 1);
3839 ServerEnvironment *env = o->m_env;
3840 if(env == NULL) return 0;
3842 int seeddiff = luaL_checkint(L, 2);
3843 int octaves = luaL_checkint(L, 3);
3844 double persistence = luaL_checknumber(L, 4);
3845 double scale = luaL_checknumber(L, 5);
3847 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3848 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3849 luaL_getmetatable(L, "PerlinNoise");
3850 lua_setmetatable(L, -2);
3854 // EnvRef:clear_objects()
3855 // clear all objects in the environment
3856 static int l_clear_objects(lua_State *L)
3858 EnvRef *o = checkobject(L, 1);
3859 o->m_env->clearAllObjects();
3864 EnvRef(ServerEnvironment *env):
3867 //infostream<<"EnvRef created"<<std::endl;
3872 //infostream<<"EnvRef destructing"<<std::endl;
3875 // Creates an EnvRef and leaves it on top of stack
3876 // Not callable from Lua; all references are created on the C side.
3877 static void create(lua_State *L, ServerEnvironment *env)
3879 EnvRef *o = new EnvRef(env);
3880 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3881 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3882 luaL_getmetatable(L, className);
3883 lua_setmetatable(L, -2);
3886 static void set_null(lua_State *L)
3888 EnvRef *o = checkobject(L, -1);
3892 static void Register(lua_State *L)
3895 int methodtable = lua_gettop(L);
3896 luaL_newmetatable(L, className);
3897 int metatable = lua_gettop(L);
3899 lua_pushliteral(L, "__metatable");
3900 lua_pushvalue(L, methodtable);
3901 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3903 lua_pushliteral(L, "__index");
3904 lua_pushvalue(L, methodtable);
3905 lua_settable(L, metatable);
3907 lua_pushliteral(L, "__gc");
3908 lua_pushcfunction(L, gc_object);
3909 lua_settable(L, metatable);
3911 lua_pop(L, 1); // drop metatable
3913 luaL_openlib(L, 0, methods, 0); // fill methodtable
3914 lua_pop(L, 1); // drop methodtable
3916 // Cannot be created from Lua
3917 //lua_register(L, className, create_object);
3920 const char EnvRef::className[] = "EnvRef";
3921 const luaL_reg EnvRef::methods[] = {
3922 method(EnvRef, set_node),
3923 method(EnvRef, add_node),
3924 method(EnvRef, remove_node),
3925 method(EnvRef, get_node),
3926 method(EnvRef, get_node_or_nil),
3927 method(EnvRef, get_node_light),
3928 method(EnvRef, place_node),
3929 method(EnvRef, dig_node),
3930 method(EnvRef, punch_node),
3931 method(EnvRef, add_entity),
3932 method(EnvRef, add_item),
3933 method(EnvRef, add_rat),
3934 method(EnvRef, add_firefly),
3935 method(EnvRef, get_meta),
3936 method(EnvRef, get_node_timer),
3937 method(EnvRef, get_player_by_name),
3938 method(EnvRef, get_objects_inside_radius),
3939 method(EnvRef, set_timeofday),
3940 method(EnvRef, get_timeofday),
3941 method(EnvRef, find_node_near),
3942 method(EnvRef, find_nodes_in_area),
3943 method(EnvRef, get_perlin),
3944 method(EnvRef, clear_objects),
3953 class LuaPseudoRandom
3956 PseudoRandom m_pseudo;
3958 static const char className[];
3959 static const luaL_reg methods[];
3961 // Exported functions
3963 // garbage collector
3964 static int gc_object(lua_State *L)
3966 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3971 // next(self, min=0, max=32767) -> get next value
3972 static int l_next(lua_State *L)
3974 LuaPseudoRandom *o = checkobject(L, 1);
3977 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3978 if(!lua_isnil(L, 2))
3979 min = luaL_checkinteger(L, 2);
3980 if(!lua_isnil(L, 3))
3981 max = luaL_checkinteger(L, 3);
3983 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
3984 throw LuaError(L, "PseudoRandom.next(): max < min");
3986 if(max - min != 32767 && max - min > 32767/5)
3987 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.");
3988 PseudoRandom &pseudo = o->m_pseudo;
3989 int val = pseudo.next();
3990 val = (val % (max-min+1)) + min;
3991 lua_pushinteger(L, val);
3996 LuaPseudoRandom(int seed):
4005 const PseudoRandom& getItem() const
4009 PseudoRandom& getItem()
4014 // LuaPseudoRandom(seed)
4015 // Creates an LuaPseudoRandom and leaves it on top of stack
4016 static int create_object(lua_State *L)
4018 int seed = luaL_checknumber(L, 1);
4019 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4020 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4021 luaL_getmetatable(L, className);
4022 lua_setmetatable(L, -2);
4026 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4028 luaL_checktype(L, narg, LUA_TUSERDATA);
4029 void *ud = luaL_checkudata(L, narg, className);
4030 if(!ud) luaL_typerror(L, narg, className);
4031 return *(LuaPseudoRandom**)ud; // unbox pointer
4034 static void Register(lua_State *L)
4037 int methodtable = lua_gettop(L);
4038 luaL_newmetatable(L, className);
4039 int metatable = lua_gettop(L);
4041 lua_pushliteral(L, "__metatable");
4042 lua_pushvalue(L, methodtable);
4043 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4045 lua_pushliteral(L, "__index");
4046 lua_pushvalue(L, methodtable);
4047 lua_settable(L, metatable);
4049 lua_pushliteral(L, "__gc");
4050 lua_pushcfunction(L, gc_object);
4051 lua_settable(L, metatable);
4053 lua_pop(L, 1); // drop metatable
4055 luaL_openlib(L, 0, methods, 0); // fill methodtable
4056 lua_pop(L, 1); // drop methodtable
4058 // Can be created from Lua (LuaPseudoRandom(seed))
4059 lua_register(L, className, create_object);
4062 const char LuaPseudoRandom::className[] = "PseudoRandom";
4063 const luaL_reg LuaPseudoRandom::methods[] = {
4064 method(LuaPseudoRandom, next),
4074 class LuaABM : public ActiveBlockModifier
4080 std::set<std::string> m_trigger_contents;
4081 std::set<std::string> m_required_neighbors;
4082 float m_trigger_interval;
4083 u32 m_trigger_chance;
4085 LuaABM(lua_State *L, int id,
4086 const std::set<std::string> &trigger_contents,
4087 const std::set<std::string> &required_neighbors,
4088 float trigger_interval, u32 trigger_chance):
4091 m_trigger_contents(trigger_contents),
4092 m_required_neighbors(required_neighbors),
4093 m_trigger_interval(trigger_interval),
4094 m_trigger_chance(trigger_chance)
4097 virtual std::set<std::string> getTriggerContents()
4099 return m_trigger_contents;
4101 virtual std::set<std::string> getRequiredNeighbors()
4103 return m_required_neighbors;
4105 virtual float getTriggerInterval()
4107 return m_trigger_interval;
4109 virtual u32 getTriggerChance()
4111 return m_trigger_chance;
4113 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4114 u32 active_object_count, u32 active_object_count_wider)
4116 lua_State *L = m_lua;
4119 assert(lua_checkstack(L, 20));
4120 StackUnroller stack_unroller(L);
4122 // Get minetest.registered_abms
4123 lua_getglobal(L, "minetest");
4124 lua_getfield(L, -1, "registered_abms");
4125 luaL_checktype(L, -1, LUA_TTABLE);
4126 int registered_abms = lua_gettop(L);
4128 // Get minetest.registered_abms[m_id]
4129 lua_pushnumber(L, m_id);
4130 lua_gettable(L, registered_abms);
4131 if(lua_isnil(L, -1))
4135 luaL_checktype(L, -1, LUA_TTABLE);
4136 lua_getfield(L, -1, "action");
4137 luaL_checktype(L, -1, LUA_TFUNCTION);
4139 pushnode(L, n, env->getGameDef()->ndef());
4140 lua_pushnumber(L, active_object_count);
4141 lua_pushnumber(L, active_object_count_wider);
4142 if(lua_pcall(L, 4, 0, 0))
4143 script_error(L, "error: %s", lua_tostring(L, -1));
4151 static void read_server_sound_params(lua_State *L, int index,
4152 ServerSoundParams ¶ms)
4155 index = lua_gettop(L) + 1 + index;
4157 params = ServerSoundParams();
4158 if(lua_istable(L, index)){
4159 getfloatfield(L, index, "gain", params.gain);
4160 getstringfield(L, index, "to_player", params.to_player);
4161 lua_getfield(L, index, "pos");
4162 if(!lua_isnil(L, -1)){
4163 v3f p = read_v3f(L, -1)*BS;
4165 params.type = ServerSoundParams::SSP_POSITIONAL;
4168 lua_getfield(L, index, "object");
4169 if(!lua_isnil(L, -1)){
4170 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4171 ServerActiveObject *sao = ObjectRef::getobject(ref);
4173 params.object = sao->getId();
4174 params.type = ServerSoundParams::SSP_OBJECT;
4178 params.max_hear_distance = BS*getfloatfield_default(L, index,
4179 "max_hear_distance", params.max_hear_distance/BS);
4180 getboolfield(L, index, "loop", params.loop);
4189 // Writes a line to dstream
4190 static int l_debug(lua_State *L)
4192 std::string text = lua_tostring(L, 1);
4193 dstream << text << std::endl;
4197 // log([level,] text)
4198 // Writes a line to the logger.
4199 // The one-argument version logs to infostream.
4200 // The two-argument version accept a log level: error, action, info, or verbose.
4201 static int l_log(lua_State *L)
4204 LogMessageLevel level = LMT_INFO;
4205 if(lua_isnone(L, 2))
4207 text = lua_tostring(L, 1);
4211 std::string levelname = lua_tostring(L, 1);
4212 text = lua_tostring(L, 2);
4213 if(levelname == "error")
4215 else if(levelname == "action")
4217 else if(levelname == "verbose")
4218 level = LMT_VERBOSE;
4220 log_printline(level, text);
4224 // request_shutdown()
4225 static int l_request_shutdown(lua_State *L)
4227 get_server(L)->requestShutdown();
4231 // get_server_status()
4232 static int l_get_server_status(lua_State *L)
4234 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4238 // register_item_raw({lots of stuff})
4239 static int l_register_item_raw(lua_State *L)
4241 luaL_checktype(L, 1, LUA_TTABLE);
4244 // Get the writable item and node definition managers from the server
4245 IWritableItemDefManager *idef =
4246 get_server(L)->getWritableItemDefManager();
4247 IWritableNodeDefManager *ndef =
4248 get_server(L)->getWritableNodeDefManager();
4250 // Check if name is defined
4252 lua_getfield(L, table, "name");
4253 if(lua_isstring(L, -1)){
4254 name = lua_tostring(L, -1);
4255 verbosestream<<"register_item_raw: "<<name<<std::endl;
4257 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4260 // Check if on_use is defined
4263 // Set a distinctive default value to check if this is set
4264 def.node_placement_prediction = "__default";
4266 // Read the item definition
4267 def = read_item_definition(L, table, def);
4269 // Default to having client-side placement prediction for nodes
4270 // ("" in item definition sets it off)
4271 if(def.node_placement_prediction == "__default"){
4272 if(def.type == ITEM_NODE)
4273 def.node_placement_prediction = name;
4275 def.node_placement_prediction = "";
4278 // Register item definition
4279 idef->registerItem(def);
4281 // Read the node definition (content features) and register it
4282 if(def.type == ITEM_NODE)
4284 ContentFeatures f = read_content_features(L, table);
4285 ndef->set(f.name, f);
4288 return 0; /* number of results */
4291 // register_alias_raw(name, convert_to_name)
4292 static int l_register_alias_raw(lua_State *L)
4294 std::string name = luaL_checkstring(L, 1);
4295 std::string convert_to = luaL_checkstring(L, 2);
4297 // Get the writable item definition manager from the server
4298 IWritableItemDefManager *idef =
4299 get_server(L)->getWritableItemDefManager();
4301 idef->registerAlias(name, convert_to);
4303 return 0; /* number of results */
4306 // helper for register_craft
4307 static bool read_craft_recipe_shaped(lua_State *L, int index,
4308 int &width, std::vector<std::string> &recipe)
4311 index = lua_gettop(L) + 1 + index;
4313 if(!lua_istable(L, index))
4318 while(lua_next(L, index) != 0){
4320 // key at index -2 and value at index -1
4321 if(!lua_istable(L, -1))
4323 int table2 = lua_gettop(L);
4325 while(lua_next(L, table2) != 0){
4326 // key at index -2 and value at index -1
4327 if(!lua_isstring(L, -1))
4329 recipe.push_back(lua_tostring(L, -1));
4330 // removes value, keeps key for next iteration
4337 if(colcount != width)
4340 // removes value, keeps key for next iteration
4347 // helper for register_craft
4348 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4349 std::vector<std::string> &recipe)
4352 index = lua_gettop(L) + 1 + index;
4354 if(!lua_istable(L, index))
4358 while(lua_next(L, index) != 0){
4359 // key at index -2 and value at index -1
4360 if(!lua_isstring(L, -1))
4362 recipe.push_back(lua_tostring(L, -1));
4363 // removes value, keeps key for next iteration
4369 // helper for register_craft
4370 static bool read_craft_replacements(lua_State *L, int index,
4371 CraftReplacements &replacements)
4374 index = lua_gettop(L) + 1 + index;
4376 if(!lua_istable(L, index))
4380 while(lua_next(L, index) != 0){
4381 // key at index -2 and value at index -1
4382 if(!lua_istable(L, -1))
4384 lua_rawgeti(L, -1, 1);
4385 if(!lua_isstring(L, -1))
4387 std::string replace_from = lua_tostring(L, -1);
4389 lua_rawgeti(L, -1, 2);
4390 if(!lua_isstring(L, -1))
4392 std::string replace_to = lua_tostring(L, -1);
4394 replacements.pairs.push_back(
4395 std::make_pair(replace_from, replace_to));
4396 // removes value, keeps key for next iteration
4401 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4402 static int l_register_craft(lua_State *L)
4404 //infostream<<"register_craft"<<std::endl;
4405 luaL_checktype(L, 1, LUA_TTABLE);
4408 // Get the writable craft definition manager from the server
4409 IWritableCraftDefManager *craftdef =
4410 get_server(L)->getWritableCraftDefManager();
4412 std::string type = getstringfield_default(L, table, "type", "shaped");
4415 CraftDefinitionShaped
4417 if(type == "shaped"){
4418 std::string output = getstringfield_default(L, table, "output", "");
4420 throw LuaError(L, "Crafting definition is missing an output");
4423 std::vector<std::string> recipe;
4424 lua_getfield(L, table, "recipe");
4425 if(lua_isnil(L, -1))
4426 throw LuaError(L, "Crafting definition is missing a recipe"
4427 " (output=\"" + output + "\")");
4428 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4429 throw LuaError(L, "Invalid crafting recipe"
4430 " (output=\"" + output + "\")");
4432 CraftReplacements replacements;
4433 lua_getfield(L, table, "replacements");
4434 if(!lua_isnil(L, -1))
4436 if(!read_craft_replacements(L, -1, replacements))
4437 throw LuaError(L, "Invalid replacements"
4438 " (output=\"" + output + "\")");
4441 CraftDefinition *def = new CraftDefinitionShaped(
4442 output, width, recipe, replacements);
4443 craftdef->registerCraft(def);
4446 CraftDefinitionShapeless
4448 else if(type == "shapeless"){
4449 std::string output = getstringfield_default(L, table, "output", "");
4451 throw LuaError(L, "Crafting definition (shapeless)"
4452 " is missing an output");
4454 std::vector<std::string> recipe;
4455 lua_getfield(L, table, "recipe");
4456 if(lua_isnil(L, -1))
4457 throw LuaError(L, "Crafting definition (shapeless)"
4458 " is missing a recipe"
4459 " (output=\"" + output + "\")");
4460 if(!read_craft_recipe_shapeless(L, -1, recipe))
4461 throw LuaError(L, "Invalid crafting recipe"
4462 " (output=\"" + output + "\")");
4464 CraftReplacements replacements;
4465 lua_getfield(L, table, "replacements");
4466 if(!lua_isnil(L, -1))
4468 if(!read_craft_replacements(L, -1, replacements))
4469 throw LuaError(L, "Invalid replacements"
4470 " (output=\"" + output + "\")");
4473 CraftDefinition *def = new CraftDefinitionShapeless(
4474 output, recipe, replacements);
4475 craftdef->registerCraft(def);
4478 CraftDefinitionToolRepair
4480 else if(type == "toolrepair"){
4481 float additional_wear = getfloatfield_default(L, table,
4482 "additional_wear", 0.0);
4484 CraftDefinition *def = new CraftDefinitionToolRepair(
4486 craftdef->registerCraft(def);
4489 CraftDefinitionCooking
4491 else if(type == "cooking"){
4492 std::string output = getstringfield_default(L, table, "output", "");
4494 throw LuaError(L, "Crafting definition (cooking)"
4495 " is missing an output");
4497 std::string recipe = getstringfield_default(L, table, "recipe", "");
4499 throw LuaError(L, "Crafting definition (cooking)"
4500 " is missing a recipe"
4501 " (output=\"" + output + "\")");
4503 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4505 CraftReplacements replacements;
4506 lua_getfield(L, table, "replacements");
4507 if(!lua_isnil(L, -1))
4509 if(!read_craft_replacements(L, -1, replacements))
4510 throw LuaError(L, "Invalid replacements"
4511 " (cooking output=\"" + output + "\")");
4514 CraftDefinition *def = new CraftDefinitionCooking(
4515 output, recipe, cooktime, replacements);
4516 craftdef->registerCraft(def);
4521 else if(type == "fuel"){
4522 std::string recipe = getstringfield_default(L, table, "recipe", "");
4524 throw LuaError(L, "Crafting definition (fuel)"
4525 " is missing a recipe");
4527 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4529 CraftReplacements replacements;
4530 lua_getfield(L, table, "replacements");
4531 if(!lua_isnil(L, -1))
4533 if(!read_craft_replacements(L, -1, replacements))
4534 throw LuaError(L, "Invalid replacements"
4535 " (fuel recipe=\"" + recipe + "\")");
4538 CraftDefinition *def = new CraftDefinitionFuel(
4539 recipe, burntime, replacements);
4540 craftdef->registerCraft(def);
4544 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4548 return 0; /* number of results */
4551 // setting_set(name, value)
4552 static int l_setting_set(lua_State *L)
4554 const char *name = luaL_checkstring(L, 1);
4555 const char *value = luaL_checkstring(L, 2);
4556 g_settings->set(name, value);
4560 // setting_get(name)
4561 static int l_setting_get(lua_State *L)
4563 const char *name = luaL_checkstring(L, 1);
4565 std::string value = g_settings->get(name);
4566 lua_pushstring(L, value.c_str());
4567 } catch(SettingNotFoundException &e){
4573 // setting_getbool(name)
4574 static int l_setting_getbool(lua_State *L)
4576 const char *name = luaL_checkstring(L, 1);
4578 bool value = g_settings->getBool(name);
4579 lua_pushboolean(L, value);
4580 } catch(SettingNotFoundException &e){
4586 // chat_send_all(text)
4587 static int l_chat_send_all(lua_State *L)
4589 const char *text = luaL_checkstring(L, 1);
4590 // Get server from registry
4591 Server *server = get_server(L);
4593 server->notifyPlayers(narrow_to_wide(text));
4597 // chat_send_player(name, text)
4598 static int l_chat_send_player(lua_State *L)
4600 const char *name = luaL_checkstring(L, 1);
4601 const char *text = luaL_checkstring(L, 2);
4602 // Get server from registry
4603 Server *server = get_server(L);
4605 server->notifyPlayer(name, narrow_to_wide(text));
4609 // get_player_privs(name, text)
4610 static int l_get_player_privs(lua_State *L)
4612 const char *name = luaL_checkstring(L, 1);
4613 // Get server from registry
4614 Server *server = get_server(L);
4617 int table = lua_gettop(L);
4618 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4619 for(std::set<std::string>::const_iterator
4620 i = privs_s.begin(); i != privs_s.end(); i++){
4621 lua_pushboolean(L, true);
4622 lua_setfield(L, table, i->c_str());
4624 lua_pushvalue(L, table);
4629 static int l_get_ban_list(lua_State *L)
4631 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4635 // get_ban_description()
4636 static int l_get_ban_description(lua_State *L)
4638 const char * ip_or_name = luaL_checkstring(L, 1);
4639 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4644 static int l_ban_player(lua_State *L)
4646 const char * name = luaL_checkstring(L, 1);
4647 Player *player = get_env(L)->getPlayer(name);
4650 lua_pushboolean(L, false); // no such player
4655 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4656 std::string ip_str = addr.serializeString();
4657 get_server(L)->setIpBanned(ip_str, name);
4659 catch(con::PeerNotFoundException) // unlikely
4661 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4662 lua_pushboolean(L, false); // error
4665 lua_pushboolean(L, true);
4669 // unban_player_or_ip()
4670 static int l_unban_player_of_ip(lua_State *L)
4672 const char * ip_or_name = luaL_checkstring(L, 1);
4673 get_server(L)->unsetIpBanned(ip_or_name);
4674 lua_pushboolean(L, true);
4678 // get_inventory(location)
4679 static int l_get_inventory(lua_State *L)
4681 InventoryLocation loc;
4683 std::string type = checkstringfield(L, 1, "type");
4684 if(type == "player"){
4685 std::string name = checkstringfield(L, 1, "name");
4686 loc.setPlayer(name);
4687 } else if(type == "node"){
4688 lua_getfield(L, 1, "pos");
4689 v3s16 pos = check_v3s16(L, -1);
4690 loc.setNodeMeta(pos);
4691 } else if(type == "detached"){
4692 std::string name = checkstringfield(L, 1, "name");
4693 loc.setDetached(name);
4696 if(get_server(L)->getInventory(loc) != NULL)
4697 InvRef::create(L, loc);
4703 // create_detached_inventory_raw(name)
4704 static int l_create_detached_inventory_raw(lua_State *L)
4706 const char *name = luaL_checkstring(L, 1);
4707 if(get_server(L)->createDetachedInventory(name) != NULL){
4708 InventoryLocation loc;
4709 loc.setDetached(name);
4710 InvRef::create(L, loc);
4717 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4718 static int l_get_dig_params(lua_State *L)
4720 std::map<std::string, int> groups;
4721 read_groups(L, 1, groups);
4722 ToolCapabilities tp = read_tool_capabilities(L, 2);
4723 if(lua_isnoneornil(L, 3))
4724 push_dig_params(L, getDigParams(groups, &tp));
4726 push_dig_params(L, getDigParams(groups, &tp,
4727 luaL_checknumber(L, 3)));
4731 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4732 static int l_get_hit_params(lua_State *L)
4734 std::map<std::string, int> groups;
4735 read_groups(L, 1, groups);
4736 ToolCapabilities tp = read_tool_capabilities(L, 2);
4737 if(lua_isnoneornil(L, 3))
4738 push_hit_params(L, getHitParams(groups, &tp));
4740 push_hit_params(L, getHitParams(groups, &tp,
4741 luaL_checknumber(L, 3)));
4745 // get_current_modname()
4746 static int l_get_current_modname(lua_State *L)
4748 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4752 // get_modpath(modname)
4753 static int l_get_modpath(lua_State *L)
4755 std::string modname = luaL_checkstring(L, 1);
4757 if(modname == "__builtin"){
4758 std::string path = get_server(L)->getBuiltinLuaPath();
4759 lua_pushstring(L, path.c_str());
4762 const ModSpec *mod = get_server(L)->getModSpec(modname);
4767 lua_pushstring(L, mod->path.c_str());
4772 // the returned list is sorted alphabetically for you
4773 static int l_get_modnames(lua_State *L)
4775 // Get a list of mods
4776 core::list<std::string> mods_unsorted, mods_sorted;
4777 get_server(L)->getModNames(mods_unsorted);
4779 // Take unsorted items from mods_unsorted and sort them into
4780 // mods_sorted; not great performance but the number of mods on a
4781 // server will likely be small.
4782 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4783 i != mods_unsorted.end(); i++)
4786 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4787 x != mods_unsorted.end(); x++)
4789 // I doubt anybody using Minetest will be using
4790 // anything not ASCII based :)
4791 if((*i).compare(*x) <= 0)
4793 mods_sorted.insert_before(x, *i);
4799 mods_sorted.push_back(*i);
4802 // Get the table insertion function from Lua.
4803 lua_getglobal(L, "table");
4804 lua_getfield(L, -1, "insert");
4805 int insertion_func = lua_gettop(L);
4807 // Package them up for Lua
4809 int new_table = lua_gettop(L);
4810 core::list<std::string>::Iterator i = mods_sorted.begin();
4811 while(i != mods_sorted.end())
4813 lua_pushvalue(L, insertion_func);
4814 lua_pushvalue(L, new_table);
4815 lua_pushstring(L, (*i).c_str());
4816 if(lua_pcall(L, 2, 0, 0) != 0)
4818 script_error(L, "error: %s", lua_tostring(L, -1));
4826 static int l_get_worldpath(lua_State *L)
4828 std::string worldpath = get_server(L)->getWorldPath();
4829 lua_pushstring(L, worldpath.c_str());
4833 // sound_play(spec, parameters)
4834 static int l_sound_play(lua_State *L)
4836 SimpleSoundSpec spec;
4837 read_soundspec(L, 1, spec);
4838 ServerSoundParams params;
4839 read_server_sound_params(L, 2, params);
4840 s32 handle = get_server(L)->playSound(spec, params);
4841 lua_pushinteger(L, handle);
4845 // sound_stop(handle)
4846 static int l_sound_stop(lua_State *L)
4848 int handle = luaL_checkinteger(L, 1);
4849 get_server(L)->stopSound(handle);
4853 // is_singleplayer()
4854 static int l_is_singleplayer(lua_State *L)
4856 lua_pushboolean(L, get_server(L)->isSingleplayer());
4860 // get_password_hash(name, raw_password)
4861 static int l_get_password_hash(lua_State *L)
4863 std::string name = luaL_checkstring(L, 1);
4864 std::string raw_password = luaL_checkstring(L, 2);
4865 std::string hash = translatePassword(name,
4866 narrow_to_wide(raw_password));
4867 lua_pushstring(L, hash.c_str());
4871 // notify_authentication_modified(name)
4872 static int l_notify_authentication_modified(lua_State *L)
4874 std::string name = "";
4875 if(lua_isstring(L, 1))
4876 name = lua_tostring(L, 1);
4877 get_server(L)->reportPrivsModified(name);
4881 // get_craft_result(input)
4882 static int l_get_craft_result(lua_State *L)
4885 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4886 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4887 es_CraftMethod, CRAFT_METHOD_NORMAL);
4889 lua_getfield(L, input_i, "width");
4890 if(lua_isnumber(L, -1))
4891 width = luaL_checkinteger(L, -1);
4893 lua_getfield(L, input_i, "items");
4894 std::vector<ItemStack> items = read_items(L, -1);
4895 lua_pop(L, 1); // items
4897 IGameDef *gdef = get_server(L);
4898 ICraftDefManager *cdef = gdef->cdef();
4899 CraftInput input(method, width, items);
4901 bool got = cdef->getCraftResult(input, output, true, gdef);
4902 lua_newtable(L); // output table
4905 item.deSerialize(output.item, gdef->idef());
4906 LuaItemStack::create(L, item);
4907 lua_setfield(L, -2, "item");
4908 setintfield(L, -1, "time", output.time);
4910 LuaItemStack::create(L, ItemStack());
4911 lua_setfield(L, -2, "item");
4912 setintfield(L, -1, "time", 0);
4914 lua_newtable(L); // decremented input table
4915 lua_pushstring(L, method_s.c_str());
4916 lua_setfield(L, -2, "method");
4917 lua_pushinteger(L, width);
4918 lua_setfield(L, -2, "width");
4919 push_items(L, input.items);
4920 lua_setfield(L, -2, "items");
4924 // get_craft_recipe(result item)
4925 static int l_get_craft_recipe(lua_State *L)
4930 std::string o_item = luaL_checkstring(L,input_i);
4932 IGameDef *gdef = get_server(L);
4933 ICraftDefManager *cdef = gdef->cdef();
4935 CraftOutput output(o_item,0);
4936 bool got = cdef->getCraftRecipe(input, output, gdef);
4937 lua_newtable(L); // output table
4940 for(std::vector<ItemStack>::const_iterator
4941 i = input.items.begin();
4942 i != input.items.end(); i++, k++)
4948 sprintf(tmp,"%d",k);
4949 lua_pushstring(L,tmp);
4950 lua_pushstring(L,i->name.c_str());
4951 lua_settable(L, -3);
4953 lua_setfield(L, -2, "items");
4954 setintfield(L, -1, "width", input.width);
4955 switch (input.method) {
4956 case CRAFT_METHOD_NORMAL:
4957 lua_pushstring(L,"normal");
4959 case CRAFT_METHOD_COOKING:
4960 lua_pushstring(L,"cooking");
4962 case CRAFT_METHOD_FUEL:
4963 lua_pushstring(L,"fuel");
4966 lua_pushstring(L,"unknown");
4968 lua_setfield(L, -2, "type");
4971 lua_setfield(L, -2, "items");
4972 setintfield(L, -1, "width", 0);
4977 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
4978 static int l_rollback_get_last_node_actor(lua_State *L)
4980 v3s16 p = read_v3s16(L, 1);
4981 int range = luaL_checknumber(L, 2);
4982 int seconds = luaL_checknumber(L, 3);
4983 Server *server = get_server(L);
4984 IRollbackManager *rollback = server->getRollbackManager();
4986 int act_seconds = 0;
4987 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
4988 lua_pushstring(L, actor.c_str());
4989 push_v3s16(L, act_p);
4990 lua_pushnumber(L, act_seconds);
4994 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
4995 static int l_rollback_revert_actions_by(lua_State *L)
4997 std::string actor = luaL_checkstring(L, 1);
4998 int seconds = luaL_checknumber(L, 2);
4999 Server *server = get_server(L);
5000 IRollbackManager *rollback = server->getRollbackManager();
5001 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5002 std::list<std::string> log;
5003 bool success = server->rollbackRevertActions(actions, &log);
5004 // Push boolean result
5005 lua_pushboolean(L, success);
5006 // Get the table insert function and push the log table
5007 lua_getglobal(L, "table");
5008 lua_getfield(L, -1, "insert");
5009 int table_insert = lua_gettop(L);
5011 int table = lua_gettop(L);
5012 for(std::list<std::string>::const_iterator i = log.begin();
5013 i != log.end(); i++)
5015 lua_pushvalue(L, table_insert);
5016 lua_pushvalue(L, table);
5017 lua_pushstring(L, i->c_str());
5018 if(lua_pcall(L, 2, 0, 0))
5019 script_error(L, "error: %s", lua_tostring(L, -1));
5021 lua_remove(L, -2); // Remove table
5022 lua_remove(L, -2); // Remove insert
5026 static const struct luaL_Reg minetest_f [] = {
5029 {"request_shutdown", l_request_shutdown},
5030 {"get_server_status", l_get_server_status},
5031 {"register_item_raw", l_register_item_raw},
5032 {"register_alias_raw", l_register_alias_raw},
5033 {"register_craft", l_register_craft},
5034 {"setting_set", l_setting_set},
5035 {"setting_get", l_setting_get},
5036 {"setting_getbool", l_setting_getbool},
5037 {"chat_send_all", l_chat_send_all},
5038 {"chat_send_player", l_chat_send_player},
5039 {"get_player_privs", l_get_player_privs},
5040 {"get_ban_list", l_get_ban_list},
5041 {"get_ban_description", l_get_ban_description},
5042 {"ban_player", l_ban_player},
5043 {"unban_player_or_ip", l_unban_player_of_ip},
5044 {"get_inventory", l_get_inventory},
5045 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5046 {"get_dig_params", l_get_dig_params},
5047 {"get_hit_params", l_get_hit_params},
5048 {"get_current_modname", l_get_current_modname},
5049 {"get_modpath", l_get_modpath},
5050 {"get_modnames", l_get_modnames},
5051 {"get_worldpath", l_get_worldpath},
5052 {"sound_play", l_sound_play},
5053 {"sound_stop", l_sound_stop},
5054 {"is_singleplayer", l_is_singleplayer},
5055 {"get_password_hash", l_get_password_hash},
5056 {"notify_authentication_modified", l_notify_authentication_modified},
5057 {"get_craft_result", l_get_craft_result},
5058 {"get_craft_recipe", l_get_craft_recipe},
5059 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5060 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5065 Main export function
5068 void scriptapi_export(lua_State *L, Server *server)
5071 assert(lua_checkstack(L, 20));
5072 verbosestream<<"scriptapi_export()"<<std::endl;
5073 StackUnroller stack_unroller(L);
5075 // Store server as light userdata in registry
5076 lua_pushlightuserdata(L, server);
5077 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5079 // Register global functions in table minetest
5081 luaL_register(L, NULL, minetest_f);
5082 lua_setglobal(L, "minetest");
5084 // Get the main minetest table
5085 lua_getglobal(L, "minetest");
5087 // Add tables to minetest
5089 lua_setfield(L, -2, "object_refs");
5091 lua_setfield(L, -2, "luaentities");
5093 // Register wrappers
5094 LuaItemStack::Register(L);
5095 InvRef::Register(L);
5096 NodeMetaRef::Register(L);
5097 NodeTimerRef::Register(L);
5098 ObjectRef::Register(L);
5099 EnvRef::Register(L);
5100 LuaPseudoRandom::Register(L);
5101 LuaPerlinNoise::Register(L);
5104 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5105 const std::string &modname)
5107 ModNameStorer modnamestorer(L, modname);
5109 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5111 errorstream<<"Error loading mod \""<<modname
5112 <<"\": modname does not follow naming conventions: "
5113 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5117 bool success = false;
5120 success = script_load(L, scriptpath.c_str());
5123 errorstream<<"Error loading mod \""<<modname
5124 <<"\": "<<e.what()<<std::endl;
5130 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5133 assert(lua_checkstack(L, 20));
5134 verbosestream<<"scriptapi_add_environment"<<std::endl;
5135 StackUnroller stack_unroller(L);
5137 // Create EnvRef on stack
5138 EnvRef::create(L, env);
5139 int envref = lua_gettop(L);
5141 // minetest.env = envref
5142 lua_getglobal(L, "minetest");
5143 luaL_checktype(L, -1, LUA_TTABLE);
5144 lua_pushvalue(L, envref);
5145 lua_setfield(L, -2, "env");
5147 // Store environment as light userdata in registry
5148 lua_pushlightuserdata(L, env);
5149 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5152 Add ActiveBlockModifiers to environment
5155 // Get minetest.registered_abms
5156 lua_getglobal(L, "minetest");
5157 lua_getfield(L, -1, "registered_abms");
5158 luaL_checktype(L, -1, LUA_TTABLE);
5159 int registered_abms = lua_gettop(L);
5161 if(lua_istable(L, registered_abms)){
5162 int table = lua_gettop(L);
5164 while(lua_next(L, table) != 0){
5165 // key at index -2 and value at index -1
5166 int id = lua_tonumber(L, -2);
5167 int current_abm = lua_gettop(L);
5169 std::set<std::string> trigger_contents;
5170 lua_getfield(L, current_abm, "nodenames");
5171 if(lua_istable(L, -1)){
5172 int table = lua_gettop(L);
5174 while(lua_next(L, table) != 0){
5175 // key at index -2 and value at index -1
5176 luaL_checktype(L, -1, LUA_TSTRING);
5177 trigger_contents.insert(lua_tostring(L, -1));
5178 // removes value, keeps key for next iteration
5181 } else if(lua_isstring(L, -1)){
5182 trigger_contents.insert(lua_tostring(L, -1));
5186 std::set<std::string> required_neighbors;
5187 lua_getfield(L, current_abm, "neighbors");
5188 if(lua_istable(L, -1)){
5189 int table = lua_gettop(L);
5191 while(lua_next(L, table) != 0){
5192 // key at index -2 and value at index -1
5193 luaL_checktype(L, -1, LUA_TSTRING);
5194 required_neighbors.insert(lua_tostring(L, -1));
5195 // removes value, keeps key for next iteration
5198 } else if(lua_isstring(L, -1)){
5199 required_neighbors.insert(lua_tostring(L, -1));
5203 float trigger_interval = 10.0;
5204 getfloatfield(L, current_abm, "interval", trigger_interval);
5206 int trigger_chance = 50;
5207 getintfield(L, current_abm, "chance", trigger_chance);
5209 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5210 required_neighbors, trigger_interval, trigger_chance);
5212 env->addActiveBlockModifier(abm);
5214 // removes value, keeps key for next iteration
5222 // Dump stack top with the dump2 function
5223 static void dump2(lua_State *L, const char *name)
5225 // Dump object (debug)
5226 lua_getglobal(L, "dump2");
5227 luaL_checktype(L, -1, LUA_TFUNCTION);
5228 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5229 lua_pushstring(L, name);
5230 if(lua_pcall(L, 2, 0, 0))
5231 script_error(L, "error: %s", lua_tostring(L, -1));
5239 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5242 assert(lua_checkstack(L, 20));
5243 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5244 StackUnroller stack_unroller(L);
5246 // Create object on stack
5247 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5248 int object = lua_gettop(L);
5250 // Get minetest.object_refs table
5251 lua_getglobal(L, "minetest");
5252 lua_getfield(L, -1, "object_refs");
5253 luaL_checktype(L, -1, LUA_TTABLE);
5254 int objectstable = lua_gettop(L);
5256 // object_refs[id] = object
5257 lua_pushnumber(L, cobj->getId()); // Push id
5258 lua_pushvalue(L, object); // Copy object to top of stack
5259 lua_settable(L, objectstable);
5262 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5265 assert(lua_checkstack(L, 20));
5266 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5267 StackUnroller stack_unroller(L);
5269 // Get minetest.object_refs table
5270 lua_getglobal(L, "minetest");
5271 lua_getfield(L, -1, "object_refs");
5272 luaL_checktype(L, -1, LUA_TTABLE);
5273 int objectstable = lua_gettop(L);
5275 // Get object_refs[id]
5276 lua_pushnumber(L, cobj->getId()); // Push id
5277 lua_gettable(L, objectstable);
5278 // Set object reference to NULL
5279 ObjectRef::set_null(L);
5280 lua_pop(L, 1); // pop object
5282 // Set object_refs[id] = nil
5283 lua_pushnumber(L, cobj->getId()); // Push id
5285 lua_settable(L, objectstable);
5292 // What scriptapi_run_callbacks does with the return values of callbacks.
5293 // Regardless of the mode, if only one callback is defined,
5294 // its return value is the total return value.
5295 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5296 enum RunCallbacksMode
5298 // Returns the return value of the first callback
5299 // Returns nil if list of callbacks is empty
5300 RUN_CALLBACKS_MODE_FIRST,
5301 // Returns the return value of the last callback
5302 // Returns nil if list of callbacks is empty
5303 RUN_CALLBACKS_MODE_LAST,
5304 // If any callback returns a false value, the first such is returned
5305 // Otherwise, the first callback's return value (trueish) is returned
5306 // Returns true if list of callbacks is empty
5307 RUN_CALLBACKS_MODE_AND,
5308 // Like above, but stops calling callbacks (short circuit)
5309 // after seeing the first false value
5310 RUN_CALLBACKS_MODE_AND_SC,
5311 // If any callback returns a true value, the first such is returned
5312 // Otherwise, the first callback's return value (falseish) is returned
5313 // Returns false if list of callbacks is empty
5314 RUN_CALLBACKS_MODE_OR,
5315 // Like above, but stops calling callbacks (short circuit)
5316 // after seeing the first true value
5317 RUN_CALLBACKS_MODE_OR_SC,
5318 // Note: "a true value" and "a false value" refer to values that
5319 // are converted by lua_toboolean to true or false, respectively.
5322 // Push the list of callbacks (a lua table).
5323 // Then push nargs arguments.
5324 // Then call this function, which
5325 // - runs the callbacks
5326 // - removes the table and arguments from the lua stack
5327 // - pushes the return value, computed depending on mode
5328 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5329 RunCallbacksMode mode)
5331 // Insert the return value into the lua stack, below the table
5332 assert(lua_gettop(L) >= nargs + 1);
5334 lua_insert(L, -(nargs + 1) - 1);
5335 // Stack now looks like this:
5336 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5338 int rv = lua_gettop(L) - nargs - 1;
5340 int arg = table + 1;
5342 luaL_checktype(L, table, LUA_TTABLE);
5346 bool first_loop = true;
5347 while(lua_next(L, table) != 0){
5348 // key at index -2 and value at index -1
5349 luaL_checktype(L, -1, LUA_TFUNCTION);
5351 for(int i = 0; i < nargs; i++)
5352 lua_pushvalue(L, arg+i);
5353 if(lua_pcall(L, nargs, 1, 0))
5354 script_error(L, "error: %s", lua_tostring(L, -1));
5356 // Move return value to designated space in stack
5359 // Result of first callback is always moved
5363 // Otherwise, what happens depends on the mode
5364 if(mode == RUN_CALLBACKS_MODE_FIRST)
5366 else if(mode == RUN_CALLBACKS_MODE_LAST)
5368 else if(mode == RUN_CALLBACKS_MODE_AND ||
5369 mode == RUN_CALLBACKS_MODE_AND_SC){
5370 if(lua_toboolean(L, rv) == true &&
5371 lua_toboolean(L, -1) == false)
5376 else if(mode == RUN_CALLBACKS_MODE_OR ||
5377 mode == RUN_CALLBACKS_MODE_OR_SC){
5378 if(lua_toboolean(L, rv) == false &&
5379 lua_toboolean(L, -1) == true)
5388 // Handle short circuit modes
5389 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5390 lua_toboolean(L, rv) == false)
5392 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5393 lua_toboolean(L, rv) == true)
5396 // value removed, keep key for next iteration
5399 // Remove stuff from stack, leaving only the return value
5402 // Fix return value in case no callbacks were called
5404 if(mode == RUN_CALLBACKS_MODE_AND ||
5405 mode == RUN_CALLBACKS_MODE_AND_SC){
5407 lua_pushboolean(L, true);
5409 else if(mode == RUN_CALLBACKS_MODE_OR ||
5410 mode == RUN_CALLBACKS_MODE_OR_SC){
5412 lua_pushboolean(L, false);
5417 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5418 const std::string &message)
5421 assert(lua_checkstack(L, 20));
5422 StackUnroller stack_unroller(L);
5424 // Get minetest.registered_on_chat_messages
5425 lua_getglobal(L, "minetest");
5426 lua_getfield(L, -1, "registered_on_chat_messages");
5428 lua_pushstring(L, name.c_str());
5429 lua_pushstring(L, message.c_str());
5430 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5431 bool ate = lua_toboolean(L, -1);
5435 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5438 assert(lua_checkstack(L, 20));
5439 StackUnroller stack_unroller(L);
5441 // Get minetest.registered_on_newplayers
5442 lua_getglobal(L, "minetest");
5443 lua_getfield(L, -1, "registered_on_newplayers");
5445 objectref_get_or_create(L, player);
5446 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5449 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5452 assert(lua_checkstack(L, 20));
5453 StackUnroller stack_unroller(L);
5455 // Get minetest.registered_on_dieplayers
5456 lua_getglobal(L, "minetest");
5457 lua_getfield(L, -1, "registered_on_dieplayers");
5459 objectref_get_or_create(L, player);
5460 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5463 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5466 assert(lua_checkstack(L, 20));
5467 StackUnroller stack_unroller(L);
5469 // Get minetest.registered_on_respawnplayers
5470 lua_getglobal(L, "minetest");
5471 lua_getfield(L, -1, "registered_on_respawnplayers");
5473 objectref_get_or_create(L, player);
5474 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5475 bool positioning_handled_by_some = lua_toboolean(L, -1);
5476 return positioning_handled_by_some;
5479 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5482 assert(lua_checkstack(L, 20));
5483 StackUnroller stack_unroller(L);
5485 // Get minetest.registered_on_joinplayers
5486 lua_getglobal(L, "minetest");
5487 lua_getfield(L, -1, "registered_on_joinplayers");
5489 objectref_get_or_create(L, player);
5490 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5493 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5496 assert(lua_checkstack(L, 20));
5497 StackUnroller stack_unroller(L);
5499 // Get minetest.registered_on_leaveplayers
5500 lua_getglobal(L, "minetest");
5501 lua_getfield(L, -1, "registered_on_leaveplayers");
5503 objectref_get_or_create(L, player);
5504 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5507 static void get_auth_handler(lua_State *L)
5509 lua_getglobal(L, "minetest");
5510 lua_getfield(L, -1, "registered_auth_handler");
5511 if(lua_isnil(L, -1)){
5513 lua_getfield(L, -1, "builtin_auth_handler");
5515 if(lua_type(L, -1) != LUA_TTABLE)
5516 throw LuaError(L, "Authentication handler table not valid");
5519 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5520 std::string *dst_password, std::set<std::string> *dst_privs)
5523 assert(lua_checkstack(L, 20));
5524 StackUnroller stack_unroller(L);
5526 get_auth_handler(L);
5527 lua_getfield(L, -1, "get_auth");
5528 if(lua_type(L, -1) != LUA_TFUNCTION)
5529 throw LuaError(L, "Authentication handler missing get_auth");
5530 lua_pushstring(L, playername.c_str());
5531 if(lua_pcall(L, 1, 1, 0))
5532 script_error(L, "error: %s", lua_tostring(L, -1));
5534 // nil = login not allowed
5535 if(lua_isnil(L, -1))
5537 luaL_checktype(L, -1, LUA_TTABLE);
5539 std::string password;
5540 bool found = getstringfield(L, -1, "password", password);
5542 throw LuaError(L, "Authentication handler didn't return password");
5544 *dst_password = password;
5546 lua_getfield(L, -1, "privileges");
5547 if(!lua_istable(L, -1))
5549 "Authentication handler didn't return privilege table");
5551 read_privileges(L, -1, *dst_privs);
5557 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5558 const std::string &password)
5561 assert(lua_checkstack(L, 20));
5562 StackUnroller stack_unroller(L);
5564 get_auth_handler(L);
5565 lua_getfield(L, -1, "create_auth");
5566 if(lua_type(L, -1) != LUA_TFUNCTION)
5567 throw LuaError(L, "Authentication handler missing create_auth");
5568 lua_pushstring(L, playername.c_str());
5569 lua_pushstring(L, password.c_str());
5570 if(lua_pcall(L, 2, 0, 0))
5571 script_error(L, "error: %s", lua_tostring(L, -1));
5574 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5575 const std::string &password)
5578 assert(lua_checkstack(L, 20));
5579 StackUnroller stack_unroller(L);
5581 get_auth_handler(L);
5582 lua_getfield(L, -1, "set_password");
5583 if(lua_type(L, -1) != LUA_TFUNCTION)
5584 throw LuaError(L, "Authentication handler missing set_password");
5585 lua_pushstring(L, playername.c_str());
5586 lua_pushstring(L, password.c_str());
5587 if(lua_pcall(L, 2, 1, 0))
5588 script_error(L, "error: %s", lua_tostring(L, -1));
5589 return lua_toboolean(L, -1);
5596 void scriptapi_on_player_receive_fields(lua_State *L,
5597 ServerActiveObject *player,
5598 const std::string &formname,
5599 const std::map<std::string, std::string> &fields)
5602 assert(lua_checkstack(L, 20));
5603 StackUnroller stack_unroller(L);
5605 // Get minetest.registered_on_chat_messages
5606 lua_getglobal(L, "minetest");
5607 lua_getfield(L, -1, "registered_on_player_receive_fields");
5610 objectref_get_or_create(L, player);
5612 lua_pushstring(L, formname.c_str());
5615 for(std::map<std::string, std::string>::const_iterator
5616 i = fields.begin(); i != fields.end(); i++){
5617 const std::string &name = i->first;
5618 const std::string &value = i->second;
5619 lua_pushstring(L, name.c_str());
5620 lua_pushlstring(L, value.c_str(), value.size());
5621 lua_settable(L, -3);
5623 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5627 item callbacks and node callbacks
5630 // Retrieves minetest.registered_items[name][callbackname]
5631 // If that is nil or on error, return false and stack is unchanged
5632 // If that is a function, returns true and pushes the
5633 // function onto the stack
5634 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5635 // is tried instead so unknown items can still be manipulated to some degree
5636 static bool get_item_callback(lua_State *L,
5637 const char *name, const char *callbackname)
5639 lua_getglobal(L, "minetest");
5640 lua_getfield(L, -1, "registered_items");
5642 luaL_checktype(L, -1, LUA_TTABLE);
5643 lua_getfield(L, -1, name);
5645 // Should be a table
5646 if(lua_type(L, -1) != LUA_TTABLE)
5648 // Report error and clean up
5649 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5652 // Try minetest.nodedef_default instead
5653 lua_getglobal(L, "minetest");
5654 lua_getfield(L, -1, "nodedef_default");
5656 luaL_checktype(L, -1, LUA_TTABLE);
5658 lua_getfield(L, -1, callbackname);
5660 // Should be a function or nil
5661 if(lua_type(L, -1) == LUA_TFUNCTION)
5665 else if(lua_isnil(L, -1))
5672 errorstream<<"Item \""<<name<<"\" callback \""
5673 <<callbackname<<" is not a function"<<std::endl;
5679 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5680 ServerActiveObject *dropper, v3f pos)
5683 assert(lua_checkstack(L, 20));
5684 StackUnroller stack_unroller(L);
5686 // Push callback function on stack
5687 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5691 LuaItemStack::create(L, item);
5692 objectref_get_or_create(L, dropper);
5693 pushFloatPos(L, pos);
5694 if(lua_pcall(L, 3, 1, 0))
5695 script_error(L, "error: %s", lua_tostring(L, -1));
5696 if(!lua_isnil(L, -1))
5697 item = read_item(L, -1);
5701 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5702 ServerActiveObject *placer, const PointedThing &pointed)
5705 assert(lua_checkstack(L, 20));
5706 StackUnroller stack_unroller(L);
5708 // Push callback function on stack
5709 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5713 LuaItemStack::create(L, item);
5714 objectref_get_or_create(L, placer);
5715 push_pointed_thing(L, pointed);
5716 if(lua_pcall(L, 3, 1, 0))
5717 script_error(L, "error: %s", lua_tostring(L, -1));
5718 if(!lua_isnil(L, -1))
5719 item = read_item(L, -1);
5723 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5724 ServerActiveObject *user, const PointedThing &pointed)
5727 assert(lua_checkstack(L, 20));
5728 StackUnroller stack_unroller(L);
5730 // Push callback function on stack
5731 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5735 LuaItemStack::create(L, item);
5736 objectref_get_or_create(L, user);
5737 push_pointed_thing(L, pointed);
5738 if(lua_pcall(L, 3, 1, 0))
5739 script_error(L, "error: %s", lua_tostring(L, -1));
5740 if(!lua_isnil(L, -1))
5741 item = read_item(L, -1);
5745 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5746 ServerActiveObject *puncher)
5749 assert(lua_checkstack(L, 20));
5750 StackUnroller stack_unroller(L);
5752 INodeDefManager *ndef = get_server(L)->ndef();
5754 // Push callback function on stack
5755 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5760 pushnode(L, node, ndef);
5761 objectref_get_or_create(L, puncher);
5762 if(lua_pcall(L, 3, 0, 0))
5763 script_error(L, "error: %s", lua_tostring(L, -1));
5767 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5768 ServerActiveObject *digger)
5771 assert(lua_checkstack(L, 20));
5772 StackUnroller stack_unroller(L);
5774 INodeDefManager *ndef = get_server(L)->ndef();
5776 // Push callback function on stack
5777 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5782 pushnode(L, node, ndef);
5783 objectref_get_or_create(L, digger);
5784 if(lua_pcall(L, 3, 0, 0))
5785 script_error(L, "error: %s", lua_tostring(L, -1));
5789 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5792 assert(lua_checkstack(L, 20));
5793 StackUnroller stack_unroller(L);
5795 INodeDefManager *ndef = get_server(L)->ndef();
5797 // Push callback function on stack
5798 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5803 if(lua_pcall(L, 1, 0, 0))
5804 script_error(L, "error: %s", lua_tostring(L, -1));
5807 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5810 assert(lua_checkstack(L, 20));
5811 StackUnroller stack_unroller(L);
5813 INodeDefManager *ndef = get_server(L)->ndef();
5815 // Push callback function on stack
5816 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5821 if(lua_pcall(L, 1, 0, 0))
5822 script_error(L, "error: %s", lua_tostring(L, -1));
5825 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5828 assert(lua_checkstack(L, 20));
5829 StackUnroller stack_unroller(L);
5831 INodeDefManager *ndef = get_server(L)->ndef();
5833 // Push callback function on stack
5834 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5839 pushnode(L, node, ndef);
5840 if(lua_pcall(L, 2, 0, 0))
5841 script_error(L, "error: %s", lua_tostring(L, -1));
5844 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5847 assert(lua_checkstack(L, 20));
5848 StackUnroller stack_unroller(L);
5850 INodeDefManager *ndef = get_server(L)->ndef();
5852 // Push callback function on stack
5853 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5858 lua_pushnumber(L,dtime);
5859 if(lua_pcall(L, 2, 1, 0))
5860 script_error(L, "error: %s", lua_tostring(L, -1));
5861 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5867 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5868 const std::string &formname,
5869 const std::map<std::string, std::string> &fields,
5870 ServerActiveObject *sender)
5873 assert(lua_checkstack(L, 20));
5874 StackUnroller stack_unroller(L);
5876 INodeDefManager *ndef = get_server(L)->ndef();
5878 // If node doesn't exist, we don't know what callback to call
5879 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5880 if(node.getContent() == CONTENT_IGNORE)
5883 // Push callback function on stack
5884 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5891 lua_pushstring(L, formname.c_str());
5894 for(std::map<std::string, std::string>::const_iterator
5895 i = fields.begin(); i != fields.end(); i++){
5896 const std::string &name = i->first;
5897 const std::string &value = i->second;
5898 lua_pushstring(L, name.c_str());
5899 lua_pushlstring(L, value.c_str(), value.size());
5900 lua_settable(L, -3);
5903 objectref_get_or_create(L, sender);
5904 if(lua_pcall(L, 4, 0, 0))
5905 script_error(L, "error: %s", lua_tostring(L, -1));
5909 Node metadata inventory callbacks
5912 // Return number of accepted items to be moved
5913 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5914 const std::string &from_list, int from_index,
5915 const std::string &to_list, int to_index,
5916 int count, ServerActiveObject *player)
5919 assert(lua_checkstack(L, 20));
5920 StackUnroller stack_unroller(L);
5922 INodeDefManager *ndef = get_server(L)->ndef();
5924 // If node doesn't exist, we don't know what callback to call
5925 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5926 if(node.getContent() == CONTENT_IGNORE)
5929 // Push callback function on stack
5930 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5931 "allow_metadata_inventory_move"))
5934 // function(pos, from_list, from_index, to_list, to_index, count, player)
5938 lua_pushstring(L, from_list.c_str());
5940 lua_pushinteger(L, from_index + 1);
5942 lua_pushstring(L, to_list.c_str());
5944 lua_pushinteger(L, to_index + 1);
5946 lua_pushinteger(L, count);
5948 objectref_get_or_create(L, player);
5949 if(lua_pcall(L, 7, 1, 0))
5950 script_error(L, "error: %s", lua_tostring(L, -1));
5951 if(!lua_isnumber(L, -1))
5952 throw LuaError(L, "allow_metadata_inventory_move should return a number");
5953 return luaL_checkinteger(L, -1);
5956 // Return number of accepted items to be put
5957 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
5958 const std::string &listname, int index, ItemStack &stack,
5959 ServerActiveObject *player)
5962 assert(lua_checkstack(L, 20));
5963 StackUnroller stack_unroller(L);
5965 INodeDefManager *ndef = get_server(L)->ndef();
5967 // If node doesn't exist, we don't know what callback to call
5968 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5969 if(node.getContent() == CONTENT_IGNORE)
5972 // Push callback function on stack
5973 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5974 "allow_metadata_inventory_put"))
5977 // Call function(pos, listname, index, stack, player)
5981 lua_pushstring(L, listname.c_str());
5983 lua_pushinteger(L, index + 1);
5985 LuaItemStack::create(L, stack);
5987 objectref_get_or_create(L, player);
5988 if(lua_pcall(L, 5, 1, 0))
5989 script_error(L, "error: %s", lua_tostring(L, -1));
5990 if(!lua_isnumber(L, -1))
5991 throw LuaError(L, "allow_metadata_inventory_put should return a number");
5992 return luaL_checkinteger(L, -1);
5995 // Return number of accepted items to be taken
5996 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
5997 const std::string &listname, int index, ItemStack &stack,
5998 ServerActiveObject *player)
6001 assert(lua_checkstack(L, 20));
6002 StackUnroller stack_unroller(L);
6004 INodeDefManager *ndef = get_server(L)->ndef();
6006 // If node doesn't exist, we don't know what callback to call
6007 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6008 if(node.getContent() == CONTENT_IGNORE)
6011 // Push callback function on stack
6012 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6013 "allow_metadata_inventory_take"))
6016 // Call function(pos, listname, index, count, player)
6020 lua_pushstring(L, listname.c_str());
6022 lua_pushinteger(L, index + 1);
6024 LuaItemStack::create(L, stack);
6026 objectref_get_or_create(L, player);
6027 if(lua_pcall(L, 5, 1, 0))
6028 script_error(L, "error: %s", lua_tostring(L, -1));
6029 if(!lua_isnumber(L, -1))
6030 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6031 return luaL_checkinteger(L, -1);
6034 // Report moved items
6035 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6036 const std::string &from_list, int from_index,
6037 const std::string &to_list, int to_index,
6038 int count, ServerActiveObject *player)
6041 assert(lua_checkstack(L, 20));
6042 StackUnroller stack_unroller(L);
6044 INodeDefManager *ndef = get_server(L)->ndef();
6046 // If node doesn't exist, we don't know what callback to call
6047 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6048 if(node.getContent() == CONTENT_IGNORE)
6051 // Push callback function on stack
6052 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6053 "on_metadata_inventory_move"))
6056 // function(pos, from_list, from_index, to_list, to_index, count, player)
6060 lua_pushstring(L, from_list.c_str());
6062 lua_pushinteger(L, from_index + 1);
6064 lua_pushstring(L, to_list.c_str());
6066 lua_pushinteger(L, to_index + 1);
6068 lua_pushinteger(L, count);
6070 objectref_get_or_create(L, player);
6071 if(lua_pcall(L, 7, 0, 0))
6072 script_error(L, "error: %s", lua_tostring(L, -1));
6076 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6077 const std::string &listname, int index, ItemStack &stack,
6078 ServerActiveObject *player)
6081 assert(lua_checkstack(L, 20));
6082 StackUnroller stack_unroller(L);
6084 INodeDefManager *ndef = get_server(L)->ndef();
6086 // If node doesn't exist, we don't know what callback to call
6087 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6088 if(node.getContent() == CONTENT_IGNORE)
6091 // Push callback function on stack
6092 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6093 "on_metadata_inventory_put"))
6096 // Call function(pos, listname, index, stack, player)
6100 lua_pushstring(L, listname.c_str());
6102 lua_pushinteger(L, index + 1);
6104 LuaItemStack::create(L, stack);
6106 objectref_get_or_create(L, player);
6107 if(lua_pcall(L, 5, 0, 0))
6108 script_error(L, "error: %s", lua_tostring(L, -1));
6111 // Report taken items
6112 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6113 const std::string &listname, int index, ItemStack &stack,
6114 ServerActiveObject *player)
6117 assert(lua_checkstack(L, 20));
6118 StackUnroller stack_unroller(L);
6120 INodeDefManager *ndef = get_server(L)->ndef();
6122 // If node doesn't exist, we don't know what callback to call
6123 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6124 if(node.getContent() == CONTENT_IGNORE)
6127 // Push callback function on stack
6128 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6129 "on_metadata_inventory_take"))
6132 // Call function(pos, listname, index, stack, player)
6136 lua_pushstring(L, listname.c_str());
6138 lua_pushinteger(L, index + 1);
6140 LuaItemStack::create(L, stack);
6142 objectref_get_or_create(L, player);
6143 if(lua_pcall(L, 5, 0, 0))
6144 script_error(L, "error: %s", lua_tostring(L, -1));
6148 Detached inventory callbacks
6151 // Retrieves minetest.detached_inventories[name][callbackname]
6152 // If that is nil or on error, return false and stack is unchanged
6153 // If that is a function, returns true and pushes the
6154 // function onto the stack
6155 static bool get_detached_inventory_callback(lua_State *L,
6156 const std::string &name, const char *callbackname)
6158 lua_getglobal(L, "minetest");
6159 lua_getfield(L, -1, "detached_inventories");
6161 luaL_checktype(L, -1, LUA_TTABLE);
6162 lua_getfield(L, -1, name.c_str());
6164 // Should be a table
6165 if(lua_type(L, -1) != LUA_TTABLE)
6167 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6171 lua_getfield(L, -1, callbackname);
6173 // Should be a function or nil
6174 if(lua_type(L, -1) == LUA_TFUNCTION)
6178 else if(lua_isnil(L, -1))
6185 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6186 <<callbackname<<"\" is not a function"<<std::endl;
6192 // Return number of accepted items to be moved
6193 int scriptapi_detached_inventory_allow_move(lua_State *L,
6194 const std::string &name,
6195 const std::string &from_list, int from_index,
6196 const std::string &to_list, int to_index,
6197 int count, ServerActiveObject *player)
6200 assert(lua_checkstack(L, 20));
6201 StackUnroller stack_unroller(L);
6203 // Push callback function on stack
6204 if(!get_detached_inventory_callback(L, name, "allow_move"))
6207 // function(inv, from_list, from_index, to_list, to_index, count, player)
6209 InventoryLocation loc;
6210 loc.setDetached(name);
6211 InvRef::create(L, loc);
6213 lua_pushstring(L, from_list.c_str());
6215 lua_pushinteger(L, from_index + 1);
6217 lua_pushstring(L, to_list.c_str());
6219 lua_pushinteger(L, to_index + 1);
6221 lua_pushinteger(L, count);
6223 objectref_get_or_create(L, player);
6224 if(lua_pcall(L, 7, 1, 0))
6225 script_error(L, "error: %s", lua_tostring(L, -1));
6226 if(!lua_isnumber(L, -1))
6227 throw LuaError(L, "allow_move should return a number");
6228 return luaL_checkinteger(L, -1);
6231 // Return number of accepted items to be put
6232 int scriptapi_detached_inventory_allow_put(lua_State *L,
6233 const std::string &name,
6234 const std::string &listname, int index, ItemStack &stack,
6235 ServerActiveObject *player)
6238 assert(lua_checkstack(L, 20));
6239 StackUnroller stack_unroller(L);
6241 // Push callback function on stack
6242 if(!get_detached_inventory_callback(L, name, "allow_put"))
6243 return stack.count; // All will be accepted
6245 // Call function(inv, listname, index, stack, player)
6247 InventoryLocation loc;
6248 loc.setDetached(name);
6249 InvRef::create(L, loc);
6251 lua_pushstring(L, listname.c_str());
6253 lua_pushinteger(L, index + 1);
6255 LuaItemStack::create(L, stack);
6257 objectref_get_or_create(L, player);
6258 if(lua_pcall(L, 5, 1, 0))
6259 script_error(L, "error: %s", lua_tostring(L, -1));
6260 if(!lua_isnumber(L, -1))
6261 throw LuaError(L, "allow_put should return a number");
6262 return luaL_checkinteger(L, -1);
6265 // Return number of accepted items to be taken
6266 int scriptapi_detached_inventory_allow_take(lua_State *L,
6267 const std::string &name,
6268 const std::string &listname, int index, ItemStack &stack,
6269 ServerActiveObject *player)
6272 assert(lua_checkstack(L, 20));
6273 StackUnroller stack_unroller(L);
6275 // Push callback function on stack
6276 if(!get_detached_inventory_callback(L, name, "allow_take"))
6277 return stack.count; // All will be accepted
6279 // Call function(inv, listname, index, stack, player)
6281 InventoryLocation loc;
6282 loc.setDetached(name);
6283 InvRef::create(L, loc);
6285 lua_pushstring(L, listname.c_str());
6287 lua_pushinteger(L, index + 1);
6289 LuaItemStack::create(L, stack);
6291 objectref_get_or_create(L, player);
6292 if(lua_pcall(L, 5, 1, 0))
6293 script_error(L, "error: %s", lua_tostring(L, -1));
6294 if(!lua_isnumber(L, -1))
6295 throw LuaError(L, "allow_take should return a number");
6296 return luaL_checkinteger(L, -1);
6299 // Report moved items
6300 void scriptapi_detached_inventory_on_move(lua_State *L,
6301 const std::string &name,
6302 const std::string &from_list, int from_index,
6303 const std::string &to_list, int to_index,
6304 int count, ServerActiveObject *player)
6307 assert(lua_checkstack(L, 20));
6308 StackUnroller stack_unroller(L);
6310 // Push callback function on stack
6311 if(!get_detached_inventory_callback(L, name, "on_move"))
6314 // function(inv, from_list, from_index, to_list, to_index, count, player)
6316 InventoryLocation loc;
6317 loc.setDetached(name);
6318 InvRef::create(L, loc);
6320 lua_pushstring(L, from_list.c_str());
6322 lua_pushinteger(L, from_index + 1);
6324 lua_pushstring(L, to_list.c_str());
6326 lua_pushinteger(L, to_index + 1);
6328 lua_pushinteger(L, count);
6330 objectref_get_or_create(L, player);
6331 if(lua_pcall(L, 7, 0, 0))
6332 script_error(L, "error: %s", lua_tostring(L, -1));
6336 void scriptapi_detached_inventory_on_put(lua_State *L,
6337 const std::string &name,
6338 const std::string &listname, int index, ItemStack &stack,
6339 ServerActiveObject *player)
6342 assert(lua_checkstack(L, 20));
6343 StackUnroller stack_unroller(L);
6345 // Push callback function on stack
6346 if(!get_detached_inventory_callback(L, name, "on_put"))
6349 // Call function(inv, listname, index, stack, player)
6351 InventoryLocation loc;
6352 loc.setDetached(name);
6353 InvRef::create(L, loc);
6355 lua_pushstring(L, listname.c_str());
6357 lua_pushinteger(L, index + 1);
6359 LuaItemStack::create(L, stack);
6361 objectref_get_or_create(L, player);
6362 if(lua_pcall(L, 5, 0, 0))
6363 script_error(L, "error: %s", lua_tostring(L, -1));
6366 // Report taken items
6367 void scriptapi_detached_inventory_on_take(lua_State *L,
6368 const std::string &name,
6369 const std::string &listname, int index, ItemStack &stack,
6370 ServerActiveObject *player)
6373 assert(lua_checkstack(L, 20));
6374 StackUnroller stack_unroller(L);
6376 // Push callback function on stack
6377 if(!get_detached_inventory_callback(L, name, "on_take"))
6380 // Call function(inv, listname, index, stack, player)
6382 InventoryLocation loc;
6383 loc.setDetached(name);
6384 InvRef::create(L, loc);
6386 lua_pushstring(L, listname.c_str());
6388 lua_pushinteger(L, index + 1);
6390 LuaItemStack::create(L, stack);
6392 objectref_get_or_create(L, player);
6393 if(lua_pcall(L, 5, 0, 0))
6394 script_error(L, "error: %s", lua_tostring(L, -1));
6401 void scriptapi_environment_step(lua_State *L, float dtime)
6404 assert(lua_checkstack(L, 20));
6405 //infostream<<"scriptapi_environment_step"<<std::endl;
6406 StackUnroller stack_unroller(L);
6408 // Get minetest.registered_globalsteps
6409 lua_getglobal(L, "minetest");
6410 lua_getfield(L, -1, "registered_globalsteps");
6412 lua_pushnumber(L, dtime);
6413 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6416 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6420 assert(lua_checkstack(L, 20));
6421 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6422 StackUnroller stack_unroller(L);
6424 // Get minetest.registered_on_generateds
6425 lua_getglobal(L, "minetest");
6426 lua_getfield(L, -1, "registered_on_generateds");
6428 push_v3s16(L, minp);
6429 push_v3s16(L, maxp);
6430 lua_pushnumber(L, blockseed);
6431 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6438 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6441 assert(lua_checkstack(L, 20));
6442 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6443 <<name<<"\""<<std::endl;
6444 StackUnroller stack_unroller(L);
6446 // Get minetest.registered_entities[name]
6447 lua_getglobal(L, "minetest");
6448 lua_getfield(L, -1, "registered_entities");
6449 luaL_checktype(L, -1, LUA_TTABLE);
6450 lua_pushstring(L, name);
6451 lua_gettable(L, -2);
6452 // Should be a table, which we will use as a prototype
6453 //luaL_checktype(L, -1, LUA_TTABLE);
6454 if(lua_type(L, -1) != LUA_TTABLE){
6455 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6458 int prototype_table = lua_gettop(L);
6459 //dump2(L, "prototype_table");
6461 // Create entity object
6463 int object = lua_gettop(L);
6465 // Set object metatable
6466 lua_pushvalue(L, prototype_table);
6467 lua_setmetatable(L, -2);
6469 // Add object reference
6470 // This should be userdata with metatable ObjectRef
6471 objectref_get(L, id);
6472 luaL_checktype(L, -1, LUA_TUSERDATA);
6473 if(!luaL_checkudata(L, -1, "ObjectRef"))
6474 luaL_typerror(L, -1, "ObjectRef");
6475 lua_setfield(L, -2, "object");
6477 // minetest.luaentities[id] = object
6478 lua_getglobal(L, "minetest");
6479 lua_getfield(L, -1, "luaentities");
6480 luaL_checktype(L, -1, LUA_TTABLE);
6481 lua_pushnumber(L, id); // Push id
6482 lua_pushvalue(L, object); // Copy object to top of stack
6483 lua_settable(L, -3);
6488 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6489 const std::string &staticdata, u32 dtime_s)
6492 assert(lua_checkstack(L, 20));
6493 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6494 StackUnroller stack_unroller(L);
6496 // Get minetest.luaentities[id]
6497 luaentity_get(L, id);
6498 int object = lua_gettop(L);
6500 // Get on_activate function
6501 lua_pushvalue(L, object);
6502 lua_getfield(L, -1, "on_activate");
6503 if(!lua_isnil(L, -1)){
6504 luaL_checktype(L, -1, LUA_TFUNCTION);
6505 lua_pushvalue(L, object); // self
6506 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6507 lua_pushinteger(L, dtime_s);
6508 // Call with 3 arguments, 0 results
6509 if(lua_pcall(L, 3, 0, 0))
6510 script_error(L, "error running function on_activate: %s\n",
6511 lua_tostring(L, -1));
6515 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6518 assert(lua_checkstack(L, 20));
6519 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6521 // Get minetest.luaentities table
6522 lua_getglobal(L, "minetest");
6523 lua_getfield(L, -1, "luaentities");
6524 luaL_checktype(L, -1, LUA_TTABLE);
6525 int objectstable = lua_gettop(L);
6527 // Set luaentities[id] = nil
6528 lua_pushnumber(L, id); // Push id
6530 lua_settable(L, objectstable);
6532 lua_pop(L, 2); // pop luaentities, minetest
6535 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6538 assert(lua_checkstack(L, 20));
6539 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6540 StackUnroller stack_unroller(L);
6542 // Get minetest.luaentities[id]
6543 luaentity_get(L, id);
6544 int object = lua_gettop(L);
6546 // Get get_staticdata function
6547 lua_pushvalue(L, object);
6548 lua_getfield(L, -1, "get_staticdata");
6549 if(lua_isnil(L, -1))
6552 luaL_checktype(L, -1, LUA_TFUNCTION);
6553 lua_pushvalue(L, object); // self
6554 // Call with 1 arguments, 1 results
6555 if(lua_pcall(L, 1, 1, 0))
6556 script_error(L, "error running function get_staticdata: %s\n",
6557 lua_tostring(L, -1));
6560 const char *s = lua_tolstring(L, -1, &len);
6561 return std::string(s, len);
6564 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6565 ObjectProperties *prop)
6568 assert(lua_checkstack(L, 20));
6569 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6570 StackUnroller stack_unroller(L);
6572 // Get minetest.luaentities[id]
6573 luaentity_get(L, id);
6574 //int object = lua_gettop(L);
6576 // Set default values that differ from ObjectProperties defaults
6581 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6583 getboolfield(L, -1, "physical", prop->physical);
6585 getfloatfield(L, -1, "weight", prop->weight);
6587 lua_getfield(L, -1, "collisionbox");
6588 if(lua_istable(L, -1))
6589 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6592 getstringfield(L, -1, "visual", prop->visual);
6594 getstringfield(L, -1, "mesh", prop->mesh);
6596 // Deprecated: read object properties directly
6597 read_object_properties(L, -1, prop);
6599 // Read initial_properties
6600 lua_getfield(L, -1, "initial_properties");
6601 read_object_properties(L, -1, prop);
6605 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6608 assert(lua_checkstack(L, 20));
6609 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6610 StackUnroller stack_unroller(L);
6612 // Get minetest.luaentities[id]
6613 luaentity_get(L, id);
6614 int object = lua_gettop(L);
6615 // State: object is at top of stack
6616 // Get step function
6617 lua_getfield(L, -1, "on_step");
6618 if(lua_isnil(L, -1))
6620 luaL_checktype(L, -1, LUA_TFUNCTION);
6621 lua_pushvalue(L, object); // self
6622 lua_pushnumber(L, dtime); // dtime
6623 // Call with 2 arguments, 0 results
6624 if(lua_pcall(L, 2, 0, 0))
6625 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6628 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6629 // tool_capabilities, direction)
6630 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6631 ServerActiveObject *puncher, float time_from_last_punch,
6632 const ToolCapabilities *toolcap, v3f dir)
6635 assert(lua_checkstack(L, 20));
6636 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6637 StackUnroller stack_unroller(L);
6639 // Get minetest.luaentities[id]
6640 luaentity_get(L, id);
6641 int object = lua_gettop(L);
6642 // State: object is at top of stack
6644 lua_getfield(L, -1, "on_punch");
6645 if(lua_isnil(L, -1))
6647 luaL_checktype(L, -1, LUA_TFUNCTION);
6648 lua_pushvalue(L, object); // self
6649 objectref_get_or_create(L, puncher); // Clicker reference
6650 lua_pushnumber(L, time_from_last_punch);
6651 push_tool_capabilities(L, *toolcap);
6653 // Call with 5 arguments, 0 results
6654 if(lua_pcall(L, 5, 0, 0))
6655 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6658 // Calls entity:on_rightclick(ObjectRef clicker)
6659 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6660 ServerActiveObject *clicker)
6663 assert(lua_checkstack(L, 20));
6664 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6665 StackUnroller stack_unroller(L);
6667 // Get minetest.luaentities[id]
6668 luaentity_get(L, id);
6669 int object = lua_gettop(L);
6670 // State: object is at top of stack
6672 lua_getfield(L, -1, "on_rightclick");
6673 if(lua_isnil(L, -1))
6675 luaL_checktype(L, -1, LUA_TFUNCTION);
6676 lua_pushvalue(L, object); // self
6677 objectref_get_or_create(L, clicker); // Clicker reference
6678 // Call with 2 arguments, 0 results
6679 if(lua_pcall(L, 2, 0, 0))
6680 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));