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 lua_getfield(L, -1, "visual_size");
941 if(lua_istable(L, -1))
942 prop->visual_size = read_v2f(L, -1);
945 lua_getfield(L, -1, "textures");
946 if(lua_istable(L, -1)){
947 prop->textures.clear();
948 int table = lua_gettop(L);
950 while(lua_next(L, table) != 0){
951 // key at index -2 and value at index -1
952 if(lua_isstring(L, -1))
953 prop->textures.push_back(lua_tostring(L, -1));
955 prop->textures.push_back("");
956 // removes value, keeps key for next iteration
962 lua_getfield(L, -1, "spritediv");
963 if(lua_istable(L, -1))
964 prop->spritediv = read_v2s16(L, -1);
967 lua_getfield(L, -1, "initial_sprite_basepos");
968 if(lua_istable(L, -1))
969 prop->initial_sprite_basepos = read_v2s16(L, -1);
972 getboolfield(L, -1, "is_visible", prop->is_visible);
973 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
974 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
981 static ItemDefinition read_item_definition(lua_State *L, int index,
982 ItemDefinition default_def = ItemDefinition())
985 index = lua_gettop(L) + 1 + index;
987 // Read the item definition
988 ItemDefinition def = default_def;
990 def.type = (ItemType)getenumfield(L, index, "type",
991 es_ItemType, ITEM_NONE);
992 getstringfield(L, index, "name", def.name);
993 getstringfield(L, index, "description", def.description);
994 getstringfield(L, index, "inventory_image", def.inventory_image);
995 getstringfield(L, index, "wield_image", def.wield_image);
997 lua_getfield(L, index, "wield_scale");
998 if(lua_istable(L, -1)){
999 def.wield_scale = check_v3f(L, -1);
1003 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1004 if(def.stack_max == 0)
1007 lua_getfield(L, index, "on_use");
1008 def.usable = lua_isfunction(L, -1);
1011 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1013 warn_if_field_exists(L, index, "tool_digging_properties",
1014 "deprecated: use tool_capabilities");
1016 lua_getfield(L, index, "tool_capabilities");
1017 if(lua_istable(L, -1)){
1018 def.tool_capabilities = new ToolCapabilities(
1019 read_tool_capabilities(L, -1));
1022 // If name is "" (hand), ensure there are ToolCapabilities
1023 // because it will be looked up there whenever any other item has
1024 // no ToolCapabilities
1025 if(def.name == "" && def.tool_capabilities == NULL){
1026 def.tool_capabilities = new ToolCapabilities();
1029 lua_getfield(L, index, "groups");
1030 read_groups(L, -1, def.groups);
1033 // Client shall immediately place this node when player places the item.
1034 // Server will update the precise end result a moment later.
1035 // "" = no prediction
1036 getstringfield(L, index, "node_placement_prediction",
1037 def.node_placement_prediction);
1046 static TileDef read_tiledef(lua_State *L, int index)
1049 index = lua_gettop(L) + 1 + index;
1053 // key at index -2 and value at index
1054 if(lua_isstring(L, index)){
1055 // "default_lava.png"
1056 tiledef.name = lua_tostring(L, index);
1058 else if(lua_istable(L, index))
1060 // {name="default_lava.png", animation={}}
1062 getstringfield(L, index, "name", tiledef.name);
1063 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1064 tiledef.backface_culling = getboolfield_default(
1065 L, index, "backface_culling", true);
1067 lua_getfield(L, index, "animation");
1068 if(lua_istable(L, -1)){
1069 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1070 tiledef.animation.type = (TileAnimationType)
1071 getenumfield(L, -1, "type", es_TileAnimationType,
1073 tiledef.animation.aspect_w =
1074 getintfield_default(L, -1, "aspect_w", 16);
1075 tiledef.animation.aspect_h =
1076 getintfield_default(L, -1, "aspect_h", 16);
1077 tiledef.animation.length =
1078 getfloatfield_default(L, -1, "length", 1.0);
1090 static ContentFeatures read_content_features(lua_State *L, int index)
1093 index = lua_gettop(L) + 1 + index;
1097 /* Cache existence of some callbacks */
1098 lua_getfield(L, index, "on_construct");
1099 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1101 lua_getfield(L, index, "on_destruct");
1102 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1104 lua_getfield(L, index, "after_destruct");
1105 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1109 getstringfield(L, index, "name", f.name);
1112 lua_getfield(L, index, "groups");
1113 read_groups(L, -1, f.groups);
1116 /* Visual definition */
1118 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1120 getfloatfield(L, index, "visual_scale", f.visual_scale);
1123 lua_getfield(L, index, "tiles");
1124 // If nil, try the deprecated name "tile_images" instead
1125 if(lua_isnil(L, -1)){
1127 warn_if_field_exists(L, index, "tile_images",
1128 "Deprecated; new name is \"tiles\".");
1129 lua_getfield(L, index, "tile_images");
1131 if(lua_istable(L, -1)){
1132 int table = lua_gettop(L);
1135 while(lua_next(L, table) != 0){
1136 // Read tiledef from value
1137 f.tiledef[i] = read_tiledef(L, -1);
1138 // removes value, keeps key for next iteration
1146 // Copy last value to all remaining textures
1148 TileDef lasttile = f.tiledef[i-1];
1150 f.tiledef[i] = lasttile;
1157 // special_tiles = {}
1158 lua_getfield(L, index, "special_tiles");
1159 // If nil, try the deprecated name "special_materials" instead
1160 if(lua_isnil(L, -1)){
1162 warn_if_field_exists(L, index, "special_materials",
1163 "Deprecated; new name is \"special_tiles\".");
1164 lua_getfield(L, index, "special_materials");
1166 if(lua_istable(L, -1)){
1167 int table = lua_gettop(L);
1170 while(lua_next(L, table) != 0){
1171 // Read tiledef from value
1172 f.tiledef_special[i] = read_tiledef(L, -1);
1173 // removes value, keeps key for next iteration
1184 f.alpha = getintfield_default(L, index, "alpha", 255);
1188 lua_getfield(L, index, "post_effect_color");
1189 if(!lua_isnil(L, -1))
1190 f.post_effect_color = readARGB8(L, -1);
1193 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1194 es_ContentParamType, CPT_NONE);
1195 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1196 es_ContentParamType2, CPT2_NONE);
1198 // Warn about some deprecated fields
1199 warn_if_field_exists(L, index, "wall_mounted",
1200 "deprecated: use paramtype2 = 'wallmounted'");
1201 warn_if_field_exists(L, index, "light_propagates",
1202 "deprecated: determined from paramtype");
1203 warn_if_field_exists(L, index, "dug_item",
1204 "deprecated: use 'drop' field");
1205 warn_if_field_exists(L, index, "extra_dug_item",
1206 "deprecated: use 'drop' field");
1207 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1208 "deprecated: use 'drop' field");
1209 warn_if_field_exists(L, index, "metadata_name",
1210 "deprecated: use on_add and metadata callbacks");
1212 // True for all ground-like things like stone and mud, false for eg. trees
1213 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1214 f.light_propagates = (f.param_type == CPT_LIGHT);
1215 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1216 // This is used for collision detection.
1217 // Also for general solidness queries.
1218 getboolfield(L, index, "walkable", f.walkable);
1219 // Player can point to these
1220 getboolfield(L, index, "pointable", f.pointable);
1221 // Player can dig these
1222 getboolfield(L, index, "diggable", f.diggable);
1223 // Player can climb these
1224 getboolfield(L, index, "climbable", f.climbable);
1225 // Player can build on these
1226 getboolfield(L, index, "buildable_to", f.buildable_to);
1227 // Whether the node is non-liquid, source liquid or flowing liquid
1228 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1229 es_LiquidType, LIQUID_NONE);
1230 // If the content is liquid, this is the flowing version of the liquid.
1231 getstringfield(L, index, "liquid_alternative_flowing",
1232 f.liquid_alternative_flowing);
1233 // If the content is liquid, this is the source version of the liquid.
1234 getstringfield(L, index, "liquid_alternative_source",
1235 f.liquid_alternative_source);
1236 // Viscosity for fluid flow, ranging from 1 to 7, with
1237 // 1 giving almost instantaneous propagation and 7 being
1238 // the slowest possible
1239 f.liquid_viscosity = getintfield_default(L, index,
1240 "liquid_viscosity", f.liquid_viscosity);
1241 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1242 // Amount of light the node emits
1243 f.light_source = getintfield_default(L, index,
1244 "light_source", f.light_source);
1245 f.damage_per_second = getintfield_default(L, index,
1246 "damage_per_second", f.damage_per_second);
1248 lua_getfield(L, index, "node_box");
1249 if(lua_istable(L, -1))
1250 f.node_box = read_nodebox(L, -1);
1253 lua_getfield(L, index, "selection_box");
1254 if(lua_istable(L, -1))
1255 f.selection_box = read_nodebox(L, -1);
1258 // Set to true if paramtype used to be 'facedir_simple'
1259 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1260 // Set to true if wall_mounted used to be set to true
1261 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1264 lua_getfield(L, index, "sounds");
1265 if(lua_istable(L, -1)){
1266 lua_getfield(L, -1, "footstep");
1267 read_soundspec(L, -1, f.sound_footstep);
1269 lua_getfield(L, -1, "dig");
1270 read_soundspec(L, -1, f.sound_dig);
1272 lua_getfield(L, -1, "dug");
1273 read_soundspec(L, -1, f.sound_dug);
1285 static ItemStack read_item(lua_State *L, int index);
1286 static std::vector<ItemStack> read_items(lua_State *L, int index);
1287 // creates a table of ItemStacks
1288 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1290 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1291 lua_State *L, int tableindex, int forcesize=-1)
1294 tableindex = lua_gettop(L) + 1 + tableindex;
1295 // If nil, delete list
1296 if(lua_isnil(L, tableindex)){
1297 inv->deleteList(name);
1300 // Otherwise set list
1301 std::vector<ItemStack> items = read_items(L, tableindex);
1302 int listsize = (forcesize != -1) ? forcesize : items.size();
1303 InventoryList *invlist = inv->addList(name, listsize);
1305 for(std::vector<ItemStack>::const_iterator
1306 i = items.begin(); i != items.end(); i++){
1307 if(forcesize != -1 && index == forcesize)
1309 invlist->changeItem(index, *i);
1312 while(forcesize != -1 && index < forcesize){
1313 invlist->deleteItem(index);
1318 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1321 InventoryList *invlist = inv->getList(name);
1322 if(invlist == NULL){
1326 std::vector<ItemStack> items;
1327 for(u32 i=0; i<invlist->getSize(); i++)
1328 items.push_back(invlist->getItem(i));
1329 push_items(L, items);
1333 Helpful macros for userdata classes
1336 #define method(class, name) {#name, class::l_##name}
1347 static const char className[];
1348 static const luaL_reg methods[];
1350 // Exported functions
1352 // garbage collector
1353 static int gc_object(lua_State *L)
1355 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1360 // is_empty(self) -> true/false
1361 static int l_is_empty(lua_State *L)
1363 LuaItemStack *o = checkobject(L, 1);
1364 ItemStack &item = o->m_stack;
1365 lua_pushboolean(L, item.empty());
1369 // get_name(self) -> string
1370 static int l_get_name(lua_State *L)
1372 LuaItemStack *o = checkobject(L, 1);
1373 ItemStack &item = o->m_stack;
1374 lua_pushstring(L, item.name.c_str());
1378 // get_count(self) -> number
1379 static int l_get_count(lua_State *L)
1381 LuaItemStack *o = checkobject(L, 1);
1382 ItemStack &item = o->m_stack;
1383 lua_pushinteger(L, item.count);
1387 // get_wear(self) -> number
1388 static int l_get_wear(lua_State *L)
1390 LuaItemStack *o = checkobject(L, 1);
1391 ItemStack &item = o->m_stack;
1392 lua_pushinteger(L, item.wear);
1396 // get_metadata(self) -> string
1397 static int l_get_metadata(lua_State *L)
1399 LuaItemStack *o = checkobject(L, 1);
1400 ItemStack &item = o->m_stack;
1401 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1405 // clear(self) -> true
1406 static int l_clear(lua_State *L)
1408 LuaItemStack *o = checkobject(L, 1);
1410 lua_pushboolean(L, true);
1414 // replace(self, itemstack or itemstring or table or nil) -> true
1415 static int l_replace(lua_State *L)
1417 LuaItemStack *o = checkobject(L, 1);
1418 o->m_stack = read_item(L, 2);
1419 lua_pushboolean(L, true);
1423 // to_string(self) -> string
1424 static int l_to_string(lua_State *L)
1426 LuaItemStack *o = checkobject(L, 1);
1427 std::string itemstring = o->m_stack.getItemString();
1428 lua_pushstring(L, itemstring.c_str());
1432 // to_table(self) -> table or nil
1433 static int l_to_table(lua_State *L)
1435 LuaItemStack *o = checkobject(L, 1);
1436 const ItemStack &item = o->m_stack;
1444 lua_pushstring(L, item.name.c_str());
1445 lua_setfield(L, -2, "name");
1446 lua_pushinteger(L, item.count);
1447 lua_setfield(L, -2, "count");
1448 lua_pushinteger(L, item.wear);
1449 lua_setfield(L, -2, "wear");
1450 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1451 lua_setfield(L, -2, "metadata");
1456 // get_stack_max(self) -> number
1457 static int l_get_stack_max(lua_State *L)
1459 LuaItemStack *o = checkobject(L, 1);
1460 ItemStack &item = o->m_stack;
1461 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1465 // get_free_space(self) -> number
1466 static int l_get_free_space(lua_State *L)
1468 LuaItemStack *o = checkobject(L, 1);
1469 ItemStack &item = o->m_stack;
1470 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1474 // is_known(self) -> true/false
1475 // Checks if the item is defined.
1476 static int l_is_known(lua_State *L)
1478 LuaItemStack *o = checkobject(L, 1);
1479 ItemStack &item = o->m_stack;
1480 bool is_known = item.isKnown(get_server(L)->idef());
1481 lua_pushboolean(L, is_known);
1485 // get_definition(self) -> table
1486 // Returns the item definition table from minetest.registered_items,
1487 // or a fallback one (name="unknown")
1488 static int l_get_definition(lua_State *L)
1490 LuaItemStack *o = checkobject(L, 1);
1491 ItemStack &item = o->m_stack;
1493 // Get minetest.registered_items[name]
1494 lua_getglobal(L, "minetest");
1495 lua_getfield(L, -1, "registered_items");
1496 luaL_checktype(L, -1, LUA_TTABLE);
1497 lua_getfield(L, -1, item.name.c_str());
1498 if(lua_isnil(L, -1))
1501 lua_getfield(L, -1, "unknown");
1506 // get_tool_capabilities(self) -> table
1507 // Returns the effective tool digging properties.
1508 // Returns those of the hand ("") if this item has none associated.
1509 static int l_get_tool_capabilities(lua_State *L)
1511 LuaItemStack *o = checkobject(L, 1);
1512 ItemStack &item = o->m_stack;
1513 const ToolCapabilities &prop =
1514 item.getToolCapabilities(get_server(L)->idef());
1515 push_tool_capabilities(L, prop);
1519 // add_wear(self, amount) -> true/false
1520 // The range for "amount" is [0,65535]. Wear is only added if the item
1521 // is a tool. Adding wear might destroy the item.
1522 // Returns true if the item is (or was) a tool.
1523 static int l_add_wear(lua_State *L)
1525 LuaItemStack *o = checkobject(L, 1);
1526 ItemStack &item = o->m_stack;
1527 int amount = lua_tointeger(L, 2);
1528 bool result = item.addWear(amount, get_server(L)->idef());
1529 lua_pushboolean(L, result);
1533 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1534 // Returns leftover item stack
1535 static int l_add_item(lua_State *L)
1537 LuaItemStack *o = checkobject(L, 1);
1538 ItemStack &item = o->m_stack;
1539 ItemStack newitem = read_item(L, 2);
1540 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1541 create(L, leftover);
1545 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1546 // First return value is true iff the new item fits fully into the stack
1547 // Second return value is the would-be-left-over item stack
1548 static int l_item_fits(lua_State *L)
1550 LuaItemStack *o = checkobject(L, 1);
1551 ItemStack &item = o->m_stack;
1552 ItemStack newitem = read_item(L, 2);
1554 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1555 lua_pushboolean(L, fits); // first return value
1556 create(L, restitem); // second return value
1560 // take_item(self, takecount=1) -> itemstack
1561 static int l_take_item(lua_State *L)
1563 LuaItemStack *o = checkobject(L, 1);
1564 ItemStack &item = o->m_stack;
1566 if(!lua_isnone(L, 2))
1567 takecount = luaL_checkinteger(L, 2);
1568 ItemStack taken = item.takeItem(takecount);
1573 // peek_item(self, peekcount=1) -> itemstack
1574 static int l_peek_item(lua_State *L)
1576 LuaItemStack *o = checkobject(L, 1);
1577 ItemStack &item = o->m_stack;
1579 if(!lua_isnone(L, 2))
1580 peekcount = lua_tointeger(L, 2);
1581 ItemStack peekaboo = item.peekItem(peekcount);
1582 create(L, peekaboo);
1587 LuaItemStack(const ItemStack &item):
1596 const ItemStack& getItem() const
1600 ItemStack& getItem()
1605 // LuaItemStack(itemstack or itemstring or table or nil)
1606 // Creates an LuaItemStack and leaves it on top of stack
1607 static int create_object(lua_State *L)
1609 ItemStack item = read_item(L, 1);
1610 LuaItemStack *o = new LuaItemStack(item);
1611 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1612 luaL_getmetatable(L, className);
1613 lua_setmetatable(L, -2);
1616 // Not callable from Lua
1617 static int create(lua_State *L, const ItemStack &item)
1619 LuaItemStack *o = new LuaItemStack(item);
1620 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1621 luaL_getmetatable(L, className);
1622 lua_setmetatable(L, -2);
1626 static LuaItemStack* checkobject(lua_State *L, int narg)
1628 luaL_checktype(L, narg, LUA_TUSERDATA);
1629 void *ud = luaL_checkudata(L, narg, className);
1630 if(!ud) luaL_typerror(L, narg, className);
1631 return *(LuaItemStack**)ud; // unbox pointer
1634 static void Register(lua_State *L)
1637 int methodtable = lua_gettop(L);
1638 luaL_newmetatable(L, className);
1639 int metatable = lua_gettop(L);
1641 lua_pushliteral(L, "__metatable");
1642 lua_pushvalue(L, methodtable);
1643 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1645 lua_pushliteral(L, "__index");
1646 lua_pushvalue(L, methodtable);
1647 lua_settable(L, metatable);
1649 lua_pushliteral(L, "__gc");
1650 lua_pushcfunction(L, gc_object);
1651 lua_settable(L, metatable);
1653 lua_pop(L, 1); // drop metatable
1655 luaL_openlib(L, 0, methods, 0); // fill methodtable
1656 lua_pop(L, 1); // drop methodtable
1658 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1659 lua_register(L, className, create_object);
1662 const char LuaItemStack::className[] = "ItemStack";
1663 const luaL_reg LuaItemStack::methods[] = {
1664 method(LuaItemStack, is_empty),
1665 method(LuaItemStack, get_name),
1666 method(LuaItemStack, get_count),
1667 method(LuaItemStack, get_wear),
1668 method(LuaItemStack, get_metadata),
1669 method(LuaItemStack, clear),
1670 method(LuaItemStack, replace),
1671 method(LuaItemStack, to_string),
1672 method(LuaItemStack, to_table),
1673 method(LuaItemStack, get_stack_max),
1674 method(LuaItemStack, get_free_space),
1675 method(LuaItemStack, is_known),
1676 method(LuaItemStack, get_definition),
1677 method(LuaItemStack, get_tool_capabilities),
1678 method(LuaItemStack, add_wear),
1679 method(LuaItemStack, add_item),
1680 method(LuaItemStack, item_fits),
1681 method(LuaItemStack, take_item),
1682 method(LuaItemStack, peek_item),
1686 static ItemStack read_item(lua_State *L, int index)
1689 index = lua_gettop(L) + 1 + index;
1691 if(lua_isnil(L, index))
1695 else if(lua_isuserdata(L, index))
1697 // Convert from LuaItemStack
1698 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1699 return o->getItem();
1701 else if(lua_isstring(L, index))
1703 // Convert from itemstring
1704 std::string itemstring = lua_tostring(L, index);
1705 IItemDefManager *idef = get_server(L)->idef();
1709 item.deSerialize(itemstring, idef);
1712 catch(SerializationError &e)
1714 infostream<<"WARNING: unable to create item from itemstring"
1715 <<": "<<itemstring<<std::endl;
1719 else if(lua_istable(L, index))
1721 // Convert from table
1722 IItemDefManager *idef = get_server(L)->idef();
1723 std::string name = getstringfield_default(L, index, "name", "");
1724 int count = getintfield_default(L, index, "count", 1);
1725 int wear = getintfield_default(L, index, "wear", 0);
1726 std::string metadata = getstringfield_default(L, index, "metadata", "");
1727 return ItemStack(name, count, wear, metadata, idef);
1731 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1735 static std::vector<ItemStack> read_items(lua_State *L, int index)
1738 index = lua_gettop(L) + 1 + index;
1740 std::vector<ItemStack> items;
1741 luaL_checktype(L, index, LUA_TTABLE);
1743 while(lua_next(L, index) != 0){
1744 // key at index -2 and value at index -1
1745 items.push_back(read_item(L, -1));
1746 // removes value, keeps key for next iteration
1752 // creates a table of ItemStacks
1753 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1755 // Get the table insert function
1756 lua_getglobal(L, "table");
1757 lua_getfield(L, -1, "insert");
1758 int table_insert = lua_gettop(L);
1759 // Create and fill table
1761 int table = lua_gettop(L);
1762 for(u32 i=0; i<items.size(); i++){
1763 ItemStack item = items[i];
1764 lua_pushvalue(L, table_insert);
1765 lua_pushvalue(L, table);
1766 LuaItemStack::create(L, item);
1767 if(lua_pcall(L, 2, 0, 0))
1768 script_error(L, "error: %s", lua_tostring(L, -1));
1770 lua_remove(L, -2); // Remove table
1771 lua_remove(L, -2); // Remove insert
1781 InventoryLocation m_loc;
1783 static const char className[];
1784 static const luaL_reg methods[];
1786 static InvRef *checkobject(lua_State *L, int narg)
1788 luaL_checktype(L, narg, LUA_TUSERDATA);
1789 void *ud = luaL_checkudata(L, narg, className);
1790 if(!ud) luaL_typerror(L, narg, className);
1791 return *(InvRef**)ud; // unbox pointer
1794 static Inventory* getinv(lua_State *L, InvRef *ref)
1796 return get_server(L)->getInventory(ref->m_loc);
1799 static InventoryList* getlist(lua_State *L, InvRef *ref,
1800 const char *listname)
1802 Inventory *inv = getinv(L, ref);
1805 return inv->getList(listname);
1808 static void reportInventoryChange(lua_State *L, InvRef *ref)
1810 // Inform other things that the inventory has changed
1811 get_server(L)->setInventoryModified(ref->m_loc);
1814 // Exported functions
1816 // garbage collector
1817 static int gc_object(lua_State *L) {
1818 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1823 // is_empty(self, listname) -> true/false
1824 static int l_is_empty(lua_State *L)
1826 InvRef *ref = checkobject(L, 1);
1827 const char *listname = luaL_checkstring(L, 2);
1828 InventoryList *list = getlist(L, ref, listname);
1829 if(list && list->getUsedSlots() > 0){
1830 lua_pushboolean(L, false);
1832 lua_pushboolean(L, true);
1837 // get_size(self, listname)
1838 static int l_get_size(lua_State *L)
1840 InvRef *ref = checkobject(L, 1);
1841 const char *listname = luaL_checkstring(L, 2);
1842 InventoryList *list = getlist(L, ref, listname);
1844 lua_pushinteger(L, list->getSize());
1846 lua_pushinteger(L, 0);
1851 // get_width(self, listname)
1852 static int l_get_width(lua_State *L)
1854 InvRef *ref = checkobject(L, 1);
1855 const char *listname = luaL_checkstring(L, 2);
1856 InventoryList *list = getlist(L, ref, listname);
1858 lua_pushinteger(L, list->getWidth());
1860 lua_pushinteger(L, 0);
1865 // set_size(self, listname, size)
1866 static int l_set_size(lua_State *L)
1868 InvRef *ref = checkobject(L, 1);
1869 const char *listname = luaL_checkstring(L, 2);
1870 int newsize = luaL_checknumber(L, 3);
1871 Inventory *inv = getinv(L, ref);
1873 inv->deleteList(listname);
1874 reportInventoryChange(L, ref);
1877 InventoryList *list = inv->getList(listname);
1879 list->setSize(newsize);
1881 list = inv->addList(listname, newsize);
1883 reportInventoryChange(L, ref);
1887 // set_width(self, listname, size)
1888 static int l_set_width(lua_State *L)
1890 InvRef *ref = checkobject(L, 1);
1891 const char *listname = luaL_checkstring(L, 2);
1892 int newwidth = luaL_checknumber(L, 3);
1893 Inventory *inv = getinv(L, ref);
1894 InventoryList *list = inv->getList(listname);
1896 list->setWidth(newwidth);
1900 reportInventoryChange(L, ref);
1904 // get_stack(self, listname, i) -> itemstack
1905 static int l_get_stack(lua_State *L)
1907 InvRef *ref = checkobject(L, 1);
1908 const char *listname = luaL_checkstring(L, 2);
1909 int i = luaL_checknumber(L, 3) - 1;
1910 InventoryList *list = getlist(L, ref, listname);
1912 if(list != NULL && i >= 0 && i < (int) list->getSize())
1913 item = list->getItem(i);
1914 LuaItemStack::create(L, item);
1918 // set_stack(self, listname, i, stack) -> true/false
1919 static int l_set_stack(lua_State *L)
1921 InvRef *ref = checkobject(L, 1);
1922 const char *listname = luaL_checkstring(L, 2);
1923 int i = luaL_checknumber(L, 3) - 1;
1924 ItemStack newitem = read_item(L, 4);
1925 InventoryList *list = getlist(L, ref, listname);
1926 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1927 list->changeItem(i, newitem);
1928 reportInventoryChange(L, ref);
1929 lua_pushboolean(L, true);
1931 lua_pushboolean(L, false);
1936 // get_list(self, listname) -> list or nil
1937 static int l_get_list(lua_State *L)
1939 InvRef *ref = checkobject(L, 1);
1940 const char *listname = luaL_checkstring(L, 2);
1941 Inventory *inv = getinv(L, ref);
1942 inventory_get_list_to_lua(inv, listname, L);
1946 // set_list(self, listname, list)
1947 static int l_set_list(lua_State *L)
1949 InvRef *ref = checkobject(L, 1);
1950 const char *listname = luaL_checkstring(L, 2);
1951 Inventory *inv = getinv(L, ref);
1952 InventoryList *list = inv->getList(listname);
1954 inventory_set_list_from_lua(inv, listname, L, 3,
1957 inventory_set_list_from_lua(inv, listname, L, 3);
1958 reportInventoryChange(L, ref);
1962 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1963 // Returns the leftover stack
1964 static int l_add_item(lua_State *L)
1966 InvRef *ref = checkobject(L, 1);
1967 const char *listname = luaL_checkstring(L, 2);
1968 ItemStack item = read_item(L, 3);
1969 InventoryList *list = getlist(L, ref, listname);
1971 ItemStack leftover = list->addItem(item);
1972 if(leftover.count != item.count)
1973 reportInventoryChange(L, ref);
1974 LuaItemStack::create(L, leftover);
1976 LuaItemStack::create(L, item);
1981 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1982 // Returns true if the item completely fits into the list
1983 static int l_room_for_item(lua_State *L)
1985 InvRef *ref = checkobject(L, 1);
1986 const char *listname = luaL_checkstring(L, 2);
1987 ItemStack item = read_item(L, 3);
1988 InventoryList *list = getlist(L, ref, listname);
1990 lua_pushboolean(L, list->roomForItem(item));
1992 lua_pushboolean(L, false);
1997 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1998 // Returns true if the list contains the given count of the given item name
1999 static int l_contains_item(lua_State *L)
2001 InvRef *ref = checkobject(L, 1);
2002 const char *listname = luaL_checkstring(L, 2);
2003 ItemStack item = read_item(L, 3);
2004 InventoryList *list = getlist(L, ref, listname);
2006 lua_pushboolean(L, list->containsItem(item));
2008 lua_pushboolean(L, false);
2013 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2014 // Returns the items that were actually removed
2015 static int l_remove_item(lua_State *L)
2017 InvRef *ref = checkobject(L, 1);
2018 const char *listname = luaL_checkstring(L, 2);
2019 ItemStack item = read_item(L, 3);
2020 InventoryList *list = getlist(L, ref, listname);
2022 ItemStack removed = list->removeItem(item);
2023 if(!removed.empty())
2024 reportInventoryChange(L, ref);
2025 LuaItemStack::create(L, removed);
2027 LuaItemStack::create(L, ItemStack());
2033 InvRef(const InventoryLocation &loc):
2042 // Creates an InvRef and leaves it on top of stack
2043 // Not callable from Lua; all references are created on the C side.
2044 static void create(lua_State *L, const InventoryLocation &loc)
2046 InvRef *o = new InvRef(loc);
2047 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2048 luaL_getmetatable(L, className);
2049 lua_setmetatable(L, -2);
2051 static void createPlayer(lua_State *L, Player *player)
2053 InventoryLocation loc;
2054 loc.setPlayer(player->getName());
2057 static void createNodeMeta(lua_State *L, v3s16 p)
2059 InventoryLocation loc;
2064 static void Register(lua_State *L)
2067 int methodtable = lua_gettop(L);
2068 luaL_newmetatable(L, className);
2069 int metatable = lua_gettop(L);
2071 lua_pushliteral(L, "__metatable");
2072 lua_pushvalue(L, methodtable);
2073 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2075 lua_pushliteral(L, "__index");
2076 lua_pushvalue(L, methodtable);
2077 lua_settable(L, metatable);
2079 lua_pushliteral(L, "__gc");
2080 lua_pushcfunction(L, gc_object);
2081 lua_settable(L, metatable);
2083 lua_pop(L, 1); // drop metatable
2085 luaL_openlib(L, 0, methods, 0); // fill methodtable
2086 lua_pop(L, 1); // drop methodtable
2088 // Cannot be created from Lua
2089 //lua_register(L, className, create_object);
2092 const char InvRef::className[] = "InvRef";
2093 const luaL_reg InvRef::methods[] = {
2094 method(InvRef, is_empty),
2095 method(InvRef, get_size),
2096 method(InvRef, set_size),
2097 method(InvRef, get_width),
2098 method(InvRef, set_width),
2099 method(InvRef, get_stack),
2100 method(InvRef, set_stack),
2101 method(InvRef, get_list),
2102 method(InvRef, set_list),
2103 method(InvRef, add_item),
2104 method(InvRef, room_for_item),
2105 method(InvRef, contains_item),
2106 method(InvRef, remove_item),
2118 ServerEnvironment *m_env;
2120 static const char className[];
2121 static const luaL_reg methods[];
2123 static NodeMetaRef *checkobject(lua_State *L, int narg)
2125 luaL_checktype(L, narg, LUA_TUSERDATA);
2126 void *ud = luaL_checkudata(L, narg, className);
2127 if(!ud) luaL_typerror(L, narg, className);
2128 return *(NodeMetaRef**)ud; // unbox pointer
2131 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2133 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2134 if(meta == NULL && auto_create)
2136 meta = new NodeMetadata(ref->m_env->getGameDef());
2137 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2142 static void reportMetadataChange(NodeMetaRef *ref)
2144 // NOTE: This same code is in rollback_interface.cpp
2145 // Inform other things that the metadata has changed
2146 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2148 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2150 ref->m_env->getMap().dispatchEvent(&event);
2151 // Set the block to be saved
2152 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2154 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2155 "NodeMetaRef::reportMetadataChange");
2158 // Exported functions
2160 // garbage collector
2161 static int gc_object(lua_State *L) {
2162 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2167 // get_string(self, name)
2168 static int l_get_string(lua_State *L)
2170 NodeMetaRef *ref = checkobject(L, 1);
2171 std::string name = luaL_checkstring(L, 2);
2173 NodeMetadata *meta = getmeta(ref, false);
2175 lua_pushlstring(L, "", 0);
2178 std::string str = meta->getString(name);
2179 lua_pushlstring(L, str.c_str(), str.size());
2183 // set_string(self, name, var)
2184 static int l_set_string(lua_State *L)
2186 NodeMetaRef *ref = checkobject(L, 1);
2187 std::string name = luaL_checkstring(L, 2);
2189 const char *s = lua_tolstring(L, 3, &len);
2190 std::string str(s, len);
2192 NodeMetadata *meta = getmeta(ref, !str.empty());
2193 if(meta == NULL || str == meta->getString(name))
2195 meta->setString(name, str);
2196 reportMetadataChange(ref);
2200 // get_int(self, name)
2201 static int l_get_int(lua_State *L)
2203 NodeMetaRef *ref = checkobject(L, 1);
2204 std::string name = lua_tostring(L, 2);
2206 NodeMetadata *meta = getmeta(ref, false);
2208 lua_pushnumber(L, 0);
2211 std::string str = meta->getString(name);
2212 lua_pushnumber(L, stoi(str));
2216 // set_int(self, name, var)
2217 static int l_set_int(lua_State *L)
2219 NodeMetaRef *ref = checkobject(L, 1);
2220 std::string name = lua_tostring(L, 2);
2221 int a = lua_tointeger(L, 3);
2222 std::string str = itos(a);
2224 NodeMetadata *meta = getmeta(ref, true);
2225 if(meta == NULL || str == meta->getString(name))
2227 meta->setString(name, str);
2228 reportMetadataChange(ref);
2232 // get_float(self, name)
2233 static int l_get_float(lua_State *L)
2235 NodeMetaRef *ref = checkobject(L, 1);
2236 std::string name = lua_tostring(L, 2);
2238 NodeMetadata *meta = getmeta(ref, false);
2240 lua_pushnumber(L, 0);
2243 std::string str = meta->getString(name);
2244 lua_pushnumber(L, stof(str));
2248 // set_float(self, name, var)
2249 static int l_set_float(lua_State *L)
2251 NodeMetaRef *ref = checkobject(L, 1);
2252 std::string name = lua_tostring(L, 2);
2253 float a = lua_tonumber(L, 3);
2254 std::string str = ftos(a);
2256 NodeMetadata *meta = getmeta(ref, true);
2257 if(meta == NULL || str == meta->getString(name))
2259 meta->setString(name, str);
2260 reportMetadataChange(ref);
2264 // get_inventory(self)
2265 static int l_get_inventory(lua_State *L)
2267 NodeMetaRef *ref = checkobject(L, 1);
2268 getmeta(ref, true); // try to ensure the metadata exists
2269 InvRef::createNodeMeta(L, ref->m_p);
2274 static int l_to_table(lua_State *L)
2276 NodeMetaRef *ref = checkobject(L, 1);
2278 NodeMetadata *meta = getmeta(ref, true);
2287 std::map<std::string, std::string> fields = meta->getStrings();
2288 for(std::map<std::string, std::string>::const_iterator
2289 i = fields.begin(); i != fields.end(); i++){
2290 const std::string &name = i->first;
2291 const std::string &value = i->second;
2292 lua_pushlstring(L, name.c_str(), name.size());
2293 lua_pushlstring(L, value.c_str(), value.size());
2294 lua_settable(L, -3);
2297 lua_setfield(L, -2, "fields");
2300 Inventory *inv = meta->getInventory();
2302 std::vector<const InventoryList*> lists = inv->getLists();
2303 for(std::vector<const InventoryList*>::const_iterator
2304 i = lists.begin(); i != lists.end(); i++){
2305 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2306 lua_setfield(L, -2, (*i)->getName().c_str());
2309 lua_setfield(L, -2, "inventory");
2313 // from_table(self, table)
2314 static int l_from_table(lua_State *L)
2316 NodeMetaRef *ref = checkobject(L, 1);
2319 if(lua_isnil(L, base)){
2321 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2322 lua_pushboolean(L, true);
2326 // Has metadata; clear old one first
2327 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2328 // Create new metadata
2329 NodeMetadata *meta = getmeta(ref, true);
2331 lua_getfield(L, base, "fields");
2332 int fieldstable = lua_gettop(L);
2334 while(lua_next(L, fieldstable) != 0){
2335 // key at index -2 and value at index -1
2336 std::string name = lua_tostring(L, -2);
2338 const char *cs = lua_tolstring(L, -1, &cl);
2339 std::string value(cs, cl);
2340 meta->setString(name, value);
2341 lua_pop(L, 1); // removes value, keeps key for next iteration
2344 Inventory *inv = meta->getInventory();
2345 lua_getfield(L, base, "inventory");
2346 int inventorytable = lua_gettop(L);
2348 while(lua_next(L, inventorytable) != 0){
2349 // key at index -2 and value at index -1
2350 std::string name = lua_tostring(L, -2);
2351 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2352 lua_pop(L, 1); // removes value, keeps key for next iteration
2354 reportMetadataChange(ref);
2355 lua_pushboolean(L, true);
2360 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2370 // Creates an NodeMetaRef and leaves it on top of stack
2371 // Not callable from Lua; all references are created on the C side.
2372 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2374 NodeMetaRef *o = new NodeMetaRef(p, env);
2375 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2376 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2377 luaL_getmetatable(L, className);
2378 lua_setmetatable(L, -2);
2381 static void Register(lua_State *L)
2384 int methodtable = lua_gettop(L);
2385 luaL_newmetatable(L, className);
2386 int metatable = lua_gettop(L);
2388 lua_pushliteral(L, "__metatable");
2389 lua_pushvalue(L, methodtable);
2390 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2392 lua_pushliteral(L, "__index");
2393 lua_pushvalue(L, methodtable);
2394 lua_settable(L, metatable);
2396 lua_pushliteral(L, "__gc");
2397 lua_pushcfunction(L, gc_object);
2398 lua_settable(L, metatable);
2400 lua_pop(L, 1); // drop metatable
2402 luaL_openlib(L, 0, methods, 0); // fill methodtable
2403 lua_pop(L, 1); // drop methodtable
2405 // Cannot be created from Lua
2406 //lua_register(L, className, create_object);
2409 const char NodeMetaRef::className[] = "NodeMetaRef";
2410 const luaL_reg NodeMetaRef::methods[] = {
2411 method(NodeMetaRef, get_string),
2412 method(NodeMetaRef, set_string),
2413 method(NodeMetaRef, get_int),
2414 method(NodeMetaRef, set_int),
2415 method(NodeMetaRef, get_float),
2416 method(NodeMetaRef, set_float),
2417 method(NodeMetaRef, get_inventory),
2418 method(NodeMetaRef, to_table),
2419 method(NodeMetaRef, from_table),
2430 ServerActiveObject *m_object;
2432 static const char className[];
2433 static const luaL_reg methods[];
2435 static ObjectRef *checkobject(lua_State *L, int narg)
2437 luaL_checktype(L, narg, LUA_TUSERDATA);
2438 void *ud = luaL_checkudata(L, narg, className);
2439 if(!ud) luaL_typerror(L, narg, className);
2440 return *(ObjectRef**)ud; // unbox pointer
2443 static ServerActiveObject* getobject(ObjectRef *ref)
2445 ServerActiveObject *co = ref->m_object;
2449 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2451 ServerActiveObject *obj = getobject(ref);
2454 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2456 return (LuaEntitySAO*)obj;
2459 static PlayerSAO* getplayersao(ObjectRef *ref)
2461 ServerActiveObject *obj = getobject(ref);
2464 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2466 return (PlayerSAO*)obj;
2469 static Player* getplayer(ObjectRef *ref)
2471 PlayerSAO *playersao = getplayersao(ref);
2472 if(playersao == NULL)
2474 return playersao->getPlayer();
2477 // Exported functions
2479 // garbage collector
2480 static int gc_object(lua_State *L) {
2481 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2482 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2488 static int l_remove(lua_State *L)
2490 ObjectRef *ref = checkobject(L, 1);
2491 ServerActiveObject *co = getobject(ref);
2492 if(co == NULL) return 0;
2493 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2494 co->m_removed = true;
2499 // returns: {x=num, y=num, z=num}
2500 static int l_getpos(lua_State *L)
2502 ObjectRef *ref = checkobject(L, 1);
2503 ServerActiveObject *co = getobject(ref);
2504 if(co == NULL) return 0;
2505 v3f pos = co->getBasePosition() / BS;
2507 lua_pushnumber(L, pos.X);
2508 lua_setfield(L, -2, "x");
2509 lua_pushnumber(L, pos.Y);
2510 lua_setfield(L, -2, "y");
2511 lua_pushnumber(L, pos.Z);
2512 lua_setfield(L, -2, "z");
2516 // setpos(self, pos)
2517 static int l_setpos(lua_State *L)
2519 ObjectRef *ref = checkobject(L, 1);
2520 //LuaEntitySAO *co = getluaobject(ref);
2521 ServerActiveObject *co = getobject(ref);
2522 if(co == NULL) return 0;
2524 v3f pos = checkFloatPos(L, 2);
2530 // moveto(self, pos, continuous=false)
2531 static int l_moveto(lua_State *L)
2533 ObjectRef *ref = checkobject(L, 1);
2534 //LuaEntitySAO *co = getluaobject(ref);
2535 ServerActiveObject *co = getobject(ref);
2536 if(co == NULL) return 0;
2538 v3f pos = checkFloatPos(L, 2);
2540 bool continuous = lua_toboolean(L, 3);
2542 co->moveTo(pos, continuous);
2546 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2547 static int l_punch(lua_State *L)
2549 ObjectRef *ref = checkobject(L, 1);
2550 ObjectRef *puncher_ref = checkobject(L, 2);
2551 ServerActiveObject *co = getobject(ref);
2552 ServerActiveObject *puncher = getobject(puncher_ref);
2553 if(co == NULL) return 0;
2554 if(puncher == NULL) return 0;
2555 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2556 v3f dir = read_v3f(L, 4);
2557 float time_from_last_punch = 1000000;
2558 if(lua_isnumber(L, 5))
2559 time_from_last_punch = lua_tonumber(L, 5);
2561 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2565 // right_click(self, clicker); clicker = an another ObjectRef
2566 static int l_right_click(lua_State *L)
2568 ObjectRef *ref = checkobject(L, 1);
2569 ObjectRef *ref2 = checkobject(L, 2);
2570 ServerActiveObject *co = getobject(ref);
2571 ServerActiveObject *co2 = getobject(ref2);
2572 if(co == NULL) return 0;
2573 if(co2 == NULL) return 0;
2575 co->rightClick(co2);
2580 // hp = number of hitpoints (2 * number of hearts)
2582 static int l_set_hp(lua_State *L)
2584 ObjectRef *ref = checkobject(L, 1);
2585 luaL_checknumber(L, 2);
2586 ServerActiveObject *co = getobject(ref);
2587 if(co == NULL) return 0;
2588 int hp = lua_tonumber(L, 2);
2589 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2590 <<" hp="<<hp<<std::endl;*/
2598 // returns: number of hitpoints (2 * number of hearts)
2599 // 0 if not applicable to this type of object
2600 static int l_get_hp(lua_State *L)
2602 ObjectRef *ref = checkobject(L, 1);
2603 ServerActiveObject *co = getobject(ref);
2606 lua_pushnumber(L, 1);
2609 int hp = co->getHP();
2610 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2611 <<" hp="<<hp<<std::endl;*/
2613 lua_pushnumber(L, hp);
2617 // get_inventory(self)
2618 static int l_get_inventory(lua_State *L)
2620 ObjectRef *ref = checkobject(L, 1);
2621 ServerActiveObject *co = getobject(ref);
2622 if(co == NULL) return 0;
2624 InventoryLocation loc = co->getInventoryLocation();
2625 if(get_server(L)->getInventory(loc) != NULL)
2626 InvRef::create(L, loc);
2628 lua_pushnil(L); // An object may have no inventory (nil)
2632 // get_wield_list(self)
2633 static int l_get_wield_list(lua_State *L)
2635 ObjectRef *ref = checkobject(L, 1);
2636 ServerActiveObject *co = getobject(ref);
2637 if(co == NULL) return 0;
2639 lua_pushstring(L, co->getWieldList().c_str());
2643 // get_wield_index(self)
2644 static int l_get_wield_index(lua_State *L)
2646 ObjectRef *ref = checkobject(L, 1);
2647 ServerActiveObject *co = getobject(ref);
2648 if(co == NULL) return 0;
2650 lua_pushinteger(L, co->getWieldIndex() + 1);
2654 // get_wielded_item(self)
2655 static int l_get_wielded_item(lua_State *L)
2657 ObjectRef *ref = checkobject(L, 1);
2658 ServerActiveObject *co = getobject(ref);
2661 LuaItemStack::create(L, ItemStack());
2665 LuaItemStack::create(L, co->getWieldedItem());
2669 // set_wielded_item(self, itemstack or itemstring or table or nil)
2670 static int l_set_wielded_item(lua_State *L)
2672 ObjectRef *ref = checkobject(L, 1);
2673 ServerActiveObject *co = getobject(ref);
2674 if(co == NULL) return 0;
2676 ItemStack item = read_item(L, 2);
2677 bool success = co->setWieldedItem(item);
2678 lua_pushboolean(L, success);
2682 // set_armor_groups(self, groups)
2683 static int l_set_armor_groups(lua_State *L)
2685 ObjectRef *ref = checkobject(L, 1);
2686 ServerActiveObject *co = getobject(ref);
2687 if(co == NULL) return 0;
2689 ItemGroupList groups;
2690 read_groups(L, 2, groups);
2691 co->setArmorGroups(groups);
2695 // set_properties(self, properties)
2696 static int l_set_properties(lua_State *L)
2698 ObjectRef *ref = checkobject(L, 1);
2699 ServerActiveObject *co = getobject(ref);
2700 if(co == NULL) return 0;
2701 ObjectProperties *prop = co->accessObjectProperties();
2704 read_object_properties(L, 2, prop);
2705 co->notifyObjectPropertiesModified();
2709 /* LuaEntitySAO-only */
2711 // setvelocity(self, {x=num, y=num, z=num})
2712 static int l_setvelocity(lua_State *L)
2714 ObjectRef *ref = checkobject(L, 1);
2715 LuaEntitySAO *co = getluaobject(ref);
2716 if(co == NULL) return 0;
2717 v3f pos = checkFloatPos(L, 2);
2719 co->setVelocity(pos);
2723 // getvelocity(self)
2724 static int l_getvelocity(lua_State *L)
2726 ObjectRef *ref = checkobject(L, 1);
2727 LuaEntitySAO *co = getluaobject(ref);
2728 if(co == NULL) return 0;
2730 v3f v = co->getVelocity();
2735 // setacceleration(self, {x=num, y=num, z=num})
2736 static int l_setacceleration(lua_State *L)
2738 ObjectRef *ref = checkobject(L, 1);
2739 LuaEntitySAO *co = getluaobject(ref);
2740 if(co == NULL) return 0;
2742 v3f pos = checkFloatPos(L, 2);
2744 co->setAcceleration(pos);
2748 // getacceleration(self)
2749 static int l_getacceleration(lua_State *L)
2751 ObjectRef *ref = checkobject(L, 1);
2752 LuaEntitySAO *co = getluaobject(ref);
2753 if(co == NULL) return 0;
2755 v3f v = co->getAcceleration();
2760 // setyaw(self, radians)
2761 static int l_setyaw(lua_State *L)
2763 ObjectRef *ref = checkobject(L, 1);
2764 LuaEntitySAO *co = getluaobject(ref);
2765 if(co == NULL) return 0;
2766 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2773 static int l_getyaw(lua_State *L)
2775 ObjectRef *ref = checkobject(L, 1);
2776 LuaEntitySAO *co = getluaobject(ref);
2777 if(co == NULL) return 0;
2779 float yaw = co->getYaw() * core::DEGTORAD;
2780 lua_pushnumber(L, yaw);
2784 // settexturemod(self, mod)
2785 static int l_settexturemod(lua_State *L)
2787 ObjectRef *ref = checkobject(L, 1);
2788 LuaEntitySAO *co = getluaobject(ref);
2789 if(co == NULL) return 0;
2791 std::string mod = luaL_checkstring(L, 2);
2792 co->setTextureMod(mod);
2796 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2797 // select_horiz_by_yawpitch=false)
2798 static int l_setsprite(lua_State *L)
2800 ObjectRef *ref = checkobject(L, 1);
2801 LuaEntitySAO *co = getluaobject(ref);
2802 if(co == NULL) return 0;
2805 if(!lua_isnil(L, 2))
2806 p = read_v2s16(L, 2);
2808 if(!lua_isnil(L, 3))
2809 num_frames = lua_tonumber(L, 3);
2810 float framelength = 0.2;
2811 if(!lua_isnil(L, 4))
2812 framelength = lua_tonumber(L, 4);
2813 bool select_horiz_by_yawpitch = false;
2814 if(!lua_isnil(L, 5))
2815 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2816 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2821 // get_entity_name(self)
2822 static int l_get_entity_name(lua_State *L)
2824 ObjectRef *ref = checkobject(L, 1);
2825 LuaEntitySAO *co = getluaobject(ref);
2826 if(co == NULL) return 0;
2828 std::string name = co->getName();
2829 lua_pushstring(L, name.c_str());
2833 // get_luaentity(self)
2834 static int l_get_luaentity(lua_State *L)
2836 ObjectRef *ref = checkobject(L, 1);
2837 LuaEntitySAO *co = getluaobject(ref);
2838 if(co == NULL) return 0;
2840 luaentity_get(L, co->getId());
2847 static int l_is_player(lua_State *L)
2849 ObjectRef *ref = checkobject(L, 1);
2850 Player *player = getplayer(ref);
2851 lua_pushboolean(L, (player != NULL));
2855 // get_player_name(self)
2856 static int l_get_player_name(lua_State *L)
2858 ObjectRef *ref = checkobject(L, 1);
2859 Player *player = getplayer(ref);
2861 lua_pushlstring(L, "", 0);
2865 lua_pushstring(L, player->getName());
2869 // get_look_dir(self)
2870 static int l_get_look_dir(lua_State *L)
2872 ObjectRef *ref = checkobject(L, 1);
2873 Player *player = getplayer(ref);
2874 if(player == NULL) return 0;
2876 float pitch = player->getRadPitch();
2877 float yaw = player->getRadYaw();
2878 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2883 // get_look_pitch(self)
2884 static int l_get_look_pitch(lua_State *L)
2886 ObjectRef *ref = checkobject(L, 1);
2887 Player *player = getplayer(ref);
2888 if(player == NULL) return 0;
2890 lua_pushnumber(L, player->getRadPitch());
2894 // get_look_yaw(self)
2895 static int l_get_look_yaw(lua_State *L)
2897 ObjectRef *ref = checkobject(L, 1);
2898 Player *player = getplayer(ref);
2899 if(player == NULL) return 0;
2901 lua_pushnumber(L, player->getRadYaw());
2905 // set_inventory_formspec(self, formspec)
2906 static int l_set_inventory_formspec(lua_State *L)
2908 ObjectRef *ref = checkobject(L, 1);
2909 Player *player = getplayer(ref);
2910 if(player == NULL) return 0;
2911 std::string formspec = luaL_checkstring(L, 2);
2913 player->inventory_formspec = formspec;
2914 get_server(L)->reportInventoryFormspecModified(player->getName());
2915 lua_pushboolean(L, true);
2919 // get_inventory_formspec(self) -> formspec
2920 static int l_get_inventory_formspec(lua_State *L)
2922 ObjectRef *ref = checkobject(L, 1);
2923 Player *player = getplayer(ref);
2924 if(player == NULL) return 0;
2926 std::string formspec = player->inventory_formspec;
2927 lua_pushlstring(L, formspec.c_str(), formspec.size());
2932 ObjectRef(ServerActiveObject *object):
2935 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2941 infostream<<"ObjectRef destructing for id="
2942 <<m_object->getId()<<std::endl;
2944 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2947 // Creates an ObjectRef and leaves it on top of stack
2948 // Not callable from Lua; all references are created on the C side.
2949 static void create(lua_State *L, ServerActiveObject *object)
2951 ObjectRef *o = new ObjectRef(object);
2952 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2953 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2954 luaL_getmetatable(L, className);
2955 lua_setmetatable(L, -2);
2958 static void set_null(lua_State *L)
2960 ObjectRef *o = checkobject(L, -1);
2964 static void Register(lua_State *L)
2967 int methodtable = lua_gettop(L);
2968 luaL_newmetatable(L, className);
2969 int metatable = lua_gettop(L);
2971 lua_pushliteral(L, "__metatable");
2972 lua_pushvalue(L, methodtable);
2973 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2975 lua_pushliteral(L, "__index");
2976 lua_pushvalue(L, methodtable);
2977 lua_settable(L, metatable);
2979 lua_pushliteral(L, "__gc");
2980 lua_pushcfunction(L, gc_object);
2981 lua_settable(L, metatable);
2983 lua_pop(L, 1); // drop metatable
2985 luaL_openlib(L, 0, methods, 0); // fill methodtable
2986 lua_pop(L, 1); // drop methodtable
2988 // Cannot be created from Lua
2989 //lua_register(L, className, create_object);
2992 const char ObjectRef::className[] = "ObjectRef";
2993 const luaL_reg ObjectRef::methods[] = {
2994 // ServerActiveObject
2995 method(ObjectRef, remove),
2996 method(ObjectRef, getpos),
2997 method(ObjectRef, setpos),
2998 method(ObjectRef, moveto),
2999 method(ObjectRef, punch),
3000 method(ObjectRef, right_click),
3001 method(ObjectRef, set_hp),
3002 method(ObjectRef, get_hp),
3003 method(ObjectRef, get_inventory),
3004 method(ObjectRef, get_wield_list),
3005 method(ObjectRef, get_wield_index),
3006 method(ObjectRef, get_wielded_item),
3007 method(ObjectRef, set_wielded_item),
3008 method(ObjectRef, set_armor_groups),
3009 method(ObjectRef, set_properties),
3010 // LuaEntitySAO-only
3011 method(ObjectRef, setvelocity),
3012 method(ObjectRef, getvelocity),
3013 method(ObjectRef, setacceleration),
3014 method(ObjectRef, getacceleration),
3015 method(ObjectRef, setyaw),
3016 method(ObjectRef, getyaw),
3017 method(ObjectRef, settexturemod),
3018 method(ObjectRef, setsprite),
3019 method(ObjectRef, get_entity_name),
3020 method(ObjectRef, get_luaentity),
3022 method(ObjectRef, is_player),
3023 method(ObjectRef, get_player_name),
3024 method(ObjectRef, get_look_dir),
3025 method(ObjectRef, get_look_pitch),
3026 method(ObjectRef, get_look_yaw),
3027 method(ObjectRef, set_inventory_formspec),
3028 method(ObjectRef, get_inventory_formspec),
3032 // Creates a new anonymous reference if cobj=NULL or id=0
3033 static void objectref_get_or_create(lua_State *L,
3034 ServerActiveObject *cobj)
3036 if(cobj == NULL || cobj->getId() == 0){
3037 ObjectRef::create(L, cobj);
3039 objectref_get(L, cobj->getId());
3048 class LuaPerlinNoise
3055 static const char className[];
3056 static const luaL_reg methods[];
3058 // Exported functions
3060 // garbage collector
3061 static int gc_object(lua_State *L)
3063 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3068 static int l_get2d(lua_State *L)
3070 LuaPerlinNoise *o = checkobject(L, 1);
3071 v2f pos2d = read_v2f(L,2);
3072 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3073 lua_pushnumber(L, val);
3076 static int l_get3d(lua_State *L)
3078 LuaPerlinNoise *o = checkobject(L, 1);
3079 v3f pos3d = read_v3f(L,2);
3080 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3081 lua_pushnumber(L, val);
3086 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3090 persistence(a_persistence),
3099 // LuaPerlinNoise(seed, octaves, persistence, scale)
3100 // Creates an LuaPerlinNoise and leaves it on top of stack
3101 static int create_object(lua_State *L)
3103 int seed = luaL_checkint(L, 1);
3104 int octaves = luaL_checkint(L, 2);
3105 double persistence = luaL_checknumber(L, 3);
3106 double scale = luaL_checknumber(L, 4);
3107 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3108 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3109 luaL_getmetatable(L, className);
3110 lua_setmetatable(L, -2);
3114 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3116 luaL_checktype(L, narg, LUA_TUSERDATA);
3117 void *ud = luaL_checkudata(L, narg, className);
3118 if(!ud) luaL_typerror(L, narg, className);
3119 return *(LuaPerlinNoise**)ud; // unbox pointer
3122 static void Register(lua_State *L)
3125 int methodtable = lua_gettop(L);
3126 luaL_newmetatable(L, className);
3127 int metatable = lua_gettop(L);
3129 lua_pushliteral(L, "__metatable");
3130 lua_pushvalue(L, methodtable);
3131 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3133 lua_pushliteral(L, "__index");
3134 lua_pushvalue(L, methodtable);
3135 lua_settable(L, metatable);
3137 lua_pushliteral(L, "__gc");
3138 lua_pushcfunction(L, gc_object);
3139 lua_settable(L, metatable);
3141 lua_pop(L, 1); // drop metatable
3143 luaL_openlib(L, 0, methods, 0); // fill methodtable
3144 lua_pop(L, 1); // drop methodtable
3146 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3147 lua_register(L, className, create_object);
3150 const char LuaPerlinNoise::className[] = "PerlinNoise";
3151 const luaL_reg LuaPerlinNoise::methods[] = {
3152 method(LuaPerlinNoise, get2d),
3153 method(LuaPerlinNoise, get3d),
3165 ServerEnvironment *m_env;
3167 static const char className[];
3168 static const luaL_reg methods[];
3170 static int gc_object(lua_State *L) {
3171 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3176 static NodeTimerRef *checkobject(lua_State *L, int narg)
3178 luaL_checktype(L, narg, LUA_TUSERDATA);
3179 void *ud = luaL_checkudata(L, narg, className);
3180 if(!ud) luaL_typerror(L, narg, className);
3181 return *(NodeTimerRef**)ud; // unbox pointer
3184 static int l_set(lua_State *L)
3186 NodeTimerRef *o = checkobject(L, 1);
3187 ServerEnvironment *env = o->m_env;
3188 if(env == NULL) return 0;
3189 f32 t = luaL_checknumber(L,2);
3190 f32 e = luaL_checknumber(L,3);
3191 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3195 static int l_start(lua_State *L)
3197 NodeTimerRef *o = checkobject(L, 1);
3198 ServerEnvironment *env = o->m_env;
3199 if(env == NULL) return 0;
3200 f32 t = luaL_checknumber(L,2);
3201 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3205 static int l_stop(lua_State *L)
3207 NodeTimerRef *o = checkobject(L, 1);
3208 ServerEnvironment *env = o->m_env;
3209 if(env == NULL) return 0;
3210 env->getMap().removeNodeTimer(o->m_p);
3214 static int l_is_started(lua_State *L)
3216 NodeTimerRef *o = checkobject(L, 1);
3217 ServerEnvironment *env = o->m_env;
3218 if(env == NULL) return 0;
3220 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3221 lua_pushboolean(L,(t.timeout != 0));
3225 static int l_get_timeout(lua_State *L)
3227 NodeTimerRef *o = checkobject(L, 1);
3228 ServerEnvironment *env = o->m_env;
3229 if(env == NULL) return 0;
3231 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3232 lua_pushnumber(L,t.timeout);
3236 static int l_get_elapsed(lua_State *L)
3238 NodeTimerRef *o = checkobject(L, 1);
3239 ServerEnvironment *env = o->m_env;
3240 if(env == NULL) return 0;
3242 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3243 lua_pushnumber(L,t.elapsed);
3248 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3258 // Creates an NodeTimerRef and leaves it on top of stack
3259 // Not callable from Lua; all references are created on the C side.
3260 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3262 NodeTimerRef *o = new NodeTimerRef(p, env);
3263 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3264 luaL_getmetatable(L, className);
3265 lua_setmetatable(L, -2);
3268 static void set_null(lua_State *L)
3270 NodeTimerRef *o = checkobject(L, -1);
3274 static void Register(lua_State *L)
3277 int methodtable = lua_gettop(L);
3278 luaL_newmetatable(L, className);
3279 int metatable = lua_gettop(L);
3281 lua_pushliteral(L, "__metatable");
3282 lua_pushvalue(L, methodtable);
3283 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3285 lua_pushliteral(L, "__index");
3286 lua_pushvalue(L, methodtable);
3287 lua_settable(L, metatable);
3289 lua_pushliteral(L, "__gc");
3290 lua_pushcfunction(L, gc_object);
3291 lua_settable(L, metatable);
3293 lua_pop(L, 1); // drop metatable
3295 luaL_openlib(L, 0, methods, 0); // fill methodtable
3296 lua_pop(L, 1); // drop methodtable
3298 // Cannot be created from Lua
3299 //lua_register(L, className, create_object);
3302 const char NodeTimerRef::className[] = "NodeTimerRef";
3303 const luaL_reg NodeTimerRef::methods[] = {
3304 method(NodeTimerRef, start),
3305 method(NodeTimerRef, set),
3306 method(NodeTimerRef, stop),
3307 method(NodeTimerRef, is_started),
3308 method(NodeTimerRef, get_timeout),
3309 method(NodeTimerRef, get_elapsed),
3320 ServerEnvironment *m_env;
3322 static const char className[];
3323 static const luaL_reg methods[];
3325 static int gc_object(lua_State *L) {
3326 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3331 static EnvRef *checkobject(lua_State *L, int narg)
3333 luaL_checktype(L, narg, LUA_TUSERDATA);
3334 void *ud = luaL_checkudata(L, narg, className);
3335 if(!ud) luaL_typerror(L, narg, className);
3336 return *(EnvRef**)ud; // unbox pointer
3339 // Exported functions
3341 // EnvRef:set_node(pos, node)
3342 // pos = {x=num, y=num, z=num}
3343 static int l_set_node(lua_State *L)
3345 EnvRef *o = checkobject(L, 1);
3346 ServerEnvironment *env = o->m_env;
3347 if(env == NULL) return 0;
3348 INodeDefManager *ndef = env->getGameDef()->ndef();
3350 v3s16 pos = read_v3s16(L, 2);
3351 MapNode n = readnode(L, 3, ndef);
3353 MapNode n_old = env->getMap().getNodeNoEx(pos);
3355 if(ndef->get(n_old).has_on_destruct)
3356 scriptapi_node_on_destruct(L, pos, n_old);
3358 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3360 // Call post-destructor
3361 if(ndef->get(n_old).has_after_destruct)
3362 scriptapi_node_after_destruct(L, pos, n_old);
3364 if(ndef->get(n).has_on_construct)
3365 scriptapi_node_on_construct(L, pos, n);
3367 lua_pushboolean(L, succeeded);
3371 static int l_add_node(lua_State *L)
3373 return l_set_node(L);
3376 // EnvRef:remove_node(pos)
3377 // pos = {x=num, y=num, z=num}
3378 static int l_remove_node(lua_State *L)
3380 EnvRef *o = checkobject(L, 1);
3381 ServerEnvironment *env = o->m_env;
3382 if(env == NULL) return 0;
3383 INodeDefManager *ndef = env->getGameDef()->ndef();
3385 v3s16 pos = read_v3s16(L, 2);
3387 MapNode n_old = env->getMap().getNodeNoEx(pos);
3389 if(ndef->get(n_old).has_on_destruct)
3390 scriptapi_node_on_destruct(L, pos, n_old);
3392 // This is slightly optimized compared to addNodeWithEvent(air)
3393 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3395 // Call post-destructor
3396 if(ndef->get(n_old).has_after_destruct)
3397 scriptapi_node_after_destruct(L, pos, n_old);
3399 lua_pushboolean(L, succeeded);
3400 // Air doesn't require constructor
3404 // EnvRef:get_node(pos)
3405 // pos = {x=num, y=num, z=num}
3406 static int l_get_node(lua_State *L)
3408 EnvRef *o = checkobject(L, 1);
3409 ServerEnvironment *env = o->m_env;
3410 if(env == NULL) return 0;
3412 v3s16 pos = read_v3s16(L, 2);
3414 MapNode n = env->getMap().getNodeNoEx(pos);
3416 pushnode(L, n, env->getGameDef()->ndef());
3420 // EnvRef:get_node_or_nil(pos)
3421 // pos = {x=num, y=num, z=num}
3422 static int l_get_node_or_nil(lua_State *L)
3424 EnvRef *o = checkobject(L, 1);
3425 ServerEnvironment *env = o->m_env;
3426 if(env == NULL) return 0;
3428 v3s16 pos = read_v3s16(L, 2);
3431 MapNode n = env->getMap().getNode(pos);
3433 pushnode(L, n, env->getGameDef()->ndef());
3435 } catch(InvalidPositionException &e)
3442 // EnvRef:get_node_light(pos, timeofday)
3443 // pos = {x=num, y=num, z=num}
3444 // timeofday: nil = current time, 0 = night, 0.5 = day
3445 static int l_get_node_light(lua_State *L)
3447 EnvRef *o = checkobject(L, 1);
3448 ServerEnvironment *env = o->m_env;
3449 if(env == NULL) return 0;
3451 v3s16 pos = read_v3s16(L, 2);
3452 u32 time_of_day = env->getTimeOfDay();
3453 if(lua_isnumber(L, 3))
3454 time_of_day = 24000.0 * lua_tonumber(L, 3);
3455 time_of_day %= 24000;
3456 u32 dnr = time_to_daynight_ratio(time_of_day);
3457 MapNode n = env->getMap().getNodeNoEx(pos);
3459 MapNode n = env->getMap().getNode(pos);
3460 INodeDefManager *ndef = env->getGameDef()->ndef();
3461 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3463 } catch(InvalidPositionException &e)
3470 // EnvRef:place_node(pos, node)
3471 // pos = {x=num, y=num, z=num}
3472 static int l_place_node(lua_State *L)
3474 EnvRef *o = checkobject(L, 1);
3475 ServerEnvironment *env = o->m_env;
3476 if(env == NULL) return 0;
3477 v3s16 pos = read_v3s16(L, 2);
3478 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3480 // Don't attempt to load non-loaded area as of now
3481 MapNode n_old = env->getMap().getNodeNoEx(pos);
3482 if(n_old.getContent() == CONTENT_IGNORE){
3483 lua_pushboolean(L, false);
3486 // Create item to place
3487 INodeDefManager *ndef = get_server(L)->ndef();
3488 IItemDefManager *idef = get_server(L)->idef();
3489 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3490 // Make pointed position
3491 PointedThing pointed;
3492 pointed.type = POINTEDTHING_NODE;
3493 pointed.node_abovesurface = pos;
3494 pointed.node_undersurface = pos + v3s16(0,-1,0);
3495 // Place it with a NULL placer (appears in Lua as a non-functional
3497 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3498 lua_pushboolean(L, success);
3502 // EnvRef:dig_node(pos)
3503 // pos = {x=num, y=num, z=num}
3504 static int l_dig_node(lua_State *L)
3506 EnvRef *o = checkobject(L, 1);
3507 ServerEnvironment *env = o->m_env;
3508 if(env == NULL) return 0;
3509 v3s16 pos = read_v3s16(L, 2);
3511 // Don't attempt to load non-loaded area as of now
3512 MapNode n = env->getMap().getNodeNoEx(pos);
3513 if(n.getContent() == CONTENT_IGNORE){
3514 lua_pushboolean(L, false);
3517 // Dig it out with a NULL digger (appears in Lua as a
3518 // non-functional ObjectRef)
3519 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3520 lua_pushboolean(L, success);
3524 // EnvRef:punch_node(pos)
3525 // pos = {x=num, y=num, z=num}
3526 static int l_punch_node(lua_State *L)
3528 EnvRef *o = checkobject(L, 1);
3529 ServerEnvironment *env = o->m_env;
3530 if(env == NULL) return 0;
3531 v3s16 pos = read_v3s16(L, 2);
3533 // Don't attempt to load non-loaded area as of now
3534 MapNode n = env->getMap().getNodeNoEx(pos);
3535 if(n.getContent() == CONTENT_IGNORE){
3536 lua_pushboolean(L, false);
3539 // Punch it with a NULL puncher (appears in Lua as a non-functional
3541 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3542 lua_pushboolean(L, success);
3546 // EnvRef:get_meta(pos)
3547 static int l_get_meta(lua_State *L)
3549 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3550 EnvRef *o = checkobject(L, 1);
3551 ServerEnvironment *env = o->m_env;
3552 if(env == NULL) return 0;
3554 v3s16 p = read_v3s16(L, 2);
3555 NodeMetaRef::create(L, p, env);
3559 // EnvRef:get_node_timer(pos)
3560 static int l_get_node_timer(lua_State *L)
3562 EnvRef *o = checkobject(L, 1);
3563 ServerEnvironment *env = o->m_env;
3564 if(env == NULL) return 0;
3566 v3s16 p = read_v3s16(L, 2);
3567 NodeTimerRef::create(L, p, env);
3571 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3572 // pos = {x=num, y=num, z=num}
3573 static int l_add_entity(lua_State *L)
3575 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3576 EnvRef *o = checkobject(L, 1);
3577 ServerEnvironment *env = o->m_env;
3578 if(env == NULL) return 0;
3580 v3f pos = checkFloatPos(L, 2);
3582 const char *name = luaL_checkstring(L, 3);
3584 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3585 int objectid = env->addActiveObject(obj);
3586 // If failed to add, return nothing (reads as nil)
3590 objectref_get_or_create(L, obj);
3594 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3595 // pos = {x=num, y=num, z=num}
3596 static int l_add_item(lua_State *L)
3598 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3599 EnvRef *o = checkobject(L, 1);
3600 ServerEnvironment *env = o->m_env;
3601 if(env == NULL) return 0;
3603 v3f pos = checkFloatPos(L, 2);
3605 ItemStack item = read_item(L, 3);
3606 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3608 // Use minetest.spawn_item to spawn a __builtin:item
3609 lua_getglobal(L, "minetest");
3610 lua_getfield(L, -1, "spawn_item");
3611 if(lua_isnil(L, -1))
3613 lua_pushvalue(L, 2);
3614 lua_pushstring(L, item.getItemString().c_str());
3615 if(lua_pcall(L, 2, 1, 0))
3616 script_error(L, "error: %s", lua_tostring(L, -1));
3618 /*lua_pushvalue(L, 1);
3619 lua_pushstring(L, "__builtin:item");
3620 lua_pushstring(L, item.getItemString().c_str());
3621 return l_add_entity(L);*/
3623 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3624 int objectid = env->addActiveObject(obj);
3625 // If failed to add, return nothing (reads as nil)
3629 objectref_get_or_create(L, obj);
3633 // EnvRef:add_rat(pos)
3634 // pos = {x=num, y=num, z=num}
3635 static int l_add_rat(lua_State *L)
3637 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3638 <<" Doing nothing."<<std::endl;
3642 // EnvRef:add_firefly(pos)
3643 // pos = {x=num, y=num, z=num}
3644 static int l_add_firefly(lua_State *L)
3646 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3647 <<" Doing nothing."<<std::endl;
3651 // EnvRef:get_player_by_name(name)
3652 static int l_get_player_by_name(lua_State *L)
3654 EnvRef *o = checkobject(L, 1);
3655 ServerEnvironment *env = o->m_env;
3656 if(env == NULL) return 0;
3658 const char *name = luaL_checkstring(L, 2);
3659 Player *player = env->getPlayer(name);
3664 PlayerSAO *sao = player->getPlayerSAO();
3669 // Put player on stack
3670 objectref_get_or_create(L, sao);
3674 // EnvRef:get_objects_inside_radius(pos, radius)
3675 static int l_get_objects_inside_radius(lua_State *L)
3677 // Get the table insert function
3678 lua_getglobal(L, "table");
3679 lua_getfield(L, -1, "insert");
3680 int table_insert = lua_gettop(L);
3682 EnvRef *o = checkobject(L, 1);
3683 ServerEnvironment *env = o->m_env;
3684 if(env == NULL) return 0;
3686 v3f pos = checkFloatPos(L, 2);
3687 float radius = luaL_checknumber(L, 3) * BS;
3688 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3690 int table = lua_gettop(L);
3691 for(std::set<u16>::const_iterator
3692 i = ids.begin(); i != ids.end(); i++){
3693 ServerActiveObject *obj = env->getActiveObject(*i);
3694 // Insert object reference into table
3695 lua_pushvalue(L, table_insert);
3696 lua_pushvalue(L, table);
3697 objectref_get_or_create(L, obj);
3698 if(lua_pcall(L, 2, 0, 0))
3699 script_error(L, "error: %s", lua_tostring(L, -1));
3704 // EnvRef:set_timeofday(val)
3706 static int l_set_timeofday(lua_State *L)
3708 EnvRef *o = checkobject(L, 1);
3709 ServerEnvironment *env = o->m_env;
3710 if(env == NULL) return 0;
3712 float timeofday_f = luaL_checknumber(L, 2);
3713 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3714 int timeofday_mh = (int)(timeofday_f * 24000.0);
3715 // This should be set directly in the environment but currently
3716 // such changes aren't immediately sent to the clients, so call
3717 // the server instead.
3718 //env->setTimeOfDay(timeofday_mh);
3719 get_server(L)->setTimeOfDay(timeofday_mh);
3723 // EnvRef:get_timeofday() -> 0...1
3724 static int l_get_timeofday(lua_State *L)
3726 EnvRef *o = checkobject(L, 1);
3727 ServerEnvironment *env = o->m_env;
3728 if(env == NULL) return 0;
3730 int timeofday_mh = env->getTimeOfDay();
3731 float timeofday_f = (float)timeofday_mh / 24000.0;
3732 lua_pushnumber(L, timeofday_f);
3737 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3738 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3739 static int l_find_node_near(lua_State *L)
3741 EnvRef *o = checkobject(L, 1);
3742 ServerEnvironment *env = o->m_env;
3743 if(env == NULL) return 0;
3744 INodeDefManager *ndef = get_server(L)->ndef();
3745 v3s16 pos = read_v3s16(L, 2);
3746 int radius = luaL_checkinteger(L, 3);
3747 std::set<content_t> filter;
3748 if(lua_istable(L, 4)){
3751 while(lua_next(L, table) != 0){
3752 // key at index -2 and value at index -1
3753 luaL_checktype(L, -1, LUA_TSTRING);
3754 ndef->getIds(lua_tostring(L, -1), filter);
3755 // removes value, keeps key for next iteration
3758 } else if(lua_isstring(L, 4)){
3759 ndef->getIds(lua_tostring(L, 4), filter);
3762 for(int d=1; d<=radius; d++){
3763 core::list<v3s16> list;
3764 getFacePositions(list, d);
3765 for(core::list<v3s16>::Iterator i = list.begin();
3766 i != list.end(); i++){
3767 v3s16 p = pos + (*i);
3768 content_t c = env->getMap().getNodeNoEx(p).getContent();
3769 if(filter.count(c) != 0){
3778 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3779 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3780 static int l_find_nodes_in_area(lua_State *L)
3782 EnvRef *o = checkobject(L, 1);
3783 ServerEnvironment *env = o->m_env;
3784 if(env == NULL) return 0;
3785 INodeDefManager *ndef = get_server(L)->ndef();
3786 v3s16 minp = read_v3s16(L, 2);
3787 v3s16 maxp = read_v3s16(L, 3);
3788 std::set<content_t> filter;
3789 if(lua_istable(L, 4)){
3792 while(lua_next(L, table) != 0){
3793 // key at index -2 and value at index -1
3794 luaL_checktype(L, -1, LUA_TSTRING);
3795 ndef->getIds(lua_tostring(L, -1), filter);
3796 // removes value, keeps key for next iteration
3799 } else if(lua_isstring(L, 4)){
3800 ndef->getIds(lua_tostring(L, 4), filter);
3803 // Get the table insert function
3804 lua_getglobal(L, "table");
3805 lua_getfield(L, -1, "insert");
3806 int table_insert = lua_gettop(L);
3809 int table = lua_gettop(L);
3810 for(s16 x=minp.X; x<=maxp.X; x++)
3811 for(s16 y=minp.Y; y<=maxp.Y; y++)
3812 for(s16 z=minp.Z; z<=maxp.Z; z++)
3815 content_t c = env->getMap().getNodeNoEx(p).getContent();
3816 if(filter.count(c) != 0){
3817 lua_pushvalue(L, table_insert);
3818 lua_pushvalue(L, table);
3820 if(lua_pcall(L, 2, 0, 0))
3821 script_error(L, "error: %s", lua_tostring(L, -1));
3827 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3828 // returns world-specific PerlinNoise
3829 static int l_get_perlin(lua_State *L)
3831 EnvRef *o = checkobject(L, 1);
3832 ServerEnvironment *env = o->m_env;
3833 if(env == NULL) return 0;
3835 int seeddiff = luaL_checkint(L, 2);
3836 int octaves = luaL_checkint(L, 3);
3837 double persistence = luaL_checknumber(L, 4);
3838 double scale = luaL_checknumber(L, 5);
3840 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3841 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3842 luaL_getmetatable(L, "PerlinNoise");
3843 lua_setmetatable(L, -2);
3847 // EnvRef:clear_objects()
3848 // clear all objects in the environment
3849 static int l_clear_objects(lua_State *L)
3851 EnvRef *o = checkobject(L, 1);
3852 o->m_env->clearAllObjects();
3857 EnvRef(ServerEnvironment *env):
3860 //infostream<<"EnvRef created"<<std::endl;
3865 //infostream<<"EnvRef destructing"<<std::endl;
3868 // Creates an EnvRef and leaves it on top of stack
3869 // Not callable from Lua; all references are created on the C side.
3870 static void create(lua_State *L, ServerEnvironment *env)
3872 EnvRef *o = new EnvRef(env);
3873 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3874 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3875 luaL_getmetatable(L, className);
3876 lua_setmetatable(L, -2);
3879 static void set_null(lua_State *L)
3881 EnvRef *o = checkobject(L, -1);
3885 static void Register(lua_State *L)
3888 int methodtable = lua_gettop(L);
3889 luaL_newmetatable(L, className);
3890 int metatable = lua_gettop(L);
3892 lua_pushliteral(L, "__metatable");
3893 lua_pushvalue(L, methodtable);
3894 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3896 lua_pushliteral(L, "__index");
3897 lua_pushvalue(L, methodtable);
3898 lua_settable(L, metatable);
3900 lua_pushliteral(L, "__gc");
3901 lua_pushcfunction(L, gc_object);
3902 lua_settable(L, metatable);
3904 lua_pop(L, 1); // drop metatable
3906 luaL_openlib(L, 0, methods, 0); // fill methodtable
3907 lua_pop(L, 1); // drop methodtable
3909 // Cannot be created from Lua
3910 //lua_register(L, className, create_object);
3913 const char EnvRef::className[] = "EnvRef";
3914 const luaL_reg EnvRef::methods[] = {
3915 method(EnvRef, set_node),
3916 method(EnvRef, add_node),
3917 method(EnvRef, remove_node),
3918 method(EnvRef, get_node),
3919 method(EnvRef, get_node_or_nil),
3920 method(EnvRef, get_node_light),
3921 method(EnvRef, place_node),
3922 method(EnvRef, dig_node),
3923 method(EnvRef, punch_node),
3924 method(EnvRef, add_entity),
3925 method(EnvRef, add_item),
3926 method(EnvRef, add_rat),
3927 method(EnvRef, add_firefly),
3928 method(EnvRef, get_meta),
3929 method(EnvRef, get_node_timer),
3930 method(EnvRef, get_player_by_name),
3931 method(EnvRef, get_objects_inside_radius),
3932 method(EnvRef, set_timeofday),
3933 method(EnvRef, get_timeofday),
3934 method(EnvRef, find_node_near),
3935 method(EnvRef, find_nodes_in_area),
3936 method(EnvRef, get_perlin),
3937 method(EnvRef, clear_objects),
3946 class LuaPseudoRandom
3949 PseudoRandom m_pseudo;
3951 static const char className[];
3952 static const luaL_reg methods[];
3954 // Exported functions
3956 // garbage collector
3957 static int gc_object(lua_State *L)
3959 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3964 // next(self, min=0, max=32767) -> get next value
3965 static int l_next(lua_State *L)
3967 LuaPseudoRandom *o = checkobject(L, 1);
3970 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3971 if(!lua_isnil(L, 2))
3972 min = luaL_checkinteger(L, 2);
3973 if(!lua_isnil(L, 3))
3974 max = luaL_checkinteger(L, 3);
3976 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
3977 throw LuaError(L, "PseudoRandom.next(): max < min");
3979 if(max - min != 32767 && max - min > 32767/5)
3980 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.");
3981 PseudoRandom &pseudo = o->m_pseudo;
3982 int val = pseudo.next();
3983 val = (val % (max-min+1)) + min;
3984 lua_pushinteger(L, val);
3989 LuaPseudoRandom(int seed):
3998 const PseudoRandom& getItem() const
4002 PseudoRandom& getItem()
4007 // LuaPseudoRandom(seed)
4008 // Creates an LuaPseudoRandom and leaves it on top of stack
4009 static int create_object(lua_State *L)
4011 int seed = luaL_checknumber(L, 1);
4012 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4013 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4014 luaL_getmetatable(L, className);
4015 lua_setmetatable(L, -2);
4019 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4021 luaL_checktype(L, narg, LUA_TUSERDATA);
4022 void *ud = luaL_checkudata(L, narg, className);
4023 if(!ud) luaL_typerror(L, narg, className);
4024 return *(LuaPseudoRandom**)ud; // unbox pointer
4027 static void Register(lua_State *L)
4030 int methodtable = lua_gettop(L);
4031 luaL_newmetatable(L, className);
4032 int metatable = lua_gettop(L);
4034 lua_pushliteral(L, "__metatable");
4035 lua_pushvalue(L, methodtable);
4036 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4038 lua_pushliteral(L, "__index");
4039 lua_pushvalue(L, methodtable);
4040 lua_settable(L, metatable);
4042 lua_pushliteral(L, "__gc");
4043 lua_pushcfunction(L, gc_object);
4044 lua_settable(L, metatable);
4046 lua_pop(L, 1); // drop metatable
4048 luaL_openlib(L, 0, methods, 0); // fill methodtable
4049 lua_pop(L, 1); // drop methodtable
4051 // Can be created from Lua (LuaPseudoRandom(seed))
4052 lua_register(L, className, create_object);
4055 const char LuaPseudoRandom::className[] = "PseudoRandom";
4056 const luaL_reg LuaPseudoRandom::methods[] = {
4057 method(LuaPseudoRandom, next),
4067 class LuaABM : public ActiveBlockModifier
4073 std::set<std::string> m_trigger_contents;
4074 std::set<std::string> m_required_neighbors;
4075 float m_trigger_interval;
4076 u32 m_trigger_chance;
4078 LuaABM(lua_State *L, int id,
4079 const std::set<std::string> &trigger_contents,
4080 const std::set<std::string> &required_neighbors,
4081 float trigger_interval, u32 trigger_chance):
4084 m_trigger_contents(trigger_contents),
4085 m_required_neighbors(required_neighbors),
4086 m_trigger_interval(trigger_interval),
4087 m_trigger_chance(trigger_chance)
4090 virtual std::set<std::string> getTriggerContents()
4092 return m_trigger_contents;
4094 virtual std::set<std::string> getRequiredNeighbors()
4096 return m_required_neighbors;
4098 virtual float getTriggerInterval()
4100 return m_trigger_interval;
4102 virtual u32 getTriggerChance()
4104 return m_trigger_chance;
4106 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4107 u32 active_object_count, u32 active_object_count_wider)
4109 lua_State *L = m_lua;
4112 assert(lua_checkstack(L, 20));
4113 StackUnroller stack_unroller(L);
4115 // Get minetest.registered_abms
4116 lua_getglobal(L, "minetest");
4117 lua_getfield(L, -1, "registered_abms");
4118 luaL_checktype(L, -1, LUA_TTABLE);
4119 int registered_abms = lua_gettop(L);
4121 // Get minetest.registered_abms[m_id]
4122 lua_pushnumber(L, m_id);
4123 lua_gettable(L, registered_abms);
4124 if(lua_isnil(L, -1))
4128 luaL_checktype(L, -1, LUA_TTABLE);
4129 lua_getfield(L, -1, "action");
4130 luaL_checktype(L, -1, LUA_TFUNCTION);
4132 pushnode(L, n, env->getGameDef()->ndef());
4133 lua_pushnumber(L, active_object_count);
4134 lua_pushnumber(L, active_object_count_wider);
4135 if(lua_pcall(L, 4, 0, 0))
4136 script_error(L, "error: %s", lua_tostring(L, -1));
4144 static void read_server_sound_params(lua_State *L, int index,
4145 ServerSoundParams ¶ms)
4148 index = lua_gettop(L) + 1 + index;
4150 params = ServerSoundParams();
4151 if(lua_istable(L, index)){
4152 getfloatfield(L, index, "gain", params.gain);
4153 getstringfield(L, index, "to_player", params.to_player);
4154 lua_getfield(L, index, "pos");
4155 if(!lua_isnil(L, -1)){
4156 v3f p = read_v3f(L, -1)*BS;
4158 params.type = ServerSoundParams::SSP_POSITIONAL;
4161 lua_getfield(L, index, "object");
4162 if(!lua_isnil(L, -1)){
4163 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4164 ServerActiveObject *sao = ObjectRef::getobject(ref);
4166 params.object = sao->getId();
4167 params.type = ServerSoundParams::SSP_OBJECT;
4171 params.max_hear_distance = BS*getfloatfield_default(L, index,
4172 "max_hear_distance", params.max_hear_distance/BS);
4173 getboolfield(L, index, "loop", params.loop);
4182 // Writes a line to dstream
4183 static int l_debug(lua_State *L)
4185 std::string text = lua_tostring(L, 1);
4186 dstream << text << std::endl;
4190 // log([level,] text)
4191 // Writes a line to the logger.
4192 // The one-argument version logs to infostream.
4193 // The two-argument version accept a log level: error, action, info, or verbose.
4194 static int l_log(lua_State *L)
4197 LogMessageLevel level = LMT_INFO;
4198 if(lua_isnone(L, 2))
4200 text = lua_tostring(L, 1);
4204 std::string levelname = lua_tostring(L, 1);
4205 text = lua_tostring(L, 2);
4206 if(levelname == "error")
4208 else if(levelname == "action")
4210 else if(levelname == "verbose")
4211 level = LMT_VERBOSE;
4213 log_printline(level, text);
4217 // request_shutdown()
4218 static int l_request_shutdown(lua_State *L)
4220 get_server(L)->requestShutdown();
4224 // get_server_status()
4225 static int l_get_server_status(lua_State *L)
4227 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4231 // register_item_raw({lots of stuff})
4232 static int l_register_item_raw(lua_State *L)
4234 luaL_checktype(L, 1, LUA_TTABLE);
4237 // Get the writable item and node definition managers from the server
4238 IWritableItemDefManager *idef =
4239 get_server(L)->getWritableItemDefManager();
4240 IWritableNodeDefManager *ndef =
4241 get_server(L)->getWritableNodeDefManager();
4243 // Check if name is defined
4245 lua_getfield(L, table, "name");
4246 if(lua_isstring(L, -1)){
4247 name = lua_tostring(L, -1);
4248 verbosestream<<"register_item_raw: "<<name<<std::endl;
4250 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4253 // Check if on_use is defined
4256 // Set a distinctive default value to check if this is set
4257 def.node_placement_prediction = "__default";
4259 // Read the item definition
4260 def = read_item_definition(L, table, def);
4262 // Default to having client-side placement prediction for nodes
4263 // ("" in item definition sets it off)
4264 if(def.node_placement_prediction == "__default"){
4265 if(def.type == ITEM_NODE)
4266 def.node_placement_prediction = name;
4268 def.node_placement_prediction = "";
4271 // Register item definition
4272 idef->registerItem(def);
4274 // Read the node definition (content features) and register it
4275 if(def.type == ITEM_NODE)
4277 ContentFeatures f = read_content_features(L, table);
4278 ndef->set(f.name, f);
4281 return 0; /* number of results */
4284 // register_alias_raw(name, convert_to_name)
4285 static int l_register_alias_raw(lua_State *L)
4287 std::string name = luaL_checkstring(L, 1);
4288 std::string convert_to = luaL_checkstring(L, 2);
4290 // Get the writable item definition manager from the server
4291 IWritableItemDefManager *idef =
4292 get_server(L)->getWritableItemDefManager();
4294 idef->registerAlias(name, convert_to);
4296 return 0; /* number of results */
4299 // helper for register_craft
4300 static bool read_craft_recipe_shaped(lua_State *L, int index,
4301 int &width, std::vector<std::string> &recipe)
4304 index = lua_gettop(L) + 1 + index;
4306 if(!lua_istable(L, index))
4311 while(lua_next(L, index) != 0){
4313 // key at index -2 and value at index -1
4314 if(!lua_istable(L, -1))
4316 int table2 = lua_gettop(L);
4318 while(lua_next(L, table2) != 0){
4319 // key at index -2 and value at index -1
4320 if(!lua_isstring(L, -1))
4322 recipe.push_back(lua_tostring(L, -1));
4323 // removes value, keeps key for next iteration
4330 if(colcount != width)
4333 // removes value, keeps key for next iteration
4340 // helper for register_craft
4341 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4342 std::vector<std::string> &recipe)
4345 index = lua_gettop(L) + 1 + index;
4347 if(!lua_istable(L, index))
4351 while(lua_next(L, index) != 0){
4352 // key at index -2 and value at index -1
4353 if(!lua_isstring(L, -1))
4355 recipe.push_back(lua_tostring(L, -1));
4356 // removes value, keeps key for next iteration
4362 // helper for register_craft
4363 static bool read_craft_replacements(lua_State *L, int index,
4364 CraftReplacements &replacements)
4367 index = lua_gettop(L) + 1 + index;
4369 if(!lua_istable(L, index))
4373 while(lua_next(L, index) != 0){
4374 // key at index -2 and value at index -1
4375 if(!lua_istable(L, -1))
4377 lua_rawgeti(L, -1, 1);
4378 if(!lua_isstring(L, -1))
4380 std::string replace_from = lua_tostring(L, -1);
4382 lua_rawgeti(L, -1, 2);
4383 if(!lua_isstring(L, -1))
4385 std::string replace_to = lua_tostring(L, -1);
4387 replacements.pairs.push_back(
4388 std::make_pair(replace_from, replace_to));
4389 // removes value, keeps key for next iteration
4394 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4395 static int l_register_craft(lua_State *L)
4397 //infostream<<"register_craft"<<std::endl;
4398 luaL_checktype(L, 1, LUA_TTABLE);
4401 // Get the writable craft definition manager from the server
4402 IWritableCraftDefManager *craftdef =
4403 get_server(L)->getWritableCraftDefManager();
4405 std::string type = getstringfield_default(L, table, "type", "shaped");
4408 CraftDefinitionShaped
4410 if(type == "shaped"){
4411 std::string output = getstringfield_default(L, table, "output", "");
4413 throw LuaError(L, "Crafting definition is missing an output");
4416 std::vector<std::string> recipe;
4417 lua_getfield(L, table, "recipe");
4418 if(lua_isnil(L, -1))
4419 throw LuaError(L, "Crafting definition is missing a recipe"
4420 " (output=\"" + output + "\")");
4421 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4422 throw LuaError(L, "Invalid crafting recipe"
4423 " (output=\"" + output + "\")");
4425 CraftReplacements replacements;
4426 lua_getfield(L, table, "replacements");
4427 if(!lua_isnil(L, -1))
4429 if(!read_craft_replacements(L, -1, replacements))
4430 throw LuaError(L, "Invalid replacements"
4431 " (output=\"" + output + "\")");
4434 CraftDefinition *def = new CraftDefinitionShaped(
4435 output, width, recipe, replacements);
4436 craftdef->registerCraft(def);
4439 CraftDefinitionShapeless
4441 else if(type == "shapeless"){
4442 std::string output = getstringfield_default(L, table, "output", "");
4444 throw LuaError(L, "Crafting definition (shapeless)"
4445 " is missing an output");
4447 std::vector<std::string> recipe;
4448 lua_getfield(L, table, "recipe");
4449 if(lua_isnil(L, -1))
4450 throw LuaError(L, "Crafting definition (shapeless)"
4451 " is missing a recipe"
4452 " (output=\"" + output + "\")");
4453 if(!read_craft_recipe_shapeless(L, -1, recipe))
4454 throw LuaError(L, "Invalid crafting recipe"
4455 " (output=\"" + output + "\")");
4457 CraftReplacements replacements;
4458 lua_getfield(L, table, "replacements");
4459 if(!lua_isnil(L, -1))
4461 if(!read_craft_replacements(L, -1, replacements))
4462 throw LuaError(L, "Invalid replacements"
4463 " (output=\"" + output + "\")");
4466 CraftDefinition *def = new CraftDefinitionShapeless(
4467 output, recipe, replacements);
4468 craftdef->registerCraft(def);
4471 CraftDefinitionToolRepair
4473 else if(type == "toolrepair"){
4474 float additional_wear = getfloatfield_default(L, table,
4475 "additional_wear", 0.0);
4477 CraftDefinition *def = new CraftDefinitionToolRepair(
4479 craftdef->registerCraft(def);
4482 CraftDefinitionCooking
4484 else if(type == "cooking"){
4485 std::string output = getstringfield_default(L, table, "output", "");
4487 throw LuaError(L, "Crafting definition (cooking)"
4488 " is missing an output");
4490 std::string recipe = getstringfield_default(L, table, "recipe", "");
4492 throw LuaError(L, "Crafting definition (cooking)"
4493 " is missing a recipe"
4494 " (output=\"" + output + "\")");
4496 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4498 CraftReplacements replacements;
4499 lua_getfield(L, table, "replacements");
4500 if(!lua_isnil(L, -1))
4502 if(!read_craft_replacements(L, -1, replacements))
4503 throw LuaError(L, "Invalid replacements"
4504 " (cooking output=\"" + output + "\")");
4507 CraftDefinition *def = new CraftDefinitionCooking(
4508 output, recipe, cooktime, replacements);
4509 craftdef->registerCraft(def);
4514 else if(type == "fuel"){
4515 std::string recipe = getstringfield_default(L, table, "recipe", "");
4517 throw LuaError(L, "Crafting definition (fuel)"
4518 " is missing a recipe");
4520 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4522 CraftReplacements replacements;
4523 lua_getfield(L, table, "replacements");
4524 if(!lua_isnil(L, -1))
4526 if(!read_craft_replacements(L, -1, replacements))
4527 throw LuaError(L, "Invalid replacements"
4528 " (fuel recipe=\"" + recipe + "\")");
4531 CraftDefinition *def = new CraftDefinitionFuel(
4532 recipe, burntime, replacements);
4533 craftdef->registerCraft(def);
4537 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4541 return 0; /* number of results */
4544 // setting_set(name, value)
4545 static int l_setting_set(lua_State *L)
4547 const char *name = luaL_checkstring(L, 1);
4548 const char *value = luaL_checkstring(L, 2);
4549 g_settings->set(name, value);
4553 // setting_get(name)
4554 static int l_setting_get(lua_State *L)
4556 const char *name = luaL_checkstring(L, 1);
4558 std::string value = g_settings->get(name);
4559 lua_pushstring(L, value.c_str());
4560 } catch(SettingNotFoundException &e){
4566 // setting_getbool(name)
4567 static int l_setting_getbool(lua_State *L)
4569 const char *name = luaL_checkstring(L, 1);
4571 bool value = g_settings->getBool(name);
4572 lua_pushboolean(L, value);
4573 } catch(SettingNotFoundException &e){
4579 // chat_send_all(text)
4580 static int l_chat_send_all(lua_State *L)
4582 const char *text = luaL_checkstring(L, 1);
4583 // Get server from registry
4584 Server *server = get_server(L);
4586 server->notifyPlayers(narrow_to_wide(text));
4590 // chat_send_player(name, text)
4591 static int l_chat_send_player(lua_State *L)
4593 const char *name = luaL_checkstring(L, 1);
4594 const char *text = luaL_checkstring(L, 2);
4595 // Get server from registry
4596 Server *server = get_server(L);
4598 server->notifyPlayer(name, narrow_to_wide(text));
4602 // get_player_privs(name, text)
4603 static int l_get_player_privs(lua_State *L)
4605 const char *name = luaL_checkstring(L, 1);
4606 // Get server from registry
4607 Server *server = get_server(L);
4610 int table = lua_gettop(L);
4611 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4612 for(std::set<std::string>::const_iterator
4613 i = privs_s.begin(); i != privs_s.end(); i++){
4614 lua_pushboolean(L, true);
4615 lua_setfield(L, table, i->c_str());
4617 lua_pushvalue(L, table);
4622 static int l_get_ban_list(lua_State *L)
4624 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4628 // get_ban_description()
4629 static int l_get_ban_description(lua_State *L)
4631 const char * ip_or_name = luaL_checkstring(L, 1);
4632 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4637 static int l_ban_player(lua_State *L)
4639 const char * name = luaL_checkstring(L, 1);
4640 Player *player = get_env(L)->getPlayer(name);
4643 lua_pushboolean(L, false); // no such player
4648 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4649 std::string ip_str = addr.serializeString();
4650 get_server(L)->setIpBanned(ip_str, name);
4652 catch(con::PeerNotFoundException) // unlikely
4654 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4655 lua_pushboolean(L, false); // error
4658 lua_pushboolean(L, true);
4662 // unban_player_or_ip()
4663 static int l_unban_player_of_ip(lua_State *L)
4665 const char * ip_or_name = luaL_checkstring(L, 1);
4666 get_server(L)->unsetIpBanned(ip_or_name);
4667 lua_pushboolean(L, true);
4671 // get_inventory(location)
4672 static int l_get_inventory(lua_State *L)
4674 InventoryLocation loc;
4676 std::string type = checkstringfield(L, 1, "type");
4677 if(type == "player"){
4678 std::string name = checkstringfield(L, 1, "name");
4679 loc.setPlayer(name);
4680 } else if(type == "node"){
4681 lua_getfield(L, 1, "pos");
4682 v3s16 pos = check_v3s16(L, -1);
4683 loc.setNodeMeta(pos);
4684 } else if(type == "detached"){
4685 std::string name = checkstringfield(L, 1, "name");
4686 loc.setDetached(name);
4689 if(get_server(L)->getInventory(loc) != NULL)
4690 InvRef::create(L, loc);
4696 // create_detached_inventory_raw(name)
4697 static int l_create_detached_inventory_raw(lua_State *L)
4699 const char *name = luaL_checkstring(L, 1);
4700 if(get_server(L)->createDetachedInventory(name) != NULL){
4701 InventoryLocation loc;
4702 loc.setDetached(name);
4703 InvRef::create(L, loc);
4710 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4711 static int l_get_dig_params(lua_State *L)
4713 std::map<std::string, int> groups;
4714 read_groups(L, 1, groups);
4715 ToolCapabilities tp = read_tool_capabilities(L, 2);
4716 if(lua_isnoneornil(L, 3))
4717 push_dig_params(L, getDigParams(groups, &tp));
4719 push_dig_params(L, getDigParams(groups, &tp,
4720 luaL_checknumber(L, 3)));
4724 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4725 static int l_get_hit_params(lua_State *L)
4727 std::map<std::string, int> groups;
4728 read_groups(L, 1, groups);
4729 ToolCapabilities tp = read_tool_capabilities(L, 2);
4730 if(lua_isnoneornil(L, 3))
4731 push_hit_params(L, getHitParams(groups, &tp));
4733 push_hit_params(L, getHitParams(groups, &tp,
4734 luaL_checknumber(L, 3)));
4738 // get_current_modname()
4739 static int l_get_current_modname(lua_State *L)
4741 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4745 // get_modpath(modname)
4746 static int l_get_modpath(lua_State *L)
4748 std::string modname = luaL_checkstring(L, 1);
4750 if(modname == "__builtin"){
4751 std::string path = get_server(L)->getBuiltinLuaPath();
4752 lua_pushstring(L, path.c_str());
4755 const ModSpec *mod = get_server(L)->getModSpec(modname);
4760 lua_pushstring(L, mod->path.c_str());
4765 // the returned list is sorted alphabetically for you
4766 static int l_get_modnames(lua_State *L)
4768 // Get a list of mods
4769 core::list<std::string> mods_unsorted, mods_sorted;
4770 get_server(L)->getModNames(mods_unsorted);
4772 // Take unsorted items from mods_unsorted and sort them into
4773 // mods_sorted; not great performance but the number of mods on a
4774 // server will likely be small.
4775 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4776 i != mods_unsorted.end(); i++)
4779 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4780 x != mods_unsorted.end(); x++)
4782 // I doubt anybody using Minetest will be using
4783 // anything not ASCII based :)
4784 if((*i).compare(*x) <= 0)
4786 mods_sorted.insert_before(x, *i);
4792 mods_sorted.push_back(*i);
4795 // Get the table insertion function from Lua.
4796 lua_getglobal(L, "table");
4797 lua_getfield(L, -1, "insert");
4798 int insertion_func = lua_gettop(L);
4800 // Package them up for Lua
4802 int new_table = lua_gettop(L);
4803 core::list<std::string>::Iterator i = mods_sorted.begin();
4804 while(i != mods_sorted.end())
4806 lua_pushvalue(L, insertion_func);
4807 lua_pushvalue(L, new_table);
4808 lua_pushstring(L, (*i).c_str());
4809 if(lua_pcall(L, 2, 0, 0) != 0)
4811 script_error(L, "error: %s", lua_tostring(L, -1));
4819 static int l_get_worldpath(lua_State *L)
4821 std::string worldpath = get_server(L)->getWorldPath();
4822 lua_pushstring(L, worldpath.c_str());
4826 // sound_play(spec, parameters)
4827 static int l_sound_play(lua_State *L)
4829 SimpleSoundSpec spec;
4830 read_soundspec(L, 1, spec);
4831 ServerSoundParams params;
4832 read_server_sound_params(L, 2, params);
4833 s32 handle = get_server(L)->playSound(spec, params);
4834 lua_pushinteger(L, handle);
4838 // sound_stop(handle)
4839 static int l_sound_stop(lua_State *L)
4841 int handle = luaL_checkinteger(L, 1);
4842 get_server(L)->stopSound(handle);
4846 // is_singleplayer()
4847 static int l_is_singleplayer(lua_State *L)
4849 lua_pushboolean(L, get_server(L)->isSingleplayer());
4853 // get_password_hash(name, raw_password)
4854 static int l_get_password_hash(lua_State *L)
4856 std::string name = luaL_checkstring(L, 1);
4857 std::string raw_password = luaL_checkstring(L, 2);
4858 std::string hash = translatePassword(name,
4859 narrow_to_wide(raw_password));
4860 lua_pushstring(L, hash.c_str());
4864 // notify_authentication_modified(name)
4865 static int l_notify_authentication_modified(lua_State *L)
4867 std::string name = "";
4868 if(lua_isstring(L, 1))
4869 name = lua_tostring(L, 1);
4870 get_server(L)->reportPrivsModified(name);
4874 // get_craft_result(input)
4875 static int l_get_craft_result(lua_State *L)
4878 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4879 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4880 es_CraftMethod, CRAFT_METHOD_NORMAL);
4882 lua_getfield(L, input_i, "width");
4883 if(lua_isnumber(L, -1))
4884 width = luaL_checkinteger(L, -1);
4886 lua_getfield(L, input_i, "items");
4887 std::vector<ItemStack> items = read_items(L, -1);
4888 lua_pop(L, 1); // items
4890 IGameDef *gdef = get_server(L);
4891 ICraftDefManager *cdef = gdef->cdef();
4892 CraftInput input(method, width, items);
4894 bool got = cdef->getCraftResult(input, output, true, gdef);
4895 lua_newtable(L); // output table
4898 item.deSerialize(output.item, gdef->idef());
4899 LuaItemStack::create(L, item);
4900 lua_setfield(L, -2, "item");
4901 setintfield(L, -1, "time", output.time);
4903 LuaItemStack::create(L, ItemStack());
4904 lua_setfield(L, -2, "item");
4905 setintfield(L, -1, "time", 0);
4907 lua_newtable(L); // decremented input table
4908 lua_pushstring(L, method_s.c_str());
4909 lua_setfield(L, -2, "method");
4910 lua_pushinteger(L, width);
4911 lua_setfield(L, -2, "width");
4912 push_items(L, input.items);
4913 lua_setfield(L, -2, "items");
4917 // get_craft_recipe(result item)
4918 static int l_get_craft_recipe(lua_State *L)
4923 std::string o_item = luaL_checkstring(L,input_i);
4925 IGameDef *gdef = get_server(L);
4926 ICraftDefManager *cdef = gdef->cdef();
4928 CraftOutput output(o_item,0);
4929 bool got = cdef->getCraftRecipe(input, output, gdef);
4930 lua_newtable(L); // output table
4933 for(std::vector<ItemStack>::const_iterator
4934 i = input.items.begin();
4935 i != input.items.end(); i++, k++)
4941 sprintf(tmp,"%d",k);
4942 lua_pushstring(L,tmp);
4943 lua_pushstring(L,i->name.c_str());
4944 lua_settable(L, -3);
4946 lua_setfield(L, -2, "items");
4947 setintfield(L, -1, "width", input.width);
4948 switch (input.method) {
4949 case CRAFT_METHOD_NORMAL:
4950 lua_pushstring(L,"normal");
4952 case CRAFT_METHOD_COOKING:
4953 lua_pushstring(L,"cooking");
4955 case CRAFT_METHOD_FUEL:
4956 lua_pushstring(L,"fuel");
4959 lua_pushstring(L,"unknown");
4961 lua_setfield(L, -2, "type");
4964 lua_setfield(L, -2, "items");
4965 setintfield(L, -1, "width", 0);
4970 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
4971 static int l_rollback_get_last_node_actor(lua_State *L)
4973 v3s16 p = read_v3s16(L, 1);
4974 int range = luaL_checknumber(L, 2);
4975 int seconds = luaL_checknumber(L, 3);
4976 Server *server = get_server(L);
4977 IRollbackManager *rollback = server->getRollbackManager();
4979 int act_seconds = 0;
4980 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
4981 lua_pushstring(L, actor.c_str());
4982 push_v3s16(L, act_p);
4983 lua_pushnumber(L, act_seconds);
4987 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
4988 static int l_rollback_revert_actions_by(lua_State *L)
4990 std::string actor = luaL_checkstring(L, 1);
4991 int seconds = luaL_checknumber(L, 2);
4992 Server *server = get_server(L);
4993 IRollbackManager *rollback = server->getRollbackManager();
4994 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
4995 std::list<std::string> log;
4996 bool success = server->rollbackRevertActions(actions, &log);
4997 // Push boolean result
4998 lua_pushboolean(L, success);
4999 // Get the table insert function and push the log table
5000 lua_getglobal(L, "table");
5001 lua_getfield(L, -1, "insert");
5002 int table_insert = lua_gettop(L);
5004 int table = lua_gettop(L);
5005 for(std::list<std::string>::const_iterator i = log.begin();
5006 i != log.end(); i++)
5008 lua_pushvalue(L, table_insert);
5009 lua_pushvalue(L, table);
5010 lua_pushstring(L, i->c_str());
5011 if(lua_pcall(L, 2, 0, 0))
5012 script_error(L, "error: %s", lua_tostring(L, -1));
5014 lua_remove(L, -2); // Remove table
5015 lua_remove(L, -2); // Remove insert
5019 static const struct luaL_Reg minetest_f [] = {
5022 {"request_shutdown", l_request_shutdown},
5023 {"get_server_status", l_get_server_status},
5024 {"register_item_raw", l_register_item_raw},
5025 {"register_alias_raw", l_register_alias_raw},
5026 {"register_craft", l_register_craft},
5027 {"setting_set", l_setting_set},
5028 {"setting_get", l_setting_get},
5029 {"setting_getbool", l_setting_getbool},
5030 {"chat_send_all", l_chat_send_all},
5031 {"chat_send_player", l_chat_send_player},
5032 {"get_player_privs", l_get_player_privs},
5033 {"get_ban_list", l_get_ban_list},
5034 {"get_ban_description", l_get_ban_description},
5035 {"ban_player", l_ban_player},
5036 {"unban_player_or_ip", l_unban_player_of_ip},
5037 {"get_inventory", l_get_inventory},
5038 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5039 {"get_dig_params", l_get_dig_params},
5040 {"get_hit_params", l_get_hit_params},
5041 {"get_current_modname", l_get_current_modname},
5042 {"get_modpath", l_get_modpath},
5043 {"get_modnames", l_get_modnames},
5044 {"get_worldpath", l_get_worldpath},
5045 {"sound_play", l_sound_play},
5046 {"sound_stop", l_sound_stop},
5047 {"is_singleplayer", l_is_singleplayer},
5048 {"get_password_hash", l_get_password_hash},
5049 {"notify_authentication_modified", l_notify_authentication_modified},
5050 {"get_craft_result", l_get_craft_result},
5051 {"get_craft_recipe", l_get_craft_recipe},
5052 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5053 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5058 Main export function
5061 void scriptapi_export(lua_State *L, Server *server)
5064 assert(lua_checkstack(L, 20));
5065 verbosestream<<"scriptapi_export()"<<std::endl;
5066 StackUnroller stack_unroller(L);
5068 // Store server as light userdata in registry
5069 lua_pushlightuserdata(L, server);
5070 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5072 // Register global functions in table minetest
5074 luaL_register(L, NULL, minetest_f);
5075 lua_setglobal(L, "minetest");
5077 // Get the main minetest table
5078 lua_getglobal(L, "minetest");
5080 // Add tables to minetest
5082 lua_setfield(L, -2, "object_refs");
5084 lua_setfield(L, -2, "luaentities");
5086 // Register wrappers
5087 LuaItemStack::Register(L);
5088 InvRef::Register(L);
5089 NodeMetaRef::Register(L);
5090 NodeTimerRef::Register(L);
5091 ObjectRef::Register(L);
5092 EnvRef::Register(L);
5093 LuaPseudoRandom::Register(L);
5094 LuaPerlinNoise::Register(L);
5097 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5098 const std::string &modname)
5100 ModNameStorer modnamestorer(L, modname);
5102 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5104 errorstream<<"Error loading mod \""<<modname
5105 <<"\": modname does not follow naming conventions: "
5106 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5110 bool success = false;
5113 success = script_load(L, scriptpath.c_str());
5116 errorstream<<"Error loading mod \""<<modname
5117 <<"\": "<<e.what()<<std::endl;
5123 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5126 assert(lua_checkstack(L, 20));
5127 verbosestream<<"scriptapi_add_environment"<<std::endl;
5128 StackUnroller stack_unroller(L);
5130 // Create EnvRef on stack
5131 EnvRef::create(L, env);
5132 int envref = lua_gettop(L);
5134 // minetest.env = envref
5135 lua_getglobal(L, "minetest");
5136 luaL_checktype(L, -1, LUA_TTABLE);
5137 lua_pushvalue(L, envref);
5138 lua_setfield(L, -2, "env");
5140 // Store environment as light userdata in registry
5141 lua_pushlightuserdata(L, env);
5142 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5145 Add ActiveBlockModifiers to environment
5148 // Get minetest.registered_abms
5149 lua_getglobal(L, "minetest");
5150 lua_getfield(L, -1, "registered_abms");
5151 luaL_checktype(L, -1, LUA_TTABLE);
5152 int registered_abms = lua_gettop(L);
5154 if(lua_istable(L, registered_abms)){
5155 int table = lua_gettop(L);
5157 while(lua_next(L, table) != 0){
5158 // key at index -2 and value at index -1
5159 int id = lua_tonumber(L, -2);
5160 int current_abm = lua_gettop(L);
5162 std::set<std::string> trigger_contents;
5163 lua_getfield(L, current_abm, "nodenames");
5164 if(lua_istable(L, -1)){
5165 int table = lua_gettop(L);
5167 while(lua_next(L, table) != 0){
5168 // key at index -2 and value at index -1
5169 luaL_checktype(L, -1, LUA_TSTRING);
5170 trigger_contents.insert(lua_tostring(L, -1));
5171 // removes value, keeps key for next iteration
5174 } else if(lua_isstring(L, -1)){
5175 trigger_contents.insert(lua_tostring(L, -1));
5179 std::set<std::string> required_neighbors;
5180 lua_getfield(L, current_abm, "neighbors");
5181 if(lua_istable(L, -1)){
5182 int table = lua_gettop(L);
5184 while(lua_next(L, table) != 0){
5185 // key at index -2 and value at index -1
5186 luaL_checktype(L, -1, LUA_TSTRING);
5187 required_neighbors.insert(lua_tostring(L, -1));
5188 // removes value, keeps key for next iteration
5191 } else if(lua_isstring(L, -1)){
5192 required_neighbors.insert(lua_tostring(L, -1));
5196 float trigger_interval = 10.0;
5197 getfloatfield(L, current_abm, "interval", trigger_interval);
5199 int trigger_chance = 50;
5200 getintfield(L, current_abm, "chance", trigger_chance);
5202 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5203 required_neighbors, trigger_interval, trigger_chance);
5205 env->addActiveBlockModifier(abm);
5207 // removes value, keeps key for next iteration
5215 // Dump stack top with the dump2 function
5216 static void dump2(lua_State *L, const char *name)
5218 // Dump object (debug)
5219 lua_getglobal(L, "dump2");
5220 luaL_checktype(L, -1, LUA_TFUNCTION);
5221 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5222 lua_pushstring(L, name);
5223 if(lua_pcall(L, 2, 0, 0))
5224 script_error(L, "error: %s", lua_tostring(L, -1));
5232 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5235 assert(lua_checkstack(L, 20));
5236 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5237 StackUnroller stack_unroller(L);
5239 // Create object on stack
5240 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5241 int object = lua_gettop(L);
5243 // Get minetest.object_refs table
5244 lua_getglobal(L, "minetest");
5245 lua_getfield(L, -1, "object_refs");
5246 luaL_checktype(L, -1, LUA_TTABLE);
5247 int objectstable = lua_gettop(L);
5249 // object_refs[id] = object
5250 lua_pushnumber(L, cobj->getId()); // Push id
5251 lua_pushvalue(L, object); // Copy object to top of stack
5252 lua_settable(L, objectstable);
5255 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5258 assert(lua_checkstack(L, 20));
5259 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5260 StackUnroller stack_unroller(L);
5262 // Get minetest.object_refs table
5263 lua_getglobal(L, "minetest");
5264 lua_getfield(L, -1, "object_refs");
5265 luaL_checktype(L, -1, LUA_TTABLE);
5266 int objectstable = lua_gettop(L);
5268 // Get object_refs[id]
5269 lua_pushnumber(L, cobj->getId()); // Push id
5270 lua_gettable(L, objectstable);
5271 // Set object reference to NULL
5272 ObjectRef::set_null(L);
5273 lua_pop(L, 1); // pop object
5275 // Set object_refs[id] = nil
5276 lua_pushnumber(L, cobj->getId()); // Push id
5278 lua_settable(L, objectstable);
5285 // What scriptapi_run_callbacks does with the return values of callbacks.
5286 // Regardless of the mode, if only one callback is defined,
5287 // its return value is the total return value.
5288 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5289 enum RunCallbacksMode
5291 // Returns the return value of the first callback
5292 // Returns nil if list of callbacks is empty
5293 RUN_CALLBACKS_MODE_FIRST,
5294 // Returns the return value of the last callback
5295 // Returns nil if list of callbacks is empty
5296 RUN_CALLBACKS_MODE_LAST,
5297 // If any callback returns a false value, the first such is returned
5298 // Otherwise, the first callback's return value (trueish) is returned
5299 // Returns true if list of callbacks is empty
5300 RUN_CALLBACKS_MODE_AND,
5301 // Like above, but stops calling callbacks (short circuit)
5302 // after seeing the first false value
5303 RUN_CALLBACKS_MODE_AND_SC,
5304 // If any callback returns a true value, the first such is returned
5305 // Otherwise, the first callback's return value (falseish) is returned
5306 // Returns false if list of callbacks is empty
5307 RUN_CALLBACKS_MODE_OR,
5308 // Like above, but stops calling callbacks (short circuit)
5309 // after seeing the first true value
5310 RUN_CALLBACKS_MODE_OR_SC,
5311 // Note: "a true value" and "a false value" refer to values that
5312 // are converted by lua_toboolean to true or false, respectively.
5315 // Push the list of callbacks (a lua table).
5316 // Then push nargs arguments.
5317 // Then call this function, which
5318 // - runs the callbacks
5319 // - removes the table and arguments from the lua stack
5320 // - pushes the return value, computed depending on mode
5321 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5322 RunCallbacksMode mode)
5324 // Insert the return value into the lua stack, below the table
5325 assert(lua_gettop(L) >= nargs + 1);
5327 lua_insert(L, -(nargs + 1) - 1);
5328 // Stack now looks like this:
5329 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5331 int rv = lua_gettop(L) - nargs - 1;
5333 int arg = table + 1;
5335 luaL_checktype(L, table, LUA_TTABLE);
5339 bool first_loop = true;
5340 while(lua_next(L, table) != 0){
5341 // key at index -2 and value at index -1
5342 luaL_checktype(L, -1, LUA_TFUNCTION);
5344 for(int i = 0; i < nargs; i++)
5345 lua_pushvalue(L, arg+i);
5346 if(lua_pcall(L, nargs, 1, 0))
5347 script_error(L, "error: %s", lua_tostring(L, -1));
5349 // Move return value to designated space in stack
5352 // Result of first callback is always moved
5356 // Otherwise, what happens depends on the mode
5357 if(mode == RUN_CALLBACKS_MODE_FIRST)
5359 else if(mode == RUN_CALLBACKS_MODE_LAST)
5361 else if(mode == RUN_CALLBACKS_MODE_AND ||
5362 mode == RUN_CALLBACKS_MODE_AND_SC){
5363 if(lua_toboolean(L, rv) == true &&
5364 lua_toboolean(L, -1) == false)
5369 else if(mode == RUN_CALLBACKS_MODE_OR ||
5370 mode == RUN_CALLBACKS_MODE_OR_SC){
5371 if(lua_toboolean(L, rv) == false &&
5372 lua_toboolean(L, -1) == true)
5381 // Handle short circuit modes
5382 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5383 lua_toboolean(L, rv) == false)
5385 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5386 lua_toboolean(L, rv) == true)
5389 // value removed, keep key for next iteration
5392 // Remove stuff from stack, leaving only the return value
5395 // Fix return value in case no callbacks were called
5397 if(mode == RUN_CALLBACKS_MODE_AND ||
5398 mode == RUN_CALLBACKS_MODE_AND_SC){
5400 lua_pushboolean(L, true);
5402 else if(mode == RUN_CALLBACKS_MODE_OR ||
5403 mode == RUN_CALLBACKS_MODE_OR_SC){
5405 lua_pushboolean(L, false);
5410 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5411 const std::string &message)
5414 assert(lua_checkstack(L, 20));
5415 StackUnroller stack_unroller(L);
5417 // Get minetest.registered_on_chat_messages
5418 lua_getglobal(L, "minetest");
5419 lua_getfield(L, -1, "registered_on_chat_messages");
5421 lua_pushstring(L, name.c_str());
5422 lua_pushstring(L, message.c_str());
5423 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5424 bool ate = lua_toboolean(L, -1);
5428 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5431 assert(lua_checkstack(L, 20));
5432 StackUnroller stack_unroller(L);
5434 // Get minetest.registered_on_newplayers
5435 lua_getglobal(L, "minetest");
5436 lua_getfield(L, -1, "registered_on_newplayers");
5438 objectref_get_or_create(L, player);
5439 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5442 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5445 assert(lua_checkstack(L, 20));
5446 StackUnroller stack_unroller(L);
5448 // Get minetest.registered_on_dieplayers
5449 lua_getglobal(L, "minetest");
5450 lua_getfield(L, -1, "registered_on_dieplayers");
5452 objectref_get_or_create(L, player);
5453 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5456 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5459 assert(lua_checkstack(L, 20));
5460 StackUnroller stack_unroller(L);
5462 // Get minetest.registered_on_respawnplayers
5463 lua_getglobal(L, "minetest");
5464 lua_getfield(L, -1, "registered_on_respawnplayers");
5466 objectref_get_or_create(L, player);
5467 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5468 bool positioning_handled_by_some = lua_toboolean(L, -1);
5469 return positioning_handled_by_some;
5472 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5475 assert(lua_checkstack(L, 20));
5476 StackUnroller stack_unroller(L);
5478 // Get minetest.registered_on_joinplayers
5479 lua_getglobal(L, "minetest");
5480 lua_getfield(L, -1, "registered_on_joinplayers");
5482 objectref_get_or_create(L, player);
5483 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5486 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5489 assert(lua_checkstack(L, 20));
5490 StackUnroller stack_unroller(L);
5492 // Get minetest.registered_on_leaveplayers
5493 lua_getglobal(L, "minetest");
5494 lua_getfield(L, -1, "registered_on_leaveplayers");
5496 objectref_get_or_create(L, player);
5497 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5500 static void get_auth_handler(lua_State *L)
5502 lua_getglobal(L, "minetest");
5503 lua_getfield(L, -1, "registered_auth_handler");
5504 if(lua_isnil(L, -1)){
5506 lua_getfield(L, -1, "builtin_auth_handler");
5508 if(lua_type(L, -1) != LUA_TTABLE)
5509 throw LuaError(L, "Authentication handler table not valid");
5512 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5513 std::string *dst_password, std::set<std::string> *dst_privs)
5516 assert(lua_checkstack(L, 20));
5517 StackUnroller stack_unroller(L);
5519 get_auth_handler(L);
5520 lua_getfield(L, -1, "get_auth");
5521 if(lua_type(L, -1) != LUA_TFUNCTION)
5522 throw LuaError(L, "Authentication handler missing get_auth");
5523 lua_pushstring(L, playername.c_str());
5524 if(lua_pcall(L, 1, 1, 0))
5525 script_error(L, "error: %s", lua_tostring(L, -1));
5527 // nil = login not allowed
5528 if(lua_isnil(L, -1))
5530 luaL_checktype(L, -1, LUA_TTABLE);
5532 std::string password;
5533 bool found = getstringfield(L, -1, "password", password);
5535 throw LuaError(L, "Authentication handler didn't return password");
5537 *dst_password = password;
5539 lua_getfield(L, -1, "privileges");
5540 if(!lua_istable(L, -1))
5542 "Authentication handler didn't return privilege table");
5544 read_privileges(L, -1, *dst_privs);
5550 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5551 const std::string &password)
5554 assert(lua_checkstack(L, 20));
5555 StackUnroller stack_unroller(L);
5557 get_auth_handler(L);
5558 lua_getfield(L, -1, "create_auth");
5559 if(lua_type(L, -1) != LUA_TFUNCTION)
5560 throw LuaError(L, "Authentication handler missing create_auth");
5561 lua_pushstring(L, playername.c_str());
5562 lua_pushstring(L, password.c_str());
5563 if(lua_pcall(L, 2, 0, 0))
5564 script_error(L, "error: %s", lua_tostring(L, -1));
5567 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5568 const std::string &password)
5571 assert(lua_checkstack(L, 20));
5572 StackUnroller stack_unroller(L);
5574 get_auth_handler(L);
5575 lua_getfield(L, -1, "set_password");
5576 if(lua_type(L, -1) != LUA_TFUNCTION)
5577 throw LuaError(L, "Authentication handler missing set_password");
5578 lua_pushstring(L, playername.c_str());
5579 lua_pushstring(L, password.c_str());
5580 if(lua_pcall(L, 2, 1, 0))
5581 script_error(L, "error: %s", lua_tostring(L, -1));
5582 return lua_toboolean(L, -1);
5589 void scriptapi_on_player_receive_fields(lua_State *L,
5590 ServerActiveObject *player,
5591 const std::string &formname,
5592 const std::map<std::string, std::string> &fields)
5595 assert(lua_checkstack(L, 20));
5596 StackUnroller stack_unroller(L);
5598 // Get minetest.registered_on_chat_messages
5599 lua_getglobal(L, "minetest");
5600 lua_getfield(L, -1, "registered_on_player_receive_fields");
5603 objectref_get_or_create(L, player);
5605 lua_pushstring(L, formname.c_str());
5608 for(std::map<std::string, std::string>::const_iterator
5609 i = fields.begin(); i != fields.end(); i++){
5610 const std::string &name = i->first;
5611 const std::string &value = i->second;
5612 lua_pushstring(L, name.c_str());
5613 lua_pushlstring(L, value.c_str(), value.size());
5614 lua_settable(L, -3);
5616 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5620 item callbacks and node callbacks
5623 // Retrieves minetest.registered_items[name][callbackname]
5624 // If that is nil or on error, return false and stack is unchanged
5625 // If that is a function, returns true and pushes the
5626 // function onto the stack
5627 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5628 // is tried instead so unknown items can still be manipulated to some degree
5629 static bool get_item_callback(lua_State *L,
5630 const char *name, const char *callbackname)
5632 lua_getglobal(L, "minetest");
5633 lua_getfield(L, -1, "registered_items");
5635 luaL_checktype(L, -1, LUA_TTABLE);
5636 lua_getfield(L, -1, name);
5638 // Should be a table
5639 if(lua_type(L, -1) != LUA_TTABLE)
5641 // Report error and clean up
5642 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5645 // Try minetest.nodedef_default instead
5646 lua_getglobal(L, "minetest");
5647 lua_getfield(L, -1, "nodedef_default");
5649 luaL_checktype(L, -1, LUA_TTABLE);
5651 lua_getfield(L, -1, callbackname);
5653 // Should be a function or nil
5654 if(lua_type(L, -1) == LUA_TFUNCTION)
5658 else if(lua_isnil(L, -1))
5665 errorstream<<"Item \""<<name<<"\" callback \""
5666 <<callbackname<<" is not a function"<<std::endl;
5672 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5673 ServerActiveObject *dropper, v3f pos)
5676 assert(lua_checkstack(L, 20));
5677 StackUnroller stack_unroller(L);
5679 // Push callback function on stack
5680 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5684 LuaItemStack::create(L, item);
5685 objectref_get_or_create(L, dropper);
5686 pushFloatPos(L, pos);
5687 if(lua_pcall(L, 3, 1, 0))
5688 script_error(L, "error: %s", lua_tostring(L, -1));
5689 if(!lua_isnil(L, -1))
5690 item = read_item(L, -1);
5694 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5695 ServerActiveObject *placer, const PointedThing &pointed)
5698 assert(lua_checkstack(L, 20));
5699 StackUnroller stack_unroller(L);
5701 // Push callback function on stack
5702 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5706 LuaItemStack::create(L, item);
5707 objectref_get_or_create(L, placer);
5708 push_pointed_thing(L, pointed);
5709 if(lua_pcall(L, 3, 1, 0))
5710 script_error(L, "error: %s", lua_tostring(L, -1));
5711 if(!lua_isnil(L, -1))
5712 item = read_item(L, -1);
5716 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5717 ServerActiveObject *user, const PointedThing &pointed)
5720 assert(lua_checkstack(L, 20));
5721 StackUnroller stack_unroller(L);
5723 // Push callback function on stack
5724 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5728 LuaItemStack::create(L, item);
5729 objectref_get_or_create(L, user);
5730 push_pointed_thing(L, pointed);
5731 if(lua_pcall(L, 3, 1, 0))
5732 script_error(L, "error: %s", lua_tostring(L, -1));
5733 if(!lua_isnil(L, -1))
5734 item = read_item(L, -1);
5738 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5739 ServerActiveObject *puncher)
5742 assert(lua_checkstack(L, 20));
5743 StackUnroller stack_unroller(L);
5745 INodeDefManager *ndef = get_server(L)->ndef();
5747 // Push callback function on stack
5748 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5753 pushnode(L, node, ndef);
5754 objectref_get_or_create(L, puncher);
5755 if(lua_pcall(L, 3, 0, 0))
5756 script_error(L, "error: %s", lua_tostring(L, -1));
5760 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5761 ServerActiveObject *digger)
5764 assert(lua_checkstack(L, 20));
5765 StackUnroller stack_unroller(L);
5767 INodeDefManager *ndef = get_server(L)->ndef();
5769 // Push callback function on stack
5770 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5775 pushnode(L, node, ndef);
5776 objectref_get_or_create(L, digger);
5777 if(lua_pcall(L, 3, 0, 0))
5778 script_error(L, "error: %s", lua_tostring(L, -1));
5782 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5785 assert(lua_checkstack(L, 20));
5786 StackUnroller stack_unroller(L);
5788 INodeDefManager *ndef = get_server(L)->ndef();
5790 // Push callback function on stack
5791 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5796 if(lua_pcall(L, 1, 0, 0))
5797 script_error(L, "error: %s", lua_tostring(L, -1));
5800 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5803 assert(lua_checkstack(L, 20));
5804 StackUnroller stack_unroller(L);
5806 INodeDefManager *ndef = get_server(L)->ndef();
5808 // Push callback function on stack
5809 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5814 if(lua_pcall(L, 1, 0, 0))
5815 script_error(L, "error: %s", lua_tostring(L, -1));
5818 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5821 assert(lua_checkstack(L, 20));
5822 StackUnroller stack_unroller(L);
5824 INodeDefManager *ndef = get_server(L)->ndef();
5826 // Push callback function on stack
5827 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5832 pushnode(L, node, ndef);
5833 if(lua_pcall(L, 2, 0, 0))
5834 script_error(L, "error: %s", lua_tostring(L, -1));
5837 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5840 assert(lua_checkstack(L, 20));
5841 StackUnroller stack_unroller(L);
5843 INodeDefManager *ndef = get_server(L)->ndef();
5845 // Push callback function on stack
5846 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5851 lua_pushnumber(L,dtime);
5852 if(lua_pcall(L, 2, 1, 0))
5853 script_error(L, "error: %s", lua_tostring(L, -1));
5854 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5860 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5861 const std::string &formname,
5862 const std::map<std::string, std::string> &fields,
5863 ServerActiveObject *sender)
5866 assert(lua_checkstack(L, 20));
5867 StackUnroller stack_unroller(L);
5869 INodeDefManager *ndef = get_server(L)->ndef();
5871 // If node doesn't exist, we don't know what callback to call
5872 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5873 if(node.getContent() == CONTENT_IGNORE)
5876 // Push callback function on stack
5877 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5884 lua_pushstring(L, formname.c_str());
5887 for(std::map<std::string, std::string>::const_iterator
5888 i = fields.begin(); i != fields.end(); i++){
5889 const std::string &name = i->first;
5890 const std::string &value = i->second;
5891 lua_pushstring(L, name.c_str());
5892 lua_pushlstring(L, value.c_str(), value.size());
5893 lua_settable(L, -3);
5896 objectref_get_or_create(L, sender);
5897 if(lua_pcall(L, 4, 0, 0))
5898 script_error(L, "error: %s", lua_tostring(L, -1));
5902 Node metadata inventory callbacks
5905 // Return number of accepted items to be moved
5906 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5907 const std::string &from_list, int from_index,
5908 const std::string &to_list, int to_index,
5909 int count, ServerActiveObject *player)
5912 assert(lua_checkstack(L, 20));
5913 StackUnroller stack_unroller(L);
5915 INodeDefManager *ndef = get_server(L)->ndef();
5917 // If node doesn't exist, we don't know what callback to call
5918 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5919 if(node.getContent() == CONTENT_IGNORE)
5922 // Push callback function on stack
5923 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5924 "allow_metadata_inventory_move"))
5927 // function(pos, from_list, from_index, to_list, to_index, count, player)
5931 lua_pushstring(L, from_list.c_str());
5933 lua_pushinteger(L, from_index + 1);
5935 lua_pushstring(L, to_list.c_str());
5937 lua_pushinteger(L, to_index + 1);
5939 lua_pushinteger(L, count);
5941 objectref_get_or_create(L, player);
5942 if(lua_pcall(L, 7, 1, 0))
5943 script_error(L, "error: %s", lua_tostring(L, -1));
5944 if(!lua_isnumber(L, -1))
5945 throw LuaError(L, "allow_metadata_inventory_move should return a number");
5946 return luaL_checkinteger(L, -1);
5949 // Return number of accepted items to be put
5950 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
5951 const std::string &listname, int index, ItemStack &stack,
5952 ServerActiveObject *player)
5955 assert(lua_checkstack(L, 20));
5956 StackUnroller stack_unroller(L);
5958 INodeDefManager *ndef = get_server(L)->ndef();
5960 // If node doesn't exist, we don't know what callback to call
5961 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5962 if(node.getContent() == CONTENT_IGNORE)
5965 // Push callback function on stack
5966 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5967 "allow_metadata_inventory_put"))
5970 // Call function(pos, listname, index, stack, player)
5974 lua_pushstring(L, listname.c_str());
5976 lua_pushinteger(L, index + 1);
5978 LuaItemStack::create(L, stack);
5980 objectref_get_or_create(L, player);
5981 if(lua_pcall(L, 5, 1, 0))
5982 script_error(L, "error: %s", lua_tostring(L, -1));
5983 if(!lua_isnumber(L, -1))
5984 throw LuaError(L, "allow_metadata_inventory_put should return a number");
5985 return luaL_checkinteger(L, -1);
5988 // Return number of accepted items to be taken
5989 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
5990 const std::string &listname, int index, ItemStack &stack,
5991 ServerActiveObject *player)
5994 assert(lua_checkstack(L, 20));
5995 StackUnroller stack_unroller(L);
5997 INodeDefManager *ndef = get_server(L)->ndef();
5999 // If node doesn't exist, we don't know what callback to call
6000 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6001 if(node.getContent() == CONTENT_IGNORE)
6004 // Push callback function on stack
6005 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6006 "allow_metadata_inventory_take"))
6009 // Call function(pos, listname, index, count, player)
6013 lua_pushstring(L, listname.c_str());
6015 lua_pushinteger(L, index + 1);
6017 LuaItemStack::create(L, stack);
6019 objectref_get_or_create(L, player);
6020 if(lua_pcall(L, 5, 1, 0))
6021 script_error(L, "error: %s", lua_tostring(L, -1));
6022 if(!lua_isnumber(L, -1))
6023 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6024 return luaL_checkinteger(L, -1);
6027 // Report moved items
6028 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6029 const std::string &from_list, int from_index,
6030 const std::string &to_list, int to_index,
6031 int count, ServerActiveObject *player)
6034 assert(lua_checkstack(L, 20));
6035 StackUnroller stack_unroller(L);
6037 INodeDefManager *ndef = get_server(L)->ndef();
6039 // If node doesn't exist, we don't know what callback to call
6040 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6041 if(node.getContent() == CONTENT_IGNORE)
6044 // Push callback function on stack
6045 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6046 "on_metadata_inventory_move"))
6049 // function(pos, from_list, from_index, to_list, to_index, count, player)
6053 lua_pushstring(L, from_list.c_str());
6055 lua_pushinteger(L, from_index + 1);
6057 lua_pushstring(L, to_list.c_str());
6059 lua_pushinteger(L, to_index + 1);
6061 lua_pushinteger(L, count);
6063 objectref_get_or_create(L, player);
6064 if(lua_pcall(L, 7, 0, 0))
6065 script_error(L, "error: %s", lua_tostring(L, -1));
6069 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6070 const std::string &listname, int index, ItemStack &stack,
6071 ServerActiveObject *player)
6074 assert(lua_checkstack(L, 20));
6075 StackUnroller stack_unroller(L);
6077 INodeDefManager *ndef = get_server(L)->ndef();
6079 // If node doesn't exist, we don't know what callback to call
6080 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6081 if(node.getContent() == CONTENT_IGNORE)
6084 // Push callback function on stack
6085 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6086 "on_metadata_inventory_put"))
6089 // Call function(pos, listname, index, stack, player)
6093 lua_pushstring(L, listname.c_str());
6095 lua_pushinteger(L, index + 1);
6097 LuaItemStack::create(L, stack);
6099 objectref_get_or_create(L, player);
6100 if(lua_pcall(L, 5, 0, 0))
6101 script_error(L, "error: %s", lua_tostring(L, -1));
6104 // Report taken items
6105 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6106 const std::string &listname, int index, ItemStack &stack,
6107 ServerActiveObject *player)
6110 assert(lua_checkstack(L, 20));
6111 StackUnroller stack_unroller(L);
6113 INodeDefManager *ndef = get_server(L)->ndef();
6115 // If node doesn't exist, we don't know what callback to call
6116 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6117 if(node.getContent() == CONTENT_IGNORE)
6120 // Push callback function on stack
6121 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6122 "on_metadata_inventory_take"))
6125 // Call function(pos, listname, index, stack, player)
6129 lua_pushstring(L, listname.c_str());
6131 lua_pushinteger(L, index + 1);
6133 LuaItemStack::create(L, stack);
6135 objectref_get_or_create(L, player);
6136 if(lua_pcall(L, 5, 0, 0))
6137 script_error(L, "error: %s", lua_tostring(L, -1));
6141 Detached inventory callbacks
6144 // Retrieves minetest.detached_inventories[name][callbackname]
6145 // If that is nil or on error, return false and stack is unchanged
6146 // If that is a function, returns true and pushes the
6147 // function onto the stack
6148 static bool get_detached_inventory_callback(lua_State *L,
6149 const std::string &name, const char *callbackname)
6151 lua_getglobal(L, "minetest");
6152 lua_getfield(L, -1, "detached_inventories");
6154 luaL_checktype(L, -1, LUA_TTABLE);
6155 lua_getfield(L, -1, name.c_str());
6157 // Should be a table
6158 if(lua_type(L, -1) != LUA_TTABLE)
6160 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6164 lua_getfield(L, -1, callbackname);
6166 // Should be a function or nil
6167 if(lua_type(L, -1) == LUA_TFUNCTION)
6171 else if(lua_isnil(L, -1))
6178 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6179 <<callbackname<<"\" is not a function"<<std::endl;
6185 // Return number of accepted items to be moved
6186 int scriptapi_detached_inventory_allow_move(lua_State *L,
6187 const std::string &name,
6188 const std::string &from_list, int from_index,
6189 const std::string &to_list, int to_index,
6190 int count, ServerActiveObject *player)
6193 assert(lua_checkstack(L, 20));
6194 StackUnroller stack_unroller(L);
6196 // Push callback function on stack
6197 if(!get_detached_inventory_callback(L, name, "allow_move"))
6200 // function(inv, from_list, from_index, to_list, to_index, count, player)
6202 InventoryLocation loc;
6203 loc.setDetached(name);
6204 InvRef::create(L, loc);
6206 lua_pushstring(L, from_list.c_str());
6208 lua_pushinteger(L, from_index + 1);
6210 lua_pushstring(L, to_list.c_str());
6212 lua_pushinteger(L, to_index + 1);
6214 lua_pushinteger(L, count);
6216 objectref_get_or_create(L, player);
6217 if(lua_pcall(L, 7, 1, 0))
6218 script_error(L, "error: %s", lua_tostring(L, -1));
6219 if(!lua_isnumber(L, -1))
6220 throw LuaError(L, "allow_move should return a number");
6221 return luaL_checkinteger(L, -1);
6224 // Return number of accepted items to be put
6225 int scriptapi_detached_inventory_allow_put(lua_State *L,
6226 const std::string &name,
6227 const std::string &listname, int index, ItemStack &stack,
6228 ServerActiveObject *player)
6231 assert(lua_checkstack(L, 20));
6232 StackUnroller stack_unroller(L);
6234 // Push callback function on stack
6235 if(!get_detached_inventory_callback(L, name, "allow_put"))
6236 return stack.count; // All will be accepted
6238 // Call function(inv, listname, index, stack, player)
6240 InventoryLocation loc;
6241 loc.setDetached(name);
6242 InvRef::create(L, loc);
6244 lua_pushstring(L, listname.c_str());
6246 lua_pushinteger(L, index + 1);
6248 LuaItemStack::create(L, stack);
6250 objectref_get_or_create(L, player);
6251 if(lua_pcall(L, 5, 1, 0))
6252 script_error(L, "error: %s", lua_tostring(L, -1));
6253 if(!lua_isnumber(L, -1))
6254 throw LuaError(L, "allow_put should return a number");
6255 return luaL_checkinteger(L, -1);
6258 // Return number of accepted items to be taken
6259 int scriptapi_detached_inventory_allow_take(lua_State *L,
6260 const std::string &name,
6261 const std::string &listname, int index, ItemStack &stack,
6262 ServerActiveObject *player)
6265 assert(lua_checkstack(L, 20));
6266 StackUnroller stack_unroller(L);
6268 // Push callback function on stack
6269 if(!get_detached_inventory_callback(L, name, "allow_take"))
6270 return stack.count; // All will be accepted
6272 // Call function(inv, listname, index, stack, player)
6274 InventoryLocation loc;
6275 loc.setDetached(name);
6276 InvRef::create(L, loc);
6278 lua_pushstring(L, listname.c_str());
6280 lua_pushinteger(L, index + 1);
6282 LuaItemStack::create(L, stack);
6284 objectref_get_or_create(L, player);
6285 if(lua_pcall(L, 5, 1, 0))
6286 script_error(L, "error: %s", lua_tostring(L, -1));
6287 if(!lua_isnumber(L, -1))
6288 throw LuaError(L, "allow_take should return a number");
6289 return luaL_checkinteger(L, -1);
6292 // Report moved items
6293 void scriptapi_detached_inventory_on_move(lua_State *L,
6294 const std::string &name,
6295 const std::string &from_list, int from_index,
6296 const std::string &to_list, int to_index,
6297 int count, ServerActiveObject *player)
6300 assert(lua_checkstack(L, 20));
6301 StackUnroller stack_unroller(L);
6303 // Push callback function on stack
6304 if(!get_detached_inventory_callback(L, name, "on_move"))
6307 // function(inv, from_list, from_index, to_list, to_index, count, player)
6309 InventoryLocation loc;
6310 loc.setDetached(name);
6311 InvRef::create(L, loc);
6313 lua_pushstring(L, from_list.c_str());
6315 lua_pushinteger(L, from_index + 1);
6317 lua_pushstring(L, to_list.c_str());
6319 lua_pushinteger(L, to_index + 1);
6321 lua_pushinteger(L, count);
6323 objectref_get_or_create(L, player);
6324 if(lua_pcall(L, 7, 0, 0))
6325 script_error(L, "error: %s", lua_tostring(L, -1));
6329 void scriptapi_detached_inventory_on_put(lua_State *L,
6330 const std::string &name,
6331 const std::string &listname, int index, ItemStack &stack,
6332 ServerActiveObject *player)
6335 assert(lua_checkstack(L, 20));
6336 StackUnroller stack_unroller(L);
6338 // Push callback function on stack
6339 if(!get_detached_inventory_callback(L, name, "on_put"))
6342 // Call function(inv, listname, index, stack, player)
6344 InventoryLocation loc;
6345 loc.setDetached(name);
6346 InvRef::create(L, loc);
6348 lua_pushstring(L, listname.c_str());
6350 lua_pushinteger(L, index + 1);
6352 LuaItemStack::create(L, stack);
6354 objectref_get_or_create(L, player);
6355 if(lua_pcall(L, 5, 0, 0))
6356 script_error(L, "error: %s", lua_tostring(L, -1));
6359 // Report taken items
6360 void scriptapi_detached_inventory_on_take(lua_State *L,
6361 const std::string &name,
6362 const std::string &listname, int index, ItemStack &stack,
6363 ServerActiveObject *player)
6366 assert(lua_checkstack(L, 20));
6367 StackUnroller stack_unroller(L);
6369 // Push callback function on stack
6370 if(!get_detached_inventory_callback(L, name, "on_take"))
6373 // Call function(inv, listname, index, stack, player)
6375 InventoryLocation loc;
6376 loc.setDetached(name);
6377 InvRef::create(L, loc);
6379 lua_pushstring(L, listname.c_str());
6381 lua_pushinteger(L, index + 1);
6383 LuaItemStack::create(L, stack);
6385 objectref_get_or_create(L, player);
6386 if(lua_pcall(L, 5, 0, 0))
6387 script_error(L, "error: %s", lua_tostring(L, -1));
6394 void scriptapi_environment_step(lua_State *L, float dtime)
6397 assert(lua_checkstack(L, 20));
6398 //infostream<<"scriptapi_environment_step"<<std::endl;
6399 StackUnroller stack_unroller(L);
6401 // Get minetest.registered_globalsteps
6402 lua_getglobal(L, "minetest");
6403 lua_getfield(L, -1, "registered_globalsteps");
6405 lua_pushnumber(L, dtime);
6406 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6409 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6413 assert(lua_checkstack(L, 20));
6414 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6415 StackUnroller stack_unroller(L);
6417 // Get minetest.registered_on_generateds
6418 lua_getglobal(L, "minetest");
6419 lua_getfield(L, -1, "registered_on_generateds");
6421 push_v3s16(L, minp);
6422 push_v3s16(L, maxp);
6423 lua_pushnumber(L, blockseed);
6424 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6431 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6434 assert(lua_checkstack(L, 20));
6435 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6436 <<name<<"\""<<std::endl;
6437 StackUnroller stack_unroller(L);
6439 // Get minetest.registered_entities[name]
6440 lua_getglobal(L, "minetest");
6441 lua_getfield(L, -1, "registered_entities");
6442 luaL_checktype(L, -1, LUA_TTABLE);
6443 lua_pushstring(L, name);
6444 lua_gettable(L, -2);
6445 // Should be a table, which we will use as a prototype
6446 //luaL_checktype(L, -1, LUA_TTABLE);
6447 if(lua_type(L, -1) != LUA_TTABLE){
6448 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6451 int prototype_table = lua_gettop(L);
6452 //dump2(L, "prototype_table");
6454 // Create entity object
6456 int object = lua_gettop(L);
6458 // Set object metatable
6459 lua_pushvalue(L, prototype_table);
6460 lua_setmetatable(L, -2);
6462 // Add object reference
6463 // This should be userdata with metatable ObjectRef
6464 objectref_get(L, id);
6465 luaL_checktype(L, -1, LUA_TUSERDATA);
6466 if(!luaL_checkudata(L, -1, "ObjectRef"))
6467 luaL_typerror(L, -1, "ObjectRef");
6468 lua_setfield(L, -2, "object");
6470 // minetest.luaentities[id] = object
6471 lua_getglobal(L, "minetest");
6472 lua_getfield(L, -1, "luaentities");
6473 luaL_checktype(L, -1, LUA_TTABLE);
6474 lua_pushnumber(L, id); // Push id
6475 lua_pushvalue(L, object); // Copy object to top of stack
6476 lua_settable(L, -3);
6481 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6482 const std::string &staticdata)
6485 assert(lua_checkstack(L, 20));
6486 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6487 StackUnroller stack_unroller(L);
6489 // Get minetest.luaentities[id]
6490 luaentity_get(L, id);
6491 int object = lua_gettop(L);
6493 // Get on_activate function
6494 lua_pushvalue(L, object);
6495 lua_getfield(L, -1, "on_activate");
6496 if(!lua_isnil(L, -1)){
6497 luaL_checktype(L, -1, LUA_TFUNCTION);
6498 lua_pushvalue(L, object); // self
6499 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6500 // Call with 2 arguments, 0 results
6501 if(lua_pcall(L, 2, 0, 0))
6502 script_error(L, "error running function on_activate: %s\n",
6503 lua_tostring(L, -1));
6507 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6510 assert(lua_checkstack(L, 20));
6511 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6513 // Get minetest.luaentities table
6514 lua_getglobal(L, "minetest");
6515 lua_getfield(L, -1, "luaentities");
6516 luaL_checktype(L, -1, LUA_TTABLE);
6517 int objectstable = lua_gettop(L);
6519 // Set luaentities[id] = nil
6520 lua_pushnumber(L, id); // Push id
6522 lua_settable(L, objectstable);
6524 lua_pop(L, 2); // pop luaentities, minetest
6527 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6530 assert(lua_checkstack(L, 20));
6531 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6532 StackUnroller stack_unroller(L);
6534 // Get minetest.luaentities[id]
6535 luaentity_get(L, id);
6536 int object = lua_gettop(L);
6538 // Get get_staticdata function
6539 lua_pushvalue(L, object);
6540 lua_getfield(L, -1, "get_staticdata");
6541 if(lua_isnil(L, -1))
6544 luaL_checktype(L, -1, LUA_TFUNCTION);
6545 lua_pushvalue(L, object); // self
6546 // Call with 1 arguments, 1 results
6547 if(lua_pcall(L, 1, 1, 0))
6548 script_error(L, "error running function get_staticdata: %s\n",
6549 lua_tostring(L, -1));
6552 const char *s = lua_tolstring(L, -1, &len);
6553 return std::string(s, len);
6556 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6557 ObjectProperties *prop)
6560 assert(lua_checkstack(L, 20));
6561 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6562 StackUnroller stack_unroller(L);
6564 // Get minetest.luaentities[id]
6565 luaentity_get(L, id);
6566 //int object = lua_gettop(L);
6568 // Set default values that differ from ObjectProperties defaults
6573 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6575 getboolfield(L, -1, "physical", prop->physical);
6577 getfloatfield(L, -1, "weight", prop->weight);
6579 lua_getfield(L, -1, "collisionbox");
6580 if(lua_istable(L, -1))
6581 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6584 getstringfield(L, -1, "visual", prop->visual);
6586 // Deprecated: read object properties directly
6587 read_object_properties(L, -1, prop);
6589 // Read initial_properties
6590 lua_getfield(L, -1, "initial_properties");
6591 read_object_properties(L, -1, prop);
6595 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6598 assert(lua_checkstack(L, 20));
6599 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6600 StackUnroller stack_unroller(L);
6602 // Get minetest.luaentities[id]
6603 luaentity_get(L, id);
6604 int object = lua_gettop(L);
6605 // State: object is at top of stack
6606 // Get step function
6607 lua_getfield(L, -1, "on_step");
6608 if(lua_isnil(L, -1))
6610 luaL_checktype(L, -1, LUA_TFUNCTION);
6611 lua_pushvalue(L, object); // self
6612 lua_pushnumber(L, dtime); // dtime
6613 // Call with 2 arguments, 0 results
6614 if(lua_pcall(L, 2, 0, 0))
6615 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6618 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6619 // tool_capabilities, direction)
6620 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6621 ServerActiveObject *puncher, float time_from_last_punch,
6622 const ToolCapabilities *toolcap, v3f dir)
6625 assert(lua_checkstack(L, 20));
6626 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6627 StackUnroller stack_unroller(L);
6629 // Get minetest.luaentities[id]
6630 luaentity_get(L, id);
6631 int object = lua_gettop(L);
6632 // State: object is at top of stack
6634 lua_getfield(L, -1, "on_punch");
6635 if(lua_isnil(L, -1))
6637 luaL_checktype(L, -1, LUA_TFUNCTION);
6638 lua_pushvalue(L, object); // self
6639 objectref_get_or_create(L, puncher); // Clicker reference
6640 lua_pushnumber(L, time_from_last_punch);
6641 push_tool_capabilities(L, *toolcap);
6643 // Call with 5 arguments, 0 results
6644 if(lua_pcall(L, 5, 0, 0))
6645 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6648 // Calls entity:on_rightclick(ObjectRef clicker)
6649 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6650 ServerActiveObject *clicker)
6653 assert(lua_checkstack(L, 20));
6654 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6655 StackUnroller stack_unroller(L);
6657 // Get minetest.luaentities[id]
6658 luaentity_get(L, id);
6659 int object = lua_gettop(L);
6660 // State: object is at top of stack
6662 lua_getfield(L, -1, "on_rightclick");
6663 if(lua_isnil(L, -1))
6665 luaL_checktype(L, -1, LUA_TFUNCTION);
6666 lua_pushvalue(L, object); // self
6667 objectref_get_or_create(L, clicker); // Clicker reference
6668 // Call with 2 arguments, 0 results
6669 if(lua_pcall(L, 2, 0, 0))
6670 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));