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, "animation_frames");
948 if(lua_istable(L, -1))
950 lua_rawgeti (L, -1, 1);
951 lua_rawgeti (L, -2, 2);
952 prop->animation_frames.X = lua_tonumber(L, -2);
953 prop->animation_frames.Y = lua_tonumber(L, -1);
958 getfloatfield(L, -1, "animation_speed", prop->animation_speed);
960 getfloatfield(L, -1, "animation_blend", prop->animation_blend);
962 lua_getfield(L, -1, "animation_bone_position");
963 if(lua_istable(L, -1))
965 lua_rawgeti (L, -1, 1);
966 lua_rawgeti (L, -2, 2);
967 std::string bone_name = lua_tostring(L, -2);
968 v3f bone_pos = read_v3f(L, -1);
969 prop->animation_bone_position[bone_name] = bone_pos;
974 lua_getfield(L, -1, "animation_bone_rotation");
975 if(lua_istable(L, -1))
977 lua_rawgeti (L, -1, 1);
978 lua_rawgeti (L, -2, 2);
979 std::string bone_name = lua_tostring(L, -2);
980 v3f bone_rot = read_v3f(L, -1);
981 prop->animation_bone_rotation[bone_name] = bone_rot;
986 lua_getfield(L, -1, "textures");
987 if(lua_istable(L, -1)){
988 prop->textures.clear();
989 int table = lua_gettop(L);
991 while(lua_next(L, table) != 0){
992 // key at index -2 and value at index -1
993 if(lua_isstring(L, -1))
994 prop->textures.push_back(lua_tostring(L, -1));
996 prop->textures.push_back("");
997 // removes value, keeps key for next iteration
1003 lua_getfield(L, -1, "spritediv");
1004 if(lua_istable(L, -1))
1005 prop->spritediv = read_v2s16(L, -1);
1008 lua_getfield(L, -1, "initial_sprite_basepos");
1009 if(lua_istable(L, -1))
1010 prop->initial_sprite_basepos = read_v2s16(L, -1);
1013 getboolfield(L, -1, "is_visible", prop->is_visible);
1014 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
1015 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
1022 static ItemDefinition read_item_definition(lua_State *L, int index,
1023 ItemDefinition default_def = ItemDefinition())
1026 index = lua_gettop(L) + 1 + index;
1028 // Read the item definition
1029 ItemDefinition def = default_def;
1031 def.type = (ItemType)getenumfield(L, index, "type",
1032 es_ItemType, ITEM_NONE);
1033 getstringfield(L, index, "name", def.name);
1034 getstringfield(L, index, "description", def.description);
1035 getstringfield(L, index, "inventory_image", def.inventory_image);
1036 getstringfield(L, index, "wield_image", def.wield_image);
1038 lua_getfield(L, index, "wield_scale");
1039 if(lua_istable(L, -1)){
1040 def.wield_scale = check_v3f(L, -1);
1044 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1045 if(def.stack_max == 0)
1048 lua_getfield(L, index, "on_use");
1049 def.usable = lua_isfunction(L, -1);
1052 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1054 warn_if_field_exists(L, index, "tool_digging_properties",
1055 "deprecated: use tool_capabilities");
1057 lua_getfield(L, index, "tool_capabilities");
1058 if(lua_istable(L, -1)){
1059 def.tool_capabilities = new ToolCapabilities(
1060 read_tool_capabilities(L, -1));
1063 // If name is "" (hand), ensure there are ToolCapabilities
1064 // because it will be looked up there whenever any other item has
1065 // no ToolCapabilities
1066 if(def.name == "" && def.tool_capabilities == NULL){
1067 def.tool_capabilities = new ToolCapabilities();
1070 lua_getfield(L, index, "groups");
1071 read_groups(L, -1, def.groups);
1074 // Client shall immediately place this node when player places the item.
1075 // Server will update the precise end result a moment later.
1076 // "" = no prediction
1077 getstringfield(L, index, "node_placement_prediction",
1078 def.node_placement_prediction);
1087 static TileDef read_tiledef(lua_State *L, int index)
1090 index = lua_gettop(L) + 1 + index;
1094 // key at index -2 and value at index
1095 if(lua_isstring(L, index)){
1096 // "default_lava.png"
1097 tiledef.name = lua_tostring(L, index);
1099 else if(lua_istable(L, index))
1101 // {name="default_lava.png", animation={}}
1103 getstringfield(L, index, "name", tiledef.name);
1104 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1105 tiledef.backface_culling = getboolfield_default(
1106 L, index, "backface_culling", true);
1108 lua_getfield(L, index, "animation");
1109 if(lua_istable(L, -1)){
1110 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1111 tiledef.animation.type = (TileAnimationType)
1112 getenumfield(L, -1, "type", es_TileAnimationType,
1114 tiledef.animation.aspect_w =
1115 getintfield_default(L, -1, "aspect_w", 16);
1116 tiledef.animation.aspect_h =
1117 getintfield_default(L, -1, "aspect_h", 16);
1118 tiledef.animation.length =
1119 getfloatfield_default(L, -1, "length", 1.0);
1131 static ContentFeatures read_content_features(lua_State *L, int index)
1134 index = lua_gettop(L) + 1 + index;
1138 /* Cache existence of some callbacks */
1139 lua_getfield(L, index, "on_construct");
1140 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1142 lua_getfield(L, index, "on_destruct");
1143 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1145 lua_getfield(L, index, "after_destruct");
1146 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1150 getstringfield(L, index, "name", f.name);
1153 lua_getfield(L, index, "groups");
1154 read_groups(L, -1, f.groups);
1157 /* Visual definition */
1159 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1161 getfloatfield(L, index, "visual_scale", f.visual_scale);
1164 lua_getfield(L, index, "tiles");
1165 // If nil, try the deprecated name "tile_images" instead
1166 if(lua_isnil(L, -1)){
1168 warn_if_field_exists(L, index, "tile_images",
1169 "Deprecated; new name is \"tiles\".");
1170 lua_getfield(L, index, "tile_images");
1172 if(lua_istable(L, -1)){
1173 int table = lua_gettop(L);
1176 while(lua_next(L, table) != 0){
1177 // Read tiledef from value
1178 f.tiledef[i] = read_tiledef(L, -1);
1179 // removes value, keeps key for next iteration
1187 // Copy last value to all remaining textures
1189 TileDef lasttile = f.tiledef[i-1];
1191 f.tiledef[i] = lasttile;
1198 // special_tiles = {}
1199 lua_getfield(L, index, "special_tiles");
1200 // If nil, try the deprecated name "special_materials" instead
1201 if(lua_isnil(L, -1)){
1203 warn_if_field_exists(L, index, "special_materials",
1204 "Deprecated; new name is \"special_tiles\".");
1205 lua_getfield(L, index, "special_materials");
1207 if(lua_istable(L, -1)){
1208 int table = lua_gettop(L);
1211 while(lua_next(L, table) != 0){
1212 // Read tiledef from value
1213 f.tiledef_special[i] = read_tiledef(L, -1);
1214 // removes value, keeps key for next iteration
1225 f.alpha = getintfield_default(L, index, "alpha", 255);
1229 lua_getfield(L, index, "post_effect_color");
1230 if(!lua_isnil(L, -1))
1231 f.post_effect_color = readARGB8(L, -1);
1234 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1235 es_ContentParamType, CPT_NONE);
1236 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1237 es_ContentParamType2, CPT2_NONE);
1239 // Warn about some deprecated fields
1240 warn_if_field_exists(L, index, "wall_mounted",
1241 "deprecated: use paramtype2 = 'wallmounted'");
1242 warn_if_field_exists(L, index, "light_propagates",
1243 "deprecated: determined from paramtype");
1244 warn_if_field_exists(L, index, "dug_item",
1245 "deprecated: use 'drop' field");
1246 warn_if_field_exists(L, index, "extra_dug_item",
1247 "deprecated: use 'drop' field");
1248 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1249 "deprecated: use 'drop' field");
1250 warn_if_field_exists(L, index, "metadata_name",
1251 "deprecated: use on_add and metadata callbacks");
1253 // True for all ground-like things like stone and mud, false for eg. trees
1254 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1255 f.light_propagates = (f.param_type == CPT_LIGHT);
1256 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1257 // This is used for collision detection.
1258 // Also for general solidness queries.
1259 getboolfield(L, index, "walkable", f.walkable);
1260 // Player can point to these
1261 getboolfield(L, index, "pointable", f.pointable);
1262 // Player can dig these
1263 getboolfield(L, index, "diggable", f.diggable);
1264 // Player can climb these
1265 getboolfield(L, index, "climbable", f.climbable);
1266 // Player can build on these
1267 getboolfield(L, index, "buildable_to", f.buildable_to);
1268 // Whether the node is non-liquid, source liquid or flowing liquid
1269 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1270 es_LiquidType, LIQUID_NONE);
1271 // If the content is liquid, this is the flowing version of the liquid.
1272 getstringfield(L, index, "liquid_alternative_flowing",
1273 f.liquid_alternative_flowing);
1274 // If the content is liquid, this is the source version of the liquid.
1275 getstringfield(L, index, "liquid_alternative_source",
1276 f.liquid_alternative_source);
1277 // Viscosity for fluid flow, ranging from 1 to 7, with
1278 // 1 giving almost instantaneous propagation and 7 being
1279 // the slowest possible
1280 f.liquid_viscosity = getintfield_default(L, index,
1281 "liquid_viscosity", f.liquid_viscosity);
1282 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1283 // Amount of light the node emits
1284 f.light_source = getintfield_default(L, index,
1285 "light_source", f.light_source);
1286 f.damage_per_second = getintfield_default(L, index,
1287 "damage_per_second", f.damage_per_second);
1289 lua_getfield(L, index, "node_box");
1290 if(lua_istable(L, -1))
1291 f.node_box = read_nodebox(L, -1);
1294 lua_getfield(L, index, "selection_box");
1295 if(lua_istable(L, -1))
1296 f.selection_box = read_nodebox(L, -1);
1299 // Set to true if paramtype used to be 'facedir_simple'
1300 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1301 // Set to true if wall_mounted used to be set to true
1302 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1305 lua_getfield(L, index, "sounds");
1306 if(lua_istable(L, -1)){
1307 lua_getfield(L, -1, "footstep");
1308 read_soundspec(L, -1, f.sound_footstep);
1310 lua_getfield(L, -1, "dig");
1311 read_soundspec(L, -1, f.sound_dig);
1313 lua_getfield(L, -1, "dug");
1314 read_soundspec(L, -1, f.sound_dug);
1326 static ItemStack read_item(lua_State *L, int index);
1327 static std::vector<ItemStack> read_items(lua_State *L, int index);
1328 // creates a table of ItemStacks
1329 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1331 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1332 lua_State *L, int tableindex, int forcesize=-1)
1335 tableindex = lua_gettop(L) + 1 + tableindex;
1336 // If nil, delete list
1337 if(lua_isnil(L, tableindex)){
1338 inv->deleteList(name);
1341 // Otherwise set list
1342 std::vector<ItemStack> items = read_items(L, tableindex);
1343 int listsize = (forcesize != -1) ? forcesize : items.size();
1344 InventoryList *invlist = inv->addList(name, listsize);
1346 for(std::vector<ItemStack>::const_iterator
1347 i = items.begin(); i != items.end(); i++){
1348 if(forcesize != -1 && index == forcesize)
1350 invlist->changeItem(index, *i);
1353 while(forcesize != -1 && index < forcesize){
1354 invlist->deleteItem(index);
1359 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1362 InventoryList *invlist = inv->getList(name);
1363 if(invlist == NULL){
1367 std::vector<ItemStack> items;
1368 for(u32 i=0; i<invlist->getSize(); i++)
1369 items.push_back(invlist->getItem(i));
1370 push_items(L, items);
1374 Helpful macros for userdata classes
1377 #define method(class, name) {#name, class::l_##name}
1388 static const char className[];
1389 static const luaL_reg methods[];
1391 // Exported functions
1393 // garbage collector
1394 static int gc_object(lua_State *L)
1396 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1401 // is_empty(self) -> true/false
1402 static int l_is_empty(lua_State *L)
1404 LuaItemStack *o = checkobject(L, 1);
1405 ItemStack &item = o->m_stack;
1406 lua_pushboolean(L, item.empty());
1410 // get_name(self) -> string
1411 static int l_get_name(lua_State *L)
1413 LuaItemStack *o = checkobject(L, 1);
1414 ItemStack &item = o->m_stack;
1415 lua_pushstring(L, item.name.c_str());
1419 // get_count(self) -> number
1420 static int l_get_count(lua_State *L)
1422 LuaItemStack *o = checkobject(L, 1);
1423 ItemStack &item = o->m_stack;
1424 lua_pushinteger(L, item.count);
1428 // get_wear(self) -> number
1429 static int l_get_wear(lua_State *L)
1431 LuaItemStack *o = checkobject(L, 1);
1432 ItemStack &item = o->m_stack;
1433 lua_pushinteger(L, item.wear);
1437 // get_metadata(self) -> string
1438 static int l_get_metadata(lua_State *L)
1440 LuaItemStack *o = checkobject(L, 1);
1441 ItemStack &item = o->m_stack;
1442 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1446 // clear(self) -> true
1447 static int l_clear(lua_State *L)
1449 LuaItemStack *o = checkobject(L, 1);
1451 lua_pushboolean(L, true);
1455 // replace(self, itemstack or itemstring or table or nil) -> true
1456 static int l_replace(lua_State *L)
1458 LuaItemStack *o = checkobject(L, 1);
1459 o->m_stack = read_item(L, 2);
1460 lua_pushboolean(L, true);
1464 // to_string(self) -> string
1465 static int l_to_string(lua_State *L)
1467 LuaItemStack *o = checkobject(L, 1);
1468 std::string itemstring = o->m_stack.getItemString();
1469 lua_pushstring(L, itemstring.c_str());
1473 // to_table(self) -> table or nil
1474 static int l_to_table(lua_State *L)
1476 LuaItemStack *o = checkobject(L, 1);
1477 const ItemStack &item = o->m_stack;
1485 lua_pushstring(L, item.name.c_str());
1486 lua_setfield(L, -2, "name");
1487 lua_pushinteger(L, item.count);
1488 lua_setfield(L, -2, "count");
1489 lua_pushinteger(L, item.wear);
1490 lua_setfield(L, -2, "wear");
1491 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1492 lua_setfield(L, -2, "metadata");
1497 // get_stack_max(self) -> number
1498 static int l_get_stack_max(lua_State *L)
1500 LuaItemStack *o = checkobject(L, 1);
1501 ItemStack &item = o->m_stack;
1502 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1506 // get_free_space(self) -> number
1507 static int l_get_free_space(lua_State *L)
1509 LuaItemStack *o = checkobject(L, 1);
1510 ItemStack &item = o->m_stack;
1511 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1515 // is_known(self) -> true/false
1516 // Checks if the item is defined.
1517 static int l_is_known(lua_State *L)
1519 LuaItemStack *o = checkobject(L, 1);
1520 ItemStack &item = o->m_stack;
1521 bool is_known = item.isKnown(get_server(L)->idef());
1522 lua_pushboolean(L, is_known);
1526 // get_definition(self) -> table
1527 // Returns the item definition table from minetest.registered_items,
1528 // or a fallback one (name="unknown")
1529 static int l_get_definition(lua_State *L)
1531 LuaItemStack *o = checkobject(L, 1);
1532 ItemStack &item = o->m_stack;
1534 // Get minetest.registered_items[name]
1535 lua_getglobal(L, "minetest");
1536 lua_getfield(L, -1, "registered_items");
1537 luaL_checktype(L, -1, LUA_TTABLE);
1538 lua_getfield(L, -1, item.name.c_str());
1539 if(lua_isnil(L, -1))
1542 lua_getfield(L, -1, "unknown");
1547 // get_tool_capabilities(self) -> table
1548 // Returns the effective tool digging properties.
1549 // Returns those of the hand ("") if this item has none associated.
1550 static int l_get_tool_capabilities(lua_State *L)
1552 LuaItemStack *o = checkobject(L, 1);
1553 ItemStack &item = o->m_stack;
1554 const ToolCapabilities &prop =
1555 item.getToolCapabilities(get_server(L)->idef());
1556 push_tool_capabilities(L, prop);
1560 // add_wear(self, amount) -> true/false
1561 // The range for "amount" is [0,65535]. Wear is only added if the item
1562 // is a tool. Adding wear might destroy the item.
1563 // Returns true if the item is (or was) a tool.
1564 static int l_add_wear(lua_State *L)
1566 LuaItemStack *o = checkobject(L, 1);
1567 ItemStack &item = o->m_stack;
1568 int amount = lua_tointeger(L, 2);
1569 bool result = item.addWear(amount, get_server(L)->idef());
1570 lua_pushboolean(L, result);
1574 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1575 // Returns leftover item stack
1576 static int l_add_item(lua_State *L)
1578 LuaItemStack *o = checkobject(L, 1);
1579 ItemStack &item = o->m_stack;
1580 ItemStack newitem = read_item(L, 2);
1581 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1582 create(L, leftover);
1586 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1587 // First return value is true iff the new item fits fully into the stack
1588 // Second return value is the would-be-left-over item stack
1589 static int l_item_fits(lua_State *L)
1591 LuaItemStack *o = checkobject(L, 1);
1592 ItemStack &item = o->m_stack;
1593 ItemStack newitem = read_item(L, 2);
1595 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1596 lua_pushboolean(L, fits); // first return value
1597 create(L, restitem); // second return value
1601 // take_item(self, takecount=1) -> itemstack
1602 static int l_take_item(lua_State *L)
1604 LuaItemStack *o = checkobject(L, 1);
1605 ItemStack &item = o->m_stack;
1607 if(!lua_isnone(L, 2))
1608 takecount = luaL_checkinteger(L, 2);
1609 ItemStack taken = item.takeItem(takecount);
1614 // peek_item(self, peekcount=1) -> itemstack
1615 static int l_peek_item(lua_State *L)
1617 LuaItemStack *o = checkobject(L, 1);
1618 ItemStack &item = o->m_stack;
1620 if(!lua_isnone(L, 2))
1621 peekcount = lua_tointeger(L, 2);
1622 ItemStack peekaboo = item.peekItem(peekcount);
1623 create(L, peekaboo);
1628 LuaItemStack(const ItemStack &item):
1637 const ItemStack& getItem() const
1641 ItemStack& getItem()
1646 // LuaItemStack(itemstack or itemstring or table or nil)
1647 // Creates an LuaItemStack and leaves it on top of stack
1648 static int create_object(lua_State *L)
1650 ItemStack item = read_item(L, 1);
1651 LuaItemStack *o = new LuaItemStack(item);
1652 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1653 luaL_getmetatable(L, className);
1654 lua_setmetatable(L, -2);
1657 // Not callable from Lua
1658 static int create(lua_State *L, const ItemStack &item)
1660 LuaItemStack *o = new LuaItemStack(item);
1661 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1662 luaL_getmetatable(L, className);
1663 lua_setmetatable(L, -2);
1667 static LuaItemStack* checkobject(lua_State *L, int narg)
1669 luaL_checktype(L, narg, LUA_TUSERDATA);
1670 void *ud = luaL_checkudata(L, narg, className);
1671 if(!ud) luaL_typerror(L, narg, className);
1672 return *(LuaItemStack**)ud; // unbox pointer
1675 static void Register(lua_State *L)
1678 int methodtable = lua_gettop(L);
1679 luaL_newmetatable(L, className);
1680 int metatable = lua_gettop(L);
1682 lua_pushliteral(L, "__metatable");
1683 lua_pushvalue(L, methodtable);
1684 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1686 lua_pushliteral(L, "__index");
1687 lua_pushvalue(L, methodtable);
1688 lua_settable(L, metatable);
1690 lua_pushliteral(L, "__gc");
1691 lua_pushcfunction(L, gc_object);
1692 lua_settable(L, metatable);
1694 lua_pop(L, 1); // drop metatable
1696 luaL_openlib(L, 0, methods, 0); // fill methodtable
1697 lua_pop(L, 1); // drop methodtable
1699 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1700 lua_register(L, className, create_object);
1703 const char LuaItemStack::className[] = "ItemStack";
1704 const luaL_reg LuaItemStack::methods[] = {
1705 method(LuaItemStack, is_empty),
1706 method(LuaItemStack, get_name),
1707 method(LuaItemStack, get_count),
1708 method(LuaItemStack, get_wear),
1709 method(LuaItemStack, get_metadata),
1710 method(LuaItemStack, clear),
1711 method(LuaItemStack, replace),
1712 method(LuaItemStack, to_string),
1713 method(LuaItemStack, to_table),
1714 method(LuaItemStack, get_stack_max),
1715 method(LuaItemStack, get_free_space),
1716 method(LuaItemStack, is_known),
1717 method(LuaItemStack, get_definition),
1718 method(LuaItemStack, get_tool_capabilities),
1719 method(LuaItemStack, add_wear),
1720 method(LuaItemStack, add_item),
1721 method(LuaItemStack, item_fits),
1722 method(LuaItemStack, take_item),
1723 method(LuaItemStack, peek_item),
1727 static ItemStack read_item(lua_State *L, int index)
1730 index = lua_gettop(L) + 1 + index;
1732 if(lua_isnil(L, index))
1736 else if(lua_isuserdata(L, index))
1738 // Convert from LuaItemStack
1739 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1740 return o->getItem();
1742 else if(lua_isstring(L, index))
1744 // Convert from itemstring
1745 std::string itemstring = lua_tostring(L, index);
1746 IItemDefManager *idef = get_server(L)->idef();
1750 item.deSerialize(itemstring, idef);
1753 catch(SerializationError &e)
1755 infostream<<"WARNING: unable to create item from itemstring"
1756 <<": "<<itemstring<<std::endl;
1760 else if(lua_istable(L, index))
1762 // Convert from table
1763 IItemDefManager *idef = get_server(L)->idef();
1764 std::string name = getstringfield_default(L, index, "name", "");
1765 int count = getintfield_default(L, index, "count", 1);
1766 int wear = getintfield_default(L, index, "wear", 0);
1767 std::string metadata = getstringfield_default(L, index, "metadata", "");
1768 return ItemStack(name, count, wear, metadata, idef);
1772 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1776 static std::vector<ItemStack> read_items(lua_State *L, int index)
1779 index = lua_gettop(L) + 1 + index;
1781 std::vector<ItemStack> items;
1782 luaL_checktype(L, index, LUA_TTABLE);
1784 while(lua_next(L, index) != 0){
1785 // key at index -2 and value at index -1
1786 items.push_back(read_item(L, -1));
1787 // removes value, keeps key for next iteration
1793 // creates a table of ItemStacks
1794 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1796 // Get the table insert function
1797 lua_getglobal(L, "table");
1798 lua_getfield(L, -1, "insert");
1799 int table_insert = lua_gettop(L);
1800 // Create and fill table
1802 int table = lua_gettop(L);
1803 for(u32 i=0; i<items.size(); i++){
1804 ItemStack item = items[i];
1805 lua_pushvalue(L, table_insert);
1806 lua_pushvalue(L, table);
1807 LuaItemStack::create(L, item);
1808 if(lua_pcall(L, 2, 0, 0))
1809 script_error(L, "error: %s", lua_tostring(L, -1));
1811 lua_remove(L, -2); // Remove table
1812 lua_remove(L, -2); // Remove insert
1822 InventoryLocation m_loc;
1824 static const char className[];
1825 static const luaL_reg methods[];
1827 static InvRef *checkobject(lua_State *L, int narg)
1829 luaL_checktype(L, narg, LUA_TUSERDATA);
1830 void *ud = luaL_checkudata(L, narg, className);
1831 if(!ud) luaL_typerror(L, narg, className);
1832 return *(InvRef**)ud; // unbox pointer
1835 static Inventory* getinv(lua_State *L, InvRef *ref)
1837 return get_server(L)->getInventory(ref->m_loc);
1840 static InventoryList* getlist(lua_State *L, InvRef *ref,
1841 const char *listname)
1843 Inventory *inv = getinv(L, ref);
1846 return inv->getList(listname);
1849 static void reportInventoryChange(lua_State *L, InvRef *ref)
1851 // Inform other things that the inventory has changed
1852 get_server(L)->setInventoryModified(ref->m_loc);
1855 // Exported functions
1857 // garbage collector
1858 static int gc_object(lua_State *L) {
1859 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1864 // is_empty(self, listname) -> true/false
1865 static int l_is_empty(lua_State *L)
1867 InvRef *ref = checkobject(L, 1);
1868 const char *listname = luaL_checkstring(L, 2);
1869 InventoryList *list = getlist(L, ref, listname);
1870 if(list && list->getUsedSlots() > 0){
1871 lua_pushboolean(L, false);
1873 lua_pushboolean(L, true);
1878 // get_size(self, listname)
1879 static int l_get_size(lua_State *L)
1881 InvRef *ref = checkobject(L, 1);
1882 const char *listname = luaL_checkstring(L, 2);
1883 InventoryList *list = getlist(L, ref, listname);
1885 lua_pushinteger(L, list->getSize());
1887 lua_pushinteger(L, 0);
1892 // get_width(self, listname)
1893 static int l_get_width(lua_State *L)
1895 InvRef *ref = checkobject(L, 1);
1896 const char *listname = luaL_checkstring(L, 2);
1897 InventoryList *list = getlist(L, ref, listname);
1899 lua_pushinteger(L, list->getWidth());
1901 lua_pushinteger(L, 0);
1906 // set_size(self, listname, size)
1907 static int l_set_size(lua_State *L)
1909 InvRef *ref = checkobject(L, 1);
1910 const char *listname = luaL_checkstring(L, 2);
1911 int newsize = luaL_checknumber(L, 3);
1912 Inventory *inv = getinv(L, ref);
1914 inv->deleteList(listname);
1915 reportInventoryChange(L, ref);
1918 InventoryList *list = inv->getList(listname);
1920 list->setSize(newsize);
1922 list = inv->addList(listname, newsize);
1924 reportInventoryChange(L, ref);
1928 // set_width(self, listname, size)
1929 static int l_set_width(lua_State *L)
1931 InvRef *ref = checkobject(L, 1);
1932 const char *listname = luaL_checkstring(L, 2);
1933 int newwidth = luaL_checknumber(L, 3);
1934 Inventory *inv = getinv(L, ref);
1935 InventoryList *list = inv->getList(listname);
1937 list->setWidth(newwidth);
1941 reportInventoryChange(L, ref);
1945 // get_stack(self, listname, i) -> itemstack
1946 static int l_get_stack(lua_State *L)
1948 InvRef *ref = checkobject(L, 1);
1949 const char *listname = luaL_checkstring(L, 2);
1950 int i = luaL_checknumber(L, 3) - 1;
1951 InventoryList *list = getlist(L, ref, listname);
1953 if(list != NULL && i >= 0 && i < (int) list->getSize())
1954 item = list->getItem(i);
1955 LuaItemStack::create(L, item);
1959 // set_stack(self, listname, i, stack) -> true/false
1960 static int l_set_stack(lua_State *L)
1962 InvRef *ref = checkobject(L, 1);
1963 const char *listname = luaL_checkstring(L, 2);
1964 int i = luaL_checknumber(L, 3) - 1;
1965 ItemStack newitem = read_item(L, 4);
1966 InventoryList *list = getlist(L, ref, listname);
1967 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1968 list->changeItem(i, newitem);
1969 reportInventoryChange(L, ref);
1970 lua_pushboolean(L, true);
1972 lua_pushboolean(L, false);
1977 // get_list(self, listname) -> list or nil
1978 static int l_get_list(lua_State *L)
1980 InvRef *ref = checkobject(L, 1);
1981 const char *listname = luaL_checkstring(L, 2);
1982 Inventory *inv = getinv(L, ref);
1983 inventory_get_list_to_lua(inv, listname, L);
1987 // set_list(self, listname, list)
1988 static int l_set_list(lua_State *L)
1990 InvRef *ref = checkobject(L, 1);
1991 const char *listname = luaL_checkstring(L, 2);
1992 Inventory *inv = getinv(L, ref);
1993 InventoryList *list = inv->getList(listname);
1995 inventory_set_list_from_lua(inv, listname, L, 3,
1998 inventory_set_list_from_lua(inv, listname, L, 3);
1999 reportInventoryChange(L, ref);
2003 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2004 // Returns the leftover stack
2005 static int l_add_item(lua_State *L)
2007 InvRef *ref = checkobject(L, 1);
2008 const char *listname = luaL_checkstring(L, 2);
2009 ItemStack item = read_item(L, 3);
2010 InventoryList *list = getlist(L, ref, listname);
2012 ItemStack leftover = list->addItem(item);
2013 if(leftover.count != item.count)
2014 reportInventoryChange(L, ref);
2015 LuaItemStack::create(L, leftover);
2017 LuaItemStack::create(L, item);
2022 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2023 // Returns true if the item completely fits into the list
2024 static int l_room_for_item(lua_State *L)
2026 InvRef *ref = checkobject(L, 1);
2027 const char *listname = luaL_checkstring(L, 2);
2028 ItemStack item = read_item(L, 3);
2029 InventoryList *list = getlist(L, ref, listname);
2031 lua_pushboolean(L, list->roomForItem(item));
2033 lua_pushboolean(L, false);
2038 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2039 // Returns true if the list contains the given count of the given item name
2040 static int l_contains_item(lua_State *L)
2042 InvRef *ref = checkobject(L, 1);
2043 const char *listname = luaL_checkstring(L, 2);
2044 ItemStack item = read_item(L, 3);
2045 InventoryList *list = getlist(L, ref, listname);
2047 lua_pushboolean(L, list->containsItem(item));
2049 lua_pushboolean(L, false);
2054 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2055 // Returns the items that were actually removed
2056 static int l_remove_item(lua_State *L)
2058 InvRef *ref = checkobject(L, 1);
2059 const char *listname = luaL_checkstring(L, 2);
2060 ItemStack item = read_item(L, 3);
2061 InventoryList *list = getlist(L, ref, listname);
2063 ItemStack removed = list->removeItem(item);
2064 if(!removed.empty())
2065 reportInventoryChange(L, ref);
2066 LuaItemStack::create(L, removed);
2068 LuaItemStack::create(L, ItemStack());
2074 InvRef(const InventoryLocation &loc):
2083 // Creates an InvRef and leaves it on top of stack
2084 // Not callable from Lua; all references are created on the C side.
2085 static void create(lua_State *L, const InventoryLocation &loc)
2087 InvRef *o = new InvRef(loc);
2088 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2089 luaL_getmetatable(L, className);
2090 lua_setmetatable(L, -2);
2092 static void createPlayer(lua_State *L, Player *player)
2094 InventoryLocation loc;
2095 loc.setPlayer(player->getName());
2098 static void createNodeMeta(lua_State *L, v3s16 p)
2100 InventoryLocation loc;
2105 static void Register(lua_State *L)
2108 int methodtable = lua_gettop(L);
2109 luaL_newmetatable(L, className);
2110 int metatable = lua_gettop(L);
2112 lua_pushliteral(L, "__metatable");
2113 lua_pushvalue(L, methodtable);
2114 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2116 lua_pushliteral(L, "__index");
2117 lua_pushvalue(L, methodtable);
2118 lua_settable(L, metatable);
2120 lua_pushliteral(L, "__gc");
2121 lua_pushcfunction(L, gc_object);
2122 lua_settable(L, metatable);
2124 lua_pop(L, 1); // drop metatable
2126 luaL_openlib(L, 0, methods, 0); // fill methodtable
2127 lua_pop(L, 1); // drop methodtable
2129 // Cannot be created from Lua
2130 //lua_register(L, className, create_object);
2133 const char InvRef::className[] = "InvRef";
2134 const luaL_reg InvRef::methods[] = {
2135 method(InvRef, is_empty),
2136 method(InvRef, get_size),
2137 method(InvRef, set_size),
2138 method(InvRef, get_width),
2139 method(InvRef, set_width),
2140 method(InvRef, get_stack),
2141 method(InvRef, set_stack),
2142 method(InvRef, get_list),
2143 method(InvRef, set_list),
2144 method(InvRef, add_item),
2145 method(InvRef, room_for_item),
2146 method(InvRef, contains_item),
2147 method(InvRef, remove_item),
2159 ServerEnvironment *m_env;
2161 static const char className[];
2162 static const luaL_reg methods[];
2164 static NodeMetaRef *checkobject(lua_State *L, int narg)
2166 luaL_checktype(L, narg, LUA_TUSERDATA);
2167 void *ud = luaL_checkudata(L, narg, className);
2168 if(!ud) luaL_typerror(L, narg, className);
2169 return *(NodeMetaRef**)ud; // unbox pointer
2172 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2174 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2175 if(meta == NULL && auto_create)
2177 meta = new NodeMetadata(ref->m_env->getGameDef());
2178 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2183 static void reportMetadataChange(NodeMetaRef *ref)
2185 // NOTE: This same code is in rollback_interface.cpp
2186 // Inform other things that the metadata has changed
2187 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2189 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2191 ref->m_env->getMap().dispatchEvent(&event);
2192 // Set the block to be saved
2193 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2195 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2196 "NodeMetaRef::reportMetadataChange");
2199 // Exported functions
2201 // garbage collector
2202 static int gc_object(lua_State *L) {
2203 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2208 // get_string(self, name)
2209 static int l_get_string(lua_State *L)
2211 NodeMetaRef *ref = checkobject(L, 1);
2212 std::string name = luaL_checkstring(L, 2);
2214 NodeMetadata *meta = getmeta(ref, false);
2216 lua_pushlstring(L, "", 0);
2219 std::string str = meta->getString(name);
2220 lua_pushlstring(L, str.c_str(), str.size());
2224 // set_string(self, name, var)
2225 static int l_set_string(lua_State *L)
2227 NodeMetaRef *ref = checkobject(L, 1);
2228 std::string name = luaL_checkstring(L, 2);
2230 const char *s = lua_tolstring(L, 3, &len);
2231 std::string str(s, len);
2233 NodeMetadata *meta = getmeta(ref, !str.empty());
2234 if(meta == NULL || str == meta->getString(name))
2236 meta->setString(name, str);
2237 reportMetadataChange(ref);
2241 // get_int(self, name)
2242 static int l_get_int(lua_State *L)
2244 NodeMetaRef *ref = checkobject(L, 1);
2245 std::string name = lua_tostring(L, 2);
2247 NodeMetadata *meta = getmeta(ref, false);
2249 lua_pushnumber(L, 0);
2252 std::string str = meta->getString(name);
2253 lua_pushnumber(L, stoi(str));
2257 // set_int(self, name, var)
2258 static int l_set_int(lua_State *L)
2260 NodeMetaRef *ref = checkobject(L, 1);
2261 std::string name = lua_tostring(L, 2);
2262 int a = lua_tointeger(L, 3);
2263 std::string str = itos(a);
2265 NodeMetadata *meta = getmeta(ref, true);
2266 if(meta == NULL || str == meta->getString(name))
2268 meta->setString(name, str);
2269 reportMetadataChange(ref);
2273 // get_float(self, name)
2274 static int l_get_float(lua_State *L)
2276 NodeMetaRef *ref = checkobject(L, 1);
2277 std::string name = lua_tostring(L, 2);
2279 NodeMetadata *meta = getmeta(ref, false);
2281 lua_pushnumber(L, 0);
2284 std::string str = meta->getString(name);
2285 lua_pushnumber(L, stof(str));
2289 // set_float(self, name, var)
2290 static int l_set_float(lua_State *L)
2292 NodeMetaRef *ref = checkobject(L, 1);
2293 std::string name = lua_tostring(L, 2);
2294 float a = lua_tonumber(L, 3);
2295 std::string str = ftos(a);
2297 NodeMetadata *meta = getmeta(ref, true);
2298 if(meta == NULL || str == meta->getString(name))
2300 meta->setString(name, str);
2301 reportMetadataChange(ref);
2305 // get_inventory(self)
2306 static int l_get_inventory(lua_State *L)
2308 NodeMetaRef *ref = checkobject(L, 1);
2309 getmeta(ref, true); // try to ensure the metadata exists
2310 InvRef::createNodeMeta(L, ref->m_p);
2315 static int l_to_table(lua_State *L)
2317 NodeMetaRef *ref = checkobject(L, 1);
2319 NodeMetadata *meta = getmeta(ref, true);
2328 std::map<std::string, std::string> fields = meta->getStrings();
2329 for(std::map<std::string, std::string>::const_iterator
2330 i = fields.begin(); i != fields.end(); i++){
2331 const std::string &name = i->first;
2332 const std::string &value = i->second;
2333 lua_pushlstring(L, name.c_str(), name.size());
2334 lua_pushlstring(L, value.c_str(), value.size());
2335 lua_settable(L, -3);
2338 lua_setfield(L, -2, "fields");
2341 Inventory *inv = meta->getInventory();
2343 std::vector<const InventoryList*> lists = inv->getLists();
2344 for(std::vector<const InventoryList*>::const_iterator
2345 i = lists.begin(); i != lists.end(); i++){
2346 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2347 lua_setfield(L, -2, (*i)->getName().c_str());
2350 lua_setfield(L, -2, "inventory");
2354 // from_table(self, table)
2355 static int l_from_table(lua_State *L)
2357 NodeMetaRef *ref = checkobject(L, 1);
2360 if(lua_isnil(L, base)){
2362 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2363 lua_pushboolean(L, true);
2367 // Has metadata; clear old one first
2368 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2369 // Create new metadata
2370 NodeMetadata *meta = getmeta(ref, true);
2372 lua_getfield(L, base, "fields");
2373 int fieldstable = lua_gettop(L);
2375 while(lua_next(L, fieldstable) != 0){
2376 // key at index -2 and value at index -1
2377 std::string name = lua_tostring(L, -2);
2379 const char *cs = lua_tolstring(L, -1, &cl);
2380 std::string value(cs, cl);
2381 meta->setString(name, value);
2382 lua_pop(L, 1); // removes value, keeps key for next iteration
2385 Inventory *inv = meta->getInventory();
2386 lua_getfield(L, base, "inventory");
2387 int inventorytable = lua_gettop(L);
2389 while(lua_next(L, inventorytable) != 0){
2390 // key at index -2 and value at index -1
2391 std::string name = lua_tostring(L, -2);
2392 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2393 lua_pop(L, 1); // removes value, keeps key for next iteration
2395 reportMetadataChange(ref);
2396 lua_pushboolean(L, true);
2401 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2411 // Creates an NodeMetaRef and leaves it on top of stack
2412 // Not callable from Lua; all references are created on the C side.
2413 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2415 NodeMetaRef *o = new NodeMetaRef(p, env);
2416 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2417 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2418 luaL_getmetatable(L, className);
2419 lua_setmetatable(L, -2);
2422 static void Register(lua_State *L)
2425 int methodtable = lua_gettop(L);
2426 luaL_newmetatable(L, className);
2427 int metatable = lua_gettop(L);
2429 lua_pushliteral(L, "__metatable");
2430 lua_pushvalue(L, methodtable);
2431 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2433 lua_pushliteral(L, "__index");
2434 lua_pushvalue(L, methodtable);
2435 lua_settable(L, metatable);
2437 lua_pushliteral(L, "__gc");
2438 lua_pushcfunction(L, gc_object);
2439 lua_settable(L, metatable);
2441 lua_pop(L, 1); // drop metatable
2443 luaL_openlib(L, 0, methods, 0); // fill methodtable
2444 lua_pop(L, 1); // drop methodtable
2446 // Cannot be created from Lua
2447 //lua_register(L, className, create_object);
2450 const char NodeMetaRef::className[] = "NodeMetaRef";
2451 const luaL_reg NodeMetaRef::methods[] = {
2452 method(NodeMetaRef, get_string),
2453 method(NodeMetaRef, set_string),
2454 method(NodeMetaRef, get_int),
2455 method(NodeMetaRef, set_int),
2456 method(NodeMetaRef, get_float),
2457 method(NodeMetaRef, set_float),
2458 method(NodeMetaRef, get_inventory),
2459 method(NodeMetaRef, to_table),
2460 method(NodeMetaRef, from_table),
2471 ServerActiveObject *m_object;
2473 static const char className[];
2474 static const luaL_reg methods[];
2476 static ObjectRef *checkobject(lua_State *L, int narg)
2478 luaL_checktype(L, narg, LUA_TUSERDATA);
2479 void *ud = luaL_checkudata(L, narg, className);
2480 if(!ud) luaL_typerror(L, narg, className);
2481 return *(ObjectRef**)ud; // unbox pointer
2484 static ServerActiveObject* getobject(ObjectRef *ref)
2486 ServerActiveObject *co = ref->m_object;
2490 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2492 ServerActiveObject *obj = getobject(ref);
2495 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2497 return (LuaEntitySAO*)obj;
2500 static PlayerSAO* getplayersao(ObjectRef *ref)
2502 ServerActiveObject *obj = getobject(ref);
2505 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2507 return (PlayerSAO*)obj;
2510 static Player* getplayer(ObjectRef *ref)
2512 PlayerSAO *playersao = getplayersao(ref);
2513 if(playersao == NULL)
2515 return playersao->getPlayer();
2518 // Exported functions
2520 // garbage collector
2521 static int gc_object(lua_State *L) {
2522 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2523 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2529 static int l_remove(lua_State *L)
2531 ObjectRef *ref = checkobject(L, 1);
2532 ServerActiveObject *co = getobject(ref);
2533 if(co == NULL) return 0;
2534 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2535 co->m_removed = true;
2540 // returns: {x=num, y=num, z=num}
2541 static int l_getpos(lua_State *L)
2543 ObjectRef *ref = checkobject(L, 1);
2544 ServerActiveObject *co = getobject(ref);
2545 if(co == NULL) return 0;
2546 v3f pos = co->getBasePosition() / BS;
2548 lua_pushnumber(L, pos.X);
2549 lua_setfield(L, -2, "x");
2550 lua_pushnumber(L, pos.Y);
2551 lua_setfield(L, -2, "y");
2552 lua_pushnumber(L, pos.Z);
2553 lua_setfield(L, -2, "z");
2557 // setpos(self, pos)
2558 static int l_setpos(lua_State *L)
2560 ObjectRef *ref = checkobject(L, 1);
2561 //LuaEntitySAO *co = getluaobject(ref);
2562 ServerActiveObject *co = getobject(ref);
2563 if(co == NULL) return 0;
2565 v3f pos = checkFloatPos(L, 2);
2571 // moveto(self, pos, continuous=false)
2572 static int l_moveto(lua_State *L)
2574 ObjectRef *ref = checkobject(L, 1);
2575 //LuaEntitySAO *co = getluaobject(ref);
2576 ServerActiveObject *co = getobject(ref);
2577 if(co == NULL) return 0;
2579 v3f pos = checkFloatPos(L, 2);
2581 bool continuous = lua_toboolean(L, 3);
2583 co->moveTo(pos, continuous);
2587 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2588 static int l_punch(lua_State *L)
2590 ObjectRef *ref = checkobject(L, 1);
2591 ObjectRef *puncher_ref = checkobject(L, 2);
2592 ServerActiveObject *co = getobject(ref);
2593 ServerActiveObject *puncher = getobject(puncher_ref);
2594 if(co == NULL) return 0;
2595 if(puncher == NULL) return 0;
2597 if(lua_type(L, 5) != LUA_TTABLE)
2598 dir = co->getBasePosition() - puncher->getBasePosition();
2600 dir = read_v3f(L, 5);
2601 float time_from_last_punch = 1000000;
2602 if(lua_isnumber(L, 3))
2603 time_from_last_punch = lua_tonumber(L, 3);
2604 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2607 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2611 // right_click(self, clicker); clicker = an another ObjectRef
2612 static int l_right_click(lua_State *L)
2614 ObjectRef *ref = checkobject(L, 1);
2615 ObjectRef *ref2 = checkobject(L, 2);
2616 ServerActiveObject *co = getobject(ref);
2617 ServerActiveObject *co2 = getobject(ref2);
2618 if(co == NULL) return 0;
2619 if(co2 == NULL) return 0;
2621 co->rightClick(co2);
2626 // hp = number of hitpoints (2 * number of hearts)
2628 static int l_set_hp(lua_State *L)
2630 ObjectRef *ref = checkobject(L, 1);
2631 luaL_checknumber(L, 2);
2632 ServerActiveObject *co = getobject(ref);
2633 if(co == NULL) return 0;
2634 int hp = lua_tonumber(L, 2);
2635 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2636 <<" hp="<<hp<<std::endl;*/
2644 // returns: number of hitpoints (2 * number of hearts)
2645 // 0 if not applicable to this type of object
2646 static int l_get_hp(lua_State *L)
2648 ObjectRef *ref = checkobject(L, 1);
2649 ServerActiveObject *co = getobject(ref);
2652 lua_pushnumber(L, 1);
2655 int hp = co->getHP();
2656 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2657 <<" hp="<<hp<<std::endl;*/
2659 lua_pushnumber(L, hp);
2663 // get_inventory(self)
2664 static int l_get_inventory(lua_State *L)
2666 ObjectRef *ref = checkobject(L, 1);
2667 ServerActiveObject *co = getobject(ref);
2668 if(co == NULL) return 0;
2670 InventoryLocation loc = co->getInventoryLocation();
2671 if(get_server(L)->getInventory(loc) != NULL)
2672 InvRef::create(L, loc);
2674 lua_pushnil(L); // An object may have no inventory (nil)
2678 // get_wield_list(self)
2679 static int l_get_wield_list(lua_State *L)
2681 ObjectRef *ref = checkobject(L, 1);
2682 ServerActiveObject *co = getobject(ref);
2683 if(co == NULL) return 0;
2685 lua_pushstring(L, co->getWieldList().c_str());
2689 // get_wield_index(self)
2690 static int l_get_wield_index(lua_State *L)
2692 ObjectRef *ref = checkobject(L, 1);
2693 ServerActiveObject *co = getobject(ref);
2694 if(co == NULL) return 0;
2696 lua_pushinteger(L, co->getWieldIndex() + 1);
2700 // get_wielded_item(self)
2701 static int l_get_wielded_item(lua_State *L)
2703 ObjectRef *ref = checkobject(L, 1);
2704 ServerActiveObject *co = getobject(ref);
2707 LuaItemStack::create(L, ItemStack());
2711 LuaItemStack::create(L, co->getWieldedItem());
2715 // set_wielded_item(self, itemstack or itemstring or table or nil)
2716 static int l_set_wielded_item(lua_State *L)
2718 ObjectRef *ref = checkobject(L, 1);
2719 ServerActiveObject *co = getobject(ref);
2720 if(co == NULL) return 0;
2722 ItemStack item = read_item(L, 2);
2723 bool success = co->setWieldedItem(item);
2724 lua_pushboolean(L, success);
2728 // set_armor_groups(self, groups)
2729 static int l_set_armor_groups(lua_State *L)
2731 ObjectRef *ref = checkobject(L, 1);
2732 ServerActiveObject *co = getobject(ref);
2733 if(co == NULL) return 0;
2735 ItemGroupList groups;
2736 read_groups(L, 2, groups);
2737 co->setArmorGroups(groups);
2741 // set_properties(self, properties)
2742 static int l_set_properties(lua_State *L)
2744 ObjectRef *ref = checkobject(L, 1);
2745 ServerActiveObject *co = getobject(ref);
2746 if(co == NULL) return 0;
2747 ObjectProperties *prop = co->accessObjectProperties();
2750 read_object_properties(L, 2, prop);
2751 co->notifyObjectPropertiesModified();
2755 /* LuaEntitySAO-only */
2757 // setvelocity(self, {x=num, y=num, z=num})
2758 static int l_setvelocity(lua_State *L)
2760 ObjectRef *ref = checkobject(L, 1);
2761 LuaEntitySAO *co = getluaobject(ref);
2762 if(co == NULL) return 0;
2763 v3f pos = checkFloatPos(L, 2);
2765 co->setVelocity(pos);
2769 // getvelocity(self)
2770 static int l_getvelocity(lua_State *L)
2772 ObjectRef *ref = checkobject(L, 1);
2773 LuaEntitySAO *co = getluaobject(ref);
2774 if(co == NULL) return 0;
2776 v3f v = co->getVelocity();
2781 // setacceleration(self, {x=num, y=num, z=num})
2782 static int l_setacceleration(lua_State *L)
2784 ObjectRef *ref = checkobject(L, 1);
2785 LuaEntitySAO *co = getluaobject(ref);
2786 if(co == NULL) return 0;
2788 v3f pos = checkFloatPos(L, 2);
2790 co->setAcceleration(pos);
2794 // getacceleration(self)
2795 static int l_getacceleration(lua_State *L)
2797 ObjectRef *ref = checkobject(L, 1);
2798 LuaEntitySAO *co = getluaobject(ref);
2799 if(co == NULL) return 0;
2801 v3f v = co->getAcceleration();
2806 // setyaw(self, radians)
2807 static int l_setyaw(lua_State *L)
2809 ObjectRef *ref = checkobject(L, 1);
2810 LuaEntitySAO *co = getluaobject(ref);
2811 if(co == NULL) return 0;
2812 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2819 static int l_getyaw(lua_State *L)
2821 ObjectRef *ref = checkobject(L, 1);
2822 LuaEntitySAO *co = getluaobject(ref);
2823 if(co == NULL) return 0;
2825 float yaw = co->getYaw() * core::DEGTORAD;
2826 lua_pushnumber(L, yaw);
2830 // settexturemod(self, mod)
2831 static int l_settexturemod(lua_State *L)
2833 ObjectRef *ref = checkobject(L, 1);
2834 LuaEntitySAO *co = getluaobject(ref);
2835 if(co == NULL) return 0;
2837 std::string mod = luaL_checkstring(L, 2);
2838 co->setTextureMod(mod);
2842 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2843 // select_horiz_by_yawpitch=false)
2844 static int l_setsprite(lua_State *L)
2846 ObjectRef *ref = checkobject(L, 1);
2847 LuaEntitySAO *co = getluaobject(ref);
2848 if(co == NULL) return 0;
2851 if(!lua_isnil(L, 2))
2852 p = read_v2s16(L, 2);
2854 if(!lua_isnil(L, 3))
2855 num_frames = lua_tonumber(L, 3);
2856 float framelength = 0.2;
2857 if(!lua_isnil(L, 4))
2858 framelength = lua_tonumber(L, 4);
2859 bool select_horiz_by_yawpitch = false;
2860 if(!lua_isnil(L, 5))
2861 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2862 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2867 // get_entity_name(self)
2868 static int l_get_entity_name(lua_State *L)
2870 ObjectRef *ref = checkobject(L, 1);
2871 LuaEntitySAO *co = getluaobject(ref);
2872 if(co == NULL) return 0;
2874 std::string name = co->getName();
2875 lua_pushstring(L, name.c_str());
2879 // get_luaentity(self)
2880 static int l_get_luaentity(lua_State *L)
2882 ObjectRef *ref = checkobject(L, 1);
2883 LuaEntitySAO *co = getluaobject(ref);
2884 if(co == NULL) return 0;
2886 luaentity_get(L, co->getId());
2893 static int l_is_player(lua_State *L)
2895 ObjectRef *ref = checkobject(L, 1);
2896 Player *player = getplayer(ref);
2897 lua_pushboolean(L, (player != NULL));
2901 // get_player_name(self)
2902 static int l_get_player_name(lua_State *L)
2904 ObjectRef *ref = checkobject(L, 1);
2905 Player *player = getplayer(ref);
2907 lua_pushlstring(L, "", 0);
2911 lua_pushstring(L, player->getName());
2915 // get_look_dir(self)
2916 static int l_get_look_dir(lua_State *L)
2918 ObjectRef *ref = checkobject(L, 1);
2919 Player *player = getplayer(ref);
2920 if(player == NULL) return 0;
2922 float pitch = player->getRadPitch();
2923 float yaw = player->getRadYaw();
2924 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2929 // get_look_pitch(self)
2930 static int l_get_look_pitch(lua_State *L)
2932 ObjectRef *ref = checkobject(L, 1);
2933 Player *player = getplayer(ref);
2934 if(player == NULL) return 0;
2936 lua_pushnumber(L, player->getRadPitch());
2940 // get_look_yaw(self)
2941 static int l_get_look_yaw(lua_State *L)
2943 ObjectRef *ref = checkobject(L, 1);
2944 Player *player = getplayer(ref);
2945 if(player == NULL) return 0;
2947 lua_pushnumber(L, player->getRadYaw());
2951 // set_inventory_formspec(self, formspec)
2952 static int l_set_inventory_formspec(lua_State *L)
2954 ObjectRef *ref = checkobject(L, 1);
2955 Player *player = getplayer(ref);
2956 if(player == NULL) return 0;
2957 std::string formspec = luaL_checkstring(L, 2);
2959 player->inventory_formspec = formspec;
2960 get_server(L)->reportInventoryFormspecModified(player->getName());
2961 lua_pushboolean(L, true);
2965 // get_inventory_formspec(self) -> formspec
2966 static int l_get_inventory_formspec(lua_State *L)
2968 ObjectRef *ref = checkobject(L, 1);
2969 Player *player = getplayer(ref);
2970 if(player == NULL) return 0;
2972 std::string formspec = player->inventory_formspec;
2973 lua_pushlstring(L, formspec.c_str(), formspec.size());
2978 ObjectRef(ServerActiveObject *object):
2981 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2987 infostream<<"ObjectRef destructing for id="
2988 <<m_object->getId()<<std::endl;
2990 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2993 // Creates an ObjectRef and leaves it on top of stack
2994 // Not callable from Lua; all references are created on the C side.
2995 static void create(lua_State *L, ServerActiveObject *object)
2997 ObjectRef *o = new ObjectRef(object);
2998 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2999 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3000 luaL_getmetatable(L, className);
3001 lua_setmetatable(L, -2);
3004 static void set_null(lua_State *L)
3006 ObjectRef *o = checkobject(L, -1);
3010 static void Register(lua_State *L)
3013 int methodtable = lua_gettop(L);
3014 luaL_newmetatable(L, className);
3015 int metatable = lua_gettop(L);
3017 lua_pushliteral(L, "__metatable");
3018 lua_pushvalue(L, methodtable);
3019 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3021 lua_pushliteral(L, "__index");
3022 lua_pushvalue(L, methodtable);
3023 lua_settable(L, metatable);
3025 lua_pushliteral(L, "__gc");
3026 lua_pushcfunction(L, gc_object);
3027 lua_settable(L, metatable);
3029 lua_pop(L, 1); // drop metatable
3031 luaL_openlib(L, 0, methods, 0); // fill methodtable
3032 lua_pop(L, 1); // drop methodtable
3034 // Cannot be created from Lua
3035 //lua_register(L, className, create_object);
3038 const char ObjectRef::className[] = "ObjectRef";
3039 const luaL_reg ObjectRef::methods[] = {
3040 // ServerActiveObject
3041 method(ObjectRef, remove),
3042 method(ObjectRef, getpos),
3043 method(ObjectRef, setpos),
3044 method(ObjectRef, moveto),
3045 method(ObjectRef, punch),
3046 method(ObjectRef, right_click),
3047 method(ObjectRef, set_hp),
3048 method(ObjectRef, get_hp),
3049 method(ObjectRef, get_inventory),
3050 method(ObjectRef, get_wield_list),
3051 method(ObjectRef, get_wield_index),
3052 method(ObjectRef, get_wielded_item),
3053 method(ObjectRef, set_wielded_item),
3054 method(ObjectRef, set_armor_groups),
3055 method(ObjectRef, set_properties),
3056 // LuaEntitySAO-only
3057 method(ObjectRef, setvelocity),
3058 method(ObjectRef, getvelocity),
3059 method(ObjectRef, setacceleration),
3060 method(ObjectRef, getacceleration),
3061 method(ObjectRef, setyaw),
3062 method(ObjectRef, getyaw),
3063 method(ObjectRef, settexturemod),
3064 method(ObjectRef, setsprite),
3065 method(ObjectRef, get_entity_name),
3066 method(ObjectRef, get_luaentity),
3068 method(ObjectRef, is_player),
3069 method(ObjectRef, get_player_name),
3070 method(ObjectRef, get_look_dir),
3071 method(ObjectRef, get_look_pitch),
3072 method(ObjectRef, get_look_yaw),
3073 method(ObjectRef, set_inventory_formspec),
3074 method(ObjectRef, get_inventory_formspec),
3078 // Creates a new anonymous reference if cobj=NULL or id=0
3079 static void objectref_get_or_create(lua_State *L,
3080 ServerActiveObject *cobj)
3082 if(cobj == NULL || cobj->getId() == 0){
3083 ObjectRef::create(L, cobj);
3085 objectref_get(L, cobj->getId());
3094 class LuaPerlinNoise
3101 static const char className[];
3102 static const luaL_reg methods[];
3104 // Exported functions
3106 // garbage collector
3107 static int gc_object(lua_State *L)
3109 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3114 static int l_get2d(lua_State *L)
3116 LuaPerlinNoise *o = checkobject(L, 1);
3117 v2f pos2d = read_v2f(L,2);
3118 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3119 lua_pushnumber(L, val);
3122 static int l_get3d(lua_State *L)
3124 LuaPerlinNoise *o = checkobject(L, 1);
3125 v3f pos3d = read_v3f(L,2);
3126 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3127 lua_pushnumber(L, val);
3132 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3136 persistence(a_persistence),
3145 // LuaPerlinNoise(seed, octaves, persistence, scale)
3146 // Creates an LuaPerlinNoise and leaves it on top of stack
3147 static int create_object(lua_State *L)
3149 int seed = luaL_checkint(L, 1);
3150 int octaves = luaL_checkint(L, 2);
3151 double persistence = luaL_checknumber(L, 3);
3152 double scale = luaL_checknumber(L, 4);
3153 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3154 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3155 luaL_getmetatable(L, className);
3156 lua_setmetatable(L, -2);
3160 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3162 luaL_checktype(L, narg, LUA_TUSERDATA);
3163 void *ud = luaL_checkudata(L, narg, className);
3164 if(!ud) luaL_typerror(L, narg, className);
3165 return *(LuaPerlinNoise**)ud; // unbox pointer
3168 static void Register(lua_State *L)
3171 int methodtable = lua_gettop(L);
3172 luaL_newmetatable(L, className);
3173 int metatable = lua_gettop(L);
3175 lua_pushliteral(L, "__metatable");
3176 lua_pushvalue(L, methodtable);
3177 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3179 lua_pushliteral(L, "__index");
3180 lua_pushvalue(L, methodtable);
3181 lua_settable(L, metatable);
3183 lua_pushliteral(L, "__gc");
3184 lua_pushcfunction(L, gc_object);
3185 lua_settable(L, metatable);
3187 lua_pop(L, 1); // drop metatable
3189 luaL_openlib(L, 0, methods, 0); // fill methodtable
3190 lua_pop(L, 1); // drop methodtable
3192 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3193 lua_register(L, className, create_object);
3196 const char LuaPerlinNoise::className[] = "PerlinNoise";
3197 const luaL_reg LuaPerlinNoise::methods[] = {
3198 method(LuaPerlinNoise, get2d),
3199 method(LuaPerlinNoise, get3d),
3211 ServerEnvironment *m_env;
3213 static const char className[];
3214 static const luaL_reg methods[];
3216 static int gc_object(lua_State *L) {
3217 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3222 static NodeTimerRef *checkobject(lua_State *L, int narg)
3224 luaL_checktype(L, narg, LUA_TUSERDATA);
3225 void *ud = luaL_checkudata(L, narg, className);
3226 if(!ud) luaL_typerror(L, narg, className);
3227 return *(NodeTimerRef**)ud; // unbox pointer
3230 static int l_set(lua_State *L)
3232 NodeTimerRef *o = checkobject(L, 1);
3233 ServerEnvironment *env = o->m_env;
3234 if(env == NULL) return 0;
3235 f32 t = luaL_checknumber(L,2);
3236 f32 e = luaL_checknumber(L,3);
3237 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3241 static int l_start(lua_State *L)
3243 NodeTimerRef *o = checkobject(L, 1);
3244 ServerEnvironment *env = o->m_env;
3245 if(env == NULL) return 0;
3246 f32 t = luaL_checknumber(L,2);
3247 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3251 static int l_stop(lua_State *L)
3253 NodeTimerRef *o = checkobject(L, 1);
3254 ServerEnvironment *env = o->m_env;
3255 if(env == NULL) return 0;
3256 env->getMap().removeNodeTimer(o->m_p);
3260 static int l_is_started(lua_State *L)
3262 NodeTimerRef *o = checkobject(L, 1);
3263 ServerEnvironment *env = o->m_env;
3264 if(env == NULL) return 0;
3266 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3267 lua_pushboolean(L,(t.timeout != 0));
3271 static int l_get_timeout(lua_State *L)
3273 NodeTimerRef *o = checkobject(L, 1);
3274 ServerEnvironment *env = o->m_env;
3275 if(env == NULL) return 0;
3277 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3278 lua_pushnumber(L,t.timeout);
3282 static int l_get_elapsed(lua_State *L)
3284 NodeTimerRef *o = checkobject(L, 1);
3285 ServerEnvironment *env = o->m_env;
3286 if(env == NULL) return 0;
3288 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3289 lua_pushnumber(L,t.elapsed);
3294 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3304 // Creates an NodeTimerRef and leaves it on top of stack
3305 // Not callable from Lua; all references are created on the C side.
3306 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3308 NodeTimerRef *o = new NodeTimerRef(p, env);
3309 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3310 luaL_getmetatable(L, className);
3311 lua_setmetatable(L, -2);
3314 static void set_null(lua_State *L)
3316 NodeTimerRef *o = checkobject(L, -1);
3320 static void Register(lua_State *L)
3323 int methodtable = lua_gettop(L);
3324 luaL_newmetatable(L, className);
3325 int metatable = lua_gettop(L);
3327 lua_pushliteral(L, "__metatable");
3328 lua_pushvalue(L, methodtable);
3329 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3331 lua_pushliteral(L, "__index");
3332 lua_pushvalue(L, methodtable);
3333 lua_settable(L, metatable);
3335 lua_pushliteral(L, "__gc");
3336 lua_pushcfunction(L, gc_object);
3337 lua_settable(L, metatable);
3339 lua_pop(L, 1); // drop metatable
3341 luaL_openlib(L, 0, methods, 0); // fill methodtable
3342 lua_pop(L, 1); // drop methodtable
3344 // Cannot be created from Lua
3345 //lua_register(L, className, create_object);
3348 const char NodeTimerRef::className[] = "NodeTimerRef";
3349 const luaL_reg NodeTimerRef::methods[] = {
3350 method(NodeTimerRef, start),
3351 method(NodeTimerRef, set),
3352 method(NodeTimerRef, stop),
3353 method(NodeTimerRef, is_started),
3354 method(NodeTimerRef, get_timeout),
3355 method(NodeTimerRef, get_elapsed),
3366 ServerEnvironment *m_env;
3368 static const char className[];
3369 static const luaL_reg methods[];
3371 static int gc_object(lua_State *L) {
3372 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3377 static EnvRef *checkobject(lua_State *L, int narg)
3379 luaL_checktype(L, narg, LUA_TUSERDATA);
3380 void *ud = luaL_checkudata(L, narg, className);
3381 if(!ud) luaL_typerror(L, narg, className);
3382 return *(EnvRef**)ud; // unbox pointer
3385 // Exported functions
3387 // EnvRef:set_node(pos, node)
3388 // pos = {x=num, y=num, z=num}
3389 static int l_set_node(lua_State *L)
3391 EnvRef *o = checkobject(L, 1);
3392 ServerEnvironment *env = o->m_env;
3393 if(env == NULL) return 0;
3394 INodeDefManager *ndef = env->getGameDef()->ndef();
3396 v3s16 pos = read_v3s16(L, 2);
3397 MapNode n = readnode(L, 3, ndef);
3399 MapNode n_old = env->getMap().getNodeNoEx(pos);
3401 if(ndef->get(n_old).has_on_destruct)
3402 scriptapi_node_on_destruct(L, pos, n_old);
3404 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3406 // Call post-destructor
3407 if(ndef->get(n_old).has_after_destruct)
3408 scriptapi_node_after_destruct(L, pos, n_old);
3410 if(ndef->get(n).has_on_construct)
3411 scriptapi_node_on_construct(L, pos, n);
3413 lua_pushboolean(L, succeeded);
3417 static int l_add_node(lua_State *L)
3419 return l_set_node(L);
3422 // EnvRef:remove_node(pos)
3423 // pos = {x=num, y=num, z=num}
3424 static int l_remove_node(lua_State *L)
3426 EnvRef *o = checkobject(L, 1);
3427 ServerEnvironment *env = o->m_env;
3428 if(env == NULL) return 0;
3429 INodeDefManager *ndef = env->getGameDef()->ndef();
3431 v3s16 pos = read_v3s16(L, 2);
3433 MapNode n_old = env->getMap().getNodeNoEx(pos);
3435 if(ndef->get(n_old).has_on_destruct)
3436 scriptapi_node_on_destruct(L, pos, n_old);
3438 // This is slightly optimized compared to addNodeWithEvent(air)
3439 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3441 // Call post-destructor
3442 if(ndef->get(n_old).has_after_destruct)
3443 scriptapi_node_after_destruct(L, pos, n_old);
3445 lua_pushboolean(L, succeeded);
3446 // Air doesn't require constructor
3450 // EnvRef:get_node(pos)
3451 // pos = {x=num, y=num, z=num}
3452 static int l_get_node(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);
3460 MapNode n = env->getMap().getNodeNoEx(pos);
3462 pushnode(L, n, env->getGameDef()->ndef());
3466 // EnvRef:get_node_or_nil(pos)
3467 // pos = {x=num, y=num, z=num}
3468 static int l_get_node_or_nil(lua_State *L)
3470 EnvRef *o = checkobject(L, 1);
3471 ServerEnvironment *env = o->m_env;
3472 if(env == NULL) return 0;
3474 v3s16 pos = read_v3s16(L, 2);
3477 MapNode n = env->getMap().getNode(pos);
3479 pushnode(L, n, env->getGameDef()->ndef());
3481 } catch(InvalidPositionException &e)
3488 // EnvRef:get_node_light(pos, timeofday)
3489 // pos = {x=num, y=num, z=num}
3490 // timeofday: nil = current time, 0 = night, 0.5 = day
3491 static int l_get_node_light(lua_State *L)
3493 EnvRef *o = checkobject(L, 1);
3494 ServerEnvironment *env = o->m_env;
3495 if(env == NULL) return 0;
3497 v3s16 pos = read_v3s16(L, 2);
3498 u32 time_of_day = env->getTimeOfDay();
3499 if(lua_isnumber(L, 3))
3500 time_of_day = 24000.0 * lua_tonumber(L, 3);
3501 time_of_day %= 24000;
3502 u32 dnr = time_to_daynight_ratio(time_of_day);
3503 MapNode n = env->getMap().getNodeNoEx(pos);
3505 MapNode n = env->getMap().getNode(pos);
3506 INodeDefManager *ndef = env->getGameDef()->ndef();
3507 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3509 } catch(InvalidPositionException &e)
3516 // EnvRef:place_node(pos, node)
3517 // pos = {x=num, y=num, z=num}
3518 static int l_place_node(lua_State *L)
3520 EnvRef *o = checkobject(L, 1);
3521 ServerEnvironment *env = o->m_env;
3522 if(env == NULL) return 0;
3523 v3s16 pos = read_v3s16(L, 2);
3524 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3526 // Don't attempt to load non-loaded area as of now
3527 MapNode n_old = env->getMap().getNodeNoEx(pos);
3528 if(n_old.getContent() == CONTENT_IGNORE){
3529 lua_pushboolean(L, false);
3532 // Create item to place
3533 INodeDefManager *ndef = get_server(L)->ndef();
3534 IItemDefManager *idef = get_server(L)->idef();
3535 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3536 // Make pointed position
3537 PointedThing pointed;
3538 pointed.type = POINTEDTHING_NODE;
3539 pointed.node_abovesurface = pos;
3540 pointed.node_undersurface = pos + v3s16(0,-1,0);
3541 // Place it with a NULL placer (appears in Lua as a non-functional
3543 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3544 lua_pushboolean(L, success);
3548 // EnvRef:dig_node(pos)
3549 // pos = {x=num, y=num, z=num}
3550 static int l_dig_node(lua_State *L)
3552 EnvRef *o = checkobject(L, 1);
3553 ServerEnvironment *env = o->m_env;
3554 if(env == NULL) return 0;
3555 v3s16 pos = read_v3s16(L, 2);
3557 // Don't attempt to load non-loaded area as of now
3558 MapNode n = env->getMap().getNodeNoEx(pos);
3559 if(n.getContent() == CONTENT_IGNORE){
3560 lua_pushboolean(L, false);
3563 // Dig it out with a NULL digger (appears in Lua as a
3564 // non-functional ObjectRef)
3565 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3566 lua_pushboolean(L, success);
3570 // EnvRef:punch_node(pos)
3571 // pos = {x=num, y=num, z=num}
3572 static int l_punch_node(lua_State *L)
3574 EnvRef *o = checkobject(L, 1);
3575 ServerEnvironment *env = o->m_env;
3576 if(env == NULL) return 0;
3577 v3s16 pos = read_v3s16(L, 2);
3579 // Don't attempt to load non-loaded area as of now
3580 MapNode n = env->getMap().getNodeNoEx(pos);
3581 if(n.getContent() == CONTENT_IGNORE){
3582 lua_pushboolean(L, false);
3585 // Punch it with a NULL puncher (appears in Lua as a non-functional
3587 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3588 lua_pushboolean(L, success);
3592 // EnvRef:get_meta(pos)
3593 static int l_get_meta(lua_State *L)
3595 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3596 EnvRef *o = checkobject(L, 1);
3597 ServerEnvironment *env = o->m_env;
3598 if(env == NULL) return 0;
3600 v3s16 p = read_v3s16(L, 2);
3601 NodeMetaRef::create(L, p, env);
3605 // EnvRef:get_node_timer(pos)
3606 static int l_get_node_timer(lua_State *L)
3608 EnvRef *o = checkobject(L, 1);
3609 ServerEnvironment *env = o->m_env;
3610 if(env == NULL) return 0;
3612 v3s16 p = read_v3s16(L, 2);
3613 NodeTimerRef::create(L, p, env);
3617 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3618 // pos = {x=num, y=num, z=num}
3619 static int l_add_entity(lua_State *L)
3621 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3622 EnvRef *o = checkobject(L, 1);
3623 ServerEnvironment *env = o->m_env;
3624 if(env == NULL) return 0;
3626 v3f pos = checkFloatPos(L, 2);
3628 const char *name = luaL_checkstring(L, 3);
3630 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
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_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3641 // pos = {x=num, y=num, z=num}
3642 static int l_add_item(lua_State *L)
3644 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3645 EnvRef *o = checkobject(L, 1);
3646 ServerEnvironment *env = o->m_env;
3647 if(env == NULL) return 0;
3649 v3f pos = checkFloatPos(L, 2);
3651 ItemStack item = read_item(L, 3);
3652 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3654 // Use minetest.spawn_item to spawn a __builtin:item
3655 lua_getglobal(L, "minetest");
3656 lua_getfield(L, -1, "spawn_item");
3657 if(lua_isnil(L, -1))
3659 lua_pushvalue(L, 2);
3660 lua_pushstring(L, item.getItemString().c_str());
3661 if(lua_pcall(L, 2, 1, 0))
3662 script_error(L, "error: %s", lua_tostring(L, -1));
3664 /*lua_pushvalue(L, 1);
3665 lua_pushstring(L, "__builtin:item");
3666 lua_pushstring(L, item.getItemString().c_str());
3667 return l_add_entity(L);*/
3669 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3670 int objectid = env->addActiveObject(obj);
3671 // If failed to add, return nothing (reads as nil)
3675 objectref_get_or_create(L, obj);
3679 // EnvRef:add_rat(pos)
3680 // pos = {x=num, y=num, z=num}
3681 static int l_add_rat(lua_State *L)
3683 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3684 <<" Doing nothing."<<std::endl;
3688 // EnvRef:add_firefly(pos)
3689 // pos = {x=num, y=num, z=num}
3690 static int l_add_firefly(lua_State *L)
3692 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3693 <<" Doing nothing."<<std::endl;
3697 // EnvRef:get_player_by_name(name)
3698 static int l_get_player_by_name(lua_State *L)
3700 EnvRef *o = checkobject(L, 1);
3701 ServerEnvironment *env = o->m_env;
3702 if(env == NULL) return 0;
3704 const char *name = luaL_checkstring(L, 2);
3705 Player *player = env->getPlayer(name);
3710 PlayerSAO *sao = player->getPlayerSAO();
3715 // Put player on stack
3716 objectref_get_or_create(L, sao);
3720 // EnvRef:get_objects_inside_radius(pos, radius)
3721 static int l_get_objects_inside_radius(lua_State *L)
3723 // Get the table insert function
3724 lua_getglobal(L, "table");
3725 lua_getfield(L, -1, "insert");
3726 int table_insert = lua_gettop(L);
3728 EnvRef *o = checkobject(L, 1);
3729 ServerEnvironment *env = o->m_env;
3730 if(env == NULL) return 0;
3732 v3f pos = checkFloatPos(L, 2);
3733 float radius = luaL_checknumber(L, 3) * BS;
3734 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3736 int table = lua_gettop(L);
3737 for(std::set<u16>::const_iterator
3738 i = ids.begin(); i != ids.end(); i++){
3739 ServerActiveObject *obj = env->getActiveObject(*i);
3740 // Insert object reference into table
3741 lua_pushvalue(L, table_insert);
3742 lua_pushvalue(L, table);
3743 objectref_get_or_create(L, obj);
3744 if(lua_pcall(L, 2, 0, 0))
3745 script_error(L, "error: %s", lua_tostring(L, -1));
3750 // EnvRef:set_timeofday(val)
3752 static int l_set_timeofday(lua_State *L)
3754 EnvRef *o = checkobject(L, 1);
3755 ServerEnvironment *env = o->m_env;
3756 if(env == NULL) return 0;
3758 float timeofday_f = luaL_checknumber(L, 2);
3759 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3760 int timeofday_mh = (int)(timeofday_f * 24000.0);
3761 // This should be set directly in the environment but currently
3762 // such changes aren't immediately sent to the clients, so call
3763 // the server instead.
3764 //env->setTimeOfDay(timeofday_mh);
3765 get_server(L)->setTimeOfDay(timeofday_mh);
3769 // EnvRef:get_timeofday() -> 0...1
3770 static int l_get_timeofday(lua_State *L)
3772 EnvRef *o = checkobject(L, 1);
3773 ServerEnvironment *env = o->m_env;
3774 if(env == NULL) return 0;
3776 int timeofday_mh = env->getTimeOfDay();
3777 float timeofday_f = (float)timeofday_mh / 24000.0;
3778 lua_pushnumber(L, timeofday_f);
3783 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3784 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3785 static int l_find_node_near(lua_State *L)
3787 EnvRef *o = checkobject(L, 1);
3788 ServerEnvironment *env = o->m_env;
3789 if(env == NULL) return 0;
3790 INodeDefManager *ndef = get_server(L)->ndef();
3791 v3s16 pos = read_v3s16(L, 2);
3792 int radius = luaL_checkinteger(L, 3);
3793 std::set<content_t> filter;
3794 if(lua_istable(L, 4)){
3797 while(lua_next(L, table) != 0){
3798 // key at index -2 and value at index -1
3799 luaL_checktype(L, -1, LUA_TSTRING);
3800 ndef->getIds(lua_tostring(L, -1), filter);
3801 // removes value, keeps key for next iteration
3804 } else if(lua_isstring(L, 4)){
3805 ndef->getIds(lua_tostring(L, 4), filter);
3808 for(int d=1; d<=radius; d++){
3809 core::list<v3s16> list;
3810 getFacePositions(list, d);
3811 for(core::list<v3s16>::Iterator i = list.begin();
3812 i != list.end(); i++){
3813 v3s16 p = pos + (*i);
3814 content_t c = env->getMap().getNodeNoEx(p).getContent();
3815 if(filter.count(c) != 0){
3824 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3825 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3826 static int l_find_nodes_in_area(lua_State *L)
3828 EnvRef *o = checkobject(L, 1);
3829 ServerEnvironment *env = o->m_env;
3830 if(env == NULL) return 0;
3831 INodeDefManager *ndef = get_server(L)->ndef();
3832 v3s16 minp = read_v3s16(L, 2);
3833 v3s16 maxp = read_v3s16(L, 3);
3834 std::set<content_t> filter;
3835 if(lua_istable(L, 4)){
3838 while(lua_next(L, table) != 0){
3839 // key at index -2 and value at index -1
3840 luaL_checktype(L, -1, LUA_TSTRING);
3841 ndef->getIds(lua_tostring(L, -1), filter);
3842 // removes value, keeps key for next iteration
3845 } else if(lua_isstring(L, 4)){
3846 ndef->getIds(lua_tostring(L, 4), filter);
3849 // Get the table insert function
3850 lua_getglobal(L, "table");
3851 lua_getfield(L, -1, "insert");
3852 int table_insert = lua_gettop(L);
3855 int table = lua_gettop(L);
3856 for(s16 x=minp.X; x<=maxp.X; x++)
3857 for(s16 y=minp.Y; y<=maxp.Y; y++)
3858 for(s16 z=minp.Z; z<=maxp.Z; z++)
3861 content_t c = env->getMap().getNodeNoEx(p).getContent();
3862 if(filter.count(c) != 0){
3863 lua_pushvalue(L, table_insert);
3864 lua_pushvalue(L, table);
3866 if(lua_pcall(L, 2, 0, 0))
3867 script_error(L, "error: %s", lua_tostring(L, -1));
3873 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3874 // returns world-specific PerlinNoise
3875 static int l_get_perlin(lua_State *L)
3877 EnvRef *o = checkobject(L, 1);
3878 ServerEnvironment *env = o->m_env;
3879 if(env == NULL) return 0;
3881 int seeddiff = luaL_checkint(L, 2);
3882 int octaves = luaL_checkint(L, 3);
3883 double persistence = luaL_checknumber(L, 4);
3884 double scale = luaL_checknumber(L, 5);
3886 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3887 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3888 luaL_getmetatable(L, "PerlinNoise");
3889 lua_setmetatable(L, -2);
3893 // EnvRef:clear_objects()
3894 // clear all objects in the environment
3895 static int l_clear_objects(lua_State *L)
3897 EnvRef *o = checkobject(L, 1);
3898 o->m_env->clearAllObjects();
3903 EnvRef(ServerEnvironment *env):
3906 //infostream<<"EnvRef created"<<std::endl;
3911 //infostream<<"EnvRef destructing"<<std::endl;
3914 // Creates an EnvRef and leaves it on top of stack
3915 // Not callable from Lua; all references are created on the C side.
3916 static void create(lua_State *L, ServerEnvironment *env)
3918 EnvRef *o = new EnvRef(env);
3919 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3920 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3921 luaL_getmetatable(L, className);
3922 lua_setmetatable(L, -2);
3925 static void set_null(lua_State *L)
3927 EnvRef *o = checkobject(L, -1);
3931 static void Register(lua_State *L)
3934 int methodtable = lua_gettop(L);
3935 luaL_newmetatable(L, className);
3936 int metatable = lua_gettop(L);
3938 lua_pushliteral(L, "__metatable");
3939 lua_pushvalue(L, methodtable);
3940 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3942 lua_pushliteral(L, "__index");
3943 lua_pushvalue(L, methodtable);
3944 lua_settable(L, metatable);
3946 lua_pushliteral(L, "__gc");
3947 lua_pushcfunction(L, gc_object);
3948 lua_settable(L, metatable);
3950 lua_pop(L, 1); // drop metatable
3952 luaL_openlib(L, 0, methods, 0); // fill methodtable
3953 lua_pop(L, 1); // drop methodtable
3955 // Cannot be created from Lua
3956 //lua_register(L, className, create_object);
3959 const char EnvRef::className[] = "EnvRef";
3960 const luaL_reg EnvRef::methods[] = {
3961 method(EnvRef, set_node),
3962 method(EnvRef, add_node),
3963 method(EnvRef, remove_node),
3964 method(EnvRef, get_node),
3965 method(EnvRef, get_node_or_nil),
3966 method(EnvRef, get_node_light),
3967 method(EnvRef, place_node),
3968 method(EnvRef, dig_node),
3969 method(EnvRef, punch_node),
3970 method(EnvRef, add_entity),
3971 method(EnvRef, add_item),
3972 method(EnvRef, add_rat),
3973 method(EnvRef, add_firefly),
3974 method(EnvRef, get_meta),
3975 method(EnvRef, get_node_timer),
3976 method(EnvRef, get_player_by_name),
3977 method(EnvRef, get_objects_inside_radius),
3978 method(EnvRef, set_timeofday),
3979 method(EnvRef, get_timeofday),
3980 method(EnvRef, find_node_near),
3981 method(EnvRef, find_nodes_in_area),
3982 method(EnvRef, get_perlin),
3983 method(EnvRef, clear_objects),
3992 class LuaPseudoRandom
3995 PseudoRandom m_pseudo;
3997 static const char className[];
3998 static const luaL_reg methods[];
4000 // Exported functions
4002 // garbage collector
4003 static int gc_object(lua_State *L)
4005 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4010 // next(self, min=0, max=32767) -> get next value
4011 static int l_next(lua_State *L)
4013 LuaPseudoRandom *o = checkobject(L, 1);
4016 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4017 if(!lua_isnil(L, 2))
4018 min = luaL_checkinteger(L, 2);
4019 if(!lua_isnil(L, 3))
4020 max = luaL_checkinteger(L, 3);
4022 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4023 throw LuaError(L, "PseudoRandom.next(): max < min");
4025 if(max - min != 32767 && max - min > 32767/5)
4026 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.");
4027 PseudoRandom &pseudo = o->m_pseudo;
4028 int val = pseudo.next();
4029 val = (val % (max-min+1)) + min;
4030 lua_pushinteger(L, val);
4035 LuaPseudoRandom(int seed):
4044 const PseudoRandom& getItem() const
4048 PseudoRandom& getItem()
4053 // LuaPseudoRandom(seed)
4054 // Creates an LuaPseudoRandom and leaves it on top of stack
4055 static int create_object(lua_State *L)
4057 int seed = luaL_checknumber(L, 1);
4058 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4059 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4060 luaL_getmetatable(L, className);
4061 lua_setmetatable(L, -2);
4065 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4067 luaL_checktype(L, narg, LUA_TUSERDATA);
4068 void *ud = luaL_checkudata(L, narg, className);
4069 if(!ud) luaL_typerror(L, narg, className);
4070 return *(LuaPseudoRandom**)ud; // unbox pointer
4073 static void Register(lua_State *L)
4076 int methodtable = lua_gettop(L);
4077 luaL_newmetatable(L, className);
4078 int metatable = lua_gettop(L);
4080 lua_pushliteral(L, "__metatable");
4081 lua_pushvalue(L, methodtable);
4082 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4084 lua_pushliteral(L, "__index");
4085 lua_pushvalue(L, methodtable);
4086 lua_settable(L, metatable);
4088 lua_pushliteral(L, "__gc");
4089 lua_pushcfunction(L, gc_object);
4090 lua_settable(L, metatable);
4092 lua_pop(L, 1); // drop metatable
4094 luaL_openlib(L, 0, methods, 0); // fill methodtable
4095 lua_pop(L, 1); // drop methodtable
4097 // Can be created from Lua (LuaPseudoRandom(seed))
4098 lua_register(L, className, create_object);
4101 const char LuaPseudoRandom::className[] = "PseudoRandom";
4102 const luaL_reg LuaPseudoRandom::methods[] = {
4103 method(LuaPseudoRandom, next),
4113 class LuaABM : public ActiveBlockModifier
4119 std::set<std::string> m_trigger_contents;
4120 std::set<std::string> m_required_neighbors;
4121 float m_trigger_interval;
4122 u32 m_trigger_chance;
4124 LuaABM(lua_State *L, int id,
4125 const std::set<std::string> &trigger_contents,
4126 const std::set<std::string> &required_neighbors,
4127 float trigger_interval, u32 trigger_chance):
4130 m_trigger_contents(trigger_contents),
4131 m_required_neighbors(required_neighbors),
4132 m_trigger_interval(trigger_interval),
4133 m_trigger_chance(trigger_chance)
4136 virtual std::set<std::string> getTriggerContents()
4138 return m_trigger_contents;
4140 virtual std::set<std::string> getRequiredNeighbors()
4142 return m_required_neighbors;
4144 virtual float getTriggerInterval()
4146 return m_trigger_interval;
4148 virtual u32 getTriggerChance()
4150 return m_trigger_chance;
4152 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4153 u32 active_object_count, u32 active_object_count_wider)
4155 lua_State *L = m_lua;
4158 assert(lua_checkstack(L, 20));
4159 StackUnroller stack_unroller(L);
4161 // Get minetest.registered_abms
4162 lua_getglobal(L, "minetest");
4163 lua_getfield(L, -1, "registered_abms");
4164 luaL_checktype(L, -1, LUA_TTABLE);
4165 int registered_abms = lua_gettop(L);
4167 // Get minetest.registered_abms[m_id]
4168 lua_pushnumber(L, m_id);
4169 lua_gettable(L, registered_abms);
4170 if(lua_isnil(L, -1))
4174 luaL_checktype(L, -1, LUA_TTABLE);
4175 lua_getfield(L, -1, "action");
4176 luaL_checktype(L, -1, LUA_TFUNCTION);
4178 pushnode(L, n, env->getGameDef()->ndef());
4179 lua_pushnumber(L, active_object_count);
4180 lua_pushnumber(L, active_object_count_wider);
4181 if(lua_pcall(L, 4, 0, 0))
4182 script_error(L, "error: %s", lua_tostring(L, -1));
4190 static void read_server_sound_params(lua_State *L, int index,
4191 ServerSoundParams ¶ms)
4194 index = lua_gettop(L) + 1 + index;
4196 params = ServerSoundParams();
4197 if(lua_istable(L, index)){
4198 getfloatfield(L, index, "gain", params.gain);
4199 getstringfield(L, index, "to_player", params.to_player);
4200 lua_getfield(L, index, "pos");
4201 if(!lua_isnil(L, -1)){
4202 v3f p = read_v3f(L, -1)*BS;
4204 params.type = ServerSoundParams::SSP_POSITIONAL;
4207 lua_getfield(L, index, "object");
4208 if(!lua_isnil(L, -1)){
4209 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4210 ServerActiveObject *sao = ObjectRef::getobject(ref);
4212 params.object = sao->getId();
4213 params.type = ServerSoundParams::SSP_OBJECT;
4217 params.max_hear_distance = BS*getfloatfield_default(L, index,
4218 "max_hear_distance", params.max_hear_distance/BS);
4219 getboolfield(L, index, "loop", params.loop);
4228 // Writes a line to dstream
4229 static int l_debug(lua_State *L)
4231 std::string text = lua_tostring(L, 1);
4232 dstream << text << std::endl;
4236 // log([level,] text)
4237 // Writes a line to the logger.
4238 // The one-argument version logs to infostream.
4239 // The two-argument version accept a log level: error, action, info, or verbose.
4240 static int l_log(lua_State *L)
4243 LogMessageLevel level = LMT_INFO;
4244 if(lua_isnone(L, 2))
4246 text = lua_tostring(L, 1);
4250 std::string levelname = lua_tostring(L, 1);
4251 text = lua_tostring(L, 2);
4252 if(levelname == "error")
4254 else if(levelname == "action")
4256 else if(levelname == "verbose")
4257 level = LMT_VERBOSE;
4259 log_printline(level, text);
4263 // request_shutdown()
4264 static int l_request_shutdown(lua_State *L)
4266 get_server(L)->requestShutdown();
4270 // get_server_status()
4271 static int l_get_server_status(lua_State *L)
4273 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4277 // register_item_raw({lots of stuff})
4278 static int l_register_item_raw(lua_State *L)
4280 luaL_checktype(L, 1, LUA_TTABLE);
4283 // Get the writable item and node definition managers from the server
4284 IWritableItemDefManager *idef =
4285 get_server(L)->getWritableItemDefManager();
4286 IWritableNodeDefManager *ndef =
4287 get_server(L)->getWritableNodeDefManager();
4289 // Check if name is defined
4291 lua_getfield(L, table, "name");
4292 if(lua_isstring(L, -1)){
4293 name = lua_tostring(L, -1);
4294 verbosestream<<"register_item_raw: "<<name<<std::endl;
4296 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4299 // Check if on_use is defined
4302 // Set a distinctive default value to check if this is set
4303 def.node_placement_prediction = "__default";
4305 // Read the item definition
4306 def = read_item_definition(L, table, def);
4308 // Default to having client-side placement prediction for nodes
4309 // ("" in item definition sets it off)
4310 if(def.node_placement_prediction == "__default"){
4311 if(def.type == ITEM_NODE)
4312 def.node_placement_prediction = name;
4314 def.node_placement_prediction = "";
4317 // Register item definition
4318 idef->registerItem(def);
4320 // Read the node definition (content features) and register it
4321 if(def.type == ITEM_NODE)
4323 ContentFeatures f = read_content_features(L, table);
4324 ndef->set(f.name, f);
4327 return 0; /* number of results */
4330 // register_alias_raw(name, convert_to_name)
4331 static int l_register_alias_raw(lua_State *L)
4333 std::string name = luaL_checkstring(L, 1);
4334 std::string convert_to = luaL_checkstring(L, 2);
4336 // Get the writable item definition manager from the server
4337 IWritableItemDefManager *idef =
4338 get_server(L)->getWritableItemDefManager();
4340 idef->registerAlias(name, convert_to);
4342 return 0; /* number of results */
4345 // helper for register_craft
4346 static bool read_craft_recipe_shaped(lua_State *L, int index,
4347 int &width, std::vector<std::string> &recipe)
4350 index = lua_gettop(L) + 1 + index;
4352 if(!lua_istable(L, index))
4357 while(lua_next(L, index) != 0){
4359 // key at index -2 and value at index -1
4360 if(!lua_istable(L, -1))
4362 int table2 = lua_gettop(L);
4364 while(lua_next(L, table2) != 0){
4365 // key at index -2 and value at index -1
4366 if(!lua_isstring(L, -1))
4368 recipe.push_back(lua_tostring(L, -1));
4369 // removes value, keeps key for next iteration
4376 if(colcount != width)
4379 // removes value, keeps key for next iteration
4386 // helper for register_craft
4387 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4388 std::vector<std::string> &recipe)
4391 index = lua_gettop(L) + 1 + index;
4393 if(!lua_istable(L, index))
4397 while(lua_next(L, index) != 0){
4398 // key at index -2 and value at index -1
4399 if(!lua_isstring(L, -1))
4401 recipe.push_back(lua_tostring(L, -1));
4402 // removes value, keeps key for next iteration
4408 // helper for register_craft
4409 static bool read_craft_replacements(lua_State *L, int index,
4410 CraftReplacements &replacements)
4413 index = lua_gettop(L) + 1 + index;
4415 if(!lua_istable(L, index))
4419 while(lua_next(L, index) != 0){
4420 // key at index -2 and value at index -1
4421 if(!lua_istable(L, -1))
4423 lua_rawgeti(L, -1, 1);
4424 if(!lua_isstring(L, -1))
4426 std::string replace_from = lua_tostring(L, -1);
4428 lua_rawgeti(L, -1, 2);
4429 if(!lua_isstring(L, -1))
4431 std::string replace_to = lua_tostring(L, -1);
4433 replacements.pairs.push_back(
4434 std::make_pair(replace_from, replace_to));
4435 // removes value, keeps key for next iteration
4440 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4441 static int l_register_craft(lua_State *L)
4443 //infostream<<"register_craft"<<std::endl;
4444 luaL_checktype(L, 1, LUA_TTABLE);
4447 // Get the writable craft definition manager from the server
4448 IWritableCraftDefManager *craftdef =
4449 get_server(L)->getWritableCraftDefManager();
4451 std::string type = getstringfield_default(L, table, "type", "shaped");
4454 CraftDefinitionShaped
4456 if(type == "shaped"){
4457 std::string output = getstringfield_default(L, table, "output", "");
4459 throw LuaError(L, "Crafting definition is missing an output");
4462 std::vector<std::string> recipe;
4463 lua_getfield(L, table, "recipe");
4464 if(lua_isnil(L, -1))
4465 throw LuaError(L, "Crafting definition is missing a recipe"
4466 " (output=\"" + output + "\")");
4467 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4468 throw LuaError(L, "Invalid crafting recipe"
4469 " (output=\"" + output + "\")");
4471 CraftReplacements replacements;
4472 lua_getfield(L, table, "replacements");
4473 if(!lua_isnil(L, -1))
4475 if(!read_craft_replacements(L, -1, replacements))
4476 throw LuaError(L, "Invalid replacements"
4477 " (output=\"" + output + "\")");
4480 CraftDefinition *def = new CraftDefinitionShaped(
4481 output, width, recipe, replacements);
4482 craftdef->registerCraft(def);
4485 CraftDefinitionShapeless
4487 else if(type == "shapeless"){
4488 std::string output = getstringfield_default(L, table, "output", "");
4490 throw LuaError(L, "Crafting definition (shapeless)"
4491 " is missing an output");
4493 std::vector<std::string> recipe;
4494 lua_getfield(L, table, "recipe");
4495 if(lua_isnil(L, -1))
4496 throw LuaError(L, "Crafting definition (shapeless)"
4497 " is missing a recipe"
4498 " (output=\"" + output + "\")");
4499 if(!read_craft_recipe_shapeless(L, -1, recipe))
4500 throw LuaError(L, "Invalid crafting recipe"
4501 " (output=\"" + output + "\")");
4503 CraftReplacements replacements;
4504 lua_getfield(L, table, "replacements");
4505 if(!lua_isnil(L, -1))
4507 if(!read_craft_replacements(L, -1, replacements))
4508 throw LuaError(L, "Invalid replacements"
4509 " (output=\"" + output + "\")");
4512 CraftDefinition *def = new CraftDefinitionShapeless(
4513 output, recipe, replacements);
4514 craftdef->registerCraft(def);
4517 CraftDefinitionToolRepair
4519 else if(type == "toolrepair"){
4520 float additional_wear = getfloatfield_default(L, table,
4521 "additional_wear", 0.0);
4523 CraftDefinition *def = new CraftDefinitionToolRepair(
4525 craftdef->registerCraft(def);
4528 CraftDefinitionCooking
4530 else if(type == "cooking"){
4531 std::string output = getstringfield_default(L, table, "output", "");
4533 throw LuaError(L, "Crafting definition (cooking)"
4534 " is missing an output");
4536 std::string recipe = getstringfield_default(L, table, "recipe", "");
4538 throw LuaError(L, "Crafting definition (cooking)"
4539 " is missing a recipe"
4540 " (output=\"" + output + "\")");
4542 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4544 CraftReplacements replacements;
4545 lua_getfield(L, table, "replacements");
4546 if(!lua_isnil(L, -1))
4548 if(!read_craft_replacements(L, -1, replacements))
4549 throw LuaError(L, "Invalid replacements"
4550 " (cooking output=\"" + output + "\")");
4553 CraftDefinition *def = new CraftDefinitionCooking(
4554 output, recipe, cooktime, replacements);
4555 craftdef->registerCraft(def);
4560 else if(type == "fuel"){
4561 std::string recipe = getstringfield_default(L, table, "recipe", "");
4563 throw LuaError(L, "Crafting definition (fuel)"
4564 " is missing a recipe");
4566 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4568 CraftReplacements replacements;
4569 lua_getfield(L, table, "replacements");
4570 if(!lua_isnil(L, -1))
4572 if(!read_craft_replacements(L, -1, replacements))
4573 throw LuaError(L, "Invalid replacements"
4574 " (fuel recipe=\"" + recipe + "\")");
4577 CraftDefinition *def = new CraftDefinitionFuel(
4578 recipe, burntime, replacements);
4579 craftdef->registerCraft(def);
4583 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4587 return 0; /* number of results */
4590 // setting_set(name, value)
4591 static int l_setting_set(lua_State *L)
4593 const char *name = luaL_checkstring(L, 1);
4594 const char *value = luaL_checkstring(L, 2);
4595 g_settings->set(name, value);
4599 // setting_get(name)
4600 static int l_setting_get(lua_State *L)
4602 const char *name = luaL_checkstring(L, 1);
4604 std::string value = g_settings->get(name);
4605 lua_pushstring(L, value.c_str());
4606 } catch(SettingNotFoundException &e){
4612 // setting_getbool(name)
4613 static int l_setting_getbool(lua_State *L)
4615 const char *name = luaL_checkstring(L, 1);
4617 bool value = g_settings->getBool(name);
4618 lua_pushboolean(L, value);
4619 } catch(SettingNotFoundException &e){
4625 // chat_send_all(text)
4626 static int l_chat_send_all(lua_State *L)
4628 const char *text = luaL_checkstring(L, 1);
4629 // Get server from registry
4630 Server *server = get_server(L);
4632 server->notifyPlayers(narrow_to_wide(text));
4636 // chat_send_player(name, text)
4637 static int l_chat_send_player(lua_State *L)
4639 const char *name = luaL_checkstring(L, 1);
4640 const char *text = luaL_checkstring(L, 2);
4641 // Get server from registry
4642 Server *server = get_server(L);
4644 server->notifyPlayer(name, narrow_to_wide(text));
4648 // get_player_privs(name, text)
4649 static int l_get_player_privs(lua_State *L)
4651 const char *name = luaL_checkstring(L, 1);
4652 // Get server from registry
4653 Server *server = get_server(L);
4656 int table = lua_gettop(L);
4657 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4658 for(std::set<std::string>::const_iterator
4659 i = privs_s.begin(); i != privs_s.end(); i++){
4660 lua_pushboolean(L, true);
4661 lua_setfield(L, table, i->c_str());
4663 lua_pushvalue(L, table);
4668 static int l_get_ban_list(lua_State *L)
4670 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4674 // get_ban_description()
4675 static int l_get_ban_description(lua_State *L)
4677 const char * ip_or_name = luaL_checkstring(L, 1);
4678 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4683 static int l_ban_player(lua_State *L)
4685 const char * name = luaL_checkstring(L, 1);
4686 Player *player = get_env(L)->getPlayer(name);
4689 lua_pushboolean(L, false); // no such player
4694 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4695 std::string ip_str = addr.serializeString();
4696 get_server(L)->setIpBanned(ip_str, name);
4698 catch(con::PeerNotFoundException) // unlikely
4700 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4701 lua_pushboolean(L, false); // error
4704 lua_pushboolean(L, true);
4708 // unban_player_or_ip()
4709 static int l_unban_player_of_ip(lua_State *L)
4711 const char * ip_or_name = luaL_checkstring(L, 1);
4712 get_server(L)->unsetIpBanned(ip_or_name);
4713 lua_pushboolean(L, true);
4717 // get_inventory(location)
4718 static int l_get_inventory(lua_State *L)
4720 InventoryLocation loc;
4722 std::string type = checkstringfield(L, 1, "type");
4723 if(type == "player"){
4724 std::string name = checkstringfield(L, 1, "name");
4725 loc.setPlayer(name);
4726 } else if(type == "node"){
4727 lua_getfield(L, 1, "pos");
4728 v3s16 pos = check_v3s16(L, -1);
4729 loc.setNodeMeta(pos);
4730 } else if(type == "detached"){
4731 std::string name = checkstringfield(L, 1, "name");
4732 loc.setDetached(name);
4735 if(get_server(L)->getInventory(loc) != NULL)
4736 InvRef::create(L, loc);
4742 // create_detached_inventory_raw(name)
4743 static int l_create_detached_inventory_raw(lua_State *L)
4745 const char *name = luaL_checkstring(L, 1);
4746 if(get_server(L)->createDetachedInventory(name) != NULL){
4747 InventoryLocation loc;
4748 loc.setDetached(name);
4749 InvRef::create(L, loc);
4756 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4757 static int l_get_dig_params(lua_State *L)
4759 std::map<std::string, int> groups;
4760 read_groups(L, 1, groups);
4761 ToolCapabilities tp = read_tool_capabilities(L, 2);
4762 if(lua_isnoneornil(L, 3))
4763 push_dig_params(L, getDigParams(groups, &tp));
4765 push_dig_params(L, getDigParams(groups, &tp,
4766 luaL_checknumber(L, 3)));
4770 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4771 static int l_get_hit_params(lua_State *L)
4773 std::map<std::string, int> groups;
4774 read_groups(L, 1, groups);
4775 ToolCapabilities tp = read_tool_capabilities(L, 2);
4776 if(lua_isnoneornil(L, 3))
4777 push_hit_params(L, getHitParams(groups, &tp));
4779 push_hit_params(L, getHitParams(groups, &tp,
4780 luaL_checknumber(L, 3)));
4784 // get_current_modname()
4785 static int l_get_current_modname(lua_State *L)
4787 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4791 // get_modpath(modname)
4792 static int l_get_modpath(lua_State *L)
4794 std::string modname = luaL_checkstring(L, 1);
4796 if(modname == "__builtin"){
4797 std::string path = get_server(L)->getBuiltinLuaPath();
4798 lua_pushstring(L, path.c_str());
4801 const ModSpec *mod = get_server(L)->getModSpec(modname);
4806 lua_pushstring(L, mod->path.c_str());
4811 // the returned list is sorted alphabetically for you
4812 static int l_get_modnames(lua_State *L)
4814 // Get a list of mods
4815 core::list<std::string> mods_unsorted, mods_sorted;
4816 get_server(L)->getModNames(mods_unsorted);
4818 // Take unsorted items from mods_unsorted and sort them into
4819 // mods_sorted; not great performance but the number of mods on a
4820 // server will likely be small.
4821 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4822 i != mods_unsorted.end(); i++)
4825 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4826 x != mods_unsorted.end(); x++)
4828 // I doubt anybody using Minetest will be using
4829 // anything not ASCII based :)
4830 if((*i).compare(*x) <= 0)
4832 mods_sorted.insert_before(x, *i);
4838 mods_sorted.push_back(*i);
4841 // Get the table insertion function from Lua.
4842 lua_getglobal(L, "table");
4843 lua_getfield(L, -1, "insert");
4844 int insertion_func = lua_gettop(L);
4846 // Package them up for Lua
4848 int new_table = lua_gettop(L);
4849 core::list<std::string>::Iterator i = mods_sorted.begin();
4850 while(i != mods_sorted.end())
4852 lua_pushvalue(L, insertion_func);
4853 lua_pushvalue(L, new_table);
4854 lua_pushstring(L, (*i).c_str());
4855 if(lua_pcall(L, 2, 0, 0) != 0)
4857 script_error(L, "error: %s", lua_tostring(L, -1));
4865 static int l_get_worldpath(lua_State *L)
4867 std::string worldpath = get_server(L)->getWorldPath();
4868 lua_pushstring(L, worldpath.c_str());
4872 // sound_play(spec, parameters)
4873 static int l_sound_play(lua_State *L)
4875 SimpleSoundSpec spec;
4876 read_soundspec(L, 1, spec);
4877 ServerSoundParams params;
4878 read_server_sound_params(L, 2, params);
4879 s32 handle = get_server(L)->playSound(spec, params);
4880 lua_pushinteger(L, handle);
4884 // sound_stop(handle)
4885 static int l_sound_stop(lua_State *L)
4887 int handle = luaL_checkinteger(L, 1);
4888 get_server(L)->stopSound(handle);
4892 // is_singleplayer()
4893 static int l_is_singleplayer(lua_State *L)
4895 lua_pushboolean(L, get_server(L)->isSingleplayer());
4899 // get_password_hash(name, raw_password)
4900 static int l_get_password_hash(lua_State *L)
4902 std::string name = luaL_checkstring(L, 1);
4903 std::string raw_password = luaL_checkstring(L, 2);
4904 std::string hash = translatePassword(name,
4905 narrow_to_wide(raw_password));
4906 lua_pushstring(L, hash.c_str());
4910 // notify_authentication_modified(name)
4911 static int l_notify_authentication_modified(lua_State *L)
4913 std::string name = "";
4914 if(lua_isstring(L, 1))
4915 name = lua_tostring(L, 1);
4916 get_server(L)->reportPrivsModified(name);
4920 // get_craft_result(input)
4921 static int l_get_craft_result(lua_State *L)
4924 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4925 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4926 es_CraftMethod, CRAFT_METHOD_NORMAL);
4928 lua_getfield(L, input_i, "width");
4929 if(lua_isnumber(L, -1))
4930 width = luaL_checkinteger(L, -1);
4932 lua_getfield(L, input_i, "items");
4933 std::vector<ItemStack> items = read_items(L, -1);
4934 lua_pop(L, 1); // items
4936 IGameDef *gdef = get_server(L);
4937 ICraftDefManager *cdef = gdef->cdef();
4938 CraftInput input(method, width, items);
4940 bool got = cdef->getCraftResult(input, output, true, gdef);
4941 lua_newtable(L); // output table
4944 item.deSerialize(output.item, gdef->idef());
4945 LuaItemStack::create(L, item);
4946 lua_setfield(L, -2, "item");
4947 setintfield(L, -1, "time", output.time);
4949 LuaItemStack::create(L, ItemStack());
4950 lua_setfield(L, -2, "item");
4951 setintfield(L, -1, "time", 0);
4953 lua_newtable(L); // decremented input table
4954 lua_pushstring(L, method_s.c_str());
4955 lua_setfield(L, -2, "method");
4956 lua_pushinteger(L, width);
4957 lua_setfield(L, -2, "width");
4958 push_items(L, input.items);
4959 lua_setfield(L, -2, "items");
4963 // get_craft_recipe(result item)
4964 static int l_get_craft_recipe(lua_State *L)
4969 std::string o_item = luaL_checkstring(L,input_i);
4971 IGameDef *gdef = get_server(L);
4972 ICraftDefManager *cdef = gdef->cdef();
4974 CraftOutput output(o_item,0);
4975 bool got = cdef->getCraftRecipe(input, output, gdef);
4976 lua_newtable(L); // output table
4979 for(std::vector<ItemStack>::const_iterator
4980 i = input.items.begin();
4981 i != input.items.end(); i++, k++)
4987 sprintf(tmp,"%d",k);
4988 lua_pushstring(L,tmp);
4989 lua_pushstring(L,i->name.c_str());
4990 lua_settable(L, -3);
4992 lua_setfield(L, -2, "items");
4993 setintfield(L, -1, "width", input.width);
4994 switch (input.method) {
4995 case CRAFT_METHOD_NORMAL:
4996 lua_pushstring(L,"normal");
4998 case CRAFT_METHOD_COOKING:
4999 lua_pushstring(L,"cooking");
5001 case CRAFT_METHOD_FUEL:
5002 lua_pushstring(L,"fuel");
5005 lua_pushstring(L,"unknown");
5007 lua_setfield(L, -2, "type");
5010 lua_setfield(L, -2, "items");
5011 setintfield(L, -1, "width", 0);
5016 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5017 static int l_rollback_get_last_node_actor(lua_State *L)
5019 v3s16 p = read_v3s16(L, 1);
5020 int range = luaL_checknumber(L, 2);
5021 int seconds = luaL_checknumber(L, 3);
5022 Server *server = get_server(L);
5023 IRollbackManager *rollback = server->getRollbackManager();
5025 int act_seconds = 0;
5026 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5027 lua_pushstring(L, actor.c_str());
5028 push_v3s16(L, act_p);
5029 lua_pushnumber(L, act_seconds);
5033 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5034 static int l_rollback_revert_actions_by(lua_State *L)
5036 std::string actor = luaL_checkstring(L, 1);
5037 int seconds = luaL_checknumber(L, 2);
5038 Server *server = get_server(L);
5039 IRollbackManager *rollback = server->getRollbackManager();
5040 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5041 std::list<std::string> log;
5042 bool success = server->rollbackRevertActions(actions, &log);
5043 // Push boolean result
5044 lua_pushboolean(L, success);
5045 // Get the table insert function and push the log table
5046 lua_getglobal(L, "table");
5047 lua_getfield(L, -1, "insert");
5048 int table_insert = lua_gettop(L);
5050 int table = lua_gettop(L);
5051 for(std::list<std::string>::const_iterator i = log.begin();
5052 i != log.end(); i++)
5054 lua_pushvalue(L, table_insert);
5055 lua_pushvalue(L, table);
5056 lua_pushstring(L, i->c_str());
5057 if(lua_pcall(L, 2, 0, 0))
5058 script_error(L, "error: %s", lua_tostring(L, -1));
5060 lua_remove(L, -2); // Remove table
5061 lua_remove(L, -2); // Remove insert
5065 static const struct luaL_Reg minetest_f [] = {
5068 {"request_shutdown", l_request_shutdown},
5069 {"get_server_status", l_get_server_status},
5070 {"register_item_raw", l_register_item_raw},
5071 {"register_alias_raw", l_register_alias_raw},
5072 {"register_craft", l_register_craft},
5073 {"setting_set", l_setting_set},
5074 {"setting_get", l_setting_get},
5075 {"setting_getbool", l_setting_getbool},
5076 {"chat_send_all", l_chat_send_all},
5077 {"chat_send_player", l_chat_send_player},
5078 {"get_player_privs", l_get_player_privs},
5079 {"get_ban_list", l_get_ban_list},
5080 {"get_ban_description", l_get_ban_description},
5081 {"ban_player", l_ban_player},
5082 {"unban_player_or_ip", l_unban_player_of_ip},
5083 {"get_inventory", l_get_inventory},
5084 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5085 {"get_dig_params", l_get_dig_params},
5086 {"get_hit_params", l_get_hit_params},
5087 {"get_current_modname", l_get_current_modname},
5088 {"get_modpath", l_get_modpath},
5089 {"get_modnames", l_get_modnames},
5090 {"get_worldpath", l_get_worldpath},
5091 {"sound_play", l_sound_play},
5092 {"sound_stop", l_sound_stop},
5093 {"is_singleplayer", l_is_singleplayer},
5094 {"get_password_hash", l_get_password_hash},
5095 {"notify_authentication_modified", l_notify_authentication_modified},
5096 {"get_craft_result", l_get_craft_result},
5097 {"get_craft_recipe", l_get_craft_recipe},
5098 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5099 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5104 Main export function
5107 void scriptapi_export(lua_State *L, Server *server)
5110 assert(lua_checkstack(L, 20));
5111 verbosestream<<"scriptapi_export()"<<std::endl;
5112 StackUnroller stack_unroller(L);
5114 // Store server as light userdata in registry
5115 lua_pushlightuserdata(L, server);
5116 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5118 // Register global functions in table minetest
5120 luaL_register(L, NULL, minetest_f);
5121 lua_setglobal(L, "minetest");
5123 // Get the main minetest table
5124 lua_getglobal(L, "minetest");
5126 // Add tables to minetest
5128 lua_setfield(L, -2, "object_refs");
5130 lua_setfield(L, -2, "luaentities");
5132 // Register wrappers
5133 LuaItemStack::Register(L);
5134 InvRef::Register(L);
5135 NodeMetaRef::Register(L);
5136 NodeTimerRef::Register(L);
5137 ObjectRef::Register(L);
5138 EnvRef::Register(L);
5139 LuaPseudoRandom::Register(L);
5140 LuaPerlinNoise::Register(L);
5143 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5144 const std::string &modname)
5146 ModNameStorer modnamestorer(L, modname);
5148 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5150 errorstream<<"Error loading mod \""<<modname
5151 <<"\": modname does not follow naming conventions: "
5152 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5156 bool success = false;
5159 success = script_load(L, scriptpath.c_str());
5162 errorstream<<"Error loading mod \""<<modname
5163 <<"\": "<<e.what()<<std::endl;
5169 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5172 assert(lua_checkstack(L, 20));
5173 verbosestream<<"scriptapi_add_environment"<<std::endl;
5174 StackUnroller stack_unroller(L);
5176 // Create EnvRef on stack
5177 EnvRef::create(L, env);
5178 int envref = lua_gettop(L);
5180 // minetest.env = envref
5181 lua_getglobal(L, "minetest");
5182 luaL_checktype(L, -1, LUA_TTABLE);
5183 lua_pushvalue(L, envref);
5184 lua_setfield(L, -2, "env");
5186 // Store environment as light userdata in registry
5187 lua_pushlightuserdata(L, env);
5188 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5191 Add ActiveBlockModifiers to environment
5194 // Get minetest.registered_abms
5195 lua_getglobal(L, "minetest");
5196 lua_getfield(L, -1, "registered_abms");
5197 luaL_checktype(L, -1, LUA_TTABLE);
5198 int registered_abms = lua_gettop(L);
5200 if(lua_istable(L, registered_abms)){
5201 int table = lua_gettop(L);
5203 while(lua_next(L, table) != 0){
5204 // key at index -2 and value at index -1
5205 int id = lua_tonumber(L, -2);
5206 int current_abm = lua_gettop(L);
5208 std::set<std::string> trigger_contents;
5209 lua_getfield(L, current_abm, "nodenames");
5210 if(lua_istable(L, -1)){
5211 int table = lua_gettop(L);
5213 while(lua_next(L, table) != 0){
5214 // key at index -2 and value at index -1
5215 luaL_checktype(L, -1, LUA_TSTRING);
5216 trigger_contents.insert(lua_tostring(L, -1));
5217 // removes value, keeps key for next iteration
5220 } else if(lua_isstring(L, -1)){
5221 trigger_contents.insert(lua_tostring(L, -1));
5225 std::set<std::string> required_neighbors;
5226 lua_getfield(L, current_abm, "neighbors");
5227 if(lua_istable(L, -1)){
5228 int table = lua_gettop(L);
5230 while(lua_next(L, table) != 0){
5231 // key at index -2 and value at index -1
5232 luaL_checktype(L, -1, LUA_TSTRING);
5233 required_neighbors.insert(lua_tostring(L, -1));
5234 // removes value, keeps key for next iteration
5237 } else if(lua_isstring(L, -1)){
5238 required_neighbors.insert(lua_tostring(L, -1));
5242 float trigger_interval = 10.0;
5243 getfloatfield(L, current_abm, "interval", trigger_interval);
5245 int trigger_chance = 50;
5246 getintfield(L, current_abm, "chance", trigger_chance);
5248 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5249 required_neighbors, trigger_interval, trigger_chance);
5251 env->addActiveBlockModifier(abm);
5253 // removes value, keeps key for next iteration
5261 // Dump stack top with the dump2 function
5262 static void dump2(lua_State *L, const char *name)
5264 // Dump object (debug)
5265 lua_getglobal(L, "dump2");
5266 luaL_checktype(L, -1, LUA_TFUNCTION);
5267 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5268 lua_pushstring(L, name);
5269 if(lua_pcall(L, 2, 0, 0))
5270 script_error(L, "error: %s", lua_tostring(L, -1));
5278 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5281 assert(lua_checkstack(L, 20));
5282 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5283 StackUnroller stack_unroller(L);
5285 // Create object on stack
5286 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5287 int object = lua_gettop(L);
5289 // Get minetest.object_refs table
5290 lua_getglobal(L, "minetest");
5291 lua_getfield(L, -1, "object_refs");
5292 luaL_checktype(L, -1, LUA_TTABLE);
5293 int objectstable = lua_gettop(L);
5295 // object_refs[id] = object
5296 lua_pushnumber(L, cobj->getId()); // Push id
5297 lua_pushvalue(L, object); // Copy object to top of stack
5298 lua_settable(L, objectstable);
5301 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5304 assert(lua_checkstack(L, 20));
5305 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5306 StackUnroller stack_unroller(L);
5308 // Get minetest.object_refs table
5309 lua_getglobal(L, "minetest");
5310 lua_getfield(L, -1, "object_refs");
5311 luaL_checktype(L, -1, LUA_TTABLE);
5312 int objectstable = lua_gettop(L);
5314 // Get object_refs[id]
5315 lua_pushnumber(L, cobj->getId()); // Push id
5316 lua_gettable(L, objectstable);
5317 // Set object reference to NULL
5318 ObjectRef::set_null(L);
5319 lua_pop(L, 1); // pop object
5321 // Set object_refs[id] = nil
5322 lua_pushnumber(L, cobj->getId()); // Push id
5324 lua_settable(L, objectstable);
5331 // What scriptapi_run_callbacks does with the return values of callbacks.
5332 // Regardless of the mode, if only one callback is defined,
5333 // its return value is the total return value.
5334 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5335 enum RunCallbacksMode
5337 // Returns the return value of the first callback
5338 // Returns nil if list of callbacks is empty
5339 RUN_CALLBACKS_MODE_FIRST,
5340 // Returns the return value of the last callback
5341 // Returns nil if list of callbacks is empty
5342 RUN_CALLBACKS_MODE_LAST,
5343 // If any callback returns a false value, the first such is returned
5344 // Otherwise, the first callback's return value (trueish) is returned
5345 // Returns true if list of callbacks is empty
5346 RUN_CALLBACKS_MODE_AND,
5347 // Like above, but stops calling callbacks (short circuit)
5348 // after seeing the first false value
5349 RUN_CALLBACKS_MODE_AND_SC,
5350 // If any callback returns a true value, the first such is returned
5351 // Otherwise, the first callback's return value (falseish) is returned
5352 // Returns false if list of callbacks is empty
5353 RUN_CALLBACKS_MODE_OR,
5354 // Like above, but stops calling callbacks (short circuit)
5355 // after seeing the first true value
5356 RUN_CALLBACKS_MODE_OR_SC,
5357 // Note: "a true value" and "a false value" refer to values that
5358 // are converted by lua_toboolean to true or false, respectively.
5361 // Push the list of callbacks (a lua table).
5362 // Then push nargs arguments.
5363 // Then call this function, which
5364 // - runs the callbacks
5365 // - removes the table and arguments from the lua stack
5366 // - pushes the return value, computed depending on mode
5367 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5368 RunCallbacksMode mode)
5370 // Insert the return value into the lua stack, below the table
5371 assert(lua_gettop(L) >= nargs + 1);
5373 lua_insert(L, -(nargs + 1) - 1);
5374 // Stack now looks like this:
5375 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5377 int rv = lua_gettop(L) - nargs - 1;
5379 int arg = table + 1;
5381 luaL_checktype(L, table, LUA_TTABLE);
5385 bool first_loop = true;
5386 while(lua_next(L, table) != 0){
5387 // key at index -2 and value at index -1
5388 luaL_checktype(L, -1, LUA_TFUNCTION);
5390 for(int i = 0; i < nargs; i++)
5391 lua_pushvalue(L, arg+i);
5392 if(lua_pcall(L, nargs, 1, 0))
5393 script_error(L, "error: %s", lua_tostring(L, -1));
5395 // Move return value to designated space in stack
5398 // Result of first callback is always moved
5402 // Otherwise, what happens depends on the mode
5403 if(mode == RUN_CALLBACKS_MODE_FIRST)
5405 else if(mode == RUN_CALLBACKS_MODE_LAST)
5407 else if(mode == RUN_CALLBACKS_MODE_AND ||
5408 mode == RUN_CALLBACKS_MODE_AND_SC){
5409 if(lua_toboolean(L, rv) == true &&
5410 lua_toboolean(L, -1) == false)
5415 else if(mode == RUN_CALLBACKS_MODE_OR ||
5416 mode == RUN_CALLBACKS_MODE_OR_SC){
5417 if(lua_toboolean(L, rv) == false &&
5418 lua_toboolean(L, -1) == true)
5427 // Handle short circuit modes
5428 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5429 lua_toboolean(L, rv) == false)
5431 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5432 lua_toboolean(L, rv) == true)
5435 // value removed, keep key for next iteration
5438 // Remove stuff from stack, leaving only the return value
5441 // Fix return value in case no callbacks were called
5443 if(mode == RUN_CALLBACKS_MODE_AND ||
5444 mode == RUN_CALLBACKS_MODE_AND_SC){
5446 lua_pushboolean(L, true);
5448 else if(mode == RUN_CALLBACKS_MODE_OR ||
5449 mode == RUN_CALLBACKS_MODE_OR_SC){
5451 lua_pushboolean(L, false);
5456 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5457 const std::string &message)
5460 assert(lua_checkstack(L, 20));
5461 StackUnroller stack_unroller(L);
5463 // Get minetest.registered_on_chat_messages
5464 lua_getglobal(L, "minetest");
5465 lua_getfield(L, -1, "registered_on_chat_messages");
5467 lua_pushstring(L, name.c_str());
5468 lua_pushstring(L, message.c_str());
5469 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5470 bool ate = lua_toboolean(L, -1);
5474 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5477 assert(lua_checkstack(L, 20));
5478 StackUnroller stack_unroller(L);
5480 // Get minetest.registered_on_newplayers
5481 lua_getglobal(L, "minetest");
5482 lua_getfield(L, -1, "registered_on_newplayers");
5484 objectref_get_or_create(L, player);
5485 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5488 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5491 assert(lua_checkstack(L, 20));
5492 StackUnroller stack_unroller(L);
5494 // Get minetest.registered_on_dieplayers
5495 lua_getglobal(L, "minetest");
5496 lua_getfield(L, -1, "registered_on_dieplayers");
5498 objectref_get_or_create(L, player);
5499 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5502 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5505 assert(lua_checkstack(L, 20));
5506 StackUnroller stack_unroller(L);
5508 // Get minetest.registered_on_respawnplayers
5509 lua_getglobal(L, "minetest");
5510 lua_getfield(L, -1, "registered_on_respawnplayers");
5512 objectref_get_or_create(L, player);
5513 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5514 bool positioning_handled_by_some = lua_toboolean(L, -1);
5515 return positioning_handled_by_some;
5518 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5521 assert(lua_checkstack(L, 20));
5522 StackUnroller stack_unroller(L);
5524 // Get minetest.registered_on_joinplayers
5525 lua_getglobal(L, "minetest");
5526 lua_getfield(L, -1, "registered_on_joinplayers");
5528 objectref_get_or_create(L, player);
5529 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5532 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5535 assert(lua_checkstack(L, 20));
5536 StackUnroller stack_unroller(L);
5538 // Get minetest.registered_on_leaveplayers
5539 lua_getglobal(L, "minetest");
5540 lua_getfield(L, -1, "registered_on_leaveplayers");
5542 objectref_get_or_create(L, player);
5543 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5546 static void get_auth_handler(lua_State *L)
5548 lua_getglobal(L, "minetest");
5549 lua_getfield(L, -1, "registered_auth_handler");
5550 if(lua_isnil(L, -1)){
5552 lua_getfield(L, -1, "builtin_auth_handler");
5554 if(lua_type(L, -1) != LUA_TTABLE)
5555 throw LuaError(L, "Authentication handler table not valid");
5558 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5559 std::string *dst_password, std::set<std::string> *dst_privs)
5562 assert(lua_checkstack(L, 20));
5563 StackUnroller stack_unroller(L);
5565 get_auth_handler(L);
5566 lua_getfield(L, -1, "get_auth");
5567 if(lua_type(L, -1) != LUA_TFUNCTION)
5568 throw LuaError(L, "Authentication handler missing get_auth");
5569 lua_pushstring(L, playername.c_str());
5570 if(lua_pcall(L, 1, 1, 0))
5571 script_error(L, "error: %s", lua_tostring(L, -1));
5573 // nil = login not allowed
5574 if(lua_isnil(L, -1))
5576 luaL_checktype(L, -1, LUA_TTABLE);
5578 std::string password;
5579 bool found = getstringfield(L, -1, "password", password);
5581 throw LuaError(L, "Authentication handler didn't return password");
5583 *dst_password = password;
5585 lua_getfield(L, -1, "privileges");
5586 if(!lua_istable(L, -1))
5588 "Authentication handler didn't return privilege table");
5590 read_privileges(L, -1, *dst_privs);
5596 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5597 const std::string &password)
5600 assert(lua_checkstack(L, 20));
5601 StackUnroller stack_unroller(L);
5603 get_auth_handler(L);
5604 lua_getfield(L, -1, "create_auth");
5605 if(lua_type(L, -1) != LUA_TFUNCTION)
5606 throw LuaError(L, "Authentication handler missing create_auth");
5607 lua_pushstring(L, playername.c_str());
5608 lua_pushstring(L, password.c_str());
5609 if(lua_pcall(L, 2, 0, 0))
5610 script_error(L, "error: %s", lua_tostring(L, -1));
5613 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5614 const std::string &password)
5617 assert(lua_checkstack(L, 20));
5618 StackUnroller stack_unroller(L);
5620 get_auth_handler(L);
5621 lua_getfield(L, -1, "set_password");
5622 if(lua_type(L, -1) != LUA_TFUNCTION)
5623 throw LuaError(L, "Authentication handler missing set_password");
5624 lua_pushstring(L, playername.c_str());
5625 lua_pushstring(L, password.c_str());
5626 if(lua_pcall(L, 2, 1, 0))
5627 script_error(L, "error: %s", lua_tostring(L, -1));
5628 return lua_toboolean(L, -1);
5635 void scriptapi_on_player_receive_fields(lua_State *L,
5636 ServerActiveObject *player,
5637 const std::string &formname,
5638 const std::map<std::string, std::string> &fields)
5641 assert(lua_checkstack(L, 20));
5642 StackUnroller stack_unroller(L);
5644 // Get minetest.registered_on_chat_messages
5645 lua_getglobal(L, "minetest");
5646 lua_getfield(L, -1, "registered_on_player_receive_fields");
5649 objectref_get_or_create(L, player);
5651 lua_pushstring(L, formname.c_str());
5654 for(std::map<std::string, std::string>::const_iterator
5655 i = fields.begin(); i != fields.end(); i++){
5656 const std::string &name = i->first;
5657 const std::string &value = i->second;
5658 lua_pushstring(L, name.c_str());
5659 lua_pushlstring(L, value.c_str(), value.size());
5660 lua_settable(L, -3);
5662 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5666 item callbacks and node callbacks
5669 // Retrieves minetest.registered_items[name][callbackname]
5670 // If that is nil or on error, return false and stack is unchanged
5671 // If that is a function, returns true and pushes the
5672 // function onto the stack
5673 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5674 // is tried instead so unknown items can still be manipulated to some degree
5675 static bool get_item_callback(lua_State *L,
5676 const char *name, const char *callbackname)
5678 lua_getglobal(L, "minetest");
5679 lua_getfield(L, -1, "registered_items");
5681 luaL_checktype(L, -1, LUA_TTABLE);
5682 lua_getfield(L, -1, name);
5684 // Should be a table
5685 if(lua_type(L, -1) != LUA_TTABLE)
5687 // Report error and clean up
5688 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5691 // Try minetest.nodedef_default instead
5692 lua_getglobal(L, "minetest");
5693 lua_getfield(L, -1, "nodedef_default");
5695 luaL_checktype(L, -1, LUA_TTABLE);
5697 lua_getfield(L, -1, callbackname);
5699 // Should be a function or nil
5700 if(lua_type(L, -1) == LUA_TFUNCTION)
5704 else if(lua_isnil(L, -1))
5711 errorstream<<"Item \""<<name<<"\" callback \""
5712 <<callbackname<<" is not a function"<<std::endl;
5718 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5719 ServerActiveObject *dropper, v3f pos)
5722 assert(lua_checkstack(L, 20));
5723 StackUnroller stack_unroller(L);
5725 // Push callback function on stack
5726 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5730 LuaItemStack::create(L, item);
5731 objectref_get_or_create(L, dropper);
5732 pushFloatPos(L, pos);
5733 if(lua_pcall(L, 3, 1, 0))
5734 script_error(L, "error: %s", lua_tostring(L, -1));
5735 if(!lua_isnil(L, -1))
5736 item = read_item(L, -1);
5740 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5741 ServerActiveObject *placer, const PointedThing &pointed)
5744 assert(lua_checkstack(L, 20));
5745 StackUnroller stack_unroller(L);
5747 // Push callback function on stack
5748 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5752 LuaItemStack::create(L, item);
5753 objectref_get_or_create(L, placer);
5754 push_pointed_thing(L, pointed);
5755 if(lua_pcall(L, 3, 1, 0))
5756 script_error(L, "error: %s", lua_tostring(L, -1));
5757 if(!lua_isnil(L, -1))
5758 item = read_item(L, -1);
5762 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5763 ServerActiveObject *user, const PointedThing &pointed)
5766 assert(lua_checkstack(L, 20));
5767 StackUnroller stack_unroller(L);
5769 // Push callback function on stack
5770 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5774 LuaItemStack::create(L, item);
5775 objectref_get_or_create(L, user);
5776 push_pointed_thing(L, pointed);
5777 if(lua_pcall(L, 3, 1, 0))
5778 script_error(L, "error: %s", lua_tostring(L, -1));
5779 if(!lua_isnil(L, -1))
5780 item = read_item(L, -1);
5784 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5785 ServerActiveObject *puncher)
5788 assert(lua_checkstack(L, 20));
5789 StackUnroller stack_unroller(L);
5791 INodeDefManager *ndef = get_server(L)->ndef();
5793 // Push callback function on stack
5794 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5799 pushnode(L, node, ndef);
5800 objectref_get_or_create(L, puncher);
5801 if(lua_pcall(L, 3, 0, 0))
5802 script_error(L, "error: %s", lua_tostring(L, -1));
5806 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5807 ServerActiveObject *digger)
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_dig"))
5821 pushnode(L, node, ndef);
5822 objectref_get_or_create(L, digger);
5823 if(lua_pcall(L, 3, 0, 0))
5824 script_error(L, "error: %s", lua_tostring(L, -1));
5828 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5831 assert(lua_checkstack(L, 20));
5832 StackUnroller stack_unroller(L);
5834 INodeDefManager *ndef = get_server(L)->ndef();
5836 // Push callback function on stack
5837 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5842 if(lua_pcall(L, 1, 0, 0))
5843 script_error(L, "error: %s", lua_tostring(L, -1));
5846 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5849 assert(lua_checkstack(L, 20));
5850 StackUnroller stack_unroller(L);
5852 INodeDefManager *ndef = get_server(L)->ndef();
5854 // Push callback function on stack
5855 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5860 if(lua_pcall(L, 1, 0, 0))
5861 script_error(L, "error: %s", lua_tostring(L, -1));
5864 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5867 assert(lua_checkstack(L, 20));
5868 StackUnroller stack_unroller(L);
5870 INodeDefManager *ndef = get_server(L)->ndef();
5872 // Push callback function on stack
5873 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5878 pushnode(L, node, ndef);
5879 if(lua_pcall(L, 2, 0, 0))
5880 script_error(L, "error: %s", lua_tostring(L, -1));
5883 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5886 assert(lua_checkstack(L, 20));
5887 StackUnroller stack_unroller(L);
5889 INodeDefManager *ndef = get_server(L)->ndef();
5891 // Push callback function on stack
5892 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5897 lua_pushnumber(L,dtime);
5898 if(lua_pcall(L, 2, 1, 0))
5899 script_error(L, "error: %s", lua_tostring(L, -1));
5900 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5906 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5907 const std::string &formname,
5908 const std::map<std::string, std::string> &fields,
5909 ServerActiveObject *sender)
5912 assert(lua_checkstack(L, 20));
5913 StackUnroller stack_unroller(L);
5915 INodeDefManager *ndef = get_server(L)->ndef();
5917 // If node doesn't exist, we don't know what callback to call
5918 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5919 if(node.getContent() == CONTENT_IGNORE)
5922 // Push callback function on stack
5923 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5930 lua_pushstring(L, formname.c_str());
5933 for(std::map<std::string, std::string>::const_iterator
5934 i = fields.begin(); i != fields.end(); i++){
5935 const std::string &name = i->first;
5936 const std::string &value = i->second;
5937 lua_pushstring(L, name.c_str());
5938 lua_pushlstring(L, value.c_str(), value.size());
5939 lua_settable(L, -3);
5942 objectref_get_or_create(L, sender);
5943 if(lua_pcall(L, 4, 0, 0))
5944 script_error(L, "error: %s", lua_tostring(L, -1));
5948 Node metadata inventory callbacks
5951 // Return number of accepted items to be moved
5952 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5953 const std::string &from_list, int from_index,
5954 const std::string &to_list, int to_index,
5955 int count, ServerActiveObject *player)
5958 assert(lua_checkstack(L, 20));
5959 StackUnroller stack_unroller(L);
5961 INodeDefManager *ndef = get_server(L)->ndef();
5963 // If node doesn't exist, we don't know what callback to call
5964 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5965 if(node.getContent() == CONTENT_IGNORE)
5968 // Push callback function on stack
5969 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5970 "allow_metadata_inventory_move"))
5973 // function(pos, from_list, from_index, to_list, to_index, count, player)
5977 lua_pushstring(L, from_list.c_str());
5979 lua_pushinteger(L, from_index + 1);
5981 lua_pushstring(L, to_list.c_str());
5983 lua_pushinteger(L, to_index + 1);
5985 lua_pushinteger(L, count);
5987 objectref_get_or_create(L, player);
5988 if(lua_pcall(L, 7, 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_move should return a number");
5992 return luaL_checkinteger(L, -1);
5995 // Return number of accepted items to be put
5996 int scriptapi_nodemeta_inventory_allow_put(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_put"))
6016 // Call function(pos, listname, index, stack, 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_put should return a number");
6031 return luaL_checkinteger(L, -1);
6034 // Return number of accepted items to be taken
6035 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6036 const std::string &listname, int index, ItemStack &stack,
6037 ServerActiveObject *player)
6040 assert(lua_checkstack(L, 20));
6041 StackUnroller stack_unroller(L);
6043 INodeDefManager *ndef = get_server(L)->ndef();
6045 // If node doesn't exist, we don't know what callback to call
6046 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6047 if(node.getContent() == CONTENT_IGNORE)
6050 // Push callback function on stack
6051 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6052 "allow_metadata_inventory_take"))
6055 // Call function(pos, listname, index, count, player)
6059 lua_pushstring(L, listname.c_str());
6061 lua_pushinteger(L, index + 1);
6063 LuaItemStack::create(L, stack);
6065 objectref_get_or_create(L, player);
6066 if(lua_pcall(L, 5, 1, 0))
6067 script_error(L, "error: %s", lua_tostring(L, -1));
6068 if(!lua_isnumber(L, -1))
6069 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6070 return luaL_checkinteger(L, -1);
6073 // Report moved items
6074 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6075 const std::string &from_list, int from_index,
6076 const std::string &to_list, int to_index,
6077 int count, ServerActiveObject *player)
6080 assert(lua_checkstack(L, 20));
6081 StackUnroller stack_unroller(L);
6083 INodeDefManager *ndef = get_server(L)->ndef();
6085 // If node doesn't exist, we don't know what callback to call
6086 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6087 if(node.getContent() == CONTENT_IGNORE)
6090 // Push callback function on stack
6091 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6092 "on_metadata_inventory_move"))
6095 // function(pos, from_list, from_index, to_list, to_index, count, player)
6099 lua_pushstring(L, from_list.c_str());
6101 lua_pushinteger(L, from_index + 1);
6103 lua_pushstring(L, to_list.c_str());
6105 lua_pushinteger(L, to_index + 1);
6107 lua_pushinteger(L, count);
6109 objectref_get_or_create(L, player);
6110 if(lua_pcall(L, 7, 0, 0))
6111 script_error(L, "error: %s", lua_tostring(L, -1));
6115 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6116 const std::string &listname, int index, ItemStack &stack,
6117 ServerActiveObject *player)
6120 assert(lua_checkstack(L, 20));
6121 StackUnroller stack_unroller(L);
6123 INodeDefManager *ndef = get_server(L)->ndef();
6125 // If node doesn't exist, we don't know what callback to call
6126 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6127 if(node.getContent() == CONTENT_IGNORE)
6130 // Push callback function on stack
6131 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6132 "on_metadata_inventory_put"))
6135 // Call function(pos, listname, index, stack, player)
6139 lua_pushstring(L, listname.c_str());
6141 lua_pushinteger(L, index + 1);
6143 LuaItemStack::create(L, stack);
6145 objectref_get_or_create(L, player);
6146 if(lua_pcall(L, 5, 0, 0))
6147 script_error(L, "error: %s", lua_tostring(L, -1));
6150 // Report taken items
6151 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6152 const std::string &listname, int index, ItemStack &stack,
6153 ServerActiveObject *player)
6156 assert(lua_checkstack(L, 20));
6157 StackUnroller stack_unroller(L);
6159 INodeDefManager *ndef = get_server(L)->ndef();
6161 // If node doesn't exist, we don't know what callback to call
6162 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6163 if(node.getContent() == CONTENT_IGNORE)
6166 // Push callback function on stack
6167 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6168 "on_metadata_inventory_take"))
6171 // Call function(pos, listname, index, stack, player)
6175 lua_pushstring(L, listname.c_str());
6177 lua_pushinteger(L, index + 1);
6179 LuaItemStack::create(L, stack);
6181 objectref_get_or_create(L, player);
6182 if(lua_pcall(L, 5, 0, 0))
6183 script_error(L, "error: %s", lua_tostring(L, -1));
6187 Detached inventory callbacks
6190 // Retrieves minetest.detached_inventories[name][callbackname]
6191 // If that is nil or on error, return false and stack is unchanged
6192 // If that is a function, returns true and pushes the
6193 // function onto the stack
6194 static bool get_detached_inventory_callback(lua_State *L,
6195 const std::string &name, const char *callbackname)
6197 lua_getglobal(L, "minetest");
6198 lua_getfield(L, -1, "detached_inventories");
6200 luaL_checktype(L, -1, LUA_TTABLE);
6201 lua_getfield(L, -1, name.c_str());
6203 // Should be a table
6204 if(lua_type(L, -1) != LUA_TTABLE)
6206 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6210 lua_getfield(L, -1, callbackname);
6212 // Should be a function or nil
6213 if(lua_type(L, -1) == LUA_TFUNCTION)
6217 else if(lua_isnil(L, -1))
6224 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6225 <<callbackname<<"\" is not a function"<<std::endl;
6231 // Return number of accepted items to be moved
6232 int scriptapi_detached_inventory_allow_move(lua_State *L,
6233 const std::string &name,
6234 const std::string &from_list, int from_index,
6235 const std::string &to_list, int to_index,
6236 int count, ServerActiveObject *player)
6239 assert(lua_checkstack(L, 20));
6240 StackUnroller stack_unroller(L);
6242 // Push callback function on stack
6243 if(!get_detached_inventory_callback(L, name, "allow_move"))
6246 // function(inv, from_list, from_index, to_list, to_index, count, player)
6248 InventoryLocation loc;
6249 loc.setDetached(name);
6250 InvRef::create(L, loc);
6252 lua_pushstring(L, from_list.c_str());
6254 lua_pushinteger(L, from_index + 1);
6256 lua_pushstring(L, to_list.c_str());
6258 lua_pushinteger(L, to_index + 1);
6260 lua_pushinteger(L, count);
6262 objectref_get_or_create(L, player);
6263 if(lua_pcall(L, 7, 1, 0))
6264 script_error(L, "error: %s", lua_tostring(L, -1));
6265 if(!lua_isnumber(L, -1))
6266 throw LuaError(L, "allow_move should return a number");
6267 return luaL_checkinteger(L, -1);
6270 // Return number of accepted items to be put
6271 int scriptapi_detached_inventory_allow_put(lua_State *L,
6272 const std::string &name,
6273 const std::string &listname, int index, ItemStack &stack,
6274 ServerActiveObject *player)
6277 assert(lua_checkstack(L, 20));
6278 StackUnroller stack_unroller(L);
6280 // Push callback function on stack
6281 if(!get_detached_inventory_callback(L, name, "allow_put"))
6282 return stack.count; // All will be accepted
6284 // Call function(inv, listname, index, stack, player)
6286 InventoryLocation loc;
6287 loc.setDetached(name);
6288 InvRef::create(L, loc);
6290 lua_pushstring(L, listname.c_str());
6292 lua_pushinteger(L, index + 1);
6294 LuaItemStack::create(L, stack);
6296 objectref_get_or_create(L, player);
6297 if(lua_pcall(L, 5, 1, 0))
6298 script_error(L, "error: %s", lua_tostring(L, -1));
6299 if(!lua_isnumber(L, -1))
6300 throw LuaError(L, "allow_put should return a number");
6301 return luaL_checkinteger(L, -1);
6304 // Return number of accepted items to be taken
6305 int scriptapi_detached_inventory_allow_take(lua_State *L,
6306 const std::string &name,
6307 const std::string &listname, int index, ItemStack &stack,
6308 ServerActiveObject *player)
6311 assert(lua_checkstack(L, 20));
6312 StackUnroller stack_unroller(L);
6314 // Push callback function on stack
6315 if(!get_detached_inventory_callback(L, name, "allow_take"))
6316 return stack.count; // All will be accepted
6318 // Call function(inv, listname, index, stack, player)
6320 InventoryLocation loc;
6321 loc.setDetached(name);
6322 InvRef::create(L, loc);
6324 lua_pushstring(L, listname.c_str());
6326 lua_pushinteger(L, index + 1);
6328 LuaItemStack::create(L, stack);
6330 objectref_get_or_create(L, player);
6331 if(lua_pcall(L, 5, 1, 0))
6332 script_error(L, "error: %s", lua_tostring(L, -1));
6333 if(!lua_isnumber(L, -1))
6334 throw LuaError(L, "allow_take should return a number");
6335 return luaL_checkinteger(L, -1);
6338 // Report moved items
6339 void scriptapi_detached_inventory_on_move(lua_State *L,
6340 const std::string &name,
6341 const std::string &from_list, int from_index,
6342 const std::string &to_list, int to_index,
6343 int count, ServerActiveObject *player)
6346 assert(lua_checkstack(L, 20));
6347 StackUnroller stack_unroller(L);
6349 // Push callback function on stack
6350 if(!get_detached_inventory_callback(L, name, "on_move"))
6353 // function(inv, from_list, from_index, to_list, to_index, count, player)
6355 InventoryLocation loc;
6356 loc.setDetached(name);
6357 InvRef::create(L, loc);
6359 lua_pushstring(L, from_list.c_str());
6361 lua_pushinteger(L, from_index + 1);
6363 lua_pushstring(L, to_list.c_str());
6365 lua_pushinteger(L, to_index + 1);
6367 lua_pushinteger(L, count);
6369 objectref_get_or_create(L, player);
6370 if(lua_pcall(L, 7, 0, 0))
6371 script_error(L, "error: %s", lua_tostring(L, -1));
6375 void scriptapi_detached_inventory_on_put(lua_State *L,
6376 const std::string &name,
6377 const std::string &listname, int index, ItemStack &stack,
6378 ServerActiveObject *player)
6381 assert(lua_checkstack(L, 20));
6382 StackUnroller stack_unroller(L);
6384 // Push callback function on stack
6385 if(!get_detached_inventory_callback(L, name, "on_put"))
6388 // Call function(inv, listname, index, stack, player)
6390 InventoryLocation loc;
6391 loc.setDetached(name);
6392 InvRef::create(L, loc);
6394 lua_pushstring(L, listname.c_str());
6396 lua_pushinteger(L, index + 1);
6398 LuaItemStack::create(L, stack);
6400 objectref_get_or_create(L, player);
6401 if(lua_pcall(L, 5, 0, 0))
6402 script_error(L, "error: %s", lua_tostring(L, -1));
6405 // Report taken items
6406 void scriptapi_detached_inventory_on_take(lua_State *L,
6407 const std::string &name,
6408 const std::string &listname, int index, ItemStack &stack,
6409 ServerActiveObject *player)
6412 assert(lua_checkstack(L, 20));
6413 StackUnroller stack_unroller(L);
6415 // Push callback function on stack
6416 if(!get_detached_inventory_callback(L, name, "on_take"))
6419 // Call function(inv, listname, index, stack, player)
6421 InventoryLocation loc;
6422 loc.setDetached(name);
6423 InvRef::create(L, loc);
6425 lua_pushstring(L, listname.c_str());
6427 lua_pushinteger(L, index + 1);
6429 LuaItemStack::create(L, stack);
6431 objectref_get_or_create(L, player);
6432 if(lua_pcall(L, 5, 0, 0))
6433 script_error(L, "error: %s", lua_tostring(L, -1));
6440 void scriptapi_environment_step(lua_State *L, float dtime)
6443 assert(lua_checkstack(L, 20));
6444 //infostream<<"scriptapi_environment_step"<<std::endl;
6445 StackUnroller stack_unroller(L);
6447 // Get minetest.registered_globalsteps
6448 lua_getglobal(L, "minetest");
6449 lua_getfield(L, -1, "registered_globalsteps");
6451 lua_pushnumber(L, dtime);
6452 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6455 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6459 assert(lua_checkstack(L, 20));
6460 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6461 StackUnroller stack_unroller(L);
6463 // Get minetest.registered_on_generateds
6464 lua_getglobal(L, "minetest");
6465 lua_getfield(L, -1, "registered_on_generateds");
6467 push_v3s16(L, minp);
6468 push_v3s16(L, maxp);
6469 lua_pushnumber(L, blockseed);
6470 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6477 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6480 assert(lua_checkstack(L, 20));
6481 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6482 <<name<<"\""<<std::endl;
6483 StackUnroller stack_unroller(L);
6485 // Get minetest.registered_entities[name]
6486 lua_getglobal(L, "minetest");
6487 lua_getfield(L, -1, "registered_entities");
6488 luaL_checktype(L, -1, LUA_TTABLE);
6489 lua_pushstring(L, name);
6490 lua_gettable(L, -2);
6491 // Should be a table, which we will use as a prototype
6492 //luaL_checktype(L, -1, LUA_TTABLE);
6493 if(lua_type(L, -1) != LUA_TTABLE){
6494 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6497 int prototype_table = lua_gettop(L);
6498 //dump2(L, "prototype_table");
6500 // Create entity object
6502 int object = lua_gettop(L);
6504 // Set object metatable
6505 lua_pushvalue(L, prototype_table);
6506 lua_setmetatable(L, -2);
6508 // Add object reference
6509 // This should be userdata with metatable ObjectRef
6510 objectref_get(L, id);
6511 luaL_checktype(L, -1, LUA_TUSERDATA);
6512 if(!luaL_checkudata(L, -1, "ObjectRef"))
6513 luaL_typerror(L, -1, "ObjectRef");
6514 lua_setfield(L, -2, "object");
6516 // minetest.luaentities[id] = object
6517 lua_getglobal(L, "minetest");
6518 lua_getfield(L, -1, "luaentities");
6519 luaL_checktype(L, -1, LUA_TTABLE);
6520 lua_pushnumber(L, id); // Push id
6521 lua_pushvalue(L, object); // Copy object to top of stack
6522 lua_settable(L, -3);
6527 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6528 const std::string &staticdata, u32 dtime_s)
6531 assert(lua_checkstack(L, 20));
6532 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6533 StackUnroller stack_unroller(L);
6535 // Get minetest.luaentities[id]
6536 luaentity_get(L, id);
6537 int object = lua_gettop(L);
6539 // Get on_activate function
6540 lua_pushvalue(L, object);
6541 lua_getfield(L, -1, "on_activate");
6542 if(!lua_isnil(L, -1)){
6543 luaL_checktype(L, -1, LUA_TFUNCTION);
6544 lua_pushvalue(L, object); // self
6545 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6546 lua_pushinteger(L, dtime_s);
6547 // Call with 3 arguments, 0 results
6548 if(lua_pcall(L, 3, 0, 0))
6549 script_error(L, "error running function on_activate: %s\n",
6550 lua_tostring(L, -1));
6554 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6557 assert(lua_checkstack(L, 20));
6558 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6560 // Get minetest.luaentities table
6561 lua_getglobal(L, "minetest");
6562 lua_getfield(L, -1, "luaentities");
6563 luaL_checktype(L, -1, LUA_TTABLE);
6564 int objectstable = lua_gettop(L);
6566 // Set luaentities[id] = nil
6567 lua_pushnumber(L, id); // Push id
6569 lua_settable(L, objectstable);
6571 lua_pop(L, 2); // pop luaentities, minetest
6574 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6577 assert(lua_checkstack(L, 20));
6578 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6579 StackUnroller stack_unroller(L);
6581 // Get minetest.luaentities[id]
6582 luaentity_get(L, id);
6583 int object = lua_gettop(L);
6585 // Get get_staticdata function
6586 lua_pushvalue(L, object);
6587 lua_getfield(L, -1, "get_staticdata");
6588 if(lua_isnil(L, -1))
6591 luaL_checktype(L, -1, LUA_TFUNCTION);
6592 lua_pushvalue(L, object); // self
6593 // Call with 1 arguments, 1 results
6594 if(lua_pcall(L, 1, 1, 0))
6595 script_error(L, "error running function get_staticdata: %s\n",
6596 lua_tostring(L, -1));
6599 const char *s = lua_tolstring(L, -1, &len);
6600 return std::string(s, len);
6603 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6604 ObjectProperties *prop)
6607 assert(lua_checkstack(L, 20));
6608 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6609 StackUnroller stack_unroller(L);
6611 // Get minetest.luaentities[id]
6612 luaentity_get(L, id);
6613 //int object = lua_gettop(L);
6615 // Set default values that differ from ObjectProperties defaults
6620 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6622 getboolfield(L, -1, "physical", prop->physical);
6624 getfloatfield(L, -1, "weight", prop->weight);
6626 lua_getfield(L, -1, "collisionbox");
6627 if(lua_istable(L, -1))
6628 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6631 getstringfield(L, -1, "visual", prop->visual);
6633 getstringfield(L, -1, "mesh", prop->mesh);
6635 // Deprecated: read object properties directly
6636 read_object_properties(L, -1, prop);
6638 // Read initial_properties
6639 lua_getfield(L, -1, "initial_properties");
6640 read_object_properties(L, -1, prop);
6644 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6647 assert(lua_checkstack(L, 20));
6648 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6649 StackUnroller stack_unroller(L);
6651 // Get minetest.luaentities[id]
6652 luaentity_get(L, id);
6653 int object = lua_gettop(L);
6654 // State: object is at top of stack
6655 // Get step function
6656 lua_getfield(L, -1, "on_step");
6657 if(lua_isnil(L, -1))
6659 luaL_checktype(L, -1, LUA_TFUNCTION);
6660 lua_pushvalue(L, object); // self
6661 lua_pushnumber(L, dtime); // dtime
6662 // Call with 2 arguments, 0 results
6663 if(lua_pcall(L, 2, 0, 0))
6664 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6667 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6668 // tool_capabilities, direction)
6669 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6670 ServerActiveObject *puncher, float time_from_last_punch,
6671 const ToolCapabilities *toolcap, v3f dir)
6674 assert(lua_checkstack(L, 20));
6675 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6676 StackUnroller stack_unroller(L);
6678 // Get minetest.luaentities[id]
6679 luaentity_get(L, id);
6680 int object = lua_gettop(L);
6681 // State: object is at top of stack
6683 lua_getfield(L, -1, "on_punch");
6684 if(lua_isnil(L, -1))
6686 luaL_checktype(L, -1, LUA_TFUNCTION);
6687 lua_pushvalue(L, object); // self
6688 objectref_get_or_create(L, puncher); // Clicker reference
6689 lua_pushnumber(L, time_from_last_punch);
6690 push_tool_capabilities(L, *toolcap);
6692 // Call with 5 arguments, 0 results
6693 if(lua_pcall(L, 5, 0, 0))
6694 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6697 // Calls entity:on_rightclick(ObjectRef clicker)
6698 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6699 ServerActiveObject *clicker)
6702 assert(lua_checkstack(L, 20));
6703 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6704 StackUnroller stack_unroller(L);
6706 // Get minetest.luaentities[id]
6707 luaentity_get(L, id);
6708 int object = lua_gettop(L);
6709 // State: object is at top of stack
6711 lua_getfield(L, -1, "on_rightclick");
6712 if(lua_isnil(L, -1))
6714 luaL_checktype(L, -1, LUA_TFUNCTION);
6715 lua_pushvalue(L, object); // self
6716 objectref_get_or_create(L, clicker); // Clicker reference
6717 // Call with 2 arguments, 0 results
6718 if(lua_pcall(L, 2, 0, 0))
6719 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));