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 // Amount of light the node emits
1242 f.light_source = getintfield_default(L, index,
1243 "light_source", f.light_source);
1244 f.damage_per_second = getintfield_default(L, index,
1245 "damage_per_second", f.damage_per_second);
1247 lua_getfield(L, index, "node_box");
1248 if(lua_istable(L, -1))
1249 f.node_box = read_nodebox(L, -1);
1252 lua_getfield(L, index, "selection_box");
1253 if(lua_istable(L, -1))
1254 f.selection_box = read_nodebox(L, -1);
1257 // Set to true if paramtype used to be 'facedir_simple'
1258 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1259 // Set to true if wall_mounted used to be set to true
1260 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1263 lua_getfield(L, index, "sounds");
1264 if(lua_istable(L, -1)){
1265 lua_getfield(L, -1, "footstep");
1266 read_soundspec(L, -1, f.sound_footstep);
1268 lua_getfield(L, -1, "dig");
1269 read_soundspec(L, -1, f.sound_dig);
1271 lua_getfield(L, -1, "dug");
1272 read_soundspec(L, -1, f.sound_dug);
1284 static ItemStack read_item(lua_State *L, int index);
1285 static std::vector<ItemStack> read_items(lua_State *L, int index);
1286 // creates a table of ItemStacks
1287 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1289 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1290 lua_State *L, int tableindex, int forcesize=-1)
1293 tableindex = lua_gettop(L) + 1 + tableindex;
1294 // If nil, delete list
1295 if(lua_isnil(L, tableindex)){
1296 inv->deleteList(name);
1299 // Otherwise set list
1300 std::vector<ItemStack> items = read_items(L, tableindex);
1301 int listsize = (forcesize != -1) ? forcesize : items.size();
1302 InventoryList *invlist = inv->addList(name, listsize);
1304 for(std::vector<ItemStack>::const_iterator
1305 i = items.begin(); i != items.end(); i++){
1306 if(forcesize != -1 && index == forcesize)
1308 invlist->changeItem(index, *i);
1311 while(forcesize != -1 && index < forcesize){
1312 invlist->deleteItem(index);
1317 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1320 InventoryList *invlist = inv->getList(name);
1321 if(invlist == NULL){
1325 std::vector<ItemStack> items;
1326 for(u32 i=0; i<invlist->getSize(); i++)
1327 items.push_back(invlist->getItem(i));
1328 push_items(L, items);
1332 Helpful macros for userdata classes
1335 #define method(class, name) {#name, class::l_##name}
1346 static const char className[];
1347 static const luaL_reg methods[];
1349 // Exported functions
1351 // garbage collector
1352 static int gc_object(lua_State *L)
1354 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1359 // is_empty(self) -> true/false
1360 static int l_is_empty(lua_State *L)
1362 LuaItemStack *o = checkobject(L, 1);
1363 ItemStack &item = o->m_stack;
1364 lua_pushboolean(L, item.empty());
1368 // get_name(self) -> string
1369 static int l_get_name(lua_State *L)
1371 LuaItemStack *o = checkobject(L, 1);
1372 ItemStack &item = o->m_stack;
1373 lua_pushstring(L, item.name.c_str());
1377 // get_count(self) -> number
1378 static int l_get_count(lua_State *L)
1380 LuaItemStack *o = checkobject(L, 1);
1381 ItemStack &item = o->m_stack;
1382 lua_pushinteger(L, item.count);
1386 // get_wear(self) -> number
1387 static int l_get_wear(lua_State *L)
1389 LuaItemStack *o = checkobject(L, 1);
1390 ItemStack &item = o->m_stack;
1391 lua_pushinteger(L, item.wear);
1395 // get_metadata(self) -> string
1396 static int l_get_metadata(lua_State *L)
1398 LuaItemStack *o = checkobject(L, 1);
1399 ItemStack &item = o->m_stack;
1400 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1404 // clear(self) -> true
1405 static int l_clear(lua_State *L)
1407 LuaItemStack *o = checkobject(L, 1);
1409 lua_pushboolean(L, true);
1413 // replace(self, itemstack or itemstring or table or nil) -> true
1414 static int l_replace(lua_State *L)
1416 LuaItemStack *o = checkobject(L, 1);
1417 o->m_stack = read_item(L, 2);
1418 lua_pushboolean(L, true);
1422 // to_string(self) -> string
1423 static int l_to_string(lua_State *L)
1425 LuaItemStack *o = checkobject(L, 1);
1426 std::string itemstring = o->m_stack.getItemString();
1427 lua_pushstring(L, itemstring.c_str());
1431 // to_table(self) -> table or nil
1432 static int l_to_table(lua_State *L)
1434 LuaItemStack *o = checkobject(L, 1);
1435 const ItemStack &item = o->m_stack;
1443 lua_pushstring(L, item.name.c_str());
1444 lua_setfield(L, -2, "name");
1445 lua_pushinteger(L, item.count);
1446 lua_setfield(L, -2, "count");
1447 lua_pushinteger(L, item.wear);
1448 lua_setfield(L, -2, "wear");
1449 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1450 lua_setfield(L, -2, "metadata");
1455 // get_stack_max(self) -> number
1456 static int l_get_stack_max(lua_State *L)
1458 LuaItemStack *o = checkobject(L, 1);
1459 ItemStack &item = o->m_stack;
1460 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1464 // get_free_space(self) -> number
1465 static int l_get_free_space(lua_State *L)
1467 LuaItemStack *o = checkobject(L, 1);
1468 ItemStack &item = o->m_stack;
1469 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1473 // is_known(self) -> true/false
1474 // Checks if the item is defined.
1475 static int l_is_known(lua_State *L)
1477 LuaItemStack *o = checkobject(L, 1);
1478 ItemStack &item = o->m_stack;
1479 bool is_known = item.isKnown(get_server(L)->idef());
1480 lua_pushboolean(L, is_known);
1484 // get_definition(self) -> table
1485 // Returns the item definition table from minetest.registered_items,
1486 // or a fallback one (name="unknown")
1487 static int l_get_definition(lua_State *L)
1489 LuaItemStack *o = checkobject(L, 1);
1490 ItemStack &item = o->m_stack;
1492 // Get minetest.registered_items[name]
1493 lua_getglobal(L, "minetest");
1494 lua_getfield(L, -1, "registered_items");
1495 luaL_checktype(L, -1, LUA_TTABLE);
1496 lua_getfield(L, -1, item.name.c_str());
1497 if(lua_isnil(L, -1))
1500 lua_getfield(L, -1, "unknown");
1505 // get_tool_capabilities(self) -> table
1506 // Returns the effective tool digging properties.
1507 // Returns those of the hand ("") if this item has none associated.
1508 static int l_get_tool_capabilities(lua_State *L)
1510 LuaItemStack *o = checkobject(L, 1);
1511 ItemStack &item = o->m_stack;
1512 const ToolCapabilities &prop =
1513 item.getToolCapabilities(get_server(L)->idef());
1514 push_tool_capabilities(L, prop);
1518 // add_wear(self, amount) -> true/false
1519 // The range for "amount" is [0,65535]. Wear is only added if the item
1520 // is a tool. Adding wear might destroy the item.
1521 // Returns true if the item is (or was) a tool.
1522 static int l_add_wear(lua_State *L)
1524 LuaItemStack *o = checkobject(L, 1);
1525 ItemStack &item = o->m_stack;
1526 int amount = lua_tointeger(L, 2);
1527 bool result = item.addWear(amount, get_server(L)->idef());
1528 lua_pushboolean(L, result);
1532 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1533 // Returns leftover item stack
1534 static int l_add_item(lua_State *L)
1536 LuaItemStack *o = checkobject(L, 1);
1537 ItemStack &item = o->m_stack;
1538 ItemStack newitem = read_item(L, 2);
1539 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1540 create(L, leftover);
1544 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1545 // First return value is true iff the new item fits fully into the stack
1546 // Second return value is the would-be-left-over item stack
1547 static int l_item_fits(lua_State *L)
1549 LuaItemStack *o = checkobject(L, 1);
1550 ItemStack &item = o->m_stack;
1551 ItemStack newitem = read_item(L, 2);
1553 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1554 lua_pushboolean(L, fits); // first return value
1555 create(L, restitem); // second return value
1559 // take_item(self, takecount=1) -> itemstack
1560 static int l_take_item(lua_State *L)
1562 LuaItemStack *o = checkobject(L, 1);
1563 ItemStack &item = o->m_stack;
1565 if(!lua_isnone(L, 2))
1566 takecount = luaL_checkinteger(L, 2);
1567 ItemStack taken = item.takeItem(takecount);
1572 // peek_item(self, peekcount=1) -> itemstack
1573 static int l_peek_item(lua_State *L)
1575 LuaItemStack *o = checkobject(L, 1);
1576 ItemStack &item = o->m_stack;
1578 if(!lua_isnone(L, 2))
1579 peekcount = lua_tointeger(L, 2);
1580 ItemStack peekaboo = item.peekItem(peekcount);
1581 create(L, peekaboo);
1586 LuaItemStack(const ItemStack &item):
1595 const ItemStack& getItem() const
1599 ItemStack& getItem()
1604 // LuaItemStack(itemstack or itemstring or table or nil)
1605 // Creates an LuaItemStack and leaves it on top of stack
1606 static int create_object(lua_State *L)
1608 ItemStack item = read_item(L, 1);
1609 LuaItemStack *o = new LuaItemStack(item);
1610 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1611 luaL_getmetatable(L, className);
1612 lua_setmetatable(L, -2);
1615 // Not callable from Lua
1616 static int create(lua_State *L, const ItemStack &item)
1618 LuaItemStack *o = new LuaItemStack(item);
1619 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1620 luaL_getmetatable(L, className);
1621 lua_setmetatable(L, -2);
1625 static LuaItemStack* checkobject(lua_State *L, int narg)
1627 luaL_checktype(L, narg, LUA_TUSERDATA);
1628 void *ud = luaL_checkudata(L, narg, className);
1629 if(!ud) luaL_typerror(L, narg, className);
1630 return *(LuaItemStack**)ud; // unbox pointer
1633 static void Register(lua_State *L)
1636 int methodtable = lua_gettop(L);
1637 luaL_newmetatable(L, className);
1638 int metatable = lua_gettop(L);
1640 lua_pushliteral(L, "__metatable");
1641 lua_pushvalue(L, methodtable);
1642 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1644 lua_pushliteral(L, "__index");
1645 lua_pushvalue(L, methodtable);
1646 lua_settable(L, metatable);
1648 lua_pushliteral(L, "__gc");
1649 lua_pushcfunction(L, gc_object);
1650 lua_settable(L, metatable);
1652 lua_pop(L, 1); // drop metatable
1654 luaL_openlib(L, 0, methods, 0); // fill methodtable
1655 lua_pop(L, 1); // drop methodtable
1657 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1658 lua_register(L, className, create_object);
1661 const char LuaItemStack::className[] = "ItemStack";
1662 const luaL_reg LuaItemStack::methods[] = {
1663 method(LuaItemStack, is_empty),
1664 method(LuaItemStack, get_name),
1665 method(LuaItemStack, get_count),
1666 method(LuaItemStack, get_wear),
1667 method(LuaItemStack, get_metadata),
1668 method(LuaItemStack, clear),
1669 method(LuaItemStack, replace),
1670 method(LuaItemStack, to_string),
1671 method(LuaItemStack, to_table),
1672 method(LuaItemStack, get_stack_max),
1673 method(LuaItemStack, get_free_space),
1674 method(LuaItemStack, is_known),
1675 method(LuaItemStack, get_definition),
1676 method(LuaItemStack, get_tool_capabilities),
1677 method(LuaItemStack, add_wear),
1678 method(LuaItemStack, add_item),
1679 method(LuaItemStack, item_fits),
1680 method(LuaItemStack, take_item),
1681 method(LuaItemStack, peek_item),
1685 static ItemStack read_item(lua_State *L, int index)
1688 index = lua_gettop(L) + 1 + index;
1690 if(lua_isnil(L, index))
1694 else if(lua_isuserdata(L, index))
1696 // Convert from LuaItemStack
1697 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1698 return o->getItem();
1700 else if(lua_isstring(L, index))
1702 // Convert from itemstring
1703 std::string itemstring = lua_tostring(L, index);
1704 IItemDefManager *idef = get_server(L)->idef();
1708 item.deSerialize(itemstring, idef);
1711 catch(SerializationError &e)
1713 infostream<<"WARNING: unable to create item from itemstring"
1714 <<": "<<itemstring<<std::endl;
1718 else if(lua_istable(L, index))
1720 // Convert from table
1721 IItemDefManager *idef = get_server(L)->idef();
1722 std::string name = getstringfield_default(L, index, "name", "");
1723 int count = getintfield_default(L, index, "count", 1);
1724 int wear = getintfield_default(L, index, "wear", 0);
1725 std::string metadata = getstringfield_default(L, index, "metadata", "");
1726 return ItemStack(name, count, wear, metadata, idef);
1730 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1734 static std::vector<ItemStack> read_items(lua_State *L, int index)
1737 index = lua_gettop(L) + 1 + index;
1739 std::vector<ItemStack> items;
1740 luaL_checktype(L, index, LUA_TTABLE);
1742 while(lua_next(L, index) != 0){
1743 // key at index -2 and value at index -1
1744 items.push_back(read_item(L, -1));
1745 // removes value, keeps key for next iteration
1751 // creates a table of ItemStacks
1752 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1754 // Get the table insert function
1755 lua_getglobal(L, "table");
1756 lua_getfield(L, -1, "insert");
1757 int table_insert = lua_gettop(L);
1758 // Create and fill table
1760 int table = lua_gettop(L);
1761 for(u32 i=0; i<items.size(); i++){
1762 ItemStack item = items[i];
1763 lua_pushvalue(L, table_insert);
1764 lua_pushvalue(L, table);
1765 LuaItemStack::create(L, item);
1766 if(lua_pcall(L, 2, 0, 0))
1767 script_error(L, "error: %s", lua_tostring(L, -1));
1769 lua_remove(L, -2); // Remove table
1770 lua_remove(L, -2); // Remove insert
1780 InventoryLocation m_loc;
1782 static const char className[];
1783 static const luaL_reg methods[];
1785 static InvRef *checkobject(lua_State *L, int narg)
1787 luaL_checktype(L, narg, LUA_TUSERDATA);
1788 void *ud = luaL_checkudata(L, narg, className);
1789 if(!ud) luaL_typerror(L, narg, className);
1790 return *(InvRef**)ud; // unbox pointer
1793 static Inventory* getinv(lua_State *L, InvRef *ref)
1795 return get_server(L)->getInventory(ref->m_loc);
1798 static InventoryList* getlist(lua_State *L, InvRef *ref,
1799 const char *listname)
1801 Inventory *inv = getinv(L, ref);
1804 return inv->getList(listname);
1807 static void reportInventoryChange(lua_State *L, InvRef *ref)
1809 // Inform other things that the inventory has changed
1810 get_server(L)->setInventoryModified(ref->m_loc);
1813 // Exported functions
1815 // garbage collector
1816 static int gc_object(lua_State *L) {
1817 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1822 // is_empty(self, listname) -> true/false
1823 static int l_is_empty(lua_State *L)
1825 InvRef *ref = checkobject(L, 1);
1826 const char *listname = luaL_checkstring(L, 2);
1827 InventoryList *list = getlist(L, ref, listname);
1828 if(list && list->getUsedSlots() > 0){
1829 lua_pushboolean(L, false);
1831 lua_pushboolean(L, true);
1836 // get_size(self, listname)
1837 static int l_get_size(lua_State *L)
1839 InvRef *ref = checkobject(L, 1);
1840 const char *listname = luaL_checkstring(L, 2);
1841 InventoryList *list = getlist(L, ref, listname);
1843 lua_pushinteger(L, list->getSize());
1845 lua_pushinteger(L, 0);
1850 // set_size(self, listname, size)
1851 static int l_set_size(lua_State *L)
1853 InvRef *ref = checkobject(L, 1);
1854 const char *listname = luaL_checkstring(L, 2);
1855 int newsize = luaL_checknumber(L, 3);
1856 Inventory *inv = getinv(L, ref);
1858 inv->deleteList(listname);
1859 reportInventoryChange(L, ref);
1862 InventoryList *list = inv->getList(listname);
1864 list->setSize(newsize);
1866 list = inv->addList(listname, newsize);
1868 reportInventoryChange(L, ref);
1872 // get_stack(self, listname, i) -> itemstack
1873 static int l_get_stack(lua_State *L)
1875 InvRef *ref = checkobject(L, 1);
1876 const char *listname = luaL_checkstring(L, 2);
1877 int i = luaL_checknumber(L, 3) - 1;
1878 InventoryList *list = getlist(L, ref, listname);
1880 if(list != NULL && i >= 0 && i < (int) list->getSize())
1881 item = list->getItem(i);
1882 LuaItemStack::create(L, item);
1886 // set_stack(self, listname, i, stack) -> true/false
1887 static int l_set_stack(lua_State *L)
1889 InvRef *ref = checkobject(L, 1);
1890 const char *listname = luaL_checkstring(L, 2);
1891 int i = luaL_checknumber(L, 3) - 1;
1892 ItemStack newitem = read_item(L, 4);
1893 InventoryList *list = getlist(L, ref, listname);
1894 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1895 list->changeItem(i, newitem);
1896 reportInventoryChange(L, ref);
1897 lua_pushboolean(L, true);
1899 lua_pushboolean(L, false);
1904 // get_list(self, listname) -> list or nil
1905 static int l_get_list(lua_State *L)
1907 InvRef *ref = checkobject(L, 1);
1908 const char *listname = luaL_checkstring(L, 2);
1909 Inventory *inv = getinv(L, ref);
1910 inventory_get_list_to_lua(inv, listname, L);
1914 // set_list(self, listname, list)
1915 static int l_set_list(lua_State *L)
1917 InvRef *ref = checkobject(L, 1);
1918 const char *listname = luaL_checkstring(L, 2);
1919 Inventory *inv = getinv(L, ref);
1920 InventoryList *list = inv->getList(listname);
1922 inventory_set_list_from_lua(inv, listname, L, 3,
1925 inventory_set_list_from_lua(inv, listname, L, 3);
1926 reportInventoryChange(L, ref);
1930 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1931 // Returns the leftover stack
1932 static int l_add_item(lua_State *L)
1934 InvRef *ref = checkobject(L, 1);
1935 const char *listname = luaL_checkstring(L, 2);
1936 ItemStack item = read_item(L, 3);
1937 InventoryList *list = getlist(L, ref, listname);
1939 ItemStack leftover = list->addItem(item);
1940 if(leftover.count != item.count)
1941 reportInventoryChange(L, ref);
1942 LuaItemStack::create(L, leftover);
1944 LuaItemStack::create(L, item);
1949 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1950 // Returns true if the item completely fits into the list
1951 static int l_room_for_item(lua_State *L)
1953 InvRef *ref = checkobject(L, 1);
1954 const char *listname = luaL_checkstring(L, 2);
1955 ItemStack item = read_item(L, 3);
1956 InventoryList *list = getlist(L, ref, listname);
1958 lua_pushboolean(L, list->roomForItem(item));
1960 lua_pushboolean(L, false);
1965 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1966 // Returns true if the list contains the given count of the given item name
1967 static int l_contains_item(lua_State *L)
1969 InvRef *ref = checkobject(L, 1);
1970 const char *listname = luaL_checkstring(L, 2);
1971 ItemStack item = read_item(L, 3);
1972 InventoryList *list = getlist(L, ref, listname);
1974 lua_pushboolean(L, list->containsItem(item));
1976 lua_pushboolean(L, false);
1981 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1982 // Returns the items that were actually removed
1983 static int l_remove_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 ItemStack removed = list->removeItem(item);
1991 if(!removed.empty())
1992 reportInventoryChange(L, ref);
1993 LuaItemStack::create(L, removed);
1995 LuaItemStack::create(L, ItemStack());
2001 InvRef(const InventoryLocation &loc):
2010 // Creates an InvRef and leaves it on top of stack
2011 // Not callable from Lua; all references are created on the C side.
2012 static void create(lua_State *L, const InventoryLocation &loc)
2014 InvRef *o = new InvRef(loc);
2015 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2016 luaL_getmetatable(L, className);
2017 lua_setmetatable(L, -2);
2019 static void createPlayer(lua_State *L, Player *player)
2021 InventoryLocation loc;
2022 loc.setPlayer(player->getName());
2025 static void createNodeMeta(lua_State *L, v3s16 p)
2027 InventoryLocation loc;
2032 static void Register(lua_State *L)
2035 int methodtable = lua_gettop(L);
2036 luaL_newmetatable(L, className);
2037 int metatable = lua_gettop(L);
2039 lua_pushliteral(L, "__metatable");
2040 lua_pushvalue(L, methodtable);
2041 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2043 lua_pushliteral(L, "__index");
2044 lua_pushvalue(L, methodtable);
2045 lua_settable(L, metatable);
2047 lua_pushliteral(L, "__gc");
2048 lua_pushcfunction(L, gc_object);
2049 lua_settable(L, metatable);
2051 lua_pop(L, 1); // drop metatable
2053 luaL_openlib(L, 0, methods, 0); // fill methodtable
2054 lua_pop(L, 1); // drop methodtable
2056 // Cannot be created from Lua
2057 //lua_register(L, className, create_object);
2060 const char InvRef::className[] = "InvRef";
2061 const luaL_reg InvRef::methods[] = {
2062 method(InvRef, is_empty),
2063 method(InvRef, get_size),
2064 method(InvRef, set_size),
2065 method(InvRef, get_stack),
2066 method(InvRef, set_stack),
2067 method(InvRef, get_list),
2068 method(InvRef, set_list),
2069 method(InvRef, add_item),
2070 method(InvRef, room_for_item),
2071 method(InvRef, contains_item),
2072 method(InvRef, remove_item),
2084 ServerEnvironment *m_env;
2086 static const char className[];
2087 static const luaL_reg methods[];
2089 static NodeMetaRef *checkobject(lua_State *L, int narg)
2091 luaL_checktype(L, narg, LUA_TUSERDATA);
2092 void *ud = luaL_checkudata(L, narg, className);
2093 if(!ud) luaL_typerror(L, narg, className);
2094 return *(NodeMetaRef**)ud; // unbox pointer
2097 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2099 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2100 if(meta == NULL && auto_create)
2102 meta = new NodeMetadata(ref->m_env->getGameDef());
2103 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2108 static void reportMetadataChange(NodeMetaRef *ref)
2110 // NOTE: This same code is in rollback_interface.cpp
2111 // Inform other things that the metadata has changed
2112 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2114 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2116 ref->m_env->getMap().dispatchEvent(&event);
2117 // Set the block to be saved
2118 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2120 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2121 "NodeMetaRef::reportMetadataChange");
2124 // Exported functions
2126 // garbage collector
2127 static int gc_object(lua_State *L) {
2128 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2133 // get_string(self, name)
2134 static int l_get_string(lua_State *L)
2136 NodeMetaRef *ref = checkobject(L, 1);
2137 std::string name = luaL_checkstring(L, 2);
2139 NodeMetadata *meta = getmeta(ref, false);
2141 lua_pushlstring(L, "", 0);
2144 std::string str = meta->getString(name);
2145 lua_pushlstring(L, str.c_str(), str.size());
2149 // set_string(self, name, var)
2150 static int l_set_string(lua_State *L)
2152 NodeMetaRef *ref = checkobject(L, 1);
2153 std::string name = luaL_checkstring(L, 2);
2155 const char *s = lua_tolstring(L, 3, &len);
2156 std::string str(s, len);
2158 NodeMetadata *meta = getmeta(ref, !str.empty());
2159 if(meta == NULL || str == meta->getString(name))
2161 meta->setString(name, str);
2162 reportMetadataChange(ref);
2166 // get_int(self, name)
2167 static int l_get_int(lua_State *L)
2169 NodeMetaRef *ref = checkobject(L, 1);
2170 std::string name = lua_tostring(L, 2);
2172 NodeMetadata *meta = getmeta(ref, false);
2174 lua_pushnumber(L, 0);
2177 std::string str = meta->getString(name);
2178 lua_pushnumber(L, stoi(str));
2182 // set_int(self, name, var)
2183 static int l_set_int(lua_State *L)
2185 NodeMetaRef *ref = checkobject(L, 1);
2186 std::string name = lua_tostring(L, 2);
2187 int a = lua_tointeger(L, 3);
2188 std::string str = itos(a);
2190 NodeMetadata *meta = getmeta(ref, true);
2191 if(meta == NULL || str == meta->getString(name))
2193 meta->setString(name, str);
2194 reportMetadataChange(ref);
2198 // get_float(self, name)
2199 static int l_get_float(lua_State *L)
2201 NodeMetaRef *ref = checkobject(L, 1);
2202 std::string name = lua_tostring(L, 2);
2204 NodeMetadata *meta = getmeta(ref, false);
2206 lua_pushnumber(L, 0);
2209 std::string str = meta->getString(name);
2210 lua_pushnumber(L, stof(str));
2214 // set_float(self, name, var)
2215 static int l_set_float(lua_State *L)
2217 NodeMetaRef *ref = checkobject(L, 1);
2218 std::string name = lua_tostring(L, 2);
2219 float a = lua_tonumber(L, 3);
2220 std::string str = ftos(a);
2222 NodeMetadata *meta = getmeta(ref, true);
2223 if(meta == NULL || str == meta->getString(name))
2225 meta->setString(name, str);
2226 reportMetadataChange(ref);
2230 // get_inventory(self)
2231 static int l_get_inventory(lua_State *L)
2233 NodeMetaRef *ref = checkobject(L, 1);
2234 getmeta(ref, true); // try to ensure the metadata exists
2235 InvRef::createNodeMeta(L, ref->m_p);
2240 static int l_to_table(lua_State *L)
2242 NodeMetaRef *ref = checkobject(L, 1);
2244 NodeMetadata *meta = getmeta(ref, true);
2253 std::map<std::string, std::string> fields = meta->getStrings();
2254 for(std::map<std::string, std::string>::const_iterator
2255 i = fields.begin(); i != fields.end(); i++){
2256 const std::string &name = i->first;
2257 const std::string &value = i->second;
2258 lua_pushlstring(L, name.c_str(), name.size());
2259 lua_pushlstring(L, value.c_str(), value.size());
2260 lua_settable(L, -3);
2263 lua_setfield(L, -2, "fields");
2266 Inventory *inv = meta->getInventory();
2268 std::vector<const InventoryList*> lists = inv->getLists();
2269 for(std::vector<const InventoryList*>::const_iterator
2270 i = lists.begin(); i != lists.end(); i++){
2271 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2272 lua_setfield(L, -2, (*i)->getName().c_str());
2275 lua_setfield(L, -2, "inventory");
2279 // from_table(self, table)
2280 static int l_from_table(lua_State *L)
2282 NodeMetaRef *ref = checkobject(L, 1);
2285 if(lua_isnil(L, base)){
2287 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2288 lua_pushboolean(L, true);
2292 // Has metadata; clear old one first
2293 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2294 // Create new metadata
2295 NodeMetadata *meta = getmeta(ref, true);
2297 lua_getfield(L, base, "fields");
2298 int fieldstable = lua_gettop(L);
2300 while(lua_next(L, fieldstable) != 0){
2301 // key at index -2 and value at index -1
2302 std::string name = lua_tostring(L, -2);
2304 const char *cs = lua_tolstring(L, -1, &cl);
2305 std::string value(cs, cl);
2306 meta->setString(name, value);
2307 lua_pop(L, 1); // removes value, keeps key for next iteration
2310 Inventory *inv = meta->getInventory();
2311 lua_getfield(L, base, "inventory");
2312 int inventorytable = lua_gettop(L);
2314 while(lua_next(L, inventorytable) != 0){
2315 // key at index -2 and value at index -1
2316 std::string name = lua_tostring(L, -2);
2317 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2318 lua_pop(L, 1); // removes value, keeps key for next iteration
2320 reportMetadataChange(ref);
2321 lua_pushboolean(L, true);
2326 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2336 // Creates an NodeMetaRef and leaves it on top of stack
2337 // Not callable from Lua; all references are created on the C side.
2338 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2340 NodeMetaRef *o = new NodeMetaRef(p, env);
2341 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2342 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2343 luaL_getmetatable(L, className);
2344 lua_setmetatable(L, -2);
2347 static void Register(lua_State *L)
2350 int methodtable = lua_gettop(L);
2351 luaL_newmetatable(L, className);
2352 int metatable = lua_gettop(L);
2354 lua_pushliteral(L, "__metatable");
2355 lua_pushvalue(L, methodtable);
2356 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2358 lua_pushliteral(L, "__index");
2359 lua_pushvalue(L, methodtable);
2360 lua_settable(L, metatable);
2362 lua_pushliteral(L, "__gc");
2363 lua_pushcfunction(L, gc_object);
2364 lua_settable(L, metatable);
2366 lua_pop(L, 1); // drop metatable
2368 luaL_openlib(L, 0, methods, 0); // fill methodtable
2369 lua_pop(L, 1); // drop methodtable
2371 // Cannot be created from Lua
2372 //lua_register(L, className, create_object);
2375 const char NodeMetaRef::className[] = "NodeMetaRef";
2376 const luaL_reg NodeMetaRef::methods[] = {
2377 method(NodeMetaRef, get_string),
2378 method(NodeMetaRef, set_string),
2379 method(NodeMetaRef, get_int),
2380 method(NodeMetaRef, set_int),
2381 method(NodeMetaRef, get_float),
2382 method(NodeMetaRef, set_float),
2383 method(NodeMetaRef, get_inventory),
2384 method(NodeMetaRef, to_table),
2385 method(NodeMetaRef, from_table),
2396 ServerActiveObject *m_object;
2398 static const char className[];
2399 static const luaL_reg methods[];
2401 static ObjectRef *checkobject(lua_State *L, int narg)
2403 luaL_checktype(L, narg, LUA_TUSERDATA);
2404 void *ud = luaL_checkudata(L, narg, className);
2405 if(!ud) luaL_typerror(L, narg, className);
2406 return *(ObjectRef**)ud; // unbox pointer
2409 static ServerActiveObject* getobject(ObjectRef *ref)
2411 ServerActiveObject *co = ref->m_object;
2415 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2417 ServerActiveObject *obj = getobject(ref);
2420 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2422 return (LuaEntitySAO*)obj;
2425 static PlayerSAO* getplayersao(ObjectRef *ref)
2427 ServerActiveObject *obj = getobject(ref);
2430 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2432 return (PlayerSAO*)obj;
2435 static Player* getplayer(ObjectRef *ref)
2437 PlayerSAO *playersao = getplayersao(ref);
2438 if(playersao == NULL)
2440 return playersao->getPlayer();
2443 // Exported functions
2445 // garbage collector
2446 static int gc_object(lua_State *L) {
2447 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2448 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2454 static int l_remove(lua_State *L)
2456 ObjectRef *ref = checkobject(L, 1);
2457 ServerActiveObject *co = getobject(ref);
2458 if(co == NULL) return 0;
2459 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2460 co->m_removed = true;
2465 // returns: {x=num, y=num, z=num}
2466 static int l_getpos(lua_State *L)
2468 ObjectRef *ref = checkobject(L, 1);
2469 ServerActiveObject *co = getobject(ref);
2470 if(co == NULL) return 0;
2471 v3f pos = co->getBasePosition() / BS;
2473 lua_pushnumber(L, pos.X);
2474 lua_setfield(L, -2, "x");
2475 lua_pushnumber(L, pos.Y);
2476 lua_setfield(L, -2, "y");
2477 lua_pushnumber(L, pos.Z);
2478 lua_setfield(L, -2, "z");
2482 // setpos(self, pos)
2483 static int l_setpos(lua_State *L)
2485 ObjectRef *ref = checkobject(L, 1);
2486 //LuaEntitySAO *co = getluaobject(ref);
2487 ServerActiveObject *co = getobject(ref);
2488 if(co == NULL) return 0;
2490 v3f pos = checkFloatPos(L, 2);
2496 // moveto(self, pos, continuous=false)
2497 static int l_moveto(lua_State *L)
2499 ObjectRef *ref = checkobject(L, 1);
2500 //LuaEntitySAO *co = getluaobject(ref);
2501 ServerActiveObject *co = getobject(ref);
2502 if(co == NULL) return 0;
2504 v3f pos = checkFloatPos(L, 2);
2506 bool continuous = lua_toboolean(L, 3);
2508 co->moveTo(pos, continuous);
2512 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2513 static int l_punch(lua_State *L)
2515 ObjectRef *ref = checkobject(L, 1);
2516 ObjectRef *puncher_ref = checkobject(L, 2);
2517 ServerActiveObject *co = getobject(ref);
2518 ServerActiveObject *puncher = getobject(puncher_ref);
2519 if(co == NULL) return 0;
2520 if(puncher == NULL) return 0;
2521 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2522 v3f dir = read_v3f(L, 4);
2523 float time_from_last_punch = 1000000;
2524 if(lua_isnumber(L, 5))
2525 time_from_last_punch = lua_tonumber(L, 5);
2527 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2531 // right_click(self, clicker); clicker = an another ObjectRef
2532 static int l_right_click(lua_State *L)
2534 ObjectRef *ref = checkobject(L, 1);
2535 ObjectRef *ref2 = checkobject(L, 2);
2536 ServerActiveObject *co = getobject(ref);
2537 ServerActiveObject *co2 = getobject(ref2);
2538 if(co == NULL) return 0;
2539 if(co2 == NULL) return 0;
2541 co->rightClick(co2);
2546 // hp = number of hitpoints (2 * number of hearts)
2548 static int l_set_hp(lua_State *L)
2550 ObjectRef *ref = checkobject(L, 1);
2551 luaL_checknumber(L, 2);
2552 ServerActiveObject *co = getobject(ref);
2553 if(co == NULL) return 0;
2554 int hp = lua_tonumber(L, 2);
2555 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2556 <<" hp="<<hp<<std::endl;*/
2564 // returns: number of hitpoints (2 * number of hearts)
2565 // 0 if not applicable to this type of object
2566 static int l_get_hp(lua_State *L)
2568 ObjectRef *ref = checkobject(L, 1);
2569 ServerActiveObject *co = getobject(ref);
2572 lua_pushnumber(L, 1);
2575 int hp = co->getHP();
2576 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2577 <<" hp="<<hp<<std::endl;*/
2579 lua_pushnumber(L, hp);
2583 // get_inventory(self)
2584 static int l_get_inventory(lua_State *L)
2586 ObjectRef *ref = checkobject(L, 1);
2587 ServerActiveObject *co = getobject(ref);
2588 if(co == NULL) return 0;
2590 InventoryLocation loc = co->getInventoryLocation();
2591 if(get_server(L)->getInventory(loc) != NULL)
2592 InvRef::create(L, loc);
2594 lua_pushnil(L); // An object may have no inventory (nil)
2598 // get_wield_list(self)
2599 static int l_get_wield_list(lua_State *L)
2601 ObjectRef *ref = checkobject(L, 1);
2602 ServerActiveObject *co = getobject(ref);
2603 if(co == NULL) return 0;
2605 lua_pushstring(L, co->getWieldList().c_str());
2609 // get_wield_index(self)
2610 static int l_get_wield_index(lua_State *L)
2612 ObjectRef *ref = checkobject(L, 1);
2613 ServerActiveObject *co = getobject(ref);
2614 if(co == NULL) return 0;
2616 lua_pushinteger(L, co->getWieldIndex() + 1);
2620 // get_wielded_item(self)
2621 static int l_get_wielded_item(lua_State *L)
2623 ObjectRef *ref = checkobject(L, 1);
2624 ServerActiveObject *co = getobject(ref);
2627 LuaItemStack::create(L, ItemStack());
2631 LuaItemStack::create(L, co->getWieldedItem());
2635 // set_wielded_item(self, itemstack or itemstring or table or nil)
2636 static int l_set_wielded_item(lua_State *L)
2638 ObjectRef *ref = checkobject(L, 1);
2639 ServerActiveObject *co = getobject(ref);
2640 if(co == NULL) return 0;
2642 ItemStack item = read_item(L, 2);
2643 bool success = co->setWieldedItem(item);
2644 lua_pushboolean(L, success);
2648 // set_armor_groups(self, groups)
2649 static int l_set_armor_groups(lua_State *L)
2651 ObjectRef *ref = checkobject(L, 1);
2652 ServerActiveObject *co = getobject(ref);
2653 if(co == NULL) return 0;
2655 ItemGroupList groups;
2656 read_groups(L, 2, groups);
2657 co->setArmorGroups(groups);
2661 // set_properties(self, properties)
2662 static int l_set_properties(lua_State *L)
2664 ObjectRef *ref = checkobject(L, 1);
2665 ServerActiveObject *co = getobject(ref);
2666 if(co == NULL) return 0;
2667 ObjectProperties *prop = co->accessObjectProperties();
2670 read_object_properties(L, 2, prop);
2671 co->notifyObjectPropertiesModified();
2675 /* LuaEntitySAO-only */
2677 // setvelocity(self, {x=num, y=num, z=num})
2678 static int l_setvelocity(lua_State *L)
2680 ObjectRef *ref = checkobject(L, 1);
2681 LuaEntitySAO *co = getluaobject(ref);
2682 if(co == NULL) return 0;
2683 v3f pos = checkFloatPos(L, 2);
2685 co->setVelocity(pos);
2689 // getvelocity(self)
2690 static int l_getvelocity(lua_State *L)
2692 ObjectRef *ref = checkobject(L, 1);
2693 LuaEntitySAO *co = getluaobject(ref);
2694 if(co == NULL) return 0;
2696 v3f v = co->getVelocity();
2701 // setacceleration(self, {x=num, y=num, z=num})
2702 static int l_setacceleration(lua_State *L)
2704 ObjectRef *ref = checkobject(L, 1);
2705 LuaEntitySAO *co = getluaobject(ref);
2706 if(co == NULL) return 0;
2708 v3f pos = checkFloatPos(L, 2);
2710 co->setAcceleration(pos);
2714 // getacceleration(self)
2715 static int l_getacceleration(lua_State *L)
2717 ObjectRef *ref = checkobject(L, 1);
2718 LuaEntitySAO *co = getluaobject(ref);
2719 if(co == NULL) return 0;
2721 v3f v = co->getAcceleration();
2726 // setyaw(self, radians)
2727 static int l_setyaw(lua_State *L)
2729 ObjectRef *ref = checkobject(L, 1);
2730 LuaEntitySAO *co = getluaobject(ref);
2731 if(co == NULL) return 0;
2732 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2739 static int l_getyaw(lua_State *L)
2741 ObjectRef *ref = checkobject(L, 1);
2742 LuaEntitySAO *co = getluaobject(ref);
2743 if(co == NULL) return 0;
2745 float yaw = co->getYaw() * core::DEGTORAD;
2746 lua_pushnumber(L, yaw);
2750 // settexturemod(self, mod)
2751 static int l_settexturemod(lua_State *L)
2753 ObjectRef *ref = checkobject(L, 1);
2754 LuaEntitySAO *co = getluaobject(ref);
2755 if(co == NULL) return 0;
2757 std::string mod = luaL_checkstring(L, 2);
2758 co->setTextureMod(mod);
2762 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2763 // select_horiz_by_yawpitch=false)
2764 static int l_setsprite(lua_State *L)
2766 ObjectRef *ref = checkobject(L, 1);
2767 LuaEntitySAO *co = getluaobject(ref);
2768 if(co == NULL) return 0;
2771 if(!lua_isnil(L, 2))
2772 p = read_v2s16(L, 2);
2774 if(!lua_isnil(L, 3))
2775 num_frames = lua_tonumber(L, 3);
2776 float framelength = 0.2;
2777 if(!lua_isnil(L, 4))
2778 framelength = lua_tonumber(L, 4);
2779 bool select_horiz_by_yawpitch = false;
2780 if(!lua_isnil(L, 5))
2781 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2782 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2787 // get_entity_name(self)
2788 static int l_get_entity_name(lua_State *L)
2790 ObjectRef *ref = checkobject(L, 1);
2791 LuaEntitySAO *co = getluaobject(ref);
2792 if(co == NULL) return 0;
2794 std::string name = co->getName();
2795 lua_pushstring(L, name.c_str());
2799 // get_luaentity(self)
2800 static int l_get_luaentity(lua_State *L)
2802 ObjectRef *ref = checkobject(L, 1);
2803 LuaEntitySAO *co = getluaobject(ref);
2804 if(co == NULL) return 0;
2806 luaentity_get(L, co->getId());
2813 static int l_is_player(lua_State *L)
2815 ObjectRef *ref = checkobject(L, 1);
2816 Player *player = getplayer(ref);
2817 lua_pushboolean(L, (player != NULL));
2821 // get_player_name(self)
2822 static int l_get_player_name(lua_State *L)
2824 ObjectRef *ref = checkobject(L, 1);
2825 Player *player = getplayer(ref);
2827 lua_pushlstring(L, "", 0);
2831 lua_pushstring(L, player->getName());
2835 // get_look_dir(self)
2836 static int l_get_look_dir(lua_State *L)
2838 ObjectRef *ref = checkobject(L, 1);
2839 Player *player = getplayer(ref);
2840 if(player == NULL) return 0;
2842 float pitch = player->getRadPitch();
2843 float yaw = player->getRadYaw();
2844 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2849 // get_look_pitch(self)
2850 static int l_get_look_pitch(lua_State *L)
2852 ObjectRef *ref = checkobject(L, 1);
2853 Player *player = getplayer(ref);
2854 if(player == NULL) return 0;
2856 lua_pushnumber(L, player->getRadPitch());
2860 // get_look_yaw(self)
2861 static int l_get_look_yaw(lua_State *L)
2863 ObjectRef *ref = checkobject(L, 1);
2864 Player *player = getplayer(ref);
2865 if(player == NULL) return 0;
2867 lua_pushnumber(L, player->getRadYaw());
2871 // set_inventory_formspec(self, formspec)
2872 static int l_set_inventory_formspec(lua_State *L)
2874 ObjectRef *ref = checkobject(L, 1);
2875 Player *player = getplayer(ref);
2876 if(player == NULL) return 0;
2877 std::string formspec = luaL_checkstring(L, 2);
2879 player->inventory_formspec = formspec;
2880 get_server(L)->reportInventoryFormspecModified(player->getName());
2881 lua_pushboolean(L, true);
2885 // get_inventory_formspec(self) -> formspec
2886 static int l_get_inventory_formspec(lua_State *L)
2888 ObjectRef *ref = checkobject(L, 1);
2889 Player *player = getplayer(ref);
2890 if(player == NULL) return 0;
2892 std::string formspec = player->inventory_formspec;
2893 lua_pushlstring(L, formspec.c_str(), formspec.size());
2898 ObjectRef(ServerActiveObject *object):
2901 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2907 infostream<<"ObjectRef destructing for id="
2908 <<m_object->getId()<<std::endl;
2910 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2913 // Creates an ObjectRef and leaves it on top of stack
2914 // Not callable from Lua; all references are created on the C side.
2915 static void create(lua_State *L, ServerActiveObject *object)
2917 ObjectRef *o = new ObjectRef(object);
2918 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2919 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2920 luaL_getmetatable(L, className);
2921 lua_setmetatable(L, -2);
2924 static void set_null(lua_State *L)
2926 ObjectRef *o = checkobject(L, -1);
2930 static void Register(lua_State *L)
2933 int methodtable = lua_gettop(L);
2934 luaL_newmetatable(L, className);
2935 int metatable = lua_gettop(L);
2937 lua_pushliteral(L, "__metatable");
2938 lua_pushvalue(L, methodtable);
2939 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2941 lua_pushliteral(L, "__index");
2942 lua_pushvalue(L, methodtable);
2943 lua_settable(L, metatable);
2945 lua_pushliteral(L, "__gc");
2946 lua_pushcfunction(L, gc_object);
2947 lua_settable(L, metatable);
2949 lua_pop(L, 1); // drop metatable
2951 luaL_openlib(L, 0, methods, 0); // fill methodtable
2952 lua_pop(L, 1); // drop methodtable
2954 // Cannot be created from Lua
2955 //lua_register(L, className, create_object);
2958 const char ObjectRef::className[] = "ObjectRef";
2959 const luaL_reg ObjectRef::methods[] = {
2960 // ServerActiveObject
2961 method(ObjectRef, remove),
2962 method(ObjectRef, getpos),
2963 method(ObjectRef, setpos),
2964 method(ObjectRef, moveto),
2965 method(ObjectRef, punch),
2966 method(ObjectRef, right_click),
2967 method(ObjectRef, set_hp),
2968 method(ObjectRef, get_hp),
2969 method(ObjectRef, get_inventory),
2970 method(ObjectRef, get_wield_list),
2971 method(ObjectRef, get_wield_index),
2972 method(ObjectRef, get_wielded_item),
2973 method(ObjectRef, set_wielded_item),
2974 method(ObjectRef, set_armor_groups),
2975 method(ObjectRef, set_properties),
2976 // LuaEntitySAO-only
2977 method(ObjectRef, setvelocity),
2978 method(ObjectRef, getvelocity),
2979 method(ObjectRef, setacceleration),
2980 method(ObjectRef, getacceleration),
2981 method(ObjectRef, setyaw),
2982 method(ObjectRef, getyaw),
2983 method(ObjectRef, settexturemod),
2984 method(ObjectRef, setsprite),
2985 method(ObjectRef, get_entity_name),
2986 method(ObjectRef, get_luaentity),
2988 method(ObjectRef, is_player),
2989 method(ObjectRef, get_player_name),
2990 method(ObjectRef, get_look_dir),
2991 method(ObjectRef, get_look_pitch),
2992 method(ObjectRef, get_look_yaw),
2993 method(ObjectRef, set_inventory_formspec),
2994 method(ObjectRef, get_inventory_formspec),
2998 // Creates a new anonymous reference if cobj=NULL or id=0
2999 static void objectref_get_or_create(lua_State *L,
3000 ServerActiveObject *cobj)
3002 if(cobj == NULL || cobj->getId() == 0){
3003 ObjectRef::create(L, cobj);
3005 objectref_get(L, cobj->getId());
3014 class LuaPerlinNoise
3021 static const char className[];
3022 static const luaL_reg methods[];
3024 // Exported functions
3026 // garbage collector
3027 static int gc_object(lua_State *L)
3029 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3034 static int l_get2d(lua_State *L)
3036 LuaPerlinNoise *o = checkobject(L, 1);
3037 v2f pos2d = read_v2f(L,2);
3038 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3039 lua_pushnumber(L, val);
3042 static int l_get3d(lua_State *L)
3044 LuaPerlinNoise *o = checkobject(L, 1);
3045 v3f pos3d = read_v3f(L,2);
3046 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3047 lua_pushnumber(L, val);
3052 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3056 persistence(a_persistence),
3065 // LuaPerlinNoise(seed, octaves, persistence, scale)
3066 // Creates an LuaPerlinNoise and leaves it on top of stack
3067 static int create_object(lua_State *L)
3069 int seed = luaL_checkint(L, 1);
3070 int octaves = luaL_checkint(L, 2);
3071 double persistence = luaL_checknumber(L, 3);
3072 double scale = luaL_checknumber(L, 4);
3073 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3074 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3075 luaL_getmetatable(L, className);
3076 lua_setmetatable(L, -2);
3080 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3082 luaL_checktype(L, narg, LUA_TUSERDATA);
3083 void *ud = luaL_checkudata(L, narg, className);
3084 if(!ud) luaL_typerror(L, narg, className);
3085 return *(LuaPerlinNoise**)ud; // unbox pointer
3088 static void Register(lua_State *L)
3091 int methodtable = lua_gettop(L);
3092 luaL_newmetatable(L, className);
3093 int metatable = lua_gettop(L);
3095 lua_pushliteral(L, "__metatable");
3096 lua_pushvalue(L, methodtable);
3097 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3099 lua_pushliteral(L, "__index");
3100 lua_pushvalue(L, methodtable);
3101 lua_settable(L, metatable);
3103 lua_pushliteral(L, "__gc");
3104 lua_pushcfunction(L, gc_object);
3105 lua_settable(L, metatable);
3107 lua_pop(L, 1); // drop metatable
3109 luaL_openlib(L, 0, methods, 0); // fill methodtable
3110 lua_pop(L, 1); // drop methodtable
3112 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3113 lua_register(L, className, create_object);
3116 const char LuaPerlinNoise::className[] = "PerlinNoise";
3117 const luaL_reg LuaPerlinNoise::methods[] = {
3118 method(LuaPerlinNoise, get2d),
3119 method(LuaPerlinNoise, get3d),
3131 ServerEnvironment *m_env;
3133 static const char className[];
3134 static const luaL_reg methods[];
3136 static int gc_object(lua_State *L) {
3137 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3142 static NodeTimerRef *checkobject(lua_State *L, int narg)
3144 luaL_checktype(L, narg, LUA_TUSERDATA);
3145 void *ud = luaL_checkudata(L, narg, className);
3146 if(!ud) luaL_typerror(L, narg, className);
3147 return *(NodeTimerRef**)ud; // unbox pointer
3150 static int l_set(lua_State *L)
3152 NodeTimerRef *o = checkobject(L, 1);
3153 ServerEnvironment *env = o->m_env;
3154 if(env == NULL) return 0;
3155 f32 t = luaL_checknumber(L,2);
3156 f32 e = luaL_checknumber(L,3);
3157 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3161 static int l_start(lua_State *L)
3163 NodeTimerRef *o = checkobject(L, 1);
3164 ServerEnvironment *env = o->m_env;
3165 if(env == NULL) return 0;
3166 f32 t = luaL_checknumber(L,2);
3167 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3171 static int l_stop(lua_State *L)
3173 NodeTimerRef *o = checkobject(L, 1);
3174 ServerEnvironment *env = o->m_env;
3175 if(env == NULL) return 0;
3176 env->getMap().removeNodeTimer(o->m_p);
3180 static int l_is_started(lua_State *L)
3182 NodeTimerRef *o = checkobject(L, 1);
3183 ServerEnvironment *env = o->m_env;
3184 if(env == NULL) return 0;
3186 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3187 lua_pushboolean(L,(t.timeout != 0));
3191 static int l_get_timeout(lua_State *L)
3193 NodeTimerRef *o = checkobject(L, 1);
3194 ServerEnvironment *env = o->m_env;
3195 if(env == NULL) return 0;
3197 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3198 lua_pushnumber(L,t.timeout);
3202 static int l_get_elapsed(lua_State *L)
3204 NodeTimerRef *o = checkobject(L, 1);
3205 ServerEnvironment *env = o->m_env;
3206 if(env == NULL) return 0;
3208 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3209 lua_pushnumber(L,t.elapsed);
3214 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3224 // Creates an NodeTimerRef and leaves it on top of stack
3225 // Not callable from Lua; all references are created on the C side.
3226 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3228 NodeTimerRef *o = new NodeTimerRef(p, env);
3229 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3230 luaL_getmetatable(L, className);
3231 lua_setmetatable(L, -2);
3234 static void set_null(lua_State *L)
3236 NodeTimerRef *o = checkobject(L, -1);
3240 static void Register(lua_State *L)
3243 int methodtable = lua_gettop(L);
3244 luaL_newmetatable(L, className);
3245 int metatable = lua_gettop(L);
3247 lua_pushliteral(L, "__metatable");
3248 lua_pushvalue(L, methodtable);
3249 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3251 lua_pushliteral(L, "__index");
3252 lua_pushvalue(L, methodtable);
3253 lua_settable(L, metatable);
3255 lua_pushliteral(L, "__gc");
3256 lua_pushcfunction(L, gc_object);
3257 lua_settable(L, metatable);
3259 lua_pop(L, 1); // drop metatable
3261 luaL_openlib(L, 0, methods, 0); // fill methodtable
3262 lua_pop(L, 1); // drop methodtable
3264 // Cannot be created from Lua
3265 //lua_register(L, className, create_object);
3268 const char NodeTimerRef::className[] = "NodeTimerRef";
3269 const luaL_reg NodeTimerRef::methods[] = {
3270 method(NodeTimerRef, start),
3271 method(NodeTimerRef, set),
3272 method(NodeTimerRef, stop),
3273 method(NodeTimerRef, is_started),
3274 method(NodeTimerRef, get_timeout),
3275 method(NodeTimerRef, get_elapsed),
3286 ServerEnvironment *m_env;
3288 static const char className[];
3289 static const luaL_reg methods[];
3291 static int gc_object(lua_State *L) {
3292 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3297 static EnvRef *checkobject(lua_State *L, int narg)
3299 luaL_checktype(L, narg, LUA_TUSERDATA);
3300 void *ud = luaL_checkudata(L, narg, className);
3301 if(!ud) luaL_typerror(L, narg, className);
3302 return *(EnvRef**)ud; // unbox pointer
3305 // Exported functions
3307 // EnvRef:set_node(pos, node)
3308 // pos = {x=num, y=num, z=num}
3309 static int l_set_node(lua_State *L)
3311 EnvRef *o = checkobject(L, 1);
3312 ServerEnvironment *env = o->m_env;
3313 if(env == NULL) return 0;
3314 INodeDefManager *ndef = env->getGameDef()->ndef();
3316 v3s16 pos = read_v3s16(L, 2);
3317 MapNode n = readnode(L, 3, ndef);
3319 MapNode n_old = env->getMap().getNodeNoEx(pos);
3321 if(ndef->get(n_old).has_on_destruct)
3322 scriptapi_node_on_destruct(L, pos, n_old);
3324 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3326 // Call post-destructor
3327 if(ndef->get(n_old).has_after_destruct)
3328 scriptapi_node_after_destruct(L, pos, n_old);
3330 if(ndef->get(n).has_on_construct)
3331 scriptapi_node_on_construct(L, pos, n);
3333 lua_pushboolean(L, succeeded);
3337 static int l_add_node(lua_State *L)
3339 return l_set_node(L);
3342 // EnvRef:remove_node(pos)
3343 // pos = {x=num, y=num, z=num}
3344 static int l_remove_node(lua_State *L)
3346 EnvRef *o = checkobject(L, 1);
3347 ServerEnvironment *env = o->m_env;
3348 if(env == NULL) return 0;
3349 INodeDefManager *ndef = env->getGameDef()->ndef();
3351 v3s16 pos = read_v3s16(L, 2);
3353 MapNode n_old = env->getMap().getNodeNoEx(pos);
3355 if(ndef->get(n_old).has_on_destruct)
3356 scriptapi_node_on_destruct(L, pos, n_old);
3358 // This is slightly optimized compared to addNodeWithEvent(air)
3359 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3361 // Call post-destructor
3362 if(ndef->get(n_old).has_after_destruct)
3363 scriptapi_node_after_destruct(L, pos, n_old);
3365 lua_pushboolean(L, succeeded);
3366 // Air doesn't require constructor
3370 // EnvRef:get_node(pos)
3371 // pos = {x=num, y=num, z=num}
3372 static int l_get_node(lua_State *L)
3374 EnvRef *o = checkobject(L, 1);
3375 ServerEnvironment *env = o->m_env;
3376 if(env == NULL) return 0;
3378 v3s16 pos = read_v3s16(L, 2);
3380 MapNode n = env->getMap().getNodeNoEx(pos);
3382 pushnode(L, n, env->getGameDef()->ndef());
3386 // EnvRef:get_node_or_nil(pos)
3387 // pos = {x=num, y=num, z=num}
3388 static int l_get_node_or_nil(lua_State *L)
3390 EnvRef *o = checkobject(L, 1);
3391 ServerEnvironment *env = o->m_env;
3392 if(env == NULL) return 0;
3394 v3s16 pos = read_v3s16(L, 2);
3397 MapNode n = env->getMap().getNode(pos);
3399 pushnode(L, n, env->getGameDef()->ndef());
3401 } catch(InvalidPositionException &e)
3408 // EnvRef:get_node_light(pos, timeofday)
3409 // pos = {x=num, y=num, z=num}
3410 // timeofday: nil = current time, 0 = night, 0.5 = day
3411 static int l_get_node_light(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);
3418 u32 time_of_day = env->getTimeOfDay();
3419 if(lua_isnumber(L, 3))
3420 time_of_day = 24000.0 * lua_tonumber(L, 3);
3421 time_of_day %= 24000;
3422 u32 dnr = time_to_daynight_ratio(time_of_day);
3423 MapNode n = env->getMap().getNodeNoEx(pos);
3425 MapNode n = env->getMap().getNode(pos);
3426 INodeDefManager *ndef = env->getGameDef()->ndef();
3427 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3429 } catch(InvalidPositionException &e)
3436 // EnvRef:place_node(pos, node)
3437 // pos = {x=num, y=num, z=num}
3438 static int l_place_node(lua_State *L)
3440 EnvRef *o = checkobject(L, 1);
3441 ServerEnvironment *env = o->m_env;
3442 if(env == NULL) return 0;
3443 v3s16 pos = read_v3s16(L, 2);
3444 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3446 // Don't attempt to load non-loaded area as of now
3447 MapNode n_old = env->getMap().getNodeNoEx(pos);
3448 if(n_old.getContent() == CONTENT_IGNORE){
3449 lua_pushboolean(L, false);
3452 // Create item to place
3453 INodeDefManager *ndef = get_server(L)->ndef();
3454 IItemDefManager *idef = get_server(L)->idef();
3455 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3456 // Make pointed position
3457 PointedThing pointed;
3458 pointed.type = POINTEDTHING_NODE;
3459 pointed.node_abovesurface = pos;
3460 pointed.node_undersurface = pos + v3s16(0,-1,0);
3461 // Place it with a NULL placer (appears in Lua as a non-functional
3463 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3464 lua_pushboolean(L, success);
3468 // EnvRef:dig_node(pos)
3469 // pos = {x=num, y=num, z=num}
3470 static int l_dig_node(lua_State *L)
3472 EnvRef *o = checkobject(L, 1);
3473 ServerEnvironment *env = o->m_env;
3474 if(env == NULL) return 0;
3475 v3s16 pos = read_v3s16(L, 2);
3477 // Don't attempt to load non-loaded area as of now
3478 MapNode n = env->getMap().getNodeNoEx(pos);
3479 if(n.getContent() == CONTENT_IGNORE){
3480 lua_pushboolean(L, false);
3483 // Dig it out with a NULL digger (appears in Lua as a
3484 // non-functional ObjectRef)
3485 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3486 lua_pushboolean(L, success);
3490 // EnvRef:punch_node(pos)
3491 // pos = {x=num, y=num, z=num}
3492 static int l_punch_node(lua_State *L)
3494 EnvRef *o = checkobject(L, 1);
3495 ServerEnvironment *env = o->m_env;
3496 if(env == NULL) return 0;
3497 v3s16 pos = read_v3s16(L, 2);
3499 // Don't attempt to load non-loaded area as of now
3500 MapNode n = env->getMap().getNodeNoEx(pos);
3501 if(n.getContent() == CONTENT_IGNORE){
3502 lua_pushboolean(L, false);
3505 // Punch it with a NULL puncher (appears in Lua as a non-functional
3507 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3508 lua_pushboolean(L, success);
3512 // EnvRef:get_meta(pos)
3513 static int l_get_meta(lua_State *L)
3515 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3516 EnvRef *o = checkobject(L, 1);
3517 ServerEnvironment *env = o->m_env;
3518 if(env == NULL) return 0;
3520 v3s16 p = read_v3s16(L, 2);
3521 NodeMetaRef::create(L, p, env);
3525 // EnvRef:get_node_timer(pos)
3526 static int l_get_node_timer(lua_State *L)
3528 EnvRef *o = checkobject(L, 1);
3529 ServerEnvironment *env = o->m_env;
3530 if(env == NULL) return 0;
3532 v3s16 p = read_v3s16(L, 2);
3533 NodeTimerRef::create(L, p, env);
3537 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3538 // pos = {x=num, y=num, z=num}
3539 static int l_add_entity(lua_State *L)
3541 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3542 EnvRef *o = checkobject(L, 1);
3543 ServerEnvironment *env = o->m_env;
3544 if(env == NULL) return 0;
3546 v3f pos = checkFloatPos(L, 2);
3548 const char *name = luaL_checkstring(L, 3);
3550 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3551 int objectid = env->addActiveObject(obj);
3552 // If failed to add, return nothing (reads as nil)
3556 objectref_get_or_create(L, obj);
3560 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3561 // pos = {x=num, y=num, z=num}
3562 static int l_add_item(lua_State *L)
3564 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3565 EnvRef *o = checkobject(L, 1);
3566 ServerEnvironment *env = o->m_env;
3567 if(env == NULL) return 0;
3569 v3f pos = checkFloatPos(L, 2);
3571 ItemStack item = read_item(L, 3);
3572 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3574 // Use minetest.spawn_item to spawn a __builtin:item
3575 lua_getglobal(L, "minetest");
3576 lua_getfield(L, -1, "spawn_item");
3577 if(lua_isnil(L, -1))
3579 lua_pushvalue(L, 2);
3580 lua_pushstring(L, item.getItemString().c_str());
3581 if(lua_pcall(L, 2, 1, 0))
3582 script_error(L, "error: %s", lua_tostring(L, -1));
3584 /*lua_pushvalue(L, 1);
3585 lua_pushstring(L, "__builtin:item");
3586 lua_pushstring(L, item.getItemString().c_str());
3587 return l_add_entity(L);*/
3589 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
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_rat(pos)
3600 // pos = {x=num, y=num, z=num}
3601 static int l_add_rat(lua_State *L)
3603 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3604 <<" Doing nothing."<<std::endl;
3608 // EnvRef:add_firefly(pos)
3609 // pos = {x=num, y=num, z=num}
3610 static int l_add_firefly(lua_State *L)
3612 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3613 <<" Doing nothing."<<std::endl;
3617 // EnvRef:get_player_by_name(name)
3618 static int l_get_player_by_name(lua_State *L)
3620 EnvRef *o = checkobject(L, 1);
3621 ServerEnvironment *env = o->m_env;
3622 if(env == NULL) return 0;
3624 const char *name = luaL_checkstring(L, 2);
3625 Player *player = env->getPlayer(name);
3630 PlayerSAO *sao = player->getPlayerSAO();
3635 // Put player on stack
3636 objectref_get_or_create(L, sao);
3640 // EnvRef:get_objects_inside_radius(pos, radius)
3641 static int l_get_objects_inside_radius(lua_State *L)
3643 // Get the table insert function
3644 lua_getglobal(L, "table");
3645 lua_getfield(L, -1, "insert");
3646 int table_insert = lua_gettop(L);
3648 EnvRef *o = checkobject(L, 1);
3649 ServerEnvironment *env = o->m_env;
3650 if(env == NULL) return 0;
3652 v3f pos = checkFloatPos(L, 2);
3653 float radius = luaL_checknumber(L, 3) * BS;
3654 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3656 int table = lua_gettop(L);
3657 for(std::set<u16>::const_iterator
3658 i = ids.begin(); i != ids.end(); i++){
3659 ServerActiveObject *obj = env->getActiveObject(*i);
3660 // Insert object reference into table
3661 lua_pushvalue(L, table_insert);
3662 lua_pushvalue(L, table);
3663 objectref_get_or_create(L, obj);
3664 if(lua_pcall(L, 2, 0, 0))
3665 script_error(L, "error: %s", lua_tostring(L, -1));
3670 // EnvRef:set_timeofday(val)
3672 static int l_set_timeofday(lua_State *L)
3674 EnvRef *o = checkobject(L, 1);
3675 ServerEnvironment *env = o->m_env;
3676 if(env == NULL) return 0;
3678 float timeofday_f = luaL_checknumber(L, 2);
3679 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3680 int timeofday_mh = (int)(timeofday_f * 24000.0);
3681 // This should be set directly in the environment but currently
3682 // such changes aren't immediately sent to the clients, so call
3683 // the server instead.
3684 //env->setTimeOfDay(timeofday_mh);
3685 get_server(L)->setTimeOfDay(timeofday_mh);
3689 // EnvRef:get_timeofday() -> 0...1
3690 static int l_get_timeofday(lua_State *L)
3692 EnvRef *o = checkobject(L, 1);
3693 ServerEnvironment *env = o->m_env;
3694 if(env == NULL) return 0;
3696 int timeofday_mh = env->getTimeOfDay();
3697 float timeofday_f = (float)timeofday_mh / 24000.0;
3698 lua_pushnumber(L, timeofday_f);
3703 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3704 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3705 static int l_find_node_near(lua_State *L)
3707 EnvRef *o = checkobject(L, 1);
3708 ServerEnvironment *env = o->m_env;
3709 if(env == NULL) return 0;
3710 INodeDefManager *ndef = get_server(L)->ndef();
3711 v3s16 pos = read_v3s16(L, 2);
3712 int radius = luaL_checkinteger(L, 3);
3713 std::set<content_t> filter;
3714 if(lua_istable(L, 4)){
3717 while(lua_next(L, table) != 0){
3718 // key at index -2 and value at index -1
3719 luaL_checktype(L, -1, LUA_TSTRING);
3720 ndef->getIds(lua_tostring(L, -1), filter);
3721 // removes value, keeps key for next iteration
3724 } else if(lua_isstring(L, 4)){
3725 ndef->getIds(lua_tostring(L, 4), filter);
3728 for(int d=1; d<=radius; d++){
3729 core::list<v3s16> list;
3730 getFacePositions(list, d);
3731 for(core::list<v3s16>::Iterator i = list.begin();
3732 i != list.end(); i++){
3733 v3s16 p = pos + (*i);
3734 content_t c = env->getMap().getNodeNoEx(p).getContent();
3735 if(filter.count(c) != 0){
3744 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3745 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3746 static int l_find_nodes_in_area(lua_State *L)
3748 EnvRef *o = checkobject(L, 1);
3749 ServerEnvironment *env = o->m_env;
3750 if(env == NULL) return 0;
3751 INodeDefManager *ndef = get_server(L)->ndef();
3752 v3s16 minp = read_v3s16(L, 2);
3753 v3s16 maxp = read_v3s16(L, 3);
3754 std::set<content_t> filter;
3755 if(lua_istable(L, 4)){
3758 while(lua_next(L, table) != 0){
3759 // key at index -2 and value at index -1
3760 luaL_checktype(L, -1, LUA_TSTRING);
3761 ndef->getIds(lua_tostring(L, -1), filter);
3762 // removes value, keeps key for next iteration
3765 } else if(lua_isstring(L, 4)){
3766 ndef->getIds(lua_tostring(L, 4), filter);
3769 // Get the table insert function
3770 lua_getglobal(L, "table");
3771 lua_getfield(L, -1, "insert");
3772 int table_insert = lua_gettop(L);
3775 int table = lua_gettop(L);
3776 for(s16 x=minp.X; x<=maxp.X; x++)
3777 for(s16 y=minp.Y; y<=maxp.Y; y++)
3778 for(s16 z=minp.Z; z<=maxp.Z; z++)
3781 content_t c = env->getMap().getNodeNoEx(p).getContent();
3782 if(filter.count(c) != 0){
3783 lua_pushvalue(L, table_insert);
3784 lua_pushvalue(L, table);
3786 if(lua_pcall(L, 2, 0, 0))
3787 script_error(L, "error: %s", lua_tostring(L, -1));
3793 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3794 // returns world-specific PerlinNoise
3795 static int l_get_perlin(lua_State *L)
3797 EnvRef *o = checkobject(L, 1);
3798 ServerEnvironment *env = o->m_env;
3799 if(env == NULL) return 0;
3801 int seeddiff = luaL_checkint(L, 2);
3802 int octaves = luaL_checkint(L, 3);
3803 double persistence = luaL_checknumber(L, 4);
3804 double scale = luaL_checknumber(L, 5);
3806 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3807 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3808 luaL_getmetatable(L, "PerlinNoise");
3809 lua_setmetatable(L, -2);
3813 // EnvRef:clear_objects()
3814 // clear all objects in the environment
3815 static int l_clear_objects(lua_State *L)
3817 EnvRef *o = checkobject(L, 1);
3818 o->m_env->clearAllObjects();
3823 EnvRef(ServerEnvironment *env):
3826 //infostream<<"EnvRef created"<<std::endl;
3831 //infostream<<"EnvRef destructing"<<std::endl;
3834 // Creates an EnvRef and leaves it on top of stack
3835 // Not callable from Lua; all references are created on the C side.
3836 static void create(lua_State *L, ServerEnvironment *env)
3838 EnvRef *o = new EnvRef(env);
3839 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3840 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3841 luaL_getmetatable(L, className);
3842 lua_setmetatable(L, -2);
3845 static void set_null(lua_State *L)
3847 EnvRef *o = checkobject(L, -1);
3851 static void Register(lua_State *L)
3854 int methodtable = lua_gettop(L);
3855 luaL_newmetatable(L, className);
3856 int metatable = lua_gettop(L);
3858 lua_pushliteral(L, "__metatable");
3859 lua_pushvalue(L, methodtable);
3860 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3862 lua_pushliteral(L, "__index");
3863 lua_pushvalue(L, methodtable);
3864 lua_settable(L, metatable);
3866 lua_pushliteral(L, "__gc");
3867 lua_pushcfunction(L, gc_object);
3868 lua_settable(L, metatable);
3870 lua_pop(L, 1); // drop metatable
3872 luaL_openlib(L, 0, methods, 0); // fill methodtable
3873 lua_pop(L, 1); // drop methodtable
3875 // Cannot be created from Lua
3876 //lua_register(L, className, create_object);
3879 const char EnvRef::className[] = "EnvRef";
3880 const luaL_reg EnvRef::methods[] = {
3881 method(EnvRef, set_node),
3882 method(EnvRef, add_node),
3883 method(EnvRef, remove_node),
3884 method(EnvRef, get_node),
3885 method(EnvRef, get_node_or_nil),
3886 method(EnvRef, get_node_light),
3887 method(EnvRef, place_node),
3888 method(EnvRef, dig_node),
3889 method(EnvRef, punch_node),
3890 method(EnvRef, add_entity),
3891 method(EnvRef, add_item),
3892 method(EnvRef, add_rat),
3893 method(EnvRef, add_firefly),
3894 method(EnvRef, get_meta),
3895 method(EnvRef, get_node_timer),
3896 method(EnvRef, get_player_by_name),
3897 method(EnvRef, get_objects_inside_radius),
3898 method(EnvRef, set_timeofday),
3899 method(EnvRef, get_timeofday),
3900 method(EnvRef, find_node_near),
3901 method(EnvRef, find_nodes_in_area),
3902 method(EnvRef, get_perlin),
3903 method(EnvRef, clear_objects),
3912 class LuaPseudoRandom
3915 PseudoRandom m_pseudo;
3917 static const char className[];
3918 static const luaL_reg methods[];
3920 // Exported functions
3922 // garbage collector
3923 static int gc_object(lua_State *L)
3925 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3930 // next(self, min=0, max=32767) -> get next value
3931 static int l_next(lua_State *L)
3933 LuaPseudoRandom *o = checkobject(L, 1);
3936 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3937 if(!lua_isnil(L, 2))
3938 min = luaL_checkinteger(L, 2);
3939 if(!lua_isnil(L, 3))
3940 max = luaL_checkinteger(L, 3);
3942 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
3943 throw LuaError(L, "PseudoRandom.next(): max < min");
3945 if(max - min != 32767 && max - min > 32767/5)
3946 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.");
3947 PseudoRandom &pseudo = o->m_pseudo;
3948 int val = pseudo.next();
3949 val = (val % (max-min+1)) + min;
3950 lua_pushinteger(L, val);
3955 LuaPseudoRandom(int seed):
3964 const PseudoRandom& getItem() const
3968 PseudoRandom& getItem()
3973 // LuaPseudoRandom(seed)
3974 // Creates an LuaPseudoRandom and leaves it on top of stack
3975 static int create_object(lua_State *L)
3977 int seed = luaL_checknumber(L, 1);
3978 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3979 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3980 luaL_getmetatable(L, className);
3981 lua_setmetatable(L, -2);
3985 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3987 luaL_checktype(L, narg, LUA_TUSERDATA);
3988 void *ud = luaL_checkudata(L, narg, className);
3989 if(!ud) luaL_typerror(L, narg, className);
3990 return *(LuaPseudoRandom**)ud; // unbox pointer
3993 static void Register(lua_State *L)
3996 int methodtable = lua_gettop(L);
3997 luaL_newmetatable(L, className);
3998 int metatable = lua_gettop(L);
4000 lua_pushliteral(L, "__metatable");
4001 lua_pushvalue(L, methodtable);
4002 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4004 lua_pushliteral(L, "__index");
4005 lua_pushvalue(L, methodtable);
4006 lua_settable(L, metatable);
4008 lua_pushliteral(L, "__gc");
4009 lua_pushcfunction(L, gc_object);
4010 lua_settable(L, metatable);
4012 lua_pop(L, 1); // drop metatable
4014 luaL_openlib(L, 0, methods, 0); // fill methodtable
4015 lua_pop(L, 1); // drop methodtable
4017 // Can be created from Lua (LuaPseudoRandom(seed))
4018 lua_register(L, className, create_object);
4021 const char LuaPseudoRandom::className[] = "PseudoRandom";
4022 const luaL_reg LuaPseudoRandom::methods[] = {
4023 method(LuaPseudoRandom, next),
4033 class LuaABM : public ActiveBlockModifier
4039 std::set<std::string> m_trigger_contents;
4040 std::set<std::string> m_required_neighbors;
4041 float m_trigger_interval;
4042 u32 m_trigger_chance;
4044 LuaABM(lua_State *L, int id,
4045 const std::set<std::string> &trigger_contents,
4046 const std::set<std::string> &required_neighbors,
4047 float trigger_interval, u32 trigger_chance):
4050 m_trigger_contents(trigger_contents),
4051 m_required_neighbors(required_neighbors),
4052 m_trigger_interval(trigger_interval),
4053 m_trigger_chance(trigger_chance)
4056 virtual std::set<std::string> getTriggerContents()
4058 return m_trigger_contents;
4060 virtual std::set<std::string> getRequiredNeighbors()
4062 return m_required_neighbors;
4064 virtual float getTriggerInterval()
4066 return m_trigger_interval;
4068 virtual u32 getTriggerChance()
4070 return m_trigger_chance;
4072 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4073 u32 active_object_count, u32 active_object_count_wider)
4075 lua_State *L = m_lua;
4078 assert(lua_checkstack(L, 20));
4079 StackUnroller stack_unroller(L);
4081 // Get minetest.registered_abms
4082 lua_getglobal(L, "minetest");
4083 lua_getfield(L, -1, "registered_abms");
4084 luaL_checktype(L, -1, LUA_TTABLE);
4085 int registered_abms = lua_gettop(L);
4087 // Get minetest.registered_abms[m_id]
4088 lua_pushnumber(L, m_id);
4089 lua_gettable(L, registered_abms);
4090 if(lua_isnil(L, -1))
4094 luaL_checktype(L, -1, LUA_TTABLE);
4095 lua_getfield(L, -1, "action");
4096 luaL_checktype(L, -1, LUA_TFUNCTION);
4098 pushnode(L, n, env->getGameDef()->ndef());
4099 lua_pushnumber(L, active_object_count);
4100 lua_pushnumber(L, active_object_count_wider);
4101 if(lua_pcall(L, 4, 0, 0))
4102 script_error(L, "error: %s", lua_tostring(L, -1));
4110 static void read_server_sound_params(lua_State *L, int index,
4111 ServerSoundParams ¶ms)
4114 index = lua_gettop(L) + 1 + index;
4116 params = ServerSoundParams();
4117 if(lua_istable(L, index)){
4118 getfloatfield(L, index, "gain", params.gain);
4119 getstringfield(L, index, "to_player", params.to_player);
4120 lua_getfield(L, index, "pos");
4121 if(!lua_isnil(L, -1)){
4122 v3f p = read_v3f(L, -1)*BS;
4124 params.type = ServerSoundParams::SSP_POSITIONAL;
4127 lua_getfield(L, index, "object");
4128 if(!lua_isnil(L, -1)){
4129 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4130 ServerActiveObject *sao = ObjectRef::getobject(ref);
4132 params.object = sao->getId();
4133 params.type = ServerSoundParams::SSP_OBJECT;
4137 params.max_hear_distance = BS*getfloatfield_default(L, index,
4138 "max_hear_distance", params.max_hear_distance/BS);
4139 getboolfield(L, index, "loop", params.loop);
4148 // Writes a line to dstream
4149 static int l_debug(lua_State *L)
4151 std::string text = lua_tostring(L, 1);
4152 dstream << text << std::endl;
4156 // log([level,] text)
4157 // Writes a line to the logger.
4158 // The one-argument version logs to infostream.
4159 // The two-argument version accept a log level: error, action, info, or verbose.
4160 static int l_log(lua_State *L)
4163 LogMessageLevel level = LMT_INFO;
4164 if(lua_isnone(L, 2))
4166 text = lua_tostring(L, 1);
4170 std::string levelname = lua_tostring(L, 1);
4171 text = lua_tostring(L, 2);
4172 if(levelname == "error")
4174 else if(levelname == "action")
4176 else if(levelname == "verbose")
4177 level = LMT_VERBOSE;
4179 log_printline(level, text);
4183 // request_shutdown()
4184 static int l_request_shutdown(lua_State *L)
4186 get_server(L)->requestShutdown();
4190 // get_server_status()
4191 static int l_get_server_status(lua_State *L)
4193 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4197 // register_item_raw({lots of stuff})
4198 static int l_register_item_raw(lua_State *L)
4200 luaL_checktype(L, 1, LUA_TTABLE);
4203 // Get the writable item and node definition managers from the server
4204 IWritableItemDefManager *idef =
4205 get_server(L)->getWritableItemDefManager();
4206 IWritableNodeDefManager *ndef =
4207 get_server(L)->getWritableNodeDefManager();
4209 // Check if name is defined
4211 lua_getfield(L, table, "name");
4212 if(lua_isstring(L, -1)){
4213 name = lua_tostring(L, -1);
4214 verbosestream<<"register_item_raw: "<<name<<std::endl;
4216 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4219 // Check if on_use is defined
4222 // Set a distinctive default value to check if this is set
4223 def.node_placement_prediction = "__default";
4225 // Read the item definition
4226 def = read_item_definition(L, table, def);
4228 // Default to having client-side placement prediction for nodes
4229 // ("" in item definition sets it off)
4230 if(def.node_placement_prediction == "__default"){
4231 if(def.type == ITEM_NODE)
4232 def.node_placement_prediction = name;
4234 def.node_placement_prediction = "";
4237 // Register item definition
4238 idef->registerItem(def);
4240 // Read the node definition (content features) and register it
4241 if(def.type == ITEM_NODE)
4243 ContentFeatures f = read_content_features(L, table);
4244 ndef->set(f.name, f);
4247 return 0; /* number of results */
4250 // register_alias_raw(name, convert_to_name)
4251 static int l_register_alias_raw(lua_State *L)
4253 std::string name = luaL_checkstring(L, 1);
4254 std::string convert_to = luaL_checkstring(L, 2);
4256 // Get the writable item definition manager from the server
4257 IWritableItemDefManager *idef =
4258 get_server(L)->getWritableItemDefManager();
4260 idef->registerAlias(name, convert_to);
4262 return 0; /* number of results */
4265 // helper for register_craft
4266 static bool read_craft_recipe_shaped(lua_State *L, int index,
4267 int &width, std::vector<std::string> &recipe)
4270 index = lua_gettop(L) + 1 + index;
4272 if(!lua_istable(L, index))
4277 while(lua_next(L, index) != 0){
4279 // key at index -2 and value at index -1
4280 if(!lua_istable(L, -1))
4282 int table2 = lua_gettop(L);
4284 while(lua_next(L, table2) != 0){
4285 // key at index -2 and value at index -1
4286 if(!lua_isstring(L, -1))
4288 recipe.push_back(lua_tostring(L, -1));
4289 // removes value, keeps key for next iteration
4296 if(colcount != width)
4299 // removes value, keeps key for next iteration
4306 // helper for register_craft
4307 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4308 std::vector<std::string> &recipe)
4311 index = lua_gettop(L) + 1 + index;
4313 if(!lua_istable(L, index))
4317 while(lua_next(L, index) != 0){
4318 // key at index -2 and value at index -1
4319 if(!lua_isstring(L, -1))
4321 recipe.push_back(lua_tostring(L, -1));
4322 // removes value, keeps key for next iteration
4328 // helper for register_craft
4329 static bool read_craft_replacements(lua_State *L, int index,
4330 CraftReplacements &replacements)
4333 index = lua_gettop(L) + 1 + index;
4335 if(!lua_istable(L, index))
4339 while(lua_next(L, index) != 0){
4340 // key at index -2 and value at index -1
4341 if(!lua_istable(L, -1))
4343 lua_rawgeti(L, -1, 1);
4344 if(!lua_isstring(L, -1))
4346 std::string replace_from = lua_tostring(L, -1);
4348 lua_rawgeti(L, -1, 2);
4349 if(!lua_isstring(L, -1))
4351 std::string replace_to = lua_tostring(L, -1);
4353 replacements.pairs.push_back(
4354 std::make_pair(replace_from, replace_to));
4355 // removes value, keeps key for next iteration
4360 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4361 static int l_register_craft(lua_State *L)
4363 //infostream<<"register_craft"<<std::endl;
4364 luaL_checktype(L, 1, LUA_TTABLE);
4367 // Get the writable craft definition manager from the server
4368 IWritableCraftDefManager *craftdef =
4369 get_server(L)->getWritableCraftDefManager();
4371 std::string type = getstringfield_default(L, table, "type", "shaped");
4374 CraftDefinitionShaped
4376 if(type == "shaped"){
4377 std::string output = getstringfield_default(L, table, "output", "");
4379 throw LuaError(L, "Crafting definition is missing an output");
4382 std::vector<std::string> recipe;
4383 lua_getfield(L, table, "recipe");
4384 if(lua_isnil(L, -1))
4385 throw LuaError(L, "Crafting definition is missing a recipe"
4386 " (output=\"" + output + "\")");
4387 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4388 throw LuaError(L, "Invalid crafting recipe"
4389 " (output=\"" + output + "\")");
4391 CraftReplacements replacements;
4392 lua_getfield(L, table, "replacements");
4393 if(!lua_isnil(L, -1))
4395 if(!read_craft_replacements(L, -1, replacements))
4396 throw LuaError(L, "Invalid replacements"
4397 " (output=\"" + output + "\")");
4400 CraftDefinition *def = new CraftDefinitionShaped(
4401 output, width, recipe, replacements);
4402 craftdef->registerCraft(def);
4405 CraftDefinitionShapeless
4407 else if(type == "shapeless"){
4408 std::string output = getstringfield_default(L, table, "output", "");
4410 throw LuaError(L, "Crafting definition (shapeless)"
4411 " is missing an output");
4413 std::vector<std::string> recipe;
4414 lua_getfield(L, table, "recipe");
4415 if(lua_isnil(L, -1))
4416 throw LuaError(L, "Crafting definition (shapeless)"
4417 " is missing a recipe"
4418 " (output=\"" + output + "\")");
4419 if(!read_craft_recipe_shapeless(L, -1, recipe))
4420 throw LuaError(L, "Invalid crafting recipe"
4421 " (output=\"" + output + "\")");
4423 CraftReplacements replacements;
4424 lua_getfield(L, table, "replacements");
4425 if(!lua_isnil(L, -1))
4427 if(!read_craft_replacements(L, -1, replacements))
4428 throw LuaError(L, "Invalid replacements"
4429 " (output=\"" + output + "\")");
4432 CraftDefinition *def = new CraftDefinitionShapeless(
4433 output, recipe, replacements);
4434 craftdef->registerCraft(def);
4437 CraftDefinitionToolRepair
4439 else if(type == "toolrepair"){
4440 float additional_wear = getfloatfield_default(L, table,
4441 "additional_wear", 0.0);
4443 CraftDefinition *def = new CraftDefinitionToolRepair(
4445 craftdef->registerCraft(def);
4448 CraftDefinitionCooking
4450 else if(type == "cooking"){
4451 std::string output = getstringfield_default(L, table, "output", "");
4453 throw LuaError(L, "Crafting definition (cooking)"
4454 " is missing an output");
4456 std::string recipe = getstringfield_default(L, table, "recipe", "");
4458 throw LuaError(L, "Crafting definition (cooking)"
4459 " is missing a recipe"
4460 " (output=\"" + output + "\")");
4462 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4464 CraftReplacements replacements;
4465 lua_getfield(L, table, "replacements");
4466 if(!lua_isnil(L, -1))
4468 if(!read_craft_replacements(L, -1, replacements))
4469 throw LuaError(L, "Invalid replacements"
4470 " (cooking output=\"" + output + "\")");
4473 CraftDefinition *def = new CraftDefinitionCooking(
4474 output, recipe, cooktime, replacements);
4475 craftdef->registerCraft(def);
4480 else if(type == "fuel"){
4481 std::string recipe = getstringfield_default(L, table, "recipe", "");
4483 throw LuaError(L, "Crafting definition (fuel)"
4484 " is missing a recipe");
4486 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4488 CraftReplacements replacements;
4489 lua_getfield(L, table, "replacements");
4490 if(!lua_isnil(L, -1))
4492 if(!read_craft_replacements(L, -1, replacements))
4493 throw LuaError(L, "Invalid replacements"
4494 " (fuel recipe=\"" + recipe + "\")");
4497 CraftDefinition *def = new CraftDefinitionFuel(
4498 recipe, burntime, replacements);
4499 craftdef->registerCraft(def);
4503 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4507 return 0; /* number of results */
4510 // setting_set(name, value)
4511 static int l_setting_set(lua_State *L)
4513 const char *name = luaL_checkstring(L, 1);
4514 const char *value = luaL_checkstring(L, 2);
4515 g_settings->set(name, value);
4519 // setting_get(name)
4520 static int l_setting_get(lua_State *L)
4522 const char *name = luaL_checkstring(L, 1);
4524 std::string value = g_settings->get(name);
4525 lua_pushstring(L, value.c_str());
4526 } catch(SettingNotFoundException &e){
4532 // setting_getbool(name)
4533 static int l_setting_getbool(lua_State *L)
4535 const char *name = luaL_checkstring(L, 1);
4537 bool value = g_settings->getBool(name);
4538 lua_pushboolean(L, value);
4539 } catch(SettingNotFoundException &e){
4545 // chat_send_all(text)
4546 static int l_chat_send_all(lua_State *L)
4548 const char *text = luaL_checkstring(L, 1);
4549 // Get server from registry
4550 Server *server = get_server(L);
4552 server->notifyPlayers(narrow_to_wide(text));
4556 // chat_send_player(name, text)
4557 static int l_chat_send_player(lua_State *L)
4559 const char *name = luaL_checkstring(L, 1);
4560 const char *text = luaL_checkstring(L, 2);
4561 // Get server from registry
4562 Server *server = get_server(L);
4564 server->notifyPlayer(name, narrow_to_wide(text));
4568 // get_player_privs(name, text)
4569 static int l_get_player_privs(lua_State *L)
4571 const char *name = luaL_checkstring(L, 1);
4572 // Get server from registry
4573 Server *server = get_server(L);
4576 int table = lua_gettop(L);
4577 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4578 for(std::set<std::string>::const_iterator
4579 i = privs_s.begin(); i != privs_s.end(); i++){
4580 lua_pushboolean(L, true);
4581 lua_setfield(L, table, i->c_str());
4583 lua_pushvalue(L, table);
4587 // get_inventory(location)
4588 static int l_get_inventory(lua_State *L)
4590 InventoryLocation loc;
4592 std::string type = checkstringfield(L, 1, "type");
4593 if(type == "player"){
4594 std::string name = checkstringfield(L, 1, "name");
4595 loc.setPlayer(name);
4596 } else if(type == "node"){
4597 lua_getfield(L, 1, "pos");
4598 v3s16 pos = check_v3s16(L, -1);
4599 loc.setNodeMeta(pos);
4600 } else if(type == "detached"){
4601 std::string name = checkstringfield(L, 1, "name");
4602 loc.setDetached(name);
4605 if(get_server(L)->getInventory(loc) != NULL)
4606 InvRef::create(L, loc);
4612 // create_detached_inventory_raw(name)
4613 static int l_create_detached_inventory_raw(lua_State *L)
4615 const char *name = luaL_checkstring(L, 1);
4616 if(get_server(L)->createDetachedInventory(name) != NULL){
4617 InventoryLocation loc;
4618 loc.setDetached(name);
4619 InvRef::create(L, loc);
4626 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4627 static int l_get_dig_params(lua_State *L)
4629 std::map<std::string, int> groups;
4630 read_groups(L, 1, groups);
4631 ToolCapabilities tp = read_tool_capabilities(L, 2);
4632 if(lua_isnoneornil(L, 3))
4633 push_dig_params(L, getDigParams(groups, &tp));
4635 push_dig_params(L, getDigParams(groups, &tp,
4636 luaL_checknumber(L, 3)));
4640 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4641 static int l_get_hit_params(lua_State *L)
4643 std::map<std::string, int> groups;
4644 read_groups(L, 1, groups);
4645 ToolCapabilities tp = read_tool_capabilities(L, 2);
4646 if(lua_isnoneornil(L, 3))
4647 push_hit_params(L, getHitParams(groups, &tp));
4649 push_hit_params(L, getHitParams(groups, &tp,
4650 luaL_checknumber(L, 3)));
4654 // get_current_modname()
4655 static int l_get_current_modname(lua_State *L)
4657 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4661 // get_modpath(modname)
4662 static int l_get_modpath(lua_State *L)
4664 std::string modname = luaL_checkstring(L, 1);
4666 if(modname == "__builtin"){
4667 std::string path = get_server(L)->getBuiltinLuaPath();
4668 lua_pushstring(L, path.c_str());
4671 const ModSpec *mod = get_server(L)->getModSpec(modname);
4676 lua_pushstring(L, mod->path.c_str());
4681 // the returned list is sorted alphabetically for you
4682 static int l_get_modnames(lua_State *L)
4684 // Get a list of mods
4685 core::list<std::string> mods_unsorted, mods_sorted;
4686 get_server(L)->getModNames(mods_unsorted);
4688 // Take unsorted items from mods_unsorted and sort them into
4689 // mods_sorted; not great performance but the number of mods on a
4690 // server will likely be small.
4691 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4692 i != mods_unsorted.end(); i++)
4695 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4696 x != mods_unsorted.end(); x++)
4698 // I doubt anybody using Minetest will be using
4699 // anything not ASCII based :)
4700 if((*i).compare(*x) <= 0)
4702 mods_sorted.insert_before(x, *i);
4708 mods_sorted.push_back(*i);
4711 // Get the table insertion function from Lua.
4712 lua_getglobal(L, "table");
4713 lua_getfield(L, -1, "insert");
4714 int insertion_func = lua_gettop(L);
4716 // Package them up for Lua
4718 int new_table = lua_gettop(L);
4719 core::list<std::string>::Iterator i = mods_sorted.begin();
4720 while(i != mods_sorted.end())
4722 lua_pushvalue(L, insertion_func);
4723 lua_pushvalue(L, new_table);
4724 lua_pushstring(L, (*i).c_str());
4725 if(lua_pcall(L, 2, 0, 0) != 0)
4727 script_error(L, "error: %s", lua_tostring(L, -1));
4735 static int l_get_worldpath(lua_State *L)
4737 std::string worldpath = get_server(L)->getWorldPath();
4738 lua_pushstring(L, worldpath.c_str());
4742 // sound_play(spec, parameters)
4743 static int l_sound_play(lua_State *L)
4745 SimpleSoundSpec spec;
4746 read_soundspec(L, 1, spec);
4747 ServerSoundParams params;
4748 read_server_sound_params(L, 2, params);
4749 s32 handle = get_server(L)->playSound(spec, params);
4750 lua_pushinteger(L, handle);
4754 // sound_stop(handle)
4755 static int l_sound_stop(lua_State *L)
4757 int handle = luaL_checkinteger(L, 1);
4758 get_server(L)->stopSound(handle);
4762 // is_singleplayer()
4763 static int l_is_singleplayer(lua_State *L)
4765 lua_pushboolean(L, get_server(L)->isSingleplayer());
4769 // get_password_hash(name, raw_password)
4770 static int l_get_password_hash(lua_State *L)
4772 std::string name = luaL_checkstring(L, 1);
4773 std::string raw_password = luaL_checkstring(L, 2);
4774 std::string hash = translatePassword(name,
4775 narrow_to_wide(raw_password));
4776 lua_pushstring(L, hash.c_str());
4780 // notify_authentication_modified(name)
4781 static int l_notify_authentication_modified(lua_State *L)
4783 std::string name = "";
4784 if(lua_isstring(L, 1))
4785 name = lua_tostring(L, 1);
4786 get_server(L)->reportPrivsModified(name);
4790 // get_craft_result(input)
4791 static int l_get_craft_result(lua_State *L)
4794 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4795 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4796 es_CraftMethod, CRAFT_METHOD_NORMAL);
4798 lua_getfield(L, input_i, "width");
4799 if(lua_isnumber(L, -1))
4800 width = luaL_checkinteger(L, -1);
4802 lua_getfield(L, input_i, "items");
4803 std::vector<ItemStack> items = read_items(L, -1);
4804 lua_pop(L, 1); // items
4806 IGameDef *gdef = get_server(L);
4807 ICraftDefManager *cdef = gdef->cdef();
4808 CraftInput input(method, width, items);
4810 bool got = cdef->getCraftResult(input, output, true, gdef);
4811 lua_newtable(L); // output table
4814 item.deSerialize(output.item, gdef->idef());
4815 LuaItemStack::create(L, item);
4816 lua_setfield(L, -2, "item");
4817 setintfield(L, -1, "time", output.time);
4819 LuaItemStack::create(L, ItemStack());
4820 lua_setfield(L, -2, "item");
4821 setintfield(L, -1, "time", 0);
4823 lua_newtable(L); // decremented input table
4824 lua_pushstring(L, method_s.c_str());
4825 lua_setfield(L, -2, "method");
4826 lua_pushinteger(L, width);
4827 lua_setfield(L, -2, "width");
4828 push_items(L, input.items);
4829 lua_setfield(L, -2, "items");
4833 // get_craft_recipe(result item)
4834 static int l_get_craft_recipe(lua_State *L)
4839 std::string o_item = luaL_checkstring(L,input_i);
4841 IGameDef *gdef = get_server(L);
4842 ICraftDefManager *cdef = gdef->cdef();
4844 CraftOutput output(o_item,0);
4845 bool got = cdef->getCraftRecipe(input, output, gdef);
4846 lua_newtable(L); // output table
4849 for(std::vector<ItemStack>::const_iterator
4850 i = input.items.begin();
4851 i != input.items.end(); i++, k++)
4857 sprintf(tmp,"%d",k);
4858 lua_pushstring(L,tmp);
4859 lua_pushstring(L,i->name.c_str());
4860 lua_settable(L, -3);
4862 lua_setfield(L, -2, "items");
4863 setintfield(L, -1, "width", input.width);
4864 switch (input.method) {
4865 case CRAFT_METHOD_NORMAL:
4866 lua_pushstring(L,"normal");
4868 case CRAFT_METHOD_COOKING:
4869 lua_pushstring(L,"cooking");
4871 case CRAFT_METHOD_FUEL:
4872 lua_pushstring(L,"fuel");
4875 lua_pushstring(L,"unknown");
4877 lua_setfield(L, -2, "type");
4880 lua_setfield(L, -2, "items");
4881 setintfield(L, -1, "width", 0);
4886 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
4887 static int l_rollback_get_last_node_actor(lua_State *L)
4889 v3s16 p = read_v3s16(L, 1);
4890 int range = luaL_checknumber(L, 2);
4891 int seconds = luaL_checknumber(L, 3);
4892 Server *server = get_server(L);
4893 IRollbackManager *rollback = server->getRollbackManager();
4895 int act_seconds = 0;
4896 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
4897 lua_pushstring(L, actor.c_str());
4898 push_v3s16(L, act_p);
4899 lua_pushnumber(L, act_seconds);
4903 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
4904 static int l_rollback_revert_actions_by(lua_State *L)
4906 std::string actor = luaL_checkstring(L, 1);
4907 int seconds = luaL_checknumber(L, 2);
4908 Server *server = get_server(L);
4909 IRollbackManager *rollback = server->getRollbackManager();
4910 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
4911 std::list<std::string> log;
4912 bool success = server->rollbackRevertActions(actions, &log);
4913 // Push boolean result
4914 lua_pushboolean(L, success);
4915 // Get the table insert function and push the log table
4916 lua_getglobal(L, "table");
4917 lua_getfield(L, -1, "insert");
4918 int table_insert = lua_gettop(L);
4920 int table = lua_gettop(L);
4921 for(std::list<std::string>::const_iterator i = log.begin();
4922 i != log.end(); i++)
4924 lua_pushvalue(L, table_insert);
4925 lua_pushvalue(L, table);
4926 lua_pushstring(L, i->c_str());
4927 if(lua_pcall(L, 2, 0, 0))
4928 script_error(L, "error: %s", lua_tostring(L, -1));
4930 lua_remove(L, -2); // Remove table
4931 lua_remove(L, -2); // Remove insert
4935 static const struct luaL_Reg minetest_f [] = {
4938 {"request_shutdown", l_request_shutdown},
4939 {"get_server_status", l_get_server_status},
4940 {"register_item_raw", l_register_item_raw},
4941 {"register_alias_raw", l_register_alias_raw},
4942 {"register_craft", l_register_craft},
4943 {"setting_set", l_setting_set},
4944 {"setting_get", l_setting_get},
4945 {"setting_getbool", l_setting_getbool},
4946 {"chat_send_all", l_chat_send_all},
4947 {"chat_send_player", l_chat_send_player},
4948 {"get_player_privs", l_get_player_privs},
4949 {"get_inventory", l_get_inventory},
4950 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
4951 {"get_dig_params", l_get_dig_params},
4952 {"get_hit_params", l_get_hit_params},
4953 {"get_current_modname", l_get_current_modname},
4954 {"get_modpath", l_get_modpath},
4955 {"get_modnames", l_get_modnames},
4956 {"get_worldpath", l_get_worldpath},
4957 {"sound_play", l_sound_play},
4958 {"sound_stop", l_sound_stop},
4959 {"is_singleplayer", l_is_singleplayer},
4960 {"get_password_hash", l_get_password_hash},
4961 {"notify_authentication_modified", l_notify_authentication_modified},
4962 {"get_craft_result", l_get_craft_result},
4963 {"get_craft_recipe", l_get_craft_recipe},
4964 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
4965 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
4970 Main export function
4973 void scriptapi_export(lua_State *L, Server *server)
4976 assert(lua_checkstack(L, 20));
4977 verbosestream<<"scriptapi_export()"<<std::endl;
4978 StackUnroller stack_unroller(L);
4980 // Store server as light userdata in registry
4981 lua_pushlightuserdata(L, server);
4982 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4984 // Register global functions in table minetest
4986 luaL_register(L, NULL, minetest_f);
4987 lua_setglobal(L, "minetest");
4989 // Get the main minetest table
4990 lua_getglobal(L, "minetest");
4992 // Add tables to minetest
4994 lua_setfield(L, -2, "object_refs");
4996 lua_setfield(L, -2, "luaentities");
4998 // Register wrappers
4999 LuaItemStack::Register(L);
5000 InvRef::Register(L);
5001 NodeMetaRef::Register(L);
5002 NodeTimerRef::Register(L);
5003 ObjectRef::Register(L);
5004 EnvRef::Register(L);
5005 LuaPseudoRandom::Register(L);
5006 LuaPerlinNoise::Register(L);
5009 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5010 const std::string &modname)
5012 ModNameStorer modnamestorer(L, modname);
5014 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5016 errorstream<<"Error loading mod \""<<modname
5017 <<"\": modname does not follow naming conventions: "
5018 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5022 bool success = false;
5025 success = script_load(L, scriptpath.c_str());
5028 errorstream<<"Error loading mod \""<<modname
5029 <<"\": "<<e.what()<<std::endl;
5035 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5038 assert(lua_checkstack(L, 20));
5039 verbosestream<<"scriptapi_add_environment"<<std::endl;
5040 StackUnroller stack_unroller(L);
5042 // Create EnvRef on stack
5043 EnvRef::create(L, env);
5044 int envref = lua_gettop(L);
5046 // minetest.env = envref
5047 lua_getglobal(L, "minetest");
5048 luaL_checktype(L, -1, LUA_TTABLE);
5049 lua_pushvalue(L, envref);
5050 lua_setfield(L, -2, "env");
5052 // Store environment as light userdata in registry
5053 lua_pushlightuserdata(L, env);
5054 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5057 Add ActiveBlockModifiers to environment
5060 // Get minetest.registered_abms
5061 lua_getglobal(L, "minetest");
5062 lua_getfield(L, -1, "registered_abms");
5063 luaL_checktype(L, -1, LUA_TTABLE);
5064 int registered_abms = lua_gettop(L);
5066 if(lua_istable(L, registered_abms)){
5067 int table = lua_gettop(L);
5069 while(lua_next(L, table) != 0){
5070 // key at index -2 and value at index -1
5071 int id = lua_tonumber(L, -2);
5072 int current_abm = lua_gettop(L);
5074 std::set<std::string> trigger_contents;
5075 lua_getfield(L, current_abm, "nodenames");
5076 if(lua_istable(L, -1)){
5077 int table = lua_gettop(L);
5079 while(lua_next(L, table) != 0){
5080 // key at index -2 and value at index -1
5081 luaL_checktype(L, -1, LUA_TSTRING);
5082 trigger_contents.insert(lua_tostring(L, -1));
5083 // removes value, keeps key for next iteration
5086 } else if(lua_isstring(L, -1)){
5087 trigger_contents.insert(lua_tostring(L, -1));
5091 std::set<std::string> required_neighbors;
5092 lua_getfield(L, current_abm, "neighbors");
5093 if(lua_istable(L, -1)){
5094 int table = lua_gettop(L);
5096 while(lua_next(L, table) != 0){
5097 // key at index -2 and value at index -1
5098 luaL_checktype(L, -1, LUA_TSTRING);
5099 required_neighbors.insert(lua_tostring(L, -1));
5100 // removes value, keeps key for next iteration
5103 } else if(lua_isstring(L, -1)){
5104 required_neighbors.insert(lua_tostring(L, -1));
5108 float trigger_interval = 10.0;
5109 getfloatfield(L, current_abm, "interval", trigger_interval);
5111 int trigger_chance = 50;
5112 getintfield(L, current_abm, "chance", trigger_chance);
5114 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5115 required_neighbors, trigger_interval, trigger_chance);
5117 env->addActiveBlockModifier(abm);
5119 // removes value, keeps key for next iteration
5127 // Dump stack top with the dump2 function
5128 static void dump2(lua_State *L, const char *name)
5130 // Dump object (debug)
5131 lua_getglobal(L, "dump2");
5132 luaL_checktype(L, -1, LUA_TFUNCTION);
5133 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5134 lua_pushstring(L, name);
5135 if(lua_pcall(L, 2, 0, 0))
5136 script_error(L, "error: %s", lua_tostring(L, -1));
5144 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5147 assert(lua_checkstack(L, 20));
5148 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5149 StackUnroller stack_unroller(L);
5151 // Create object on stack
5152 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5153 int object = lua_gettop(L);
5155 // Get minetest.object_refs table
5156 lua_getglobal(L, "minetest");
5157 lua_getfield(L, -1, "object_refs");
5158 luaL_checktype(L, -1, LUA_TTABLE);
5159 int objectstable = lua_gettop(L);
5161 // object_refs[id] = object
5162 lua_pushnumber(L, cobj->getId()); // Push id
5163 lua_pushvalue(L, object); // Copy object to top of stack
5164 lua_settable(L, objectstable);
5167 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5170 assert(lua_checkstack(L, 20));
5171 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5172 StackUnroller stack_unroller(L);
5174 // Get minetest.object_refs table
5175 lua_getglobal(L, "minetest");
5176 lua_getfield(L, -1, "object_refs");
5177 luaL_checktype(L, -1, LUA_TTABLE);
5178 int objectstable = lua_gettop(L);
5180 // Get object_refs[id]
5181 lua_pushnumber(L, cobj->getId()); // Push id
5182 lua_gettable(L, objectstable);
5183 // Set object reference to NULL
5184 ObjectRef::set_null(L);
5185 lua_pop(L, 1); // pop object
5187 // Set object_refs[id] = nil
5188 lua_pushnumber(L, cobj->getId()); // Push id
5190 lua_settable(L, objectstable);
5197 // What scriptapi_run_callbacks does with the return values of callbacks.
5198 // Regardless of the mode, if only one callback is defined,
5199 // its return value is the total return value.
5200 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5201 enum RunCallbacksMode
5203 // Returns the return value of the first callback
5204 // Returns nil if list of callbacks is empty
5205 RUN_CALLBACKS_MODE_FIRST,
5206 // Returns the return value of the last callback
5207 // Returns nil if list of callbacks is empty
5208 RUN_CALLBACKS_MODE_LAST,
5209 // If any callback returns a false value, the first such is returned
5210 // Otherwise, the first callback's return value (trueish) is returned
5211 // Returns true if list of callbacks is empty
5212 RUN_CALLBACKS_MODE_AND,
5213 // Like above, but stops calling callbacks (short circuit)
5214 // after seeing the first false value
5215 RUN_CALLBACKS_MODE_AND_SC,
5216 // If any callback returns a true value, the first such is returned
5217 // Otherwise, the first callback's return value (falseish) is returned
5218 // Returns false if list of callbacks is empty
5219 RUN_CALLBACKS_MODE_OR,
5220 // Like above, but stops calling callbacks (short circuit)
5221 // after seeing the first true value
5222 RUN_CALLBACKS_MODE_OR_SC,
5223 // Note: "a true value" and "a false value" refer to values that
5224 // are converted by lua_toboolean to true or false, respectively.
5227 // Push the list of callbacks (a lua table).
5228 // Then push nargs arguments.
5229 // Then call this function, which
5230 // - runs the callbacks
5231 // - removes the table and arguments from the lua stack
5232 // - pushes the return value, computed depending on mode
5233 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5234 RunCallbacksMode mode)
5236 // Insert the return value into the lua stack, below the table
5237 assert(lua_gettop(L) >= nargs + 1);
5239 lua_insert(L, -(nargs + 1) - 1);
5240 // Stack now looks like this:
5241 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5243 int rv = lua_gettop(L) - nargs - 1;
5245 int arg = table + 1;
5247 luaL_checktype(L, table, LUA_TTABLE);
5251 bool first_loop = true;
5252 while(lua_next(L, table) != 0){
5253 // key at index -2 and value at index -1
5254 luaL_checktype(L, -1, LUA_TFUNCTION);
5256 for(int i = 0; i < nargs; i++)
5257 lua_pushvalue(L, arg+i);
5258 if(lua_pcall(L, nargs, 1, 0))
5259 script_error(L, "error: %s", lua_tostring(L, -1));
5261 // Move return value to designated space in stack
5264 // Result of first callback is always moved
5268 // Otherwise, what happens depends on the mode
5269 if(mode == RUN_CALLBACKS_MODE_FIRST)
5271 else if(mode == RUN_CALLBACKS_MODE_LAST)
5273 else if(mode == RUN_CALLBACKS_MODE_AND ||
5274 mode == RUN_CALLBACKS_MODE_AND_SC){
5275 if(lua_toboolean(L, rv) == true &&
5276 lua_toboolean(L, -1) == false)
5281 else if(mode == RUN_CALLBACKS_MODE_OR ||
5282 mode == RUN_CALLBACKS_MODE_OR_SC){
5283 if(lua_toboolean(L, rv) == false &&
5284 lua_toboolean(L, -1) == true)
5293 // Handle short circuit modes
5294 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5295 lua_toboolean(L, rv) == false)
5297 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5298 lua_toboolean(L, rv) == true)
5301 // value removed, keep key for next iteration
5304 // Remove stuff from stack, leaving only the return value
5307 // Fix return value in case no callbacks were called
5309 if(mode == RUN_CALLBACKS_MODE_AND ||
5310 mode == RUN_CALLBACKS_MODE_AND_SC){
5312 lua_pushboolean(L, true);
5314 else if(mode == RUN_CALLBACKS_MODE_OR ||
5315 mode == RUN_CALLBACKS_MODE_OR_SC){
5317 lua_pushboolean(L, false);
5322 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5323 const std::string &message)
5326 assert(lua_checkstack(L, 20));
5327 StackUnroller stack_unroller(L);
5329 // Get minetest.registered_on_chat_messages
5330 lua_getglobal(L, "minetest");
5331 lua_getfield(L, -1, "registered_on_chat_messages");
5333 lua_pushstring(L, name.c_str());
5334 lua_pushstring(L, message.c_str());
5335 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5336 bool ate = lua_toboolean(L, -1);
5340 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5343 assert(lua_checkstack(L, 20));
5344 StackUnroller stack_unroller(L);
5346 // Get minetest.registered_on_newplayers
5347 lua_getglobal(L, "minetest");
5348 lua_getfield(L, -1, "registered_on_newplayers");
5350 objectref_get_or_create(L, player);
5351 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5354 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5357 assert(lua_checkstack(L, 20));
5358 StackUnroller stack_unroller(L);
5360 // Get minetest.registered_on_dieplayers
5361 lua_getglobal(L, "minetest");
5362 lua_getfield(L, -1, "registered_on_dieplayers");
5364 objectref_get_or_create(L, player);
5365 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5368 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5371 assert(lua_checkstack(L, 20));
5372 StackUnroller stack_unroller(L);
5374 // Get minetest.registered_on_respawnplayers
5375 lua_getglobal(L, "minetest");
5376 lua_getfield(L, -1, "registered_on_respawnplayers");
5378 objectref_get_or_create(L, player);
5379 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5380 bool positioning_handled_by_some = lua_toboolean(L, -1);
5381 return positioning_handled_by_some;
5384 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5387 assert(lua_checkstack(L, 20));
5388 StackUnroller stack_unroller(L);
5390 // Get minetest.registered_on_joinplayers
5391 lua_getglobal(L, "minetest");
5392 lua_getfield(L, -1, "registered_on_joinplayers");
5394 objectref_get_or_create(L, player);
5395 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5398 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5401 assert(lua_checkstack(L, 20));
5402 StackUnroller stack_unroller(L);
5404 // Get minetest.registered_on_leaveplayers
5405 lua_getglobal(L, "minetest");
5406 lua_getfield(L, -1, "registered_on_leaveplayers");
5408 objectref_get_or_create(L, player);
5409 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5412 static void get_auth_handler(lua_State *L)
5414 lua_getglobal(L, "minetest");
5415 lua_getfield(L, -1, "registered_auth_handler");
5416 if(lua_isnil(L, -1)){
5418 lua_getfield(L, -1, "builtin_auth_handler");
5420 if(lua_type(L, -1) != LUA_TTABLE)
5421 throw LuaError(L, "Authentication handler table not valid");
5424 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5425 std::string *dst_password, std::set<std::string> *dst_privs)
5428 assert(lua_checkstack(L, 20));
5429 StackUnroller stack_unroller(L);
5431 get_auth_handler(L);
5432 lua_getfield(L, -1, "get_auth");
5433 if(lua_type(L, -1) != LUA_TFUNCTION)
5434 throw LuaError(L, "Authentication handler missing get_auth");
5435 lua_pushstring(L, playername.c_str());
5436 if(lua_pcall(L, 1, 1, 0))
5437 script_error(L, "error: %s", lua_tostring(L, -1));
5439 // nil = login not allowed
5440 if(lua_isnil(L, -1))
5442 luaL_checktype(L, -1, LUA_TTABLE);
5444 std::string password;
5445 bool found = getstringfield(L, -1, "password", password);
5447 throw LuaError(L, "Authentication handler didn't return password");
5449 *dst_password = password;
5451 lua_getfield(L, -1, "privileges");
5452 if(!lua_istable(L, -1))
5454 "Authentication handler didn't return privilege table");
5456 read_privileges(L, -1, *dst_privs);
5462 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5463 const std::string &password)
5466 assert(lua_checkstack(L, 20));
5467 StackUnroller stack_unroller(L);
5469 get_auth_handler(L);
5470 lua_getfield(L, -1, "create_auth");
5471 if(lua_type(L, -1) != LUA_TFUNCTION)
5472 throw LuaError(L, "Authentication handler missing create_auth");
5473 lua_pushstring(L, playername.c_str());
5474 lua_pushstring(L, password.c_str());
5475 if(lua_pcall(L, 2, 0, 0))
5476 script_error(L, "error: %s", lua_tostring(L, -1));
5479 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5480 const std::string &password)
5483 assert(lua_checkstack(L, 20));
5484 StackUnroller stack_unroller(L);
5486 get_auth_handler(L);
5487 lua_getfield(L, -1, "set_password");
5488 if(lua_type(L, -1) != LUA_TFUNCTION)
5489 throw LuaError(L, "Authentication handler missing set_password");
5490 lua_pushstring(L, playername.c_str());
5491 lua_pushstring(L, password.c_str());
5492 if(lua_pcall(L, 2, 1, 0))
5493 script_error(L, "error: %s", lua_tostring(L, -1));
5494 return lua_toboolean(L, -1);
5501 void scriptapi_on_player_receive_fields(lua_State *L,
5502 ServerActiveObject *player,
5503 const std::string &formname,
5504 const std::map<std::string, std::string> &fields)
5507 assert(lua_checkstack(L, 20));
5508 StackUnroller stack_unroller(L);
5510 // Get minetest.registered_on_chat_messages
5511 lua_getglobal(L, "minetest");
5512 lua_getfield(L, -1, "registered_on_player_receive_fields");
5515 objectref_get_or_create(L, player);
5517 lua_pushstring(L, formname.c_str());
5520 for(std::map<std::string, std::string>::const_iterator
5521 i = fields.begin(); i != fields.end(); i++){
5522 const std::string &name = i->first;
5523 const std::string &value = i->second;
5524 lua_pushstring(L, name.c_str());
5525 lua_pushlstring(L, value.c_str(), value.size());
5526 lua_settable(L, -3);
5528 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5532 item callbacks and node callbacks
5535 // Retrieves minetest.registered_items[name][callbackname]
5536 // If that is nil or on error, return false and stack is unchanged
5537 // If that is a function, returns true and pushes the
5538 // function onto the stack
5539 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5540 // is tried instead so unknown items can still be manipulated to some degree
5541 static bool get_item_callback(lua_State *L,
5542 const char *name, const char *callbackname)
5544 lua_getglobal(L, "minetest");
5545 lua_getfield(L, -1, "registered_items");
5547 luaL_checktype(L, -1, LUA_TTABLE);
5548 lua_getfield(L, -1, name);
5550 // Should be a table
5551 if(lua_type(L, -1) != LUA_TTABLE)
5553 // Report error and clean up
5554 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5557 // Try minetest.nodedef_default instead
5558 lua_getglobal(L, "minetest");
5559 lua_getfield(L, -1, "nodedef_default");
5561 luaL_checktype(L, -1, LUA_TTABLE);
5563 lua_getfield(L, -1, callbackname);
5565 // Should be a function or nil
5566 if(lua_type(L, -1) == LUA_TFUNCTION)
5570 else if(lua_isnil(L, -1))
5577 errorstream<<"Item \""<<name<<"\" callback \""
5578 <<callbackname<<" is not a function"<<std::endl;
5584 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5585 ServerActiveObject *dropper, v3f pos)
5588 assert(lua_checkstack(L, 20));
5589 StackUnroller stack_unroller(L);
5591 // Push callback function on stack
5592 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5596 LuaItemStack::create(L, item);
5597 objectref_get_or_create(L, dropper);
5598 pushFloatPos(L, pos);
5599 if(lua_pcall(L, 3, 1, 0))
5600 script_error(L, "error: %s", lua_tostring(L, -1));
5601 if(!lua_isnil(L, -1))
5602 item = read_item(L, -1);
5606 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5607 ServerActiveObject *placer, const PointedThing &pointed)
5610 assert(lua_checkstack(L, 20));
5611 StackUnroller stack_unroller(L);
5613 // Push callback function on stack
5614 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5618 LuaItemStack::create(L, item);
5619 objectref_get_or_create(L, placer);
5620 push_pointed_thing(L, pointed);
5621 if(lua_pcall(L, 3, 1, 0))
5622 script_error(L, "error: %s", lua_tostring(L, -1));
5623 if(!lua_isnil(L, -1))
5624 item = read_item(L, -1);
5628 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5629 ServerActiveObject *user, const PointedThing &pointed)
5632 assert(lua_checkstack(L, 20));
5633 StackUnroller stack_unroller(L);
5635 // Push callback function on stack
5636 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5640 LuaItemStack::create(L, item);
5641 objectref_get_or_create(L, user);
5642 push_pointed_thing(L, pointed);
5643 if(lua_pcall(L, 3, 1, 0))
5644 script_error(L, "error: %s", lua_tostring(L, -1));
5645 if(!lua_isnil(L, -1))
5646 item = read_item(L, -1);
5650 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5651 ServerActiveObject *puncher)
5654 assert(lua_checkstack(L, 20));
5655 StackUnroller stack_unroller(L);
5657 INodeDefManager *ndef = get_server(L)->ndef();
5659 // Push callback function on stack
5660 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5665 pushnode(L, node, ndef);
5666 objectref_get_or_create(L, puncher);
5667 if(lua_pcall(L, 3, 0, 0))
5668 script_error(L, "error: %s", lua_tostring(L, -1));
5672 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5673 ServerActiveObject *digger)
5676 assert(lua_checkstack(L, 20));
5677 StackUnroller stack_unroller(L);
5679 INodeDefManager *ndef = get_server(L)->ndef();
5681 // Push callback function on stack
5682 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5687 pushnode(L, node, ndef);
5688 objectref_get_or_create(L, digger);
5689 if(lua_pcall(L, 3, 0, 0))
5690 script_error(L, "error: %s", lua_tostring(L, -1));
5694 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5697 assert(lua_checkstack(L, 20));
5698 StackUnroller stack_unroller(L);
5700 INodeDefManager *ndef = get_server(L)->ndef();
5702 // Push callback function on stack
5703 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5708 if(lua_pcall(L, 1, 0, 0))
5709 script_error(L, "error: %s", lua_tostring(L, -1));
5712 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5715 assert(lua_checkstack(L, 20));
5716 StackUnroller stack_unroller(L);
5718 INodeDefManager *ndef = get_server(L)->ndef();
5720 // Push callback function on stack
5721 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5726 if(lua_pcall(L, 1, 0, 0))
5727 script_error(L, "error: %s", lua_tostring(L, -1));
5730 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5733 assert(lua_checkstack(L, 20));
5734 StackUnroller stack_unroller(L);
5736 INodeDefManager *ndef = get_server(L)->ndef();
5738 // Push callback function on stack
5739 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5744 pushnode(L, node, ndef);
5745 if(lua_pcall(L, 2, 0, 0))
5746 script_error(L, "error: %s", lua_tostring(L, -1));
5749 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5752 assert(lua_checkstack(L, 20));
5753 StackUnroller stack_unroller(L);
5755 INodeDefManager *ndef = get_server(L)->ndef();
5757 // Push callback function on stack
5758 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5763 lua_pushnumber(L,dtime);
5764 if(lua_pcall(L, 2, 1, 0))
5765 script_error(L, "error: %s", lua_tostring(L, -1));
5766 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5772 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5773 const std::string &formname,
5774 const std::map<std::string, std::string> &fields,
5775 ServerActiveObject *sender)
5778 assert(lua_checkstack(L, 20));
5779 StackUnroller stack_unroller(L);
5781 INodeDefManager *ndef = get_server(L)->ndef();
5783 // If node doesn't exist, we don't know what callback to call
5784 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5785 if(node.getContent() == CONTENT_IGNORE)
5788 // Push callback function on stack
5789 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5796 lua_pushstring(L, formname.c_str());
5799 for(std::map<std::string, std::string>::const_iterator
5800 i = fields.begin(); i != fields.end(); i++){
5801 const std::string &name = i->first;
5802 const std::string &value = i->second;
5803 lua_pushstring(L, name.c_str());
5804 lua_pushlstring(L, value.c_str(), value.size());
5805 lua_settable(L, -3);
5808 objectref_get_or_create(L, sender);
5809 if(lua_pcall(L, 4, 0, 0))
5810 script_error(L, "error: %s", lua_tostring(L, -1));
5814 Node metadata inventory callbacks
5817 // Return number of accepted items to be moved
5818 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
5819 const std::string &from_list, int from_index,
5820 const std::string &to_list, int to_index,
5821 int count, ServerActiveObject *player)
5824 assert(lua_checkstack(L, 20));
5825 StackUnroller stack_unroller(L);
5827 INodeDefManager *ndef = get_server(L)->ndef();
5829 // If node doesn't exist, we don't know what callback to call
5830 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5831 if(node.getContent() == CONTENT_IGNORE)
5834 // Push callback function on stack
5835 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5836 "allow_metadata_inventory_move"))
5839 // function(pos, from_list, from_index, to_list, to_index, count, player)
5843 lua_pushstring(L, from_list.c_str());
5845 lua_pushinteger(L, from_index + 1);
5847 lua_pushstring(L, to_list.c_str());
5849 lua_pushinteger(L, to_index + 1);
5851 lua_pushinteger(L, count);
5853 objectref_get_or_create(L, player);
5854 if(lua_pcall(L, 7, 1, 0))
5855 script_error(L, "error: %s", lua_tostring(L, -1));
5856 if(!lua_isnumber(L, -1))
5857 throw LuaError(L, "allow_metadata_inventory_move should return a number");
5858 return luaL_checkinteger(L, -1);
5861 // Return number of accepted items to be put
5862 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
5863 const std::string &listname, int index, ItemStack &stack,
5864 ServerActiveObject *player)
5867 assert(lua_checkstack(L, 20));
5868 StackUnroller stack_unroller(L);
5870 INodeDefManager *ndef = get_server(L)->ndef();
5872 // If node doesn't exist, we don't know what callback to call
5873 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5874 if(node.getContent() == CONTENT_IGNORE)
5877 // Push callback function on stack
5878 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5879 "allow_metadata_inventory_put"))
5882 // Call function(pos, listname, index, stack, player)
5886 lua_pushstring(L, listname.c_str());
5888 lua_pushinteger(L, index + 1);
5890 LuaItemStack::create(L, stack);
5892 objectref_get_or_create(L, player);
5893 if(lua_pcall(L, 5, 1, 0))
5894 script_error(L, "error: %s", lua_tostring(L, -1));
5895 if(!lua_isnumber(L, -1))
5896 throw LuaError(L, "allow_metadata_inventory_put should return a number");
5897 return luaL_checkinteger(L, -1);
5900 // Return number of accepted items to be taken
5901 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
5902 const std::string &listname, int index, ItemStack &stack,
5903 ServerActiveObject *player)
5906 assert(lua_checkstack(L, 20));
5907 StackUnroller stack_unroller(L);
5909 INodeDefManager *ndef = get_server(L)->ndef();
5911 // If node doesn't exist, we don't know what callback to call
5912 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5913 if(node.getContent() == CONTENT_IGNORE)
5916 // Push callback function on stack
5917 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5918 "allow_metadata_inventory_take"))
5921 // Call function(pos, listname, index, count, player)
5925 lua_pushstring(L, listname.c_str());
5927 lua_pushinteger(L, index + 1);
5929 LuaItemStack::create(L, stack);
5931 objectref_get_or_create(L, player);
5932 if(lua_pcall(L, 5, 1, 0))
5933 script_error(L, "error: %s", lua_tostring(L, -1));
5934 if(!lua_isnumber(L, -1))
5935 throw LuaError(L, "allow_metadata_inventory_take should return a number");
5936 return luaL_checkinteger(L, -1);
5939 // Report moved items
5940 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
5941 const std::string &from_list, int from_index,
5942 const std::string &to_list, int to_index,
5943 int count, ServerActiveObject *player)
5946 assert(lua_checkstack(L, 20));
5947 StackUnroller stack_unroller(L);
5949 INodeDefManager *ndef = get_server(L)->ndef();
5951 // If node doesn't exist, we don't know what callback to call
5952 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5953 if(node.getContent() == CONTENT_IGNORE)
5956 // Push callback function on stack
5957 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5958 "on_metadata_inventory_move"))
5961 // function(pos, from_list, from_index, to_list, to_index, count, player)
5965 lua_pushstring(L, from_list.c_str());
5967 lua_pushinteger(L, from_index + 1);
5969 lua_pushstring(L, to_list.c_str());
5971 lua_pushinteger(L, to_index + 1);
5973 lua_pushinteger(L, count);
5975 objectref_get_or_create(L, player);
5976 if(lua_pcall(L, 7, 0, 0))
5977 script_error(L, "error: %s", lua_tostring(L, -1));
5981 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
5982 const std::string &listname, int index, ItemStack &stack,
5983 ServerActiveObject *player)
5986 assert(lua_checkstack(L, 20));
5987 StackUnroller stack_unroller(L);
5989 INodeDefManager *ndef = get_server(L)->ndef();
5991 // If node doesn't exist, we don't know what callback to call
5992 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5993 if(node.getContent() == CONTENT_IGNORE)
5996 // Push callback function on stack
5997 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5998 "on_metadata_inventory_put"))
6001 // Call function(pos, listname, index, stack, player)
6005 lua_pushstring(L, listname.c_str());
6007 lua_pushinteger(L, index + 1);
6009 LuaItemStack::create(L, stack);
6011 objectref_get_or_create(L, player);
6012 if(lua_pcall(L, 5, 0, 0))
6013 script_error(L, "error: %s", lua_tostring(L, -1));
6016 // Report taken items
6017 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6018 const std::string &listname, int index, ItemStack &stack,
6019 ServerActiveObject *player)
6022 assert(lua_checkstack(L, 20));
6023 StackUnroller stack_unroller(L);
6025 INodeDefManager *ndef = get_server(L)->ndef();
6027 // If node doesn't exist, we don't know what callback to call
6028 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6029 if(node.getContent() == CONTENT_IGNORE)
6032 // Push callback function on stack
6033 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6034 "on_metadata_inventory_take"))
6037 // Call function(pos, listname, index, stack, player)
6041 lua_pushstring(L, listname.c_str());
6043 lua_pushinteger(L, index + 1);
6045 LuaItemStack::create(L, stack);
6047 objectref_get_or_create(L, player);
6048 if(lua_pcall(L, 5, 0, 0))
6049 script_error(L, "error: %s", lua_tostring(L, -1));
6053 Detached inventory callbacks
6056 // Retrieves minetest.detached_inventories[name][callbackname]
6057 // If that is nil or on error, return false and stack is unchanged
6058 // If that is a function, returns true and pushes the
6059 // function onto the stack
6060 static bool get_detached_inventory_callback(lua_State *L,
6061 const std::string &name, const char *callbackname)
6063 lua_getglobal(L, "minetest");
6064 lua_getfield(L, -1, "detached_inventories");
6066 luaL_checktype(L, -1, LUA_TTABLE);
6067 lua_getfield(L, -1, name.c_str());
6069 // Should be a table
6070 if(lua_type(L, -1) != LUA_TTABLE)
6072 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6076 lua_getfield(L, -1, callbackname);
6078 // Should be a function or nil
6079 if(lua_type(L, -1) == LUA_TFUNCTION)
6083 else if(lua_isnil(L, -1))
6090 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6091 <<callbackname<<"\" is not a function"<<std::endl;
6097 // Return number of accepted items to be moved
6098 int scriptapi_detached_inventory_allow_move(lua_State *L,
6099 const std::string &name,
6100 const std::string &from_list, int from_index,
6101 const std::string &to_list, int to_index,
6102 int count, ServerActiveObject *player)
6105 assert(lua_checkstack(L, 20));
6106 StackUnroller stack_unroller(L);
6108 // Push callback function on stack
6109 if(!get_detached_inventory_callback(L, name, "allow_move"))
6112 // function(inv, from_list, from_index, to_list, to_index, count, player)
6114 InventoryLocation loc;
6115 loc.setDetached(name);
6116 InvRef::create(L, loc);
6118 lua_pushstring(L, from_list.c_str());
6120 lua_pushinteger(L, from_index + 1);
6122 lua_pushstring(L, to_list.c_str());
6124 lua_pushinteger(L, to_index + 1);
6126 lua_pushinteger(L, count);
6128 objectref_get_or_create(L, player);
6129 if(lua_pcall(L, 7, 1, 0))
6130 script_error(L, "error: %s", lua_tostring(L, -1));
6131 if(!lua_isnumber(L, -1))
6132 throw LuaError(L, "allow_move should return a number");
6133 return luaL_checkinteger(L, -1);
6136 // Return number of accepted items to be put
6137 int scriptapi_detached_inventory_allow_put(lua_State *L,
6138 const std::string &name,
6139 const std::string &listname, int index, ItemStack &stack,
6140 ServerActiveObject *player)
6143 assert(lua_checkstack(L, 20));
6144 StackUnroller stack_unroller(L);
6146 // Push callback function on stack
6147 if(!get_detached_inventory_callback(L, name, "allow_put"))
6148 return stack.count; // All will be accepted
6150 // Call function(inv, listname, index, stack, player)
6152 InventoryLocation loc;
6153 loc.setDetached(name);
6154 InvRef::create(L, loc);
6156 lua_pushstring(L, listname.c_str());
6158 lua_pushinteger(L, index + 1);
6160 LuaItemStack::create(L, stack);
6162 objectref_get_or_create(L, player);
6163 if(lua_pcall(L, 5, 1, 0))
6164 script_error(L, "error: %s", lua_tostring(L, -1));
6165 if(!lua_isnumber(L, -1))
6166 throw LuaError(L, "allow_put should return a number");
6167 return luaL_checkinteger(L, -1);
6170 // Return number of accepted items to be taken
6171 int scriptapi_detached_inventory_allow_take(lua_State *L,
6172 const std::string &name,
6173 const std::string &listname, int index, ItemStack &stack,
6174 ServerActiveObject *player)
6177 assert(lua_checkstack(L, 20));
6178 StackUnroller stack_unroller(L);
6180 // Push callback function on stack
6181 if(!get_detached_inventory_callback(L, name, "allow_take"))
6182 return stack.count; // All will be accepted
6184 // Call function(inv, listname, index, stack, player)
6186 InventoryLocation loc;
6187 loc.setDetached(name);
6188 InvRef::create(L, loc);
6190 lua_pushstring(L, listname.c_str());
6192 lua_pushinteger(L, index + 1);
6194 LuaItemStack::create(L, stack);
6196 objectref_get_or_create(L, player);
6197 if(lua_pcall(L, 5, 1, 0))
6198 script_error(L, "error: %s", lua_tostring(L, -1));
6199 if(!lua_isnumber(L, -1))
6200 throw LuaError(L, "allow_take should return a number");
6201 return luaL_checkinteger(L, -1);
6204 // Report moved items
6205 void scriptapi_detached_inventory_on_move(lua_State *L,
6206 const std::string &name,
6207 const std::string &from_list, int from_index,
6208 const std::string &to_list, int to_index,
6209 int count, ServerActiveObject *player)
6212 assert(lua_checkstack(L, 20));
6213 StackUnroller stack_unroller(L);
6215 // Push callback function on stack
6216 if(!get_detached_inventory_callback(L, name, "on_move"))
6219 // function(inv, from_list, from_index, to_list, to_index, count, player)
6221 InventoryLocation loc;
6222 loc.setDetached(name);
6223 InvRef::create(L, loc);
6225 lua_pushstring(L, from_list.c_str());
6227 lua_pushinteger(L, from_index + 1);
6229 lua_pushstring(L, to_list.c_str());
6231 lua_pushinteger(L, to_index + 1);
6233 lua_pushinteger(L, count);
6235 objectref_get_or_create(L, player);
6236 if(lua_pcall(L, 7, 0, 0))
6237 script_error(L, "error: %s", lua_tostring(L, -1));
6241 void scriptapi_detached_inventory_on_put(lua_State *L,
6242 const std::string &name,
6243 const std::string &listname, int index, ItemStack &stack,
6244 ServerActiveObject *player)
6247 assert(lua_checkstack(L, 20));
6248 StackUnroller stack_unroller(L);
6250 // Push callback function on stack
6251 if(!get_detached_inventory_callback(L, name, "on_put"))
6254 // Call function(inv, listname, index, stack, player)
6256 InventoryLocation loc;
6257 loc.setDetached(name);
6258 InvRef::create(L, loc);
6260 lua_pushstring(L, listname.c_str());
6262 lua_pushinteger(L, index + 1);
6264 LuaItemStack::create(L, stack);
6266 objectref_get_or_create(L, player);
6267 if(lua_pcall(L, 5, 0, 0))
6268 script_error(L, "error: %s", lua_tostring(L, -1));
6271 // Report taken items
6272 void scriptapi_detached_inventory_on_take(lua_State *L,
6273 const std::string &name,
6274 const std::string &listname, int index, ItemStack &stack,
6275 ServerActiveObject *player)
6278 assert(lua_checkstack(L, 20));
6279 StackUnroller stack_unroller(L);
6281 // Push callback function on stack
6282 if(!get_detached_inventory_callback(L, name, "on_take"))
6285 // Call function(inv, listname, index, stack, player)
6287 InventoryLocation loc;
6288 loc.setDetached(name);
6289 InvRef::create(L, loc);
6291 lua_pushstring(L, listname.c_str());
6293 lua_pushinteger(L, index + 1);
6295 LuaItemStack::create(L, stack);
6297 objectref_get_or_create(L, player);
6298 if(lua_pcall(L, 5, 0, 0))
6299 script_error(L, "error: %s", lua_tostring(L, -1));
6306 void scriptapi_environment_step(lua_State *L, float dtime)
6309 assert(lua_checkstack(L, 20));
6310 //infostream<<"scriptapi_environment_step"<<std::endl;
6311 StackUnroller stack_unroller(L);
6313 // Get minetest.registered_globalsteps
6314 lua_getglobal(L, "minetest");
6315 lua_getfield(L, -1, "registered_globalsteps");
6317 lua_pushnumber(L, dtime);
6318 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6321 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6325 assert(lua_checkstack(L, 20));
6326 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6327 StackUnroller stack_unroller(L);
6329 // Get minetest.registered_on_generateds
6330 lua_getglobal(L, "minetest");
6331 lua_getfield(L, -1, "registered_on_generateds");
6333 push_v3s16(L, minp);
6334 push_v3s16(L, maxp);
6335 lua_pushnumber(L, blockseed);
6336 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6343 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6346 assert(lua_checkstack(L, 20));
6347 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6348 <<name<<"\""<<std::endl;
6349 StackUnroller stack_unroller(L);
6351 // Get minetest.registered_entities[name]
6352 lua_getglobal(L, "minetest");
6353 lua_getfield(L, -1, "registered_entities");
6354 luaL_checktype(L, -1, LUA_TTABLE);
6355 lua_pushstring(L, name);
6356 lua_gettable(L, -2);
6357 // Should be a table, which we will use as a prototype
6358 //luaL_checktype(L, -1, LUA_TTABLE);
6359 if(lua_type(L, -1) != LUA_TTABLE){
6360 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6363 int prototype_table = lua_gettop(L);
6364 //dump2(L, "prototype_table");
6366 // Create entity object
6368 int object = lua_gettop(L);
6370 // Set object metatable
6371 lua_pushvalue(L, prototype_table);
6372 lua_setmetatable(L, -2);
6374 // Add object reference
6375 // This should be userdata with metatable ObjectRef
6376 objectref_get(L, id);
6377 luaL_checktype(L, -1, LUA_TUSERDATA);
6378 if(!luaL_checkudata(L, -1, "ObjectRef"))
6379 luaL_typerror(L, -1, "ObjectRef");
6380 lua_setfield(L, -2, "object");
6382 // minetest.luaentities[id] = object
6383 lua_getglobal(L, "minetest");
6384 lua_getfield(L, -1, "luaentities");
6385 luaL_checktype(L, -1, LUA_TTABLE);
6386 lua_pushnumber(L, id); // Push id
6387 lua_pushvalue(L, object); // Copy object to top of stack
6388 lua_settable(L, -3);
6393 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6394 const std::string &staticdata)
6397 assert(lua_checkstack(L, 20));
6398 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6399 StackUnroller stack_unroller(L);
6401 // Get minetest.luaentities[id]
6402 luaentity_get(L, id);
6403 int object = lua_gettop(L);
6405 // Get on_activate function
6406 lua_pushvalue(L, object);
6407 lua_getfield(L, -1, "on_activate");
6408 if(!lua_isnil(L, -1)){
6409 luaL_checktype(L, -1, LUA_TFUNCTION);
6410 lua_pushvalue(L, object); // self
6411 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6412 // Call with 2 arguments, 0 results
6413 if(lua_pcall(L, 2, 0, 0))
6414 script_error(L, "error running function on_activate: %s\n",
6415 lua_tostring(L, -1));
6419 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6422 assert(lua_checkstack(L, 20));
6423 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6425 // Get minetest.luaentities table
6426 lua_getglobal(L, "minetest");
6427 lua_getfield(L, -1, "luaentities");
6428 luaL_checktype(L, -1, LUA_TTABLE);
6429 int objectstable = lua_gettop(L);
6431 // Set luaentities[id] = nil
6432 lua_pushnumber(L, id); // Push id
6434 lua_settable(L, objectstable);
6436 lua_pop(L, 2); // pop luaentities, minetest
6439 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6442 assert(lua_checkstack(L, 20));
6443 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6444 StackUnroller stack_unroller(L);
6446 // Get minetest.luaentities[id]
6447 luaentity_get(L, id);
6448 int object = lua_gettop(L);
6450 // Get get_staticdata function
6451 lua_pushvalue(L, object);
6452 lua_getfield(L, -1, "get_staticdata");
6453 if(lua_isnil(L, -1))
6456 luaL_checktype(L, -1, LUA_TFUNCTION);
6457 lua_pushvalue(L, object); // self
6458 // Call with 1 arguments, 1 results
6459 if(lua_pcall(L, 1, 1, 0))
6460 script_error(L, "error running function get_staticdata: %s\n",
6461 lua_tostring(L, -1));
6464 const char *s = lua_tolstring(L, -1, &len);
6465 return std::string(s, len);
6468 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6469 ObjectProperties *prop)
6472 assert(lua_checkstack(L, 20));
6473 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6474 StackUnroller stack_unroller(L);
6476 // Get minetest.luaentities[id]
6477 luaentity_get(L, id);
6478 //int object = lua_gettop(L);
6480 // Set default values that differ from ObjectProperties defaults
6485 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6487 getboolfield(L, -1, "physical", prop->physical);
6489 getfloatfield(L, -1, "weight", prop->weight);
6491 lua_getfield(L, -1, "collisionbox");
6492 if(lua_istable(L, -1))
6493 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6496 getstringfield(L, -1, "visual", prop->visual);
6498 // Deprecated: read object properties directly
6499 read_object_properties(L, -1, prop);
6501 // Read initial_properties
6502 lua_getfield(L, -1, "initial_properties");
6503 read_object_properties(L, -1, prop);
6507 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6510 assert(lua_checkstack(L, 20));
6511 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6512 StackUnroller stack_unroller(L);
6514 // Get minetest.luaentities[id]
6515 luaentity_get(L, id);
6516 int object = lua_gettop(L);
6517 // State: object is at top of stack
6518 // Get step function
6519 lua_getfield(L, -1, "on_step");
6520 if(lua_isnil(L, -1))
6522 luaL_checktype(L, -1, LUA_TFUNCTION);
6523 lua_pushvalue(L, object); // self
6524 lua_pushnumber(L, dtime); // dtime
6525 // Call with 2 arguments, 0 results
6526 if(lua_pcall(L, 2, 0, 0))
6527 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6530 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6531 // tool_capabilities, direction)
6532 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6533 ServerActiveObject *puncher, float time_from_last_punch,
6534 const ToolCapabilities *toolcap, v3f dir)
6537 assert(lua_checkstack(L, 20));
6538 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6539 StackUnroller stack_unroller(L);
6541 // Get minetest.luaentities[id]
6542 luaentity_get(L, id);
6543 int object = lua_gettop(L);
6544 // State: object is at top of stack
6546 lua_getfield(L, -1, "on_punch");
6547 if(lua_isnil(L, -1))
6549 luaL_checktype(L, -1, LUA_TFUNCTION);
6550 lua_pushvalue(L, object); // self
6551 objectref_get_or_create(L, puncher); // Clicker reference
6552 lua_pushnumber(L, time_from_last_punch);
6553 push_tool_capabilities(L, *toolcap);
6555 // Call with 5 arguments, 0 results
6556 if(lua_pcall(L, 5, 0, 0))
6557 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6560 // Calls entity:on_rightclick(ObjectRef clicker)
6561 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6562 ServerActiveObject *clicker)
6565 assert(lua_checkstack(L, 20));
6566 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6567 StackUnroller stack_unroller(L);
6569 // Get minetest.luaentities[id]
6570 luaentity_get(L, id);
6571 int object = lua_gettop(L);
6572 // State: object is at top of stack
6574 lua_getfield(L, -1, "on_rightclick");
6575 if(lua_isnil(L, -1))
6577 luaL_checktype(L, -1, LUA_TFUNCTION);
6578 lua_pushvalue(L, object); // self
6579 objectref_get_or_create(L, clicker); // Clicker reference
6580 // Call with 2 arguments, 0 results
6581 if(lua_pcall(L, 2, 0, 0))
6582 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));