3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "scriptapi.h"
34 #include "serverobject.h"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
41 #include "main.h" // For g_settings
42 #include "settings.h" // For accessing g_settings
43 #include "nodemetadata.h"
44 #include "mapblock.h" // For getNodeBlockPos
45 #include "content_nodemeta.h"
47 #include "daynightratio.h"
48 #include "noise.h" // PseudoRandom for LuaPseudoRandom
49 #include "util/pointedthing.h"
52 static void stackDump(lua_State *L, std::ostream &o)
55 int top = lua_gettop(L);
56 for (i = 1; i <= top; i++) { /* repeat for each level */
57 int t = lua_type(L, i);
60 case LUA_TSTRING: /* strings */
61 o<<"\""<<lua_tostring(L, i)<<"\"";
64 case LUA_TBOOLEAN: /* booleans */
65 o<<(lua_toboolean(L, i) ? "true" : "false");
68 case LUA_TNUMBER: /* numbers */ {
70 snprintf(buf, 10, "%g", lua_tonumber(L, i));
74 default: /* other values */
75 o<<lua_typename(L, t);
84 static void realitycheck(lua_State *L)
86 int top = lua_gettop(L);
88 dstream<<"Stack is over 30:"<<std::endl;
89 stackDump(L, dstream);
90 script_error(L, "Stack is over 30 (reality check)");
100 StackUnroller(lua_State *L):
104 m_original_top = lua_gettop(m_lua); // store stack height
108 lua_settop(m_lua, m_original_top); // restore stack height
117 ModNameStorer(lua_State *L_, const std::string modname):
120 // Store current modname in registry
121 lua_pushstring(L, modname.c_str());
122 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
126 // Clear current modname in registry
128 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
133 Getters for stuff in main tables
136 static Server* get_server(lua_State *L)
138 // Get server from registry
139 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
140 Server *server = (Server*)lua_touserdata(L, -1);
145 static ServerEnvironment* get_env(lua_State *L)
147 // Get environment from registry
148 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
149 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
154 static void objectref_get(lua_State *L, u16 id)
156 // Get minetest.object_refs[i]
157 lua_getglobal(L, "minetest");
158 lua_getfield(L, -1, "object_refs");
159 luaL_checktype(L, -1, LUA_TTABLE);
160 lua_pushnumber(L, id);
162 lua_remove(L, -2); // object_refs
163 lua_remove(L, -2); // minetest
166 static void luaentity_get(lua_State *L, u16 id)
168 // Get minetest.luaentities[i]
169 lua_getglobal(L, "minetest");
170 lua_getfield(L, -1, "luaentities");
171 luaL_checktype(L, -1, LUA_TTABLE);
172 lua_pushnumber(L, id);
174 lua_remove(L, -2); // luaentities
175 lua_remove(L, -2); // minetest
182 static bool getstringfield(lua_State *L, int table,
183 const char *fieldname, std::string &result)
185 lua_getfield(L, table, fieldname);
187 if(lua_isstring(L, -1)){
189 const char *ptr = lua_tolstring(L, -1, &len);
190 result.assign(ptr, len);
197 static bool getintfield(lua_State *L, int table,
198 const char *fieldname, int &result)
200 lua_getfield(L, table, fieldname);
202 if(lua_isnumber(L, -1)){
203 result = lua_tonumber(L, -1);
210 static bool getfloatfield(lua_State *L, int table,
211 const char *fieldname, float &result)
213 lua_getfield(L, table, fieldname);
215 if(lua_isnumber(L, -1)){
216 result = lua_tonumber(L, -1);
223 static bool getboolfield(lua_State *L, int table,
224 const char *fieldname, bool &result)
226 lua_getfield(L, table, fieldname);
228 if(lua_isboolean(L, -1)){
229 result = lua_toboolean(L, -1);
236 static std::string checkstringfield(lua_State *L, int table,
237 const char *fieldname)
239 lua_getfield(L, table, fieldname);
240 std::string s = luaL_checkstring(L, -1);
245 static std::string getstringfield_default(lua_State *L, int table,
246 const char *fieldname, const std::string &default_)
248 std::string result = default_;
249 getstringfield(L, table, fieldname, result);
253 static int getintfield_default(lua_State *L, int table,
254 const char *fieldname, int default_)
256 int result = default_;
257 getintfield(L, table, fieldname, result);
261 static float getfloatfield_default(lua_State *L, int table,
262 const char *fieldname, float default_)
264 float result = default_;
265 getfloatfield(L, table, fieldname, result);
269 static bool getboolfield_default(lua_State *L, int table,
270 const char *fieldname, bool default_)
272 bool result = default_;
273 getboolfield(L, table, fieldname, result);
283 static bool string_to_enum(const EnumString *spec, int &result,
284 const std::string &str)
286 const EnumString *esp = spec;
288 if(str == std::string(esp->str)){
297 /*static bool enum_to_string(const EnumString *spec, std::string &result,
300 const EnumString *esp = spec;
311 static int getenumfield(lua_State *L, int table,
312 const char *fieldname, const EnumString *spec, int default_)
314 int result = default_;
315 string_to_enum(spec, result,
316 getstringfield_default(L, table, fieldname, ""));
320 static void setintfield(lua_State *L, int table,
321 const char *fieldname, int value)
323 lua_pushinteger(L, value);
326 lua_setfield(L, table, fieldname);
329 static void setfloatfield(lua_State *L, int table,
330 const char *fieldname, float value)
332 lua_pushnumber(L, value);
335 lua_setfield(L, table, fieldname);
338 static void setboolfield(lua_State *L, int table,
339 const char *fieldname, bool value)
341 lua_pushboolean(L, value);
344 lua_setfield(L, table, fieldname);
347 static void warn_if_field_exists(lua_State *L, int table,
348 const char *fieldname, const std::string &message)
350 lua_getfield(L, table, fieldname);
351 if(!lua_isnil(L, -1)){
352 infostream<<script_get_backtrace(L)<<std::endl;
353 infostream<<"WARNING: field \""<<fieldname<<"\": "
354 <<message<<std::endl;
360 EnumString definitions
363 struct EnumString es_ItemType[] =
367 {ITEM_CRAFT, "craft"},
372 struct EnumString es_DrawType[] =
374 {NDT_NORMAL, "normal"},
375 {NDT_AIRLIKE, "airlike"},
376 {NDT_LIQUID, "liquid"},
377 {NDT_FLOWINGLIQUID, "flowingliquid"},
378 {NDT_GLASSLIKE, "glasslike"},
379 {NDT_ALLFACES, "allfaces"},
380 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
381 {NDT_TORCHLIKE, "torchlike"},
382 {NDT_SIGNLIKE, "signlike"},
383 {NDT_PLANTLIKE, "plantlike"},
384 {NDT_FENCELIKE, "fencelike"},
385 {NDT_RAILLIKE, "raillike"},
386 {NDT_NODEBOX, "nodebox"},
390 struct EnumString es_ContentParamType[] =
393 {CPT_LIGHT, "light"},
397 struct EnumString es_ContentParamType2[] =
401 {CPT2_FLOWINGLIQUID, "flowingliquid"},
402 {CPT2_FACEDIR, "facedir"},
403 {CPT2_WALLMOUNTED, "wallmounted"},
407 struct EnumString es_LiquidType[] =
409 {LIQUID_NONE, "none"},
410 {LIQUID_FLOWING, "flowing"},
411 {LIQUID_SOURCE, "source"},
415 struct EnumString es_NodeBoxType[] =
417 {NODEBOX_REGULAR, "regular"},
418 {NODEBOX_FIXED, "fixed"},
419 {NODEBOX_WALLMOUNTED, "wallmounted"},
423 struct EnumString es_CraftMethod[] =
425 {CRAFT_METHOD_NORMAL, "normal"},
426 {CRAFT_METHOD_COOKING, "cooking"},
427 {CRAFT_METHOD_FUEL, "fuel"},
431 struct EnumString es_TileAnimationType[] =
434 {TAT_VERTICAL_FRAMES, "vertical_frames"},
439 C struct <-> Lua table converter functions
442 static void push_v3f(lua_State *L, v3f p)
445 lua_pushnumber(L, p.X);
446 lua_setfield(L, -2, "x");
447 lua_pushnumber(L, p.Y);
448 lua_setfield(L, -2, "y");
449 lua_pushnumber(L, p.Z);
450 lua_setfield(L, -2, "z");
453 static v2s16 read_v2s16(lua_State *L, int index)
456 luaL_checktype(L, index, LUA_TTABLE);
457 lua_getfield(L, index, "x");
458 p.X = lua_tonumber(L, -1);
460 lua_getfield(L, index, "y");
461 p.Y = lua_tonumber(L, -1);
466 static v2f read_v2f(lua_State *L, int index)
469 luaL_checktype(L, index, LUA_TTABLE);
470 lua_getfield(L, index, "x");
471 p.X = lua_tonumber(L, -1);
473 lua_getfield(L, index, "y");
474 p.Y = lua_tonumber(L, -1);
479 static v3f read_v3f(lua_State *L, int index)
482 luaL_checktype(L, index, LUA_TTABLE);
483 lua_getfield(L, index, "x");
484 pos.X = lua_tonumber(L, -1);
486 lua_getfield(L, index, "y");
487 pos.Y = lua_tonumber(L, -1);
489 lua_getfield(L, index, "z");
490 pos.Z = lua_tonumber(L, -1);
495 static v3f check_v3f(lua_State *L, int index)
498 luaL_checktype(L, index, LUA_TTABLE);
499 lua_getfield(L, index, "x");
500 pos.X = luaL_checknumber(L, -1);
502 lua_getfield(L, index, "y");
503 pos.Y = luaL_checknumber(L, -1);
505 lua_getfield(L, index, "z");
506 pos.Z = luaL_checknumber(L, -1);
511 static void pushFloatPos(lua_State *L, v3f p)
517 static v3f checkFloatPos(lua_State *L, int index)
519 return check_v3f(L, index) * BS;
522 static void push_v3s16(lua_State *L, v3s16 p)
525 lua_pushnumber(L, p.X);
526 lua_setfield(L, -2, "x");
527 lua_pushnumber(L, p.Y);
528 lua_setfield(L, -2, "y");
529 lua_pushnumber(L, p.Z);
530 lua_setfield(L, -2, "z");
533 static v3s16 read_v3s16(lua_State *L, int index)
535 // Correct rounding at <0
536 v3f pf = read_v3f(L, index);
537 return floatToInt(pf, 1.0);
540 static v3s16 check_v3s16(lua_State *L, int index)
542 // Correct rounding at <0
543 v3f pf = check_v3f(L, index);
544 return floatToInt(pf, 1.0);
547 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
550 lua_pushstring(L, ndef->get(n).name.c_str());
551 lua_setfield(L, -2, "name");
552 lua_pushnumber(L, n.getParam1());
553 lua_setfield(L, -2, "param1");
554 lua_pushnumber(L, n.getParam2());
555 lua_setfield(L, -2, "param2");
558 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
560 lua_getfield(L, index, "name");
561 const char *name = luaL_checkstring(L, -1);
564 lua_getfield(L, index, "param1");
568 param1 = lua_tonumber(L, -1);
571 lua_getfield(L, index, "param2");
575 param2 = lua_tonumber(L, -1);
577 return MapNode(ndef, name, param1, param2);
580 static video::SColor readARGB8(lua_State *L, int index)
583 luaL_checktype(L, index, LUA_TTABLE);
584 lua_getfield(L, index, "a");
585 if(lua_isnumber(L, -1))
586 color.setAlpha(lua_tonumber(L, -1));
588 lua_getfield(L, index, "r");
589 color.setRed(lua_tonumber(L, -1));
591 lua_getfield(L, index, "g");
592 color.setGreen(lua_tonumber(L, -1));
594 lua_getfield(L, index, "b");
595 color.setBlue(lua_tonumber(L, -1));
600 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
603 if(lua_istable(L, index)){
604 lua_rawgeti(L, index, 1);
605 box.MinEdge.X = lua_tonumber(L, -1) * scale;
607 lua_rawgeti(L, index, 2);
608 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
610 lua_rawgeti(L, index, 3);
611 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
613 lua_rawgeti(L, index, 4);
614 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
616 lua_rawgeti(L, index, 5);
617 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
619 lua_rawgeti(L, index, 6);
620 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
626 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
628 std::vector<aabb3f> boxes;
629 if(lua_istable(L, index)){
630 int n = lua_objlen(L, index);
631 // Check if it's a single box or a list of boxes
632 bool possibly_single_box = (n == 6);
633 for(int i = 1; i <= n && possibly_single_box; i++){
634 lua_rawgeti(L, index, i);
635 if(!lua_isnumber(L, -1))
636 possibly_single_box = false;
639 if(possibly_single_box){
641 boxes.push_back(read_aabb3f(L, index, scale));
643 // Read a list of boxes
644 for(int i = 1; i <= n; i++){
645 lua_rawgeti(L, index, i);
646 boxes.push_back(read_aabb3f(L, -1, scale));
654 static NodeBox read_nodebox(lua_State *L, int index)
657 if(lua_istable(L, -1)){
658 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
659 es_NodeBoxType, NODEBOX_REGULAR);
661 lua_getfield(L, index, "fixed");
662 if(lua_istable(L, -1))
663 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
666 lua_getfield(L, index, "wall_top");
667 if(lua_istable(L, -1))
668 nodebox.wall_top = read_aabb3f(L, -1, BS);
671 lua_getfield(L, index, "wall_bottom");
672 if(lua_istable(L, -1))
673 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
676 lua_getfield(L, index, "wall_side");
677 if(lua_istable(L, -1))
678 nodebox.wall_side = read_aabb3f(L, -1, BS);
687 static void read_groups(lua_State *L, int index,
688 std::map<std::string, int> &result)
690 if (!lua_istable(L,index))
696 while(lua_next(L, index) != 0){
697 // key at index -2 and value at index -1
698 std::string name = luaL_checkstring(L, -2);
699 int rating = luaL_checkinteger(L, -1);
700 result[name] = rating;
701 // removes value, keeps key for next iteration
709 static void read_privileges(lua_State *L, int index,
710 std::set<std::string> &result)
716 while(lua_next(L, index) != 0){
717 // key at index -2 and value at index -1
718 std::string key = luaL_checkstring(L, -2);
719 bool value = lua_toboolean(L, -1);
722 // removes value, keeps key for next iteration
731 static ToolCapabilities read_tool_capabilities(
732 lua_State *L, int table)
734 ToolCapabilities toolcap;
735 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
736 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
737 lua_getfield(L, table, "groupcaps");
738 if(lua_istable(L, -1)){
739 int table_groupcaps = lua_gettop(L);
741 while(lua_next(L, table_groupcaps) != 0){
742 // key at index -2 and value at index -1
743 std::string groupname = luaL_checkstring(L, -2);
744 if(lua_istable(L, -1)){
745 int table_groupcap = lua_gettop(L);
746 // This will be created
747 ToolGroupCap groupcap;
748 // Read simple parameters
749 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
750 getintfield(L, table_groupcap, "uses", groupcap.uses);
751 // DEPRECATED: maxwear
753 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
755 groupcap.uses = 1.0/maxwear;
758 infostream<<script_get_backtrace(L)<<std::endl;
759 infostream<<"WARNING: field \"maxwear\" is deprecated; "
760 <<"should replace with uses=1/maxwear"<<std::endl;
762 // Read "times" table
763 lua_getfield(L, table_groupcap, "times");
764 if(lua_istable(L, -1)){
765 int table_times = lua_gettop(L);
767 while(lua_next(L, table_times) != 0){
768 // key at index -2 and value at index -1
769 int rating = luaL_checkinteger(L, -2);
770 float time = luaL_checknumber(L, -1);
771 groupcap.times[rating] = time;
772 // removes value, keeps key for next iteration
777 // Insert groupcap into toolcap
778 toolcap.groupcaps[groupname] = groupcap;
780 // removes value, keeps key for next iteration
788 static void set_tool_capabilities(lua_State *L, int table,
789 const ToolCapabilities &toolcap)
791 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
792 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
793 // Create groupcaps table
796 for(std::map<std::string, ToolGroupCap>::const_iterator
797 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
798 // Create groupcap table
800 const std::string &name = i->first;
801 const ToolGroupCap &groupcap = i->second;
802 // Create subtable "times"
804 for(std::map<int, float>::const_iterator
805 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
806 int rating = i->first;
807 float time = i->second;
808 lua_pushinteger(L, rating);
809 lua_pushnumber(L, time);
812 // Set subtable "times"
813 lua_setfield(L, -2, "times");
814 // Set simple parameters
815 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
816 setintfield(L, -1, "uses", groupcap.uses);
817 // Insert groupcap table into groupcaps table
818 lua_setfield(L, -2, name.c_str());
820 // Set groupcaps table
821 lua_setfield(L, -2, "groupcaps");
824 static void push_tool_capabilities(lua_State *L,
825 const ToolCapabilities &prop)
828 set_tool_capabilities(L, -1, prop);
835 static void set_dig_params(lua_State *L, int table,
836 const DigParams ¶ms)
838 setboolfield(L, table, "diggable", params.diggable);
839 setfloatfield(L, table, "time", params.time);
840 setintfield(L, table, "wear", params.wear);
843 static void push_dig_params(lua_State *L,
844 const DigParams ¶ms)
847 set_dig_params(L, -1, params);
854 static void set_hit_params(lua_State *L, int table,
855 const HitParams ¶ms)
857 setintfield(L, table, "hp", params.hp);
858 setintfield(L, table, "wear", params.wear);
861 static void push_hit_params(lua_State *L,
862 const HitParams ¶ms)
865 set_hit_params(L, -1, params);
872 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
875 if(pointed.type == POINTEDTHING_NODE)
877 lua_pushstring(L, "node");
878 lua_setfield(L, -2, "type");
879 push_v3s16(L, pointed.node_undersurface);
880 lua_setfield(L, -2, "under");
881 push_v3s16(L, pointed.node_abovesurface);
882 lua_setfield(L, -2, "above");
884 else if(pointed.type == POINTEDTHING_OBJECT)
886 lua_pushstring(L, "object");
887 lua_setfield(L, -2, "type");
888 objectref_get(L, pointed.object_id);
889 lua_setfield(L, -2, "ref");
893 lua_pushstring(L, "nothing");
894 lua_setfield(L, -2, "type");
902 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
905 index = lua_gettop(L) + 1 + index;
906 if(lua_isnil(L, index)){
907 } else if(lua_istable(L, index)){
908 getstringfield(L, index, "name", spec.name);
909 getfloatfield(L, index, "gain", spec.gain);
910 } else if(lua_isstring(L, index)){
911 spec.name = lua_tostring(L, index);
919 static void read_object_properties(lua_State *L, int index,
920 ObjectProperties *prop)
923 index = lua_gettop(L) + 1 + index;
924 if(!lua_istable(L, index))
927 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
929 getboolfield(L, -1, "physical", prop->physical);
931 getfloatfield(L, -1, "weight", prop->weight);
933 lua_getfield(L, -1, "collisionbox");
934 if(lua_istable(L, -1))
935 prop->collisionbox = read_aabb3f(L, -1, 1.0);
938 getstringfield(L, -1, "visual", prop->visual);
940 getstringfield(L, -1, "mesh", prop->mesh);
942 lua_getfield(L, -1, "visual_size");
943 if(lua_istable(L, -1))
944 prop->visual_size = read_v2f(L, -1);
947 lua_getfield(L, -1, "textures");
948 if(lua_istable(L, -1)){
949 prop->textures.clear();
950 int table = lua_gettop(L);
952 while(lua_next(L, table) != 0){
953 // key at index -2 and value at index -1
954 if(lua_isstring(L, -1))
955 prop->textures.push_back(lua_tostring(L, -1));
957 prop->textures.push_back("");
958 // removes value, keeps key for next iteration
964 lua_getfield(L, -1, "spritediv");
965 if(lua_istable(L, -1))
966 prop->spritediv = read_v2s16(L, -1);
969 lua_getfield(L, -1, "initial_sprite_basepos");
970 if(lua_istable(L, -1))
971 prop->initial_sprite_basepos = read_v2s16(L, -1);
974 getboolfield(L, -1, "is_visible", prop->is_visible);
975 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
976 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
983 static ItemDefinition read_item_definition(lua_State *L, int index,
984 ItemDefinition default_def = ItemDefinition())
987 index = lua_gettop(L) + 1 + index;
989 // Read the item definition
990 ItemDefinition def = default_def;
992 def.type = (ItemType)getenumfield(L, index, "type",
993 es_ItemType, ITEM_NONE);
994 getstringfield(L, index, "name", def.name);
995 getstringfield(L, index, "description", def.description);
996 getstringfield(L, index, "inventory_image", def.inventory_image);
997 getstringfield(L, index, "wield_image", def.wield_image);
999 lua_getfield(L, index, "wield_scale");
1000 if(lua_istable(L, -1)){
1001 def.wield_scale = check_v3f(L, -1);
1005 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1006 if(def.stack_max == 0)
1009 lua_getfield(L, index, "on_use");
1010 def.usable = lua_isfunction(L, -1);
1013 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1015 warn_if_field_exists(L, index, "tool_digging_properties",
1016 "deprecated: use tool_capabilities");
1018 lua_getfield(L, index, "tool_capabilities");
1019 if(lua_istable(L, -1)){
1020 def.tool_capabilities = new ToolCapabilities(
1021 read_tool_capabilities(L, -1));
1024 // If name is "" (hand), ensure there are ToolCapabilities
1025 // because it will be looked up there whenever any other item has
1026 // no ToolCapabilities
1027 if(def.name == "" && def.tool_capabilities == NULL){
1028 def.tool_capabilities = new ToolCapabilities();
1031 lua_getfield(L, index, "groups");
1032 read_groups(L, -1, def.groups);
1035 // Client shall immediately place this node when player places the item.
1036 // Server will update the precise end result a moment later.
1037 // "" = no prediction
1038 getstringfield(L, index, "node_placement_prediction",
1039 def.node_placement_prediction);
1048 static TileDef read_tiledef(lua_State *L, int index)
1051 index = lua_gettop(L) + 1 + index;
1055 // key at index -2 and value at index
1056 if(lua_isstring(L, index)){
1057 // "default_lava.png"
1058 tiledef.name = lua_tostring(L, index);
1060 else if(lua_istable(L, index))
1062 // {name="default_lava.png", animation={}}
1064 getstringfield(L, index, "name", tiledef.name);
1065 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1066 tiledef.backface_culling = getboolfield_default(
1067 L, index, "backface_culling", true);
1069 lua_getfield(L, index, "animation");
1070 if(lua_istable(L, -1)){
1071 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1072 tiledef.animation.type = (TileAnimationType)
1073 getenumfield(L, -1, "type", es_TileAnimationType,
1075 tiledef.animation.aspect_w =
1076 getintfield_default(L, -1, "aspect_w", 16);
1077 tiledef.animation.aspect_h =
1078 getintfield_default(L, -1, "aspect_h", 16);
1079 tiledef.animation.length =
1080 getfloatfield_default(L, -1, "length", 1.0);
1092 static ContentFeatures read_content_features(lua_State *L, int index)
1095 index = lua_gettop(L) + 1 + index;
1099 /* Cache existence of some callbacks */
1100 lua_getfield(L, index, "on_construct");
1101 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1103 lua_getfield(L, index, "on_destruct");
1104 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1106 lua_getfield(L, index, "after_destruct");
1107 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1111 getstringfield(L, index, "name", f.name);
1114 lua_getfield(L, index, "groups");
1115 read_groups(L, -1, f.groups);
1118 /* Visual definition */
1120 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1122 getfloatfield(L, index, "visual_scale", f.visual_scale);
1125 lua_getfield(L, index, "tiles");
1126 // If nil, try the deprecated name "tile_images" instead
1127 if(lua_isnil(L, -1)){
1129 warn_if_field_exists(L, index, "tile_images",
1130 "Deprecated; new name is \"tiles\".");
1131 lua_getfield(L, index, "tile_images");
1133 if(lua_istable(L, -1)){
1134 int table = lua_gettop(L);
1137 while(lua_next(L, table) != 0){
1138 // Read tiledef from value
1139 f.tiledef[i] = read_tiledef(L, -1);
1140 // removes value, keeps key for next iteration
1148 // Copy last value to all remaining textures
1150 TileDef lasttile = f.tiledef[i-1];
1152 f.tiledef[i] = lasttile;
1159 // special_tiles = {}
1160 lua_getfield(L, index, "special_tiles");
1161 // If nil, try the deprecated name "special_materials" instead
1162 if(lua_isnil(L, -1)){
1164 warn_if_field_exists(L, index, "special_materials",
1165 "Deprecated; new name is \"special_tiles\".");
1166 lua_getfield(L, index, "special_materials");
1168 if(lua_istable(L, -1)){
1169 int table = lua_gettop(L);
1172 while(lua_next(L, table) != 0){
1173 // Read tiledef from value
1174 f.tiledef_special[i] = read_tiledef(L, -1);
1175 // removes value, keeps key for next iteration
1186 f.alpha = getintfield_default(L, index, "alpha", 255);
1190 lua_getfield(L, index, "post_effect_color");
1191 if(!lua_isnil(L, -1))
1192 f.post_effect_color = readARGB8(L, -1);
1195 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1196 es_ContentParamType, CPT_NONE);
1197 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1198 es_ContentParamType2, CPT2_NONE);
1200 // Warn about some deprecated fields
1201 warn_if_field_exists(L, index, "wall_mounted",
1202 "deprecated: use paramtype2 = 'wallmounted'");
1203 warn_if_field_exists(L, index, "light_propagates",
1204 "deprecated: determined from paramtype");
1205 warn_if_field_exists(L, index, "dug_item",
1206 "deprecated: use 'drop' field");
1207 warn_if_field_exists(L, index, "extra_dug_item",
1208 "deprecated: use 'drop' field");
1209 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1210 "deprecated: use 'drop' field");
1211 warn_if_field_exists(L, index, "metadata_name",
1212 "deprecated: use on_add and metadata callbacks");
1214 // True for all ground-like things like stone and mud, false for eg. trees
1215 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1216 f.light_propagates = (f.param_type == CPT_LIGHT);
1217 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1218 // This is used for collision detection.
1219 // Also for general solidness queries.
1220 getboolfield(L, index, "walkable", f.walkable);
1221 // Player can point to these
1222 getboolfield(L, index, "pointable", f.pointable);
1223 // Player can dig these
1224 getboolfield(L, index, "diggable", f.diggable);
1225 // Player can climb these
1226 getboolfield(L, index, "climbable", f.climbable);
1227 // Player can build on these
1228 getboolfield(L, index, "buildable_to", f.buildable_to);
1229 // Whether the node is non-liquid, source liquid or flowing liquid
1230 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1231 es_LiquidType, LIQUID_NONE);
1232 // If the content is liquid, this is the flowing version of the liquid.
1233 getstringfield(L, index, "liquid_alternative_flowing",
1234 f.liquid_alternative_flowing);
1235 // If the content is liquid, this is the source version of the liquid.
1236 getstringfield(L, index, "liquid_alternative_source",
1237 f.liquid_alternative_source);
1238 // Viscosity for fluid flow, ranging from 1 to 7, with
1239 // 1 giving almost instantaneous propagation and 7 being
1240 // the slowest possible
1241 f.liquid_viscosity = getintfield_default(L, index,
1242 "liquid_viscosity", f.liquid_viscosity);
1243 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1244 // Amount of light the node emits
1245 f.light_source = getintfield_default(L, index,
1246 "light_source", f.light_source);
1247 f.damage_per_second = getintfield_default(L, index,
1248 "damage_per_second", f.damage_per_second);
1250 lua_getfield(L, index, "node_box");
1251 if(lua_istable(L, -1))
1252 f.node_box = read_nodebox(L, -1);
1255 lua_getfield(L, index, "selection_box");
1256 if(lua_istable(L, -1))
1257 f.selection_box = read_nodebox(L, -1);
1260 // Set to true if paramtype used to be 'facedir_simple'
1261 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1262 // Set to true if wall_mounted used to be set to true
1263 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1266 lua_getfield(L, index, "sounds");
1267 if(lua_istable(L, -1)){
1268 lua_getfield(L, -1, "footstep");
1269 read_soundspec(L, -1, f.sound_footstep);
1271 lua_getfield(L, -1, "dig");
1272 read_soundspec(L, -1, f.sound_dig);
1274 lua_getfield(L, -1, "dug");
1275 read_soundspec(L, -1, f.sound_dug);
1287 static ItemStack read_item(lua_State *L, int index);
1288 static std::vector<ItemStack> read_items(lua_State *L, int index);
1289 // creates a table of ItemStacks
1290 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1292 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1293 lua_State *L, int tableindex, int forcesize=-1)
1296 tableindex = lua_gettop(L) + 1 + tableindex;
1297 // If nil, delete list
1298 if(lua_isnil(L, tableindex)){
1299 inv->deleteList(name);
1302 // Otherwise set list
1303 std::vector<ItemStack> items = read_items(L, tableindex);
1304 int listsize = (forcesize != -1) ? forcesize : items.size();
1305 InventoryList *invlist = inv->addList(name, listsize);
1307 for(std::vector<ItemStack>::const_iterator
1308 i = items.begin(); i != items.end(); i++){
1309 if(forcesize != -1 && index == forcesize)
1311 invlist->changeItem(index, *i);
1314 while(forcesize != -1 && index < forcesize){
1315 invlist->deleteItem(index);
1320 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1323 InventoryList *invlist = inv->getList(name);
1324 if(invlist == NULL){
1328 std::vector<ItemStack> items;
1329 for(u32 i=0; i<invlist->getSize(); i++)
1330 items.push_back(invlist->getItem(i));
1331 push_items(L, items);
1335 Helpful macros for userdata classes
1338 #define method(class, name) {#name, class::l_##name}
1349 static const char className[];
1350 static const luaL_reg methods[];
1352 // Exported functions
1354 // garbage collector
1355 static int gc_object(lua_State *L)
1357 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1362 // is_empty(self) -> true/false
1363 static int l_is_empty(lua_State *L)
1365 LuaItemStack *o = checkobject(L, 1);
1366 ItemStack &item = o->m_stack;
1367 lua_pushboolean(L, item.empty());
1371 // get_name(self) -> string
1372 static int l_get_name(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1376 lua_pushstring(L, item.name.c_str());
1380 // get_count(self) -> number
1381 static int l_get_count(lua_State *L)
1383 LuaItemStack *o = checkobject(L, 1);
1384 ItemStack &item = o->m_stack;
1385 lua_pushinteger(L, item.count);
1389 // get_wear(self) -> number
1390 static int l_get_wear(lua_State *L)
1392 LuaItemStack *o = checkobject(L, 1);
1393 ItemStack &item = o->m_stack;
1394 lua_pushinteger(L, item.wear);
1398 // get_metadata(self) -> string
1399 static int l_get_metadata(lua_State *L)
1401 LuaItemStack *o = checkobject(L, 1);
1402 ItemStack &item = o->m_stack;
1403 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1407 // clear(self) -> true
1408 static int l_clear(lua_State *L)
1410 LuaItemStack *o = checkobject(L, 1);
1412 lua_pushboolean(L, true);
1416 // replace(self, itemstack or itemstring or table or nil) -> true
1417 static int l_replace(lua_State *L)
1419 LuaItemStack *o = checkobject(L, 1);
1420 o->m_stack = read_item(L, 2);
1421 lua_pushboolean(L, true);
1425 // to_string(self) -> string
1426 static int l_to_string(lua_State *L)
1428 LuaItemStack *o = checkobject(L, 1);
1429 std::string itemstring = o->m_stack.getItemString();
1430 lua_pushstring(L, itemstring.c_str());
1434 // to_table(self) -> table or nil
1435 static int l_to_table(lua_State *L)
1437 LuaItemStack *o = checkobject(L, 1);
1438 const ItemStack &item = o->m_stack;
1446 lua_pushstring(L, item.name.c_str());
1447 lua_setfield(L, -2, "name");
1448 lua_pushinteger(L, item.count);
1449 lua_setfield(L, -2, "count");
1450 lua_pushinteger(L, item.wear);
1451 lua_setfield(L, -2, "wear");
1452 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1453 lua_setfield(L, -2, "metadata");
1458 // get_stack_max(self) -> number
1459 static int l_get_stack_max(lua_State *L)
1461 LuaItemStack *o = checkobject(L, 1);
1462 ItemStack &item = o->m_stack;
1463 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1467 // get_free_space(self) -> number
1468 static int l_get_free_space(lua_State *L)
1470 LuaItemStack *o = checkobject(L, 1);
1471 ItemStack &item = o->m_stack;
1472 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1476 // is_known(self) -> true/false
1477 // Checks if the item is defined.
1478 static int l_is_known(lua_State *L)
1480 LuaItemStack *o = checkobject(L, 1);
1481 ItemStack &item = o->m_stack;
1482 bool is_known = item.isKnown(get_server(L)->idef());
1483 lua_pushboolean(L, is_known);
1487 // get_definition(self) -> table
1488 // Returns the item definition table from minetest.registered_items,
1489 // or a fallback one (name="unknown")
1490 static int l_get_definition(lua_State *L)
1492 LuaItemStack *o = checkobject(L, 1);
1493 ItemStack &item = o->m_stack;
1495 // Get minetest.registered_items[name]
1496 lua_getglobal(L, "minetest");
1497 lua_getfield(L, -1, "registered_items");
1498 luaL_checktype(L, -1, LUA_TTABLE);
1499 lua_getfield(L, -1, item.name.c_str());
1500 if(lua_isnil(L, -1))
1503 lua_getfield(L, -1, "unknown");
1508 // get_tool_capabilities(self) -> table
1509 // Returns the effective tool digging properties.
1510 // Returns those of the hand ("") if this item has none associated.
1511 static int l_get_tool_capabilities(lua_State *L)
1513 LuaItemStack *o = checkobject(L, 1);
1514 ItemStack &item = o->m_stack;
1515 const ToolCapabilities &prop =
1516 item.getToolCapabilities(get_server(L)->idef());
1517 push_tool_capabilities(L, prop);
1521 // add_wear(self, amount) -> true/false
1522 // The range for "amount" is [0,65535]. Wear is only added if the item
1523 // is a tool. Adding wear might destroy the item.
1524 // Returns true if the item is (or was) a tool.
1525 static int l_add_wear(lua_State *L)
1527 LuaItemStack *o = checkobject(L, 1);
1528 ItemStack &item = o->m_stack;
1529 int amount = lua_tointeger(L, 2);
1530 bool result = item.addWear(amount, get_server(L)->idef());
1531 lua_pushboolean(L, result);
1535 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1536 // Returns leftover item stack
1537 static int l_add_item(lua_State *L)
1539 LuaItemStack *o = checkobject(L, 1);
1540 ItemStack &item = o->m_stack;
1541 ItemStack newitem = read_item(L, 2);
1542 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1543 create(L, leftover);
1547 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1548 // First return value is true iff the new item fits fully into the stack
1549 // Second return value is the would-be-left-over item stack
1550 static int l_item_fits(lua_State *L)
1552 LuaItemStack *o = checkobject(L, 1);
1553 ItemStack &item = o->m_stack;
1554 ItemStack newitem = read_item(L, 2);
1556 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1557 lua_pushboolean(L, fits); // first return value
1558 create(L, restitem); // second return value
1562 // take_item(self, takecount=1) -> itemstack
1563 static int l_take_item(lua_State *L)
1565 LuaItemStack *o = checkobject(L, 1);
1566 ItemStack &item = o->m_stack;
1568 if(!lua_isnone(L, 2))
1569 takecount = luaL_checkinteger(L, 2);
1570 ItemStack taken = item.takeItem(takecount);
1575 // peek_item(self, peekcount=1) -> itemstack
1576 static int l_peek_item(lua_State *L)
1578 LuaItemStack *o = checkobject(L, 1);
1579 ItemStack &item = o->m_stack;
1581 if(!lua_isnone(L, 2))
1582 peekcount = lua_tointeger(L, 2);
1583 ItemStack peekaboo = item.peekItem(peekcount);
1584 create(L, peekaboo);
1589 LuaItemStack(const ItemStack &item):
1598 const ItemStack& getItem() const
1602 ItemStack& getItem()
1607 // LuaItemStack(itemstack or itemstring or table or nil)
1608 // Creates an LuaItemStack and leaves it on top of stack
1609 static int create_object(lua_State *L)
1611 ItemStack item = read_item(L, 1);
1612 LuaItemStack *o = new LuaItemStack(item);
1613 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1614 luaL_getmetatable(L, className);
1615 lua_setmetatable(L, -2);
1618 // Not callable from Lua
1619 static int create(lua_State *L, const ItemStack &item)
1621 LuaItemStack *o = new LuaItemStack(item);
1622 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1623 luaL_getmetatable(L, className);
1624 lua_setmetatable(L, -2);
1628 static LuaItemStack* checkobject(lua_State *L, int narg)
1630 luaL_checktype(L, narg, LUA_TUSERDATA);
1631 void *ud = luaL_checkudata(L, narg, className);
1632 if(!ud) luaL_typerror(L, narg, className);
1633 return *(LuaItemStack**)ud; // unbox pointer
1636 static void Register(lua_State *L)
1639 int methodtable = lua_gettop(L);
1640 luaL_newmetatable(L, className);
1641 int metatable = lua_gettop(L);
1643 lua_pushliteral(L, "__metatable");
1644 lua_pushvalue(L, methodtable);
1645 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1647 lua_pushliteral(L, "__index");
1648 lua_pushvalue(L, methodtable);
1649 lua_settable(L, metatable);
1651 lua_pushliteral(L, "__gc");
1652 lua_pushcfunction(L, gc_object);
1653 lua_settable(L, metatable);
1655 lua_pop(L, 1); // drop metatable
1657 luaL_openlib(L, 0, methods, 0); // fill methodtable
1658 lua_pop(L, 1); // drop methodtable
1660 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1661 lua_register(L, className, create_object);
1664 const char LuaItemStack::className[] = "ItemStack";
1665 const luaL_reg LuaItemStack::methods[] = {
1666 method(LuaItemStack, is_empty),
1667 method(LuaItemStack, get_name),
1668 method(LuaItemStack, get_count),
1669 method(LuaItemStack, get_wear),
1670 method(LuaItemStack, get_metadata),
1671 method(LuaItemStack, clear),
1672 method(LuaItemStack, replace),
1673 method(LuaItemStack, to_string),
1674 method(LuaItemStack, to_table),
1675 method(LuaItemStack, get_stack_max),
1676 method(LuaItemStack, get_free_space),
1677 method(LuaItemStack, is_known),
1678 method(LuaItemStack, get_definition),
1679 method(LuaItemStack, get_tool_capabilities),
1680 method(LuaItemStack, add_wear),
1681 method(LuaItemStack, add_item),
1682 method(LuaItemStack, item_fits),
1683 method(LuaItemStack, take_item),
1684 method(LuaItemStack, peek_item),
1688 static ItemStack read_item(lua_State *L, int index)
1691 index = lua_gettop(L) + 1 + index;
1693 if(lua_isnil(L, index))
1697 else if(lua_isuserdata(L, index))
1699 // Convert from LuaItemStack
1700 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1701 return o->getItem();
1703 else if(lua_isstring(L, index))
1705 // Convert from itemstring
1706 std::string itemstring = lua_tostring(L, index);
1707 IItemDefManager *idef = get_server(L)->idef();
1711 item.deSerialize(itemstring, idef);
1714 catch(SerializationError &e)
1716 infostream<<"WARNING: unable to create item from itemstring"
1717 <<": "<<itemstring<<std::endl;
1721 else if(lua_istable(L, index))
1723 // Convert from table
1724 IItemDefManager *idef = get_server(L)->idef();
1725 std::string name = getstringfield_default(L, index, "name", "");
1726 int count = getintfield_default(L, index, "count", 1);
1727 int wear = getintfield_default(L, index, "wear", 0);
1728 std::string metadata = getstringfield_default(L, index, "metadata", "");
1729 return ItemStack(name, count, wear, metadata, idef);
1733 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1737 static std::vector<ItemStack> read_items(lua_State *L, int index)
1740 index = lua_gettop(L) + 1 + index;
1742 std::vector<ItemStack> items;
1743 luaL_checktype(L, index, LUA_TTABLE);
1745 while(lua_next(L, index) != 0){
1746 // key at index -2 and value at index -1
1747 items.push_back(read_item(L, -1));
1748 // removes value, keeps key for next iteration
1754 // creates a table of ItemStacks
1755 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1757 // Get the table insert function
1758 lua_getglobal(L, "table");
1759 lua_getfield(L, -1, "insert");
1760 int table_insert = lua_gettop(L);
1761 // Create and fill table
1763 int table = lua_gettop(L);
1764 for(u32 i=0; i<items.size(); i++){
1765 ItemStack item = items[i];
1766 lua_pushvalue(L, table_insert);
1767 lua_pushvalue(L, table);
1768 LuaItemStack::create(L, item);
1769 if(lua_pcall(L, 2, 0, 0))
1770 script_error(L, "error: %s", lua_tostring(L, -1));
1772 lua_remove(L, -2); // Remove table
1773 lua_remove(L, -2); // Remove insert
1783 InventoryLocation m_loc;
1785 static const char className[];
1786 static const luaL_reg methods[];
1788 static InvRef *checkobject(lua_State *L, int narg)
1790 luaL_checktype(L, narg, LUA_TUSERDATA);
1791 void *ud = luaL_checkudata(L, narg, className);
1792 if(!ud) luaL_typerror(L, narg, className);
1793 return *(InvRef**)ud; // unbox pointer
1796 static Inventory* getinv(lua_State *L, InvRef *ref)
1798 return get_server(L)->getInventory(ref->m_loc);
1801 static InventoryList* getlist(lua_State *L, InvRef *ref,
1802 const char *listname)
1804 Inventory *inv = getinv(L, ref);
1807 return inv->getList(listname);
1810 static void reportInventoryChange(lua_State *L, InvRef *ref)
1812 // Inform other things that the inventory has changed
1813 get_server(L)->setInventoryModified(ref->m_loc);
1816 // Exported functions
1818 // garbage collector
1819 static int gc_object(lua_State *L) {
1820 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1825 // is_empty(self, listname) -> true/false
1826 static int l_is_empty(lua_State *L)
1828 InvRef *ref = checkobject(L, 1);
1829 const char *listname = luaL_checkstring(L, 2);
1830 InventoryList *list = getlist(L, ref, listname);
1831 if(list && list->getUsedSlots() > 0){
1832 lua_pushboolean(L, false);
1834 lua_pushboolean(L, true);
1839 // get_size(self, listname)
1840 static int l_get_size(lua_State *L)
1842 InvRef *ref = checkobject(L, 1);
1843 const char *listname = luaL_checkstring(L, 2);
1844 InventoryList *list = getlist(L, ref, listname);
1846 lua_pushinteger(L, list->getSize());
1848 lua_pushinteger(L, 0);
1853 // get_width(self, listname)
1854 static int l_get_width(lua_State *L)
1856 InvRef *ref = checkobject(L, 1);
1857 const char *listname = luaL_checkstring(L, 2);
1858 InventoryList *list = getlist(L, ref, listname);
1860 lua_pushinteger(L, list->getWidth());
1862 lua_pushinteger(L, 0);
1867 // set_size(self, listname, size)
1868 static int l_set_size(lua_State *L)
1870 InvRef *ref = checkobject(L, 1);
1871 const char *listname = luaL_checkstring(L, 2);
1872 int newsize = luaL_checknumber(L, 3);
1873 Inventory *inv = getinv(L, ref);
1875 inv->deleteList(listname);
1876 reportInventoryChange(L, ref);
1879 InventoryList *list = inv->getList(listname);
1881 list->setSize(newsize);
1883 list = inv->addList(listname, newsize);
1885 reportInventoryChange(L, ref);
1889 // set_width(self, listname, size)
1890 static int l_set_width(lua_State *L)
1892 InvRef *ref = checkobject(L, 1);
1893 const char *listname = luaL_checkstring(L, 2);
1894 int newwidth = luaL_checknumber(L, 3);
1895 Inventory *inv = getinv(L, ref);
1896 InventoryList *list = inv->getList(listname);
1898 list->setWidth(newwidth);
1902 reportInventoryChange(L, ref);
1906 // get_stack(self, listname, i) -> itemstack
1907 static int l_get_stack(lua_State *L)
1909 InvRef *ref = checkobject(L, 1);
1910 const char *listname = luaL_checkstring(L, 2);
1911 int i = luaL_checknumber(L, 3) - 1;
1912 InventoryList *list = getlist(L, ref, listname);
1914 if(list != NULL && i >= 0 && i < (int) list->getSize())
1915 item = list->getItem(i);
1916 LuaItemStack::create(L, item);
1920 // set_stack(self, listname, i, stack) -> true/false
1921 static int l_set_stack(lua_State *L)
1923 InvRef *ref = checkobject(L, 1);
1924 const char *listname = luaL_checkstring(L, 2);
1925 int i = luaL_checknumber(L, 3) - 1;
1926 ItemStack newitem = read_item(L, 4);
1927 InventoryList *list = getlist(L, ref, listname);
1928 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1929 list->changeItem(i, newitem);
1930 reportInventoryChange(L, ref);
1931 lua_pushboolean(L, true);
1933 lua_pushboolean(L, false);
1938 // get_list(self, listname) -> list or nil
1939 static int l_get_list(lua_State *L)
1941 InvRef *ref = checkobject(L, 1);
1942 const char *listname = luaL_checkstring(L, 2);
1943 Inventory *inv = getinv(L, ref);
1944 inventory_get_list_to_lua(inv, listname, L);
1948 // set_list(self, listname, list)
1949 static int l_set_list(lua_State *L)
1951 InvRef *ref = checkobject(L, 1);
1952 const char *listname = luaL_checkstring(L, 2);
1953 Inventory *inv = getinv(L, ref);
1954 InventoryList *list = inv->getList(listname);
1956 inventory_set_list_from_lua(inv, listname, L, 3,
1959 inventory_set_list_from_lua(inv, listname, L, 3);
1960 reportInventoryChange(L, ref);
1964 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1965 // Returns the leftover stack
1966 static int l_add_item(lua_State *L)
1968 InvRef *ref = checkobject(L, 1);
1969 const char *listname = luaL_checkstring(L, 2);
1970 ItemStack item = read_item(L, 3);
1971 InventoryList *list = getlist(L, ref, listname);
1973 ItemStack leftover = list->addItem(item);
1974 if(leftover.count != item.count)
1975 reportInventoryChange(L, ref);
1976 LuaItemStack::create(L, leftover);
1978 LuaItemStack::create(L, item);
1983 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1984 // Returns true if the item completely fits into the list
1985 static int l_room_for_item(lua_State *L)
1987 InvRef *ref = checkobject(L, 1);
1988 const char *listname = luaL_checkstring(L, 2);
1989 ItemStack item = read_item(L, 3);
1990 InventoryList *list = getlist(L, ref, listname);
1992 lua_pushboolean(L, list->roomForItem(item));
1994 lua_pushboolean(L, false);
1999 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2000 // Returns true if the list contains the given count of the given item name
2001 static int l_contains_item(lua_State *L)
2003 InvRef *ref = checkobject(L, 1);
2004 const char *listname = luaL_checkstring(L, 2);
2005 ItemStack item = read_item(L, 3);
2006 InventoryList *list = getlist(L, ref, listname);
2008 lua_pushboolean(L, list->containsItem(item));
2010 lua_pushboolean(L, false);
2015 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2016 // Returns the items that were actually removed
2017 static int l_remove_item(lua_State *L)
2019 InvRef *ref = checkobject(L, 1);
2020 const char *listname = luaL_checkstring(L, 2);
2021 ItemStack item = read_item(L, 3);
2022 InventoryList *list = getlist(L, ref, listname);
2024 ItemStack removed = list->removeItem(item);
2025 if(!removed.empty())
2026 reportInventoryChange(L, ref);
2027 LuaItemStack::create(L, removed);
2029 LuaItemStack::create(L, ItemStack());
2035 InvRef(const InventoryLocation &loc):
2044 // Creates an InvRef and leaves it on top of stack
2045 // Not callable from Lua; all references are created on the C side.
2046 static void create(lua_State *L, const InventoryLocation &loc)
2048 InvRef *o = new InvRef(loc);
2049 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2050 luaL_getmetatable(L, className);
2051 lua_setmetatable(L, -2);
2053 static void createPlayer(lua_State *L, Player *player)
2055 InventoryLocation loc;
2056 loc.setPlayer(player->getName());
2059 static void createNodeMeta(lua_State *L, v3s16 p)
2061 InventoryLocation loc;
2066 static void Register(lua_State *L)
2069 int methodtable = lua_gettop(L);
2070 luaL_newmetatable(L, className);
2071 int metatable = lua_gettop(L);
2073 lua_pushliteral(L, "__metatable");
2074 lua_pushvalue(L, methodtable);
2075 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2077 lua_pushliteral(L, "__index");
2078 lua_pushvalue(L, methodtable);
2079 lua_settable(L, metatable);
2081 lua_pushliteral(L, "__gc");
2082 lua_pushcfunction(L, gc_object);
2083 lua_settable(L, metatable);
2085 lua_pop(L, 1); // drop metatable
2087 luaL_openlib(L, 0, methods, 0); // fill methodtable
2088 lua_pop(L, 1); // drop methodtable
2090 // Cannot be created from Lua
2091 //lua_register(L, className, create_object);
2094 const char InvRef::className[] = "InvRef";
2095 const luaL_reg InvRef::methods[] = {
2096 method(InvRef, is_empty),
2097 method(InvRef, get_size),
2098 method(InvRef, set_size),
2099 method(InvRef, get_width),
2100 method(InvRef, set_width),
2101 method(InvRef, get_stack),
2102 method(InvRef, set_stack),
2103 method(InvRef, get_list),
2104 method(InvRef, set_list),
2105 method(InvRef, add_item),
2106 method(InvRef, room_for_item),
2107 method(InvRef, contains_item),
2108 method(InvRef, remove_item),
2120 ServerEnvironment *m_env;
2122 static const char className[];
2123 static const luaL_reg methods[];
2125 static NodeMetaRef *checkobject(lua_State *L, int narg)
2127 luaL_checktype(L, narg, LUA_TUSERDATA);
2128 void *ud = luaL_checkudata(L, narg, className);
2129 if(!ud) luaL_typerror(L, narg, className);
2130 return *(NodeMetaRef**)ud; // unbox pointer
2133 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2135 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2136 if(meta == NULL && auto_create)
2138 meta = new NodeMetadata(ref->m_env->getGameDef());
2139 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2144 static void reportMetadataChange(NodeMetaRef *ref)
2146 // NOTE: This same code is in rollback_interface.cpp
2147 // Inform other things that the metadata has changed
2148 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2150 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2152 ref->m_env->getMap().dispatchEvent(&event);
2153 // Set the block to be saved
2154 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2156 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2157 "NodeMetaRef::reportMetadataChange");
2160 // Exported functions
2162 // garbage collector
2163 static int gc_object(lua_State *L) {
2164 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2169 // get_string(self, name)
2170 static int l_get_string(lua_State *L)
2172 NodeMetaRef *ref = checkobject(L, 1);
2173 std::string name = luaL_checkstring(L, 2);
2175 NodeMetadata *meta = getmeta(ref, false);
2177 lua_pushlstring(L, "", 0);
2180 std::string str = meta->getString(name);
2181 lua_pushlstring(L, str.c_str(), str.size());
2185 // set_string(self, name, var)
2186 static int l_set_string(lua_State *L)
2188 NodeMetaRef *ref = checkobject(L, 1);
2189 std::string name = luaL_checkstring(L, 2);
2191 const char *s = lua_tolstring(L, 3, &len);
2192 std::string str(s, len);
2194 NodeMetadata *meta = getmeta(ref, !str.empty());
2195 if(meta == NULL || str == meta->getString(name))
2197 meta->setString(name, str);
2198 reportMetadataChange(ref);
2202 // get_int(self, name)
2203 static int l_get_int(lua_State *L)
2205 NodeMetaRef *ref = checkobject(L, 1);
2206 std::string name = lua_tostring(L, 2);
2208 NodeMetadata *meta = getmeta(ref, false);
2210 lua_pushnumber(L, 0);
2213 std::string str = meta->getString(name);
2214 lua_pushnumber(L, stoi(str));
2218 // set_int(self, name, var)
2219 static int l_set_int(lua_State *L)
2221 NodeMetaRef *ref = checkobject(L, 1);
2222 std::string name = lua_tostring(L, 2);
2223 int a = lua_tointeger(L, 3);
2224 std::string str = itos(a);
2226 NodeMetadata *meta = getmeta(ref, true);
2227 if(meta == NULL || str == meta->getString(name))
2229 meta->setString(name, str);
2230 reportMetadataChange(ref);
2234 // get_float(self, name)
2235 static int l_get_float(lua_State *L)
2237 NodeMetaRef *ref = checkobject(L, 1);
2238 std::string name = lua_tostring(L, 2);
2240 NodeMetadata *meta = getmeta(ref, false);
2242 lua_pushnumber(L, 0);
2245 std::string str = meta->getString(name);
2246 lua_pushnumber(L, stof(str));
2250 // set_float(self, name, var)
2251 static int l_set_float(lua_State *L)
2253 NodeMetaRef *ref = checkobject(L, 1);
2254 std::string name = lua_tostring(L, 2);
2255 float a = lua_tonumber(L, 3);
2256 std::string str = ftos(a);
2258 NodeMetadata *meta = getmeta(ref, true);
2259 if(meta == NULL || str == meta->getString(name))
2261 meta->setString(name, str);
2262 reportMetadataChange(ref);
2266 // get_inventory(self)
2267 static int l_get_inventory(lua_State *L)
2269 NodeMetaRef *ref = checkobject(L, 1);
2270 getmeta(ref, true); // try to ensure the metadata exists
2271 InvRef::createNodeMeta(L, ref->m_p);
2276 static int l_to_table(lua_State *L)
2278 NodeMetaRef *ref = checkobject(L, 1);
2280 NodeMetadata *meta = getmeta(ref, true);
2289 std::map<std::string, std::string> fields = meta->getStrings();
2290 for(std::map<std::string, std::string>::const_iterator
2291 i = fields.begin(); i != fields.end(); i++){
2292 const std::string &name = i->first;
2293 const std::string &value = i->second;
2294 lua_pushlstring(L, name.c_str(), name.size());
2295 lua_pushlstring(L, value.c_str(), value.size());
2296 lua_settable(L, -3);
2299 lua_setfield(L, -2, "fields");
2302 Inventory *inv = meta->getInventory();
2304 std::vector<const InventoryList*> lists = inv->getLists();
2305 for(std::vector<const InventoryList*>::const_iterator
2306 i = lists.begin(); i != lists.end(); i++){
2307 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2308 lua_setfield(L, -2, (*i)->getName().c_str());
2311 lua_setfield(L, -2, "inventory");
2315 // from_table(self, table)
2316 static int l_from_table(lua_State *L)
2318 NodeMetaRef *ref = checkobject(L, 1);
2321 if(lua_isnil(L, base)){
2323 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2324 lua_pushboolean(L, true);
2328 // Has metadata; clear old one first
2329 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2330 // Create new metadata
2331 NodeMetadata *meta = getmeta(ref, true);
2333 lua_getfield(L, base, "fields");
2334 int fieldstable = lua_gettop(L);
2336 while(lua_next(L, fieldstable) != 0){
2337 // key at index -2 and value at index -1
2338 std::string name = lua_tostring(L, -2);
2340 const char *cs = lua_tolstring(L, -1, &cl);
2341 std::string value(cs, cl);
2342 meta->setString(name, value);
2343 lua_pop(L, 1); // removes value, keeps key for next iteration
2346 Inventory *inv = meta->getInventory();
2347 lua_getfield(L, base, "inventory");
2348 int inventorytable = lua_gettop(L);
2350 while(lua_next(L, inventorytable) != 0){
2351 // key at index -2 and value at index -1
2352 std::string name = lua_tostring(L, -2);
2353 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2354 lua_pop(L, 1); // removes value, keeps key for next iteration
2356 reportMetadataChange(ref);
2357 lua_pushboolean(L, true);
2362 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2372 // Creates an NodeMetaRef and leaves it on top of stack
2373 // Not callable from Lua; all references are created on the C side.
2374 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2376 NodeMetaRef *o = new NodeMetaRef(p, env);
2377 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2378 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2379 luaL_getmetatable(L, className);
2380 lua_setmetatable(L, -2);
2383 static void Register(lua_State *L)
2386 int methodtable = lua_gettop(L);
2387 luaL_newmetatable(L, className);
2388 int metatable = lua_gettop(L);
2390 lua_pushliteral(L, "__metatable");
2391 lua_pushvalue(L, methodtable);
2392 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2394 lua_pushliteral(L, "__index");
2395 lua_pushvalue(L, methodtable);
2396 lua_settable(L, metatable);
2398 lua_pushliteral(L, "__gc");
2399 lua_pushcfunction(L, gc_object);
2400 lua_settable(L, metatable);
2402 lua_pop(L, 1); // drop metatable
2404 luaL_openlib(L, 0, methods, 0); // fill methodtable
2405 lua_pop(L, 1); // drop methodtable
2407 // Cannot be created from Lua
2408 //lua_register(L, className, create_object);
2411 const char NodeMetaRef::className[] = "NodeMetaRef";
2412 const luaL_reg NodeMetaRef::methods[] = {
2413 method(NodeMetaRef, get_string),
2414 method(NodeMetaRef, set_string),
2415 method(NodeMetaRef, get_int),
2416 method(NodeMetaRef, set_int),
2417 method(NodeMetaRef, get_float),
2418 method(NodeMetaRef, set_float),
2419 method(NodeMetaRef, get_inventory),
2420 method(NodeMetaRef, to_table),
2421 method(NodeMetaRef, from_table),
2432 ServerActiveObject *m_object;
2434 static const char className[];
2435 static const luaL_reg methods[];
2437 static ObjectRef *checkobject(lua_State *L, int narg)
2439 luaL_checktype(L, narg, LUA_TUSERDATA);
2440 void *ud = luaL_checkudata(L, narg, className);
2441 if(!ud) luaL_typerror(L, narg, className);
2442 return *(ObjectRef**)ud; // unbox pointer
2445 static ServerActiveObject* getobject(ObjectRef *ref)
2447 ServerActiveObject *co = ref->m_object;
2451 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2453 ServerActiveObject *obj = getobject(ref);
2456 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2458 return (LuaEntitySAO*)obj;
2461 static PlayerSAO* getplayersao(ObjectRef *ref)
2463 ServerActiveObject *obj = getobject(ref);
2466 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2468 return (PlayerSAO*)obj;
2471 static Player* getplayer(ObjectRef *ref)
2473 PlayerSAO *playersao = getplayersao(ref);
2474 if(playersao == NULL)
2476 return playersao->getPlayer();
2479 // Exported functions
2481 // garbage collector
2482 static int gc_object(lua_State *L) {
2483 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2484 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2490 static int l_remove(lua_State *L)
2492 ObjectRef *ref = checkobject(L, 1);
2493 ServerActiveObject *co = getobject(ref);
2494 if(co == NULL) return 0;
2495 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2496 co->m_removed = true;
2501 // returns: {x=num, y=num, z=num}
2502 static int l_getpos(lua_State *L)
2504 ObjectRef *ref = checkobject(L, 1);
2505 ServerActiveObject *co = getobject(ref);
2506 if(co == NULL) return 0;
2507 v3f pos = co->getBasePosition() / BS;
2509 lua_pushnumber(L, pos.X);
2510 lua_setfield(L, -2, "x");
2511 lua_pushnumber(L, pos.Y);
2512 lua_setfield(L, -2, "y");
2513 lua_pushnumber(L, pos.Z);
2514 lua_setfield(L, -2, "z");
2518 // setpos(self, pos)
2519 static int l_setpos(lua_State *L)
2521 ObjectRef *ref = checkobject(L, 1);
2522 //LuaEntitySAO *co = getluaobject(ref);
2523 ServerActiveObject *co = getobject(ref);
2524 if(co == NULL) return 0;
2526 v3f pos = checkFloatPos(L, 2);
2532 // moveto(self, pos, continuous=false)
2533 static int l_moveto(lua_State *L)
2535 ObjectRef *ref = checkobject(L, 1);
2536 //LuaEntitySAO *co = getluaobject(ref);
2537 ServerActiveObject *co = getobject(ref);
2538 if(co == NULL) return 0;
2540 v3f pos = checkFloatPos(L, 2);
2542 bool continuous = lua_toboolean(L, 3);
2544 co->moveTo(pos, continuous);
2548 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2549 static int l_punch(lua_State *L)
2551 ObjectRef *ref = checkobject(L, 1);
2552 ObjectRef *puncher_ref = checkobject(L, 2);
2553 ServerActiveObject *co = getobject(ref);
2554 ServerActiveObject *puncher = getobject(puncher_ref);
2555 if(co == NULL) return 0;
2556 if(puncher == NULL) return 0;
2558 if(lua_type(L, 5) != LUA_TTABLE)
2559 dir = co->getBasePosition() - puncher->getBasePosition();
2561 dir = read_v3f(L, 5);
2562 float time_from_last_punch = 1000000;
2563 if(lua_isnumber(L, 3))
2564 time_from_last_punch = lua_tonumber(L, 3);
2565 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2568 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2572 // right_click(self, clicker); clicker = an another ObjectRef
2573 static int l_right_click(lua_State *L)
2575 ObjectRef *ref = checkobject(L, 1);
2576 ObjectRef *ref2 = checkobject(L, 2);
2577 ServerActiveObject *co = getobject(ref);
2578 ServerActiveObject *co2 = getobject(ref2);
2579 if(co == NULL) return 0;
2580 if(co2 == NULL) return 0;
2582 co->rightClick(co2);
2587 // hp = number of hitpoints (2 * number of hearts)
2589 static int l_set_hp(lua_State *L)
2591 ObjectRef *ref = checkobject(L, 1);
2592 luaL_checknumber(L, 2);
2593 ServerActiveObject *co = getobject(ref);
2594 if(co == NULL) return 0;
2595 int hp = lua_tonumber(L, 2);
2596 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2597 <<" hp="<<hp<<std::endl;*/
2605 // returns: number of hitpoints (2 * number of hearts)
2606 // 0 if not applicable to this type of object
2607 static int l_get_hp(lua_State *L)
2609 ObjectRef *ref = checkobject(L, 1);
2610 ServerActiveObject *co = getobject(ref);
2613 lua_pushnumber(L, 1);
2616 int hp = co->getHP();
2617 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2618 <<" hp="<<hp<<std::endl;*/
2620 lua_pushnumber(L, hp);
2624 // get_inventory(self)
2625 static int l_get_inventory(lua_State *L)
2627 ObjectRef *ref = checkobject(L, 1);
2628 ServerActiveObject *co = getobject(ref);
2629 if(co == NULL) return 0;
2631 InventoryLocation loc = co->getInventoryLocation();
2632 if(get_server(L)->getInventory(loc) != NULL)
2633 InvRef::create(L, loc);
2635 lua_pushnil(L); // An object may have no inventory (nil)
2639 // get_wield_list(self)
2640 static int l_get_wield_list(lua_State *L)
2642 ObjectRef *ref = checkobject(L, 1);
2643 ServerActiveObject *co = getobject(ref);
2644 if(co == NULL) return 0;
2646 lua_pushstring(L, co->getWieldList().c_str());
2650 // get_wield_index(self)
2651 static int l_get_wield_index(lua_State *L)
2653 ObjectRef *ref = checkobject(L, 1);
2654 ServerActiveObject *co = getobject(ref);
2655 if(co == NULL) return 0;
2657 lua_pushinteger(L, co->getWieldIndex() + 1);
2661 // get_wielded_item(self)
2662 static int l_get_wielded_item(lua_State *L)
2664 ObjectRef *ref = checkobject(L, 1);
2665 ServerActiveObject *co = getobject(ref);
2668 LuaItemStack::create(L, ItemStack());
2672 LuaItemStack::create(L, co->getWieldedItem());
2676 // set_wielded_item(self, itemstack or itemstring or table or nil)
2677 static int l_set_wielded_item(lua_State *L)
2679 ObjectRef *ref = checkobject(L, 1);
2680 ServerActiveObject *co = getobject(ref);
2681 if(co == NULL) return 0;
2683 ItemStack item = read_item(L, 2);
2684 bool success = co->setWieldedItem(item);
2685 lua_pushboolean(L, success);
2689 // set_armor_groups(self, groups)
2690 static int l_set_armor_groups(lua_State *L)
2692 ObjectRef *ref = checkobject(L, 1);
2693 ServerActiveObject *co = getobject(ref);
2694 if(co == NULL) return 0;
2696 ItemGroupList groups;
2697 read_groups(L, 2, groups);
2698 co->setArmorGroups(groups);
2702 // setanimations(self, frames, frame_speed, frame_blend)
2703 static int l_set_animations(lua_State *L)
2705 ObjectRef *ref = checkobject(L, 1);
2706 ServerActiveObject *co = getobject(ref);
2707 if(co == NULL) return 0;
2710 v2f frames = v2f(1, 1);
2711 if(!lua_isnil(L, 2))
2712 frames = read_v2f(L, 2);
2713 float frame_speed = 15;
2714 if(!lua_isnil(L, 3))
2715 frame_speed = lua_tonumber(L, 3);
2716 float frame_blend = 0;
2717 if(!lua_isnil(L, 4))
2718 frame_blend = lua_tonumber(L, 4);
2719 co->setAnimations(frames, frame_speed, frame_blend);
2723 // setboneposrot(std::string bone, v3f position, v3f rotation)
2724 static int l_set_bone_posrot(lua_State *L)
2726 ObjectRef *ref = checkobject(L, 1);
2727 ServerActiveObject *co = getobject(ref);
2728 if(co == NULL) return 0;
2731 std::string bone = "";
2732 if(!lua_isnil(L, 2))
2733 bone = lua_tostring(L, 2);
2734 v3f position = v3f(0, 0, 0);
2735 if(!lua_isnil(L, 3))
2736 position = read_v3f(L, 3);
2737 v3f rotation = v3f(0, 0, 0);
2738 if(!lua_isnil(L, 4))
2739 rotation = read_v3f(L, 4);
2740 co->setBonePosRot(bone, position, rotation);
2744 // set_properties(self, properties)
2745 static int l_set_properties(lua_State *L)
2747 ObjectRef *ref = checkobject(L, 1);
2748 ServerActiveObject *co = getobject(ref);
2749 if(co == NULL) return 0;
2750 ObjectProperties *prop = co->accessObjectProperties();
2753 read_object_properties(L, 2, prop);
2754 co->notifyObjectPropertiesModified();
2758 /* LuaEntitySAO-only */
2760 // setvelocity(self, {x=num, y=num, z=num})
2761 static int l_setvelocity(lua_State *L)
2763 ObjectRef *ref = checkobject(L, 1);
2764 LuaEntitySAO *co = getluaobject(ref);
2765 if(co == NULL) return 0;
2766 v3f pos = checkFloatPos(L, 2);
2768 co->setVelocity(pos);
2772 // getvelocity(self)
2773 static int l_getvelocity(lua_State *L)
2775 ObjectRef *ref = checkobject(L, 1);
2776 LuaEntitySAO *co = getluaobject(ref);
2777 if(co == NULL) return 0;
2779 v3f v = co->getVelocity();
2784 // setacceleration(self, {x=num, y=num, z=num})
2785 static int l_setacceleration(lua_State *L)
2787 ObjectRef *ref = checkobject(L, 1);
2788 LuaEntitySAO *co = getluaobject(ref);
2789 if(co == NULL) return 0;
2791 v3f pos = checkFloatPos(L, 2);
2793 co->setAcceleration(pos);
2797 // getacceleration(self)
2798 static int l_getacceleration(lua_State *L)
2800 ObjectRef *ref = checkobject(L, 1);
2801 LuaEntitySAO *co = getluaobject(ref);
2802 if(co == NULL) return 0;
2804 v3f v = co->getAcceleration();
2809 // setyaw(self, radians)
2810 static int l_setyaw(lua_State *L)
2812 ObjectRef *ref = checkobject(L, 1);
2813 LuaEntitySAO *co = getluaobject(ref);
2814 if(co == NULL) return 0;
2815 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2822 static int l_getyaw(lua_State *L)
2824 ObjectRef *ref = checkobject(L, 1);
2825 LuaEntitySAO *co = getluaobject(ref);
2826 if(co == NULL) return 0;
2828 float yaw = co->getYaw() * core::DEGTORAD;
2829 lua_pushnumber(L, yaw);
2833 // settexturemod(self, mod)
2834 static int l_settexturemod(lua_State *L)
2836 ObjectRef *ref = checkobject(L, 1);
2837 LuaEntitySAO *co = getluaobject(ref);
2838 if(co == NULL) return 0;
2840 std::string mod = luaL_checkstring(L, 2);
2841 co->setTextureMod(mod);
2845 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2846 // select_horiz_by_yawpitch=false)
2847 static int l_setsprite(lua_State *L)
2849 ObjectRef *ref = checkobject(L, 1);
2850 LuaEntitySAO *co = getluaobject(ref);
2851 if(co == NULL) return 0;
2854 if(!lua_isnil(L, 2))
2855 p = read_v2s16(L, 2);
2857 if(!lua_isnil(L, 3))
2858 num_frames = lua_tonumber(L, 3);
2859 float framelength = 0.2;
2860 if(!lua_isnil(L, 4))
2861 framelength = lua_tonumber(L, 4);
2862 bool select_horiz_by_yawpitch = false;
2863 if(!lua_isnil(L, 5))
2864 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2865 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2870 // get_entity_name(self)
2871 static int l_get_entity_name(lua_State *L)
2873 ObjectRef *ref = checkobject(L, 1);
2874 LuaEntitySAO *co = getluaobject(ref);
2875 if(co == NULL) return 0;
2877 std::string name = co->getName();
2878 lua_pushstring(L, name.c_str());
2882 // get_luaentity(self)
2883 static int l_get_luaentity(lua_State *L)
2885 ObjectRef *ref = checkobject(L, 1);
2886 LuaEntitySAO *co = getluaobject(ref);
2887 if(co == NULL) return 0;
2889 luaentity_get(L, co->getId());
2896 static int l_is_player(lua_State *L)
2898 ObjectRef *ref = checkobject(L, 1);
2899 Player *player = getplayer(ref);
2900 lua_pushboolean(L, (player != NULL));
2904 // get_player_name(self)
2905 static int l_get_player_name(lua_State *L)
2907 ObjectRef *ref = checkobject(L, 1);
2908 Player *player = getplayer(ref);
2910 lua_pushlstring(L, "", 0);
2914 lua_pushstring(L, player->getName());
2918 // get_look_dir(self)
2919 static int l_get_look_dir(lua_State *L)
2921 ObjectRef *ref = checkobject(L, 1);
2922 Player *player = getplayer(ref);
2923 if(player == NULL) return 0;
2925 float pitch = player->getRadPitch();
2926 float yaw = player->getRadYaw();
2927 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2932 // get_look_pitch(self)
2933 static int l_get_look_pitch(lua_State *L)
2935 ObjectRef *ref = checkobject(L, 1);
2936 Player *player = getplayer(ref);
2937 if(player == NULL) return 0;
2939 lua_pushnumber(L, player->getRadPitch());
2943 // get_look_yaw(self)
2944 static int l_get_look_yaw(lua_State *L)
2946 ObjectRef *ref = checkobject(L, 1);
2947 Player *player = getplayer(ref);
2948 if(player == NULL) return 0;
2950 lua_pushnumber(L, player->getRadYaw());
2954 // set_inventory_formspec(self, formspec)
2955 static int l_set_inventory_formspec(lua_State *L)
2957 ObjectRef *ref = checkobject(L, 1);
2958 Player *player = getplayer(ref);
2959 if(player == NULL) return 0;
2960 std::string formspec = luaL_checkstring(L, 2);
2962 player->inventory_formspec = formspec;
2963 get_server(L)->reportInventoryFormspecModified(player->getName());
2964 lua_pushboolean(L, true);
2968 // get_inventory_formspec(self) -> formspec
2969 static int l_get_inventory_formspec(lua_State *L)
2971 ObjectRef *ref = checkobject(L, 1);
2972 Player *player = getplayer(ref);
2973 if(player == NULL) return 0;
2975 std::string formspec = player->inventory_formspec;
2976 lua_pushlstring(L, formspec.c_str(), formspec.size());
2981 ObjectRef(ServerActiveObject *object):
2984 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2990 infostream<<"ObjectRef destructing for id="
2991 <<m_object->getId()<<std::endl;
2993 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2996 // Creates an ObjectRef and leaves it on top of stack
2997 // Not callable from Lua; all references are created on the C side.
2998 static void create(lua_State *L, ServerActiveObject *object)
3000 ObjectRef *o = new ObjectRef(object);
3001 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3002 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3003 luaL_getmetatable(L, className);
3004 lua_setmetatable(L, -2);
3007 static void set_null(lua_State *L)
3009 ObjectRef *o = checkobject(L, -1);
3013 static void Register(lua_State *L)
3016 int methodtable = lua_gettop(L);
3017 luaL_newmetatable(L, className);
3018 int metatable = lua_gettop(L);
3020 lua_pushliteral(L, "__metatable");
3021 lua_pushvalue(L, methodtable);
3022 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3024 lua_pushliteral(L, "__index");
3025 lua_pushvalue(L, methodtable);
3026 lua_settable(L, metatable);
3028 lua_pushliteral(L, "__gc");
3029 lua_pushcfunction(L, gc_object);
3030 lua_settable(L, metatable);
3032 lua_pop(L, 1); // drop metatable
3034 luaL_openlib(L, 0, methods, 0); // fill methodtable
3035 lua_pop(L, 1); // drop methodtable
3037 // Cannot be created from Lua
3038 //lua_register(L, className, create_object);
3041 const char ObjectRef::className[] = "ObjectRef";
3042 const luaL_reg ObjectRef::methods[] = {
3043 // ServerActiveObject
3044 method(ObjectRef, remove),
3045 method(ObjectRef, getpos),
3046 method(ObjectRef, setpos),
3047 method(ObjectRef, moveto),
3048 method(ObjectRef, punch),
3049 method(ObjectRef, right_click),
3050 method(ObjectRef, set_hp),
3051 method(ObjectRef, get_hp),
3052 method(ObjectRef, get_inventory),
3053 method(ObjectRef, get_wield_list),
3054 method(ObjectRef, get_wield_index),
3055 method(ObjectRef, get_wielded_item),
3056 method(ObjectRef, set_wielded_item),
3057 method(ObjectRef, set_armor_groups),
3058 method(ObjectRef, set_animations),
3059 method(ObjectRef, set_bone_posrot),
3060 method(ObjectRef, set_properties),
3061 // LuaEntitySAO-only
3062 method(ObjectRef, setvelocity),
3063 method(ObjectRef, getvelocity),
3064 method(ObjectRef, setacceleration),
3065 method(ObjectRef, getacceleration),
3066 method(ObjectRef, setyaw),
3067 method(ObjectRef, getyaw),
3068 method(ObjectRef, settexturemod),
3069 method(ObjectRef, setsprite),
3070 method(ObjectRef, get_entity_name),
3071 method(ObjectRef, get_luaentity),
3073 method(ObjectRef, is_player),
3074 method(ObjectRef, get_player_name),
3075 method(ObjectRef, get_look_dir),
3076 method(ObjectRef, get_look_pitch),
3077 method(ObjectRef, get_look_yaw),
3078 method(ObjectRef, set_inventory_formspec),
3079 method(ObjectRef, get_inventory_formspec),
3083 // Creates a new anonymous reference if cobj=NULL or id=0
3084 static void objectref_get_or_create(lua_State *L,
3085 ServerActiveObject *cobj)
3087 if(cobj == NULL || cobj->getId() == 0){
3088 ObjectRef::create(L, cobj);
3090 objectref_get(L, cobj->getId());
3099 class LuaPerlinNoise
3106 static const char className[];
3107 static const luaL_reg methods[];
3109 // Exported functions
3111 // garbage collector
3112 static int gc_object(lua_State *L)
3114 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3119 static int l_get2d(lua_State *L)
3121 LuaPerlinNoise *o = checkobject(L, 1);
3122 v2f pos2d = read_v2f(L,2);
3123 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3124 lua_pushnumber(L, val);
3127 static int l_get3d(lua_State *L)
3129 LuaPerlinNoise *o = checkobject(L, 1);
3130 v3f pos3d = read_v3f(L,2);
3131 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3132 lua_pushnumber(L, val);
3137 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3141 persistence(a_persistence),
3150 // LuaPerlinNoise(seed, octaves, persistence, scale)
3151 // Creates an LuaPerlinNoise and leaves it on top of stack
3152 static int create_object(lua_State *L)
3154 int seed = luaL_checkint(L, 1);
3155 int octaves = luaL_checkint(L, 2);
3156 double persistence = luaL_checknumber(L, 3);
3157 double scale = luaL_checknumber(L, 4);
3158 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3159 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3160 luaL_getmetatable(L, className);
3161 lua_setmetatable(L, -2);
3165 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3167 luaL_checktype(L, narg, LUA_TUSERDATA);
3168 void *ud = luaL_checkudata(L, narg, className);
3169 if(!ud) luaL_typerror(L, narg, className);
3170 return *(LuaPerlinNoise**)ud; // unbox pointer
3173 static void Register(lua_State *L)
3176 int methodtable = lua_gettop(L);
3177 luaL_newmetatable(L, className);
3178 int metatable = lua_gettop(L);
3180 lua_pushliteral(L, "__metatable");
3181 lua_pushvalue(L, methodtable);
3182 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3184 lua_pushliteral(L, "__index");
3185 lua_pushvalue(L, methodtable);
3186 lua_settable(L, metatable);
3188 lua_pushliteral(L, "__gc");
3189 lua_pushcfunction(L, gc_object);
3190 lua_settable(L, metatable);
3192 lua_pop(L, 1); // drop metatable
3194 luaL_openlib(L, 0, methods, 0); // fill methodtable
3195 lua_pop(L, 1); // drop methodtable
3197 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3198 lua_register(L, className, create_object);
3201 const char LuaPerlinNoise::className[] = "PerlinNoise";
3202 const luaL_reg LuaPerlinNoise::methods[] = {
3203 method(LuaPerlinNoise, get2d),
3204 method(LuaPerlinNoise, get3d),
3216 ServerEnvironment *m_env;
3218 static const char className[];
3219 static const luaL_reg methods[];
3221 static int gc_object(lua_State *L) {
3222 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3227 static NodeTimerRef *checkobject(lua_State *L, int narg)
3229 luaL_checktype(L, narg, LUA_TUSERDATA);
3230 void *ud = luaL_checkudata(L, narg, className);
3231 if(!ud) luaL_typerror(L, narg, className);
3232 return *(NodeTimerRef**)ud; // unbox pointer
3235 static int l_set(lua_State *L)
3237 NodeTimerRef *o = checkobject(L, 1);
3238 ServerEnvironment *env = o->m_env;
3239 if(env == NULL) return 0;
3240 f32 t = luaL_checknumber(L,2);
3241 f32 e = luaL_checknumber(L,3);
3242 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3246 static int l_start(lua_State *L)
3248 NodeTimerRef *o = checkobject(L, 1);
3249 ServerEnvironment *env = o->m_env;
3250 if(env == NULL) return 0;
3251 f32 t = luaL_checknumber(L,2);
3252 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3256 static int l_stop(lua_State *L)
3258 NodeTimerRef *o = checkobject(L, 1);
3259 ServerEnvironment *env = o->m_env;
3260 if(env == NULL) return 0;
3261 env->getMap().removeNodeTimer(o->m_p);
3265 static int l_is_started(lua_State *L)
3267 NodeTimerRef *o = checkobject(L, 1);
3268 ServerEnvironment *env = o->m_env;
3269 if(env == NULL) return 0;
3271 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3272 lua_pushboolean(L,(t.timeout != 0));
3276 static int l_get_timeout(lua_State *L)
3278 NodeTimerRef *o = checkobject(L, 1);
3279 ServerEnvironment *env = o->m_env;
3280 if(env == NULL) return 0;
3282 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3283 lua_pushnumber(L,t.timeout);
3287 static int l_get_elapsed(lua_State *L)
3289 NodeTimerRef *o = checkobject(L, 1);
3290 ServerEnvironment *env = o->m_env;
3291 if(env == NULL) return 0;
3293 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3294 lua_pushnumber(L,t.elapsed);
3299 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3309 // Creates an NodeTimerRef and leaves it on top of stack
3310 // Not callable from Lua; all references are created on the C side.
3311 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3313 NodeTimerRef *o = new NodeTimerRef(p, env);
3314 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3315 luaL_getmetatable(L, className);
3316 lua_setmetatable(L, -2);
3319 static void set_null(lua_State *L)
3321 NodeTimerRef *o = checkobject(L, -1);
3325 static void Register(lua_State *L)
3328 int methodtable = lua_gettop(L);
3329 luaL_newmetatable(L, className);
3330 int metatable = lua_gettop(L);
3332 lua_pushliteral(L, "__metatable");
3333 lua_pushvalue(L, methodtable);
3334 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3336 lua_pushliteral(L, "__index");
3337 lua_pushvalue(L, methodtable);
3338 lua_settable(L, metatable);
3340 lua_pushliteral(L, "__gc");
3341 lua_pushcfunction(L, gc_object);
3342 lua_settable(L, metatable);
3344 lua_pop(L, 1); // drop metatable
3346 luaL_openlib(L, 0, methods, 0); // fill methodtable
3347 lua_pop(L, 1); // drop methodtable
3349 // Cannot be created from Lua
3350 //lua_register(L, className, create_object);
3353 const char NodeTimerRef::className[] = "NodeTimerRef";
3354 const luaL_reg NodeTimerRef::methods[] = {
3355 method(NodeTimerRef, start),
3356 method(NodeTimerRef, set),
3357 method(NodeTimerRef, stop),
3358 method(NodeTimerRef, is_started),
3359 method(NodeTimerRef, get_timeout),
3360 method(NodeTimerRef, get_elapsed),
3371 ServerEnvironment *m_env;
3373 static const char className[];
3374 static const luaL_reg methods[];
3376 static int gc_object(lua_State *L) {
3377 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3382 static EnvRef *checkobject(lua_State *L, int narg)
3384 luaL_checktype(L, narg, LUA_TUSERDATA);
3385 void *ud = luaL_checkudata(L, narg, className);
3386 if(!ud) luaL_typerror(L, narg, className);
3387 return *(EnvRef**)ud; // unbox pointer
3390 // Exported functions
3392 // EnvRef:set_node(pos, node)
3393 // pos = {x=num, y=num, z=num}
3394 static int l_set_node(lua_State *L)
3396 EnvRef *o = checkobject(L, 1);
3397 ServerEnvironment *env = o->m_env;
3398 if(env == NULL) return 0;
3399 INodeDefManager *ndef = env->getGameDef()->ndef();
3401 v3s16 pos = read_v3s16(L, 2);
3402 MapNode n = readnode(L, 3, ndef);
3404 MapNode n_old = env->getMap().getNodeNoEx(pos);
3406 if(ndef->get(n_old).has_on_destruct)
3407 scriptapi_node_on_destruct(L, pos, n_old);
3409 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3411 // Call post-destructor
3412 if(ndef->get(n_old).has_after_destruct)
3413 scriptapi_node_after_destruct(L, pos, n_old);
3415 if(ndef->get(n).has_on_construct)
3416 scriptapi_node_on_construct(L, pos, n);
3418 lua_pushboolean(L, succeeded);
3422 static int l_add_node(lua_State *L)
3424 return l_set_node(L);
3427 // EnvRef:remove_node(pos)
3428 // pos = {x=num, y=num, z=num}
3429 static int l_remove_node(lua_State *L)
3431 EnvRef *o = checkobject(L, 1);
3432 ServerEnvironment *env = o->m_env;
3433 if(env == NULL) return 0;
3434 INodeDefManager *ndef = env->getGameDef()->ndef();
3436 v3s16 pos = read_v3s16(L, 2);
3438 MapNode n_old = env->getMap().getNodeNoEx(pos);
3440 if(ndef->get(n_old).has_on_destruct)
3441 scriptapi_node_on_destruct(L, pos, n_old);
3443 // This is slightly optimized compared to addNodeWithEvent(air)
3444 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3446 // Call post-destructor
3447 if(ndef->get(n_old).has_after_destruct)
3448 scriptapi_node_after_destruct(L, pos, n_old);
3450 lua_pushboolean(L, succeeded);
3451 // Air doesn't require constructor
3455 // EnvRef:get_node(pos)
3456 // pos = {x=num, y=num, z=num}
3457 static int l_get_node(lua_State *L)
3459 EnvRef *o = checkobject(L, 1);
3460 ServerEnvironment *env = o->m_env;
3461 if(env == NULL) return 0;
3463 v3s16 pos = read_v3s16(L, 2);
3465 MapNode n = env->getMap().getNodeNoEx(pos);
3467 pushnode(L, n, env->getGameDef()->ndef());
3471 // EnvRef:get_node_or_nil(pos)
3472 // pos = {x=num, y=num, z=num}
3473 static int l_get_node_or_nil(lua_State *L)
3475 EnvRef *o = checkobject(L, 1);
3476 ServerEnvironment *env = o->m_env;
3477 if(env == NULL) return 0;
3479 v3s16 pos = read_v3s16(L, 2);
3482 MapNode n = env->getMap().getNode(pos);
3484 pushnode(L, n, env->getGameDef()->ndef());
3486 } catch(InvalidPositionException &e)
3493 // EnvRef:get_node_light(pos, timeofday)
3494 // pos = {x=num, y=num, z=num}
3495 // timeofday: nil = current time, 0 = night, 0.5 = day
3496 static int l_get_node_light(lua_State *L)
3498 EnvRef *o = checkobject(L, 1);
3499 ServerEnvironment *env = o->m_env;
3500 if(env == NULL) return 0;
3502 v3s16 pos = read_v3s16(L, 2);
3503 u32 time_of_day = env->getTimeOfDay();
3504 if(lua_isnumber(L, 3))
3505 time_of_day = 24000.0 * lua_tonumber(L, 3);
3506 time_of_day %= 24000;
3507 u32 dnr = time_to_daynight_ratio(time_of_day);
3508 MapNode n = env->getMap().getNodeNoEx(pos);
3510 MapNode n = env->getMap().getNode(pos);
3511 INodeDefManager *ndef = env->getGameDef()->ndef();
3512 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3514 } catch(InvalidPositionException &e)
3521 // EnvRef:place_node(pos, node)
3522 // pos = {x=num, y=num, z=num}
3523 static int l_place_node(lua_State *L)
3525 EnvRef *o = checkobject(L, 1);
3526 ServerEnvironment *env = o->m_env;
3527 if(env == NULL) return 0;
3528 v3s16 pos = read_v3s16(L, 2);
3529 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3531 // Don't attempt to load non-loaded area as of now
3532 MapNode n_old = env->getMap().getNodeNoEx(pos);
3533 if(n_old.getContent() == CONTENT_IGNORE){
3534 lua_pushboolean(L, false);
3537 // Create item to place
3538 INodeDefManager *ndef = get_server(L)->ndef();
3539 IItemDefManager *idef = get_server(L)->idef();
3540 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3541 // Make pointed position
3542 PointedThing pointed;
3543 pointed.type = POINTEDTHING_NODE;
3544 pointed.node_abovesurface = pos;
3545 pointed.node_undersurface = pos + v3s16(0,-1,0);
3546 // Place it with a NULL placer (appears in Lua as a non-functional
3548 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3549 lua_pushboolean(L, success);
3553 // EnvRef:dig_node(pos)
3554 // pos = {x=num, y=num, z=num}
3555 static int l_dig_node(lua_State *L)
3557 EnvRef *o = checkobject(L, 1);
3558 ServerEnvironment *env = o->m_env;
3559 if(env == NULL) return 0;
3560 v3s16 pos = read_v3s16(L, 2);
3562 // Don't attempt to load non-loaded area as of now
3563 MapNode n = env->getMap().getNodeNoEx(pos);
3564 if(n.getContent() == CONTENT_IGNORE){
3565 lua_pushboolean(L, false);
3568 // Dig it out with a NULL digger (appears in Lua as a
3569 // non-functional ObjectRef)
3570 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3571 lua_pushboolean(L, success);
3575 // EnvRef:punch_node(pos)
3576 // pos = {x=num, y=num, z=num}
3577 static int l_punch_node(lua_State *L)
3579 EnvRef *o = checkobject(L, 1);
3580 ServerEnvironment *env = o->m_env;
3581 if(env == NULL) return 0;
3582 v3s16 pos = read_v3s16(L, 2);
3584 // Don't attempt to load non-loaded area as of now
3585 MapNode n = env->getMap().getNodeNoEx(pos);
3586 if(n.getContent() == CONTENT_IGNORE){
3587 lua_pushboolean(L, false);
3590 // Punch it with a NULL puncher (appears in Lua as a non-functional
3592 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3593 lua_pushboolean(L, success);
3597 // EnvRef:get_meta(pos)
3598 static int l_get_meta(lua_State *L)
3600 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3601 EnvRef *o = checkobject(L, 1);
3602 ServerEnvironment *env = o->m_env;
3603 if(env == NULL) return 0;
3605 v3s16 p = read_v3s16(L, 2);
3606 NodeMetaRef::create(L, p, env);
3610 // EnvRef:get_node_timer(pos)
3611 static int l_get_node_timer(lua_State *L)
3613 EnvRef *o = checkobject(L, 1);
3614 ServerEnvironment *env = o->m_env;
3615 if(env == NULL) return 0;
3617 v3s16 p = read_v3s16(L, 2);
3618 NodeTimerRef::create(L, p, env);
3622 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3623 // pos = {x=num, y=num, z=num}
3624 static int l_add_entity(lua_State *L)
3626 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3627 EnvRef *o = checkobject(L, 1);
3628 ServerEnvironment *env = o->m_env;
3629 if(env == NULL) return 0;
3631 v3f pos = checkFloatPos(L, 2);
3633 const char *name = luaL_checkstring(L, 3);
3635 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3636 int objectid = env->addActiveObject(obj);
3637 // If failed to add, return nothing (reads as nil)
3641 objectref_get_or_create(L, obj);
3645 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3646 // pos = {x=num, y=num, z=num}
3647 static int l_add_item(lua_State *L)
3649 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3650 EnvRef *o = checkobject(L, 1);
3651 ServerEnvironment *env = o->m_env;
3652 if(env == NULL) return 0;
3654 v3f pos = checkFloatPos(L, 2);
3656 ItemStack item = read_item(L, 3);
3657 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3659 // Use minetest.spawn_item to spawn a __builtin:item
3660 lua_getglobal(L, "minetest");
3661 lua_getfield(L, -1, "spawn_item");
3662 if(lua_isnil(L, -1))
3664 lua_pushvalue(L, 2);
3665 lua_pushstring(L, item.getItemString().c_str());
3666 if(lua_pcall(L, 2, 1, 0))
3667 script_error(L, "error: %s", lua_tostring(L, -1));
3669 /*lua_pushvalue(L, 1);
3670 lua_pushstring(L, "__builtin:item");
3671 lua_pushstring(L, item.getItemString().c_str());
3672 return l_add_entity(L);*/
3674 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3675 int objectid = env->addActiveObject(obj);
3676 // If failed to add, return nothing (reads as nil)
3680 objectref_get_or_create(L, obj);
3684 // EnvRef:add_rat(pos)
3685 // pos = {x=num, y=num, z=num}
3686 static int l_add_rat(lua_State *L)
3688 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3689 <<" Doing nothing."<<std::endl;
3693 // EnvRef:add_firefly(pos)
3694 // pos = {x=num, y=num, z=num}
3695 static int l_add_firefly(lua_State *L)
3697 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3698 <<" Doing nothing."<<std::endl;
3702 // EnvRef:get_player_by_name(name)
3703 static int l_get_player_by_name(lua_State *L)
3705 EnvRef *o = checkobject(L, 1);
3706 ServerEnvironment *env = o->m_env;
3707 if(env == NULL) return 0;
3709 const char *name = luaL_checkstring(L, 2);
3710 Player *player = env->getPlayer(name);
3715 PlayerSAO *sao = player->getPlayerSAO();
3720 // Put player on stack
3721 objectref_get_or_create(L, sao);
3725 // EnvRef:get_objects_inside_radius(pos, radius)
3726 static int l_get_objects_inside_radius(lua_State *L)
3728 // Get the table insert function
3729 lua_getglobal(L, "table");
3730 lua_getfield(L, -1, "insert");
3731 int table_insert = lua_gettop(L);
3733 EnvRef *o = checkobject(L, 1);
3734 ServerEnvironment *env = o->m_env;
3735 if(env == NULL) return 0;
3737 v3f pos = checkFloatPos(L, 2);
3738 float radius = luaL_checknumber(L, 3) * BS;
3739 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3741 int table = lua_gettop(L);
3742 for(std::set<u16>::const_iterator
3743 i = ids.begin(); i != ids.end(); i++){
3744 ServerActiveObject *obj = env->getActiveObject(*i);
3745 // Insert object reference into table
3746 lua_pushvalue(L, table_insert);
3747 lua_pushvalue(L, table);
3748 objectref_get_or_create(L, obj);
3749 if(lua_pcall(L, 2, 0, 0))
3750 script_error(L, "error: %s", lua_tostring(L, -1));
3755 // EnvRef:set_timeofday(val)
3757 static int l_set_timeofday(lua_State *L)
3759 EnvRef *o = checkobject(L, 1);
3760 ServerEnvironment *env = o->m_env;
3761 if(env == NULL) return 0;
3763 float timeofday_f = luaL_checknumber(L, 2);
3764 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3765 int timeofday_mh = (int)(timeofday_f * 24000.0);
3766 // This should be set directly in the environment but currently
3767 // such changes aren't immediately sent to the clients, so call
3768 // the server instead.
3769 //env->setTimeOfDay(timeofday_mh);
3770 get_server(L)->setTimeOfDay(timeofday_mh);
3774 // EnvRef:get_timeofday() -> 0...1
3775 static int l_get_timeofday(lua_State *L)
3777 EnvRef *o = checkobject(L, 1);
3778 ServerEnvironment *env = o->m_env;
3779 if(env == NULL) return 0;
3781 int timeofday_mh = env->getTimeOfDay();
3782 float timeofday_f = (float)timeofday_mh / 24000.0;
3783 lua_pushnumber(L, timeofday_f);
3788 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3789 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3790 static int l_find_node_near(lua_State *L)
3792 EnvRef *o = checkobject(L, 1);
3793 ServerEnvironment *env = o->m_env;
3794 if(env == NULL) return 0;
3795 INodeDefManager *ndef = get_server(L)->ndef();
3796 v3s16 pos = read_v3s16(L, 2);
3797 int radius = luaL_checkinteger(L, 3);
3798 std::set<content_t> filter;
3799 if(lua_istable(L, 4)){
3802 while(lua_next(L, table) != 0){
3803 // key at index -2 and value at index -1
3804 luaL_checktype(L, -1, LUA_TSTRING);
3805 ndef->getIds(lua_tostring(L, -1), filter);
3806 // removes value, keeps key for next iteration
3809 } else if(lua_isstring(L, 4)){
3810 ndef->getIds(lua_tostring(L, 4), filter);
3813 for(int d=1; d<=radius; d++){
3814 core::list<v3s16> list;
3815 getFacePositions(list, d);
3816 for(core::list<v3s16>::Iterator i = list.begin();
3817 i != list.end(); i++){
3818 v3s16 p = pos + (*i);
3819 content_t c = env->getMap().getNodeNoEx(p).getContent();
3820 if(filter.count(c) != 0){
3829 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3830 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3831 static int l_find_nodes_in_area(lua_State *L)
3833 EnvRef *o = checkobject(L, 1);
3834 ServerEnvironment *env = o->m_env;
3835 if(env == NULL) return 0;
3836 INodeDefManager *ndef = get_server(L)->ndef();
3837 v3s16 minp = read_v3s16(L, 2);
3838 v3s16 maxp = read_v3s16(L, 3);
3839 std::set<content_t> filter;
3840 if(lua_istable(L, 4)){
3843 while(lua_next(L, table) != 0){
3844 // key at index -2 and value at index -1
3845 luaL_checktype(L, -1, LUA_TSTRING);
3846 ndef->getIds(lua_tostring(L, -1), filter);
3847 // removes value, keeps key for next iteration
3850 } else if(lua_isstring(L, 4)){
3851 ndef->getIds(lua_tostring(L, 4), filter);
3854 // Get the table insert function
3855 lua_getglobal(L, "table");
3856 lua_getfield(L, -1, "insert");
3857 int table_insert = lua_gettop(L);
3860 int table = lua_gettop(L);
3861 for(s16 x=minp.X; x<=maxp.X; x++)
3862 for(s16 y=minp.Y; y<=maxp.Y; y++)
3863 for(s16 z=minp.Z; z<=maxp.Z; z++)
3866 content_t c = env->getMap().getNodeNoEx(p).getContent();
3867 if(filter.count(c) != 0){
3868 lua_pushvalue(L, table_insert);
3869 lua_pushvalue(L, table);
3871 if(lua_pcall(L, 2, 0, 0))
3872 script_error(L, "error: %s", lua_tostring(L, -1));
3878 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3879 // returns world-specific PerlinNoise
3880 static int l_get_perlin(lua_State *L)
3882 EnvRef *o = checkobject(L, 1);
3883 ServerEnvironment *env = o->m_env;
3884 if(env == NULL) return 0;
3886 int seeddiff = luaL_checkint(L, 2);
3887 int octaves = luaL_checkint(L, 3);
3888 double persistence = luaL_checknumber(L, 4);
3889 double scale = luaL_checknumber(L, 5);
3891 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3892 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3893 luaL_getmetatable(L, "PerlinNoise");
3894 lua_setmetatable(L, -2);
3898 // EnvRef:clear_objects()
3899 // clear all objects in the environment
3900 static int l_clear_objects(lua_State *L)
3902 EnvRef *o = checkobject(L, 1);
3903 o->m_env->clearAllObjects();
3908 EnvRef(ServerEnvironment *env):
3911 //infostream<<"EnvRef created"<<std::endl;
3916 //infostream<<"EnvRef destructing"<<std::endl;
3919 // Creates an EnvRef and leaves it on top of stack
3920 // Not callable from Lua; all references are created on the C side.
3921 static void create(lua_State *L, ServerEnvironment *env)
3923 EnvRef *o = new EnvRef(env);
3924 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3925 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3926 luaL_getmetatable(L, className);
3927 lua_setmetatable(L, -2);
3930 static void set_null(lua_State *L)
3932 EnvRef *o = checkobject(L, -1);
3936 static void Register(lua_State *L)
3939 int methodtable = lua_gettop(L);
3940 luaL_newmetatable(L, className);
3941 int metatable = lua_gettop(L);
3943 lua_pushliteral(L, "__metatable");
3944 lua_pushvalue(L, methodtable);
3945 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3947 lua_pushliteral(L, "__index");
3948 lua_pushvalue(L, methodtable);
3949 lua_settable(L, metatable);
3951 lua_pushliteral(L, "__gc");
3952 lua_pushcfunction(L, gc_object);
3953 lua_settable(L, metatable);
3955 lua_pop(L, 1); // drop metatable
3957 luaL_openlib(L, 0, methods, 0); // fill methodtable
3958 lua_pop(L, 1); // drop methodtable
3960 // Cannot be created from Lua
3961 //lua_register(L, className, create_object);
3964 const char EnvRef::className[] = "EnvRef";
3965 const luaL_reg EnvRef::methods[] = {
3966 method(EnvRef, set_node),
3967 method(EnvRef, add_node),
3968 method(EnvRef, remove_node),
3969 method(EnvRef, get_node),
3970 method(EnvRef, get_node_or_nil),
3971 method(EnvRef, get_node_light),
3972 method(EnvRef, place_node),
3973 method(EnvRef, dig_node),
3974 method(EnvRef, punch_node),
3975 method(EnvRef, add_entity),
3976 method(EnvRef, add_item),
3977 method(EnvRef, add_rat),
3978 method(EnvRef, add_firefly),
3979 method(EnvRef, get_meta),
3980 method(EnvRef, get_node_timer),
3981 method(EnvRef, get_player_by_name),
3982 method(EnvRef, get_objects_inside_radius),
3983 method(EnvRef, set_timeofday),
3984 method(EnvRef, get_timeofday),
3985 method(EnvRef, find_node_near),
3986 method(EnvRef, find_nodes_in_area),
3987 method(EnvRef, get_perlin),
3988 method(EnvRef, clear_objects),
3997 class LuaPseudoRandom
4000 PseudoRandom m_pseudo;
4002 static const char className[];
4003 static const luaL_reg methods[];
4005 // Exported functions
4007 // garbage collector
4008 static int gc_object(lua_State *L)
4010 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4015 // next(self, min=0, max=32767) -> get next value
4016 static int l_next(lua_State *L)
4018 LuaPseudoRandom *o = checkobject(L, 1);
4021 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4022 if(!lua_isnil(L, 2))
4023 min = luaL_checkinteger(L, 2);
4024 if(!lua_isnil(L, 3))
4025 max = luaL_checkinteger(L, 3);
4027 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4028 throw LuaError(L, "PseudoRandom.next(): max < min");
4030 if(max - min != 32767 && max - min > 32767/5)
4031 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.");
4032 PseudoRandom &pseudo = o->m_pseudo;
4033 int val = pseudo.next();
4034 val = (val % (max-min+1)) + min;
4035 lua_pushinteger(L, val);
4040 LuaPseudoRandom(int seed):
4049 const PseudoRandom& getItem() const
4053 PseudoRandom& getItem()
4058 // LuaPseudoRandom(seed)
4059 // Creates an LuaPseudoRandom and leaves it on top of stack
4060 static int create_object(lua_State *L)
4062 int seed = luaL_checknumber(L, 1);
4063 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4064 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4065 luaL_getmetatable(L, className);
4066 lua_setmetatable(L, -2);
4070 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4072 luaL_checktype(L, narg, LUA_TUSERDATA);
4073 void *ud = luaL_checkudata(L, narg, className);
4074 if(!ud) luaL_typerror(L, narg, className);
4075 return *(LuaPseudoRandom**)ud; // unbox pointer
4078 static void Register(lua_State *L)
4081 int methodtable = lua_gettop(L);
4082 luaL_newmetatable(L, className);
4083 int metatable = lua_gettop(L);
4085 lua_pushliteral(L, "__metatable");
4086 lua_pushvalue(L, methodtable);
4087 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4089 lua_pushliteral(L, "__index");
4090 lua_pushvalue(L, methodtable);
4091 lua_settable(L, metatable);
4093 lua_pushliteral(L, "__gc");
4094 lua_pushcfunction(L, gc_object);
4095 lua_settable(L, metatable);
4097 lua_pop(L, 1); // drop metatable
4099 luaL_openlib(L, 0, methods, 0); // fill methodtable
4100 lua_pop(L, 1); // drop methodtable
4102 // Can be created from Lua (LuaPseudoRandom(seed))
4103 lua_register(L, className, create_object);
4106 const char LuaPseudoRandom::className[] = "PseudoRandom";
4107 const luaL_reg LuaPseudoRandom::methods[] = {
4108 method(LuaPseudoRandom, next),
4118 class LuaABM : public ActiveBlockModifier
4124 std::set<std::string> m_trigger_contents;
4125 std::set<std::string> m_required_neighbors;
4126 float m_trigger_interval;
4127 u32 m_trigger_chance;
4129 LuaABM(lua_State *L, int id,
4130 const std::set<std::string> &trigger_contents,
4131 const std::set<std::string> &required_neighbors,
4132 float trigger_interval, u32 trigger_chance):
4135 m_trigger_contents(trigger_contents),
4136 m_required_neighbors(required_neighbors),
4137 m_trigger_interval(trigger_interval),
4138 m_trigger_chance(trigger_chance)
4141 virtual std::set<std::string> getTriggerContents()
4143 return m_trigger_contents;
4145 virtual std::set<std::string> getRequiredNeighbors()
4147 return m_required_neighbors;
4149 virtual float getTriggerInterval()
4151 return m_trigger_interval;
4153 virtual u32 getTriggerChance()
4155 return m_trigger_chance;
4157 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4158 u32 active_object_count, u32 active_object_count_wider)
4160 lua_State *L = m_lua;
4163 assert(lua_checkstack(L, 20));
4164 StackUnroller stack_unroller(L);
4166 // Get minetest.registered_abms
4167 lua_getglobal(L, "minetest");
4168 lua_getfield(L, -1, "registered_abms");
4169 luaL_checktype(L, -1, LUA_TTABLE);
4170 int registered_abms = lua_gettop(L);
4172 // Get minetest.registered_abms[m_id]
4173 lua_pushnumber(L, m_id);
4174 lua_gettable(L, registered_abms);
4175 if(lua_isnil(L, -1))
4179 luaL_checktype(L, -1, LUA_TTABLE);
4180 lua_getfield(L, -1, "action");
4181 luaL_checktype(L, -1, LUA_TFUNCTION);
4183 pushnode(L, n, env->getGameDef()->ndef());
4184 lua_pushnumber(L, active_object_count);
4185 lua_pushnumber(L, active_object_count_wider);
4186 if(lua_pcall(L, 4, 0, 0))
4187 script_error(L, "error: %s", lua_tostring(L, -1));
4195 static void read_server_sound_params(lua_State *L, int index,
4196 ServerSoundParams ¶ms)
4199 index = lua_gettop(L) + 1 + index;
4201 params = ServerSoundParams();
4202 if(lua_istable(L, index)){
4203 getfloatfield(L, index, "gain", params.gain);
4204 getstringfield(L, index, "to_player", params.to_player);
4205 lua_getfield(L, index, "pos");
4206 if(!lua_isnil(L, -1)){
4207 v3f p = read_v3f(L, -1)*BS;
4209 params.type = ServerSoundParams::SSP_POSITIONAL;
4212 lua_getfield(L, index, "object");
4213 if(!lua_isnil(L, -1)){
4214 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4215 ServerActiveObject *sao = ObjectRef::getobject(ref);
4217 params.object = sao->getId();
4218 params.type = ServerSoundParams::SSP_OBJECT;
4222 params.max_hear_distance = BS*getfloatfield_default(L, index,
4223 "max_hear_distance", params.max_hear_distance/BS);
4224 getboolfield(L, index, "loop", params.loop);
4233 // Writes a line to dstream
4234 static int l_debug(lua_State *L)
4236 std::string text = lua_tostring(L, 1);
4237 dstream << text << std::endl;
4241 // log([level,] text)
4242 // Writes a line to the logger.
4243 // The one-argument version logs to infostream.
4244 // The two-argument version accept a log level: error, action, info, or verbose.
4245 static int l_log(lua_State *L)
4248 LogMessageLevel level = LMT_INFO;
4249 if(lua_isnone(L, 2))
4251 text = lua_tostring(L, 1);
4255 std::string levelname = lua_tostring(L, 1);
4256 text = lua_tostring(L, 2);
4257 if(levelname == "error")
4259 else if(levelname == "action")
4261 else if(levelname == "verbose")
4262 level = LMT_VERBOSE;
4264 log_printline(level, text);
4268 // request_shutdown()
4269 static int l_request_shutdown(lua_State *L)
4271 get_server(L)->requestShutdown();
4275 // get_server_status()
4276 static int l_get_server_status(lua_State *L)
4278 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4282 // register_item_raw({lots of stuff})
4283 static int l_register_item_raw(lua_State *L)
4285 luaL_checktype(L, 1, LUA_TTABLE);
4288 // Get the writable item and node definition managers from the server
4289 IWritableItemDefManager *idef =
4290 get_server(L)->getWritableItemDefManager();
4291 IWritableNodeDefManager *ndef =
4292 get_server(L)->getWritableNodeDefManager();
4294 // Check if name is defined
4296 lua_getfield(L, table, "name");
4297 if(lua_isstring(L, -1)){
4298 name = lua_tostring(L, -1);
4299 verbosestream<<"register_item_raw: "<<name<<std::endl;
4301 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4304 // Check if on_use is defined
4307 // Set a distinctive default value to check if this is set
4308 def.node_placement_prediction = "__default";
4310 // Read the item definition
4311 def = read_item_definition(L, table, def);
4313 // Default to having client-side placement prediction for nodes
4314 // ("" in item definition sets it off)
4315 if(def.node_placement_prediction == "__default"){
4316 if(def.type == ITEM_NODE)
4317 def.node_placement_prediction = name;
4319 def.node_placement_prediction = "";
4322 // Register item definition
4323 idef->registerItem(def);
4325 // Read the node definition (content features) and register it
4326 if(def.type == ITEM_NODE)
4328 ContentFeatures f = read_content_features(L, table);
4329 ndef->set(f.name, f);
4332 return 0; /* number of results */
4335 // register_alias_raw(name, convert_to_name)
4336 static int l_register_alias_raw(lua_State *L)
4338 std::string name = luaL_checkstring(L, 1);
4339 std::string convert_to = luaL_checkstring(L, 2);
4341 // Get the writable item definition manager from the server
4342 IWritableItemDefManager *idef =
4343 get_server(L)->getWritableItemDefManager();
4345 idef->registerAlias(name, convert_to);
4347 return 0; /* number of results */
4350 // helper for register_craft
4351 static bool read_craft_recipe_shaped(lua_State *L, int index,
4352 int &width, std::vector<std::string> &recipe)
4355 index = lua_gettop(L) + 1 + index;
4357 if(!lua_istable(L, index))
4362 while(lua_next(L, index) != 0){
4364 // key at index -2 and value at index -1
4365 if(!lua_istable(L, -1))
4367 int table2 = lua_gettop(L);
4369 while(lua_next(L, table2) != 0){
4370 // key at index -2 and value at index -1
4371 if(!lua_isstring(L, -1))
4373 recipe.push_back(lua_tostring(L, -1));
4374 // removes value, keeps key for next iteration
4381 if(colcount != width)
4384 // removes value, keeps key for next iteration
4391 // helper for register_craft
4392 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4393 std::vector<std::string> &recipe)
4396 index = lua_gettop(L) + 1 + index;
4398 if(!lua_istable(L, index))
4402 while(lua_next(L, index) != 0){
4403 // key at index -2 and value at index -1
4404 if(!lua_isstring(L, -1))
4406 recipe.push_back(lua_tostring(L, -1));
4407 // removes value, keeps key for next iteration
4413 // helper for register_craft
4414 static bool read_craft_replacements(lua_State *L, int index,
4415 CraftReplacements &replacements)
4418 index = lua_gettop(L) + 1 + index;
4420 if(!lua_istable(L, index))
4424 while(lua_next(L, index) != 0){
4425 // key at index -2 and value at index -1
4426 if(!lua_istable(L, -1))
4428 lua_rawgeti(L, -1, 1);
4429 if(!lua_isstring(L, -1))
4431 std::string replace_from = lua_tostring(L, -1);
4433 lua_rawgeti(L, -1, 2);
4434 if(!lua_isstring(L, -1))
4436 std::string replace_to = lua_tostring(L, -1);
4438 replacements.pairs.push_back(
4439 std::make_pair(replace_from, replace_to));
4440 // removes value, keeps key for next iteration
4445 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4446 static int l_register_craft(lua_State *L)
4448 //infostream<<"register_craft"<<std::endl;
4449 luaL_checktype(L, 1, LUA_TTABLE);
4452 // Get the writable craft definition manager from the server
4453 IWritableCraftDefManager *craftdef =
4454 get_server(L)->getWritableCraftDefManager();
4456 std::string type = getstringfield_default(L, table, "type", "shaped");
4459 CraftDefinitionShaped
4461 if(type == "shaped"){
4462 std::string output = getstringfield_default(L, table, "output", "");
4464 throw LuaError(L, "Crafting definition is missing an output");
4467 std::vector<std::string> recipe;
4468 lua_getfield(L, table, "recipe");
4469 if(lua_isnil(L, -1))
4470 throw LuaError(L, "Crafting definition is missing a recipe"
4471 " (output=\"" + output + "\")");
4472 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4473 throw LuaError(L, "Invalid crafting recipe"
4474 " (output=\"" + output + "\")");
4476 CraftReplacements replacements;
4477 lua_getfield(L, table, "replacements");
4478 if(!lua_isnil(L, -1))
4480 if(!read_craft_replacements(L, -1, replacements))
4481 throw LuaError(L, "Invalid replacements"
4482 " (output=\"" + output + "\")");
4485 CraftDefinition *def = new CraftDefinitionShaped(
4486 output, width, recipe, replacements);
4487 craftdef->registerCraft(def);
4490 CraftDefinitionShapeless
4492 else if(type == "shapeless"){
4493 std::string output = getstringfield_default(L, table, "output", "");
4495 throw LuaError(L, "Crafting definition (shapeless)"
4496 " is missing an output");
4498 std::vector<std::string> recipe;
4499 lua_getfield(L, table, "recipe");
4500 if(lua_isnil(L, -1))
4501 throw LuaError(L, "Crafting definition (shapeless)"
4502 " is missing a recipe"
4503 " (output=\"" + output + "\")");
4504 if(!read_craft_recipe_shapeless(L, -1, recipe))
4505 throw LuaError(L, "Invalid crafting recipe"
4506 " (output=\"" + output + "\")");
4508 CraftReplacements replacements;
4509 lua_getfield(L, table, "replacements");
4510 if(!lua_isnil(L, -1))
4512 if(!read_craft_replacements(L, -1, replacements))
4513 throw LuaError(L, "Invalid replacements"
4514 " (output=\"" + output + "\")");
4517 CraftDefinition *def = new CraftDefinitionShapeless(
4518 output, recipe, replacements);
4519 craftdef->registerCraft(def);
4522 CraftDefinitionToolRepair
4524 else if(type == "toolrepair"){
4525 float additional_wear = getfloatfield_default(L, table,
4526 "additional_wear", 0.0);
4528 CraftDefinition *def = new CraftDefinitionToolRepair(
4530 craftdef->registerCraft(def);
4533 CraftDefinitionCooking
4535 else if(type == "cooking"){
4536 std::string output = getstringfield_default(L, table, "output", "");
4538 throw LuaError(L, "Crafting definition (cooking)"
4539 " is missing an output");
4541 std::string recipe = getstringfield_default(L, table, "recipe", "");
4543 throw LuaError(L, "Crafting definition (cooking)"
4544 " is missing a recipe"
4545 " (output=\"" + output + "\")");
4547 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4549 CraftReplacements replacements;
4550 lua_getfield(L, table, "replacements");
4551 if(!lua_isnil(L, -1))
4553 if(!read_craft_replacements(L, -1, replacements))
4554 throw LuaError(L, "Invalid replacements"
4555 " (cooking output=\"" + output + "\")");
4558 CraftDefinition *def = new CraftDefinitionCooking(
4559 output, recipe, cooktime, replacements);
4560 craftdef->registerCraft(def);
4565 else if(type == "fuel"){
4566 std::string recipe = getstringfield_default(L, table, "recipe", "");
4568 throw LuaError(L, "Crafting definition (fuel)"
4569 " is missing a recipe");
4571 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4573 CraftReplacements replacements;
4574 lua_getfield(L, table, "replacements");
4575 if(!lua_isnil(L, -1))
4577 if(!read_craft_replacements(L, -1, replacements))
4578 throw LuaError(L, "Invalid replacements"
4579 " (fuel recipe=\"" + recipe + "\")");
4582 CraftDefinition *def = new CraftDefinitionFuel(
4583 recipe, burntime, replacements);
4584 craftdef->registerCraft(def);
4588 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4592 return 0; /* number of results */
4595 // setting_set(name, value)
4596 static int l_setting_set(lua_State *L)
4598 const char *name = luaL_checkstring(L, 1);
4599 const char *value = luaL_checkstring(L, 2);
4600 g_settings->set(name, value);
4604 // setting_get(name)
4605 static int l_setting_get(lua_State *L)
4607 const char *name = luaL_checkstring(L, 1);
4609 std::string value = g_settings->get(name);
4610 lua_pushstring(L, value.c_str());
4611 } catch(SettingNotFoundException &e){
4617 // setting_getbool(name)
4618 static int l_setting_getbool(lua_State *L)
4620 const char *name = luaL_checkstring(L, 1);
4622 bool value = g_settings->getBool(name);
4623 lua_pushboolean(L, value);
4624 } catch(SettingNotFoundException &e){
4630 // chat_send_all(text)
4631 static int l_chat_send_all(lua_State *L)
4633 const char *text = luaL_checkstring(L, 1);
4634 // Get server from registry
4635 Server *server = get_server(L);
4637 server->notifyPlayers(narrow_to_wide(text));
4641 // chat_send_player(name, text)
4642 static int l_chat_send_player(lua_State *L)
4644 const char *name = luaL_checkstring(L, 1);
4645 const char *text = luaL_checkstring(L, 2);
4646 // Get server from registry
4647 Server *server = get_server(L);
4649 server->notifyPlayer(name, narrow_to_wide(text));
4653 // get_player_privs(name, text)
4654 static int l_get_player_privs(lua_State *L)
4656 const char *name = luaL_checkstring(L, 1);
4657 // Get server from registry
4658 Server *server = get_server(L);
4661 int table = lua_gettop(L);
4662 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4663 for(std::set<std::string>::const_iterator
4664 i = privs_s.begin(); i != privs_s.end(); i++){
4665 lua_pushboolean(L, true);
4666 lua_setfield(L, table, i->c_str());
4668 lua_pushvalue(L, table);
4673 static int l_get_ban_list(lua_State *L)
4675 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4679 // get_ban_description()
4680 static int l_get_ban_description(lua_State *L)
4682 const char * ip_or_name = luaL_checkstring(L, 1);
4683 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4688 static int l_ban_player(lua_State *L)
4690 const char * name = luaL_checkstring(L, 1);
4691 Player *player = get_env(L)->getPlayer(name);
4694 lua_pushboolean(L, false); // no such player
4699 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4700 std::string ip_str = addr.serializeString();
4701 get_server(L)->setIpBanned(ip_str, name);
4703 catch(con::PeerNotFoundException) // unlikely
4705 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4706 lua_pushboolean(L, false); // error
4709 lua_pushboolean(L, true);
4713 // unban_player_or_ip()
4714 static int l_unban_player_of_ip(lua_State *L)
4716 const char * ip_or_name = luaL_checkstring(L, 1);
4717 get_server(L)->unsetIpBanned(ip_or_name);
4718 lua_pushboolean(L, true);
4722 // get_inventory(location)
4723 static int l_get_inventory(lua_State *L)
4725 InventoryLocation loc;
4727 std::string type = checkstringfield(L, 1, "type");
4728 if(type == "player"){
4729 std::string name = checkstringfield(L, 1, "name");
4730 loc.setPlayer(name);
4731 } else if(type == "node"){
4732 lua_getfield(L, 1, "pos");
4733 v3s16 pos = check_v3s16(L, -1);
4734 loc.setNodeMeta(pos);
4735 } else if(type == "detached"){
4736 std::string name = checkstringfield(L, 1, "name");
4737 loc.setDetached(name);
4740 if(get_server(L)->getInventory(loc) != NULL)
4741 InvRef::create(L, loc);
4747 // create_detached_inventory_raw(name)
4748 static int l_create_detached_inventory_raw(lua_State *L)
4750 const char *name = luaL_checkstring(L, 1);
4751 if(get_server(L)->createDetachedInventory(name) != NULL){
4752 InventoryLocation loc;
4753 loc.setDetached(name);
4754 InvRef::create(L, loc);
4761 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4762 static int l_get_dig_params(lua_State *L)
4764 std::map<std::string, int> groups;
4765 read_groups(L, 1, groups);
4766 ToolCapabilities tp = read_tool_capabilities(L, 2);
4767 if(lua_isnoneornil(L, 3))
4768 push_dig_params(L, getDigParams(groups, &tp));
4770 push_dig_params(L, getDigParams(groups, &tp,
4771 luaL_checknumber(L, 3)));
4775 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4776 static int l_get_hit_params(lua_State *L)
4778 std::map<std::string, int> groups;
4779 read_groups(L, 1, groups);
4780 ToolCapabilities tp = read_tool_capabilities(L, 2);
4781 if(lua_isnoneornil(L, 3))
4782 push_hit_params(L, getHitParams(groups, &tp));
4784 push_hit_params(L, getHitParams(groups, &tp,
4785 luaL_checknumber(L, 3)));
4789 // get_current_modname()
4790 static int l_get_current_modname(lua_State *L)
4792 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4796 // get_modpath(modname)
4797 static int l_get_modpath(lua_State *L)
4799 std::string modname = luaL_checkstring(L, 1);
4801 if(modname == "__builtin"){
4802 std::string path = get_server(L)->getBuiltinLuaPath();
4803 lua_pushstring(L, path.c_str());
4806 const ModSpec *mod = get_server(L)->getModSpec(modname);
4811 lua_pushstring(L, mod->path.c_str());
4816 // the returned list is sorted alphabetically for you
4817 static int l_get_modnames(lua_State *L)
4819 // Get a list of mods
4820 core::list<std::string> mods_unsorted, mods_sorted;
4821 get_server(L)->getModNames(mods_unsorted);
4823 // Take unsorted items from mods_unsorted and sort them into
4824 // mods_sorted; not great performance but the number of mods on a
4825 // server will likely be small.
4826 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4827 i != mods_unsorted.end(); i++)
4830 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4831 x != mods_unsorted.end(); x++)
4833 // I doubt anybody using Minetest will be using
4834 // anything not ASCII based :)
4835 if((*i).compare(*x) <= 0)
4837 mods_sorted.insert_before(x, *i);
4843 mods_sorted.push_back(*i);
4846 // Get the table insertion function from Lua.
4847 lua_getglobal(L, "table");
4848 lua_getfield(L, -1, "insert");
4849 int insertion_func = lua_gettop(L);
4851 // Package them up for Lua
4853 int new_table = lua_gettop(L);
4854 core::list<std::string>::Iterator i = mods_sorted.begin();
4855 while(i != mods_sorted.end())
4857 lua_pushvalue(L, insertion_func);
4858 lua_pushvalue(L, new_table);
4859 lua_pushstring(L, (*i).c_str());
4860 if(lua_pcall(L, 2, 0, 0) != 0)
4862 script_error(L, "error: %s", lua_tostring(L, -1));
4870 static int l_get_worldpath(lua_State *L)
4872 std::string worldpath = get_server(L)->getWorldPath();
4873 lua_pushstring(L, worldpath.c_str());
4877 // sound_play(spec, parameters)
4878 static int l_sound_play(lua_State *L)
4880 SimpleSoundSpec spec;
4881 read_soundspec(L, 1, spec);
4882 ServerSoundParams params;
4883 read_server_sound_params(L, 2, params);
4884 s32 handle = get_server(L)->playSound(spec, params);
4885 lua_pushinteger(L, handle);
4889 // sound_stop(handle)
4890 static int l_sound_stop(lua_State *L)
4892 int handle = luaL_checkinteger(L, 1);
4893 get_server(L)->stopSound(handle);
4897 // is_singleplayer()
4898 static int l_is_singleplayer(lua_State *L)
4900 lua_pushboolean(L, get_server(L)->isSingleplayer());
4904 // get_password_hash(name, raw_password)
4905 static int l_get_password_hash(lua_State *L)
4907 std::string name = luaL_checkstring(L, 1);
4908 std::string raw_password = luaL_checkstring(L, 2);
4909 std::string hash = translatePassword(name,
4910 narrow_to_wide(raw_password));
4911 lua_pushstring(L, hash.c_str());
4915 // notify_authentication_modified(name)
4916 static int l_notify_authentication_modified(lua_State *L)
4918 std::string name = "";
4919 if(lua_isstring(L, 1))
4920 name = lua_tostring(L, 1);
4921 get_server(L)->reportPrivsModified(name);
4925 // get_craft_result(input)
4926 static int l_get_craft_result(lua_State *L)
4929 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4930 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4931 es_CraftMethod, CRAFT_METHOD_NORMAL);
4933 lua_getfield(L, input_i, "width");
4934 if(lua_isnumber(L, -1))
4935 width = luaL_checkinteger(L, -1);
4937 lua_getfield(L, input_i, "items");
4938 std::vector<ItemStack> items = read_items(L, -1);
4939 lua_pop(L, 1); // items
4941 IGameDef *gdef = get_server(L);
4942 ICraftDefManager *cdef = gdef->cdef();
4943 CraftInput input(method, width, items);
4945 bool got = cdef->getCraftResult(input, output, true, gdef);
4946 lua_newtable(L); // output table
4949 item.deSerialize(output.item, gdef->idef());
4950 LuaItemStack::create(L, item);
4951 lua_setfield(L, -2, "item");
4952 setintfield(L, -1, "time", output.time);
4954 LuaItemStack::create(L, ItemStack());
4955 lua_setfield(L, -2, "item");
4956 setintfield(L, -1, "time", 0);
4958 lua_newtable(L); // decremented input table
4959 lua_pushstring(L, method_s.c_str());
4960 lua_setfield(L, -2, "method");
4961 lua_pushinteger(L, width);
4962 lua_setfield(L, -2, "width");
4963 push_items(L, input.items);
4964 lua_setfield(L, -2, "items");
4968 // get_craft_recipe(result item)
4969 static int l_get_craft_recipe(lua_State *L)
4974 std::string o_item = luaL_checkstring(L,input_i);
4976 IGameDef *gdef = get_server(L);
4977 ICraftDefManager *cdef = gdef->cdef();
4979 CraftOutput output(o_item,0);
4980 bool got = cdef->getCraftRecipe(input, output, gdef);
4981 lua_newtable(L); // output table
4984 for(std::vector<ItemStack>::const_iterator
4985 i = input.items.begin();
4986 i != input.items.end(); i++, k++)
4992 sprintf(tmp,"%d",k);
4993 lua_pushstring(L,tmp);
4994 lua_pushstring(L,i->name.c_str());
4995 lua_settable(L, -3);
4997 lua_setfield(L, -2, "items");
4998 setintfield(L, -1, "width", input.width);
4999 switch (input.method) {
5000 case CRAFT_METHOD_NORMAL:
5001 lua_pushstring(L,"normal");
5003 case CRAFT_METHOD_COOKING:
5004 lua_pushstring(L,"cooking");
5006 case CRAFT_METHOD_FUEL:
5007 lua_pushstring(L,"fuel");
5010 lua_pushstring(L,"unknown");
5012 lua_setfield(L, -2, "type");
5015 lua_setfield(L, -2, "items");
5016 setintfield(L, -1, "width", 0);
5021 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5022 static int l_rollback_get_last_node_actor(lua_State *L)
5024 v3s16 p = read_v3s16(L, 1);
5025 int range = luaL_checknumber(L, 2);
5026 int seconds = luaL_checknumber(L, 3);
5027 Server *server = get_server(L);
5028 IRollbackManager *rollback = server->getRollbackManager();
5030 int act_seconds = 0;
5031 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5032 lua_pushstring(L, actor.c_str());
5033 push_v3s16(L, act_p);
5034 lua_pushnumber(L, act_seconds);
5038 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5039 static int l_rollback_revert_actions_by(lua_State *L)
5041 std::string actor = luaL_checkstring(L, 1);
5042 int seconds = luaL_checknumber(L, 2);
5043 Server *server = get_server(L);
5044 IRollbackManager *rollback = server->getRollbackManager();
5045 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5046 std::list<std::string> log;
5047 bool success = server->rollbackRevertActions(actions, &log);
5048 // Push boolean result
5049 lua_pushboolean(L, success);
5050 // Get the table insert function and push the log table
5051 lua_getglobal(L, "table");
5052 lua_getfield(L, -1, "insert");
5053 int table_insert = lua_gettop(L);
5055 int table = lua_gettop(L);
5056 for(std::list<std::string>::const_iterator i = log.begin();
5057 i != log.end(); i++)
5059 lua_pushvalue(L, table_insert);
5060 lua_pushvalue(L, table);
5061 lua_pushstring(L, i->c_str());
5062 if(lua_pcall(L, 2, 0, 0))
5063 script_error(L, "error: %s", lua_tostring(L, -1));
5065 lua_remove(L, -2); // Remove table
5066 lua_remove(L, -2); // Remove insert
5070 static const struct luaL_Reg minetest_f [] = {
5073 {"request_shutdown", l_request_shutdown},
5074 {"get_server_status", l_get_server_status},
5075 {"register_item_raw", l_register_item_raw},
5076 {"register_alias_raw", l_register_alias_raw},
5077 {"register_craft", l_register_craft},
5078 {"setting_set", l_setting_set},
5079 {"setting_get", l_setting_get},
5080 {"setting_getbool", l_setting_getbool},
5081 {"chat_send_all", l_chat_send_all},
5082 {"chat_send_player", l_chat_send_player},
5083 {"get_player_privs", l_get_player_privs},
5084 {"get_ban_list", l_get_ban_list},
5085 {"get_ban_description", l_get_ban_description},
5086 {"ban_player", l_ban_player},
5087 {"unban_player_or_ip", l_unban_player_of_ip},
5088 {"get_inventory", l_get_inventory},
5089 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5090 {"get_dig_params", l_get_dig_params},
5091 {"get_hit_params", l_get_hit_params},
5092 {"get_current_modname", l_get_current_modname},
5093 {"get_modpath", l_get_modpath},
5094 {"get_modnames", l_get_modnames},
5095 {"get_worldpath", l_get_worldpath},
5096 {"sound_play", l_sound_play},
5097 {"sound_stop", l_sound_stop},
5098 {"is_singleplayer", l_is_singleplayer},
5099 {"get_password_hash", l_get_password_hash},
5100 {"notify_authentication_modified", l_notify_authentication_modified},
5101 {"get_craft_result", l_get_craft_result},
5102 {"get_craft_recipe", l_get_craft_recipe},
5103 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5104 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5109 Main export function
5112 void scriptapi_export(lua_State *L, Server *server)
5115 assert(lua_checkstack(L, 20));
5116 verbosestream<<"scriptapi_export()"<<std::endl;
5117 StackUnroller stack_unroller(L);
5119 // Store server as light userdata in registry
5120 lua_pushlightuserdata(L, server);
5121 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5123 // Register global functions in table minetest
5125 luaL_register(L, NULL, minetest_f);
5126 lua_setglobal(L, "minetest");
5128 // Get the main minetest table
5129 lua_getglobal(L, "minetest");
5131 // Add tables to minetest
5133 lua_setfield(L, -2, "object_refs");
5135 lua_setfield(L, -2, "luaentities");
5137 // Register wrappers
5138 LuaItemStack::Register(L);
5139 InvRef::Register(L);
5140 NodeMetaRef::Register(L);
5141 NodeTimerRef::Register(L);
5142 ObjectRef::Register(L);
5143 EnvRef::Register(L);
5144 LuaPseudoRandom::Register(L);
5145 LuaPerlinNoise::Register(L);
5148 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5149 const std::string &modname)
5151 ModNameStorer modnamestorer(L, modname);
5153 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5155 errorstream<<"Error loading mod \""<<modname
5156 <<"\": modname does not follow naming conventions: "
5157 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5161 bool success = false;
5164 success = script_load(L, scriptpath.c_str());
5167 errorstream<<"Error loading mod \""<<modname
5168 <<"\": "<<e.what()<<std::endl;
5174 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5177 assert(lua_checkstack(L, 20));
5178 verbosestream<<"scriptapi_add_environment"<<std::endl;
5179 StackUnroller stack_unroller(L);
5181 // Create EnvRef on stack
5182 EnvRef::create(L, env);
5183 int envref = lua_gettop(L);
5185 // minetest.env = envref
5186 lua_getglobal(L, "minetest");
5187 luaL_checktype(L, -1, LUA_TTABLE);
5188 lua_pushvalue(L, envref);
5189 lua_setfield(L, -2, "env");
5191 // Store environment as light userdata in registry
5192 lua_pushlightuserdata(L, env);
5193 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5196 Add ActiveBlockModifiers to environment
5199 // Get minetest.registered_abms
5200 lua_getglobal(L, "minetest");
5201 lua_getfield(L, -1, "registered_abms");
5202 luaL_checktype(L, -1, LUA_TTABLE);
5203 int registered_abms = lua_gettop(L);
5205 if(lua_istable(L, registered_abms)){
5206 int table = lua_gettop(L);
5208 while(lua_next(L, table) != 0){
5209 // key at index -2 and value at index -1
5210 int id = lua_tonumber(L, -2);
5211 int current_abm = lua_gettop(L);
5213 std::set<std::string> trigger_contents;
5214 lua_getfield(L, current_abm, "nodenames");
5215 if(lua_istable(L, -1)){
5216 int table = lua_gettop(L);
5218 while(lua_next(L, table) != 0){
5219 // key at index -2 and value at index -1
5220 luaL_checktype(L, -1, LUA_TSTRING);
5221 trigger_contents.insert(lua_tostring(L, -1));
5222 // removes value, keeps key for next iteration
5225 } else if(lua_isstring(L, -1)){
5226 trigger_contents.insert(lua_tostring(L, -1));
5230 std::set<std::string> required_neighbors;
5231 lua_getfield(L, current_abm, "neighbors");
5232 if(lua_istable(L, -1)){
5233 int table = lua_gettop(L);
5235 while(lua_next(L, table) != 0){
5236 // key at index -2 and value at index -1
5237 luaL_checktype(L, -1, LUA_TSTRING);
5238 required_neighbors.insert(lua_tostring(L, -1));
5239 // removes value, keeps key for next iteration
5242 } else if(lua_isstring(L, -1)){
5243 required_neighbors.insert(lua_tostring(L, -1));
5247 float trigger_interval = 10.0;
5248 getfloatfield(L, current_abm, "interval", trigger_interval);
5250 int trigger_chance = 50;
5251 getintfield(L, current_abm, "chance", trigger_chance);
5253 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5254 required_neighbors, trigger_interval, trigger_chance);
5256 env->addActiveBlockModifier(abm);
5258 // removes value, keeps key for next iteration
5266 // Dump stack top with the dump2 function
5267 static void dump2(lua_State *L, const char *name)
5269 // Dump object (debug)
5270 lua_getglobal(L, "dump2");
5271 luaL_checktype(L, -1, LUA_TFUNCTION);
5272 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5273 lua_pushstring(L, name);
5274 if(lua_pcall(L, 2, 0, 0))
5275 script_error(L, "error: %s", lua_tostring(L, -1));
5283 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5286 assert(lua_checkstack(L, 20));
5287 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5288 StackUnroller stack_unroller(L);
5290 // Create object on stack
5291 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5292 int object = lua_gettop(L);
5294 // Get minetest.object_refs table
5295 lua_getglobal(L, "minetest");
5296 lua_getfield(L, -1, "object_refs");
5297 luaL_checktype(L, -1, LUA_TTABLE);
5298 int objectstable = lua_gettop(L);
5300 // object_refs[id] = object
5301 lua_pushnumber(L, cobj->getId()); // Push id
5302 lua_pushvalue(L, object); // Copy object to top of stack
5303 lua_settable(L, objectstable);
5306 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5309 assert(lua_checkstack(L, 20));
5310 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5311 StackUnroller stack_unroller(L);
5313 // Get minetest.object_refs table
5314 lua_getglobal(L, "minetest");
5315 lua_getfield(L, -1, "object_refs");
5316 luaL_checktype(L, -1, LUA_TTABLE);
5317 int objectstable = lua_gettop(L);
5319 // Get object_refs[id]
5320 lua_pushnumber(L, cobj->getId()); // Push id
5321 lua_gettable(L, objectstable);
5322 // Set object reference to NULL
5323 ObjectRef::set_null(L);
5324 lua_pop(L, 1); // pop object
5326 // Set object_refs[id] = nil
5327 lua_pushnumber(L, cobj->getId()); // Push id
5329 lua_settable(L, objectstable);
5336 // What scriptapi_run_callbacks does with the return values of callbacks.
5337 // Regardless of the mode, if only one callback is defined,
5338 // its return value is the total return value.
5339 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5340 enum RunCallbacksMode
5342 // Returns the return value of the first callback
5343 // Returns nil if list of callbacks is empty
5344 RUN_CALLBACKS_MODE_FIRST,
5345 // Returns the return value of the last callback
5346 // Returns nil if list of callbacks is empty
5347 RUN_CALLBACKS_MODE_LAST,
5348 // If any callback returns a false value, the first such is returned
5349 // Otherwise, the first callback's return value (trueish) is returned
5350 // Returns true if list of callbacks is empty
5351 RUN_CALLBACKS_MODE_AND,
5352 // Like above, but stops calling callbacks (short circuit)
5353 // after seeing the first false value
5354 RUN_CALLBACKS_MODE_AND_SC,
5355 // If any callback returns a true value, the first such is returned
5356 // Otherwise, the first callback's return value (falseish) is returned
5357 // Returns false if list of callbacks is empty
5358 RUN_CALLBACKS_MODE_OR,
5359 // Like above, but stops calling callbacks (short circuit)
5360 // after seeing the first true value
5361 RUN_CALLBACKS_MODE_OR_SC,
5362 // Note: "a true value" and "a false value" refer to values that
5363 // are converted by lua_toboolean to true or false, respectively.
5366 // Push the list of callbacks (a lua table).
5367 // Then push nargs arguments.
5368 // Then call this function, which
5369 // - runs the callbacks
5370 // - removes the table and arguments from the lua stack
5371 // - pushes the return value, computed depending on mode
5372 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5373 RunCallbacksMode mode)
5375 // Insert the return value into the lua stack, below the table
5376 assert(lua_gettop(L) >= nargs + 1);
5378 lua_insert(L, -(nargs + 1) - 1);
5379 // Stack now looks like this:
5380 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5382 int rv = lua_gettop(L) - nargs - 1;
5384 int arg = table + 1;
5386 luaL_checktype(L, table, LUA_TTABLE);
5390 bool first_loop = true;
5391 while(lua_next(L, table) != 0){
5392 // key at index -2 and value at index -1
5393 luaL_checktype(L, -1, LUA_TFUNCTION);
5395 for(int i = 0; i < nargs; i++)
5396 lua_pushvalue(L, arg+i);
5397 if(lua_pcall(L, nargs, 1, 0))
5398 script_error(L, "error: %s", lua_tostring(L, -1));
5400 // Move return value to designated space in stack
5403 // Result of first callback is always moved
5407 // Otherwise, what happens depends on the mode
5408 if(mode == RUN_CALLBACKS_MODE_FIRST)
5410 else if(mode == RUN_CALLBACKS_MODE_LAST)
5412 else if(mode == RUN_CALLBACKS_MODE_AND ||
5413 mode == RUN_CALLBACKS_MODE_AND_SC){
5414 if(lua_toboolean(L, rv) == true &&
5415 lua_toboolean(L, -1) == false)
5420 else if(mode == RUN_CALLBACKS_MODE_OR ||
5421 mode == RUN_CALLBACKS_MODE_OR_SC){
5422 if(lua_toboolean(L, rv) == false &&
5423 lua_toboolean(L, -1) == true)
5432 // Handle short circuit modes
5433 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5434 lua_toboolean(L, rv) == false)
5436 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5437 lua_toboolean(L, rv) == true)
5440 // value removed, keep key for next iteration
5443 // Remove stuff from stack, leaving only the return value
5446 // Fix return value in case no callbacks were called
5448 if(mode == RUN_CALLBACKS_MODE_AND ||
5449 mode == RUN_CALLBACKS_MODE_AND_SC){
5451 lua_pushboolean(L, true);
5453 else if(mode == RUN_CALLBACKS_MODE_OR ||
5454 mode == RUN_CALLBACKS_MODE_OR_SC){
5456 lua_pushboolean(L, false);
5461 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5462 const std::string &message)
5465 assert(lua_checkstack(L, 20));
5466 StackUnroller stack_unroller(L);
5468 // Get minetest.registered_on_chat_messages
5469 lua_getglobal(L, "minetest");
5470 lua_getfield(L, -1, "registered_on_chat_messages");
5472 lua_pushstring(L, name.c_str());
5473 lua_pushstring(L, message.c_str());
5474 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5475 bool ate = lua_toboolean(L, -1);
5479 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5482 assert(lua_checkstack(L, 20));
5483 StackUnroller stack_unroller(L);
5485 // Get minetest.registered_on_newplayers
5486 lua_getglobal(L, "minetest");
5487 lua_getfield(L, -1, "registered_on_newplayers");
5489 objectref_get_or_create(L, player);
5490 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5493 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5496 assert(lua_checkstack(L, 20));
5497 StackUnroller stack_unroller(L);
5499 // Get minetest.registered_on_dieplayers
5500 lua_getglobal(L, "minetest");
5501 lua_getfield(L, -1, "registered_on_dieplayers");
5503 objectref_get_or_create(L, player);
5504 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5507 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5510 assert(lua_checkstack(L, 20));
5511 StackUnroller stack_unroller(L);
5513 // Get minetest.registered_on_respawnplayers
5514 lua_getglobal(L, "minetest");
5515 lua_getfield(L, -1, "registered_on_respawnplayers");
5517 objectref_get_or_create(L, player);
5518 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5519 bool positioning_handled_by_some = lua_toboolean(L, -1);
5520 return positioning_handled_by_some;
5523 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5526 assert(lua_checkstack(L, 20));
5527 StackUnroller stack_unroller(L);
5529 // Get minetest.registered_on_joinplayers
5530 lua_getglobal(L, "minetest");
5531 lua_getfield(L, -1, "registered_on_joinplayers");
5533 objectref_get_or_create(L, player);
5534 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5537 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5540 assert(lua_checkstack(L, 20));
5541 StackUnroller stack_unroller(L);
5543 // Get minetest.registered_on_leaveplayers
5544 lua_getglobal(L, "minetest");
5545 lua_getfield(L, -1, "registered_on_leaveplayers");
5547 objectref_get_or_create(L, player);
5548 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5551 static void get_auth_handler(lua_State *L)
5553 lua_getglobal(L, "minetest");
5554 lua_getfield(L, -1, "registered_auth_handler");
5555 if(lua_isnil(L, -1)){
5557 lua_getfield(L, -1, "builtin_auth_handler");
5559 if(lua_type(L, -1) != LUA_TTABLE)
5560 throw LuaError(L, "Authentication handler table not valid");
5563 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5564 std::string *dst_password, std::set<std::string> *dst_privs)
5567 assert(lua_checkstack(L, 20));
5568 StackUnroller stack_unroller(L);
5570 get_auth_handler(L);
5571 lua_getfield(L, -1, "get_auth");
5572 if(lua_type(L, -1) != LUA_TFUNCTION)
5573 throw LuaError(L, "Authentication handler missing get_auth");
5574 lua_pushstring(L, playername.c_str());
5575 if(lua_pcall(L, 1, 1, 0))
5576 script_error(L, "error: %s", lua_tostring(L, -1));
5578 // nil = login not allowed
5579 if(lua_isnil(L, -1))
5581 luaL_checktype(L, -1, LUA_TTABLE);
5583 std::string password;
5584 bool found = getstringfield(L, -1, "password", password);
5586 throw LuaError(L, "Authentication handler didn't return password");
5588 *dst_password = password;
5590 lua_getfield(L, -1, "privileges");
5591 if(!lua_istable(L, -1))
5593 "Authentication handler didn't return privilege table");
5595 read_privileges(L, -1, *dst_privs);
5601 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5602 const std::string &password)
5605 assert(lua_checkstack(L, 20));
5606 StackUnroller stack_unroller(L);
5608 get_auth_handler(L);
5609 lua_getfield(L, -1, "create_auth");
5610 if(lua_type(L, -1) != LUA_TFUNCTION)
5611 throw LuaError(L, "Authentication handler missing create_auth");
5612 lua_pushstring(L, playername.c_str());
5613 lua_pushstring(L, password.c_str());
5614 if(lua_pcall(L, 2, 0, 0))
5615 script_error(L, "error: %s", lua_tostring(L, -1));
5618 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5619 const std::string &password)
5622 assert(lua_checkstack(L, 20));
5623 StackUnroller stack_unroller(L);
5625 get_auth_handler(L);
5626 lua_getfield(L, -1, "set_password");
5627 if(lua_type(L, -1) != LUA_TFUNCTION)
5628 throw LuaError(L, "Authentication handler missing set_password");
5629 lua_pushstring(L, playername.c_str());
5630 lua_pushstring(L, password.c_str());
5631 if(lua_pcall(L, 2, 1, 0))
5632 script_error(L, "error: %s", lua_tostring(L, -1));
5633 return lua_toboolean(L, -1);
5640 void scriptapi_on_player_receive_fields(lua_State *L,
5641 ServerActiveObject *player,
5642 const std::string &formname,
5643 const std::map<std::string, std::string> &fields)
5646 assert(lua_checkstack(L, 20));
5647 StackUnroller stack_unroller(L);
5649 // Get minetest.registered_on_chat_messages
5650 lua_getglobal(L, "minetest");
5651 lua_getfield(L, -1, "registered_on_player_receive_fields");
5654 objectref_get_or_create(L, player);
5656 lua_pushstring(L, formname.c_str());
5659 for(std::map<std::string, std::string>::const_iterator
5660 i = fields.begin(); i != fields.end(); i++){
5661 const std::string &name = i->first;
5662 const std::string &value = i->second;
5663 lua_pushstring(L, name.c_str());
5664 lua_pushlstring(L, value.c_str(), value.size());
5665 lua_settable(L, -3);
5667 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5671 item callbacks and node callbacks
5674 // Retrieves minetest.registered_items[name][callbackname]
5675 // If that is nil or on error, return false and stack is unchanged
5676 // If that is a function, returns true and pushes the
5677 // function onto the stack
5678 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5679 // is tried instead so unknown items can still be manipulated to some degree
5680 static bool get_item_callback(lua_State *L,
5681 const char *name, const char *callbackname)
5683 lua_getglobal(L, "minetest");
5684 lua_getfield(L, -1, "registered_items");
5686 luaL_checktype(L, -1, LUA_TTABLE);
5687 lua_getfield(L, -1, name);
5689 // Should be a table
5690 if(lua_type(L, -1) != LUA_TTABLE)
5692 // Report error and clean up
5693 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5696 // Try minetest.nodedef_default instead
5697 lua_getglobal(L, "minetest");
5698 lua_getfield(L, -1, "nodedef_default");
5700 luaL_checktype(L, -1, LUA_TTABLE);
5702 lua_getfield(L, -1, callbackname);
5704 // Should be a function or nil
5705 if(lua_type(L, -1) == LUA_TFUNCTION)
5709 else if(lua_isnil(L, -1))
5716 errorstream<<"Item \""<<name<<"\" callback \""
5717 <<callbackname<<" is not a function"<<std::endl;
5723 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5724 ServerActiveObject *dropper, v3f pos)
5727 assert(lua_checkstack(L, 20));
5728 StackUnroller stack_unroller(L);
5730 // Push callback function on stack
5731 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5735 LuaItemStack::create(L, item);
5736 objectref_get_or_create(L, dropper);
5737 pushFloatPos(L, pos);
5738 if(lua_pcall(L, 3, 1, 0))
5739 script_error(L, "error: %s", lua_tostring(L, -1));
5740 if(!lua_isnil(L, -1))
5741 item = read_item(L, -1);
5745 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5746 ServerActiveObject *placer, const PointedThing &pointed)
5749 assert(lua_checkstack(L, 20));
5750 StackUnroller stack_unroller(L);
5752 // Push callback function on stack
5753 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5757 LuaItemStack::create(L, item);
5758 objectref_get_or_create(L, placer);
5759 push_pointed_thing(L, pointed);
5760 if(lua_pcall(L, 3, 1, 0))
5761 script_error(L, "error: %s", lua_tostring(L, -1));
5762 if(!lua_isnil(L, -1))
5763 item = read_item(L, -1);
5767 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5768 ServerActiveObject *user, const PointedThing &pointed)
5771 assert(lua_checkstack(L, 20));
5772 StackUnroller stack_unroller(L);
5774 // Push callback function on stack
5775 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5779 LuaItemStack::create(L, item);
5780 objectref_get_or_create(L, user);
5781 push_pointed_thing(L, pointed);
5782 if(lua_pcall(L, 3, 1, 0))
5783 script_error(L, "error: %s", lua_tostring(L, -1));
5784 if(!lua_isnil(L, -1))
5785 item = read_item(L, -1);
5789 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5790 ServerActiveObject *puncher)
5793 assert(lua_checkstack(L, 20));
5794 StackUnroller stack_unroller(L);
5796 INodeDefManager *ndef = get_server(L)->ndef();
5798 // Push callback function on stack
5799 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5804 pushnode(L, node, ndef);
5805 objectref_get_or_create(L, puncher);
5806 if(lua_pcall(L, 3, 0, 0))
5807 script_error(L, "error: %s", lua_tostring(L, -1));
5811 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5812 ServerActiveObject *digger)
5815 assert(lua_checkstack(L, 20));
5816 StackUnroller stack_unroller(L);
5818 INodeDefManager *ndef = get_server(L)->ndef();
5820 // Push callback function on stack
5821 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5826 pushnode(L, node, ndef);
5827 objectref_get_or_create(L, digger);
5828 if(lua_pcall(L, 3, 0, 0))
5829 script_error(L, "error: %s", lua_tostring(L, -1));
5833 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5836 assert(lua_checkstack(L, 20));
5837 StackUnroller stack_unroller(L);
5839 INodeDefManager *ndef = get_server(L)->ndef();
5841 // Push callback function on stack
5842 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5847 if(lua_pcall(L, 1, 0, 0))
5848 script_error(L, "error: %s", lua_tostring(L, -1));
5851 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5854 assert(lua_checkstack(L, 20));
5855 StackUnroller stack_unroller(L);
5857 INodeDefManager *ndef = get_server(L)->ndef();
5859 // Push callback function on stack
5860 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5865 if(lua_pcall(L, 1, 0, 0))
5866 script_error(L, "error: %s", lua_tostring(L, -1));
5869 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5872 assert(lua_checkstack(L, 20));
5873 StackUnroller stack_unroller(L);
5875 INodeDefManager *ndef = get_server(L)->ndef();
5877 // Push callback function on stack
5878 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5883 pushnode(L, node, ndef);
5884 if(lua_pcall(L, 2, 0, 0))
5885 script_error(L, "error: %s", lua_tostring(L, -1));
5888 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5891 assert(lua_checkstack(L, 20));
5892 StackUnroller stack_unroller(L);
5894 INodeDefManager *ndef = get_server(L)->ndef();
5896 // Push callback function on stack
5897 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5902 lua_pushnumber(L,dtime);
5903 if(lua_pcall(L, 2, 1, 0))
5904 script_error(L, "error: %s", lua_tostring(L, -1));
5905 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5911 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5912 const std::string &formname,
5913 const std::map<std::string, std::string> &fields,
5914 ServerActiveObject *sender)
5917 assert(lua_checkstack(L, 20));
5918 StackUnroller stack_unroller(L);
5920 INodeDefManager *ndef = get_server(L)->ndef();
5922 // If node doesn't exist, we don't know what callback to call
5923 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5924 if(node.getContent() == CONTENT_IGNORE)
5927 // Push callback function on stack
5928 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5935 lua_pushstring(L, formname.c_str());
5938 for(std::map<std::string, std::string>::const_iterator
5939 i = fields.begin(); i != fields.end(); i++){
5940 const std::string &name = i->first;
5941 const std::string &value = i->second;
5942 lua_pushstring(L, name.c_str());
5943 lua_pushlstring(L, value.c_str(), value.size());
5944 lua_settable(L, -3);
5947 objectref_get_or_create(L, sender);
5948 if(lua_pcall(L, 4, 0, 0))
5949 script_error(L, "error: %s", lua_tostring(L, -1));
5953 Node metadata inventory callbacks
5956 // Return number of accepted items to be moved
5957 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5958 const std::string &from_list, int from_index,
5959 const std::string &to_list, int to_index,
5960 int count, ServerActiveObject *player)
5963 assert(lua_checkstack(L, 20));
5964 StackUnroller stack_unroller(L);
5966 INodeDefManager *ndef = get_server(L)->ndef();
5968 // If node doesn't exist, we don't know what callback to call
5969 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5970 if(node.getContent() == CONTENT_IGNORE)
5973 // Push callback function on stack
5974 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5975 "allow_metadata_inventory_move"))
5978 // function(pos, from_list, from_index, to_list, to_index, count, player)
5982 lua_pushstring(L, from_list.c_str());
5984 lua_pushinteger(L, from_index + 1);
5986 lua_pushstring(L, to_list.c_str());
5988 lua_pushinteger(L, to_index + 1);
5990 lua_pushinteger(L, count);
5992 objectref_get_or_create(L, player);
5993 if(lua_pcall(L, 7, 1, 0))
5994 script_error(L, "error: %s", lua_tostring(L, -1));
5995 if(!lua_isnumber(L, -1))
5996 throw LuaError(L, "allow_metadata_inventory_move should return a number");
5997 return luaL_checkinteger(L, -1);
6000 // Return number of accepted items to be put
6001 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6002 const std::string &listname, int index, ItemStack &stack,
6003 ServerActiveObject *player)
6006 assert(lua_checkstack(L, 20));
6007 StackUnroller stack_unroller(L);
6009 INodeDefManager *ndef = get_server(L)->ndef();
6011 // If node doesn't exist, we don't know what callback to call
6012 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6013 if(node.getContent() == CONTENT_IGNORE)
6016 // Push callback function on stack
6017 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6018 "allow_metadata_inventory_put"))
6021 // Call function(pos, listname, index, stack, player)
6025 lua_pushstring(L, listname.c_str());
6027 lua_pushinteger(L, index + 1);
6029 LuaItemStack::create(L, stack);
6031 objectref_get_or_create(L, player);
6032 if(lua_pcall(L, 5, 1, 0))
6033 script_error(L, "error: %s", lua_tostring(L, -1));
6034 if(!lua_isnumber(L, -1))
6035 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6036 return luaL_checkinteger(L, -1);
6039 // Return number of accepted items to be taken
6040 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6041 const std::string &listname, int index, ItemStack &stack,
6042 ServerActiveObject *player)
6045 assert(lua_checkstack(L, 20));
6046 StackUnroller stack_unroller(L);
6048 INodeDefManager *ndef = get_server(L)->ndef();
6050 // If node doesn't exist, we don't know what callback to call
6051 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6052 if(node.getContent() == CONTENT_IGNORE)
6055 // Push callback function on stack
6056 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6057 "allow_metadata_inventory_take"))
6060 // Call function(pos, listname, index, count, player)
6064 lua_pushstring(L, listname.c_str());
6066 lua_pushinteger(L, index + 1);
6068 LuaItemStack::create(L, stack);
6070 objectref_get_or_create(L, player);
6071 if(lua_pcall(L, 5, 1, 0))
6072 script_error(L, "error: %s", lua_tostring(L, -1));
6073 if(!lua_isnumber(L, -1))
6074 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6075 return luaL_checkinteger(L, -1);
6078 // Report moved items
6079 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6080 const std::string &from_list, int from_index,
6081 const std::string &to_list, int to_index,
6082 int count, ServerActiveObject *player)
6085 assert(lua_checkstack(L, 20));
6086 StackUnroller stack_unroller(L);
6088 INodeDefManager *ndef = get_server(L)->ndef();
6090 // If node doesn't exist, we don't know what callback to call
6091 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6092 if(node.getContent() == CONTENT_IGNORE)
6095 // Push callback function on stack
6096 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6097 "on_metadata_inventory_move"))
6100 // function(pos, from_list, from_index, to_list, to_index, count, player)
6104 lua_pushstring(L, from_list.c_str());
6106 lua_pushinteger(L, from_index + 1);
6108 lua_pushstring(L, to_list.c_str());
6110 lua_pushinteger(L, to_index + 1);
6112 lua_pushinteger(L, count);
6114 objectref_get_or_create(L, player);
6115 if(lua_pcall(L, 7, 0, 0))
6116 script_error(L, "error: %s", lua_tostring(L, -1));
6120 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6121 const std::string &listname, int index, ItemStack &stack,
6122 ServerActiveObject *player)
6125 assert(lua_checkstack(L, 20));
6126 StackUnroller stack_unroller(L);
6128 INodeDefManager *ndef = get_server(L)->ndef();
6130 // If node doesn't exist, we don't know what callback to call
6131 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6132 if(node.getContent() == CONTENT_IGNORE)
6135 // Push callback function on stack
6136 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6137 "on_metadata_inventory_put"))
6140 // Call function(pos, listname, index, stack, player)
6144 lua_pushstring(L, listname.c_str());
6146 lua_pushinteger(L, index + 1);
6148 LuaItemStack::create(L, stack);
6150 objectref_get_or_create(L, player);
6151 if(lua_pcall(L, 5, 0, 0))
6152 script_error(L, "error: %s", lua_tostring(L, -1));
6155 // Report taken items
6156 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6157 const std::string &listname, int index, ItemStack &stack,
6158 ServerActiveObject *player)
6161 assert(lua_checkstack(L, 20));
6162 StackUnroller stack_unroller(L);
6164 INodeDefManager *ndef = get_server(L)->ndef();
6166 // If node doesn't exist, we don't know what callback to call
6167 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6168 if(node.getContent() == CONTENT_IGNORE)
6171 // Push callback function on stack
6172 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6173 "on_metadata_inventory_take"))
6176 // Call function(pos, listname, index, stack, player)
6180 lua_pushstring(L, listname.c_str());
6182 lua_pushinteger(L, index + 1);
6184 LuaItemStack::create(L, stack);
6186 objectref_get_or_create(L, player);
6187 if(lua_pcall(L, 5, 0, 0))
6188 script_error(L, "error: %s", lua_tostring(L, -1));
6192 Detached inventory callbacks
6195 // Retrieves minetest.detached_inventories[name][callbackname]
6196 // If that is nil or on error, return false and stack is unchanged
6197 // If that is a function, returns true and pushes the
6198 // function onto the stack
6199 static bool get_detached_inventory_callback(lua_State *L,
6200 const std::string &name, const char *callbackname)
6202 lua_getglobal(L, "minetest");
6203 lua_getfield(L, -1, "detached_inventories");
6205 luaL_checktype(L, -1, LUA_TTABLE);
6206 lua_getfield(L, -1, name.c_str());
6208 // Should be a table
6209 if(lua_type(L, -1) != LUA_TTABLE)
6211 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6215 lua_getfield(L, -1, callbackname);
6217 // Should be a function or nil
6218 if(lua_type(L, -1) == LUA_TFUNCTION)
6222 else if(lua_isnil(L, -1))
6229 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6230 <<callbackname<<"\" is not a function"<<std::endl;
6236 // Return number of accepted items to be moved
6237 int scriptapi_detached_inventory_allow_move(lua_State *L,
6238 const std::string &name,
6239 const std::string &from_list, int from_index,
6240 const std::string &to_list, int to_index,
6241 int count, ServerActiveObject *player)
6244 assert(lua_checkstack(L, 20));
6245 StackUnroller stack_unroller(L);
6247 // Push callback function on stack
6248 if(!get_detached_inventory_callback(L, name, "allow_move"))
6251 // function(inv, from_list, from_index, to_list, to_index, count, player)
6253 InventoryLocation loc;
6254 loc.setDetached(name);
6255 InvRef::create(L, loc);
6257 lua_pushstring(L, from_list.c_str());
6259 lua_pushinteger(L, from_index + 1);
6261 lua_pushstring(L, to_list.c_str());
6263 lua_pushinteger(L, to_index + 1);
6265 lua_pushinteger(L, count);
6267 objectref_get_or_create(L, player);
6268 if(lua_pcall(L, 7, 1, 0))
6269 script_error(L, "error: %s", lua_tostring(L, -1));
6270 if(!lua_isnumber(L, -1))
6271 throw LuaError(L, "allow_move should return a number");
6272 return luaL_checkinteger(L, -1);
6275 // Return number of accepted items to be put
6276 int scriptapi_detached_inventory_allow_put(lua_State *L,
6277 const std::string &name,
6278 const std::string &listname, int index, ItemStack &stack,
6279 ServerActiveObject *player)
6282 assert(lua_checkstack(L, 20));
6283 StackUnroller stack_unroller(L);
6285 // Push callback function on stack
6286 if(!get_detached_inventory_callback(L, name, "allow_put"))
6287 return stack.count; // All will be accepted
6289 // Call function(inv, listname, index, stack, player)
6291 InventoryLocation loc;
6292 loc.setDetached(name);
6293 InvRef::create(L, loc);
6295 lua_pushstring(L, listname.c_str());
6297 lua_pushinteger(L, index + 1);
6299 LuaItemStack::create(L, stack);
6301 objectref_get_or_create(L, player);
6302 if(lua_pcall(L, 5, 1, 0))
6303 script_error(L, "error: %s", lua_tostring(L, -1));
6304 if(!lua_isnumber(L, -1))
6305 throw LuaError(L, "allow_put should return a number");
6306 return luaL_checkinteger(L, -1);
6309 // Return number of accepted items to be taken
6310 int scriptapi_detached_inventory_allow_take(lua_State *L,
6311 const std::string &name,
6312 const std::string &listname, int index, ItemStack &stack,
6313 ServerActiveObject *player)
6316 assert(lua_checkstack(L, 20));
6317 StackUnroller stack_unroller(L);
6319 // Push callback function on stack
6320 if(!get_detached_inventory_callback(L, name, "allow_take"))
6321 return stack.count; // All will be accepted
6323 // Call function(inv, listname, index, stack, player)
6325 InventoryLocation loc;
6326 loc.setDetached(name);
6327 InvRef::create(L, loc);
6329 lua_pushstring(L, listname.c_str());
6331 lua_pushinteger(L, index + 1);
6333 LuaItemStack::create(L, stack);
6335 objectref_get_or_create(L, player);
6336 if(lua_pcall(L, 5, 1, 0))
6337 script_error(L, "error: %s", lua_tostring(L, -1));
6338 if(!lua_isnumber(L, -1))
6339 throw LuaError(L, "allow_take should return a number");
6340 return luaL_checkinteger(L, -1);
6343 // Report moved items
6344 void scriptapi_detached_inventory_on_move(lua_State *L,
6345 const std::string &name,
6346 const std::string &from_list, int from_index,
6347 const std::string &to_list, int to_index,
6348 int count, ServerActiveObject *player)
6351 assert(lua_checkstack(L, 20));
6352 StackUnroller stack_unroller(L);
6354 // Push callback function on stack
6355 if(!get_detached_inventory_callback(L, name, "on_move"))
6358 // function(inv, from_list, from_index, to_list, to_index, count, player)
6360 InventoryLocation loc;
6361 loc.setDetached(name);
6362 InvRef::create(L, loc);
6364 lua_pushstring(L, from_list.c_str());
6366 lua_pushinteger(L, from_index + 1);
6368 lua_pushstring(L, to_list.c_str());
6370 lua_pushinteger(L, to_index + 1);
6372 lua_pushinteger(L, count);
6374 objectref_get_or_create(L, player);
6375 if(lua_pcall(L, 7, 0, 0))
6376 script_error(L, "error: %s", lua_tostring(L, -1));
6380 void scriptapi_detached_inventory_on_put(lua_State *L,
6381 const std::string &name,
6382 const std::string &listname, int index, ItemStack &stack,
6383 ServerActiveObject *player)
6386 assert(lua_checkstack(L, 20));
6387 StackUnroller stack_unroller(L);
6389 // Push callback function on stack
6390 if(!get_detached_inventory_callback(L, name, "on_put"))
6393 // Call function(inv, listname, index, stack, player)
6395 InventoryLocation loc;
6396 loc.setDetached(name);
6397 InvRef::create(L, loc);
6399 lua_pushstring(L, listname.c_str());
6401 lua_pushinteger(L, index + 1);
6403 LuaItemStack::create(L, stack);
6405 objectref_get_or_create(L, player);
6406 if(lua_pcall(L, 5, 0, 0))
6407 script_error(L, "error: %s", lua_tostring(L, -1));
6410 // Report taken items
6411 void scriptapi_detached_inventory_on_take(lua_State *L,
6412 const std::string &name,
6413 const std::string &listname, int index, ItemStack &stack,
6414 ServerActiveObject *player)
6417 assert(lua_checkstack(L, 20));
6418 StackUnroller stack_unroller(L);
6420 // Push callback function on stack
6421 if(!get_detached_inventory_callback(L, name, "on_take"))
6424 // Call function(inv, listname, index, stack, player)
6426 InventoryLocation loc;
6427 loc.setDetached(name);
6428 InvRef::create(L, loc);
6430 lua_pushstring(L, listname.c_str());
6432 lua_pushinteger(L, index + 1);
6434 LuaItemStack::create(L, stack);
6436 objectref_get_or_create(L, player);
6437 if(lua_pcall(L, 5, 0, 0))
6438 script_error(L, "error: %s", lua_tostring(L, -1));
6445 void scriptapi_environment_step(lua_State *L, float dtime)
6448 assert(lua_checkstack(L, 20));
6449 //infostream<<"scriptapi_environment_step"<<std::endl;
6450 StackUnroller stack_unroller(L);
6452 // Get minetest.registered_globalsteps
6453 lua_getglobal(L, "minetest");
6454 lua_getfield(L, -1, "registered_globalsteps");
6456 lua_pushnumber(L, dtime);
6457 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6460 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6464 assert(lua_checkstack(L, 20));
6465 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6466 StackUnroller stack_unroller(L);
6468 // Get minetest.registered_on_generateds
6469 lua_getglobal(L, "minetest");
6470 lua_getfield(L, -1, "registered_on_generateds");
6472 push_v3s16(L, minp);
6473 push_v3s16(L, maxp);
6474 lua_pushnumber(L, blockseed);
6475 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6482 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6485 assert(lua_checkstack(L, 20));
6486 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6487 <<name<<"\""<<std::endl;
6488 StackUnroller stack_unroller(L);
6490 // Get minetest.registered_entities[name]
6491 lua_getglobal(L, "minetest");
6492 lua_getfield(L, -1, "registered_entities");
6493 luaL_checktype(L, -1, LUA_TTABLE);
6494 lua_pushstring(L, name);
6495 lua_gettable(L, -2);
6496 // Should be a table, which we will use as a prototype
6497 //luaL_checktype(L, -1, LUA_TTABLE);
6498 if(lua_type(L, -1) != LUA_TTABLE){
6499 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6502 int prototype_table = lua_gettop(L);
6503 //dump2(L, "prototype_table");
6505 // Create entity object
6507 int object = lua_gettop(L);
6509 // Set object metatable
6510 lua_pushvalue(L, prototype_table);
6511 lua_setmetatable(L, -2);
6513 // Add object reference
6514 // This should be userdata with metatable ObjectRef
6515 objectref_get(L, id);
6516 luaL_checktype(L, -1, LUA_TUSERDATA);
6517 if(!luaL_checkudata(L, -1, "ObjectRef"))
6518 luaL_typerror(L, -1, "ObjectRef");
6519 lua_setfield(L, -2, "object");
6521 // minetest.luaentities[id] = object
6522 lua_getglobal(L, "minetest");
6523 lua_getfield(L, -1, "luaentities");
6524 luaL_checktype(L, -1, LUA_TTABLE);
6525 lua_pushnumber(L, id); // Push id
6526 lua_pushvalue(L, object); // Copy object to top of stack
6527 lua_settable(L, -3);
6532 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6533 const std::string &staticdata, u32 dtime_s)
6536 assert(lua_checkstack(L, 20));
6537 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6538 StackUnroller stack_unroller(L);
6540 // Get minetest.luaentities[id]
6541 luaentity_get(L, id);
6542 int object = lua_gettop(L);
6544 // Get on_activate function
6545 lua_pushvalue(L, object);
6546 lua_getfield(L, -1, "on_activate");
6547 if(!lua_isnil(L, -1)){
6548 luaL_checktype(L, -1, LUA_TFUNCTION);
6549 lua_pushvalue(L, object); // self
6550 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6551 lua_pushinteger(L, dtime_s);
6552 // Call with 3 arguments, 0 results
6553 if(lua_pcall(L, 3, 0, 0))
6554 script_error(L, "error running function on_activate: %s\n",
6555 lua_tostring(L, -1));
6559 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6562 assert(lua_checkstack(L, 20));
6563 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6565 // Get minetest.luaentities table
6566 lua_getglobal(L, "minetest");
6567 lua_getfield(L, -1, "luaentities");
6568 luaL_checktype(L, -1, LUA_TTABLE);
6569 int objectstable = lua_gettop(L);
6571 // Set luaentities[id] = nil
6572 lua_pushnumber(L, id); // Push id
6574 lua_settable(L, objectstable);
6576 lua_pop(L, 2); // pop luaentities, minetest
6579 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6582 assert(lua_checkstack(L, 20));
6583 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6584 StackUnroller stack_unroller(L);
6586 // Get minetest.luaentities[id]
6587 luaentity_get(L, id);
6588 int object = lua_gettop(L);
6590 // Get get_staticdata function
6591 lua_pushvalue(L, object);
6592 lua_getfield(L, -1, "get_staticdata");
6593 if(lua_isnil(L, -1))
6596 luaL_checktype(L, -1, LUA_TFUNCTION);
6597 lua_pushvalue(L, object); // self
6598 // Call with 1 arguments, 1 results
6599 if(lua_pcall(L, 1, 1, 0))
6600 script_error(L, "error running function get_staticdata: %s\n",
6601 lua_tostring(L, -1));
6604 const char *s = lua_tolstring(L, -1, &len);
6605 return std::string(s, len);
6608 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6609 ObjectProperties *prop)
6612 assert(lua_checkstack(L, 20));
6613 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6614 StackUnroller stack_unroller(L);
6616 // Get minetest.luaentities[id]
6617 luaentity_get(L, id);
6618 //int object = lua_gettop(L);
6620 // Set default values that differ from ObjectProperties defaults
6625 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6627 getboolfield(L, -1, "physical", prop->physical);
6629 getfloatfield(L, -1, "weight", prop->weight);
6631 lua_getfield(L, -1, "collisionbox");
6632 if(lua_istable(L, -1))
6633 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6636 getstringfield(L, -1, "visual", prop->visual);
6638 getstringfield(L, -1, "mesh", prop->mesh);
6640 // Deprecated: read object properties directly
6641 read_object_properties(L, -1, prop);
6643 // Read initial_properties
6644 lua_getfield(L, -1, "initial_properties");
6645 read_object_properties(L, -1, prop);
6649 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6652 assert(lua_checkstack(L, 20));
6653 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6654 StackUnroller stack_unroller(L);
6656 // Get minetest.luaentities[id]
6657 luaentity_get(L, id);
6658 int object = lua_gettop(L);
6659 // State: object is at top of stack
6660 // Get step function
6661 lua_getfield(L, -1, "on_step");
6662 if(lua_isnil(L, -1))
6664 luaL_checktype(L, -1, LUA_TFUNCTION);
6665 lua_pushvalue(L, object); // self
6666 lua_pushnumber(L, dtime); // dtime
6667 // Call with 2 arguments, 0 results
6668 if(lua_pcall(L, 2, 0, 0))
6669 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6672 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6673 // tool_capabilities, direction)
6674 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6675 ServerActiveObject *puncher, float time_from_last_punch,
6676 const ToolCapabilities *toolcap, v3f dir)
6679 assert(lua_checkstack(L, 20));
6680 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6681 StackUnroller stack_unroller(L);
6683 // Get minetest.luaentities[id]
6684 luaentity_get(L, id);
6685 int object = lua_gettop(L);
6686 // State: object is at top of stack
6688 lua_getfield(L, -1, "on_punch");
6689 if(lua_isnil(L, -1))
6691 luaL_checktype(L, -1, LUA_TFUNCTION);
6692 lua_pushvalue(L, object); // self
6693 objectref_get_or_create(L, puncher); // Clicker reference
6694 lua_pushnumber(L, time_from_last_punch);
6695 push_tool_capabilities(L, *toolcap);
6697 // Call with 5 arguments, 0 results
6698 if(lua_pcall(L, 5, 0, 0))
6699 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6702 // Calls entity:on_rightclick(ObjectRef clicker)
6703 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6704 ServerActiveObject *clicker)
6707 assert(lua_checkstack(L, 20));
6708 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6709 StackUnroller stack_unroller(L);
6711 // Get minetest.luaentities[id]
6712 luaentity_get(L, id);
6713 int object = lua_gettop(L);
6714 // State: object is at top of stack
6716 lua_getfield(L, -1, "on_rightclick");
6717 if(lua_isnil(L, -1))
6719 luaL_checktype(L, -1, LUA_TFUNCTION);
6720 lua_pushvalue(L, object); // self
6721 objectref_get_or_create(L, clicker); // Clicker reference
6722 // Call with 2 arguments, 0 results
6723 if(lua_pcall(L, 2, 0, 0))
6724 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));