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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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"
37 #include "luaentity_common.h"
38 #include "content_sao.h" // For LuaEntitySAO
42 #include "main.h" // For g_settings
43 #include "settings.h" // For accessing g_settings
44 #include "nodemetadata.h"
45 #include "mapblock.h" // For getNodeBlockPos
46 #include "content_nodemeta.h"
49 #include "daynightratio.h"
51 static void stackDump(lua_State *L, std::ostream &o)
54 int top = lua_gettop(L);
55 for (i = 1; i <= top; i++) { /* repeat for each level */
56 int t = lua_type(L, i);
59 case LUA_TSTRING: /* strings */
60 o<<"\""<<lua_tostring(L, i)<<"\"";
63 case LUA_TBOOLEAN: /* booleans */
64 o<<(lua_toboolean(L, i) ? "true" : "false");
67 case LUA_TNUMBER: /* numbers */ {
69 snprintf(buf, 10, "%g", lua_tonumber(L, i));
73 default: /* other values */
74 o<<lua_typename(L, t);
83 static void realitycheck(lua_State *L)
85 int top = lua_gettop(L);
87 dstream<<"Stack is over 30:"<<std::endl;
88 stackDump(L, dstream);
89 script_error(L, "Stack is over 30 (reality check)");
99 StackUnroller(lua_State *L):
103 m_original_top = lua_gettop(m_lua); // store stack height
107 lua_settop(m_lua, m_original_top); // restore stack height
116 ModNameStorer(lua_State *L_, const std::string modname):
119 // Store current modname in registry
120 lua_pushstring(L, modname.c_str());
121 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
125 // Clear current modname in registry
127 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
132 Getters for stuff in main tables
135 static Server* get_server(lua_State *L)
137 // Get server from registry
138 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
139 Server *server = (Server*)lua_touserdata(L, -1);
144 static ServerEnvironment* get_env(lua_State *L)
146 // Get environment from registry
147 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
148 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
153 static void objectref_get(lua_State *L, u16 id)
155 // Get minetest.object_refs[i]
156 lua_getglobal(L, "minetest");
157 lua_getfield(L, -1, "object_refs");
158 luaL_checktype(L, -1, LUA_TTABLE);
159 lua_pushnumber(L, id);
161 lua_remove(L, -2); // object_refs
162 lua_remove(L, -2); // minetest
165 static void luaentity_get(lua_State *L, u16 id)
167 // Get minetest.luaentities[i]
168 lua_getglobal(L, "minetest");
169 lua_getfield(L, -1, "luaentities");
170 luaL_checktype(L, -1, LUA_TTABLE);
171 lua_pushnumber(L, id);
173 lua_remove(L, -2); // luaentities
174 lua_remove(L, -2); // minetest
181 static bool getstringfield(lua_State *L, int table,
182 const char *fieldname, std::string &result)
184 lua_getfield(L, table, fieldname);
186 if(lua_isstring(L, -1)){
188 const char *ptr = lua_tolstring(L, -1, &len);
189 result.assign(ptr, len);
196 static bool getintfield(lua_State *L, int table,
197 const char *fieldname, int &result)
199 lua_getfield(L, table, fieldname);
201 if(lua_isnumber(L, -1)){
202 result = lua_tonumber(L, -1);
209 static bool getfloatfield(lua_State *L, int table,
210 const char *fieldname, float &result)
212 lua_getfield(L, table, fieldname);
214 if(lua_isnumber(L, -1)){
215 result = lua_tonumber(L, -1);
222 static bool getboolfield(lua_State *L, int table,
223 const char *fieldname, bool &result)
225 lua_getfield(L, table, fieldname);
227 if(lua_isboolean(L, -1)){
228 result = lua_toboolean(L, -1);
235 static std::string checkstringfield(lua_State *L, int table,
236 const char *fieldname)
238 lua_getfield(L, table, fieldname);
239 std::string s = luaL_checkstring(L, -1);
244 static std::string getstringfield_default(lua_State *L, int table,
245 const char *fieldname, const std::string &default_)
247 std::string result = default_;
248 getstringfield(L, table, fieldname, result);
252 static int getintfield_default(lua_State *L, int table,
253 const char *fieldname, int default_)
255 int result = default_;
256 getintfield(L, table, fieldname, result);
260 static float getfloatfield_default(lua_State *L, int table,
261 const char *fieldname, float default_)
263 float result = default_;
264 getfloatfield(L, table, fieldname, result);
268 static bool getboolfield_default(lua_State *L, int table,
269 const char *fieldname, bool default_)
271 bool result = default_;
272 getboolfield(L, table, fieldname, result);
282 static bool string_to_enum(const EnumString *spec, int &result,
283 const std::string &str)
285 const EnumString *esp = spec;
287 if(str == std::string(esp->str)){
296 /*static bool enum_to_string(const EnumString *spec, std::string &result,
299 const EnumString *esp = spec;
310 static int getenumfield(lua_State *L, int table,
311 const char *fieldname, const EnumString *spec, int default_)
313 int result = default_;
314 string_to_enum(spec, result,
315 getstringfield_default(L, table, fieldname, ""));
319 static void setintfield(lua_State *L, int table,
320 const char *fieldname, int value)
322 lua_pushinteger(L, value);
325 lua_setfield(L, table, fieldname);
328 static void setfloatfield(lua_State *L, int table,
329 const char *fieldname, float value)
331 lua_pushnumber(L, value);
334 lua_setfield(L, table, fieldname);
337 static void setboolfield(lua_State *L, int table,
338 const char *fieldname, bool value)
340 lua_pushboolean(L, value);
343 lua_setfield(L, table, fieldname);
346 static void warn_if_field_exists(lua_State *L, int table,
347 const char *fieldname, const std::string &message)
349 lua_getfield(L, table, fieldname);
350 if(!lua_isnil(L, -1)){
351 infostream<<script_get_backtrace(L)<<std::endl;
352 infostream<<"WARNING: field \""<<fieldname<<"\": "
353 <<message<<std::endl;
359 EnumString definitions
362 struct EnumString es_ItemType[] =
366 {ITEM_CRAFT, "craft"},
371 struct EnumString es_DrawType[] =
373 {NDT_NORMAL, "normal"},
374 {NDT_AIRLIKE, "airlike"},
375 {NDT_LIQUID, "liquid"},
376 {NDT_FLOWINGLIQUID, "flowingliquid"},
377 {NDT_GLASSLIKE, "glasslike"},
378 {NDT_ALLFACES, "allfaces"},
379 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
380 {NDT_TORCHLIKE, "torchlike"},
381 {NDT_SIGNLIKE, "signlike"},
382 {NDT_PLANTLIKE, "plantlike"},
383 {NDT_FENCELIKE, "fencelike"},
384 {NDT_RAILLIKE, "raillike"},
388 struct EnumString es_ContentParamType[] =
391 {CPT_LIGHT, "light"},
395 struct EnumString es_ContentParamType2[] =
399 {CPT2_FLOWINGLIQUID, "flowingliquid"},
400 {CPT2_FACEDIR, "facedir"},
401 {CPT2_WALLMOUNTED, "wallmounted"},
405 struct EnumString es_LiquidType[] =
407 {LIQUID_NONE, "none"},
408 {LIQUID_FLOWING, "flowing"},
409 {LIQUID_SOURCE, "source"},
413 struct EnumString es_NodeBoxType[] =
415 {NODEBOX_REGULAR, "regular"},
416 {NODEBOX_FIXED, "fixed"},
417 {NODEBOX_WALLMOUNTED, "wallmounted"},
422 C struct <-> Lua table converter functions
425 static void push_v3f(lua_State *L, v3f p)
428 lua_pushnumber(L, p.X);
429 lua_setfield(L, -2, "x");
430 lua_pushnumber(L, p.Y);
431 lua_setfield(L, -2, "y");
432 lua_pushnumber(L, p.Z);
433 lua_setfield(L, -2, "z");
436 static v2s16 read_v2s16(lua_State *L, int index)
439 luaL_checktype(L, index, LUA_TTABLE);
440 lua_getfield(L, index, "x");
441 p.X = lua_tonumber(L, -1);
443 lua_getfield(L, index, "y");
444 p.Y = lua_tonumber(L, -1);
449 static v2f read_v2f(lua_State *L, int index)
452 luaL_checktype(L, index, LUA_TTABLE);
453 lua_getfield(L, index, "x");
454 p.X = lua_tonumber(L, -1);
456 lua_getfield(L, index, "y");
457 p.Y = lua_tonumber(L, -1);
462 static v3f read_v3f(lua_State *L, int index)
465 luaL_checktype(L, index, LUA_TTABLE);
466 lua_getfield(L, index, "x");
467 pos.X = lua_tonumber(L, -1);
469 lua_getfield(L, index, "y");
470 pos.Y = lua_tonumber(L, -1);
472 lua_getfield(L, index, "z");
473 pos.Z = lua_tonumber(L, -1);
478 static v3f check_v3f(lua_State *L, int index)
481 luaL_checktype(L, index, LUA_TTABLE);
482 lua_getfield(L, index, "x");
483 pos.X = luaL_checknumber(L, -1);
485 lua_getfield(L, index, "y");
486 pos.Y = luaL_checknumber(L, -1);
488 lua_getfield(L, index, "z");
489 pos.Z = luaL_checknumber(L, -1);
494 static void pushFloatPos(lua_State *L, v3f p)
500 static v3f checkFloatPos(lua_State *L, int index)
502 return check_v3f(L, index) * BS;
505 static void push_v3s16(lua_State *L, v3s16 p)
508 lua_pushnumber(L, p.X);
509 lua_setfield(L, -2, "x");
510 lua_pushnumber(L, p.Y);
511 lua_setfield(L, -2, "y");
512 lua_pushnumber(L, p.Z);
513 lua_setfield(L, -2, "z");
516 static v3s16 read_v3s16(lua_State *L, int index)
518 // Correct rounding at <0
519 v3f pf = read_v3f(L, index);
520 return floatToInt(pf, 1.0);
523 static v3s16 check_v3s16(lua_State *L, int index)
525 // Correct rounding at <0
526 v3f pf = check_v3f(L, index);
527 return floatToInt(pf, 1.0);
530 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
533 lua_pushstring(L, ndef->get(n).name.c_str());
534 lua_setfield(L, -2, "name");
535 lua_pushnumber(L, n.getParam1());
536 lua_setfield(L, -2, "param1");
537 lua_pushnumber(L, n.getParam2());
538 lua_setfield(L, -2, "param2");
541 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
543 lua_getfield(L, index, "name");
544 const char *name = luaL_checkstring(L, -1);
547 lua_getfield(L, index, "param1");
551 param1 = lua_tonumber(L, -1);
554 lua_getfield(L, index, "param2");
558 param2 = lua_tonumber(L, -1);
560 return MapNode(ndef, name, param1, param2);
563 static video::SColor readARGB8(lua_State *L, int index)
566 luaL_checktype(L, index, LUA_TTABLE);
567 lua_getfield(L, index, "a");
568 if(lua_isnumber(L, -1))
569 color.setAlpha(lua_tonumber(L, -1));
571 lua_getfield(L, index, "r");
572 color.setRed(lua_tonumber(L, -1));
574 lua_getfield(L, index, "g");
575 color.setGreen(lua_tonumber(L, -1));
577 lua_getfield(L, index, "b");
578 color.setBlue(lua_tonumber(L, -1));
583 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
585 core::aabbox3d<f32> box;
586 if(lua_istable(L, -1)){
587 lua_rawgeti(L, -1, 1);
588 box.MinEdge.X = lua_tonumber(L, -1) * scale;
590 lua_rawgeti(L, -1, 2);
591 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
593 lua_rawgeti(L, -1, 3);
594 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
596 lua_rawgeti(L, -1, 4);
597 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
599 lua_rawgeti(L, -1, 5);
600 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
602 lua_rawgeti(L, -1, 6);
603 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
614 static MaterialProperties read_material_properties(
615 lua_State *L, int table)
617 MaterialProperties prop;
618 prop.diggability = (Diggability)getenumfield(L, -1, "diggability",
619 es_Diggability, DIGGABLE_NORMAL);
620 getfloatfield(L, -1, "constant_time", prop.constant_time);
621 getfloatfield(L, -1, "weight", prop.weight);
622 getfloatfield(L, -1, "crackiness", prop.crackiness);
623 getfloatfield(L, -1, "crumbliness", prop.crumbliness);
624 getfloatfield(L, -1, "cuttability", prop.cuttability);
625 getfloatfield(L, -1, "flammability", prop.flammability);
633 static void read_groups(lua_State *L, int index,
634 std::map<std::string, int> &result)
640 while(lua_next(L, index) != 0){
641 // key at index -2 and value at index -1
642 std::string name = luaL_checkstring(L, -2);
643 int rating = luaL_checkinteger(L, -1);
644 result[name] = rating;
645 // removes value, keeps key for next iteration
654 static ToolCapabilities read_tool_capabilities(
655 lua_State *L, int table)
657 ToolCapabilities toolcap;
658 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
659 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
660 lua_getfield(L, table, "groupcaps");
661 if(lua_istable(L, -1)){
662 int table_groupcaps = lua_gettop(L);
664 while(lua_next(L, table_groupcaps) != 0){
665 // key at index -2 and value at index -1
666 std::string groupname = luaL_checkstring(L, -2);
667 if(lua_istable(L, -1)){
668 int table_groupcap = lua_gettop(L);
669 // This will be created
670 ToolGroupCap groupcap;
671 // Read simple parameters
672 getfloatfield(L, table_groupcap, "maxwear", groupcap.maxwear);
673 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
674 // Read "times" table
675 lua_getfield(L, table_groupcap, "times");
676 if(lua_istable(L, -1)){
677 int table_times = lua_gettop(L);
679 while(lua_next(L, table_times) != 0){
680 // key at index -2 and value at index -1
681 int rating = luaL_checkinteger(L, -2);
682 float time = luaL_checknumber(L, -1);
683 groupcap.times[rating] = time;
684 // removes value, keeps key for next iteration
689 // Insert groupcap into toolcap
690 toolcap.groupcaps[groupname] = groupcap;
692 // removes value, keeps key for next iteration
700 static void set_tool_capabilities(lua_State *L, int table,
701 const ToolCapabilities &toolcap)
703 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
704 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
705 // Create groupcaps table
708 for(std::map<std::string, ToolGroupCap>::const_iterator
709 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
710 // Create groupcap table
712 const std::string &name = i->first;
713 const ToolGroupCap &groupcap = i->second;
714 // Create subtable "times"
716 for(std::map<int, float>::const_iterator
717 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
718 int rating = i->first;
719 float time = i->second;
720 lua_pushinteger(L, rating);
721 lua_pushnumber(L, time);
724 // Set subtable "times"
725 lua_setfield(L, -2, "times");
726 // Set simple parameters
727 setfloatfield(L, -1, "maxwear", groupcap.maxwear);
728 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
729 // Insert groupcap table into groupcaps table
730 lua_setfield(L, -2, name.c_str());
732 // Set groupcaps table
733 lua_setfield(L, -2, "groupcaps");
736 static void push_tool_capabilities(lua_State *L,
737 const ToolCapabilities &prop)
740 set_tool_capabilities(L, -1, prop);
747 static void set_dig_params(lua_State *L, int table,
748 const DigParams ¶ms)
750 setboolfield(L, table, "diggable", params.diggable);
751 setfloatfield(L, table, "time", params.time);
752 setintfield(L, table, "wear", params.wear);
755 static void push_dig_params(lua_State *L,
756 const DigParams ¶ms)
759 set_dig_params(L, -1, params);
766 static void set_hit_params(lua_State *L, int table,
767 const HitParams ¶ms)
769 setintfield(L, table, "hp", params.hp);
770 setintfield(L, table, "wear", params.wear);
773 static void push_hit_params(lua_State *L,
774 const HitParams ¶ms)
777 set_hit_params(L, -1, params);
784 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
787 if(pointed.type == POINTEDTHING_NODE)
789 lua_pushstring(L, "node");
790 lua_setfield(L, -2, "type");
791 push_v3s16(L, pointed.node_undersurface);
792 lua_setfield(L, -2, "under");
793 push_v3s16(L, pointed.node_abovesurface);
794 lua_setfield(L, -2, "above");
796 else if(pointed.type == POINTEDTHING_OBJECT)
798 lua_pushstring(L, "object");
799 lua_setfield(L, -2, "type");
800 objectref_get(L, pointed.object_id);
801 lua_setfield(L, -2, "ref");
805 lua_pushstring(L, "nothing");
806 lua_setfield(L, -2, "type");
814 static ItemDefinition read_item_definition(lua_State *L, int index)
817 index = lua_gettop(L) + 1 + index;
819 // Read the item definition
822 def.type = (ItemType)getenumfield(L, index, "type",
823 es_ItemType, ITEM_NONE);
824 getstringfield(L, index, "name", def.name);
825 getstringfield(L, index, "description", def.description);
826 getstringfield(L, index, "inventory_image", def.inventory_image);
827 getstringfield(L, index, "wield_image", def.wield_image);
829 lua_getfield(L, index, "wield_scale");
830 if(lua_istable(L, -1)){
831 def.wield_scale = check_v3f(L, -1);
835 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
836 if(def.stack_max == 0)
839 lua_getfield(L, index, "on_use");
840 def.usable = lua_isfunction(L, -1);
843 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
845 warn_if_field_exists(L, index, "tool_digging_properties",
846 "deprecated: use tool_capabilities");
848 lua_getfield(L, index, "tool_capabilities");
849 if(lua_istable(L, -1)){
850 def.tool_capabilities = new ToolCapabilities(
851 read_tool_capabilities(L, -1));
854 // If name is "" (hand), ensure there are ToolCapabilities
855 // because it will be looked up there whenever any other item has
856 // no ToolCapabilities
857 if(def.name == "" && def.tool_capabilities == NULL){
858 def.tool_capabilities = new ToolCapabilities();
861 lua_getfield(L, index, "groups");
862 read_groups(L, -1, def.groups);
872 static ContentFeatures read_content_features(lua_State *L, int index)
875 index = lua_gettop(L) + 1 + index;
879 getstringfield(L, index, "name", f.name);
882 lua_getfield(L, index, "groups");
883 read_groups(L, -1, f.groups);
886 /* Visual definition */
888 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
890 getfloatfield(L, index, "visual_scale", f.visual_scale);
892 lua_getfield(L, index, "tile_images");
893 if(lua_istable(L, -1)){
894 int table = lua_gettop(L);
897 while(lua_next(L, table) != 0){
898 // key at index -2 and value at index -1
899 if(lua_isstring(L, -1))
900 f.tname_tiles[i] = lua_tostring(L, -1);
902 f.tname_tiles[i] = "";
903 // removes value, keeps key for next iteration
911 // Copy last value to all remaining textures
913 std::string lastname = f.tname_tiles[i-1];
915 f.tname_tiles[i] = lastname;
922 lua_getfield(L, index, "special_materials");
923 if(lua_istable(L, -1)){
924 int table = lua_gettop(L);
927 while(lua_next(L, table) != 0){
928 // key at index -2 and value at index -1
929 int smtable = lua_gettop(L);
930 std::string tname = getstringfield_default(
931 L, smtable, "image", "");
932 bool backface_culling = getboolfield_default(
933 L, smtable, "backface_culling", true);
934 MaterialSpec mspec(tname, backface_culling);
935 f.mspec_special[i] = mspec;
936 // removes value, keeps key for next iteration
947 f.alpha = getintfield_default(L, index, "alpha", 255);
951 lua_getfield(L, index, "post_effect_color");
952 if(!lua_isnil(L, -1))
953 f.post_effect_color = readARGB8(L, -1);
956 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
957 es_ContentParamType, CPT_NONE);
958 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
959 es_ContentParamType2, CPT2_NONE);
961 // Warn about some deprecated fields
962 warn_if_field_exists(L, index, "wall_mounted",
963 "deprecated: use paramtype2 = 'wallmounted'");
964 warn_if_field_exists(L, index, "light_propagates",
965 "deprecated: determined from paramtype");
966 warn_if_field_exists(L, index, "dug_item",
967 "deprecated: use 'drop' field");
968 warn_if_field_exists(L, index, "extra_dug_item",
969 "deprecated: use 'drop' field");
970 warn_if_field_exists(L, index, "extra_dug_item_rarity",
971 "deprecated: use 'drop' field");
973 // True for all ground-like things like stone and mud, false for eg. trees
974 getboolfield(L, index, "is_ground_content", f.is_ground_content);
975 f.light_propagates = (f.param_type == CPT_LIGHT);
976 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
977 // This is used for collision detection.
978 // Also for general solidness queries.
979 getboolfield(L, index, "walkable", f.walkable);
980 // Player can point to these
981 getboolfield(L, index, "pointable", f.pointable);
982 // Player can dig these
983 getboolfield(L, index, "diggable", f.diggable);
984 // Player can climb these
985 getboolfield(L, index, "climbable", f.climbable);
986 // Player can build on these
987 getboolfield(L, index, "buildable_to", f.buildable_to);
988 // Metadata name of node (eg. "furnace")
989 getstringfield(L, index, "metadata_name", f.metadata_name);
990 // Whether the node is non-liquid, source liquid or flowing liquid
991 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
992 es_LiquidType, LIQUID_NONE);
993 // If the content is liquid, this is the flowing version of the liquid.
994 getstringfield(L, index, "liquid_alternative_flowing",
995 f.liquid_alternative_flowing);
996 // If the content is liquid, this is the source version of the liquid.
997 getstringfield(L, index, "liquid_alternative_source",
998 f.liquid_alternative_source);
999 // Viscosity for fluid flow, ranging from 1 to 7, with
1000 // 1 giving almost instantaneous propagation and 7 being
1001 // the slowest possible
1002 f.liquid_viscosity = getintfield_default(L, index,
1003 "liquid_viscosity", f.liquid_viscosity);
1004 // Amount of light the node emits
1005 f.light_source = getintfield_default(L, index,
1006 "light_source", f.light_source);
1007 f.damage_per_second = getintfield_default(L, index,
1008 "damage_per_second", f.damage_per_second);
1010 lua_getfield(L, index, "selection_box");
1011 if(lua_istable(L, -1)){
1012 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1013 es_NodeBoxType, NODEBOX_REGULAR);
1015 lua_getfield(L, -1, "fixed");
1016 if(lua_istable(L, -1))
1017 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1020 lua_getfield(L, -1, "wall_top");
1021 if(lua_istable(L, -1))
1022 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1025 lua_getfield(L, -1, "wall_bottom");
1026 if(lua_istable(L, -1))
1027 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1030 lua_getfield(L, -1, "wall_side");
1031 if(lua_istable(L, -1))
1032 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1037 // Set to true if paramtype used to be 'facedir_simple'
1038 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1039 // Set to true if wall_mounted used to be set to true
1040 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1049 static ItemStack read_item(lua_State *L, int index);
1051 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1052 lua_State *L, int tableindex, int forcesize=-1)
1054 dstream<<"inventory_set_list_from_lua\n";
1056 tableindex = lua_gettop(L) + 1 + tableindex;
1057 // If nil, delete list
1058 if(lua_isnil(L, tableindex)){
1059 inv->deleteList(name);
1062 // Otherwise set list
1063 std::vector<ItemStack> items;
1064 luaL_checktype(L, tableindex, LUA_TTABLE);
1066 while(lua_next(L, tableindex) != 0){
1067 // key at index -2 and value at index -1
1068 items.push_back(read_item(L, -1));
1069 // removes value, keeps key for next iteration
1072 int listsize = (forcesize != -1) ? forcesize : items.size();
1073 InventoryList *invlist = inv->addList(name, listsize);
1075 for(std::vector<ItemStack>::const_iterator
1076 i = items.begin(); i != items.end(); i++){
1077 if(forcesize != -1 && index == forcesize)
1079 invlist->changeItem(index, *i);
1082 while(forcesize != -1 && index < forcesize){
1083 invlist->deleteItem(index);
1086 dstream<<"inventory_set_list_from_lua done\n";
1089 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1092 InventoryList *invlist = inv->getList(name);
1093 if(invlist == NULL){
1097 // Get the table insert function
1098 lua_getglobal(L, "table");
1099 lua_getfield(L, -1, "insert");
1100 int table_insert = lua_gettop(L);
1101 // Create and fill table
1103 int table = lua_gettop(L);
1104 for(u32 i=0; i<invlist->getSize(); i++){
1105 ItemStack item = invlist->getItem(i);
1106 lua_pushvalue(L, table_insert);
1107 lua_pushvalue(L, table);
1108 lua_pushstring(L, item.getItemString().c_str());
1109 if(lua_pcall(L, 2, 0, 0))
1110 script_error(L, "error: %s", lua_tostring(L, -1));
1115 Helpful macros for userdata classes
1118 #define method(class, name) {#name, class::l_##name}
1129 static const char className[];
1130 static const luaL_reg methods[];
1132 // Exported functions
1134 // garbage collector
1135 static int gc_object(lua_State *L)
1137 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1142 // is_empty(self) -> true/false
1143 static int l_is_empty(lua_State *L)
1145 LuaItemStack *o = checkobject(L, 1);
1146 ItemStack &item = o->m_stack;
1147 lua_pushboolean(L, item.empty());
1151 // get_name(self) -> string
1152 static int l_get_name(lua_State *L)
1154 LuaItemStack *o = checkobject(L, 1);
1155 ItemStack &item = o->m_stack;
1156 lua_pushstring(L, item.name.c_str());
1160 // get_count(self) -> number
1161 static int l_get_count(lua_State *L)
1163 LuaItemStack *o = checkobject(L, 1);
1164 ItemStack &item = o->m_stack;
1165 lua_pushinteger(L, item.count);
1169 // get_wear(self) -> number
1170 static int l_get_wear(lua_State *L)
1172 LuaItemStack *o = checkobject(L, 1);
1173 ItemStack &item = o->m_stack;
1174 lua_pushinteger(L, item.wear);
1178 // get_metadata(self) -> string
1179 static int l_get_metadata(lua_State *L)
1181 LuaItemStack *o = checkobject(L, 1);
1182 ItemStack &item = o->m_stack;
1183 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1187 // clear(self) -> true
1188 static int l_clear(lua_State *L)
1190 LuaItemStack *o = checkobject(L, 1);
1192 lua_pushboolean(L, true);
1196 // replace(self, itemstack or itemstring or table or nil) -> true
1197 static int l_replace(lua_State *L)
1199 LuaItemStack *o = checkobject(L, 1);
1200 o->m_stack = read_item(L, 2);
1201 lua_pushboolean(L, true);
1205 // to_string(self) -> string
1206 static int l_to_string(lua_State *L)
1208 LuaItemStack *o = checkobject(L, 1);
1209 std::string itemstring = o->m_stack.getItemString();
1210 lua_pushstring(L, itemstring.c_str());
1214 // to_table(self) -> table or nil
1215 static int l_to_table(lua_State *L)
1217 LuaItemStack *o = checkobject(L, 1);
1218 const ItemStack &item = o->m_stack;
1226 lua_pushstring(L, item.name.c_str());
1227 lua_setfield(L, -2, "name");
1228 lua_pushinteger(L, item.count);
1229 lua_setfield(L, -2, "count");
1230 lua_pushinteger(L, item.wear);
1231 lua_setfield(L, -2, "wear");
1232 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1233 lua_setfield(L, -2, "metadata");
1238 // get_stack_max(self) -> number
1239 static int l_get_stack_max(lua_State *L)
1241 LuaItemStack *o = checkobject(L, 1);
1242 ItemStack &item = o->m_stack;
1243 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1247 // get_free_space(self) -> number
1248 static int l_get_free_space(lua_State *L)
1250 LuaItemStack *o = checkobject(L, 1);
1251 ItemStack &item = o->m_stack;
1252 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1256 // is_known(self) -> true/false
1257 // Checks if the item is defined.
1258 static int l_is_known(lua_State *L)
1260 LuaItemStack *o = checkobject(L, 1);
1261 ItemStack &item = o->m_stack;
1262 bool is_known = item.isKnown(get_server(L)->idef());
1263 lua_pushboolean(L, is_known);
1267 // get_definition(self) -> table
1268 // Returns the item definition table from minetest.registered_items,
1269 // or a fallback one (name="unknown")
1270 static int l_get_definition(lua_State *L)
1272 LuaItemStack *o = checkobject(L, 1);
1273 ItemStack &item = o->m_stack;
1275 // Get minetest.registered_items[name]
1276 lua_getglobal(L, "minetest");
1277 lua_getfield(L, -1, "registered_items");
1278 luaL_checktype(L, -1, LUA_TTABLE);
1279 lua_getfield(L, -1, item.name.c_str());
1280 if(lua_isnil(L, -1))
1283 lua_getfield(L, -1, "unknown");
1288 // get_tool_capabilities(self) -> table
1289 // Returns the effective tool digging properties.
1290 // Returns those of the hand ("") if this item has none associated.
1291 static int l_get_tool_capabilities(lua_State *L)
1293 LuaItemStack *o = checkobject(L, 1);
1294 ItemStack &item = o->m_stack;
1295 const ToolCapabilities &prop =
1296 item.getToolCapabilities(get_server(L)->idef());
1297 push_tool_capabilities(L, prop);
1301 // add_wear(self, amount) -> true/false
1302 // The range for "amount" is [0,65535]. Wear is only added if the item
1303 // is a tool. Adding wear might destroy the item.
1304 // Returns true if the item is (or was) a tool.
1305 static int l_add_wear(lua_State *L)
1307 LuaItemStack *o = checkobject(L, 1);
1308 ItemStack &item = o->m_stack;
1309 int amount = lua_tointeger(L, 2);
1310 bool result = item.addWear(amount, get_server(L)->idef());
1311 lua_pushboolean(L, result);
1315 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1316 // Returns leftover item stack
1317 static int l_add_item(lua_State *L)
1319 LuaItemStack *o = checkobject(L, 1);
1320 ItemStack &item = o->m_stack;
1321 ItemStack newitem = read_item(L, 2);
1322 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1323 create(L, leftover);
1327 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1328 // First return value is true iff the new item fits fully into the stack
1329 // Second return value is the would-be-left-over item stack
1330 static int l_item_fits(lua_State *L)
1332 LuaItemStack *o = checkobject(L, 1);
1333 ItemStack &item = o->m_stack;
1334 ItemStack newitem = read_item(L, 2);
1336 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1337 lua_pushboolean(L, fits); // first return value
1338 create(L, restitem); // second return value
1342 // take_item(self, takecount=1) -> itemstack
1343 static int l_take_item(lua_State *L)
1345 LuaItemStack *o = checkobject(L, 1);
1346 ItemStack &item = o->m_stack;
1348 if(!lua_isnone(L, 2))
1349 takecount = lua_tointeger(L, 2);
1350 ItemStack taken = item.takeItem(takecount);
1355 // peek_item(self, peekcount=1) -> itemstack
1356 static int l_peek_item(lua_State *L)
1358 LuaItemStack *o = checkobject(L, 1);
1359 ItemStack &item = o->m_stack;
1361 if(!lua_isnone(L, 2))
1362 peekcount = lua_tointeger(L, 2);
1363 ItemStack peekaboo = item.peekItem(peekcount);
1364 create(L, peekaboo);
1369 LuaItemStack(const ItemStack &item):
1378 const ItemStack& getItem() const
1382 ItemStack& getItem()
1387 // LuaItemStack(itemstack or itemstring or table or nil)
1388 // Creates an LuaItemStack and leaves it on top of stack
1389 static int create_object(lua_State *L)
1391 ItemStack item = read_item(L, 1);
1392 LuaItemStack *o = new LuaItemStack(item);
1393 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1394 luaL_getmetatable(L, className);
1395 lua_setmetatable(L, -2);
1398 // Not callable from Lua
1399 static int create(lua_State *L, const ItemStack &item)
1401 LuaItemStack *o = new LuaItemStack(item);
1402 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1403 luaL_getmetatable(L, className);
1404 lua_setmetatable(L, -2);
1408 static LuaItemStack* checkobject(lua_State *L, int narg)
1410 luaL_checktype(L, narg, LUA_TUSERDATA);
1411 void *ud = luaL_checkudata(L, narg, className);
1412 if(!ud) luaL_typerror(L, narg, className);
1413 return *(LuaItemStack**)ud; // unbox pointer
1416 static void Register(lua_State *L)
1419 int methodtable = lua_gettop(L);
1420 luaL_newmetatable(L, className);
1421 int metatable = lua_gettop(L);
1423 lua_pushliteral(L, "__metatable");
1424 lua_pushvalue(L, methodtable);
1425 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1427 lua_pushliteral(L, "__index");
1428 lua_pushvalue(L, methodtable);
1429 lua_settable(L, metatable);
1431 lua_pushliteral(L, "__gc");
1432 lua_pushcfunction(L, gc_object);
1433 lua_settable(L, metatable);
1435 lua_pop(L, 1); // drop metatable
1437 luaL_openlib(L, 0, methods, 0); // fill methodtable
1438 lua_pop(L, 1); // drop methodtable
1440 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1441 lua_register(L, className, create_object);
1444 const char LuaItemStack::className[] = "ItemStack";
1445 const luaL_reg LuaItemStack::methods[] = {
1446 method(LuaItemStack, is_empty),
1447 method(LuaItemStack, get_name),
1448 method(LuaItemStack, get_count),
1449 method(LuaItemStack, get_wear),
1450 method(LuaItemStack, get_metadata),
1451 method(LuaItemStack, clear),
1452 method(LuaItemStack, replace),
1453 method(LuaItemStack, to_string),
1454 method(LuaItemStack, to_table),
1455 method(LuaItemStack, get_stack_max),
1456 method(LuaItemStack, get_free_space),
1457 method(LuaItemStack, is_known),
1458 method(LuaItemStack, get_definition),
1459 method(LuaItemStack, get_tool_capabilities),
1460 method(LuaItemStack, add_wear),
1461 method(LuaItemStack, add_item),
1462 method(LuaItemStack, item_fits),
1463 method(LuaItemStack, take_item),
1464 method(LuaItemStack, peek_item),
1468 static ItemStack read_item(lua_State *L, int index)
1471 index = lua_gettop(L) + 1 + index;
1473 if(lua_isnil(L, index))
1477 else if(lua_isuserdata(L, index))
1479 // Convert from LuaItemStack
1480 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1481 return o->getItem();
1483 else if(lua_isstring(L, index))
1485 // Convert from itemstring
1486 std::string itemstring = lua_tostring(L, index);
1487 IItemDefManager *idef = get_server(L)->idef();
1491 item.deSerialize(itemstring, idef);
1494 catch(SerializationError &e)
1496 infostream<<"WARNING: unable to create item from itemstring"
1497 <<": "<<itemstring<<std::endl;
1501 else if(lua_istable(L, index))
1503 // Convert from table
1504 IItemDefManager *idef = get_server(L)->idef();
1505 std::string name = getstringfield_default(L, index, "name", "");
1506 int count = getintfield_default(L, index, "count", 1);
1507 int wear = getintfield_default(L, index, "wear", 0);
1508 std::string metadata = getstringfield_default(L, index, "metadata", "");
1509 return ItemStack(name, count, wear, metadata, idef);
1513 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1524 InventoryLocation m_loc;
1526 static const char className[];
1527 static const luaL_reg methods[];
1529 static InvRef *checkobject(lua_State *L, int narg)
1531 luaL_checktype(L, narg, LUA_TUSERDATA);
1532 void *ud = luaL_checkudata(L, narg, className);
1533 if(!ud) luaL_typerror(L, narg, className);
1534 return *(InvRef**)ud; // unbox pointer
1537 static Inventory* getinv(lua_State *L, InvRef *ref)
1539 return get_server(L)->getInventory(ref->m_loc);
1542 static InventoryList* getlist(lua_State *L, InvRef *ref,
1543 const char *listname)
1545 Inventory *inv = getinv(L, ref);
1548 return inv->getList(listname);
1551 static void reportInventoryChange(lua_State *L, InvRef *ref)
1553 // Inform other things that the inventory has changed
1554 get_server(L)->setInventoryModified(ref->m_loc);
1557 // Exported functions
1559 // garbage collector
1560 static int gc_object(lua_State *L) {
1561 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1566 // get_size(self, listname)
1567 static int l_get_size(lua_State *L)
1569 InvRef *ref = checkobject(L, 1);
1570 const char *listname = luaL_checkstring(L, 2);
1571 InventoryList *list = getlist(L, ref, listname);
1573 lua_pushinteger(L, list->getSize());
1575 lua_pushinteger(L, 0);
1580 // set_size(self, listname, size)
1581 static int l_set_size(lua_State *L)
1583 InvRef *ref = checkobject(L, 1);
1584 const char *listname = luaL_checkstring(L, 2);
1585 int newsize = luaL_checknumber(L, 3);
1586 Inventory *inv = getinv(L, ref);
1588 inv->deleteList(listname);
1589 reportInventoryChange(L, ref);
1592 InventoryList *list = inv->getList(listname);
1594 list->setSize(newsize);
1596 list = inv->addList(listname, newsize);
1598 reportInventoryChange(L, ref);
1602 // get_stack(self, listname, i) -> itemstack
1603 static int l_get_stack(lua_State *L)
1605 InvRef *ref = checkobject(L, 1);
1606 const char *listname = luaL_checkstring(L, 2);
1607 int i = luaL_checknumber(L, 3) - 1;
1608 InventoryList *list = getlist(L, ref, listname);
1610 if(list != NULL && i >= 0 && i < (int) list->getSize())
1611 item = list->getItem(i);
1612 LuaItemStack::create(L, item);
1616 // set_stack(self, listname, i, stack) -> true/false
1617 static int l_set_stack(lua_State *L)
1619 InvRef *ref = checkobject(L, 1);
1620 const char *listname = luaL_checkstring(L, 2);
1621 int i = luaL_checknumber(L, 3) - 1;
1622 ItemStack newitem = read_item(L, 4);
1623 InventoryList *list = getlist(L, ref, listname);
1624 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1625 list->changeItem(i, newitem);
1626 reportInventoryChange(L, ref);
1627 lua_pushboolean(L, true);
1629 lua_pushboolean(L, false);
1634 // get_list(self, listname) -> list or nil
1635 static int l_get_list(lua_State *L)
1637 InvRef *ref = checkobject(L, 1);
1638 const char *listname = luaL_checkstring(L, 2);
1639 Inventory *inv = getinv(L, ref);
1640 inventory_get_list_to_lua(inv, listname, L);
1644 // set_list(self, listname, list)
1645 static int l_set_list(lua_State *L)
1647 InvRef *ref = checkobject(L, 1);
1648 const char *listname = luaL_checkstring(L, 2);
1649 Inventory *inv = getinv(L, ref);
1650 InventoryList *list = inv->getList(listname);
1652 inventory_set_list_from_lua(inv, listname, L, 3,
1655 inventory_set_list_from_lua(inv, listname, L, 3);
1656 reportInventoryChange(L, ref);
1660 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1661 // Returns the leftover stack
1662 static int l_add_item(lua_State *L)
1664 InvRef *ref = checkobject(L, 1);
1665 const char *listname = luaL_checkstring(L, 2);
1666 ItemStack item = read_item(L, 3);
1667 InventoryList *list = getlist(L, ref, listname);
1669 ItemStack leftover = list->addItem(item);
1670 if(leftover.count != item.count)
1671 reportInventoryChange(L, ref);
1672 LuaItemStack::create(L, leftover);
1674 LuaItemStack::create(L, item);
1679 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1680 // Returns true if the item completely fits into the list
1681 static int l_room_for_item(lua_State *L)
1683 InvRef *ref = checkobject(L, 1);
1684 const char *listname = luaL_checkstring(L, 2);
1685 ItemStack item = read_item(L, 3);
1686 InventoryList *list = getlist(L, ref, listname);
1688 lua_pushboolean(L, list->roomForItem(item));
1690 lua_pushboolean(L, false);
1695 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1696 // Returns true if the list contains the given count of the given item name
1697 static int l_contains_item(lua_State *L)
1699 InvRef *ref = checkobject(L, 1);
1700 const char *listname = luaL_checkstring(L, 2);
1701 ItemStack item = read_item(L, 3);
1702 InventoryList *list = getlist(L, ref, listname);
1704 lua_pushboolean(L, list->containsItem(item));
1706 lua_pushboolean(L, false);
1711 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1712 // Returns the items that were actually removed
1713 static int l_remove_item(lua_State *L)
1715 InvRef *ref = checkobject(L, 1);
1716 const char *listname = luaL_checkstring(L, 2);
1717 ItemStack item = read_item(L, 3);
1718 InventoryList *list = getlist(L, ref, listname);
1720 ItemStack removed = list->removeItem(item);
1721 if(!removed.empty())
1722 reportInventoryChange(L, ref);
1723 LuaItemStack::create(L, removed);
1725 LuaItemStack::create(L, ItemStack());
1731 InvRef(const InventoryLocation &loc):
1740 // Creates an InvRef and leaves it on top of stack
1741 // Not callable from Lua; all references are created on the C side.
1742 static void create(lua_State *L, const InventoryLocation &loc)
1744 InvRef *o = new InvRef(loc);
1745 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1746 luaL_getmetatable(L, className);
1747 lua_setmetatable(L, -2);
1749 static void createPlayer(lua_State *L, Player *player)
1751 InventoryLocation loc;
1752 loc.setPlayer(player->getName());
1755 static void createNodeMeta(lua_State *L, v3s16 p)
1757 InventoryLocation loc;
1762 static void Register(lua_State *L)
1765 int methodtable = lua_gettop(L);
1766 luaL_newmetatable(L, className);
1767 int metatable = lua_gettop(L);
1769 lua_pushliteral(L, "__metatable");
1770 lua_pushvalue(L, methodtable);
1771 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1773 lua_pushliteral(L, "__index");
1774 lua_pushvalue(L, methodtable);
1775 lua_settable(L, metatable);
1777 lua_pushliteral(L, "__gc");
1778 lua_pushcfunction(L, gc_object);
1779 lua_settable(L, metatable);
1781 lua_pop(L, 1); // drop metatable
1783 luaL_openlib(L, 0, methods, 0); // fill methodtable
1784 lua_pop(L, 1); // drop methodtable
1786 // Cannot be created from Lua
1787 //lua_register(L, className, create_object);
1790 const char InvRef::className[] = "InvRef";
1791 const luaL_reg InvRef::methods[] = {
1792 method(InvRef, get_size),
1793 method(InvRef, set_size),
1794 method(InvRef, get_stack),
1795 method(InvRef, set_stack),
1796 method(InvRef, get_list),
1797 method(InvRef, set_list),
1798 method(InvRef, add_item),
1799 method(InvRef, room_for_item),
1800 method(InvRef, contains_item),
1801 method(InvRef, remove_item),
1813 ServerEnvironment *m_env;
1815 static const char className[];
1816 static const luaL_reg methods[];
1818 static NodeMetaRef *checkobject(lua_State *L, int narg)
1820 luaL_checktype(L, narg, LUA_TUSERDATA);
1821 void *ud = luaL_checkudata(L, narg, className);
1822 if(!ud) luaL_typerror(L, narg, className);
1823 return *(NodeMetaRef**)ud; // unbox pointer
1826 static NodeMetadata* getmeta(NodeMetaRef *ref)
1828 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1832 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1834 NodeMetadata *meta = getmeta(ref);
1837 if(meta->typeId() != NODEMETA_GENERIC)
1839 return (IGenericNodeMetadata*)meta;
1842 static void reportMetadataChange(NodeMetaRef *ref)
1844 // Inform other things that the metadata has changed
1845 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1847 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1849 ref->m_env->getMap().dispatchEvent(&event);
1850 // Set the block to be saved
1851 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1853 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1854 "NodeMetaRef::reportMetadataChange");
1857 // Exported functions
1859 // garbage collector
1860 static int gc_object(lua_State *L) {
1861 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1867 static int l_get_type(lua_State *L)
1869 NodeMetaRef *ref = checkobject(L, 1);
1870 NodeMetadata *meta = getmeta(ref);
1876 lua_pushstring(L, meta->typeName());
1880 // allows_text_input(self)
1881 static int l_allows_text_input(lua_State *L)
1883 NodeMetaRef *ref = checkobject(L, 1);
1884 NodeMetadata *meta = getmeta(ref);
1885 if(meta == NULL) return 0;
1887 lua_pushboolean(L, meta->allowsTextInput());
1891 // set_text(self, text)
1892 static int l_set_text(lua_State *L)
1894 NodeMetaRef *ref = checkobject(L, 1);
1895 NodeMetadata *meta = getmeta(ref);
1896 if(meta == NULL) return 0;
1898 std::string text = luaL_checkstring(L, 2);
1899 meta->setText(text);
1900 reportMetadataChange(ref);
1905 static int l_get_text(lua_State *L)
1907 NodeMetaRef *ref = checkobject(L, 1);
1908 NodeMetadata *meta = getmeta(ref);
1909 if(meta == NULL) return 0;
1911 std::string text = meta->getText();
1912 lua_pushstring(L, text.c_str());
1917 static int l_get_owner(lua_State *L)
1919 NodeMetaRef *ref = checkobject(L, 1);
1920 NodeMetadata *meta = getmeta(ref);
1921 if(meta == NULL) return 0;
1923 std::string owner = meta->getOwner();
1924 lua_pushstring(L, owner.c_str());
1928 // set_owner(self, string)
1929 static int l_set_owner(lua_State *L)
1931 NodeMetaRef *ref = checkobject(L, 1);
1932 NodeMetadata *meta = getmeta(ref);
1933 if(meta == NULL) return 0;
1935 std::string owner = luaL_checkstring(L, 2);
1936 meta->setOwner(owner);
1937 reportMetadataChange(ref);
1941 // get_allow_removal(self)
1942 static int l_get_allow_removal(lua_State *L)
1944 NodeMetaRef *ref = checkobject(L, 1);
1945 NodeMetadata *meta = getmeta(ref);
1947 lua_pushboolean(L, true);
1951 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1955 /* IGenericNodeMetadata interface */
1957 // set_infotext(self, text)
1958 static int l_set_infotext(lua_State *L)
1960 NodeMetaRef *ref = checkobject(L, 1);
1961 NodeMetadata *meta = getmeta(ref);
1962 if(meta == NULL) return 0;
1964 std::string text = luaL_checkstring(L, 2);
1965 meta->setInfoText(text);
1966 reportMetadataChange(ref);
1970 // get_inventory(self)
1971 static int l_get_inventory(lua_State *L)
1973 NodeMetaRef *ref = checkobject(L, 1);
1974 NodeMetadata *meta = getmeta(ref);
1975 if(meta == NULL) return 0;
1977 InvRef::createNodeMeta(L, ref->m_p);
1981 // set_inventory_draw_spec(self, text)
1982 static int l_set_inventory_draw_spec(lua_State *L)
1984 NodeMetaRef *ref = checkobject(L, 1);
1985 NodeMetadata *meta = getmeta(ref);
1986 if(meta == NULL) return 0;
1988 std::string text = luaL_checkstring(L, 2);
1989 meta->setInventoryDrawSpec(text);
1990 reportMetadataChange(ref);
1994 // set_allow_text_input(self, text)
1995 static int l_set_allow_text_input(lua_State *L)
1997 NodeMetaRef *ref = checkobject(L, 1);
1998 NodeMetadata *meta = getmeta(ref);
1999 if(meta == NULL) return 0;
2001 bool b = lua_toboolean(L, 2);
2002 meta->setAllowTextInput(b);
2003 reportMetadataChange(ref);
2007 // set_allow_removal(self, text)
2008 static int l_set_allow_removal(lua_State *L)
2010 NodeMetaRef *ref = checkobject(L, 1);
2011 NodeMetadata *meta = getmeta(ref);
2012 if(meta == NULL) return 0;
2014 bool b = lua_toboolean(L, 2);
2015 meta->setRemovalDisabled(!b);
2016 reportMetadataChange(ref);
2020 // set_enforce_owner(self, text)
2021 static int l_set_enforce_owner(lua_State *L)
2023 NodeMetaRef *ref = checkobject(L, 1);
2024 NodeMetadata *meta = getmeta(ref);
2025 if(meta == NULL) return 0;
2027 bool b = lua_toboolean(L, 2);
2028 meta->setEnforceOwner(b);
2029 reportMetadataChange(ref);
2033 // is_inventory_modified(self)
2034 static int l_is_inventory_modified(lua_State *L)
2036 NodeMetaRef *ref = checkobject(L, 1);
2037 NodeMetadata *meta = getmeta(ref);
2038 if(meta == NULL) return 0;
2040 lua_pushboolean(L, meta->isInventoryModified());
2044 // reset_inventory_modified(self)
2045 static int l_reset_inventory_modified(lua_State *L)
2047 NodeMetaRef *ref = checkobject(L, 1);
2048 NodeMetadata *meta = getmeta(ref);
2049 if(meta == NULL) return 0;
2051 meta->resetInventoryModified();
2052 reportMetadataChange(ref);
2056 // is_text_modified(self)
2057 static int l_is_text_modified(lua_State *L)
2059 NodeMetaRef *ref = checkobject(L, 1);
2060 NodeMetadata *meta = getmeta(ref);
2061 if(meta == NULL) return 0;
2063 lua_pushboolean(L, meta->isTextModified());
2067 // reset_text_modified(self)
2068 static int l_reset_text_modified(lua_State *L)
2070 NodeMetaRef *ref = checkobject(L, 1);
2071 NodeMetadata *meta = getmeta(ref);
2072 if(meta == NULL) return 0;
2074 meta->resetTextModified();
2075 reportMetadataChange(ref);
2079 // set_string(self, name, var)
2080 static int l_set_string(lua_State *L)
2082 NodeMetaRef *ref = checkobject(L, 1);
2083 NodeMetadata *meta = getmeta(ref);
2084 if(meta == NULL) return 0;
2086 std::string name = luaL_checkstring(L, 2);
2088 const char *s = lua_tolstring(L, 3, &len);
2089 std::string str(s, len);
2090 meta->setString(name, str);
2091 reportMetadataChange(ref);
2095 // get_string(self, name)
2096 static int l_get_string(lua_State *L)
2098 NodeMetaRef *ref = checkobject(L, 1);
2099 NodeMetadata *meta = getmeta(ref);
2100 if(meta == NULL) return 0;
2102 std::string name = luaL_checkstring(L, 2);
2103 std::string str = meta->getString(name);
2104 lua_pushlstring(L, str.c_str(), str.size());
2109 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2119 // Creates an NodeMetaRef and leaves it on top of stack
2120 // Not callable from Lua; all references are created on the C side.
2121 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2123 NodeMetaRef *o = new NodeMetaRef(p, env);
2124 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2125 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2126 luaL_getmetatable(L, className);
2127 lua_setmetatable(L, -2);
2130 static void Register(lua_State *L)
2133 int methodtable = lua_gettop(L);
2134 luaL_newmetatable(L, className);
2135 int metatable = lua_gettop(L);
2137 lua_pushliteral(L, "__metatable");
2138 lua_pushvalue(L, methodtable);
2139 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2141 lua_pushliteral(L, "__index");
2142 lua_pushvalue(L, methodtable);
2143 lua_settable(L, metatable);
2145 lua_pushliteral(L, "__gc");
2146 lua_pushcfunction(L, gc_object);
2147 lua_settable(L, metatable);
2149 lua_pop(L, 1); // drop metatable
2151 luaL_openlib(L, 0, methods, 0); // fill methodtable
2152 lua_pop(L, 1); // drop methodtable
2154 // Cannot be created from Lua
2155 //lua_register(L, className, create_object);
2158 const char NodeMetaRef::className[] = "NodeMetaRef";
2159 const luaL_reg NodeMetaRef::methods[] = {
2160 method(NodeMetaRef, get_type),
2161 method(NodeMetaRef, allows_text_input),
2162 method(NodeMetaRef, set_text),
2163 method(NodeMetaRef, get_text),
2164 method(NodeMetaRef, get_owner),
2165 method(NodeMetaRef, set_owner),
2166 method(NodeMetaRef, get_allow_removal),
2167 method(NodeMetaRef, set_infotext),
2168 method(NodeMetaRef, get_inventory),
2169 method(NodeMetaRef, set_inventory_draw_spec),
2170 method(NodeMetaRef, set_allow_text_input),
2171 method(NodeMetaRef, set_allow_removal),
2172 method(NodeMetaRef, set_enforce_owner),
2173 method(NodeMetaRef, is_inventory_modified),
2174 method(NodeMetaRef, reset_inventory_modified),
2175 method(NodeMetaRef, is_text_modified),
2176 method(NodeMetaRef, reset_text_modified),
2177 method(NodeMetaRef, set_string),
2178 method(NodeMetaRef, get_string),
2189 ServerActiveObject *m_object;
2191 static const char className[];
2192 static const luaL_reg methods[];
2194 static ObjectRef *checkobject(lua_State *L, int narg)
2196 luaL_checktype(L, narg, LUA_TUSERDATA);
2197 void *ud = luaL_checkudata(L, narg, className);
2198 if(!ud) luaL_typerror(L, narg, className);
2199 return *(ObjectRef**)ud; // unbox pointer
2202 static ServerActiveObject* getobject(ObjectRef *ref)
2204 ServerActiveObject *co = ref->m_object;
2208 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2210 ServerActiveObject *obj = getobject(ref);
2213 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2215 return (LuaEntitySAO*)obj;
2218 static ServerRemotePlayer* getplayer(ObjectRef *ref)
2220 ServerActiveObject *obj = getobject(ref);
2223 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2225 return static_cast<ServerRemotePlayer*>(obj);
2228 // Exported functions
2230 // garbage collector
2231 static int gc_object(lua_State *L) {
2232 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2233 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2239 static int l_remove(lua_State *L)
2241 ObjectRef *ref = checkobject(L, 1);
2242 ServerActiveObject *co = getobject(ref);
2243 if(co == NULL) return 0;
2244 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2245 co->m_removed = true;
2250 // returns: {x=num, y=num, z=num}
2251 static int l_getpos(lua_State *L)
2253 ObjectRef *ref = checkobject(L, 1);
2254 ServerActiveObject *co = getobject(ref);
2255 if(co == NULL) return 0;
2256 v3f pos = co->getBasePosition() / BS;
2258 lua_pushnumber(L, pos.X);
2259 lua_setfield(L, -2, "x");
2260 lua_pushnumber(L, pos.Y);
2261 lua_setfield(L, -2, "y");
2262 lua_pushnumber(L, pos.Z);
2263 lua_setfield(L, -2, "z");
2267 // setpos(self, pos)
2268 static int l_setpos(lua_State *L)
2270 ObjectRef *ref = checkobject(L, 1);
2271 //LuaEntitySAO *co = getluaobject(ref);
2272 ServerActiveObject *co = getobject(ref);
2273 if(co == NULL) return 0;
2275 v3f pos = checkFloatPos(L, 2);
2278 // Move player if applicable
2279 ServerRemotePlayer *player = getplayer(ref);
2281 get_server(L)->SendMovePlayer(player);
2285 // moveto(self, pos, continuous=false)
2286 static int l_moveto(lua_State *L)
2288 ObjectRef *ref = checkobject(L, 1);
2289 //LuaEntitySAO *co = getluaobject(ref);
2290 ServerActiveObject *co = getobject(ref);
2291 if(co == NULL) return 0;
2293 v3f pos = checkFloatPos(L, 2);
2295 bool continuous = lua_toboolean(L, 3);
2297 co->moveTo(pos, continuous);
2301 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2302 static int l_punch(lua_State *L)
2304 ObjectRef *ref = checkobject(L, 1);
2305 ObjectRef *puncher_ref = checkobject(L, 2);
2306 ServerActiveObject *co = getobject(ref);
2307 ServerActiveObject *puncher = getobject(puncher_ref);
2308 if(co == NULL) return 0;
2309 if(puncher == NULL) return 0;
2310 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2311 v3f dir = read_v3f(L, 4);
2312 float time_from_last_punch = 1000000;
2313 if(lua_isnumber(L, 5))
2314 time_from_last_punch = lua_tonumber(L, 5);
2316 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2320 // right_click(self, clicker); clicker = an another ObjectRef
2321 static int l_right_click(lua_State *L)
2323 ObjectRef *ref = checkobject(L, 1);
2324 ObjectRef *ref2 = checkobject(L, 2);
2325 ServerActiveObject *co = getobject(ref);
2326 ServerActiveObject *co2 = getobject(ref2);
2327 if(co == NULL) return 0;
2328 if(co2 == NULL) return 0;
2330 co->rightClick(co2);
2335 // hp = number of hitpoints (2 * number of hearts)
2337 static int l_set_hp(lua_State *L)
2339 ObjectRef *ref = checkobject(L, 1);
2340 luaL_checknumber(L, 2);
2341 ServerActiveObject *co = getobject(ref);
2342 if(co == NULL) return 0;
2343 int hp = lua_tonumber(L, 2);
2344 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2345 <<" hp="<<hp<<std::endl;*/
2353 // returns: number of hitpoints (2 * number of hearts)
2354 // 0 if not applicable to this type of object
2355 static int l_get_hp(lua_State *L)
2357 ObjectRef *ref = checkobject(L, 1);
2358 ServerActiveObject *co = getobject(ref);
2359 if(co == NULL) return 0;
2360 int hp = co->getHP();
2361 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2362 <<" hp="<<hp<<std::endl;*/
2364 lua_pushnumber(L, hp);
2368 // get_inventory(self)
2369 static int l_get_inventory(lua_State *L)
2371 ObjectRef *ref = checkobject(L, 1);
2372 ServerActiveObject *co = getobject(ref);
2373 if(co == NULL) return 0;
2375 InventoryLocation loc = co->getInventoryLocation();
2376 if(get_server(L)->getInventory(loc) != NULL)
2377 InvRef::create(L, loc);
2383 // get_wield_list(self)
2384 static int l_get_wield_list(lua_State *L)
2386 ObjectRef *ref = checkobject(L, 1);
2387 ServerActiveObject *co = getobject(ref);
2388 if(co == NULL) return 0;
2390 lua_pushstring(L, co->getWieldList().c_str());
2394 // get_wield_index(self)
2395 static int l_get_wield_index(lua_State *L)
2397 ObjectRef *ref = checkobject(L, 1);
2398 ServerActiveObject *co = getobject(ref);
2399 if(co == NULL) return 0;
2401 lua_pushinteger(L, co->getWieldIndex() + 1);
2405 // get_wielded_item(self)
2406 static int l_get_wielded_item(lua_State *L)
2408 ObjectRef *ref = checkobject(L, 1);
2409 ServerActiveObject *co = getobject(ref);
2410 if(co == NULL) return 0;
2412 LuaItemStack::create(L, co->getWieldedItem());
2416 // set_wielded_item(self, itemstack or itemstring or table or nil)
2417 static int l_set_wielded_item(lua_State *L)
2419 ObjectRef *ref = checkobject(L, 1);
2420 ServerActiveObject *co = getobject(ref);
2421 if(co == NULL) return 0;
2423 ItemStack item = read_item(L, 2);
2424 bool success = co->setWieldedItem(item);
2425 lua_pushboolean(L, success);
2429 /* LuaEntitySAO-only */
2431 // setvelocity(self, {x=num, y=num, z=num})
2432 static int l_setvelocity(lua_State *L)
2434 ObjectRef *ref = checkobject(L, 1);
2435 LuaEntitySAO *co = getluaobject(ref);
2436 if(co == NULL) return 0;
2438 v3f pos = checkFloatPos(L, 2);
2440 co->setVelocity(pos);
2444 // getvelocity(self)
2445 static int l_getvelocity(lua_State *L)
2447 ObjectRef *ref = checkobject(L, 1);
2448 LuaEntitySAO *co = getluaobject(ref);
2449 if(co == NULL) return 0;
2451 v3f v = co->getVelocity();
2456 // setacceleration(self, {x=num, y=num, z=num})
2457 static int l_setacceleration(lua_State *L)
2459 ObjectRef *ref = checkobject(L, 1);
2460 LuaEntitySAO *co = getluaobject(ref);
2461 if(co == NULL) return 0;
2463 v3f pos = checkFloatPos(L, 2);
2465 co->setAcceleration(pos);
2469 // getacceleration(self)
2470 static int l_getacceleration(lua_State *L)
2472 ObjectRef *ref = checkobject(L, 1);
2473 LuaEntitySAO *co = getluaobject(ref);
2474 if(co == NULL) return 0;
2476 v3f v = co->getAcceleration();
2481 // setyaw(self, radians)
2482 static int l_setyaw(lua_State *L)
2484 ObjectRef *ref = checkobject(L, 1);
2485 LuaEntitySAO *co = getluaobject(ref);
2486 if(co == NULL) return 0;
2488 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2495 static int l_getyaw(lua_State *L)
2497 ObjectRef *ref = checkobject(L, 1);
2498 LuaEntitySAO *co = getluaobject(ref);
2499 if(co == NULL) return 0;
2501 float yaw = co->getYaw() * core::DEGTORAD;
2502 lua_pushnumber(L, yaw);
2506 // settexturemod(self, mod)
2507 static int l_settexturemod(lua_State *L)
2509 ObjectRef *ref = checkobject(L, 1);
2510 LuaEntitySAO *co = getluaobject(ref);
2511 if(co == NULL) return 0;
2513 std::string mod = luaL_checkstring(L, 2);
2514 co->setTextureMod(mod);
2518 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2519 // select_horiz_by_yawpitch=false)
2520 static int l_setsprite(lua_State *L)
2522 ObjectRef *ref = checkobject(L, 1);
2523 LuaEntitySAO *co = getluaobject(ref);
2524 if(co == NULL) return 0;
2527 if(!lua_isnil(L, 2))
2528 p = read_v2s16(L, 2);
2530 if(!lua_isnil(L, 3))
2531 num_frames = lua_tonumber(L, 3);
2532 float framelength = 0.2;
2533 if(!lua_isnil(L, 4))
2534 framelength = lua_tonumber(L, 4);
2535 bool select_horiz_by_yawpitch = false;
2536 if(!lua_isnil(L, 5))
2537 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2538 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2542 // set_armor_groups(self, groups)
2543 static int l_set_armor_groups(lua_State *L)
2545 ObjectRef *ref = checkobject(L, 1);
2546 LuaEntitySAO *co = getluaobject(ref);
2547 if(co == NULL) return 0;
2549 ItemGroupList groups;
2550 read_groups(L, 2, groups);
2551 co->setArmorGroups(groups);
2556 // get_entity_name(self)
2557 static int l_get_entity_name(lua_State *L)
2559 ObjectRef *ref = checkobject(L, 1);
2560 LuaEntitySAO *co = getluaobject(ref);
2561 if(co == NULL) return 0;
2563 std::string name = co->getName();
2564 lua_pushstring(L, name.c_str());
2568 // get_luaentity(self)
2569 static int l_get_luaentity(lua_State *L)
2571 ObjectRef *ref = checkobject(L, 1);
2572 LuaEntitySAO *co = getluaobject(ref);
2573 if(co == NULL) return 0;
2575 luaentity_get(L, co->getId());
2581 // get_player_name(self)
2582 static int l_get_player_name(lua_State *L)
2584 ObjectRef *ref = checkobject(L, 1);
2585 ServerRemotePlayer *player = getplayer(ref);
2591 lua_pushstring(L, player->getName());
2595 // get_look_dir(self)
2596 static int l_get_look_dir(lua_State *L)
2598 ObjectRef *ref = checkobject(L, 1);
2599 ServerRemotePlayer *player = getplayer(ref);
2600 if(player == NULL) return 0;
2602 float pitch = player->getRadPitch();
2603 float yaw = player->getRadYaw();
2604 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2609 // get_look_pitch(self)
2610 static int l_get_look_pitch(lua_State *L)
2612 ObjectRef *ref = checkobject(L, 1);
2613 ServerRemotePlayer *player = getplayer(ref);
2614 if(player == NULL) return 0;
2616 lua_pushnumber(L, player->getRadPitch());
2620 // get_look_yaw(self)
2621 static int l_get_look_yaw(lua_State *L)
2623 ObjectRef *ref = checkobject(L, 1);
2624 ServerRemotePlayer *player = getplayer(ref);
2625 if(player == NULL) return 0;
2627 lua_pushnumber(L, player->getRadYaw());
2632 ObjectRef(ServerActiveObject *object):
2635 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2641 infostream<<"ObjectRef destructing for id="
2642 <<m_object->getId()<<std::endl;
2644 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2647 // Creates an ObjectRef and leaves it on top of stack
2648 // Not callable from Lua; all references are created on the C side.
2649 static void create(lua_State *L, ServerActiveObject *object)
2651 ObjectRef *o = new ObjectRef(object);
2652 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2653 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2654 luaL_getmetatable(L, className);
2655 lua_setmetatable(L, -2);
2658 static void set_null(lua_State *L)
2660 ObjectRef *o = checkobject(L, -1);
2664 static void Register(lua_State *L)
2667 int methodtable = lua_gettop(L);
2668 luaL_newmetatable(L, className);
2669 int metatable = lua_gettop(L);
2671 lua_pushliteral(L, "__metatable");
2672 lua_pushvalue(L, methodtable);
2673 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2675 lua_pushliteral(L, "__index");
2676 lua_pushvalue(L, methodtable);
2677 lua_settable(L, metatable);
2679 lua_pushliteral(L, "__gc");
2680 lua_pushcfunction(L, gc_object);
2681 lua_settable(L, metatable);
2683 lua_pop(L, 1); // drop metatable
2685 luaL_openlib(L, 0, methods, 0); // fill methodtable
2686 lua_pop(L, 1); // drop methodtable
2688 // Cannot be created from Lua
2689 //lua_register(L, className, create_object);
2692 const char ObjectRef::className[] = "ObjectRef";
2693 const luaL_reg ObjectRef::methods[] = {
2694 // ServerActiveObject
2695 method(ObjectRef, remove),
2696 method(ObjectRef, getpos),
2697 method(ObjectRef, setpos),
2698 method(ObjectRef, moveto),
2699 method(ObjectRef, punch),
2700 method(ObjectRef, right_click),
2701 method(ObjectRef, set_hp),
2702 method(ObjectRef, get_hp),
2703 method(ObjectRef, get_inventory),
2704 method(ObjectRef, get_wield_list),
2705 method(ObjectRef, get_wield_index),
2706 method(ObjectRef, get_wielded_item),
2707 method(ObjectRef, set_wielded_item),
2708 // LuaEntitySAO-only
2709 method(ObjectRef, setvelocity),
2710 method(ObjectRef, getvelocity),
2711 method(ObjectRef, setacceleration),
2712 method(ObjectRef, getacceleration),
2713 method(ObjectRef, setyaw),
2714 method(ObjectRef, getyaw),
2715 method(ObjectRef, settexturemod),
2716 method(ObjectRef, setsprite),
2717 method(ObjectRef, set_armor_groups),
2718 method(ObjectRef, get_entity_name),
2719 method(ObjectRef, get_luaentity),
2721 method(ObjectRef, get_player_name),
2722 method(ObjectRef, get_look_dir),
2723 method(ObjectRef, get_look_pitch),
2724 method(ObjectRef, get_look_yaw),
2728 // Creates a new anonymous reference if id=0
2729 static void objectref_get_or_create(lua_State *L,
2730 ServerActiveObject *cobj)
2732 if(cobj->getId() == 0){
2733 ObjectRef::create(L, cobj);
2735 objectref_get(L, cobj->getId());
2746 ServerEnvironment *m_env;
2748 static const char className[];
2749 static const luaL_reg methods[];
2751 static EnvRef *checkobject(lua_State *L, int narg)
2753 luaL_checktype(L, narg, LUA_TUSERDATA);
2754 void *ud = luaL_checkudata(L, narg, className);
2755 if(!ud) luaL_typerror(L, narg, className);
2756 return *(EnvRef**)ud; // unbox pointer
2759 // Exported functions
2761 // EnvRef:add_node(pos, node)
2762 // pos = {x=num, y=num, z=num}
2763 static int l_add_node(lua_State *L)
2765 //infostream<<"EnvRef::l_add_node()"<<std::endl;
2766 EnvRef *o = checkobject(L, 1);
2767 ServerEnvironment *env = o->m_env;
2768 if(env == NULL) return 0;
2770 v3s16 pos = read_v3s16(L, 2);
2772 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2774 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2775 lua_pushboolean(L, succeeded);
2779 // EnvRef:remove_node(pos)
2780 // pos = {x=num, y=num, z=num}
2781 static int l_remove_node(lua_State *L)
2783 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2784 EnvRef *o = checkobject(L, 1);
2785 ServerEnvironment *env = o->m_env;
2786 if(env == NULL) return 0;
2788 v3s16 pos = read_v3s16(L, 2);
2790 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2791 lua_pushboolean(L, succeeded);
2795 // EnvRef:get_node(pos)
2796 // pos = {x=num, y=num, z=num}
2797 static int l_get_node(lua_State *L)
2799 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2800 EnvRef *o = checkobject(L, 1);
2801 ServerEnvironment *env = o->m_env;
2802 if(env == NULL) return 0;
2804 v3s16 pos = read_v3s16(L, 2);
2806 MapNode n = env->getMap().getNodeNoEx(pos);
2808 pushnode(L, n, env->getGameDef()->ndef());
2812 // EnvRef:get_node_or_nil(pos)
2813 // pos = {x=num, y=num, z=num}
2814 static int l_get_node_or_nil(lua_State *L)
2816 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2817 EnvRef *o = checkobject(L, 1);
2818 ServerEnvironment *env = o->m_env;
2819 if(env == NULL) return 0;
2821 v3s16 pos = read_v3s16(L, 2);
2824 MapNode n = env->getMap().getNode(pos);
2826 pushnode(L, n, env->getGameDef()->ndef());
2828 } catch(InvalidPositionException &e)
2835 // EnvRef:get_node_light(pos, timeofday)
2836 // pos = {x=num, y=num, z=num}
2837 // timeofday: nil = current time, 0 = night, 0.5 = day
2838 static int l_get_node_light(lua_State *L)
2840 EnvRef *o = checkobject(L, 1);
2841 ServerEnvironment *env = o->m_env;
2842 if(env == NULL) return 0;
2844 v3s16 pos = read_v3s16(L, 2);
2845 u32 time_of_day = env->getTimeOfDay();
2846 if(lua_isnumber(L, 3))
2847 time_of_day = 24000.0 * lua_tonumber(L, 3);
2848 time_of_day %= 24000;
2849 u32 dnr = time_to_daynight_ratio(time_of_day);
2850 MapNode n = env->getMap().getNodeNoEx(pos);
2852 MapNode n = env->getMap().getNode(pos);
2853 INodeDefManager *ndef = env->getGameDef()->ndef();
2854 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2856 } catch(InvalidPositionException &e)
2863 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2864 // pos = {x=num, y=num, z=num}
2865 static int l_add_entity(lua_State *L)
2867 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2868 EnvRef *o = checkobject(L, 1);
2869 ServerEnvironment *env = o->m_env;
2870 if(env == NULL) return 0;
2872 v3f pos = checkFloatPos(L, 2);
2874 const char *name = luaL_checkstring(L, 3);
2876 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2877 int objectid = env->addActiveObject(obj);
2878 // If failed to add, return nothing (reads as nil)
2882 objectref_get_or_create(L, obj);
2886 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2887 // pos = {x=num, y=num, z=num}
2888 static int l_add_item(lua_State *L)
2890 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2891 EnvRef *o = checkobject(L, 1);
2892 ServerEnvironment *env = o->m_env;
2893 if(env == NULL) return 0;
2895 v3f pos = checkFloatPos(L, 2);
2897 ItemStack item = read_item(L, 3);
2898 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2901 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2902 int objectid = env->addActiveObject(obj);
2903 // If failed to add, return nothing (reads as nil)
2907 objectref_get_or_create(L, obj);
2911 // EnvRef:add_rat(pos)
2912 // pos = {x=num, y=num, z=num}
2913 static int l_add_rat(lua_State *L)
2915 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2916 <<" Doing nothing."<<std::endl;
2920 // EnvRef:add_firefly(pos)
2921 // pos = {x=num, y=num, z=num}
2922 static int l_add_firefly(lua_State *L)
2924 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2925 <<" Doing nothing."<<std::endl;
2929 // EnvRef:get_meta(pos)
2930 static int l_get_meta(lua_State *L)
2932 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2933 EnvRef *o = checkobject(L, 1);
2934 ServerEnvironment *env = o->m_env;
2935 if(env == NULL) return 0;
2937 v3s16 p = read_v3s16(L, 2);
2938 NodeMetaRef::create(L, p, env);
2942 // EnvRef:get_player_by_name(name)
2943 static int l_get_player_by_name(lua_State *L)
2945 EnvRef *o = checkobject(L, 1);
2946 ServerEnvironment *env = o->m_env;
2947 if(env == NULL) return 0;
2949 const char *name = luaL_checkstring(L, 2);
2950 ServerRemotePlayer *player =
2951 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2956 // Put player on stack
2957 objectref_get_or_create(L, player);
2961 // EnvRef:get_objects_inside_radius(pos, radius)
2962 static int l_get_objects_inside_radius(lua_State *L)
2964 // Get the table insert function
2965 lua_getglobal(L, "table");
2966 lua_getfield(L, -1, "insert");
2967 int table_insert = lua_gettop(L);
2969 EnvRef *o = checkobject(L, 1);
2970 ServerEnvironment *env = o->m_env;
2971 if(env == NULL) return 0;
2973 v3f pos = checkFloatPos(L, 2);
2974 float radius = luaL_checknumber(L, 3) * BS;
2975 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
2977 int table = lua_gettop(L);
2978 for(std::set<u16>::const_iterator
2979 i = ids.begin(); i != ids.end(); i++){
2980 ServerActiveObject *obj = env->getActiveObject(*i);
2981 // Insert object reference into table
2982 lua_pushvalue(L, table_insert);
2983 lua_pushvalue(L, table);
2984 objectref_get_or_create(L, obj);
2985 if(lua_pcall(L, 2, 0, 0))
2986 script_error(L, "error: %s", lua_tostring(L, -1));
2991 // EnvRef:set_timeofday(val)
2993 static int l_set_timeofday(lua_State *L)
2995 EnvRef *o = checkobject(L, 1);
2996 ServerEnvironment *env = o->m_env;
2997 if(env == NULL) return 0;
2999 float timeofday_f = luaL_checknumber(L, 2);
3000 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3001 int timeofday_mh = (int)(timeofday_f * 24000.0);
3002 // This should be set directly in the environment but currently
3003 // such changes aren't immediately sent to the clients, so call
3004 // the server instead.
3005 //env->setTimeOfDay(timeofday_mh);
3006 get_server(L)->setTimeOfDay(timeofday_mh);
3010 // EnvRef:get_timeofday() -> 0...1
3011 static int l_get_timeofday(lua_State *L)
3013 EnvRef *o = checkobject(L, 1);
3014 ServerEnvironment *env = o->m_env;
3015 if(env == NULL) return 0;
3017 int timeofday_mh = env->getTimeOfDay();
3018 float timeofday_f = (float)timeofday_mh / 24000.0;
3019 lua_pushnumber(L, timeofday_f);
3023 static int gc_object(lua_State *L) {
3024 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3030 EnvRef(ServerEnvironment *env):
3033 //infostream<<"EnvRef created"<<std::endl;
3038 //infostream<<"EnvRef destructing"<<std::endl;
3041 // Creates an EnvRef and leaves it on top of stack
3042 // Not callable from Lua; all references are created on the C side.
3043 static void create(lua_State *L, ServerEnvironment *env)
3045 EnvRef *o = new EnvRef(env);
3046 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3047 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3048 luaL_getmetatable(L, className);
3049 lua_setmetatable(L, -2);
3052 static void set_null(lua_State *L)
3054 EnvRef *o = checkobject(L, -1);
3058 static void Register(lua_State *L)
3061 int methodtable = lua_gettop(L);
3062 luaL_newmetatable(L, className);
3063 int metatable = lua_gettop(L);
3065 lua_pushliteral(L, "__metatable");
3066 lua_pushvalue(L, methodtable);
3067 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3069 lua_pushliteral(L, "__index");
3070 lua_pushvalue(L, methodtable);
3071 lua_settable(L, metatable);
3073 lua_pushliteral(L, "__gc");
3074 lua_pushcfunction(L, gc_object);
3075 lua_settable(L, metatable);
3077 lua_pop(L, 1); // drop metatable
3079 luaL_openlib(L, 0, methods, 0); // fill methodtable
3080 lua_pop(L, 1); // drop methodtable
3082 // Cannot be created from Lua
3083 //lua_register(L, className, create_object);
3086 const char EnvRef::className[] = "EnvRef";
3087 const luaL_reg EnvRef::methods[] = {
3088 method(EnvRef, add_node),
3089 method(EnvRef, remove_node),
3090 method(EnvRef, get_node),
3091 method(EnvRef, get_node_or_nil),
3092 method(EnvRef, get_node_light),
3093 method(EnvRef, add_entity),
3094 method(EnvRef, add_item),
3095 method(EnvRef, add_rat),
3096 method(EnvRef, add_firefly),
3097 method(EnvRef, get_meta),
3098 method(EnvRef, get_player_by_name),
3099 method(EnvRef, get_objects_inside_radius),
3100 method(EnvRef, set_timeofday),
3101 method(EnvRef, get_timeofday),
3109 class LuaABM : public ActiveBlockModifier
3115 std::set<std::string> m_trigger_contents;
3116 std::set<std::string> m_required_neighbors;
3117 float m_trigger_interval;
3118 u32 m_trigger_chance;
3120 LuaABM(lua_State *L, int id,
3121 const std::set<std::string> &trigger_contents,
3122 const std::set<std::string> &required_neighbors,
3123 float trigger_interval, u32 trigger_chance):
3126 m_trigger_contents(trigger_contents),
3127 m_required_neighbors(required_neighbors),
3128 m_trigger_interval(trigger_interval),
3129 m_trigger_chance(trigger_chance)
3132 virtual std::set<std::string> getTriggerContents()
3134 return m_trigger_contents;
3136 virtual std::set<std::string> getRequiredNeighbors()
3138 return m_required_neighbors;
3140 virtual float getTriggerInterval()
3142 return m_trigger_interval;
3144 virtual u32 getTriggerChance()
3146 return m_trigger_chance;
3148 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3149 u32 active_object_count, u32 active_object_count_wider)
3151 lua_State *L = m_lua;
3154 assert(lua_checkstack(L, 20));
3155 StackUnroller stack_unroller(L);
3157 // Get minetest.registered_abms
3158 lua_getglobal(L, "minetest");
3159 lua_getfield(L, -1, "registered_abms");
3160 luaL_checktype(L, -1, LUA_TTABLE);
3161 int registered_abms = lua_gettop(L);
3163 // Get minetest.registered_abms[m_id]
3164 lua_pushnumber(L, m_id);
3165 lua_gettable(L, registered_abms);
3166 if(lua_isnil(L, -1))
3170 luaL_checktype(L, -1, LUA_TTABLE);
3171 lua_getfield(L, -1, "action");
3172 luaL_checktype(L, -1, LUA_TFUNCTION);
3174 pushnode(L, n, env->getGameDef()->ndef());
3175 lua_pushnumber(L, active_object_count);
3176 lua_pushnumber(L, active_object_count_wider);
3177 if(lua_pcall(L, 4, 0, 0))
3178 script_error(L, "error: %s", lua_tostring(L, -1));
3183 // Writes a line to dstream
3184 static int l_debug(lua_State *L)
3186 std::string text = lua_tostring(L, 1);
3187 dstream << text << std::endl;
3191 // log([level,] text)
3192 // Writes a line to the logger.
3193 // The one-argument version logs to infostream.
3194 // The two-argument version accept a log level: error, action, info, or verbose.
3195 static int l_log(lua_State *L)
3198 LogMessageLevel level = LMT_INFO;
3199 if(lua_isnone(L, 2))
3201 text = lua_tostring(L, 1);
3205 std::string levelname = lua_tostring(L, 1);
3206 text = lua_tostring(L, 2);
3207 if(levelname == "error")
3209 else if(levelname == "action")
3211 else if(levelname == "verbose")
3212 level = LMT_VERBOSE;
3214 log_printline(level, text);
3218 // register_item_raw({lots of stuff})
3219 static int l_register_item_raw(lua_State *L)
3221 luaL_checktype(L, 1, LUA_TTABLE);
3224 // Get the writable item and node definition managers from the server
3225 IWritableItemDefManager *idef =
3226 get_server(L)->getWritableItemDefManager();
3227 IWritableNodeDefManager *ndef =
3228 get_server(L)->getWritableNodeDefManager();
3230 // Check if name is defined
3231 lua_getfield(L, table, "name");
3232 if(lua_isstring(L, -1)){
3233 std::string name = lua_tostring(L, -1);
3234 verbosestream<<"register_item_raw: "<<name<<std::endl;
3236 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3239 // Check if on_use is defined
3241 // Read the item definition and register it
3242 ItemDefinition def = read_item_definition(L, table);
3243 idef->registerItem(def);
3245 // Read the node definition (content features) and register it
3246 if(def.type == ITEM_NODE)
3248 ContentFeatures f = read_content_features(L, table);
3249 ndef->set(f.name, f);
3252 return 0; /* number of results */
3255 // register_alias_raw(name, convert_to_name)
3256 static int l_register_alias_raw(lua_State *L)
3258 std::string name = luaL_checkstring(L, 1);
3259 std::string convert_to = luaL_checkstring(L, 2);
3261 // Get the writable item definition manager from the server
3262 IWritableItemDefManager *idef =
3263 get_server(L)->getWritableItemDefManager();
3265 idef->registerAlias(name, convert_to);
3267 return 0; /* number of results */
3270 // helper for register_craft
3271 static bool read_craft_recipe_shaped(lua_State *L, int index,
3272 int &width, std::vector<std::string> &recipe)
3275 index = lua_gettop(L) + 1 + index;
3277 if(!lua_istable(L, index))
3282 while(lua_next(L, index) != 0){
3284 // key at index -2 and value at index -1
3285 if(!lua_istable(L, -1))
3287 int table2 = lua_gettop(L);
3289 while(lua_next(L, table2) != 0){
3290 // key at index -2 and value at index -1
3291 if(!lua_isstring(L, -1))
3293 recipe.push_back(lua_tostring(L, -1));
3294 // removes value, keeps key for next iteration
3301 if(colcount != width)
3304 // removes value, keeps key for next iteration
3311 // helper for register_craft
3312 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3313 std::vector<std::string> &recipe)
3316 index = lua_gettop(L) + 1 + index;
3318 if(!lua_istable(L, index))
3322 while(lua_next(L, index) != 0){
3323 // key at index -2 and value at index -1
3324 if(!lua_isstring(L, -1))
3326 recipe.push_back(lua_tostring(L, -1));
3327 // removes value, keeps key for next iteration
3333 // helper for register_craft
3334 static bool read_craft_replacements(lua_State *L, int index,
3335 CraftReplacements &replacements)
3338 index = lua_gettop(L) + 1 + index;
3340 if(!lua_istable(L, index))
3344 while(lua_next(L, index) != 0){
3345 // key at index -2 and value at index -1
3346 if(!lua_istable(L, -1))
3348 lua_rawgeti(L, -1, 1);
3349 if(!lua_isstring(L, -1))
3351 std::string replace_from = lua_tostring(L, -1);
3353 lua_rawgeti(L, -1, 2);
3354 if(!lua_isstring(L, -1))
3356 std::string replace_to = lua_tostring(L, -1);
3358 replacements.pairs.push_back(
3359 std::make_pair(replace_from, replace_to));
3360 // removes value, keeps key for next iteration
3365 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3366 static int l_register_craft(lua_State *L)
3368 //infostream<<"register_craft"<<std::endl;
3369 luaL_checktype(L, 1, LUA_TTABLE);
3372 // Get the writable craft definition manager from the server
3373 IWritableCraftDefManager *craftdef =
3374 get_server(L)->getWritableCraftDefManager();
3376 std::string type = getstringfield_default(L, table, "type", "shaped");
3379 CraftDefinitionShaped
3381 if(type == "shaped"){
3382 std::string output = getstringfield_default(L, table, "output", "");
3384 throw LuaError(L, "Crafting definition is missing an output");
3387 std::vector<std::string> recipe;
3388 lua_getfield(L, table, "recipe");
3389 if(lua_isnil(L, -1))
3390 throw LuaError(L, "Crafting definition is missing a recipe"
3391 " (output=\"" + output + "\")");
3392 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3393 throw LuaError(L, "Invalid crafting recipe"
3394 " (output=\"" + output + "\")");
3396 CraftReplacements replacements;
3397 lua_getfield(L, table, "replacements");
3398 if(!lua_isnil(L, -1))
3400 if(!read_craft_replacements(L, -1, replacements))
3401 throw LuaError(L, "Invalid replacements"
3402 " (output=\"" + output + "\")");
3405 CraftDefinition *def = new CraftDefinitionShaped(
3406 output, width, recipe, replacements);
3407 craftdef->registerCraft(def);
3410 CraftDefinitionShapeless
3412 else if(type == "shapeless"){
3413 std::string output = getstringfield_default(L, table, "output", "");
3415 throw LuaError(L, "Crafting definition (shapeless)"
3416 " is missing an output");
3418 std::vector<std::string> recipe;
3419 lua_getfield(L, table, "recipe");
3420 if(lua_isnil(L, -1))
3421 throw LuaError(L, "Crafting definition (shapeless)"
3422 " is missing a recipe"
3423 " (output=\"" + output + "\")");
3424 if(!read_craft_recipe_shapeless(L, -1, recipe))
3425 throw LuaError(L, "Invalid crafting recipe"
3426 " (output=\"" + output + "\")");
3428 CraftReplacements replacements;
3429 lua_getfield(L, table, "replacements");
3430 if(!lua_isnil(L, -1))
3432 if(!read_craft_replacements(L, -1, replacements))
3433 throw LuaError(L, "Invalid replacements"
3434 " (output=\"" + output + "\")");
3437 CraftDefinition *def = new CraftDefinitionShapeless(
3438 output, recipe, replacements);
3439 craftdef->registerCraft(def);
3442 CraftDefinitionToolRepair
3444 else if(type == "toolrepair"){
3445 float additional_wear = getfloatfield_default(L, table,
3446 "additional_wear", 0.0);
3448 CraftDefinition *def = new CraftDefinitionToolRepair(
3450 craftdef->registerCraft(def);
3453 CraftDefinitionCooking
3455 else if(type == "cooking"){
3456 std::string output = getstringfield_default(L, table, "output", "");
3458 throw LuaError(L, "Crafting definition (cooking)"
3459 " is missing an output");
3461 std::string recipe = getstringfield_default(L, table, "recipe", "");
3463 throw LuaError(L, "Crafting definition (cooking)"
3464 " is missing a recipe"
3465 " (output=\"" + output + "\")");
3467 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3469 CraftDefinition *def = new CraftDefinitionCooking(
3470 output, recipe, cooktime);
3471 craftdef->registerCraft(def);
3476 else if(type == "fuel"){
3477 std::string recipe = getstringfield_default(L, table, "recipe", "");
3479 throw LuaError(L, "Crafting definition (fuel)"
3480 " is missing a recipe");
3482 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3484 CraftDefinition *def = new CraftDefinitionFuel(
3486 craftdef->registerCraft(def);
3490 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3494 return 0; /* number of results */
3497 // setting_get(name)
3498 static int l_setting_get(lua_State *L)
3500 const char *name = luaL_checkstring(L, 1);
3502 std::string value = g_settings->get(name);
3503 lua_pushstring(L, value.c_str());
3504 } catch(SettingNotFoundException &e){
3510 // setting_getbool(name)
3511 static int l_setting_getbool(lua_State *L)
3513 const char *name = luaL_checkstring(L, 1);
3515 bool value = g_settings->getBool(name);
3516 lua_pushboolean(L, value);
3517 } catch(SettingNotFoundException &e){
3523 // chat_send_all(text)
3524 static int l_chat_send_all(lua_State *L)
3526 const char *text = luaL_checkstring(L, 1);
3527 // Get server from registry
3528 Server *server = get_server(L);
3530 server->notifyPlayers(narrow_to_wide(text));
3534 // chat_send_player(name, text)
3535 static int l_chat_send_player(lua_State *L)
3537 const char *name = luaL_checkstring(L, 1);
3538 const char *text = luaL_checkstring(L, 2);
3539 // Get server from registry
3540 Server *server = get_server(L);
3542 server->notifyPlayer(name, narrow_to_wide(text));
3546 // get_player_privs(name, text)
3547 static int l_get_player_privs(lua_State *L)
3549 const char *name = luaL_checkstring(L, 1);
3550 // Get server from registry
3551 Server *server = get_server(L);
3554 int table = lua_gettop(L);
3555 u64 privs_i = server->getPlayerEffectivePrivs(name);
3556 std::set<std::string> privs_s = privsToSet(privs_i);
3557 for(std::set<std::string>::const_iterator
3558 i = privs_s.begin(); i != privs_s.end(); i++){
3559 lua_pushboolean(L, true);
3560 lua_setfield(L, table, i->c_str());
3562 lua_pushvalue(L, table);
3566 // get_inventory(location)
3567 static int l_get_inventory(lua_State *L)
3569 InventoryLocation loc;
3571 std::string type = checkstringfield(L, 1, "type");
3572 if(type == "player"){
3573 std::string name = checkstringfield(L, 1, "name");
3574 loc.setPlayer(name);
3575 } else if(type == "node"){
3576 lua_getfield(L, 1, "pos");
3577 v3s16 pos = check_v3s16(L, -1);
3578 loc.setNodeMeta(pos);
3581 if(get_server(L)->getInventory(loc) != NULL)
3582 InvRef::create(L, loc);
3588 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3589 static int l_get_dig_params(lua_State *L)
3591 std::map<std::string, int> groups;
3592 read_groups(L, 1, groups);
3593 ToolCapabilities tp = read_tool_capabilities(L, 2);
3594 if(lua_isnoneornil(L, 3))
3595 push_dig_params(L, getDigParams(groups, &tp));
3597 push_dig_params(L, getDigParams(groups, &tp,
3598 luaL_checknumber(L, 3)));
3602 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3603 static int l_get_hit_params(lua_State *L)
3605 std::map<std::string, int> groups;
3606 read_groups(L, 1, groups);
3607 ToolCapabilities tp = read_tool_capabilities(L, 2);
3608 if(lua_isnoneornil(L, 3))
3609 push_hit_params(L, getHitParams(groups, &tp));
3611 push_hit_params(L, getHitParams(groups, &tp,
3612 luaL_checknumber(L, 3)));
3616 // get_current_modname()
3617 static int l_get_current_modname(lua_State *L)
3619 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3623 // get_modpath(modname)
3624 static int l_get_modpath(lua_State *L)
3626 const char *modname = luaL_checkstring(L, 1);
3628 const ModSpec *mod = get_server(L)->getModSpec(modname);
3633 lua_pushstring(L, mod->path.c_str());
3638 static int l_get_worldpath(lua_State *L)
3640 std::string worldpath = get_server(L)->getWorldPath();
3641 lua_pushstring(L, worldpath.c_str());
3645 static const struct luaL_Reg minetest_f [] = {
3648 {"register_item_raw", l_register_item_raw},
3649 {"register_alias_raw", l_register_alias_raw},
3650 {"register_craft", l_register_craft},
3651 {"setting_get", l_setting_get},
3652 {"setting_getbool", l_setting_getbool},
3653 {"chat_send_all", l_chat_send_all},
3654 {"chat_send_player", l_chat_send_player},
3655 {"get_player_privs", l_get_player_privs},
3656 {"get_inventory", l_get_inventory},
3657 {"get_dig_params", l_get_dig_params},
3658 {"get_hit_params", l_get_hit_params},
3659 {"get_current_modname", l_get_current_modname},
3660 {"get_modpath", l_get_modpath},
3661 {"get_worldpath", l_get_worldpath},
3666 Main export function
3669 void scriptapi_export(lua_State *L, Server *server)
3672 assert(lua_checkstack(L, 20));
3673 verbosestream<<"scriptapi_export()"<<std::endl;
3674 StackUnroller stack_unroller(L);
3676 // Store server as light userdata in registry
3677 lua_pushlightuserdata(L, server);
3678 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3680 // Register global functions in table minetest
3682 luaL_register(L, NULL, minetest_f);
3683 lua_setglobal(L, "minetest");
3685 // Get the main minetest table
3686 lua_getglobal(L, "minetest");
3688 // Add tables to minetest
3691 lua_setfield(L, -2, "object_refs");
3693 lua_setfield(L, -2, "luaentities");
3695 // Register wrappers
3696 LuaItemStack::Register(L);
3697 InvRef::Register(L);
3698 NodeMetaRef::Register(L);
3699 ObjectRef::Register(L);
3700 EnvRef::Register(L);
3703 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3704 const std::string &modname)
3706 ModNameStorer modnamestorer(L, modname);
3708 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3710 errorstream<<"Error loading mod \""<<modname
3711 <<"\": modname does not follow naming conventions: "
3712 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3716 bool success = false;
3719 success = script_load(L, scriptpath.c_str());
3722 errorstream<<"Error loading mod \""<<modname
3723 <<"\": "<<e.what()<<std::endl;
3729 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3732 assert(lua_checkstack(L, 20));
3733 verbosestream<<"scriptapi_add_environment"<<std::endl;
3734 StackUnroller stack_unroller(L);
3736 // Create EnvRef on stack
3737 EnvRef::create(L, env);
3738 int envref = lua_gettop(L);
3740 // minetest.env = envref
3741 lua_getglobal(L, "minetest");
3742 luaL_checktype(L, -1, LUA_TTABLE);
3743 lua_pushvalue(L, envref);
3744 lua_setfield(L, -2, "env");
3746 // Store environment as light userdata in registry
3747 lua_pushlightuserdata(L, env);
3748 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3751 Add ActiveBlockModifiers to environment
3754 // Get minetest.registered_abms
3755 lua_getglobal(L, "minetest");
3756 lua_getfield(L, -1, "registered_abms");
3757 luaL_checktype(L, -1, LUA_TTABLE);
3758 int registered_abms = lua_gettop(L);
3760 if(lua_istable(L, registered_abms)){
3761 int table = lua_gettop(L);
3763 while(lua_next(L, table) != 0){
3764 // key at index -2 and value at index -1
3765 int id = lua_tonumber(L, -2);
3766 int current_abm = lua_gettop(L);
3768 std::set<std::string> trigger_contents;
3769 lua_getfield(L, current_abm, "nodenames");
3770 if(lua_istable(L, -1)){
3771 int table = lua_gettop(L);
3773 while(lua_next(L, table) != 0){
3774 // key at index -2 and value at index -1
3775 luaL_checktype(L, -1, LUA_TSTRING);
3776 trigger_contents.insert(lua_tostring(L, -1));
3777 // removes value, keeps key for next iteration
3780 } else if(lua_isstring(L, -1)){
3781 trigger_contents.insert(lua_tostring(L, -1));
3785 std::set<std::string> required_neighbors;
3786 lua_getfield(L, current_abm, "neighbors");
3787 if(lua_istable(L, -1)){
3788 int table = lua_gettop(L);
3790 while(lua_next(L, table) != 0){
3791 // key at index -2 and value at index -1
3792 luaL_checktype(L, -1, LUA_TSTRING);
3793 required_neighbors.insert(lua_tostring(L, -1));
3794 // removes value, keeps key for next iteration
3797 } else if(lua_isstring(L, -1)){
3798 required_neighbors.insert(lua_tostring(L, -1));
3802 float trigger_interval = 10.0;
3803 getfloatfield(L, current_abm, "interval", trigger_interval);
3805 int trigger_chance = 50;
3806 getintfield(L, current_abm, "chance", trigger_chance);
3808 LuaABM *abm = new LuaABM(L, id, trigger_contents,
3809 required_neighbors, trigger_interval, trigger_chance);
3811 env->addActiveBlockModifier(abm);
3813 // removes value, keeps key for next iteration
3821 // Dump stack top with the dump2 function
3822 static void dump2(lua_State *L, const char *name)
3824 // Dump object (debug)
3825 lua_getglobal(L, "dump2");
3826 luaL_checktype(L, -1, LUA_TFUNCTION);
3827 lua_pushvalue(L, -2); // Get previous stack top as first parameter
3828 lua_pushstring(L, name);
3829 if(lua_pcall(L, 2, 0, 0))
3830 script_error(L, "error: %s", lua_tostring(L, -1));
3838 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
3841 assert(lua_checkstack(L, 20));
3842 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
3843 StackUnroller stack_unroller(L);
3845 // Create object on stack
3846 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
3847 int object = lua_gettop(L);
3849 // Get minetest.object_refs table
3850 lua_getglobal(L, "minetest");
3851 lua_getfield(L, -1, "object_refs");
3852 luaL_checktype(L, -1, LUA_TTABLE);
3853 int objectstable = lua_gettop(L);
3855 // object_refs[id] = object
3856 lua_pushnumber(L, cobj->getId()); // Push id
3857 lua_pushvalue(L, object); // Copy object to top of stack
3858 lua_settable(L, objectstable);
3861 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
3864 assert(lua_checkstack(L, 20));
3865 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
3866 StackUnroller stack_unroller(L);
3868 // Get minetest.object_refs table
3869 lua_getglobal(L, "minetest");
3870 lua_getfield(L, -1, "object_refs");
3871 luaL_checktype(L, -1, LUA_TTABLE);
3872 int objectstable = lua_gettop(L);
3874 // Get object_refs[id]
3875 lua_pushnumber(L, cobj->getId()); // Push id
3876 lua_gettable(L, objectstable);
3877 // Set object reference to NULL
3878 ObjectRef::set_null(L);
3879 lua_pop(L, 1); // pop object
3881 // Set object_refs[id] = nil
3882 lua_pushnumber(L, cobj->getId()); // Push id
3884 lua_settable(L, objectstable);
3887 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
3888 const std::string &message)
3891 assert(lua_checkstack(L, 20));
3892 StackUnroller stack_unroller(L);
3894 // Get minetest.registered_on_chat_messages
3895 lua_getglobal(L, "minetest");
3896 lua_getfield(L, -1, "registered_on_chat_messages");
3897 luaL_checktype(L, -1, LUA_TTABLE);
3898 int table = lua_gettop(L);
3901 while(lua_next(L, table) != 0){
3902 // key at index -2 and value at index -1
3903 luaL_checktype(L, -1, LUA_TFUNCTION);
3905 lua_pushstring(L, name.c_str());
3906 lua_pushstring(L, message.c_str());
3907 if(lua_pcall(L, 2, 1, 0))
3908 script_error(L, "error: %s", lua_tostring(L, -1));
3909 bool ate = lua_toboolean(L, -1);
3913 // value removed, keep key for next iteration
3922 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
3925 assert(lua_checkstack(L, 20));
3926 StackUnroller stack_unroller(L);
3928 // Get minetest.registered_on_newplayers
3929 lua_getglobal(L, "minetest");
3930 lua_getfield(L, -1, "registered_on_newplayers");
3931 luaL_checktype(L, -1, LUA_TTABLE);
3932 int table = lua_gettop(L);
3935 while(lua_next(L, table) != 0){
3936 // key at index -2 and value at index -1
3937 luaL_checktype(L, -1, LUA_TFUNCTION);
3939 objectref_get_or_create(L, player);
3940 if(lua_pcall(L, 1, 0, 0))
3941 script_error(L, "error: %s", lua_tostring(L, -1));
3942 // value removed, keep key for next iteration
3946 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
3949 assert(lua_checkstack(L, 20));
3950 StackUnroller stack_unroller(L);
3952 // Get minetest.registered_on_dieplayers
3953 lua_getglobal(L, "minetest");
3954 lua_getfield(L, -1, "registered_on_dieplayers");
3955 luaL_checktype(L, -1, LUA_TTABLE);
3956 int table = lua_gettop(L);
3959 while(lua_next(L, table) != 0){
3960 // key at index -2 and value at index -1
3961 luaL_checktype(L, -1, LUA_TFUNCTION);
3963 objectref_get_or_create(L, player);
3964 if(lua_pcall(L, 1, 0, 0))
3965 script_error(L, "error: %s", lua_tostring(L, -1));
3966 // value removed, keep key for next iteration
3971 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
3974 assert(lua_checkstack(L, 20));
3975 StackUnroller stack_unroller(L);
3977 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
3979 bool positioning_handled_by_some = false;
3981 // Get minetest.registered_on_respawnplayers
3982 lua_getglobal(L, "minetest");
3983 lua_getfield(L, -1, "registered_on_respawnplayers");
3984 luaL_checktype(L, -1, LUA_TTABLE);
3985 int table = lua_gettop(L);
3988 while(lua_next(L, table) != 0){
3989 // key at index -2 and value at index -1
3990 luaL_checktype(L, -1, LUA_TFUNCTION);
3992 objectref_get_or_create(L, player);
3993 if(lua_pcall(L, 1, 1, 0))
3994 script_error(L, "error: %s", lua_tostring(L, -1));
3995 bool positioning_handled = lua_toboolean(L, -1);
3997 if(positioning_handled)
3998 positioning_handled_by_some = true;
3999 // value removed, keep key for next iteration
4001 return positioning_handled_by_some;
4004 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4006 lua_getglobal(L, "minetest");
4007 lua_getfield(L, -1, "creative_inventory");
4008 luaL_checktype(L, -1, LUA_TTABLE);
4009 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4010 PLAYER_INVENTORY_SIZE);
4014 item callbacks and node callbacks
4017 // Retrieves minetest.registered_items[name][callbackname]
4018 // If that is nil or on error, return false and stack is unchanged
4019 // If that is a function, returns true and pushes the
4020 // function onto the stack
4021 static bool get_item_callback(lua_State *L,
4022 const char *name, const char *callbackname)
4024 lua_getglobal(L, "minetest");
4025 lua_getfield(L, -1, "registered_items");
4027 luaL_checktype(L, -1, LUA_TTABLE);
4028 lua_getfield(L, -1, name);
4030 // Should be a table
4031 if(lua_type(L, -1) != LUA_TTABLE)
4033 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4037 lua_getfield(L, -1, callbackname);
4039 // Should be a function or nil
4040 if(lua_type(L, -1) == LUA_TFUNCTION)
4044 else if(lua_isnil(L, -1))
4051 errorstream<<"Item \""<<name<<"\" callback \""
4052 <<callbackname<<" is not a function"<<std::endl;
4058 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4059 ServerActiveObject *dropper, v3f pos)
4062 assert(lua_checkstack(L, 20));
4063 StackUnroller stack_unroller(L);
4065 // Push callback function on stack
4066 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4070 LuaItemStack::create(L, item);
4071 objectref_get_or_create(L, dropper);
4072 pushFloatPos(L, pos);
4073 if(lua_pcall(L, 3, 1, 0))
4074 script_error(L, "error: %s", lua_tostring(L, -1));
4075 if(!lua_isnil(L, -1))
4076 item = read_item(L, -1);
4080 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4081 ServerActiveObject *placer, const PointedThing &pointed)
4084 assert(lua_checkstack(L, 20));
4085 StackUnroller stack_unroller(L);
4087 // Push callback function on stack
4088 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4092 LuaItemStack::create(L, item);
4093 objectref_get_or_create(L, placer);
4094 push_pointed_thing(L, pointed);
4095 if(lua_pcall(L, 3, 1, 0))
4096 script_error(L, "error: %s", lua_tostring(L, -1));
4097 if(!lua_isnil(L, -1))
4098 item = read_item(L, -1);
4102 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4103 ServerActiveObject *user, const PointedThing &pointed)
4106 assert(lua_checkstack(L, 20));
4107 StackUnroller stack_unroller(L);
4109 // Push callback function on stack
4110 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4114 LuaItemStack::create(L, item);
4115 objectref_get_or_create(L, user);
4116 push_pointed_thing(L, pointed);
4117 if(lua_pcall(L, 3, 1, 0))
4118 script_error(L, "error: %s", lua_tostring(L, -1));
4119 if(!lua_isnil(L, -1))
4120 item = read_item(L, -1);
4124 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4125 ServerActiveObject *puncher)
4128 assert(lua_checkstack(L, 20));
4129 StackUnroller stack_unroller(L);
4131 INodeDefManager *ndef = get_server(L)->ndef();
4133 // Push callback function on stack
4134 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4139 pushnode(L, node, ndef);
4140 objectref_get_or_create(L, puncher);
4141 if(lua_pcall(L, 3, 0, 0))
4142 script_error(L, "error: %s", lua_tostring(L, -1));
4146 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4147 ServerActiveObject *digger)
4150 assert(lua_checkstack(L, 20));
4151 StackUnroller stack_unroller(L);
4153 INodeDefManager *ndef = get_server(L)->ndef();
4155 // Push callback function on stack
4156 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4161 pushnode(L, node, ndef);
4162 objectref_get_or_create(L, digger);
4163 if(lua_pcall(L, 3, 0, 0))
4164 script_error(L, "error: %s", lua_tostring(L, -1));
4172 void scriptapi_environment_step(lua_State *L, float dtime)
4175 assert(lua_checkstack(L, 20));
4176 //infostream<<"scriptapi_environment_step"<<std::endl;
4177 StackUnroller stack_unroller(L);
4179 // Get minetest.registered_globalsteps
4180 lua_getglobal(L, "minetest");
4181 lua_getfield(L, -1, "registered_globalsteps");
4182 luaL_checktype(L, -1, LUA_TTABLE);
4183 int table = lua_gettop(L);
4186 while(lua_next(L, table) != 0){
4187 // key at index -2 and value at index -1
4188 luaL_checktype(L, -1, LUA_TFUNCTION);
4190 lua_pushnumber(L, dtime);
4191 if(lua_pcall(L, 1, 0, 0))
4192 script_error(L, "error: %s", lua_tostring(L, -1));
4193 // value removed, keep key for next iteration
4197 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
4200 assert(lua_checkstack(L, 20));
4201 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4202 StackUnroller stack_unroller(L);
4204 // Get minetest.registered_on_generateds
4205 lua_getglobal(L, "minetest");
4206 lua_getfield(L, -1, "registered_on_generateds");
4207 luaL_checktype(L, -1, LUA_TTABLE);
4208 int table = lua_gettop(L);
4211 while(lua_next(L, table) != 0){
4212 // key at index -2 and value at index -1
4213 luaL_checktype(L, -1, LUA_TFUNCTION);
4215 push_v3s16(L, minp);
4216 push_v3s16(L, maxp);
4217 if(lua_pcall(L, 2, 0, 0))
4218 script_error(L, "error: %s", lua_tostring(L, -1));
4219 // value removed, keep key for next iteration
4227 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4230 assert(lua_checkstack(L, 20));
4231 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4232 <<name<<"\""<<std::endl;
4233 StackUnroller stack_unroller(L);
4235 // Get minetest.registered_entities[name]
4236 lua_getglobal(L, "minetest");
4237 lua_getfield(L, -1, "registered_entities");
4238 luaL_checktype(L, -1, LUA_TTABLE);
4239 lua_pushstring(L, name);
4240 lua_gettable(L, -2);
4241 // Should be a table, which we will use as a prototype
4242 //luaL_checktype(L, -1, LUA_TTABLE);
4243 if(lua_type(L, -1) != LUA_TTABLE){
4244 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4247 int prototype_table = lua_gettop(L);
4248 //dump2(L, "prototype_table");
4250 // Create entity object
4252 int object = lua_gettop(L);
4254 // Set object metatable
4255 lua_pushvalue(L, prototype_table);
4256 lua_setmetatable(L, -2);
4258 // Add object reference
4259 // This should be userdata with metatable ObjectRef
4260 objectref_get(L, id);
4261 luaL_checktype(L, -1, LUA_TUSERDATA);
4262 if(!luaL_checkudata(L, -1, "ObjectRef"))
4263 luaL_typerror(L, -1, "ObjectRef");
4264 lua_setfield(L, -2, "object");
4266 // minetest.luaentities[id] = object
4267 lua_getglobal(L, "minetest");
4268 lua_getfield(L, -1, "luaentities");
4269 luaL_checktype(L, -1, LUA_TTABLE);
4270 lua_pushnumber(L, id); // Push id
4271 lua_pushvalue(L, object); // Copy object to top of stack
4272 lua_settable(L, -3);
4277 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4278 const std::string &staticdata)
4281 assert(lua_checkstack(L, 20));
4282 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4283 StackUnroller stack_unroller(L);
4285 // Get minetest.luaentities[id]
4286 luaentity_get(L, id);
4287 int object = lua_gettop(L);
4289 // Get on_activate function
4290 lua_pushvalue(L, object);
4291 lua_getfield(L, -1, "on_activate");
4292 if(!lua_isnil(L, -1)){
4293 luaL_checktype(L, -1, LUA_TFUNCTION);
4294 lua_pushvalue(L, object); // self
4295 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4296 // Call with 2 arguments, 0 results
4297 if(lua_pcall(L, 2, 0, 0))
4298 script_error(L, "error running function on_activate: %s\n",
4299 lua_tostring(L, -1));
4303 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4306 assert(lua_checkstack(L, 20));
4307 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4309 // Get minetest.luaentities table
4310 lua_getglobal(L, "minetest");
4311 lua_getfield(L, -1, "luaentities");
4312 luaL_checktype(L, -1, LUA_TTABLE);
4313 int objectstable = lua_gettop(L);
4315 // Set luaentities[id] = nil
4316 lua_pushnumber(L, id); // Push id
4318 lua_settable(L, objectstable);
4320 lua_pop(L, 2); // pop luaentities, minetest
4323 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4326 assert(lua_checkstack(L, 20));
4327 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4328 StackUnroller stack_unroller(L);
4330 // Get minetest.luaentities[id]
4331 luaentity_get(L, id);
4332 int object = lua_gettop(L);
4334 // Get get_staticdata function
4335 lua_pushvalue(L, object);
4336 lua_getfield(L, -1, "get_staticdata");
4337 if(lua_isnil(L, -1))
4340 luaL_checktype(L, -1, LUA_TFUNCTION);
4341 lua_pushvalue(L, object); // self
4342 // Call with 1 arguments, 1 results
4343 if(lua_pcall(L, 1, 1, 0))
4344 script_error(L, "error running function get_staticdata: %s\n",
4345 lua_tostring(L, -1));
4348 const char *s = lua_tolstring(L, -1, &len);
4349 return std::string(s, len);
4352 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4353 LuaEntityProperties *prop)
4356 assert(lua_checkstack(L, 20));
4357 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4358 StackUnroller stack_unroller(L);
4360 // Get minetest.luaentities[id]
4361 luaentity_get(L, id);
4362 //int object = lua_gettop(L);
4366 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4368 getboolfield(L, -1, "physical", prop->physical);
4370 getfloatfield(L, -1, "weight", prop->weight);
4372 lua_getfield(L, -1, "collisionbox");
4373 if(lua_istable(L, -1))
4374 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4377 getstringfield(L, -1, "visual", prop->visual);
4379 lua_getfield(L, -1, "visual_size");
4380 if(lua_istable(L, -1))
4381 prop->visual_size = read_v2f(L, -1);
4384 lua_getfield(L, -1, "textures");
4385 if(lua_istable(L, -1)){
4386 prop->textures.clear();
4387 int table = lua_gettop(L);
4389 while(lua_next(L, table) != 0){
4390 // key at index -2 and value at index -1
4391 if(lua_isstring(L, -1))
4392 prop->textures.push_back(lua_tostring(L, -1));
4394 prop->textures.push_back("");
4395 // removes value, keeps key for next iteration
4401 lua_getfield(L, -1, "spritediv");
4402 if(lua_istable(L, -1))
4403 prop->spritediv = read_v2s16(L, -1);
4406 lua_getfield(L, -1, "initial_sprite_basepos");
4407 if(lua_istable(L, -1))
4408 prop->initial_sprite_basepos = read_v2s16(L, -1);
4412 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4415 assert(lua_checkstack(L, 20));
4416 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4417 StackUnroller stack_unroller(L);
4419 // Get minetest.luaentities[id]
4420 luaentity_get(L, id);
4421 int object = lua_gettop(L);
4422 // State: object is at top of stack
4423 // Get step function
4424 lua_getfield(L, -1, "on_step");
4425 if(lua_isnil(L, -1))
4427 luaL_checktype(L, -1, LUA_TFUNCTION);
4428 lua_pushvalue(L, object); // self
4429 lua_pushnumber(L, dtime); // dtime
4430 // Call with 2 arguments, 0 results
4431 if(lua_pcall(L, 2, 0, 0))
4432 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4435 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4436 // tool_capabilities, direction)
4437 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4438 ServerActiveObject *puncher, float time_from_last_punch,
4439 const ToolCapabilities *toolcap, v3f dir)
4442 assert(lua_checkstack(L, 20));
4443 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4444 StackUnroller stack_unroller(L);
4446 // Get minetest.luaentities[id]
4447 luaentity_get(L, id);
4448 int object = lua_gettop(L);
4449 // State: object is at top of stack
4451 lua_getfield(L, -1, "on_punch");
4452 if(lua_isnil(L, -1))
4454 luaL_checktype(L, -1, LUA_TFUNCTION);
4455 lua_pushvalue(L, object); // self
4456 objectref_get_or_create(L, puncher); // Clicker reference
4457 lua_pushnumber(L, time_from_last_punch);
4458 push_tool_capabilities(L, *toolcap);
4460 // Call with 5 arguments, 0 results
4461 if(lua_pcall(L, 5, 0, 0))
4462 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4465 // Calls entity:on_rightclick(ObjectRef clicker)
4466 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4467 ServerActiveObject *clicker)
4470 assert(lua_checkstack(L, 20));
4471 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4472 StackUnroller stack_unroller(L);
4474 // Get minetest.luaentities[id]
4475 luaentity_get(L, id);
4476 int object = lua_gettop(L);
4477 // State: object is at top of stack
4479 lua_getfield(L, -1, "on_rightclick");
4480 if(lua_isnil(L, -1))
4482 luaL_checktype(L, -1, LUA_TFUNCTION);
4483 lua_pushvalue(L, object); // self
4484 objectref_get_or_create(L, clicker); // Clicker reference
4485 // Call with 2 arguments, 0 results
4486 if(lua_pcall(L, 2, 0, 0))
4487 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));