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, time_from_last_punch, tool_capabilities, dir)
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;
2556 if(lua_type(L, 5) != LUA_TTABLE)
2557 dir = co->getBasePosition() - puncher->getBasePosition();
2559 dir = read_v3f(L, 5);
2560 float time_from_last_punch = 1000000;
2561 if(lua_isnumber(L, 3))
2562 time_from_last_punch = lua_tonumber(L, 3);
2563 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2566 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2570 // right_click(self, clicker); clicker = an another ObjectRef
2571 static int l_right_click(lua_State *L)
2573 ObjectRef *ref = checkobject(L, 1);
2574 ObjectRef *ref2 = checkobject(L, 2);
2575 ServerActiveObject *co = getobject(ref);
2576 ServerActiveObject *co2 = getobject(ref2);
2577 if(co == NULL) return 0;
2578 if(co2 == NULL) return 0;
2580 co->rightClick(co2);
2585 // hp = number of hitpoints (2 * number of hearts)
2587 static int l_set_hp(lua_State *L)
2589 ObjectRef *ref = checkobject(L, 1);
2590 luaL_checknumber(L, 2);
2591 ServerActiveObject *co = getobject(ref);
2592 if(co == NULL) return 0;
2593 int hp = lua_tonumber(L, 2);
2594 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2595 <<" hp="<<hp<<std::endl;*/
2603 // returns: number of hitpoints (2 * number of hearts)
2604 // 0 if not applicable to this type of object
2605 static int l_get_hp(lua_State *L)
2607 ObjectRef *ref = checkobject(L, 1);
2608 ServerActiveObject *co = getobject(ref);
2611 lua_pushnumber(L, 1);
2614 int hp = co->getHP();
2615 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2616 <<" hp="<<hp<<std::endl;*/
2618 lua_pushnumber(L, hp);
2622 // get_inventory(self)
2623 static int l_get_inventory(lua_State *L)
2625 ObjectRef *ref = checkobject(L, 1);
2626 ServerActiveObject *co = getobject(ref);
2627 if(co == NULL) return 0;
2629 InventoryLocation loc = co->getInventoryLocation();
2630 if(get_server(L)->getInventory(loc) != NULL)
2631 InvRef::create(L, loc);
2633 lua_pushnil(L); // An object may have no inventory (nil)
2637 // get_wield_list(self)
2638 static int l_get_wield_list(lua_State *L)
2640 ObjectRef *ref = checkobject(L, 1);
2641 ServerActiveObject *co = getobject(ref);
2642 if(co == NULL) return 0;
2644 lua_pushstring(L, co->getWieldList().c_str());
2648 // get_wield_index(self)
2649 static int l_get_wield_index(lua_State *L)
2651 ObjectRef *ref = checkobject(L, 1);
2652 ServerActiveObject *co = getobject(ref);
2653 if(co == NULL) return 0;
2655 lua_pushinteger(L, co->getWieldIndex() + 1);
2659 // get_wielded_item(self)
2660 static int l_get_wielded_item(lua_State *L)
2662 ObjectRef *ref = checkobject(L, 1);
2663 ServerActiveObject *co = getobject(ref);
2666 LuaItemStack::create(L, ItemStack());
2670 LuaItemStack::create(L, co->getWieldedItem());
2674 // set_wielded_item(self, itemstack or itemstring or table or nil)
2675 static int l_set_wielded_item(lua_State *L)
2677 ObjectRef *ref = checkobject(L, 1);
2678 ServerActiveObject *co = getobject(ref);
2679 if(co == NULL) return 0;
2681 ItemStack item = read_item(L, 2);
2682 bool success = co->setWieldedItem(item);
2683 lua_pushboolean(L, success);
2687 // set_armor_groups(self, groups)
2688 static int l_set_armor_groups(lua_State *L)
2690 ObjectRef *ref = checkobject(L, 1);
2691 ServerActiveObject *co = getobject(ref);
2692 if(co == NULL) return 0;
2694 ItemGroupList groups;
2695 read_groups(L, 2, groups);
2696 co->setArmorGroups(groups);
2700 // set_properties(self, properties)
2701 static int l_set_properties(lua_State *L)
2703 ObjectRef *ref = checkobject(L, 1);
2704 ServerActiveObject *co = getobject(ref);
2705 if(co == NULL) return 0;
2706 ObjectProperties *prop = co->accessObjectProperties();
2709 read_object_properties(L, 2, prop);
2710 co->notifyObjectPropertiesModified();
2714 /* LuaEntitySAO-only */
2716 // setvelocity(self, {x=num, y=num, z=num})
2717 static int l_setvelocity(lua_State *L)
2719 ObjectRef *ref = checkobject(L, 1);
2720 LuaEntitySAO *co = getluaobject(ref);
2721 if(co == NULL) return 0;
2722 v3f pos = checkFloatPos(L, 2);
2724 co->setVelocity(pos);
2728 // getvelocity(self)
2729 static int l_getvelocity(lua_State *L)
2731 ObjectRef *ref = checkobject(L, 1);
2732 LuaEntitySAO *co = getluaobject(ref);
2733 if(co == NULL) return 0;
2735 v3f v = co->getVelocity();
2740 // setacceleration(self, {x=num, y=num, z=num})
2741 static int l_setacceleration(lua_State *L)
2743 ObjectRef *ref = checkobject(L, 1);
2744 LuaEntitySAO *co = getluaobject(ref);
2745 if(co == NULL) return 0;
2747 v3f pos = checkFloatPos(L, 2);
2749 co->setAcceleration(pos);
2753 // getacceleration(self)
2754 static int l_getacceleration(lua_State *L)
2756 ObjectRef *ref = checkobject(L, 1);
2757 LuaEntitySAO *co = getluaobject(ref);
2758 if(co == NULL) return 0;
2760 v3f v = co->getAcceleration();
2765 // setyaw(self, radians)
2766 static int l_setyaw(lua_State *L)
2768 ObjectRef *ref = checkobject(L, 1);
2769 LuaEntitySAO *co = getluaobject(ref);
2770 if(co == NULL) return 0;
2771 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2778 static int l_getyaw(lua_State *L)
2780 ObjectRef *ref = checkobject(L, 1);
2781 LuaEntitySAO *co = getluaobject(ref);
2782 if(co == NULL) return 0;
2784 float yaw = co->getYaw() * core::DEGTORAD;
2785 lua_pushnumber(L, yaw);
2789 // settexturemod(self, mod)
2790 static int l_settexturemod(lua_State *L)
2792 ObjectRef *ref = checkobject(L, 1);
2793 LuaEntitySAO *co = getluaobject(ref);
2794 if(co == NULL) return 0;
2796 std::string mod = luaL_checkstring(L, 2);
2797 co->setTextureMod(mod);
2801 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2802 // select_horiz_by_yawpitch=false)
2803 static int l_setsprite(lua_State *L)
2805 ObjectRef *ref = checkobject(L, 1);
2806 LuaEntitySAO *co = getluaobject(ref);
2807 if(co == NULL) return 0;
2810 if(!lua_isnil(L, 2))
2811 p = read_v2s16(L, 2);
2813 if(!lua_isnil(L, 3))
2814 num_frames = lua_tonumber(L, 3);
2815 float framelength = 0.2;
2816 if(!lua_isnil(L, 4))
2817 framelength = lua_tonumber(L, 4);
2818 bool select_horiz_by_yawpitch = false;
2819 if(!lua_isnil(L, 5))
2820 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2821 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2826 // get_entity_name(self)
2827 static int l_get_entity_name(lua_State *L)
2829 ObjectRef *ref = checkobject(L, 1);
2830 LuaEntitySAO *co = getluaobject(ref);
2831 if(co == NULL) return 0;
2833 std::string name = co->getName();
2834 lua_pushstring(L, name.c_str());
2838 // get_luaentity(self)
2839 static int l_get_luaentity(lua_State *L)
2841 ObjectRef *ref = checkobject(L, 1);
2842 LuaEntitySAO *co = getluaobject(ref);
2843 if(co == NULL) return 0;
2845 luaentity_get(L, co->getId());
2852 static int l_is_player(lua_State *L)
2854 ObjectRef *ref = checkobject(L, 1);
2855 Player *player = getplayer(ref);
2856 lua_pushboolean(L, (player != NULL));
2860 // get_player_name(self)
2861 static int l_get_player_name(lua_State *L)
2863 ObjectRef *ref = checkobject(L, 1);
2864 Player *player = getplayer(ref);
2866 lua_pushlstring(L, "", 0);
2870 lua_pushstring(L, player->getName());
2874 // get_look_dir(self)
2875 static int l_get_look_dir(lua_State *L)
2877 ObjectRef *ref = checkobject(L, 1);
2878 Player *player = getplayer(ref);
2879 if(player == NULL) return 0;
2881 float pitch = player->getRadPitch();
2882 float yaw = player->getRadYaw();
2883 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2888 // get_look_pitch(self)
2889 static int l_get_look_pitch(lua_State *L)
2891 ObjectRef *ref = checkobject(L, 1);
2892 Player *player = getplayer(ref);
2893 if(player == NULL) return 0;
2895 lua_pushnumber(L, player->getRadPitch());
2899 // get_look_yaw(self)
2900 static int l_get_look_yaw(lua_State *L)
2902 ObjectRef *ref = checkobject(L, 1);
2903 Player *player = getplayer(ref);
2904 if(player == NULL) return 0;
2906 lua_pushnumber(L, player->getRadYaw());
2910 // set_inventory_formspec(self, formspec)
2911 static int l_set_inventory_formspec(lua_State *L)
2913 ObjectRef *ref = checkobject(L, 1);
2914 Player *player = getplayer(ref);
2915 if(player == NULL) return 0;
2916 std::string formspec = luaL_checkstring(L, 2);
2918 player->inventory_formspec = formspec;
2919 get_server(L)->reportInventoryFormspecModified(player->getName());
2920 lua_pushboolean(L, true);
2924 // get_inventory_formspec(self) -> formspec
2925 static int l_get_inventory_formspec(lua_State *L)
2927 ObjectRef *ref = checkobject(L, 1);
2928 Player *player = getplayer(ref);
2929 if(player == NULL) return 0;
2931 std::string formspec = player->inventory_formspec;
2932 lua_pushlstring(L, formspec.c_str(), formspec.size());
2937 ObjectRef(ServerActiveObject *object):
2940 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2946 infostream<<"ObjectRef destructing for id="
2947 <<m_object->getId()<<std::endl;
2949 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2952 // Creates an ObjectRef and leaves it on top of stack
2953 // Not callable from Lua; all references are created on the C side.
2954 static void create(lua_State *L, ServerActiveObject *object)
2956 ObjectRef *o = new ObjectRef(object);
2957 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2958 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2959 luaL_getmetatable(L, className);
2960 lua_setmetatable(L, -2);
2963 static void set_null(lua_State *L)
2965 ObjectRef *o = checkobject(L, -1);
2969 static void Register(lua_State *L)
2972 int methodtable = lua_gettop(L);
2973 luaL_newmetatable(L, className);
2974 int metatable = lua_gettop(L);
2976 lua_pushliteral(L, "__metatable");
2977 lua_pushvalue(L, methodtable);
2978 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2980 lua_pushliteral(L, "__index");
2981 lua_pushvalue(L, methodtable);
2982 lua_settable(L, metatable);
2984 lua_pushliteral(L, "__gc");
2985 lua_pushcfunction(L, gc_object);
2986 lua_settable(L, metatable);
2988 lua_pop(L, 1); // drop metatable
2990 luaL_openlib(L, 0, methods, 0); // fill methodtable
2991 lua_pop(L, 1); // drop methodtable
2993 // Cannot be created from Lua
2994 //lua_register(L, className, create_object);
2997 const char ObjectRef::className[] = "ObjectRef";
2998 const luaL_reg ObjectRef::methods[] = {
2999 // ServerActiveObject
3000 method(ObjectRef, remove),
3001 method(ObjectRef, getpos),
3002 method(ObjectRef, setpos),
3003 method(ObjectRef, moveto),
3004 method(ObjectRef, punch),
3005 method(ObjectRef, right_click),
3006 method(ObjectRef, set_hp),
3007 method(ObjectRef, get_hp),
3008 method(ObjectRef, get_inventory),
3009 method(ObjectRef, get_wield_list),
3010 method(ObjectRef, get_wield_index),
3011 method(ObjectRef, get_wielded_item),
3012 method(ObjectRef, set_wielded_item),
3013 method(ObjectRef, set_armor_groups),
3014 method(ObjectRef, set_properties),
3015 // LuaEntitySAO-only
3016 method(ObjectRef, setvelocity),
3017 method(ObjectRef, getvelocity),
3018 method(ObjectRef, setacceleration),
3019 method(ObjectRef, getacceleration),
3020 method(ObjectRef, setyaw),
3021 method(ObjectRef, getyaw),
3022 method(ObjectRef, settexturemod),
3023 method(ObjectRef, setsprite),
3024 method(ObjectRef, get_entity_name),
3025 method(ObjectRef, get_luaentity),
3027 method(ObjectRef, is_player),
3028 method(ObjectRef, get_player_name),
3029 method(ObjectRef, get_look_dir),
3030 method(ObjectRef, get_look_pitch),
3031 method(ObjectRef, get_look_yaw),
3032 method(ObjectRef, set_inventory_formspec),
3033 method(ObjectRef, get_inventory_formspec),
3037 // Creates a new anonymous reference if cobj=NULL or id=0
3038 static void objectref_get_or_create(lua_State *L,
3039 ServerActiveObject *cobj)
3041 if(cobj == NULL || cobj->getId() == 0){
3042 ObjectRef::create(L, cobj);
3044 objectref_get(L, cobj->getId());
3053 class LuaPerlinNoise
3060 static const char className[];
3061 static const luaL_reg methods[];
3063 // Exported functions
3065 // garbage collector
3066 static int gc_object(lua_State *L)
3068 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3073 static int l_get2d(lua_State *L)
3075 LuaPerlinNoise *o = checkobject(L, 1);
3076 v2f pos2d = read_v2f(L,2);
3077 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3078 lua_pushnumber(L, val);
3081 static int l_get3d(lua_State *L)
3083 LuaPerlinNoise *o = checkobject(L, 1);
3084 v3f pos3d = read_v3f(L,2);
3085 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3086 lua_pushnumber(L, val);
3091 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3095 persistence(a_persistence),
3104 // LuaPerlinNoise(seed, octaves, persistence, scale)
3105 // Creates an LuaPerlinNoise and leaves it on top of stack
3106 static int create_object(lua_State *L)
3108 int seed = luaL_checkint(L, 1);
3109 int octaves = luaL_checkint(L, 2);
3110 double persistence = luaL_checknumber(L, 3);
3111 double scale = luaL_checknumber(L, 4);
3112 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3113 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3114 luaL_getmetatable(L, className);
3115 lua_setmetatable(L, -2);
3119 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3121 luaL_checktype(L, narg, LUA_TUSERDATA);
3122 void *ud = luaL_checkudata(L, narg, className);
3123 if(!ud) luaL_typerror(L, narg, className);
3124 return *(LuaPerlinNoise**)ud; // unbox pointer
3127 static void Register(lua_State *L)
3130 int methodtable = lua_gettop(L);
3131 luaL_newmetatable(L, className);
3132 int metatable = lua_gettop(L);
3134 lua_pushliteral(L, "__metatable");
3135 lua_pushvalue(L, methodtable);
3136 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3138 lua_pushliteral(L, "__index");
3139 lua_pushvalue(L, methodtable);
3140 lua_settable(L, metatable);
3142 lua_pushliteral(L, "__gc");
3143 lua_pushcfunction(L, gc_object);
3144 lua_settable(L, metatable);
3146 lua_pop(L, 1); // drop metatable
3148 luaL_openlib(L, 0, methods, 0); // fill methodtable
3149 lua_pop(L, 1); // drop methodtable
3151 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3152 lua_register(L, className, create_object);
3155 const char LuaPerlinNoise::className[] = "PerlinNoise";
3156 const luaL_reg LuaPerlinNoise::methods[] = {
3157 method(LuaPerlinNoise, get2d),
3158 method(LuaPerlinNoise, get3d),
3170 ServerEnvironment *m_env;
3172 static const char className[];
3173 static const luaL_reg methods[];
3175 static int gc_object(lua_State *L) {
3176 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3181 static NodeTimerRef *checkobject(lua_State *L, int narg)
3183 luaL_checktype(L, narg, LUA_TUSERDATA);
3184 void *ud = luaL_checkudata(L, narg, className);
3185 if(!ud) luaL_typerror(L, narg, className);
3186 return *(NodeTimerRef**)ud; // unbox pointer
3189 static int l_set(lua_State *L)
3191 NodeTimerRef *o = checkobject(L, 1);
3192 ServerEnvironment *env = o->m_env;
3193 if(env == NULL) return 0;
3194 f32 t = luaL_checknumber(L,2);
3195 f32 e = luaL_checknumber(L,3);
3196 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3200 static int l_start(lua_State *L)
3202 NodeTimerRef *o = checkobject(L, 1);
3203 ServerEnvironment *env = o->m_env;
3204 if(env == NULL) return 0;
3205 f32 t = luaL_checknumber(L,2);
3206 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3210 static int l_stop(lua_State *L)
3212 NodeTimerRef *o = checkobject(L, 1);
3213 ServerEnvironment *env = o->m_env;
3214 if(env == NULL) return 0;
3215 env->getMap().removeNodeTimer(o->m_p);
3219 static int l_is_started(lua_State *L)
3221 NodeTimerRef *o = checkobject(L, 1);
3222 ServerEnvironment *env = o->m_env;
3223 if(env == NULL) return 0;
3225 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3226 lua_pushboolean(L,(t.timeout != 0));
3230 static int l_get_timeout(lua_State *L)
3232 NodeTimerRef *o = checkobject(L, 1);
3233 ServerEnvironment *env = o->m_env;
3234 if(env == NULL) return 0;
3236 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3237 lua_pushnumber(L,t.timeout);
3241 static int l_get_elapsed(lua_State *L)
3243 NodeTimerRef *o = checkobject(L, 1);
3244 ServerEnvironment *env = o->m_env;
3245 if(env == NULL) return 0;
3247 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3248 lua_pushnumber(L,t.elapsed);
3253 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3263 // Creates an NodeTimerRef and leaves it on top of stack
3264 // Not callable from Lua; all references are created on the C side.
3265 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3267 NodeTimerRef *o = new NodeTimerRef(p, env);
3268 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3269 luaL_getmetatable(L, className);
3270 lua_setmetatable(L, -2);
3273 static void set_null(lua_State *L)
3275 NodeTimerRef *o = checkobject(L, -1);
3279 static void Register(lua_State *L)
3282 int methodtable = lua_gettop(L);
3283 luaL_newmetatable(L, className);
3284 int metatable = lua_gettop(L);
3286 lua_pushliteral(L, "__metatable");
3287 lua_pushvalue(L, methodtable);
3288 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3290 lua_pushliteral(L, "__index");
3291 lua_pushvalue(L, methodtable);
3292 lua_settable(L, metatable);
3294 lua_pushliteral(L, "__gc");
3295 lua_pushcfunction(L, gc_object);
3296 lua_settable(L, metatable);
3298 lua_pop(L, 1); // drop metatable
3300 luaL_openlib(L, 0, methods, 0); // fill methodtable
3301 lua_pop(L, 1); // drop methodtable
3303 // Cannot be created from Lua
3304 //lua_register(L, className, create_object);
3307 const char NodeTimerRef::className[] = "NodeTimerRef";
3308 const luaL_reg NodeTimerRef::methods[] = {
3309 method(NodeTimerRef, start),
3310 method(NodeTimerRef, set),
3311 method(NodeTimerRef, stop),
3312 method(NodeTimerRef, is_started),
3313 method(NodeTimerRef, get_timeout),
3314 method(NodeTimerRef, get_elapsed),
3325 ServerEnvironment *m_env;
3327 static const char className[];
3328 static const luaL_reg methods[];
3330 static int gc_object(lua_State *L) {
3331 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3336 static EnvRef *checkobject(lua_State *L, int narg)
3338 luaL_checktype(L, narg, LUA_TUSERDATA);
3339 void *ud = luaL_checkudata(L, narg, className);
3340 if(!ud) luaL_typerror(L, narg, className);
3341 return *(EnvRef**)ud; // unbox pointer
3344 // Exported functions
3346 // EnvRef:set_node(pos, node)
3347 // pos = {x=num, y=num, z=num}
3348 static int l_set_node(lua_State *L)
3350 EnvRef *o = checkobject(L, 1);
3351 ServerEnvironment *env = o->m_env;
3352 if(env == NULL) return 0;
3353 INodeDefManager *ndef = env->getGameDef()->ndef();
3355 v3s16 pos = read_v3s16(L, 2);
3356 MapNode n = readnode(L, 3, ndef);
3358 MapNode n_old = env->getMap().getNodeNoEx(pos);
3360 if(ndef->get(n_old).has_on_destruct)
3361 scriptapi_node_on_destruct(L, pos, n_old);
3363 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3365 // Call post-destructor
3366 if(ndef->get(n_old).has_after_destruct)
3367 scriptapi_node_after_destruct(L, pos, n_old);
3369 if(ndef->get(n).has_on_construct)
3370 scriptapi_node_on_construct(L, pos, n);
3372 lua_pushboolean(L, succeeded);
3376 static int l_add_node(lua_State *L)
3378 return l_set_node(L);
3381 // EnvRef:remove_node(pos)
3382 // pos = {x=num, y=num, z=num}
3383 static int l_remove_node(lua_State *L)
3385 EnvRef *o = checkobject(L, 1);
3386 ServerEnvironment *env = o->m_env;
3387 if(env == NULL) return 0;
3388 INodeDefManager *ndef = env->getGameDef()->ndef();
3390 v3s16 pos = read_v3s16(L, 2);
3392 MapNode n_old = env->getMap().getNodeNoEx(pos);
3394 if(ndef->get(n_old).has_on_destruct)
3395 scriptapi_node_on_destruct(L, pos, n_old);
3397 // This is slightly optimized compared to addNodeWithEvent(air)
3398 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3400 // Call post-destructor
3401 if(ndef->get(n_old).has_after_destruct)
3402 scriptapi_node_after_destruct(L, pos, n_old);
3404 lua_pushboolean(L, succeeded);
3405 // Air doesn't require constructor
3409 // EnvRef:get_node(pos)
3410 // pos = {x=num, y=num, z=num}
3411 static int l_get_node(lua_State *L)
3413 EnvRef *o = checkobject(L, 1);
3414 ServerEnvironment *env = o->m_env;
3415 if(env == NULL) return 0;
3417 v3s16 pos = read_v3s16(L, 2);
3419 MapNode n = env->getMap().getNodeNoEx(pos);
3421 pushnode(L, n, env->getGameDef()->ndef());
3425 // EnvRef:get_node_or_nil(pos)
3426 // pos = {x=num, y=num, z=num}
3427 static int l_get_node_or_nil(lua_State *L)
3429 EnvRef *o = checkobject(L, 1);
3430 ServerEnvironment *env = o->m_env;
3431 if(env == NULL) return 0;
3433 v3s16 pos = read_v3s16(L, 2);
3436 MapNode n = env->getMap().getNode(pos);
3438 pushnode(L, n, env->getGameDef()->ndef());
3440 } catch(InvalidPositionException &e)
3447 // EnvRef:get_node_light(pos, timeofday)
3448 // pos = {x=num, y=num, z=num}
3449 // timeofday: nil = current time, 0 = night, 0.5 = day
3450 static int l_get_node_light(lua_State *L)
3452 EnvRef *o = checkobject(L, 1);
3453 ServerEnvironment *env = o->m_env;
3454 if(env == NULL) return 0;
3456 v3s16 pos = read_v3s16(L, 2);
3457 u32 time_of_day = env->getTimeOfDay();
3458 if(lua_isnumber(L, 3))
3459 time_of_day = 24000.0 * lua_tonumber(L, 3);
3460 time_of_day %= 24000;
3461 u32 dnr = time_to_daynight_ratio(time_of_day);
3462 MapNode n = env->getMap().getNodeNoEx(pos);
3464 MapNode n = env->getMap().getNode(pos);
3465 INodeDefManager *ndef = env->getGameDef()->ndef();
3466 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3468 } catch(InvalidPositionException &e)
3475 // EnvRef:place_node(pos, node)
3476 // pos = {x=num, y=num, z=num}
3477 static int l_place_node(lua_State *L)
3479 EnvRef *o = checkobject(L, 1);
3480 ServerEnvironment *env = o->m_env;
3481 if(env == NULL) return 0;
3482 v3s16 pos = read_v3s16(L, 2);
3483 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3485 // Don't attempt to load non-loaded area as of now
3486 MapNode n_old = env->getMap().getNodeNoEx(pos);
3487 if(n_old.getContent() == CONTENT_IGNORE){
3488 lua_pushboolean(L, false);
3491 // Create item to place
3492 INodeDefManager *ndef = get_server(L)->ndef();
3493 IItemDefManager *idef = get_server(L)->idef();
3494 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3495 // Make pointed position
3496 PointedThing pointed;
3497 pointed.type = POINTEDTHING_NODE;
3498 pointed.node_abovesurface = pos;
3499 pointed.node_undersurface = pos + v3s16(0,-1,0);
3500 // Place it with a NULL placer (appears in Lua as a non-functional
3502 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3503 lua_pushboolean(L, success);
3507 // EnvRef:dig_node(pos)
3508 // pos = {x=num, y=num, z=num}
3509 static int l_dig_node(lua_State *L)
3511 EnvRef *o = checkobject(L, 1);
3512 ServerEnvironment *env = o->m_env;
3513 if(env == NULL) return 0;
3514 v3s16 pos = read_v3s16(L, 2);
3516 // Don't attempt to load non-loaded area as of now
3517 MapNode n = env->getMap().getNodeNoEx(pos);
3518 if(n.getContent() == CONTENT_IGNORE){
3519 lua_pushboolean(L, false);
3522 // Dig it out with a NULL digger (appears in Lua as a
3523 // non-functional ObjectRef)
3524 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3525 lua_pushboolean(L, success);
3529 // EnvRef:punch_node(pos)
3530 // pos = {x=num, y=num, z=num}
3531 static int l_punch_node(lua_State *L)
3533 EnvRef *o = checkobject(L, 1);
3534 ServerEnvironment *env = o->m_env;
3535 if(env == NULL) return 0;
3536 v3s16 pos = read_v3s16(L, 2);
3538 // Don't attempt to load non-loaded area as of now
3539 MapNode n = env->getMap().getNodeNoEx(pos);
3540 if(n.getContent() == CONTENT_IGNORE){
3541 lua_pushboolean(L, false);
3544 // Punch it with a NULL puncher (appears in Lua as a non-functional
3546 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3547 lua_pushboolean(L, success);
3551 // EnvRef:get_meta(pos)
3552 static int l_get_meta(lua_State *L)
3554 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3555 EnvRef *o = checkobject(L, 1);
3556 ServerEnvironment *env = o->m_env;
3557 if(env == NULL) return 0;
3559 v3s16 p = read_v3s16(L, 2);
3560 NodeMetaRef::create(L, p, env);
3564 // EnvRef:get_node_timer(pos)
3565 static int l_get_node_timer(lua_State *L)
3567 EnvRef *o = checkobject(L, 1);
3568 ServerEnvironment *env = o->m_env;
3569 if(env == NULL) return 0;
3571 v3s16 p = read_v3s16(L, 2);
3572 NodeTimerRef::create(L, p, env);
3576 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3577 // pos = {x=num, y=num, z=num}
3578 static int l_add_entity(lua_State *L)
3580 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3581 EnvRef *o = checkobject(L, 1);
3582 ServerEnvironment *env = o->m_env;
3583 if(env == NULL) return 0;
3585 v3f pos = checkFloatPos(L, 2);
3587 const char *name = luaL_checkstring(L, 3);
3589 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3590 int objectid = env->addActiveObject(obj);
3591 // If failed to add, return nothing (reads as nil)
3595 objectref_get_or_create(L, obj);
3599 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3600 // pos = {x=num, y=num, z=num}
3601 static int l_add_item(lua_State *L)
3603 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3604 EnvRef *o = checkobject(L, 1);
3605 ServerEnvironment *env = o->m_env;
3606 if(env == NULL) return 0;
3608 v3f pos = checkFloatPos(L, 2);
3610 ItemStack item = read_item(L, 3);
3611 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3613 // Use minetest.spawn_item to spawn a __builtin:item
3614 lua_getglobal(L, "minetest");
3615 lua_getfield(L, -1, "spawn_item");
3616 if(lua_isnil(L, -1))
3618 lua_pushvalue(L, 2);
3619 lua_pushstring(L, item.getItemString().c_str());
3620 if(lua_pcall(L, 2, 1, 0))
3621 script_error(L, "error: %s", lua_tostring(L, -1));
3623 /*lua_pushvalue(L, 1);
3624 lua_pushstring(L, "__builtin:item");
3625 lua_pushstring(L, item.getItemString().c_str());
3626 return l_add_entity(L);*/
3628 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3629 int objectid = env->addActiveObject(obj);
3630 // If failed to add, return nothing (reads as nil)
3634 objectref_get_or_create(L, obj);
3638 // EnvRef:add_rat(pos)
3639 // pos = {x=num, y=num, z=num}
3640 static int l_add_rat(lua_State *L)
3642 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3643 <<" Doing nothing."<<std::endl;
3647 // EnvRef:add_firefly(pos)
3648 // pos = {x=num, y=num, z=num}
3649 static int l_add_firefly(lua_State *L)
3651 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3652 <<" Doing nothing."<<std::endl;
3656 // EnvRef:get_player_by_name(name)
3657 static int l_get_player_by_name(lua_State *L)
3659 EnvRef *o = checkobject(L, 1);
3660 ServerEnvironment *env = o->m_env;
3661 if(env == NULL) return 0;
3663 const char *name = luaL_checkstring(L, 2);
3664 Player *player = env->getPlayer(name);
3669 PlayerSAO *sao = player->getPlayerSAO();
3674 // Put player on stack
3675 objectref_get_or_create(L, sao);
3679 // EnvRef:get_objects_inside_radius(pos, radius)
3680 static int l_get_objects_inside_radius(lua_State *L)
3682 // Get the table insert function
3683 lua_getglobal(L, "table");
3684 lua_getfield(L, -1, "insert");
3685 int table_insert = lua_gettop(L);
3687 EnvRef *o = checkobject(L, 1);
3688 ServerEnvironment *env = o->m_env;
3689 if(env == NULL) return 0;
3691 v3f pos = checkFloatPos(L, 2);
3692 float radius = luaL_checknumber(L, 3) * BS;
3693 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3695 int table = lua_gettop(L);
3696 for(std::set<u16>::const_iterator
3697 i = ids.begin(); i != ids.end(); i++){
3698 ServerActiveObject *obj = env->getActiveObject(*i);
3699 // Insert object reference into table
3700 lua_pushvalue(L, table_insert);
3701 lua_pushvalue(L, table);
3702 objectref_get_or_create(L, obj);
3703 if(lua_pcall(L, 2, 0, 0))
3704 script_error(L, "error: %s", lua_tostring(L, -1));
3709 // EnvRef:set_timeofday(val)
3711 static int l_set_timeofday(lua_State *L)
3713 EnvRef *o = checkobject(L, 1);
3714 ServerEnvironment *env = o->m_env;
3715 if(env == NULL) return 0;
3717 float timeofday_f = luaL_checknumber(L, 2);
3718 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3719 int timeofday_mh = (int)(timeofday_f * 24000.0);
3720 // This should be set directly in the environment but currently
3721 // such changes aren't immediately sent to the clients, so call
3722 // the server instead.
3723 //env->setTimeOfDay(timeofday_mh);
3724 get_server(L)->setTimeOfDay(timeofday_mh);
3728 // EnvRef:get_timeofday() -> 0...1
3729 static int l_get_timeofday(lua_State *L)
3731 EnvRef *o = checkobject(L, 1);
3732 ServerEnvironment *env = o->m_env;
3733 if(env == NULL) return 0;
3735 int timeofday_mh = env->getTimeOfDay();
3736 float timeofday_f = (float)timeofday_mh / 24000.0;
3737 lua_pushnumber(L, timeofday_f);
3742 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3743 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3744 static int l_find_node_near(lua_State *L)
3746 EnvRef *o = checkobject(L, 1);
3747 ServerEnvironment *env = o->m_env;
3748 if(env == NULL) return 0;
3749 INodeDefManager *ndef = get_server(L)->ndef();
3750 v3s16 pos = read_v3s16(L, 2);
3751 int radius = luaL_checkinteger(L, 3);
3752 std::set<content_t> filter;
3753 if(lua_istable(L, 4)){
3756 while(lua_next(L, table) != 0){
3757 // key at index -2 and value at index -1
3758 luaL_checktype(L, -1, LUA_TSTRING);
3759 ndef->getIds(lua_tostring(L, -1), filter);
3760 // removes value, keeps key for next iteration
3763 } else if(lua_isstring(L, 4)){
3764 ndef->getIds(lua_tostring(L, 4), filter);
3767 for(int d=1; d<=radius; d++){
3768 core::list<v3s16> list;
3769 getFacePositions(list, d);
3770 for(core::list<v3s16>::Iterator i = list.begin();
3771 i != list.end(); i++){
3772 v3s16 p = pos + (*i);
3773 content_t c = env->getMap().getNodeNoEx(p).getContent();
3774 if(filter.count(c) != 0){
3783 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3784 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3785 static int l_find_nodes_in_area(lua_State *L)
3787 EnvRef *o = checkobject(L, 1);
3788 ServerEnvironment *env = o->m_env;
3789 if(env == NULL) return 0;
3790 INodeDefManager *ndef = get_server(L)->ndef();
3791 v3s16 minp = read_v3s16(L, 2);
3792 v3s16 maxp = read_v3s16(L, 3);
3793 std::set<content_t> filter;
3794 if(lua_istable(L, 4)){
3797 while(lua_next(L, table) != 0){
3798 // key at index -2 and value at index -1
3799 luaL_checktype(L, -1, LUA_TSTRING);
3800 ndef->getIds(lua_tostring(L, -1), filter);
3801 // removes value, keeps key for next iteration
3804 } else if(lua_isstring(L, 4)){
3805 ndef->getIds(lua_tostring(L, 4), filter);
3808 // Get the table insert function
3809 lua_getglobal(L, "table");
3810 lua_getfield(L, -1, "insert");
3811 int table_insert = lua_gettop(L);
3814 int table = lua_gettop(L);
3815 for(s16 x=minp.X; x<=maxp.X; x++)
3816 for(s16 y=minp.Y; y<=maxp.Y; y++)
3817 for(s16 z=minp.Z; z<=maxp.Z; z++)
3820 content_t c = env->getMap().getNodeNoEx(p).getContent();
3821 if(filter.count(c) != 0){
3822 lua_pushvalue(L, table_insert);
3823 lua_pushvalue(L, table);
3825 if(lua_pcall(L, 2, 0, 0))
3826 script_error(L, "error: %s", lua_tostring(L, -1));
3832 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3833 // returns world-specific PerlinNoise
3834 static int l_get_perlin(lua_State *L)
3836 EnvRef *o = checkobject(L, 1);
3837 ServerEnvironment *env = o->m_env;
3838 if(env == NULL) return 0;
3840 int seeddiff = luaL_checkint(L, 2);
3841 int octaves = luaL_checkint(L, 3);
3842 double persistence = luaL_checknumber(L, 4);
3843 double scale = luaL_checknumber(L, 5);
3845 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3846 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3847 luaL_getmetatable(L, "PerlinNoise");
3848 lua_setmetatable(L, -2);
3852 // EnvRef:clear_objects()
3853 // clear all objects in the environment
3854 static int l_clear_objects(lua_State *L)
3856 EnvRef *o = checkobject(L, 1);
3857 o->m_env->clearAllObjects();
3862 EnvRef(ServerEnvironment *env):
3865 //infostream<<"EnvRef created"<<std::endl;
3870 //infostream<<"EnvRef destructing"<<std::endl;
3873 // Creates an EnvRef and leaves it on top of stack
3874 // Not callable from Lua; all references are created on the C side.
3875 static void create(lua_State *L, ServerEnvironment *env)
3877 EnvRef *o = new EnvRef(env);
3878 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3879 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3880 luaL_getmetatable(L, className);
3881 lua_setmetatable(L, -2);
3884 static void set_null(lua_State *L)
3886 EnvRef *o = checkobject(L, -1);
3890 static void Register(lua_State *L)
3893 int methodtable = lua_gettop(L);
3894 luaL_newmetatable(L, className);
3895 int metatable = lua_gettop(L);
3897 lua_pushliteral(L, "__metatable");
3898 lua_pushvalue(L, methodtable);
3899 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3901 lua_pushliteral(L, "__index");
3902 lua_pushvalue(L, methodtable);
3903 lua_settable(L, metatable);
3905 lua_pushliteral(L, "__gc");
3906 lua_pushcfunction(L, gc_object);
3907 lua_settable(L, metatable);
3909 lua_pop(L, 1); // drop metatable
3911 luaL_openlib(L, 0, methods, 0); // fill methodtable
3912 lua_pop(L, 1); // drop methodtable
3914 // Cannot be created from Lua
3915 //lua_register(L, className, create_object);
3918 const char EnvRef::className[] = "EnvRef";
3919 const luaL_reg EnvRef::methods[] = {
3920 method(EnvRef, set_node),
3921 method(EnvRef, add_node),
3922 method(EnvRef, remove_node),
3923 method(EnvRef, get_node),
3924 method(EnvRef, get_node_or_nil),
3925 method(EnvRef, get_node_light),
3926 method(EnvRef, place_node),
3927 method(EnvRef, dig_node),
3928 method(EnvRef, punch_node),
3929 method(EnvRef, add_entity),
3930 method(EnvRef, add_item),
3931 method(EnvRef, add_rat),
3932 method(EnvRef, add_firefly),
3933 method(EnvRef, get_meta),
3934 method(EnvRef, get_node_timer),
3935 method(EnvRef, get_player_by_name),
3936 method(EnvRef, get_objects_inside_radius),
3937 method(EnvRef, set_timeofday),
3938 method(EnvRef, get_timeofday),
3939 method(EnvRef, find_node_near),
3940 method(EnvRef, find_nodes_in_area),
3941 method(EnvRef, get_perlin),
3942 method(EnvRef, clear_objects),
3951 class LuaPseudoRandom
3954 PseudoRandom m_pseudo;
3956 static const char className[];
3957 static const luaL_reg methods[];
3959 // Exported functions
3961 // garbage collector
3962 static int gc_object(lua_State *L)
3964 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3969 // next(self, min=0, max=32767) -> get next value
3970 static int l_next(lua_State *L)
3972 LuaPseudoRandom *o = checkobject(L, 1);
3975 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3976 if(!lua_isnil(L, 2))
3977 min = luaL_checkinteger(L, 2);
3978 if(!lua_isnil(L, 3))
3979 max = luaL_checkinteger(L, 3);
3981 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
3982 throw LuaError(L, "PseudoRandom.next(): max < min");
3984 if(max - min != 32767 && max - min > 32767/5)
3985 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.");
3986 PseudoRandom &pseudo = o->m_pseudo;
3987 int val = pseudo.next();
3988 val = (val % (max-min+1)) + min;
3989 lua_pushinteger(L, val);
3994 LuaPseudoRandom(int seed):
4003 const PseudoRandom& getItem() const
4007 PseudoRandom& getItem()
4012 // LuaPseudoRandom(seed)
4013 // Creates an LuaPseudoRandom and leaves it on top of stack
4014 static int create_object(lua_State *L)
4016 int seed = luaL_checknumber(L, 1);
4017 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4018 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4019 luaL_getmetatable(L, className);
4020 lua_setmetatable(L, -2);
4024 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4026 luaL_checktype(L, narg, LUA_TUSERDATA);
4027 void *ud = luaL_checkudata(L, narg, className);
4028 if(!ud) luaL_typerror(L, narg, className);
4029 return *(LuaPseudoRandom**)ud; // unbox pointer
4032 static void Register(lua_State *L)
4035 int methodtable = lua_gettop(L);
4036 luaL_newmetatable(L, className);
4037 int metatable = lua_gettop(L);
4039 lua_pushliteral(L, "__metatable");
4040 lua_pushvalue(L, methodtable);
4041 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4043 lua_pushliteral(L, "__index");
4044 lua_pushvalue(L, methodtable);
4045 lua_settable(L, metatable);
4047 lua_pushliteral(L, "__gc");
4048 lua_pushcfunction(L, gc_object);
4049 lua_settable(L, metatable);
4051 lua_pop(L, 1); // drop metatable
4053 luaL_openlib(L, 0, methods, 0); // fill methodtable
4054 lua_pop(L, 1); // drop methodtable
4056 // Can be created from Lua (LuaPseudoRandom(seed))
4057 lua_register(L, className, create_object);
4060 const char LuaPseudoRandom::className[] = "PseudoRandom";
4061 const luaL_reg LuaPseudoRandom::methods[] = {
4062 method(LuaPseudoRandom, next),
4072 class LuaABM : public ActiveBlockModifier
4078 std::set<std::string> m_trigger_contents;
4079 std::set<std::string> m_required_neighbors;
4080 float m_trigger_interval;
4081 u32 m_trigger_chance;
4083 LuaABM(lua_State *L, int id,
4084 const std::set<std::string> &trigger_contents,
4085 const std::set<std::string> &required_neighbors,
4086 float trigger_interval, u32 trigger_chance):
4089 m_trigger_contents(trigger_contents),
4090 m_required_neighbors(required_neighbors),
4091 m_trigger_interval(trigger_interval),
4092 m_trigger_chance(trigger_chance)
4095 virtual std::set<std::string> getTriggerContents()
4097 return m_trigger_contents;
4099 virtual std::set<std::string> getRequiredNeighbors()
4101 return m_required_neighbors;
4103 virtual float getTriggerInterval()
4105 return m_trigger_interval;
4107 virtual u32 getTriggerChance()
4109 return m_trigger_chance;
4111 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4112 u32 active_object_count, u32 active_object_count_wider)
4114 lua_State *L = m_lua;
4117 assert(lua_checkstack(L, 20));
4118 StackUnroller stack_unroller(L);
4120 // Get minetest.registered_abms
4121 lua_getglobal(L, "minetest");
4122 lua_getfield(L, -1, "registered_abms");
4123 luaL_checktype(L, -1, LUA_TTABLE);
4124 int registered_abms = lua_gettop(L);
4126 // Get minetest.registered_abms[m_id]
4127 lua_pushnumber(L, m_id);
4128 lua_gettable(L, registered_abms);
4129 if(lua_isnil(L, -1))
4133 luaL_checktype(L, -1, LUA_TTABLE);
4134 lua_getfield(L, -1, "action");
4135 luaL_checktype(L, -1, LUA_TFUNCTION);
4137 pushnode(L, n, env->getGameDef()->ndef());
4138 lua_pushnumber(L, active_object_count);
4139 lua_pushnumber(L, active_object_count_wider);
4140 if(lua_pcall(L, 4, 0, 0))
4141 script_error(L, "error: %s", lua_tostring(L, -1));
4149 static void read_server_sound_params(lua_State *L, int index,
4150 ServerSoundParams ¶ms)
4153 index = lua_gettop(L) + 1 + index;
4155 params = ServerSoundParams();
4156 if(lua_istable(L, index)){
4157 getfloatfield(L, index, "gain", params.gain);
4158 getstringfield(L, index, "to_player", params.to_player);
4159 lua_getfield(L, index, "pos");
4160 if(!lua_isnil(L, -1)){
4161 v3f p = read_v3f(L, -1)*BS;
4163 params.type = ServerSoundParams::SSP_POSITIONAL;
4166 lua_getfield(L, index, "object");
4167 if(!lua_isnil(L, -1)){
4168 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4169 ServerActiveObject *sao = ObjectRef::getobject(ref);
4171 params.object = sao->getId();
4172 params.type = ServerSoundParams::SSP_OBJECT;
4176 params.max_hear_distance = BS*getfloatfield_default(L, index,
4177 "max_hear_distance", params.max_hear_distance/BS);
4178 getboolfield(L, index, "loop", params.loop);
4187 // Writes a line to dstream
4188 static int l_debug(lua_State *L)
4190 std::string text = lua_tostring(L, 1);
4191 dstream << text << std::endl;
4195 // log([level,] text)
4196 // Writes a line to the logger.
4197 // The one-argument version logs to infostream.
4198 // The two-argument version accept a log level: error, action, info, or verbose.
4199 static int l_log(lua_State *L)
4202 LogMessageLevel level = LMT_INFO;
4203 if(lua_isnone(L, 2))
4205 text = lua_tostring(L, 1);
4209 std::string levelname = lua_tostring(L, 1);
4210 text = lua_tostring(L, 2);
4211 if(levelname == "error")
4213 else if(levelname == "action")
4215 else if(levelname == "verbose")
4216 level = LMT_VERBOSE;
4218 log_printline(level, text);
4222 // request_shutdown()
4223 static int l_request_shutdown(lua_State *L)
4225 get_server(L)->requestShutdown();
4229 // get_server_status()
4230 static int l_get_server_status(lua_State *L)
4232 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4236 // register_item_raw({lots of stuff})
4237 static int l_register_item_raw(lua_State *L)
4239 luaL_checktype(L, 1, LUA_TTABLE);
4242 // Get the writable item and node definition managers from the server
4243 IWritableItemDefManager *idef =
4244 get_server(L)->getWritableItemDefManager();
4245 IWritableNodeDefManager *ndef =
4246 get_server(L)->getWritableNodeDefManager();
4248 // Check if name is defined
4250 lua_getfield(L, table, "name");
4251 if(lua_isstring(L, -1)){
4252 name = lua_tostring(L, -1);
4253 verbosestream<<"register_item_raw: "<<name<<std::endl;
4255 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4258 // Check if on_use is defined
4261 // Set a distinctive default value to check if this is set
4262 def.node_placement_prediction = "__default";
4264 // Read the item definition
4265 def = read_item_definition(L, table, def);
4267 // Default to having client-side placement prediction for nodes
4268 // ("" in item definition sets it off)
4269 if(def.node_placement_prediction == "__default"){
4270 if(def.type == ITEM_NODE)
4271 def.node_placement_prediction = name;
4273 def.node_placement_prediction = "";
4276 // Register item definition
4277 idef->registerItem(def);
4279 // Read the node definition (content features) and register it
4280 if(def.type == ITEM_NODE)
4282 ContentFeatures f = read_content_features(L, table);
4283 ndef->set(f.name, f);
4286 return 0; /* number of results */
4289 // register_alias_raw(name, convert_to_name)
4290 static int l_register_alias_raw(lua_State *L)
4292 std::string name = luaL_checkstring(L, 1);
4293 std::string convert_to = luaL_checkstring(L, 2);
4295 // Get the writable item definition manager from the server
4296 IWritableItemDefManager *idef =
4297 get_server(L)->getWritableItemDefManager();
4299 idef->registerAlias(name, convert_to);
4301 return 0; /* number of results */
4304 // helper for register_craft
4305 static bool read_craft_recipe_shaped(lua_State *L, int index,
4306 int &width, std::vector<std::string> &recipe)
4309 index = lua_gettop(L) + 1 + index;
4311 if(!lua_istable(L, index))
4316 while(lua_next(L, index) != 0){
4318 // key at index -2 and value at index -1
4319 if(!lua_istable(L, -1))
4321 int table2 = lua_gettop(L);
4323 while(lua_next(L, table2) != 0){
4324 // key at index -2 and value at index -1
4325 if(!lua_isstring(L, -1))
4327 recipe.push_back(lua_tostring(L, -1));
4328 // removes value, keeps key for next iteration
4335 if(colcount != width)
4338 // removes value, keeps key for next iteration
4345 // helper for register_craft
4346 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4347 std::vector<std::string> &recipe)
4350 index = lua_gettop(L) + 1 + index;
4352 if(!lua_istable(L, index))
4356 while(lua_next(L, index) != 0){
4357 // key at index -2 and value at index -1
4358 if(!lua_isstring(L, -1))
4360 recipe.push_back(lua_tostring(L, -1));
4361 // removes value, keeps key for next iteration
4367 // helper for register_craft
4368 static bool read_craft_replacements(lua_State *L, int index,
4369 CraftReplacements &replacements)
4372 index = lua_gettop(L) + 1 + index;
4374 if(!lua_istable(L, index))
4378 while(lua_next(L, index) != 0){
4379 // key at index -2 and value at index -1
4380 if(!lua_istable(L, -1))
4382 lua_rawgeti(L, -1, 1);
4383 if(!lua_isstring(L, -1))
4385 std::string replace_from = lua_tostring(L, -1);
4387 lua_rawgeti(L, -1, 2);
4388 if(!lua_isstring(L, -1))
4390 std::string replace_to = lua_tostring(L, -1);
4392 replacements.pairs.push_back(
4393 std::make_pair(replace_from, replace_to));
4394 // removes value, keeps key for next iteration
4399 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4400 static int l_register_craft(lua_State *L)
4402 //infostream<<"register_craft"<<std::endl;
4403 luaL_checktype(L, 1, LUA_TTABLE);
4406 // Get the writable craft definition manager from the server
4407 IWritableCraftDefManager *craftdef =
4408 get_server(L)->getWritableCraftDefManager();
4410 std::string type = getstringfield_default(L, table, "type", "shaped");
4413 CraftDefinitionShaped
4415 if(type == "shaped"){
4416 std::string output = getstringfield_default(L, table, "output", "");
4418 throw LuaError(L, "Crafting definition is missing an output");
4421 std::vector<std::string> recipe;
4422 lua_getfield(L, table, "recipe");
4423 if(lua_isnil(L, -1))
4424 throw LuaError(L, "Crafting definition is missing a recipe"
4425 " (output=\"" + output + "\")");
4426 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4427 throw LuaError(L, "Invalid crafting recipe"
4428 " (output=\"" + output + "\")");
4430 CraftReplacements replacements;
4431 lua_getfield(L, table, "replacements");
4432 if(!lua_isnil(L, -1))
4434 if(!read_craft_replacements(L, -1, replacements))
4435 throw LuaError(L, "Invalid replacements"
4436 " (output=\"" + output + "\")");
4439 CraftDefinition *def = new CraftDefinitionShaped(
4440 output, width, recipe, replacements);
4441 craftdef->registerCraft(def);
4444 CraftDefinitionShapeless
4446 else if(type == "shapeless"){
4447 std::string output = getstringfield_default(L, table, "output", "");
4449 throw LuaError(L, "Crafting definition (shapeless)"
4450 " is missing an output");
4452 std::vector<std::string> recipe;
4453 lua_getfield(L, table, "recipe");
4454 if(lua_isnil(L, -1))
4455 throw LuaError(L, "Crafting definition (shapeless)"
4456 " is missing a recipe"
4457 " (output=\"" + output + "\")");
4458 if(!read_craft_recipe_shapeless(L, -1, recipe))
4459 throw LuaError(L, "Invalid crafting recipe"
4460 " (output=\"" + output + "\")");
4462 CraftReplacements replacements;
4463 lua_getfield(L, table, "replacements");
4464 if(!lua_isnil(L, -1))
4466 if(!read_craft_replacements(L, -1, replacements))
4467 throw LuaError(L, "Invalid replacements"
4468 " (output=\"" + output + "\")");
4471 CraftDefinition *def = new CraftDefinitionShapeless(
4472 output, recipe, replacements);
4473 craftdef->registerCraft(def);
4476 CraftDefinitionToolRepair
4478 else if(type == "toolrepair"){
4479 float additional_wear = getfloatfield_default(L, table,
4480 "additional_wear", 0.0);
4482 CraftDefinition *def = new CraftDefinitionToolRepair(
4484 craftdef->registerCraft(def);
4487 CraftDefinitionCooking
4489 else if(type == "cooking"){
4490 std::string output = getstringfield_default(L, table, "output", "");
4492 throw LuaError(L, "Crafting definition (cooking)"
4493 " is missing an output");
4495 std::string recipe = getstringfield_default(L, table, "recipe", "");
4497 throw LuaError(L, "Crafting definition (cooking)"
4498 " is missing a recipe"
4499 " (output=\"" + output + "\")");
4501 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4503 CraftReplacements replacements;
4504 lua_getfield(L, table, "replacements");
4505 if(!lua_isnil(L, -1))
4507 if(!read_craft_replacements(L, -1, replacements))
4508 throw LuaError(L, "Invalid replacements"
4509 " (cooking output=\"" + output + "\")");
4512 CraftDefinition *def = new CraftDefinitionCooking(
4513 output, recipe, cooktime, replacements);
4514 craftdef->registerCraft(def);
4519 else if(type == "fuel"){
4520 std::string recipe = getstringfield_default(L, table, "recipe", "");
4522 throw LuaError(L, "Crafting definition (fuel)"
4523 " is missing a recipe");
4525 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4527 CraftReplacements replacements;
4528 lua_getfield(L, table, "replacements");
4529 if(!lua_isnil(L, -1))
4531 if(!read_craft_replacements(L, -1, replacements))
4532 throw LuaError(L, "Invalid replacements"
4533 " (fuel recipe=\"" + recipe + "\")");
4536 CraftDefinition *def = new CraftDefinitionFuel(
4537 recipe, burntime, replacements);
4538 craftdef->registerCraft(def);
4542 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4546 return 0; /* number of results */
4549 // setting_set(name, value)
4550 static int l_setting_set(lua_State *L)
4552 const char *name = luaL_checkstring(L, 1);
4553 const char *value = luaL_checkstring(L, 2);
4554 g_settings->set(name, value);
4558 // setting_get(name)
4559 static int l_setting_get(lua_State *L)
4561 const char *name = luaL_checkstring(L, 1);
4563 std::string value = g_settings->get(name);
4564 lua_pushstring(L, value.c_str());
4565 } catch(SettingNotFoundException &e){
4571 // setting_getbool(name)
4572 static int l_setting_getbool(lua_State *L)
4574 const char *name = luaL_checkstring(L, 1);
4576 bool value = g_settings->getBool(name);
4577 lua_pushboolean(L, value);
4578 } catch(SettingNotFoundException &e){
4584 // chat_send_all(text)
4585 static int l_chat_send_all(lua_State *L)
4587 const char *text = luaL_checkstring(L, 1);
4588 // Get server from registry
4589 Server *server = get_server(L);
4591 server->notifyPlayers(narrow_to_wide(text));
4595 // chat_send_player(name, text)
4596 static int l_chat_send_player(lua_State *L)
4598 const char *name = luaL_checkstring(L, 1);
4599 const char *text = luaL_checkstring(L, 2);
4600 // Get server from registry
4601 Server *server = get_server(L);
4603 server->notifyPlayer(name, narrow_to_wide(text));
4607 // get_player_privs(name, text)
4608 static int l_get_player_privs(lua_State *L)
4610 const char *name = luaL_checkstring(L, 1);
4611 // Get server from registry
4612 Server *server = get_server(L);
4615 int table = lua_gettop(L);
4616 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4617 for(std::set<std::string>::const_iterator
4618 i = privs_s.begin(); i != privs_s.end(); i++){
4619 lua_pushboolean(L, true);
4620 lua_setfield(L, table, i->c_str());
4622 lua_pushvalue(L, table);
4627 static int l_get_ban_list(lua_State *L)
4629 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4633 // get_ban_description()
4634 static int l_get_ban_description(lua_State *L)
4636 const char * ip_or_name = luaL_checkstring(L, 1);
4637 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4642 static int l_ban_player(lua_State *L)
4644 const char * name = luaL_checkstring(L, 1);
4645 Player *player = get_env(L)->getPlayer(name);
4648 lua_pushboolean(L, false); // no such player
4653 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4654 std::string ip_str = addr.serializeString();
4655 get_server(L)->setIpBanned(ip_str, name);
4657 catch(con::PeerNotFoundException) // unlikely
4659 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4660 lua_pushboolean(L, false); // error
4663 lua_pushboolean(L, true);
4667 // unban_player_or_ip()
4668 static int l_unban_player_of_ip(lua_State *L)
4670 const char * ip_or_name = luaL_checkstring(L, 1);
4671 get_server(L)->unsetIpBanned(ip_or_name);
4672 lua_pushboolean(L, true);
4676 // get_inventory(location)
4677 static int l_get_inventory(lua_State *L)
4679 InventoryLocation loc;
4681 std::string type = checkstringfield(L, 1, "type");
4682 if(type == "player"){
4683 std::string name = checkstringfield(L, 1, "name");
4684 loc.setPlayer(name);
4685 } else if(type == "node"){
4686 lua_getfield(L, 1, "pos");
4687 v3s16 pos = check_v3s16(L, -1);
4688 loc.setNodeMeta(pos);
4689 } else if(type == "detached"){
4690 std::string name = checkstringfield(L, 1, "name");
4691 loc.setDetached(name);
4694 if(get_server(L)->getInventory(loc) != NULL)
4695 InvRef::create(L, loc);
4701 // create_detached_inventory_raw(name)
4702 static int l_create_detached_inventory_raw(lua_State *L)
4704 const char *name = luaL_checkstring(L, 1);
4705 if(get_server(L)->createDetachedInventory(name) != NULL){
4706 InventoryLocation loc;
4707 loc.setDetached(name);
4708 InvRef::create(L, loc);
4715 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4716 static int l_get_dig_params(lua_State *L)
4718 std::map<std::string, int> groups;
4719 read_groups(L, 1, groups);
4720 ToolCapabilities tp = read_tool_capabilities(L, 2);
4721 if(lua_isnoneornil(L, 3))
4722 push_dig_params(L, getDigParams(groups, &tp));
4724 push_dig_params(L, getDigParams(groups, &tp,
4725 luaL_checknumber(L, 3)));
4729 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4730 static int l_get_hit_params(lua_State *L)
4732 std::map<std::string, int> groups;
4733 read_groups(L, 1, groups);
4734 ToolCapabilities tp = read_tool_capabilities(L, 2);
4735 if(lua_isnoneornil(L, 3))
4736 push_hit_params(L, getHitParams(groups, &tp));
4738 push_hit_params(L, getHitParams(groups, &tp,
4739 luaL_checknumber(L, 3)));
4743 // get_current_modname()
4744 static int l_get_current_modname(lua_State *L)
4746 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4750 // get_modpath(modname)
4751 static int l_get_modpath(lua_State *L)
4753 std::string modname = luaL_checkstring(L, 1);
4755 if(modname == "__builtin"){
4756 std::string path = get_server(L)->getBuiltinLuaPath();
4757 lua_pushstring(L, path.c_str());
4760 const ModSpec *mod = get_server(L)->getModSpec(modname);
4765 lua_pushstring(L, mod->path.c_str());
4770 // the returned list is sorted alphabetically for you
4771 static int l_get_modnames(lua_State *L)
4773 // Get a list of mods
4774 core::list<std::string> mods_unsorted, mods_sorted;
4775 get_server(L)->getModNames(mods_unsorted);
4777 // Take unsorted items from mods_unsorted and sort them into
4778 // mods_sorted; not great performance but the number of mods on a
4779 // server will likely be small.
4780 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4781 i != mods_unsorted.end(); i++)
4784 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4785 x != mods_unsorted.end(); x++)
4787 // I doubt anybody using Minetest will be using
4788 // anything not ASCII based :)
4789 if((*i).compare(*x) <= 0)
4791 mods_sorted.insert_before(x, *i);
4797 mods_sorted.push_back(*i);
4800 // Get the table insertion function from Lua.
4801 lua_getglobal(L, "table");
4802 lua_getfield(L, -1, "insert");
4803 int insertion_func = lua_gettop(L);
4805 // Package them up for Lua
4807 int new_table = lua_gettop(L);
4808 core::list<std::string>::Iterator i = mods_sorted.begin();
4809 while(i != mods_sorted.end())
4811 lua_pushvalue(L, insertion_func);
4812 lua_pushvalue(L, new_table);
4813 lua_pushstring(L, (*i).c_str());
4814 if(lua_pcall(L, 2, 0, 0) != 0)
4816 script_error(L, "error: %s", lua_tostring(L, -1));
4824 static int l_get_worldpath(lua_State *L)
4826 std::string worldpath = get_server(L)->getWorldPath();
4827 lua_pushstring(L, worldpath.c_str());
4831 // sound_play(spec, parameters)
4832 static int l_sound_play(lua_State *L)
4834 SimpleSoundSpec spec;
4835 read_soundspec(L, 1, spec);
4836 ServerSoundParams params;
4837 read_server_sound_params(L, 2, params);
4838 s32 handle = get_server(L)->playSound(spec, params);
4839 lua_pushinteger(L, handle);
4843 // sound_stop(handle)
4844 static int l_sound_stop(lua_State *L)
4846 int handle = luaL_checkinteger(L, 1);
4847 get_server(L)->stopSound(handle);
4851 // is_singleplayer()
4852 static int l_is_singleplayer(lua_State *L)
4854 lua_pushboolean(L, get_server(L)->isSingleplayer());
4858 // get_password_hash(name, raw_password)
4859 static int l_get_password_hash(lua_State *L)
4861 std::string name = luaL_checkstring(L, 1);
4862 std::string raw_password = luaL_checkstring(L, 2);
4863 std::string hash = translatePassword(name,
4864 narrow_to_wide(raw_password));
4865 lua_pushstring(L, hash.c_str());
4869 // notify_authentication_modified(name)
4870 static int l_notify_authentication_modified(lua_State *L)
4872 std::string name = "";
4873 if(lua_isstring(L, 1))
4874 name = lua_tostring(L, 1);
4875 get_server(L)->reportPrivsModified(name);
4879 // get_craft_result(input)
4880 static int l_get_craft_result(lua_State *L)
4883 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4884 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4885 es_CraftMethod, CRAFT_METHOD_NORMAL);
4887 lua_getfield(L, input_i, "width");
4888 if(lua_isnumber(L, -1))
4889 width = luaL_checkinteger(L, -1);
4891 lua_getfield(L, input_i, "items");
4892 std::vector<ItemStack> items = read_items(L, -1);
4893 lua_pop(L, 1); // items
4895 IGameDef *gdef = get_server(L);
4896 ICraftDefManager *cdef = gdef->cdef();
4897 CraftInput input(method, width, items);
4899 bool got = cdef->getCraftResult(input, output, true, gdef);
4900 lua_newtable(L); // output table
4903 item.deSerialize(output.item, gdef->idef());
4904 LuaItemStack::create(L, item);
4905 lua_setfield(L, -2, "item");
4906 setintfield(L, -1, "time", output.time);
4908 LuaItemStack::create(L, ItemStack());
4909 lua_setfield(L, -2, "item");
4910 setintfield(L, -1, "time", 0);
4912 lua_newtable(L); // decremented input table
4913 lua_pushstring(L, method_s.c_str());
4914 lua_setfield(L, -2, "method");
4915 lua_pushinteger(L, width);
4916 lua_setfield(L, -2, "width");
4917 push_items(L, input.items);
4918 lua_setfield(L, -2, "items");
4922 // get_craft_recipe(result item)
4923 static int l_get_craft_recipe(lua_State *L)
4928 std::string o_item = luaL_checkstring(L,input_i);
4930 IGameDef *gdef = get_server(L);
4931 ICraftDefManager *cdef = gdef->cdef();
4933 CraftOutput output(o_item,0);
4934 bool got = cdef->getCraftRecipe(input, output, gdef);
4935 lua_newtable(L); // output table
4938 for(std::vector<ItemStack>::const_iterator
4939 i = input.items.begin();
4940 i != input.items.end(); i++, k++)
4946 sprintf(tmp,"%d",k);
4947 lua_pushstring(L,tmp);
4948 lua_pushstring(L,i->name.c_str());
4949 lua_settable(L, -3);
4951 lua_setfield(L, -2, "items");
4952 setintfield(L, -1, "width", input.width);
4953 switch (input.method) {
4954 case CRAFT_METHOD_NORMAL:
4955 lua_pushstring(L,"normal");
4957 case CRAFT_METHOD_COOKING:
4958 lua_pushstring(L,"cooking");
4960 case CRAFT_METHOD_FUEL:
4961 lua_pushstring(L,"fuel");
4964 lua_pushstring(L,"unknown");
4966 lua_setfield(L, -2, "type");
4969 lua_setfield(L, -2, "items");
4970 setintfield(L, -1, "width", 0);
4975 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
4976 static int l_rollback_get_last_node_actor(lua_State *L)
4978 v3s16 p = read_v3s16(L, 1);
4979 int range = luaL_checknumber(L, 2);
4980 int seconds = luaL_checknumber(L, 3);
4981 Server *server = get_server(L);
4982 IRollbackManager *rollback = server->getRollbackManager();
4984 int act_seconds = 0;
4985 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
4986 lua_pushstring(L, actor.c_str());
4987 push_v3s16(L, act_p);
4988 lua_pushnumber(L, act_seconds);
4992 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
4993 static int l_rollback_revert_actions_by(lua_State *L)
4995 std::string actor = luaL_checkstring(L, 1);
4996 int seconds = luaL_checknumber(L, 2);
4997 Server *server = get_server(L);
4998 IRollbackManager *rollback = server->getRollbackManager();
4999 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5000 std::list<std::string> log;
5001 bool success = server->rollbackRevertActions(actions, &log);
5002 // Push boolean result
5003 lua_pushboolean(L, success);
5004 // Get the table insert function and push the log table
5005 lua_getglobal(L, "table");
5006 lua_getfield(L, -1, "insert");
5007 int table_insert = lua_gettop(L);
5009 int table = lua_gettop(L);
5010 for(std::list<std::string>::const_iterator i = log.begin();
5011 i != log.end(); i++)
5013 lua_pushvalue(L, table_insert);
5014 lua_pushvalue(L, table);
5015 lua_pushstring(L, i->c_str());
5016 if(lua_pcall(L, 2, 0, 0))
5017 script_error(L, "error: %s", lua_tostring(L, -1));
5019 lua_remove(L, -2); // Remove table
5020 lua_remove(L, -2); // Remove insert
5024 static const struct luaL_Reg minetest_f [] = {
5027 {"request_shutdown", l_request_shutdown},
5028 {"get_server_status", l_get_server_status},
5029 {"register_item_raw", l_register_item_raw},
5030 {"register_alias_raw", l_register_alias_raw},
5031 {"register_craft", l_register_craft},
5032 {"setting_set", l_setting_set},
5033 {"setting_get", l_setting_get},
5034 {"setting_getbool", l_setting_getbool},
5035 {"chat_send_all", l_chat_send_all},
5036 {"chat_send_player", l_chat_send_player},
5037 {"get_player_privs", l_get_player_privs},
5038 {"get_ban_list", l_get_ban_list},
5039 {"get_ban_description", l_get_ban_description},
5040 {"ban_player", l_ban_player},
5041 {"unban_player_or_ip", l_unban_player_of_ip},
5042 {"get_inventory", l_get_inventory},
5043 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5044 {"get_dig_params", l_get_dig_params},
5045 {"get_hit_params", l_get_hit_params},
5046 {"get_current_modname", l_get_current_modname},
5047 {"get_modpath", l_get_modpath},
5048 {"get_modnames", l_get_modnames},
5049 {"get_worldpath", l_get_worldpath},
5050 {"sound_play", l_sound_play},
5051 {"sound_stop", l_sound_stop},
5052 {"is_singleplayer", l_is_singleplayer},
5053 {"get_password_hash", l_get_password_hash},
5054 {"notify_authentication_modified", l_notify_authentication_modified},
5055 {"get_craft_result", l_get_craft_result},
5056 {"get_craft_recipe", l_get_craft_recipe},
5057 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5058 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5063 Main export function
5066 void scriptapi_export(lua_State *L, Server *server)
5069 assert(lua_checkstack(L, 20));
5070 verbosestream<<"scriptapi_export()"<<std::endl;
5071 StackUnroller stack_unroller(L);
5073 // Store server as light userdata in registry
5074 lua_pushlightuserdata(L, server);
5075 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5077 // Register global functions in table minetest
5079 luaL_register(L, NULL, minetest_f);
5080 lua_setglobal(L, "minetest");
5082 // Get the main minetest table
5083 lua_getglobal(L, "minetest");
5085 // Add tables to minetest
5087 lua_setfield(L, -2, "object_refs");
5089 lua_setfield(L, -2, "luaentities");
5091 // Register wrappers
5092 LuaItemStack::Register(L);
5093 InvRef::Register(L);
5094 NodeMetaRef::Register(L);
5095 NodeTimerRef::Register(L);
5096 ObjectRef::Register(L);
5097 EnvRef::Register(L);
5098 LuaPseudoRandom::Register(L);
5099 LuaPerlinNoise::Register(L);
5102 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5103 const std::string &modname)
5105 ModNameStorer modnamestorer(L, modname);
5107 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5109 errorstream<<"Error loading mod \""<<modname
5110 <<"\": modname does not follow naming conventions: "
5111 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5115 bool success = false;
5118 success = script_load(L, scriptpath.c_str());
5121 errorstream<<"Error loading mod \""<<modname
5122 <<"\": "<<e.what()<<std::endl;
5128 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5131 assert(lua_checkstack(L, 20));
5132 verbosestream<<"scriptapi_add_environment"<<std::endl;
5133 StackUnroller stack_unroller(L);
5135 // Create EnvRef on stack
5136 EnvRef::create(L, env);
5137 int envref = lua_gettop(L);
5139 // minetest.env = envref
5140 lua_getglobal(L, "minetest");
5141 luaL_checktype(L, -1, LUA_TTABLE);
5142 lua_pushvalue(L, envref);
5143 lua_setfield(L, -2, "env");
5145 // Store environment as light userdata in registry
5146 lua_pushlightuserdata(L, env);
5147 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5150 Add ActiveBlockModifiers to environment
5153 // Get minetest.registered_abms
5154 lua_getglobal(L, "minetest");
5155 lua_getfield(L, -1, "registered_abms");
5156 luaL_checktype(L, -1, LUA_TTABLE);
5157 int registered_abms = lua_gettop(L);
5159 if(lua_istable(L, registered_abms)){
5160 int table = lua_gettop(L);
5162 while(lua_next(L, table) != 0){
5163 // key at index -2 and value at index -1
5164 int id = lua_tonumber(L, -2);
5165 int current_abm = lua_gettop(L);
5167 std::set<std::string> trigger_contents;
5168 lua_getfield(L, current_abm, "nodenames");
5169 if(lua_istable(L, -1)){
5170 int table = lua_gettop(L);
5172 while(lua_next(L, table) != 0){
5173 // key at index -2 and value at index -1
5174 luaL_checktype(L, -1, LUA_TSTRING);
5175 trigger_contents.insert(lua_tostring(L, -1));
5176 // removes value, keeps key for next iteration
5179 } else if(lua_isstring(L, -1)){
5180 trigger_contents.insert(lua_tostring(L, -1));
5184 std::set<std::string> required_neighbors;
5185 lua_getfield(L, current_abm, "neighbors");
5186 if(lua_istable(L, -1)){
5187 int table = lua_gettop(L);
5189 while(lua_next(L, table) != 0){
5190 // key at index -2 and value at index -1
5191 luaL_checktype(L, -1, LUA_TSTRING);
5192 required_neighbors.insert(lua_tostring(L, -1));
5193 // removes value, keeps key for next iteration
5196 } else if(lua_isstring(L, -1)){
5197 required_neighbors.insert(lua_tostring(L, -1));
5201 float trigger_interval = 10.0;
5202 getfloatfield(L, current_abm, "interval", trigger_interval);
5204 int trigger_chance = 50;
5205 getintfield(L, current_abm, "chance", trigger_chance);
5207 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5208 required_neighbors, trigger_interval, trigger_chance);
5210 env->addActiveBlockModifier(abm);
5212 // removes value, keeps key for next iteration
5220 // Dump stack top with the dump2 function
5221 static void dump2(lua_State *L, const char *name)
5223 // Dump object (debug)
5224 lua_getglobal(L, "dump2");
5225 luaL_checktype(L, -1, LUA_TFUNCTION);
5226 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5227 lua_pushstring(L, name);
5228 if(lua_pcall(L, 2, 0, 0))
5229 script_error(L, "error: %s", lua_tostring(L, -1));
5237 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5240 assert(lua_checkstack(L, 20));
5241 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5242 StackUnroller stack_unroller(L);
5244 // Create object on stack
5245 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5246 int object = lua_gettop(L);
5248 // Get minetest.object_refs table
5249 lua_getglobal(L, "minetest");
5250 lua_getfield(L, -1, "object_refs");
5251 luaL_checktype(L, -1, LUA_TTABLE);
5252 int objectstable = lua_gettop(L);
5254 // object_refs[id] = object
5255 lua_pushnumber(L, cobj->getId()); // Push id
5256 lua_pushvalue(L, object); // Copy object to top of stack
5257 lua_settable(L, objectstable);
5260 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5263 assert(lua_checkstack(L, 20));
5264 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5265 StackUnroller stack_unroller(L);
5267 // Get minetest.object_refs table
5268 lua_getglobal(L, "minetest");
5269 lua_getfield(L, -1, "object_refs");
5270 luaL_checktype(L, -1, LUA_TTABLE);
5271 int objectstable = lua_gettop(L);
5273 // Get object_refs[id]
5274 lua_pushnumber(L, cobj->getId()); // Push id
5275 lua_gettable(L, objectstable);
5276 // Set object reference to NULL
5277 ObjectRef::set_null(L);
5278 lua_pop(L, 1); // pop object
5280 // Set object_refs[id] = nil
5281 lua_pushnumber(L, cobj->getId()); // Push id
5283 lua_settable(L, objectstable);
5290 // What scriptapi_run_callbacks does with the return values of callbacks.
5291 // Regardless of the mode, if only one callback is defined,
5292 // its return value is the total return value.
5293 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5294 enum RunCallbacksMode
5296 // Returns the return value of the first callback
5297 // Returns nil if list of callbacks is empty
5298 RUN_CALLBACKS_MODE_FIRST,
5299 // Returns the return value of the last callback
5300 // Returns nil if list of callbacks is empty
5301 RUN_CALLBACKS_MODE_LAST,
5302 // If any callback returns a false value, the first such is returned
5303 // Otherwise, the first callback's return value (trueish) is returned
5304 // Returns true if list of callbacks is empty
5305 RUN_CALLBACKS_MODE_AND,
5306 // Like above, but stops calling callbacks (short circuit)
5307 // after seeing the first false value
5308 RUN_CALLBACKS_MODE_AND_SC,
5309 // If any callback returns a true value, the first such is returned
5310 // Otherwise, the first callback's return value (falseish) is returned
5311 // Returns false if list of callbacks is empty
5312 RUN_CALLBACKS_MODE_OR,
5313 // Like above, but stops calling callbacks (short circuit)
5314 // after seeing the first true value
5315 RUN_CALLBACKS_MODE_OR_SC,
5316 // Note: "a true value" and "a false value" refer to values that
5317 // are converted by lua_toboolean to true or false, respectively.
5320 // Push the list of callbacks (a lua table).
5321 // Then push nargs arguments.
5322 // Then call this function, which
5323 // - runs the callbacks
5324 // - removes the table and arguments from the lua stack
5325 // - pushes the return value, computed depending on mode
5326 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5327 RunCallbacksMode mode)
5329 // Insert the return value into the lua stack, below the table
5330 assert(lua_gettop(L) >= nargs + 1);
5332 lua_insert(L, -(nargs + 1) - 1);
5333 // Stack now looks like this:
5334 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5336 int rv = lua_gettop(L) - nargs - 1;
5338 int arg = table + 1;
5340 luaL_checktype(L, table, LUA_TTABLE);
5344 bool first_loop = true;
5345 while(lua_next(L, table) != 0){
5346 // key at index -2 and value at index -1
5347 luaL_checktype(L, -1, LUA_TFUNCTION);
5349 for(int i = 0; i < nargs; i++)
5350 lua_pushvalue(L, arg+i);
5351 if(lua_pcall(L, nargs, 1, 0))
5352 script_error(L, "error: %s", lua_tostring(L, -1));
5354 // Move return value to designated space in stack
5357 // Result of first callback is always moved
5361 // Otherwise, what happens depends on the mode
5362 if(mode == RUN_CALLBACKS_MODE_FIRST)
5364 else if(mode == RUN_CALLBACKS_MODE_LAST)
5366 else if(mode == RUN_CALLBACKS_MODE_AND ||
5367 mode == RUN_CALLBACKS_MODE_AND_SC){
5368 if(lua_toboolean(L, rv) == true &&
5369 lua_toboolean(L, -1) == false)
5374 else if(mode == RUN_CALLBACKS_MODE_OR ||
5375 mode == RUN_CALLBACKS_MODE_OR_SC){
5376 if(lua_toboolean(L, rv) == false &&
5377 lua_toboolean(L, -1) == true)
5386 // Handle short circuit modes
5387 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5388 lua_toboolean(L, rv) == false)
5390 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5391 lua_toboolean(L, rv) == true)
5394 // value removed, keep key for next iteration
5397 // Remove stuff from stack, leaving only the return value
5400 // Fix return value in case no callbacks were called
5402 if(mode == RUN_CALLBACKS_MODE_AND ||
5403 mode == RUN_CALLBACKS_MODE_AND_SC){
5405 lua_pushboolean(L, true);
5407 else if(mode == RUN_CALLBACKS_MODE_OR ||
5408 mode == RUN_CALLBACKS_MODE_OR_SC){
5410 lua_pushboolean(L, false);
5415 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5416 const std::string &message)
5419 assert(lua_checkstack(L, 20));
5420 StackUnroller stack_unroller(L);
5422 // Get minetest.registered_on_chat_messages
5423 lua_getglobal(L, "minetest");
5424 lua_getfield(L, -1, "registered_on_chat_messages");
5426 lua_pushstring(L, name.c_str());
5427 lua_pushstring(L, message.c_str());
5428 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5429 bool ate = lua_toboolean(L, -1);
5433 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5436 assert(lua_checkstack(L, 20));
5437 StackUnroller stack_unroller(L);
5439 // Get minetest.registered_on_newplayers
5440 lua_getglobal(L, "minetest");
5441 lua_getfield(L, -1, "registered_on_newplayers");
5443 objectref_get_or_create(L, player);
5444 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5447 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5450 assert(lua_checkstack(L, 20));
5451 StackUnroller stack_unroller(L);
5453 // Get minetest.registered_on_dieplayers
5454 lua_getglobal(L, "minetest");
5455 lua_getfield(L, -1, "registered_on_dieplayers");
5457 objectref_get_or_create(L, player);
5458 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5461 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5464 assert(lua_checkstack(L, 20));
5465 StackUnroller stack_unroller(L);
5467 // Get minetest.registered_on_respawnplayers
5468 lua_getglobal(L, "minetest");
5469 lua_getfield(L, -1, "registered_on_respawnplayers");
5471 objectref_get_or_create(L, player);
5472 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5473 bool positioning_handled_by_some = lua_toboolean(L, -1);
5474 return positioning_handled_by_some;
5477 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5480 assert(lua_checkstack(L, 20));
5481 StackUnroller stack_unroller(L);
5483 // Get minetest.registered_on_joinplayers
5484 lua_getglobal(L, "minetest");
5485 lua_getfield(L, -1, "registered_on_joinplayers");
5487 objectref_get_or_create(L, player);
5488 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5491 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5494 assert(lua_checkstack(L, 20));
5495 StackUnroller stack_unroller(L);
5497 // Get minetest.registered_on_leaveplayers
5498 lua_getglobal(L, "minetest");
5499 lua_getfield(L, -1, "registered_on_leaveplayers");
5501 objectref_get_or_create(L, player);
5502 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5505 static void get_auth_handler(lua_State *L)
5507 lua_getglobal(L, "minetest");
5508 lua_getfield(L, -1, "registered_auth_handler");
5509 if(lua_isnil(L, -1)){
5511 lua_getfield(L, -1, "builtin_auth_handler");
5513 if(lua_type(L, -1) != LUA_TTABLE)
5514 throw LuaError(L, "Authentication handler table not valid");
5517 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5518 std::string *dst_password, std::set<std::string> *dst_privs)
5521 assert(lua_checkstack(L, 20));
5522 StackUnroller stack_unroller(L);
5524 get_auth_handler(L);
5525 lua_getfield(L, -1, "get_auth");
5526 if(lua_type(L, -1) != LUA_TFUNCTION)
5527 throw LuaError(L, "Authentication handler missing get_auth");
5528 lua_pushstring(L, playername.c_str());
5529 if(lua_pcall(L, 1, 1, 0))
5530 script_error(L, "error: %s", lua_tostring(L, -1));
5532 // nil = login not allowed
5533 if(lua_isnil(L, -1))
5535 luaL_checktype(L, -1, LUA_TTABLE);
5537 std::string password;
5538 bool found = getstringfield(L, -1, "password", password);
5540 throw LuaError(L, "Authentication handler didn't return password");
5542 *dst_password = password;
5544 lua_getfield(L, -1, "privileges");
5545 if(!lua_istable(L, -1))
5547 "Authentication handler didn't return privilege table");
5549 read_privileges(L, -1, *dst_privs);
5555 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5556 const std::string &password)
5559 assert(lua_checkstack(L, 20));
5560 StackUnroller stack_unroller(L);
5562 get_auth_handler(L);
5563 lua_getfield(L, -1, "create_auth");
5564 if(lua_type(L, -1) != LUA_TFUNCTION)
5565 throw LuaError(L, "Authentication handler missing create_auth");
5566 lua_pushstring(L, playername.c_str());
5567 lua_pushstring(L, password.c_str());
5568 if(lua_pcall(L, 2, 0, 0))
5569 script_error(L, "error: %s", lua_tostring(L, -1));
5572 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5573 const std::string &password)
5576 assert(lua_checkstack(L, 20));
5577 StackUnroller stack_unroller(L);
5579 get_auth_handler(L);
5580 lua_getfield(L, -1, "set_password");
5581 if(lua_type(L, -1) != LUA_TFUNCTION)
5582 throw LuaError(L, "Authentication handler missing set_password");
5583 lua_pushstring(L, playername.c_str());
5584 lua_pushstring(L, password.c_str());
5585 if(lua_pcall(L, 2, 1, 0))
5586 script_error(L, "error: %s", lua_tostring(L, -1));
5587 return lua_toboolean(L, -1);
5594 void scriptapi_on_player_receive_fields(lua_State *L,
5595 ServerActiveObject *player,
5596 const std::string &formname,
5597 const std::map<std::string, std::string> &fields)
5600 assert(lua_checkstack(L, 20));
5601 StackUnroller stack_unroller(L);
5603 // Get minetest.registered_on_chat_messages
5604 lua_getglobal(L, "minetest");
5605 lua_getfield(L, -1, "registered_on_player_receive_fields");
5608 objectref_get_or_create(L, player);
5610 lua_pushstring(L, formname.c_str());
5613 for(std::map<std::string, std::string>::const_iterator
5614 i = fields.begin(); i != fields.end(); i++){
5615 const std::string &name = i->first;
5616 const std::string &value = i->second;
5617 lua_pushstring(L, name.c_str());
5618 lua_pushlstring(L, value.c_str(), value.size());
5619 lua_settable(L, -3);
5621 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5625 item callbacks and node callbacks
5628 // Retrieves minetest.registered_items[name][callbackname]
5629 // If that is nil or on error, return false and stack is unchanged
5630 // If that is a function, returns true and pushes the
5631 // function onto the stack
5632 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5633 // is tried instead so unknown items can still be manipulated to some degree
5634 static bool get_item_callback(lua_State *L,
5635 const char *name, const char *callbackname)
5637 lua_getglobal(L, "minetest");
5638 lua_getfield(L, -1, "registered_items");
5640 luaL_checktype(L, -1, LUA_TTABLE);
5641 lua_getfield(L, -1, name);
5643 // Should be a table
5644 if(lua_type(L, -1) != LUA_TTABLE)
5646 // Report error and clean up
5647 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5650 // Try minetest.nodedef_default instead
5651 lua_getglobal(L, "minetest");
5652 lua_getfield(L, -1, "nodedef_default");
5654 luaL_checktype(L, -1, LUA_TTABLE);
5656 lua_getfield(L, -1, callbackname);
5658 // Should be a function or nil
5659 if(lua_type(L, -1) == LUA_TFUNCTION)
5663 else if(lua_isnil(L, -1))
5670 errorstream<<"Item \""<<name<<"\" callback \""
5671 <<callbackname<<" is not a function"<<std::endl;
5677 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5678 ServerActiveObject *dropper, v3f pos)
5681 assert(lua_checkstack(L, 20));
5682 StackUnroller stack_unroller(L);
5684 // Push callback function on stack
5685 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5689 LuaItemStack::create(L, item);
5690 objectref_get_or_create(L, dropper);
5691 pushFloatPos(L, pos);
5692 if(lua_pcall(L, 3, 1, 0))
5693 script_error(L, "error: %s", lua_tostring(L, -1));
5694 if(!lua_isnil(L, -1))
5695 item = read_item(L, -1);
5699 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5700 ServerActiveObject *placer, const PointedThing &pointed)
5703 assert(lua_checkstack(L, 20));
5704 StackUnroller stack_unroller(L);
5706 // Push callback function on stack
5707 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5711 LuaItemStack::create(L, item);
5712 objectref_get_or_create(L, placer);
5713 push_pointed_thing(L, pointed);
5714 if(lua_pcall(L, 3, 1, 0))
5715 script_error(L, "error: %s", lua_tostring(L, -1));
5716 if(!lua_isnil(L, -1))
5717 item = read_item(L, -1);
5721 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5722 ServerActiveObject *user, const PointedThing &pointed)
5725 assert(lua_checkstack(L, 20));
5726 StackUnroller stack_unroller(L);
5728 // Push callback function on stack
5729 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5733 LuaItemStack::create(L, item);
5734 objectref_get_or_create(L, user);
5735 push_pointed_thing(L, pointed);
5736 if(lua_pcall(L, 3, 1, 0))
5737 script_error(L, "error: %s", lua_tostring(L, -1));
5738 if(!lua_isnil(L, -1))
5739 item = read_item(L, -1);
5743 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5744 ServerActiveObject *puncher)
5747 assert(lua_checkstack(L, 20));
5748 StackUnroller stack_unroller(L);
5750 INodeDefManager *ndef = get_server(L)->ndef();
5752 // Push callback function on stack
5753 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5758 pushnode(L, node, ndef);
5759 objectref_get_or_create(L, puncher);
5760 if(lua_pcall(L, 3, 0, 0))
5761 script_error(L, "error: %s", lua_tostring(L, -1));
5765 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5766 ServerActiveObject *digger)
5769 assert(lua_checkstack(L, 20));
5770 StackUnroller stack_unroller(L);
5772 INodeDefManager *ndef = get_server(L)->ndef();
5774 // Push callback function on stack
5775 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5780 pushnode(L, node, ndef);
5781 objectref_get_or_create(L, digger);
5782 if(lua_pcall(L, 3, 0, 0))
5783 script_error(L, "error: %s", lua_tostring(L, -1));
5787 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5790 assert(lua_checkstack(L, 20));
5791 StackUnroller stack_unroller(L);
5793 INodeDefManager *ndef = get_server(L)->ndef();
5795 // Push callback function on stack
5796 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5801 if(lua_pcall(L, 1, 0, 0))
5802 script_error(L, "error: %s", lua_tostring(L, -1));
5805 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5808 assert(lua_checkstack(L, 20));
5809 StackUnroller stack_unroller(L);
5811 INodeDefManager *ndef = get_server(L)->ndef();
5813 // Push callback function on stack
5814 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5819 if(lua_pcall(L, 1, 0, 0))
5820 script_error(L, "error: %s", lua_tostring(L, -1));
5823 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5826 assert(lua_checkstack(L, 20));
5827 StackUnroller stack_unroller(L);
5829 INodeDefManager *ndef = get_server(L)->ndef();
5831 // Push callback function on stack
5832 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5837 pushnode(L, node, ndef);
5838 if(lua_pcall(L, 2, 0, 0))
5839 script_error(L, "error: %s", lua_tostring(L, -1));
5842 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5845 assert(lua_checkstack(L, 20));
5846 StackUnroller stack_unroller(L);
5848 INodeDefManager *ndef = get_server(L)->ndef();
5850 // Push callback function on stack
5851 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5856 lua_pushnumber(L,dtime);
5857 if(lua_pcall(L, 2, 1, 0))
5858 script_error(L, "error: %s", lua_tostring(L, -1));
5859 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5865 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5866 const std::string &formname,
5867 const std::map<std::string, std::string> &fields,
5868 ServerActiveObject *sender)
5871 assert(lua_checkstack(L, 20));
5872 StackUnroller stack_unroller(L);
5874 INodeDefManager *ndef = get_server(L)->ndef();
5876 // If node doesn't exist, we don't know what callback to call
5877 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5878 if(node.getContent() == CONTENT_IGNORE)
5881 // Push callback function on stack
5882 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5889 lua_pushstring(L, formname.c_str());
5892 for(std::map<std::string, std::string>::const_iterator
5893 i = fields.begin(); i != fields.end(); i++){
5894 const std::string &name = i->first;
5895 const std::string &value = i->second;
5896 lua_pushstring(L, name.c_str());
5897 lua_pushlstring(L, value.c_str(), value.size());
5898 lua_settable(L, -3);
5901 objectref_get_or_create(L, sender);
5902 if(lua_pcall(L, 4, 0, 0))
5903 script_error(L, "error: %s", lua_tostring(L, -1));
5907 Node metadata inventory callbacks
5910 // Return number of accepted items to be moved
5911 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5912 const std::string &from_list, int from_index,
5913 const std::string &to_list, int to_index,
5914 int count, ServerActiveObject *player)
5917 assert(lua_checkstack(L, 20));
5918 StackUnroller stack_unroller(L);
5920 INodeDefManager *ndef = get_server(L)->ndef();
5922 // If node doesn't exist, we don't know what callback to call
5923 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5924 if(node.getContent() == CONTENT_IGNORE)
5927 // Push callback function on stack
5928 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5929 "allow_metadata_inventory_move"))
5932 // function(pos, from_list, from_index, to_list, to_index, count, player)
5936 lua_pushstring(L, from_list.c_str());
5938 lua_pushinteger(L, from_index + 1);
5940 lua_pushstring(L, to_list.c_str());
5942 lua_pushinteger(L, to_index + 1);
5944 lua_pushinteger(L, count);
5946 objectref_get_or_create(L, player);
5947 if(lua_pcall(L, 7, 1, 0))
5948 script_error(L, "error: %s", lua_tostring(L, -1));
5949 if(!lua_isnumber(L, -1))
5950 throw LuaError(L, "allow_metadata_inventory_move should return a number");
5951 return luaL_checkinteger(L, -1);
5954 // Return number of accepted items to be put
5955 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
5956 const std::string &listname, int index, ItemStack &stack,
5957 ServerActiveObject *player)
5960 assert(lua_checkstack(L, 20));
5961 StackUnroller stack_unroller(L);
5963 INodeDefManager *ndef = get_server(L)->ndef();
5965 // If node doesn't exist, we don't know what callback to call
5966 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5967 if(node.getContent() == CONTENT_IGNORE)
5970 // Push callback function on stack
5971 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5972 "allow_metadata_inventory_put"))
5975 // Call function(pos, listname, index, stack, player)
5979 lua_pushstring(L, listname.c_str());
5981 lua_pushinteger(L, index + 1);
5983 LuaItemStack::create(L, stack);
5985 objectref_get_or_create(L, player);
5986 if(lua_pcall(L, 5, 1, 0))
5987 script_error(L, "error: %s", lua_tostring(L, -1));
5988 if(!lua_isnumber(L, -1))
5989 throw LuaError(L, "allow_metadata_inventory_put should return a number");
5990 return luaL_checkinteger(L, -1);
5993 // Return number of accepted items to be taken
5994 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
5995 const std::string &listname, int index, ItemStack &stack,
5996 ServerActiveObject *player)
5999 assert(lua_checkstack(L, 20));
6000 StackUnroller stack_unroller(L);
6002 INodeDefManager *ndef = get_server(L)->ndef();
6004 // If node doesn't exist, we don't know what callback to call
6005 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6006 if(node.getContent() == CONTENT_IGNORE)
6009 // Push callback function on stack
6010 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6011 "allow_metadata_inventory_take"))
6014 // Call function(pos, listname, index, count, player)
6018 lua_pushstring(L, listname.c_str());
6020 lua_pushinteger(L, index + 1);
6022 LuaItemStack::create(L, stack);
6024 objectref_get_or_create(L, player);
6025 if(lua_pcall(L, 5, 1, 0))
6026 script_error(L, "error: %s", lua_tostring(L, -1));
6027 if(!lua_isnumber(L, -1))
6028 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6029 return luaL_checkinteger(L, -1);
6032 // Report moved items
6033 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6034 const std::string &from_list, int from_index,
6035 const std::string &to_list, int to_index,
6036 int count, ServerActiveObject *player)
6039 assert(lua_checkstack(L, 20));
6040 StackUnroller stack_unroller(L);
6042 INodeDefManager *ndef = get_server(L)->ndef();
6044 // If node doesn't exist, we don't know what callback to call
6045 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6046 if(node.getContent() == CONTENT_IGNORE)
6049 // Push callback function on stack
6050 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6051 "on_metadata_inventory_move"))
6054 // function(pos, from_list, from_index, to_list, to_index, count, player)
6058 lua_pushstring(L, from_list.c_str());
6060 lua_pushinteger(L, from_index + 1);
6062 lua_pushstring(L, to_list.c_str());
6064 lua_pushinteger(L, to_index + 1);
6066 lua_pushinteger(L, count);
6068 objectref_get_or_create(L, player);
6069 if(lua_pcall(L, 7, 0, 0))
6070 script_error(L, "error: %s", lua_tostring(L, -1));
6074 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6075 const std::string &listname, int index, ItemStack &stack,
6076 ServerActiveObject *player)
6079 assert(lua_checkstack(L, 20));
6080 StackUnroller stack_unroller(L);
6082 INodeDefManager *ndef = get_server(L)->ndef();
6084 // If node doesn't exist, we don't know what callback to call
6085 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6086 if(node.getContent() == CONTENT_IGNORE)
6089 // Push callback function on stack
6090 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6091 "on_metadata_inventory_put"))
6094 // Call function(pos, listname, index, stack, player)
6098 lua_pushstring(L, listname.c_str());
6100 lua_pushinteger(L, index + 1);
6102 LuaItemStack::create(L, stack);
6104 objectref_get_or_create(L, player);
6105 if(lua_pcall(L, 5, 0, 0))
6106 script_error(L, "error: %s", lua_tostring(L, -1));
6109 // Report taken items
6110 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6111 const std::string &listname, int index, ItemStack &stack,
6112 ServerActiveObject *player)
6115 assert(lua_checkstack(L, 20));
6116 StackUnroller stack_unroller(L);
6118 INodeDefManager *ndef = get_server(L)->ndef();
6120 // If node doesn't exist, we don't know what callback to call
6121 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6122 if(node.getContent() == CONTENT_IGNORE)
6125 // Push callback function on stack
6126 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6127 "on_metadata_inventory_take"))
6130 // Call function(pos, listname, index, stack, player)
6134 lua_pushstring(L, listname.c_str());
6136 lua_pushinteger(L, index + 1);
6138 LuaItemStack::create(L, stack);
6140 objectref_get_or_create(L, player);
6141 if(lua_pcall(L, 5, 0, 0))
6142 script_error(L, "error: %s", lua_tostring(L, -1));
6146 Detached inventory callbacks
6149 // Retrieves minetest.detached_inventories[name][callbackname]
6150 // If that is nil or on error, return false and stack is unchanged
6151 // If that is a function, returns true and pushes the
6152 // function onto the stack
6153 static bool get_detached_inventory_callback(lua_State *L,
6154 const std::string &name, const char *callbackname)
6156 lua_getglobal(L, "minetest");
6157 lua_getfield(L, -1, "detached_inventories");
6159 luaL_checktype(L, -1, LUA_TTABLE);
6160 lua_getfield(L, -1, name.c_str());
6162 // Should be a table
6163 if(lua_type(L, -1) != LUA_TTABLE)
6165 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6169 lua_getfield(L, -1, callbackname);
6171 // Should be a function or nil
6172 if(lua_type(L, -1) == LUA_TFUNCTION)
6176 else if(lua_isnil(L, -1))
6183 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6184 <<callbackname<<"\" is not a function"<<std::endl;
6190 // Return number of accepted items to be moved
6191 int scriptapi_detached_inventory_allow_move(lua_State *L,
6192 const std::string &name,
6193 const std::string &from_list, int from_index,
6194 const std::string &to_list, int to_index,
6195 int count, ServerActiveObject *player)
6198 assert(lua_checkstack(L, 20));
6199 StackUnroller stack_unroller(L);
6201 // Push callback function on stack
6202 if(!get_detached_inventory_callback(L, name, "allow_move"))
6205 // function(inv, from_list, from_index, to_list, to_index, count, player)
6207 InventoryLocation loc;
6208 loc.setDetached(name);
6209 InvRef::create(L, loc);
6211 lua_pushstring(L, from_list.c_str());
6213 lua_pushinteger(L, from_index + 1);
6215 lua_pushstring(L, to_list.c_str());
6217 lua_pushinteger(L, to_index + 1);
6219 lua_pushinteger(L, count);
6221 objectref_get_or_create(L, player);
6222 if(lua_pcall(L, 7, 1, 0))
6223 script_error(L, "error: %s", lua_tostring(L, -1));
6224 if(!lua_isnumber(L, -1))
6225 throw LuaError(L, "allow_move should return a number");
6226 return luaL_checkinteger(L, -1);
6229 // Return number of accepted items to be put
6230 int scriptapi_detached_inventory_allow_put(lua_State *L,
6231 const std::string &name,
6232 const std::string &listname, int index, ItemStack &stack,
6233 ServerActiveObject *player)
6236 assert(lua_checkstack(L, 20));
6237 StackUnroller stack_unroller(L);
6239 // Push callback function on stack
6240 if(!get_detached_inventory_callback(L, name, "allow_put"))
6241 return stack.count; // All will be accepted
6243 // Call function(inv, listname, index, stack, player)
6245 InventoryLocation loc;
6246 loc.setDetached(name);
6247 InvRef::create(L, loc);
6249 lua_pushstring(L, listname.c_str());
6251 lua_pushinteger(L, index + 1);
6253 LuaItemStack::create(L, stack);
6255 objectref_get_or_create(L, player);
6256 if(lua_pcall(L, 5, 1, 0))
6257 script_error(L, "error: %s", lua_tostring(L, -1));
6258 if(!lua_isnumber(L, -1))
6259 throw LuaError(L, "allow_put should return a number");
6260 return luaL_checkinteger(L, -1);
6263 // Return number of accepted items to be taken
6264 int scriptapi_detached_inventory_allow_take(lua_State *L,
6265 const std::string &name,
6266 const std::string &listname, int index, ItemStack &stack,
6267 ServerActiveObject *player)
6270 assert(lua_checkstack(L, 20));
6271 StackUnroller stack_unroller(L);
6273 // Push callback function on stack
6274 if(!get_detached_inventory_callback(L, name, "allow_take"))
6275 return stack.count; // All will be accepted
6277 // Call function(inv, listname, index, stack, player)
6279 InventoryLocation loc;
6280 loc.setDetached(name);
6281 InvRef::create(L, loc);
6283 lua_pushstring(L, listname.c_str());
6285 lua_pushinteger(L, index + 1);
6287 LuaItemStack::create(L, stack);
6289 objectref_get_or_create(L, player);
6290 if(lua_pcall(L, 5, 1, 0))
6291 script_error(L, "error: %s", lua_tostring(L, -1));
6292 if(!lua_isnumber(L, -1))
6293 throw LuaError(L, "allow_take should return a number");
6294 return luaL_checkinteger(L, -1);
6297 // Report moved items
6298 void scriptapi_detached_inventory_on_move(lua_State *L,
6299 const std::string &name,
6300 const std::string &from_list, int from_index,
6301 const std::string &to_list, int to_index,
6302 int count, ServerActiveObject *player)
6305 assert(lua_checkstack(L, 20));
6306 StackUnroller stack_unroller(L);
6308 // Push callback function on stack
6309 if(!get_detached_inventory_callback(L, name, "on_move"))
6312 // function(inv, from_list, from_index, to_list, to_index, count, player)
6314 InventoryLocation loc;
6315 loc.setDetached(name);
6316 InvRef::create(L, loc);
6318 lua_pushstring(L, from_list.c_str());
6320 lua_pushinteger(L, from_index + 1);
6322 lua_pushstring(L, to_list.c_str());
6324 lua_pushinteger(L, to_index + 1);
6326 lua_pushinteger(L, count);
6328 objectref_get_or_create(L, player);
6329 if(lua_pcall(L, 7, 0, 0))
6330 script_error(L, "error: %s", lua_tostring(L, -1));
6334 void scriptapi_detached_inventory_on_put(lua_State *L,
6335 const std::string &name,
6336 const std::string &listname, int index, ItemStack &stack,
6337 ServerActiveObject *player)
6340 assert(lua_checkstack(L, 20));
6341 StackUnroller stack_unroller(L);
6343 // Push callback function on stack
6344 if(!get_detached_inventory_callback(L, name, "on_put"))
6347 // Call function(inv, listname, index, stack, player)
6349 InventoryLocation loc;
6350 loc.setDetached(name);
6351 InvRef::create(L, loc);
6353 lua_pushstring(L, listname.c_str());
6355 lua_pushinteger(L, index + 1);
6357 LuaItemStack::create(L, stack);
6359 objectref_get_or_create(L, player);
6360 if(lua_pcall(L, 5, 0, 0))
6361 script_error(L, "error: %s", lua_tostring(L, -1));
6364 // Report taken items
6365 void scriptapi_detached_inventory_on_take(lua_State *L,
6366 const std::string &name,
6367 const std::string &listname, int index, ItemStack &stack,
6368 ServerActiveObject *player)
6371 assert(lua_checkstack(L, 20));
6372 StackUnroller stack_unroller(L);
6374 // Push callback function on stack
6375 if(!get_detached_inventory_callback(L, name, "on_take"))
6378 // Call function(inv, listname, index, stack, player)
6380 InventoryLocation loc;
6381 loc.setDetached(name);
6382 InvRef::create(L, loc);
6384 lua_pushstring(L, listname.c_str());
6386 lua_pushinteger(L, index + 1);
6388 LuaItemStack::create(L, stack);
6390 objectref_get_or_create(L, player);
6391 if(lua_pcall(L, 5, 0, 0))
6392 script_error(L, "error: %s", lua_tostring(L, -1));
6399 void scriptapi_environment_step(lua_State *L, float dtime)
6402 assert(lua_checkstack(L, 20));
6403 //infostream<<"scriptapi_environment_step"<<std::endl;
6404 StackUnroller stack_unroller(L);
6406 // Get minetest.registered_globalsteps
6407 lua_getglobal(L, "minetest");
6408 lua_getfield(L, -1, "registered_globalsteps");
6410 lua_pushnumber(L, dtime);
6411 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6414 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6418 assert(lua_checkstack(L, 20));
6419 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6420 StackUnroller stack_unroller(L);
6422 // Get minetest.registered_on_generateds
6423 lua_getglobal(L, "minetest");
6424 lua_getfield(L, -1, "registered_on_generateds");
6426 push_v3s16(L, minp);
6427 push_v3s16(L, maxp);
6428 lua_pushnumber(L, blockseed);
6429 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6436 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6439 assert(lua_checkstack(L, 20));
6440 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6441 <<name<<"\""<<std::endl;
6442 StackUnroller stack_unroller(L);
6444 // Get minetest.registered_entities[name]
6445 lua_getglobal(L, "minetest");
6446 lua_getfield(L, -1, "registered_entities");
6447 luaL_checktype(L, -1, LUA_TTABLE);
6448 lua_pushstring(L, name);
6449 lua_gettable(L, -2);
6450 // Should be a table, which we will use as a prototype
6451 //luaL_checktype(L, -1, LUA_TTABLE);
6452 if(lua_type(L, -1) != LUA_TTABLE){
6453 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6456 int prototype_table = lua_gettop(L);
6457 //dump2(L, "prototype_table");
6459 // Create entity object
6461 int object = lua_gettop(L);
6463 // Set object metatable
6464 lua_pushvalue(L, prototype_table);
6465 lua_setmetatable(L, -2);
6467 // Add object reference
6468 // This should be userdata with metatable ObjectRef
6469 objectref_get(L, id);
6470 luaL_checktype(L, -1, LUA_TUSERDATA);
6471 if(!luaL_checkudata(L, -1, "ObjectRef"))
6472 luaL_typerror(L, -1, "ObjectRef");
6473 lua_setfield(L, -2, "object");
6475 // minetest.luaentities[id] = object
6476 lua_getglobal(L, "minetest");
6477 lua_getfield(L, -1, "luaentities");
6478 luaL_checktype(L, -1, LUA_TTABLE);
6479 lua_pushnumber(L, id); // Push id
6480 lua_pushvalue(L, object); // Copy object to top of stack
6481 lua_settable(L, -3);
6486 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6487 const std::string &staticdata, u32 dtime_s)
6490 assert(lua_checkstack(L, 20));
6491 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6492 StackUnroller stack_unroller(L);
6494 // Get minetest.luaentities[id]
6495 luaentity_get(L, id);
6496 int object = lua_gettop(L);
6498 // Get on_activate function
6499 lua_pushvalue(L, object);
6500 lua_getfield(L, -1, "on_activate");
6501 if(!lua_isnil(L, -1)){
6502 luaL_checktype(L, -1, LUA_TFUNCTION);
6503 lua_pushvalue(L, object); // self
6504 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6505 lua_pushinteger(L, dtime_s);
6506 // Call with 3 arguments, 0 results
6507 if(lua_pcall(L, 3, 0, 0))
6508 script_error(L, "error running function on_activate: %s\n",
6509 lua_tostring(L, -1));
6513 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6516 assert(lua_checkstack(L, 20));
6517 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6519 // Get minetest.luaentities table
6520 lua_getglobal(L, "minetest");
6521 lua_getfield(L, -1, "luaentities");
6522 luaL_checktype(L, -1, LUA_TTABLE);
6523 int objectstable = lua_gettop(L);
6525 // Set luaentities[id] = nil
6526 lua_pushnumber(L, id); // Push id
6528 lua_settable(L, objectstable);
6530 lua_pop(L, 2); // pop luaentities, minetest
6533 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6536 assert(lua_checkstack(L, 20));
6537 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6538 StackUnroller stack_unroller(L);
6540 // Get minetest.luaentities[id]
6541 luaentity_get(L, id);
6542 int object = lua_gettop(L);
6544 // Get get_staticdata function
6545 lua_pushvalue(L, object);
6546 lua_getfield(L, -1, "get_staticdata");
6547 if(lua_isnil(L, -1))
6550 luaL_checktype(L, -1, LUA_TFUNCTION);
6551 lua_pushvalue(L, object); // self
6552 // Call with 1 arguments, 1 results
6553 if(lua_pcall(L, 1, 1, 0))
6554 script_error(L, "error running function get_staticdata: %s\n",
6555 lua_tostring(L, -1));
6558 const char *s = lua_tolstring(L, -1, &len);
6559 return std::string(s, len);
6562 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6563 ObjectProperties *prop)
6566 assert(lua_checkstack(L, 20));
6567 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6568 StackUnroller stack_unroller(L);
6570 // Get minetest.luaentities[id]
6571 luaentity_get(L, id);
6572 //int object = lua_gettop(L);
6574 // Set default values that differ from ObjectProperties defaults
6579 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6581 getboolfield(L, -1, "physical", prop->physical);
6583 getfloatfield(L, -1, "weight", prop->weight);
6585 lua_getfield(L, -1, "collisionbox");
6586 if(lua_istable(L, -1))
6587 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6590 getstringfield(L, -1, "visual", prop->visual);
6592 // Deprecated: read object properties directly
6593 read_object_properties(L, -1, prop);
6595 // Read initial_properties
6596 lua_getfield(L, -1, "initial_properties");
6597 read_object_properties(L, -1, prop);
6601 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6604 assert(lua_checkstack(L, 20));
6605 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6606 StackUnroller stack_unroller(L);
6608 // Get minetest.luaentities[id]
6609 luaentity_get(L, id);
6610 int object = lua_gettop(L);
6611 // State: object is at top of stack
6612 // Get step function
6613 lua_getfield(L, -1, "on_step");
6614 if(lua_isnil(L, -1))
6616 luaL_checktype(L, -1, LUA_TFUNCTION);
6617 lua_pushvalue(L, object); // self
6618 lua_pushnumber(L, dtime); // dtime
6619 // Call with 2 arguments, 0 results
6620 if(lua_pcall(L, 2, 0, 0))
6621 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6624 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6625 // tool_capabilities, direction)
6626 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6627 ServerActiveObject *puncher, float time_from_last_punch,
6628 const ToolCapabilities *toolcap, v3f dir)
6631 assert(lua_checkstack(L, 20));
6632 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6633 StackUnroller stack_unroller(L);
6635 // Get minetest.luaentities[id]
6636 luaentity_get(L, id);
6637 int object = lua_gettop(L);
6638 // State: object is at top of stack
6640 lua_getfield(L, -1, "on_punch");
6641 if(lua_isnil(L, -1))
6643 luaL_checktype(L, -1, LUA_TFUNCTION);
6644 lua_pushvalue(L, object); // self
6645 objectref_get_or_create(L, puncher); // Clicker reference
6646 lua_pushnumber(L, time_from_last_punch);
6647 push_tool_capabilities(L, *toolcap);
6649 // Call with 5 arguments, 0 results
6650 if(lua_pcall(L, 5, 0, 0))
6651 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6654 // Calls entity:on_rightclick(ObjectRef clicker)
6655 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6656 ServerActiveObject *clicker)
6659 assert(lua_checkstack(L, 20));
6660 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6661 StackUnroller stack_unroller(L);
6663 // Get minetest.luaentities[id]
6664 luaentity_get(L, id);
6665 int object = lua_gettop(L);
6666 // State: object is at top of stack
6668 lua_getfield(L, -1, "on_rightclick");
6669 if(lua_isnil(L, -1))
6671 luaL_checktype(L, -1, LUA_TFUNCTION);
6672 lua_pushvalue(L, object); // self
6673 objectref_get_or_create(L, clicker); // Clicker reference
6674 // Call with 2 arguments, 0 results
6675 if(lua_pcall(L, 2, 0, 0))
6676 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));