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 SimpleSoundSpec read_soundspec(lua_State *L, int index)
817 index = lua_gettop(L) + 1 + index;
818 SimpleSoundSpec spec;
819 if(lua_isnil(L, index)){
820 } else if(lua_istable(L, index)){
821 getstringfield(L, index, "name", spec.name);
822 getfloatfield(L, index, "gain", spec.gain);
823 } else if(lua_isstring(L, index)){
824 spec.name = lua_tostring(L, index);
833 static ItemDefinition read_item_definition(lua_State *L, int index)
836 index = lua_gettop(L) + 1 + index;
838 // Read the item definition
841 def.type = (ItemType)getenumfield(L, index, "type",
842 es_ItemType, ITEM_NONE);
843 getstringfield(L, index, "name", def.name);
844 getstringfield(L, index, "description", def.description);
845 getstringfield(L, index, "inventory_image", def.inventory_image);
846 getstringfield(L, index, "wield_image", def.wield_image);
848 lua_getfield(L, index, "wield_scale");
849 if(lua_istable(L, -1)){
850 def.wield_scale = check_v3f(L, -1);
854 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
855 if(def.stack_max == 0)
858 lua_getfield(L, index, "on_use");
859 def.usable = lua_isfunction(L, -1);
862 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
864 warn_if_field_exists(L, index, "tool_digging_properties",
865 "deprecated: use tool_capabilities");
867 lua_getfield(L, index, "tool_capabilities");
868 if(lua_istable(L, -1)){
869 def.tool_capabilities = new ToolCapabilities(
870 read_tool_capabilities(L, -1));
873 // If name is "" (hand), ensure there are ToolCapabilities
874 // because it will be looked up there whenever any other item has
875 // no ToolCapabilities
876 if(def.name == "" && def.tool_capabilities == NULL){
877 def.tool_capabilities = new ToolCapabilities();
880 lua_getfield(L, index, "groups");
881 read_groups(L, -1, def.groups);
891 static ContentFeatures read_content_features(lua_State *L, int index)
894 index = lua_gettop(L) + 1 + index;
898 getstringfield(L, index, "name", f.name);
901 lua_getfield(L, index, "groups");
902 read_groups(L, -1, f.groups);
905 /* Visual definition */
907 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
909 getfloatfield(L, index, "visual_scale", f.visual_scale);
911 lua_getfield(L, index, "tile_images");
912 if(lua_istable(L, -1)){
913 int table = lua_gettop(L);
916 while(lua_next(L, table) != 0){
917 // key at index -2 and value at index -1
918 if(lua_isstring(L, -1))
919 f.tname_tiles[i] = lua_tostring(L, -1);
921 f.tname_tiles[i] = "";
922 // removes value, keeps key for next iteration
930 // Copy last value to all remaining textures
932 std::string lastname = f.tname_tiles[i-1];
934 f.tname_tiles[i] = lastname;
941 lua_getfield(L, index, "special_materials");
942 if(lua_istable(L, -1)){
943 int table = lua_gettop(L);
946 while(lua_next(L, table) != 0){
947 // key at index -2 and value at index -1
948 int smtable = lua_gettop(L);
949 std::string tname = getstringfield_default(
950 L, smtable, "image", "");
951 bool backface_culling = getboolfield_default(
952 L, smtable, "backface_culling", true);
953 MaterialSpec mspec(tname, backface_culling);
954 f.mspec_special[i] = mspec;
955 // removes value, keeps key for next iteration
966 f.alpha = getintfield_default(L, index, "alpha", 255);
970 lua_getfield(L, index, "post_effect_color");
971 if(!lua_isnil(L, -1))
972 f.post_effect_color = readARGB8(L, -1);
975 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
976 es_ContentParamType, CPT_NONE);
977 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
978 es_ContentParamType2, CPT2_NONE);
980 // Warn about some deprecated fields
981 warn_if_field_exists(L, index, "wall_mounted",
982 "deprecated: use paramtype2 = 'wallmounted'");
983 warn_if_field_exists(L, index, "light_propagates",
984 "deprecated: determined from paramtype");
985 warn_if_field_exists(L, index, "dug_item",
986 "deprecated: use 'drop' field");
987 warn_if_field_exists(L, index, "extra_dug_item",
988 "deprecated: use 'drop' field");
989 warn_if_field_exists(L, index, "extra_dug_item_rarity",
990 "deprecated: use 'drop' field");
992 // True for all ground-like things like stone and mud, false for eg. trees
993 getboolfield(L, index, "is_ground_content", f.is_ground_content);
994 f.light_propagates = (f.param_type == CPT_LIGHT);
995 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
996 // This is used for collision detection.
997 // Also for general solidness queries.
998 getboolfield(L, index, "walkable", f.walkable);
999 // Player can point to these
1000 getboolfield(L, index, "pointable", f.pointable);
1001 // Player can dig these
1002 getboolfield(L, index, "diggable", f.diggable);
1003 // Player can climb these
1004 getboolfield(L, index, "climbable", f.climbable);
1005 // Player can build on these
1006 getboolfield(L, index, "buildable_to", f.buildable_to);
1007 // Metadata name of node (eg. "furnace")
1008 getstringfield(L, index, "metadata_name", f.metadata_name);
1009 // Whether the node is non-liquid, source liquid or flowing liquid
1010 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1011 es_LiquidType, LIQUID_NONE);
1012 // If the content is liquid, this is the flowing version of the liquid.
1013 getstringfield(L, index, "liquid_alternative_flowing",
1014 f.liquid_alternative_flowing);
1015 // If the content is liquid, this is the source version of the liquid.
1016 getstringfield(L, index, "liquid_alternative_source",
1017 f.liquid_alternative_source);
1018 // Viscosity for fluid flow, ranging from 1 to 7, with
1019 // 1 giving almost instantaneous propagation and 7 being
1020 // the slowest possible
1021 f.liquid_viscosity = getintfield_default(L, index,
1022 "liquid_viscosity", f.liquid_viscosity);
1023 // Amount of light the node emits
1024 f.light_source = getintfield_default(L, index,
1025 "light_source", f.light_source);
1026 f.damage_per_second = getintfield_default(L, index,
1027 "damage_per_second", f.damage_per_second);
1029 lua_getfield(L, index, "selection_box");
1030 if(lua_istable(L, -1)){
1031 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1032 es_NodeBoxType, NODEBOX_REGULAR);
1034 lua_getfield(L, -1, "fixed");
1035 if(lua_istable(L, -1))
1036 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1039 lua_getfield(L, -1, "wall_top");
1040 if(lua_istable(L, -1))
1041 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1044 lua_getfield(L, -1, "wall_bottom");
1045 if(lua_istable(L, -1))
1046 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1049 lua_getfield(L, -1, "wall_side");
1050 if(lua_istable(L, -1))
1051 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1056 // Set to true if paramtype used to be 'facedir_simple'
1057 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1058 // Set to true if wall_mounted used to be set to true
1059 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1062 lua_getfield(L, index, "sounds");
1063 if(lua_istable(L, -1)){
1064 lua_getfield(L, -1, "footstep");
1065 f.sound_footstep = read_soundspec(L, -1);
1077 static ItemStack read_item(lua_State *L, int index);
1079 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1080 lua_State *L, int tableindex, int forcesize=-1)
1082 dstream<<"inventory_set_list_from_lua\n";
1084 tableindex = lua_gettop(L) + 1 + tableindex;
1085 // If nil, delete list
1086 if(lua_isnil(L, tableindex)){
1087 inv->deleteList(name);
1090 // Otherwise set list
1091 std::vector<ItemStack> items;
1092 luaL_checktype(L, tableindex, LUA_TTABLE);
1094 while(lua_next(L, tableindex) != 0){
1095 // key at index -2 and value at index -1
1096 items.push_back(read_item(L, -1));
1097 // removes value, keeps key for next iteration
1100 int listsize = (forcesize != -1) ? forcesize : items.size();
1101 InventoryList *invlist = inv->addList(name, listsize);
1103 for(std::vector<ItemStack>::const_iterator
1104 i = items.begin(); i != items.end(); i++){
1105 if(forcesize != -1 && index == forcesize)
1107 invlist->changeItem(index, *i);
1110 while(forcesize != -1 && index < forcesize){
1111 invlist->deleteItem(index);
1114 dstream<<"inventory_set_list_from_lua done\n";
1117 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1120 InventoryList *invlist = inv->getList(name);
1121 if(invlist == NULL){
1125 // Get the table insert function
1126 lua_getglobal(L, "table");
1127 lua_getfield(L, -1, "insert");
1128 int table_insert = lua_gettop(L);
1129 // Create and fill table
1131 int table = lua_gettop(L);
1132 for(u32 i=0; i<invlist->getSize(); i++){
1133 ItemStack item = invlist->getItem(i);
1134 lua_pushvalue(L, table_insert);
1135 lua_pushvalue(L, table);
1136 lua_pushstring(L, item.getItemString().c_str());
1137 if(lua_pcall(L, 2, 0, 0))
1138 script_error(L, "error: %s", lua_tostring(L, -1));
1143 Helpful macros for userdata classes
1146 #define method(class, name) {#name, class::l_##name}
1157 static const char className[];
1158 static const luaL_reg methods[];
1160 // Exported functions
1162 // garbage collector
1163 static int gc_object(lua_State *L)
1165 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1170 // is_empty(self) -> true/false
1171 static int l_is_empty(lua_State *L)
1173 LuaItemStack *o = checkobject(L, 1);
1174 ItemStack &item = o->m_stack;
1175 lua_pushboolean(L, item.empty());
1179 // get_name(self) -> string
1180 static int l_get_name(lua_State *L)
1182 LuaItemStack *o = checkobject(L, 1);
1183 ItemStack &item = o->m_stack;
1184 lua_pushstring(L, item.name.c_str());
1188 // get_count(self) -> number
1189 static int l_get_count(lua_State *L)
1191 LuaItemStack *o = checkobject(L, 1);
1192 ItemStack &item = o->m_stack;
1193 lua_pushinteger(L, item.count);
1197 // get_wear(self) -> number
1198 static int l_get_wear(lua_State *L)
1200 LuaItemStack *o = checkobject(L, 1);
1201 ItemStack &item = o->m_stack;
1202 lua_pushinteger(L, item.wear);
1206 // get_metadata(self) -> string
1207 static int l_get_metadata(lua_State *L)
1209 LuaItemStack *o = checkobject(L, 1);
1210 ItemStack &item = o->m_stack;
1211 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1215 // clear(self) -> true
1216 static int l_clear(lua_State *L)
1218 LuaItemStack *o = checkobject(L, 1);
1220 lua_pushboolean(L, true);
1224 // replace(self, itemstack or itemstring or table or nil) -> true
1225 static int l_replace(lua_State *L)
1227 LuaItemStack *o = checkobject(L, 1);
1228 o->m_stack = read_item(L, 2);
1229 lua_pushboolean(L, true);
1233 // to_string(self) -> string
1234 static int l_to_string(lua_State *L)
1236 LuaItemStack *o = checkobject(L, 1);
1237 std::string itemstring = o->m_stack.getItemString();
1238 lua_pushstring(L, itemstring.c_str());
1242 // to_table(self) -> table or nil
1243 static int l_to_table(lua_State *L)
1245 LuaItemStack *o = checkobject(L, 1);
1246 const ItemStack &item = o->m_stack;
1254 lua_pushstring(L, item.name.c_str());
1255 lua_setfield(L, -2, "name");
1256 lua_pushinteger(L, item.count);
1257 lua_setfield(L, -2, "count");
1258 lua_pushinteger(L, item.wear);
1259 lua_setfield(L, -2, "wear");
1260 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1261 lua_setfield(L, -2, "metadata");
1266 // get_stack_max(self) -> number
1267 static int l_get_stack_max(lua_State *L)
1269 LuaItemStack *o = checkobject(L, 1);
1270 ItemStack &item = o->m_stack;
1271 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1275 // get_free_space(self) -> number
1276 static int l_get_free_space(lua_State *L)
1278 LuaItemStack *o = checkobject(L, 1);
1279 ItemStack &item = o->m_stack;
1280 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1284 // is_known(self) -> true/false
1285 // Checks if the item is defined.
1286 static int l_is_known(lua_State *L)
1288 LuaItemStack *o = checkobject(L, 1);
1289 ItemStack &item = o->m_stack;
1290 bool is_known = item.isKnown(get_server(L)->idef());
1291 lua_pushboolean(L, is_known);
1295 // get_definition(self) -> table
1296 // Returns the item definition table from minetest.registered_items,
1297 // or a fallback one (name="unknown")
1298 static int l_get_definition(lua_State *L)
1300 LuaItemStack *o = checkobject(L, 1);
1301 ItemStack &item = o->m_stack;
1303 // Get minetest.registered_items[name]
1304 lua_getglobal(L, "minetest");
1305 lua_getfield(L, -1, "registered_items");
1306 luaL_checktype(L, -1, LUA_TTABLE);
1307 lua_getfield(L, -1, item.name.c_str());
1308 if(lua_isnil(L, -1))
1311 lua_getfield(L, -1, "unknown");
1316 // get_tool_capabilities(self) -> table
1317 // Returns the effective tool digging properties.
1318 // Returns those of the hand ("") if this item has none associated.
1319 static int l_get_tool_capabilities(lua_State *L)
1321 LuaItemStack *o = checkobject(L, 1);
1322 ItemStack &item = o->m_stack;
1323 const ToolCapabilities &prop =
1324 item.getToolCapabilities(get_server(L)->idef());
1325 push_tool_capabilities(L, prop);
1329 // add_wear(self, amount) -> true/false
1330 // The range for "amount" is [0,65535]. Wear is only added if the item
1331 // is a tool. Adding wear might destroy the item.
1332 // Returns true if the item is (or was) a tool.
1333 static int l_add_wear(lua_State *L)
1335 LuaItemStack *o = checkobject(L, 1);
1336 ItemStack &item = o->m_stack;
1337 int amount = lua_tointeger(L, 2);
1338 bool result = item.addWear(amount, get_server(L)->idef());
1339 lua_pushboolean(L, result);
1343 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1344 // Returns leftover item stack
1345 static int l_add_item(lua_State *L)
1347 LuaItemStack *o = checkobject(L, 1);
1348 ItemStack &item = o->m_stack;
1349 ItemStack newitem = read_item(L, 2);
1350 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1351 create(L, leftover);
1355 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1356 // First return value is true iff the new item fits fully into the stack
1357 // Second return value is the would-be-left-over item stack
1358 static int l_item_fits(lua_State *L)
1360 LuaItemStack *o = checkobject(L, 1);
1361 ItemStack &item = o->m_stack;
1362 ItemStack newitem = read_item(L, 2);
1364 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1365 lua_pushboolean(L, fits); // first return value
1366 create(L, restitem); // second return value
1370 // take_item(self, takecount=1) -> itemstack
1371 static int l_take_item(lua_State *L)
1373 LuaItemStack *o = checkobject(L, 1);
1374 ItemStack &item = o->m_stack;
1376 if(!lua_isnone(L, 2))
1377 takecount = lua_tointeger(L, 2);
1378 ItemStack taken = item.takeItem(takecount);
1383 // peek_item(self, peekcount=1) -> itemstack
1384 static int l_peek_item(lua_State *L)
1386 LuaItemStack *o = checkobject(L, 1);
1387 ItemStack &item = o->m_stack;
1389 if(!lua_isnone(L, 2))
1390 peekcount = lua_tointeger(L, 2);
1391 ItemStack peekaboo = item.peekItem(peekcount);
1392 create(L, peekaboo);
1397 LuaItemStack(const ItemStack &item):
1406 const ItemStack& getItem() const
1410 ItemStack& getItem()
1415 // LuaItemStack(itemstack or itemstring or table or nil)
1416 // Creates an LuaItemStack and leaves it on top of stack
1417 static int create_object(lua_State *L)
1419 ItemStack item = read_item(L, 1);
1420 LuaItemStack *o = new LuaItemStack(item);
1421 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1422 luaL_getmetatable(L, className);
1423 lua_setmetatable(L, -2);
1426 // Not callable from Lua
1427 static int create(lua_State *L, const ItemStack &item)
1429 LuaItemStack *o = new LuaItemStack(item);
1430 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1431 luaL_getmetatable(L, className);
1432 lua_setmetatable(L, -2);
1436 static LuaItemStack* checkobject(lua_State *L, int narg)
1438 luaL_checktype(L, narg, LUA_TUSERDATA);
1439 void *ud = luaL_checkudata(L, narg, className);
1440 if(!ud) luaL_typerror(L, narg, className);
1441 return *(LuaItemStack**)ud; // unbox pointer
1444 static void Register(lua_State *L)
1447 int methodtable = lua_gettop(L);
1448 luaL_newmetatable(L, className);
1449 int metatable = lua_gettop(L);
1451 lua_pushliteral(L, "__metatable");
1452 lua_pushvalue(L, methodtable);
1453 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1455 lua_pushliteral(L, "__index");
1456 lua_pushvalue(L, methodtable);
1457 lua_settable(L, metatable);
1459 lua_pushliteral(L, "__gc");
1460 lua_pushcfunction(L, gc_object);
1461 lua_settable(L, metatable);
1463 lua_pop(L, 1); // drop metatable
1465 luaL_openlib(L, 0, methods, 0); // fill methodtable
1466 lua_pop(L, 1); // drop methodtable
1468 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1469 lua_register(L, className, create_object);
1472 const char LuaItemStack::className[] = "ItemStack";
1473 const luaL_reg LuaItemStack::methods[] = {
1474 method(LuaItemStack, is_empty),
1475 method(LuaItemStack, get_name),
1476 method(LuaItemStack, get_count),
1477 method(LuaItemStack, get_wear),
1478 method(LuaItemStack, get_metadata),
1479 method(LuaItemStack, clear),
1480 method(LuaItemStack, replace),
1481 method(LuaItemStack, to_string),
1482 method(LuaItemStack, to_table),
1483 method(LuaItemStack, get_stack_max),
1484 method(LuaItemStack, get_free_space),
1485 method(LuaItemStack, is_known),
1486 method(LuaItemStack, get_definition),
1487 method(LuaItemStack, get_tool_capabilities),
1488 method(LuaItemStack, add_wear),
1489 method(LuaItemStack, add_item),
1490 method(LuaItemStack, item_fits),
1491 method(LuaItemStack, take_item),
1492 method(LuaItemStack, peek_item),
1496 static ItemStack read_item(lua_State *L, int index)
1499 index = lua_gettop(L) + 1 + index;
1501 if(lua_isnil(L, index))
1505 else if(lua_isuserdata(L, index))
1507 // Convert from LuaItemStack
1508 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1509 return o->getItem();
1511 else if(lua_isstring(L, index))
1513 // Convert from itemstring
1514 std::string itemstring = lua_tostring(L, index);
1515 IItemDefManager *idef = get_server(L)->idef();
1519 item.deSerialize(itemstring, idef);
1522 catch(SerializationError &e)
1524 infostream<<"WARNING: unable to create item from itemstring"
1525 <<": "<<itemstring<<std::endl;
1529 else if(lua_istable(L, index))
1531 // Convert from table
1532 IItemDefManager *idef = get_server(L)->idef();
1533 std::string name = getstringfield_default(L, index, "name", "");
1534 int count = getintfield_default(L, index, "count", 1);
1535 int wear = getintfield_default(L, index, "wear", 0);
1536 std::string metadata = getstringfield_default(L, index, "metadata", "");
1537 return ItemStack(name, count, wear, metadata, idef);
1541 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1552 InventoryLocation m_loc;
1554 static const char className[];
1555 static const luaL_reg methods[];
1557 static InvRef *checkobject(lua_State *L, int narg)
1559 luaL_checktype(L, narg, LUA_TUSERDATA);
1560 void *ud = luaL_checkudata(L, narg, className);
1561 if(!ud) luaL_typerror(L, narg, className);
1562 return *(InvRef**)ud; // unbox pointer
1565 static Inventory* getinv(lua_State *L, InvRef *ref)
1567 return get_server(L)->getInventory(ref->m_loc);
1570 static InventoryList* getlist(lua_State *L, InvRef *ref,
1571 const char *listname)
1573 Inventory *inv = getinv(L, ref);
1576 return inv->getList(listname);
1579 static void reportInventoryChange(lua_State *L, InvRef *ref)
1581 // Inform other things that the inventory has changed
1582 get_server(L)->setInventoryModified(ref->m_loc);
1585 // Exported functions
1587 // garbage collector
1588 static int gc_object(lua_State *L) {
1589 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1594 // get_size(self, listname)
1595 static int l_get_size(lua_State *L)
1597 InvRef *ref = checkobject(L, 1);
1598 const char *listname = luaL_checkstring(L, 2);
1599 InventoryList *list = getlist(L, ref, listname);
1601 lua_pushinteger(L, list->getSize());
1603 lua_pushinteger(L, 0);
1608 // set_size(self, listname, size)
1609 static int l_set_size(lua_State *L)
1611 InvRef *ref = checkobject(L, 1);
1612 const char *listname = luaL_checkstring(L, 2);
1613 int newsize = luaL_checknumber(L, 3);
1614 Inventory *inv = getinv(L, ref);
1616 inv->deleteList(listname);
1617 reportInventoryChange(L, ref);
1620 InventoryList *list = inv->getList(listname);
1622 list->setSize(newsize);
1624 list = inv->addList(listname, newsize);
1626 reportInventoryChange(L, ref);
1630 // get_stack(self, listname, i) -> itemstack
1631 static int l_get_stack(lua_State *L)
1633 InvRef *ref = checkobject(L, 1);
1634 const char *listname = luaL_checkstring(L, 2);
1635 int i = luaL_checknumber(L, 3) - 1;
1636 InventoryList *list = getlist(L, ref, listname);
1638 if(list != NULL && i >= 0 && i < (int) list->getSize())
1639 item = list->getItem(i);
1640 LuaItemStack::create(L, item);
1644 // set_stack(self, listname, i, stack) -> true/false
1645 static int l_set_stack(lua_State *L)
1647 InvRef *ref = checkobject(L, 1);
1648 const char *listname = luaL_checkstring(L, 2);
1649 int i = luaL_checknumber(L, 3) - 1;
1650 ItemStack newitem = read_item(L, 4);
1651 InventoryList *list = getlist(L, ref, listname);
1652 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1653 list->changeItem(i, newitem);
1654 reportInventoryChange(L, ref);
1655 lua_pushboolean(L, true);
1657 lua_pushboolean(L, false);
1662 // get_list(self, listname) -> list or nil
1663 static int l_get_list(lua_State *L)
1665 InvRef *ref = checkobject(L, 1);
1666 const char *listname = luaL_checkstring(L, 2);
1667 Inventory *inv = getinv(L, ref);
1668 inventory_get_list_to_lua(inv, listname, L);
1672 // set_list(self, listname, list)
1673 static int l_set_list(lua_State *L)
1675 InvRef *ref = checkobject(L, 1);
1676 const char *listname = luaL_checkstring(L, 2);
1677 Inventory *inv = getinv(L, ref);
1678 InventoryList *list = inv->getList(listname);
1680 inventory_set_list_from_lua(inv, listname, L, 3,
1683 inventory_set_list_from_lua(inv, listname, L, 3);
1684 reportInventoryChange(L, ref);
1688 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1689 // Returns the leftover stack
1690 static int l_add_item(lua_State *L)
1692 InvRef *ref = checkobject(L, 1);
1693 const char *listname = luaL_checkstring(L, 2);
1694 ItemStack item = read_item(L, 3);
1695 InventoryList *list = getlist(L, ref, listname);
1697 ItemStack leftover = list->addItem(item);
1698 if(leftover.count != item.count)
1699 reportInventoryChange(L, ref);
1700 LuaItemStack::create(L, leftover);
1702 LuaItemStack::create(L, item);
1707 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1708 // Returns true if the item completely fits into the list
1709 static int l_room_for_item(lua_State *L)
1711 InvRef *ref = checkobject(L, 1);
1712 const char *listname = luaL_checkstring(L, 2);
1713 ItemStack item = read_item(L, 3);
1714 InventoryList *list = getlist(L, ref, listname);
1716 lua_pushboolean(L, list->roomForItem(item));
1718 lua_pushboolean(L, false);
1723 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1724 // Returns true if the list contains the given count of the given item name
1725 static int l_contains_item(lua_State *L)
1727 InvRef *ref = checkobject(L, 1);
1728 const char *listname = luaL_checkstring(L, 2);
1729 ItemStack item = read_item(L, 3);
1730 InventoryList *list = getlist(L, ref, listname);
1732 lua_pushboolean(L, list->containsItem(item));
1734 lua_pushboolean(L, false);
1739 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1740 // Returns the items that were actually removed
1741 static int l_remove_item(lua_State *L)
1743 InvRef *ref = checkobject(L, 1);
1744 const char *listname = luaL_checkstring(L, 2);
1745 ItemStack item = read_item(L, 3);
1746 InventoryList *list = getlist(L, ref, listname);
1748 ItemStack removed = list->removeItem(item);
1749 if(!removed.empty())
1750 reportInventoryChange(L, ref);
1751 LuaItemStack::create(L, removed);
1753 LuaItemStack::create(L, ItemStack());
1759 InvRef(const InventoryLocation &loc):
1768 // Creates an InvRef and leaves it on top of stack
1769 // Not callable from Lua; all references are created on the C side.
1770 static void create(lua_State *L, const InventoryLocation &loc)
1772 InvRef *o = new InvRef(loc);
1773 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1774 luaL_getmetatable(L, className);
1775 lua_setmetatable(L, -2);
1777 static void createPlayer(lua_State *L, Player *player)
1779 InventoryLocation loc;
1780 loc.setPlayer(player->getName());
1783 static void createNodeMeta(lua_State *L, v3s16 p)
1785 InventoryLocation loc;
1790 static void Register(lua_State *L)
1793 int methodtable = lua_gettop(L);
1794 luaL_newmetatable(L, className);
1795 int metatable = lua_gettop(L);
1797 lua_pushliteral(L, "__metatable");
1798 lua_pushvalue(L, methodtable);
1799 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1801 lua_pushliteral(L, "__index");
1802 lua_pushvalue(L, methodtable);
1803 lua_settable(L, metatable);
1805 lua_pushliteral(L, "__gc");
1806 lua_pushcfunction(L, gc_object);
1807 lua_settable(L, metatable);
1809 lua_pop(L, 1); // drop metatable
1811 luaL_openlib(L, 0, methods, 0); // fill methodtable
1812 lua_pop(L, 1); // drop methodtable
1814 // Cannot be created from Lua
1815 //lua_register(L, className, create_object);
1818 const char InvRef::className[] = "InvRef";
1819 const luaL_reg InvRef::methods[] = {
1820 method(InvRef, get_size),
1821 method(InvRef, set_size),
1822 method(InvRef, get_stack),
1823 method(InvRef, set_stack),
1824 method(InvRef, get_list),
1825 method(InvRef, set_list),
1826 method(InvRef, add_item),
1827 method(InvRef, room_for_item),
1828 method(InvRef, contains_item),
1829 method(InvRef, remove_item),
1841 ServerEnvironment *m_env;
1843 static const char className[];
1844 static const luaL_reg methods[];
1846 static NodeMetaRef *checkobject(lua_State *L, int narg)
1848 luaL_checktype(L, narg, LUA_TUSERDATA);
1849 void *ud = luaL_checkudata(L, narg, className);
1850 if(!ud) luaL_typerror(L, narg, className);
1851 return *(NodeMetaRef**)ud; // unbox pointer
1854 static NodeMetadata* getmeta(NodeMetaRef *ref)
1856 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1860 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1862 NodeMetadata *meta = getmeta(ref);
1865 if(meta->typeId() != NODEMETA_GENERIC)
1867 return (IGenericNodeMetadata*)meta;
1870 static void reportMetadataChange(NodeMetaRef *ref)
1872 // Inform other things that the metadata has changed
1873 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1875 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1877 ref->m_env->getMap().dispatchEvent(&event);
1878 // Set the block to be saved
1879 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1881 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1882 "NodeMetaRef::reportMetadataChange");
1885 // Exported functions
1887 // garbage collector
1888 static int gc_object(lua_State *L) {
1889 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1895 static int l_get_type(lua_State *L)
1897 NodeMetaRef *ref = checkobject(L, 1);
1898 NodeMetadata *meta = getmeta(ref);
1904 lua_pushstring(L, meta->typeName());
1908 // allows_text_input(self)
1909 static int l_allows_text_input(lua_State *L)
1911 NodeMetaRef *ref = checkobject(L, 1);
1912 NodeMetadata *meta = getmeta(ref);
1913 if(meta == NULL) return 0;
1915 lua_pushboolean(L, meta->allowsTextInput());
1919 // set_text(self, text)
1920 static int l_set_text(lua_State *L)
1922 NodeMetaRef *ref = checkobject(L, 1);
1923 NodeMetadata *meta = getmeta(ref);
1924 if(meta == NULL) return 0;
1926 std::string text = luaL_checkstring(L, 2);
1927 meta->setText(text);
1928 reportMetadataChange(ref);
1933 static int l_get_text(lua_State *L)
1935 NodeMetaRef *ref = checkobject(L, 1);
1936 NodeMetadata *meta = getmeta(ref);
1937 if(meta == NULL) return 0;
1939 std::string text = meta->getText();
1940 lua_pushstring(L, text.c_str());
1945 static int l_get_owner(lua_State *L)
1947 NodeMetaRef *ref = checkobject(L, 1);
1948 NodeMetadata *meta = getmeta(ref);
1949 if(meta == NULL) return 0;
1951 std::string owner = meta->getOwner();
1952 lua_pushstring(L, owner.c_str());
1956 // set_owner(self, string)
1957 static int l_set_owner(lua_State *L)
1959 NodeMetaRef *ref = checkobject(L, 1);
1960 NodeMetadata *meta = getmeta(ref);
1961 if(meta == NULL) return 0;
1963 std::string owner = luaL_checkstring(L, 2);
1964 meta->setOwner(owner);
1965 reportMetadataChange(ref);
1969 // get_allow_removal(self)
1970 static int l_get_allow_removal(lua_State *L)
1972 NodeMetaRef *ref = checkobject(L, 1);
1973 NodeMetadata *meta = getmeta(ref);
1975 lua_pushboolean(L, true);
1979 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1983 /* IGenericNodeMetadata interface */
1985 // set_infotext(self, text)
1986 static int l_set_infotext(lua_State *L)
1988 NodeMetaRef *ref = checkobject(L, 1);
1989 NodeMetadata *meta = getmeta(ref);
1990 if(meta == NULL) return 0;
1992 std::string text = luaL_checkstring(L, 2);
1993 meta->setInfoText(text);
1994 reportMetadataChange(ref);
1998 // get_inventory(self)
1999 static int l_get_inventory(lua_State *L)
2001 NodeMetaRef *ref = checkobject(L, 1);
2002 NodeMetadata *meta = getmeta(ref);
2003 if(meta == NULL) return 0;
2005 InvRef::createNodeMeta(L, ref->m_p);
2009 // set_inventory_draw_spec(self, text)
2010 static int l_set_inventory_draw_spec(lua_State *L)
2012 NodeMetaRef *ref = checkobject(L, 1);
2013 NodeMetadata *meta = getmeta(ref);
2014 if(meta == NULL) return 0;
2016 std::string text = luaL_checkstring(L, 2);
2017 meta->setInventoryDrawSpec(text);
2018 reportMetadataChange(ref);
2022 // set_allow_text_input(self, text)
2023 static int l_set_allow_text_input(lua_State *L)
2025 NodeMetaRef *ref = checkobject(L, 1);
2026 NodeMetadata *meta = getmeta(ref);
2027 if(meta == NULL) return 0;
2029 bool b = lua_toboolean(L, 2);
2030 meta->setAllowTextInput(b);
2031 reportMetadataChange(ref);
2035 // set_allow_removal(self, text)
2036 static int l_set_allow_removal(lua_State *L)
2038 NodeMetaRef *ref = checkobject(L, 1);
2039 NodeMetadata *meta = getmeta(ref);
2040 if(meta == NULL) return 0;
2042 bool b = lua_toboolean(L, 2);
2043 meta->setRemovalDisabled(!b);
2044 reportMetadataChange(ref);
2048 // set_enforce_owner(self, text)
2049 static int l_set_enforce_owner(lua_State *L)
2051 NodeMetaRef *ref = checkobject(L, 1);
2052 NodeMetadata *meta = getmeta(ref);
2053 if(meta == NULL) return 0;
2055 bool b = lua_toboolean(L, 2);
2056 meta->setEnforceOwner(b);
2057 reportMetadataChange(ref);
2061 // is_inventory_modified(self)
2062 static int l_is_inventory_modified(lua_State *L)
2064 NodeMetaRef *ref = checkobject(L, 1);
2065 NodeMetadata *meta = getmeta(ref);
2066 if(meta == NULL) return 0;
2068 lua_pushboolean(L, meta->isInventoryModified());
2072 // reset_inventory_modified(self)
2073 static int l_reset_inventory_modified(lua_State *L)
2075 NodeMetaRef *ref = checkobject(L, 1);
2076 NodeMetadata *meta = getmeta(ref);
2077 if(meta == NULL) return 0;
2079 meta->resetInventoryModified();
2080 reportMetadataChange(ref);
2084 // is_text_modified(self)
2085 static int l_is_text_modified(lua_State *L)
2087 NodeMetaRef *ref = checkobject(L, 1);
2088 NodeMetadata *meta = getmeta(ref);
2089 if(meta == NULL) return 0;
2091 lua_pushboolean(L, meta->isTextModified());
2095 // reset_text_modified(self)
2096 static int l_reset_text_modified(lua_State *L)
2098 NodeMetaRef *ref = checkobject(L, 1);
2099 NodeMetadata *meta = getmeta(ref);
2100 if(meta == NULL) return 0;
2102 meta->resetTextModified();
2103 reportMetadataChange(ref);
2107 // set_string(self, name, var)
2108 static int l_set_string(lua_State *L)
2110 NodeMetaRef *ref = checkobject(L, 1);
2111 NodeMetadata *meta = getmeta(ref);
2112 if(meta == NULL) return 0;
2114 std::string name = luaL_checkstring(L, 2);
2116 const char *s = lua_tolstring(L, 3, &len);
2117 std::string str(s, len);
2118 meta->setString(name, str);
2119 reportMetadataChange(ref);
2123 // get_string(self, name)
2124 static int l_get_string(lua_State *L)
2126 NodeMetaRef *ref = checkobject(L, 1);
2127 NodeMetadata *meta = getmeta(ref);
2128 if(meta == NULL) return 0;
2130 std::string name = luaL_checkstring(L, 2);
2131 std::string str = meta->getString(name);
2132 lua_pushlstring(L, str.c_str(), str.size());
2137 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2147 // Creates an NodeMetaRef and leaves it on top of stack
2148 // Not callable from Lua; all references are created on the C side.
2149 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2151 NodeMetaRef *o = new NodeMetaRef(p, env);
2152 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2153 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2154 luaL_getmetatable(L, className);
2155 lua_setmetatable(L, -2);
2158 static void Register(lua_State *L)
2161 int methodtable = lua_gettop(L);
2162 luaL_newmetatable(L, className);
2163 int metatable = lua_gettop(L);
2165 lua_pushliteral(L, "__metatable");
2166 lua_pushvalue(L, methodtable);
2167 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2169 lua_pushliteral(L, "__index");
2170 lua_pushvalue(L, methodtable);
2171 lua_settable(L, metatable);
2173 lua_pushliteral(L, "__gc");
2174 lua_pushcfunction(L, gc_object);
2175 lua_settable(L, metatable);
2177 lua_pop(L, 1); // drop metatable
2179 luaL_openlib(L, 0, methods, 0); // fill methodtable
2180 lua_pop(L, 1); // drop methodtable
2182 // Cannot be created from Lua
2183 //lua_register(L, className, create_object);
2186 const char NodeMetaRef::className[] = "NodeMetaRef";
2187 const luaL_reg NodeMetaRef::methods[] = {
2188 method(NodeMetaRef, get_type),
2189 method(NodeMetaRef, allows_text_input),
2190 method(NodeMetaRef, set_text),
2191 method(NodeMetaRef, get_text),
2192 method(NodeMetaRef, get_owner),
2193 method(NodeMetaRef, set_owner),
2194 method(NodeMetaRef, get_allow_removal),
2195 method(NodeMetaRef, set_infotext),
2196 method(NodeMetaRef, get_inventory),
2197 method(NodeMetaRef, set_inventory_draw_spec),
2198 method(NodeMetaRef, set_allow_text_input),
2199 method(NodeMetaRef, set_allow_removal),
2200 method(NodeMetaRef, set_enforce_owner),
2201 method(NodeMetaRef, is_inventory_modified),
2202 method(NodeMetaRef, reset_inventory_modified),
2203 method(NodeMetaRef, is_text_modified),
2204 method(NodeMetaRef, reset_text_modified),
2205 method(NodeMetaRef, set_string),
2206 method(NodeMetaRef, get_string),
2217 ServerActiveObject *m_object;
2219 static const char className[];
2220 static const luaL_reg methods[];
2222 static ObjectRef *checkobject(lua_State *L, int narg)
2224 luaL_checktype(L, narg, LUA_TUSERDATA);
2225 void *ud = luaL_checkudata(L, narg, className);
2226 if(!ud) luaL_typerror(L, narg, className);
2227 return *(ObjectRef**)ud; // unbox pointer
2230 static ServerActiveObject* getobject(ObjectRef *ref)
2232 ServerActiveObject *co = ref->m_object;
2236 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2238 ServerActiveObject *obj = getobject(ref);
2241 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2243 return (LuaEntitySAO*)obj;
2246 static ServerRemotePlayer* getplayer(ObjectRef *ref)
2248 ServerActiveObject *obj = getobject(ref);
2251 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2253 return static_cast<ServerRemotePlayer*>(obj);
2256 // Exported functions
2258 // garbage collector
2259 static int gc_object(lua_State *L) {
2260 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2261 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2267 static int l_remove(lua_State *L)
2269 ObjectRef *ref = checkobject(L, 1);
2270 ServerActiveObject *co = getobject(ref);
2271 if(co == NULL) return 0;
2272 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2273 co->m_removed = true;
2278 // returns: {x=num, y=num, z=num}
2279 static int l_getpos(lua_State *L)
2281 ObjectRef *ref = checkobject(L, 1);
2282 ServerActiveObject *co = getobject(ref);
2283 if(co == NULL) return 0;
2284 v3f pos = co->getBasePosition() / BS;
2286 lua_pushnumber(L, pos.X);
2287 lua_setfield(L, -2, "x");
2288 lua_pushnumber(L, pos.Y);
2289 lua_setfield(L, -2, "y");
2290 lua_pushnumber(L, pos.Z);
2291 lua_setfield(L, -2, "z");
2295 // setpos(self, pos)
2296 static int l_setpos(lua_State *L)
2298 ObjectRef *ref = checkobject(L, 1);
2299 //LuaEntitySAO *co = getluaobject(ref);
2300 ServerActiveObject *co = getobject(ref);
2301 if(co == NULL) return 0;
2303 v3f pos = checkFloatPos(L, 2);
2306 // Move player if applicable
2307 ServerRemotePlayer *player = getplayer(ref);
2309 get_server(L)->SendMovePlayer(player);
2313 // moveto(self, pos, continuous=false)
2314 static int l_moveto(lua_State *L)
2316 ObjectRef *ref = checkobject(L, 1);
2317 //LuaEntitySAO *co = getluaobject(ref);
2318 ServerActiveObject *co = getobject(ref);
2319 if(co == NULL) return 0;
2321 v3f pos = checkFloatPos(L, 2);
2323 bool continuous = lua_toboolean(L, 3);
2325 co->moveTo(pos, continuous);
2329 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2330 static int l_punch(lua_State *L)
2332 ObjectRef *ref = checkobject(L, 1);
2333 ObjectRef *puncher_ref = checkobject(L, 2);
2334 ServerActiveObject *co = getobject(ref);
2335 ServerActiveObject *puncher = getobject(puncher_ref);
2336 if(co == NULL) return 0;
2337 if(puncher == NULL) return 0;
2338 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2339 v3f dir = read_v3f(L, 4);
2340 float time_from_last_punch = 1000000;
2341 if(lua_isnumber(L, 5))
2342 time_from_last_punch = lua_tonumber(L, 5);
2344 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2348 // right_click(self, clicker); clicker = an another ObjectRef
2349 static int l_right_click(lua_State *L)
2351 ObjectRef *ref = checkobject(L, 1);
2352 ObjectRef *ref2 = checkobject(L, 2);
2353 ServerActiveObject *co = getobject(ref);
2354 ServerActiveObject *co2 = getobject(ref2);
2355 if(co == NULL) return 0;
2356 if(co2 == NULL) return 0;
2358 co->rightClick(co2);
2363 // hp = number of hitpoints (2 * number of hearts)
2365 static int l_set_hp(lua_State *L)
2367 ObjectRef *ref = checkobject(L, 1);
2368 luaL_checknumber(L, 2);
2369 ServerActiveObject *co = getobject(ref);
2370 if(co == NULL) return 0;
2371 int hp = lua_tonumber(L, 2);
2372 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2373 <<" hp="<<hp<<std::endl;*/
2381 // returns: number of hitpoints (2 * number of hearts)
2382 // 0 if not applicable to this type of object
2383 static int l_get_hp(lua_State *L)
2385 ObjectRef *ref = checkobject(L, 1);
2386 ServerActiveObject *co = getobject(ref);
2387 if(co == NULL) return 0;
2388 int hp = co->getHP();
2389 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2390 <<" hp="<<hp<<std::endl;*/
2392 lua_pushnumber(L, hp);
2396 // get_inventory(self)
2397 static int l_get_inventory(lua_State *L)
2399 ObjectRef *ref = checkobject(L, 1);
2400 ServerActiveObject *co = getobject(ref);
2401 if(co == NULL) return 0;
2403 InventoryLocation loc = co->getInventoryLocation();
2404 if(get_server(L)->getInventory(loc) != NULL)
2405 InvRef::create(L, loc);
2411 // get_wield_list(self)
2412 static int l_get_wield_list(lua_State *L)
2414 ObjectRef *ref = checkobject(L, 1);
2415 ServerActiveObject *co = getobject(ref);
2416 if(co == NULL) return 0;
2418 lua_pushstring(L, co->getWieldList().c_str());
2422 // get_wield_index(self)
2423 static int l_get_wield_index(lua_State *L)
2425 ObjectRef *ref = checkobject(L, 1);
2426 ServerActiveObject *co = getobject(ref);
2427 if(co == NULL) return 0;
2429 lua_pushinteger(L, co->getWieldIndex() + 1);
2433 // get_wielded_item(self)
2434 static int l_get_wielded_item(lua_State *L)
2436 ObjectRef *ref = checkobject(L, 1);
2437 ServerActiveObject *co = getobject(ref);
2438 if(co == NULL) return 0;
2440 LuaItemStack::create(L, co->getWieldedItem());
2444 // set_wielded_item(self, itemstack or itemstring or table or nil)
2445 static int l_set_wielded_item(lua_State *L)
2447 ObjectRef *ref = checkobject(L, 1);
2448 ServerActiveObject *co = getobject(ref);
2449 if(co == NULL) return 0;
2451 ItemStack item = read_item(L, 2);
2452 bool success = co->setWieldedItem(item);
2453 lua_pushboolean(L, success);
2457 /* LuaEntitySAO-only */
2459 // setvelocity(self, {x=num, y=num, z=num})
2460 static int l_setvelocity(lua_State *L)
2462 ObjectRef *ref = checkobject(L, 1);
2463 LuaEntitySAO *co = getluaobject(ref);
2464 if(co == NULL) return 0;
2466 v3f pos = checkFloatPos(L, 2);
2468 co->setVelocity(pos);
2472 // getvelocity(self)
2473 static int l_getvelocity(lua_State *L)
2475 ObjectRef *ref = checkobject(L, 1);
2476 LuaEntitySAO *co = getluaobject(ref);
2477 if(co == NULL) return 0;
2479 v3f v = co->getVelocity();
2484 // setacceleration(self, {x=num, y=num, z=num})
2485 static int l_setacceleration(lua_State *L)
2487 ObjectRef *ref = checkobject(L, 1);
2488 LuaEntitySAO *co = getluaobject(ref);
2489 if(co == NULL) return 0;
2491 v3f pos = checkFloatPos(L, 2);
2493 co->setAcceleration(pos);
2497 // getacceleration(self)
2498 static int l_getacceleration(lua_State *L)
2500 ObjectRef *ref = checkobject(L, 1);
2501 LuaEntitySAO *co = getluaobject(ref);
2502 if(co == NULL) return 0;
2504 v3f v = co->getAcceleration();
2509 // setyaw(self, radians)
2510 static int l_setyaw(lua_State *L)
2512 ObjectRef *ref = checkobject(L, 1);
2513 LuaEntitySAO *co = getluaobject(ref);
2514 if(co == NULL) return 0;
2516 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2523 static int l_getyaw(lua_State *L)
2525 ObjectRef *ref = checkobject(L, 1);
2526 LuaEntitySAO *co = getluaobject(ref);
2527 if(co == NULL) return 0;
2529 float yaw = co->getYaw() * core::DEGTORAD;
2530 lua_pushnumber(L, yaw);
2534 // settexturemod(self, mod)
2535 static int l_settexturemod(lua_State *L)
2537 ObjectRef *ref = checkobject(L, 1);
2538 LuaEntitySAO *co = getluaobject(ref);
2539 if(co == NULL) return 0;
2541 std::string mod = luaL_checkstring(L, 2);
2542 co->setTextureMod(mod);
2546 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2547 // select_horiz_by_yawpitch=false)
2548 static int l_setsprite(lua_State *L)
2550 ObjectRef *ref = checkobject(L, 1);
2551 LuaEntitySAO *co = getluaobject(ref);
2552 if(co == NULL) return 0;
2555 if(!lua_isnil(L, 2))
2556 p = read_v2s16(L, 2);
2558 if(!lua_isnil(L, 3))
2559 num_frames = lua_tonumber(L, 3);
2560 float framelength = 0.2;
2561 if(!lua_isnil(L, 4))
2562 framelength = lua_tonumber(L, 4);
2563 bool select_horiz_by_yawpitch = false;
2564 if(!lua_isnil(L, 5))
2565 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2566 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2570 // set_armor_groups(self, groups)
2571 static int l_set_armor_groups(lua_State *L)
2573 ObjectRef *ref = checkobject(L, 1);
2574 LuaEntitySAO *co = getluaobject(ref);
2575 if(co == NULL) return 0;
2577 ItemGroupList groups;
2578 read_groups(L, 2, groups);
2579 co->setArmorGroups(groups);
2584 // get_entity_name(self)
2585 static int l_get_entity_name(lua_State *L)
2587 ObjectRef *ref = checkobject(L, 1);
2588 LuaEntitySAO *co = getluaobject(ref);
2589 if(co == NULL) return 0;
2591 std::string name = co->getName();
2592 lua_pushstring(L, name.c_str());
2596 // get_luaentity(self)
2597 static int l_get_luaentity(lua_State *L)
2599 ObjectRef *ref = checkobject(L, 1);
2600 LuaEntitySAO *co = getluaobject(ref);
2601 if(co == NULL) return 0;
2603 luaentity_get(L, co->getId());
2609 // get_player_name(self)
2610 static int l_get_player_name(lua_State *L)
2612 ObjectRef *ref = checkobject(L, 1);
2613 ServerRemotePlayer *player = getplayer(ref);
2619 lua_pushstring(L, player->getName());
2623 // get_look_dir(self)
2624 static int l_get_look_dir(lua_State *L)
2626 ObjectRef *ref = checkobject(L, 1);
2627 ServerRemotePlayer *player = getplayer(ref);
2628 if(player == NULL) return 0;
2630 float pitch = player->getRadPitch();
2631 float yaw = player->getRadYaw();
2632 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2637 // get_look_pitch(self)
2638 static int l_get_look_pitch(lua_State *L)
2640 ObjectRef *ref = checkobject(L, 1);
2641 ServerRemotePlayer *player = getplayer(ref);
2642 if(player == NULL) return 0;
2644 lua_pushnumber(L, player->getRadPitch());
2648 // get_look_yaw(self)
2649 static int l_get_look_yaw(lua_State *L)
2651 ObjectRef *ref = checkobject(L, 1);
2652 ServerRemotePlayer *player = getplayer(ref);
2653 if(player == NULL) return 0;
2655 lua_pushnumber(L, player->getRadYaw());
2660 ObjectRef(ServerActiveObject *object):
2663 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2669 infostream<<"ObjectRef destructing for id="
2670 <<m_object->getId()<<std::endl;
2672 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2675 // Creates an ObjectRef and leaves it on top of stack
2676 // Not callable from Lua; all references are created on the C side.
2677 static void create(lua_State *L, ServerActiveObject *object)
2679 ObjectRef *o = new ObjectRef(object);
2680 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2681 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2682 luaL_getmetatable(L, className);
2683 lua_setmetatable(L, -2);
2686 static void set_null(lua_State *L)
2688 ObjectRef *o = checkobject(L, -1);
2692 static void Register(lua_State *L)
2695 int methodtable = lua_gettop(L);
2696 luaL_newmetatable(L, className);
2697 int metatable = lua_gettop(L);
2699 lua_pushliteral(L, "__metatable");
2700 lua_pushvalue(L, methodtable);
2701 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2703 lua_pushliteral(L, "__index");
2704 lua_pushvalue(L, methodtable);
2705 lua_settable(L, metatable);
2707 lua_pushliteral(L, "__gc");
2708 lua_pushcfunction(L, gc_object);
2709 lua_settable(L, metatable);
2711 lua_pop(L, 1); // drop metatable
2713 luaL_openlib(L, 0, methods, 0); // fill methodtable
2714 lua_pop(L, 1); // drop methodtable
2716 // Cannot be created from Lua
2717 //lua_register(L, className, create_object);
2720 const char ObjectRef::className[] = "ObjectRef";
2721 const luaL_reg ObjectRef::methods[] = {
2722 // ServerActiveObject
2723 method(ObjectRef, remove),
2724 method(ObjectRef, getpos),
2725 method(ObjectRef, setpos),
2726 method(ObjectRef, moveto),
2727 method(ObjectRef, punch),
2728 method(ObjectRef, right_click),
2729 method(ObjectRef, set_hp),
2730 method(ObjectRef, get_hp),
2731 method(ObjectRef, get_inventory),
2732 method(ObjectRef, get_wield_list),
2733 method(ObjectRef, get_wield_index),
2734 method(ObjectRef, get_wielded_item),
2735 method(ObjectRef, set_wielded_item),
2736 // LuaEntitySAO-only
2737 method(ObjectRef, setvelocity),
2738 method(ObjectRef, getvelocity),
2739 method(ObjectRef, setacceleration),
2740 method(ObjectRef, getacceleration),
2741 method(ObjectRef, setyaw),
2742 method(ObjectRef, getyaw),
2743 method(ObjectRef, settexturemod),
2744 method(ObjectRef, setsprite),
2745 method(ObjectRef, set_armor_groups),
2746 method(ObjectRef, get_entity_name),
2747 method(ObjectRef, get_luaentity),
2749 method(ObjectRef, get_player_name),
2750 method(ObjectRef, get_look_dir),
2751 method(ObjectRef, get_look_pitch),
2752 method(ObjectRef, get_look_yaw),
2756 // Creates a new anonymous reference if id=0
2757 static void objectref_get_or_create(lua_State *L,
2758 ServerActiveObject *cobj)
2760 if(cobj->getId() == 0){
2761 ObjectRef::create(L, cobj);
2763 objectref_get(L, cobj->getId());
2774 ServerEnvironment *m_env;
2776 static const char className[];
2777 static const luaL_reg methods[];
2779 static EnvRef *checkobject(lua_State *L, int narg)
2781 luaL_checktype(L, narg, LUA_TUSERDATA);
2782 void *ud = luaL_checkudata(L, narg, className);
2783 if(!ud) luaL_typerror(L, narg, className);
2784 return *(EnvRef**)ud; // unbox pointer
2787 // Exported functions
2789 // EnvRef:add_node(pos, node)
2790 // pos = {x=num, y=num, z=num}
2791 static int l_add_node(lua_State *L)
2793 //infostream<<"EnvRef::l_add_node()"<<std::endl;
2794 EnvRef *o = checkobject(L, 1);
2795 ServerEnvironment *env = o->m_env;
2796 if(env == NULL) return 0;
2798 v3s16 pos = read_v3s16(L, 2);
2800 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2802 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2803 lua_pushboolean(L, succeeded);
2807 // EnvRef:remove_node(pos)
2808 // pos = {x=num, y=num, z=num}
2809 static int l_remove_node(lua_State *L)
2811 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2812 EnvRef *o = checkobject(L, 1);
2813 ServerEnvironment *env = o->m_env;
2814 if(env == NULL) return 0;
2816 v3s16 pos = read_v3s16(L, 2);
2818 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2819 lua_pushboolean(L, succeeded);
2823 // EnvRef:get_node(pos)
2824 // pos = {x=num, y=num, z=num}
2825 static int l_get_node(lua_State *L)
2827 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2828 EnvRef *o = checkobject(L, 1);
2829 ServerEnvironment *env = o->m_env;
2830 if(env == NULL) return 0;
2832 v3s16 pos = read_v3s16(L, 2);
2834 MapNode n = env->getMap().getNodeNoEx(pos);
2836 pushnode(L, n, env->getGameDef()->ndef());
2840 // EnvRef:get_node_or_nil(pos)
2841 // pos = {x=num, y=num, z=num}
2842 static int l_get_node_or_nil(lua_State *L)
2844 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2845 EnvRef *o = checkobject(L, 1);
2846 ServerEnvironment *env = o->m_env;
2847 if(env == NULL) return 0;
2849 v3s16 pos = read_v3s16(L, 2);
2852 MapNode n = env->getMap().getNode(pos);
2854 pushnode(L, n, env->getGameDef()->ndef());
2856 } catch(InvalidPositionException &e)
2863 // EnvRef:get_node_light(pos, timeofday)
2864 // pos = {x=num, y=num, z=num}
2865 // timeofday: nil = current time, 0 = night, 0.5 = day
2866 static int l_get_node_light(lua_State *L)
2868 EnvRef *o = checkobject(L, 1);
2869 ServerEnvironment *env = o->m_env;
2870 if(env == NULL) return 0;
2872 v3s16 pos = read_v3s16(L, 2);
2873 u32 time_of_day = env->getTimeOfDay();
2874 if(lua_isnumber(L, 3))
2875 time_of_day = 24000.0 * lua_tonumber(L, 3);
2876 time_of_day %= 24000;
2877 u32 dnr = time_to_daynight_ratio(time_of_day);
2878 MapNode n = env->getMap().getNodeNoEx(pos);
2880 MapNode n = env->getMap().getNode(pos);
2881 INodeDefManager *ndef = env->getGameDef()->ndef();
2882 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2884 } catch(InvalidPositionException &e)
2891 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2892 // pos = {x=num, y=num, z=num}
2893 static int l_add_entity(lua_State *L)
2895 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2896 EnvRef *o = checkobject(L, 1);
2897 ServerEnvironment *env = o->m_env;
2898 if(env == NULL) return 0;
2900 v3f pos = checkFloatPos(L, 2);
2902 const char *name = luaL_checkstring(L, 3);
2904 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2905 int objectid = env->addActiveObject(obj);
2906 // If failed to add, return nothing (reads as nil)
2910 objectref_get_or_create(L, obj);
2914 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2915 // pos = {x=num, y=num, z=num}
2916 static int l_add_item(lua_State *L)
2918 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2919 EnvRef *o = checkobject(L, 1);
2920 ServerEnvironment *env = o->m_env;
2921 if(env == NULL) return 0;
2923 v3f pos = checkFloatPos(L, 2);
2925 ItemStack item = read_item(L, 3);
2926 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2929 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2930 int objectid = env->addActiveObject(obj);
2931 // If failed to add, return nothing (reads as nil)
2935 objectref_get_or_create(L, obj);
2939 // EnvRef:add_rat(pos)
2940 // pos = {x=num, y=num, z=num}
2941 static int l_add_rat(lua_State *L)
2943 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2944 <<" Doing nothing."<<std::endl;
2948 // EnvRef:add_firefly(pos)
2949 // pos = {x=num, y=num, z=num}
2950 static int l_add_firefly(lua_State *L)
2952 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2953 <<" Doing nothing."<<std::endl;
2957 // EnvRef:get_meta(pos)
2958 static int l_get_meta(lua_State *L)
2960 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2961 EnvRef *o = checkobject(L, 1);
2962 ServerEnvironment *env = o->m_env;
2963 if(env == NULL) return 0;
2965 v3s16 p = read_v3s16(L, 2);
2966 NodeMetaRef::create(L, p, env);
2970 // EnvRef:get_player_by_name(name)
2971 static int l_get_player_by_name(lua_State *L)
2973 EnvRef *o = checkobject(L, 1);
2974 ServerEnvironment *env = o->m_env;
2975 if(env == NULL) return 0;
2977 const char *name = luaL_checkstring(L, 2);
2978 ServerRemotePlayer *player =
2979 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2984 // Put player on stack
2985 objectref_get_or_create(L, player);
2989 // EnvRef:get_objects_inside_radius(pos, radius)
2990 static int l_get_objects_inside_radius(lua_State *L)
2992 // Get the table insert function
2993 lua_getglobal(L, "table");
2994 lua_getfield(L, -1, "insert");
2995 int table_insert = lua_gettop(L);
2997 EnvRef *o = checkobject(L, 1);
2998 ServerEnvironment *env = o->m_env;
2999 if(env == NULL) return 0;
3001 v3f pos = checkFloatPos(L, 2);
3002 float radius = luaL_checknumber(L, 3) * BS;
3003 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3005 int table = lua_gettop(L);
3006 for(std::set<u16>::const_iterator
3007 i = ids.begin(); i != ids.end(); i++){
3008 ServerActiveObject *obj = env->getActiveObject(*i);
3009 // Insert object reference into table
3010 lua_pushvalue(L, table_insert);
3011 lua_pushvalue(L, table);
3012 objectref_get_or_create(L, obj);
3013 if(lua_pcall(L, 2, 0, 0))
3014 script_error(L, "error: %s", lua_tostring(L, -1));
3019 // EnvRef:set_timeofday(val)
3021 static int l_set_timeofday(lua_State *L)
3023 EnvRef *o = checkobject(L, 1);
3024 ServerEnvironment *env = o->m_env;
3025 if(env == NULL) return 0;
3027 float timeofday_f = luaL_checknumber(L, 2);
3028 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3029 int timeofday_mh = (int)(timeofday_f * 24000.0);
3030 // This should be set directly in the environment but currently
3031 // such changes aren't immediately sent to the clients, so call
3032 // the server instead.
3033 //env->setTimeOfDay(timeofday_mh);
3034 get_server(L)->setTimeOfDay(timeofday_mh);
3038 // EnvRef:get_timeofday() -> 0...1
3039 static int l_get_timeofday(lua_State *L)
3041 EnvRef *o = checkobject(L, 1);
3042 ServerEnvironment *env = o->m_env;
3043 if(env == NULL) return 0;
3045 int timeofday_mh = env->getTimeOfDay();
3046 float timeofday_f = (float)timeofday_mh / 24000.0;
3047 lua_pushnumber(L, timeofday_f);
3051 static int gc_object(lua_State *L) {
3052 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3058 EnvRef(ServerEnvironment *env):
3061 //infostream<<"EnvRef created"<<std::endl;
3066 //infostream<<"EnvRef destructing"<<std::endl;
3069 // Creates an EnvRef and leaves it on top of stack
3070 // Not callable from Lua; all references are created on the C side.
3071 static void create(lua_State *L, ServerEnvironment *env)
3073 EnvRef *o = new EnvRef(env);
3074 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3075 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3076 luaL_getmetatable(L, className);
3077 lua_setmetatable(L, -2);
3080 static void set_null(lua_State *L)
3082 EnvRef *o = checkobject(L, -1);
3086 static void Register(lua_State *L)
3089 int methodtable = lua_gettop(L);
3090 luaL_newmetatable(L, className);
3091 int metatable = lua_gettop(L);
3093 lua_pushliteral(L, "__metatable");
3094 lua_pushvalue(L, methodtable);
3095 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3097 lua_pushliteral(L, "__index");
3098 lua_pushvalue(L, methodtable);
3099 lua_settable(L, metatable);
3101 lua_pushliteral(L, "__gc");
3102 lua_pushcfunction(L, gc_object);
3103 lua_settable(L, metatable);
3105 lua_pop(L, 1); // drop metatable
3107 luaL_openlib(L, 0, methods, 0); // fill methodtable
3108 lua_pop(L, 1); // drop methodtable
3110 // Cannot be created from Lua
3111 //lua_register(L, className, create_object);
3114 const char EnvRef::className[] = "EnvRef";
3115 const luaL_reg EnvRef::methods[] = {
3116 method(EnvRef, add_node),
3117 method(EnvRef, remove_node),
3118 method(EnvRef, get_node),
3119 method(EnvRef, get_node_or_nil),
3120 method(EnvRef, get_node_light),
3121 method(EnvRef, add_entity),
3122 method(EnvRef, add_item),
3123 method(EnvRef, add_rat),
3124 method(EnvRef, add_firefly),
3125 method(EnvRef, get_meta),
3126 method(EnvRef, get_player_by_name),
3127 method(EnvRef, get_objects_inside_radius),
3128 method(EnvRef, set_timeofday),
3129 method(EnvRef, get_timeofday),
3137 class LuaABM : public ActiveBlockModifier
3143 std::set<std::string> m_trigger_contents;
3144 std::set<std::string> m_required_neighbors;
3145 float m_trigger_interval;
3146 u32 m_trigger_chance;
3148 LuaABM(lua_State *L, int id,
3149 const std::set<std::string> &trigger_contents,
3150 const std::set<std::string> &required_neighbors,
3151 float trigger_interval, u32 trigger_chance):
3154 m_trigger_contents(trigger_contents),
3155 m_required_neighbors(required_neighbors),
3156 m_trigger_interval(trigger_interval),
3157 m_trigger_chance(trigger_chance)
3160 virtual std::set<std::string> getTriggerContents()
3162 return m_trigger_contents;
3164 virtual std::set<std::string> getRequiredNeighbors()
3166 return m_required_neighbors;
3168 virtual float getTriggerInterval()
3170 return m_trigger_interval;
3172 virtual u32 getTriggerChance()
3174 return m_trigger_chance;
3176 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3177 u32 active_object_count, u32 active_object_count_wider)
3179 lua_State *L = m_lua;
3182 assert(lua_checkstack(L, 20));
3183 StackUnroller stack_unroller(L);
3185 // Get minetest.registered_abms
3186 lua_getglobal(L, "minetest");
3187 lua_getfield(L, -1, "registered_abms");
3188 luaL_checktype(L, -1, LUA_TTABLE);
3189 int registered_abms = lua_gettop(L);
3191 // Get minetest.registered_abms[m_id]
3192 lua_pushnumber(L, m_id);
3193 lua_gettable(L, registered_abms);
3194 if(lua_isnil(L, -1))
3198 luaL_checktype(L, -1, LUA_TTABLE);
3199 lua_getfield(L, -1, "action");
3200 luaL_checktype(L, -1, LUA_TFUNCTION);
3202 pushnode(L, n, env->getGameDef()->ndef());
3203 lua_pushnumber(L, active_object_count);
3204 lua_pushnumber(L, active_object_count_wider);
3205 if(lua_pcall(L, 4, 0, 0))
3206 script_error(L, "error: %s", lua_tostring(L, -1));
3211 // Writes a line to dstream
3212 static int l_debug(lua_State *L)
3214 std::string text = lua_tostring(L, 1);
3215 dstream << text << std::endl;
3219 // log([level,] text)
3220 // Writes a line to the logger.
3221 // The one-argument version logs to infostream.
3222 // The two-argument version accept a log level: error, action, info, or verbose.
3223 static int l_log(lua_State *L)
3226 LogMessageLevel level = LMT_INFO;
3227 if(lua_isnone(L, 2))
3229 text = lua_tostring(L, 1);
3233 std::string levelname = lua_tostring(L, 1);
3234 text = lua_tostring(L, 2);
3235 if(levelname == "error")
3237 else if(levelname == "action")
3239 else if(levelname == "verbose")
3240 level = LMT_VERBOSE;
3242 log_printline(level, text);
3246 // register_item_raw({lots of stuff})
3247 static int l_register_item_raw(lua_State *L)
3249 luaL_checktype(L, 1, LUA_TTABLE);
3252 // Get the writable item and node definition managers from the server
3253 IWritableItemDefManager *idef =
3254 get_server(L)->getWritableItemDefManager();
3255 IWritableNodeDefManager *ndef =
3256 get_server(L)->getWritableNodeDefManager();
3258 // Check if name is defined
3259 lua_getfield(L, table, "name");
3260 if(lua_isstring(L, -1)){
3261 std::string name = lua_tostring(L, -1);
3262 verbosestream<<"register_item_raw: "<<name<<std::endl;
3264 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3267 // Check if on_use is defined
3269 // Read the item definition and register it
3270 ItemDefinition def = read_item_definition(L, table);
3271 idef->registerItem(def);
3273 // Read the node definition (content features) and register it
3274 if(def.type == ITEM_NODE)
3276 ContentFeatures f = read_content_features(L, table);
3277 ndef->set(f.name, f);
3280 return 0; /* number of results */
3283 // register_alias_raw(name, convert_to_name)
3284 static int l_register_alias_raw(lua_State *L)
3286 std::string name = luaL_checkstring(L, 1);
3287 std::string convert_to = luaL_checkstring(L, 2);
3289 // Get the writable item definition manager from the server
3290 IWritableItemDefManager *idef =
3291 get_server(L)->getWritableItemDefManager();
3293 idef->registerAlias(name, convert_to);
3295 return 0; /* number of results */
3298 // helper for register_craft
3299 static bool read_craft_recipe_shaped(lua_State *L, int index,
3300 int &width, std::vector<std::string> &recipe)
3303 index = lua_gettop(L) + 1 + index;
3305 if(!lua_istable(L, index))
3310 while(lua_next(L, index) != 0){
3312 // key at index -2 and value at index -1
3313 if(!lua_istable(L, -1))
3315 int table2 = lua_gettop(L);
3317 while(lua_next(L, table2) != 0){
3318 // key at index -2 and value at index -1
3319 if(!lua_isstring(L, -1))
3321 recipe.push_back(lua_tostring(L, -1));
3322 // removes value, keeps key for next iteration
3329 if(colcount != width)
3332 // removes value, keeps key for next iteration
3339 // helper for register_craft
3340 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3341 std::vector<std::string> &recipe)
3344 index = lua_gettop(L) + 1 + index;
3346 if(!lua_istable(L, index))
3350 while(lua_next(L, index) != 0){
3351 // key at index -2 and value at index -1
3352 if(!lua_isstring(L, -1))
3354 recipe.push_back(lua_tostring(L, -1));
3355 // removes value, keeps key for next iteration
3361 // helper for register_craft
3362 static bool read_craft_replacements(lua_State *L, int index,
3363 CraftReplacements &replacements)
3366 index = lua_gettop(L) + 1 + index;
3368 if(!lua_istable(L, index))
3372 while(lua_next(L, index) != 0){
3373 // key at index -2 and value at index -1
3374 if(!lua_istable(L, -1))
3376 lua_rawgeti(L, -1, 1);
3377 if(!lua_isstring(L, -1))
3379 std::string replace_from = lua_tostring(L, -1);
3381 lua_rawgeti(L, -1, 2);
3382 if(!lua_isstring(L, -1))
3384 std::string replace_to = lua_tostring(L, -1);
3386 replacements.pairs.push_back(
3387 std::make_pair(replace_from, replace_to));
3388 // removes value, keeps key for next iteration
3393 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3394 static int l_register_craft(lua_State *L)
3396 //infostream<<"register_craft"<<std::endl;
3397 luaL_checktype(L, 1, LUA_TTABLE);
3400 // Get the writable craft definition manager from the server
3401 IWritableCraftDefManager *craftdef =
3402 get_server(L)->getWritableCraftDefManager();
3404 std::string type = getstringfield_default(L, table, "type", "shaped");
3407 CraftDefinitionShaped
3409 if(type == "shaped"){
3410 std::string output = getstringfield_default(L, table, "output", "");
3412 throw LuaError(L, "Crafting definition is missing an output");
3415 std::vector<std::string> recipe;
3416 lua_getfield(L, table, "recipe");
3417 if(lua_isnil(L, -1))
3418 throw LuaError(L, "Crafting definition is missing a recipe"
3419 " (output=\"" + output + "\")");
3420 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3421 throw LuaError(L, "Invalid crafting recipe"
3422 " (output=\"" + output + "\")");
3424 CraftReplacements replacements;
3425 lua_getfield(L, table, "replacements");
3426 if(!lua_isnil(L, -1))
3428 if(!read_craft_replacements(L, -1, replacements))
3429 throw LuaError(L, "Invalid replacements"
3430 " (output=\"" + output + "\")");
3433 CraftDefinition *def = new CraftDefinitionShaped(
3434 output, width, recipe, replacements);
3435 craftdef->registerCraft(def);
3438 CraftDefinitionShapeless
3440 else if(type == "shapeless"){
3441 std::string output = getstringfield_default(L, table, "output", "");
3443 throw LuaError(L, "Crafting definition (shapeless)"
3444 " is missing an output");
3446 std::vector<std::string> recipe;
3447 lua_getfield(L, table, "recipe");
3448 if(lua_isnil(L, -1))
3449 throw LuaError(L, "Crafting definition (shapeless)"
3450 " is missing a recipe"
3451 " (output=\"" + output + "\")");
3452 if(!read_craft_recipe_shapeless(L, -1, recipe))
3453 throw LuaError(L, "Invalid crafting recipe"
3454 " (output=\"" + output + "\")");
3456 CraftReplacements replacements;
3457 lua_getfield(L, table, "replacements");
3458 if(!lua_isnil(L, -1))
3460 if(!read_craft_replacements(L, -1, replacements))
3461 throw LuaError(L, "Invalid replacements"
3462 " (output=\"" + output + "\")");
3465 CraftDefinition *def = new CraftDefinitionShapeless(
3466 output, recipe, replacements);
3467 craftdef->registerCraft(def);
3470 CraftDefinitionToolRepair
3472 else if(type == "toolrepair"){
3473 float additional_wear = getfloatfield_default(L, table,
3474 "additional_wear", 0.0);
3476 CraftDefinition *def = new CraftDefinitionToolRepair(
3478 craftdef->registerCraft(def);
3481 CraftDefinitionCooking
3483 else if(type == "cooking"){
3484 std::string output = getstringfield_default(L, table, "output", "");
3486 throw LuaError(L, "Crafting definition (cooking)"
3487 " is missing an output");
3489 std::string recipe = getstringfield_default(L, table, "recipe", "");
3491 throw LuaError(L, "Crafting definition (cooking)"
3492 " is missing a recipe"
3493 " (output=\"" + output + "\")");
3495 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3497 CraftDefinition *def = new CraftDefinitionCooking(
3498 output, recipe, cooktime);
3499 craftdef->registerCraft(def);
3504 else if(type == "fuel"){
3505 std::string recipe = getstringfield_default(L, table, "recipe", "");
3507 throw LuaError(L, "Crafting definition (fuel)"
3508 " is missing a recipe");
3510 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3512 CraftDefinition *def = new CraftDefinitionFuel(
3514 craftdef->registerCraft(def);
3518 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3522 return 0; /* number of results */
3525 // setting_get(name)
3526 static int l_setting_get(lua_State *L)
3528 const char *name = luaL_checkstring(L, 1);
3530 std::string value = g_settings->get(name);
3531 lua_pushstring(L, value.c_str());
3532 } catch(SettingNotFoundException &e){
3538 // setting_getbool(name)
3539 static int l_setting_getbool(lua_State *L)
3541 const char *name = luaL_checkstring(L, 1);
3543 bool value = g_settings->getBool(name);
3544 lua_pushboolean(L, value);
3545 } catch(SettingNotFoundException &e){
3551 // chat_send_all(text)
3552 static int l_chat_send_all(lua_State *L)
3554 const char *text = luaL_checkstring(L, 1);
3555 // Get server from registry
3556 Server *server = get_server(L);
3558 server->notifyPlayers(narrow_to_wide(text));
3562 // chat_send_player(name, text)
3563 static int l_chat_send_player(lua_State *L)
3565 const char *name = luaL_checkstring(L, 1);
3566 const char *text = luaL_checkstring(L, 2);
3567 // Get server from registry
3568 Server *server = get_server(L);
3570 server->notifyPlayer(name, narrow_to_wide(text));
3574 // get_player_privs(name, text)
3575 static int l_get_player_privs(lua_State *L)
3577 const char *name = luaL_checkstring(L, 1);
3578 // Get server from registry
3579 Server *server = get_server(L);
3582 int table = lua_gettop(L);
3583 u64 privs_i = server->getPlayerEffectivePrivs(name);
3584 std::set<std::string> privs_s = privsToSet(privs_i);
3585 for(std::set<std::string>::const_iterator
3586 i = privs_s.begin(); i != privs_s.end(); i++){
3587 lua_pushboolean(L, true);
3588 lua_setfield(L, table, i->c_str());
3590 lua_pushvalue(L, table);
3594 // get_inventory(location)
3595 static int l_get_inventory(lua_State *L)
3597 InventoryLocation loc;
3599 std::string type = checkstringfield(L, 1, "type");
3600 if(type == "player"){
3601 std::string name = checkstringfield(L, 1, "name");
3602 loc.setPlayer(name);
3603 } else if(type == "node"){
3604 lua_getfield(L, 1, "pos");
3605 v3s16 pos = check_v3s16(L, -1);
3606 loc.setNodeMeta(pos);
3609 if(get_server(L)->getInventory(loc) != NULL)
3610 InvRef::create(L, loc);
3616 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3617 static int l_get_dig_params(lua_State *L)
3619 std::map<std::string, int> groups;
3620 read_groups(L, 1, groups);
3621 ToolCapabilities tp = read_tool_capabilities(L, 2);
3622 if(lua_isnoneornil(L, 3))
3623 push_dig_params(L, getDigParams(groups, &tp));
3625 push_dig_params(L, getDigParams(groups, &tp,
3626 luaL_checknumber(L, 3)));
3630 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3631 static int l_get_hit_params(lua_State *L)
3633 std::map<std::string, int> groups;
3634 read_groups(L, 1, groups);
3635 ToolCapabilities tp = read_tool_capabilities(L, 2);
3636 if(lua_isnoneornil(L, 3))
3637 push_hit_params(L, getHitParams(groups, &tp));
3639 push_hit_params(L, getHitParams(groups, &tp,
3640 luaL_checknumber(L, 3)));
3644 // get_current_modname()
3645 static int l_get_current_modname(lua_State *L)
3647 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3651 // get_modpath(modname)
3652 static int l_get_modpath(lua_State *L)
3654 const char *modname = luaL_checkstring(L, 1);
3656 const ModSpec *mod = get_server(L)->getModSpec(modname);
3661 lua_pushstring(L, mod->path.c_str());
3666 static int l_get_worldpath(lua_State *L)
3668 std::string worldpath = get_server(L)->getWorldPath();
3669 lua_pushstring(L, worldpath.c_str());
3673 static const struct luaL_Reg minetest_f [] = {
3676 {"register_item_raw", l_register_item_raw},
3677 {"register_alias_raw", l_register_alias_raw},
3678 {"register_craft", l_register_craft},
3679 {"setting_get", l_setting_get},
3680 {"setting_getbool", l_setting_getbool},
3681 {"chat_send_all", l_chat_send_all},
3682 {"chat_send_player", l_chat_send_player},
3683 {"get_player_privs", l_get_player_privs},
3684 {"get_inventory", l_get_inventory},
3685 {"get_dig_params", l_get_dig_params},
3686 {"get_hit_params", l_get_hit_params},
3687 {"get_current_modname", l_get_current_modname},
3688 {"get_modpath", l_get_modpath},
3689 {"get_worldpath", l_get_worldpath},
3694 Main export function
3697 void scriptapi_export(lua_State *L, Server *server)
3700 assert(lua_checkstack(L, 20));
3701 verbosestream<<"scriptapi_export()"<<std::endl;
3702 StackUnroller stack_unroller(L);
3704 // Store server as light userdata in registry
3705 lua_pushlightuserdata(L, server);
3706 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3708 // Register global functions in table minetest
3710 luaL_register(L, NULL, minetest_f);
3711 lua_setglobal(L, "minetest");
3713 // Get the main minetest table
3714 lua_getglobal(L, "minetest");
3716 // Add tables to minetest
3719 lua_setfield(L, -2, "object_refs");
3721 lua_setfield(L, -2, "luaentities");
3723 // Register wrappers
3724 LuaItemStack::Register(L);
3725 InvRef::Register(L);
3726 NodeMetaRef::Register(L);
3727 ObjectRef::Register(L);
3728 EnvRef::Register(L);
3731 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3732 const std::string &modname)
3734 ModNameStorer modnamestorer(L, modname);
3736 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3738 errorstream<<"Error loading mod \""<<modname
3739 <<"\": modname does not follow naming conventions: "
3740 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3744 bool success = false;
3747 success = script_load(L, scriptpath.c_str());
3750 errorstream<<"Error loading mod \""<<modname
3751 <<"\": "<<e.what()<<std::endl;
3757 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3760 assert(lua_checkstack(L, 20));
3761 verbosestream<<"scriptapi_add_environment"<<std::endl;
3762 StackUnroller stack_unroller(L);
3764 // Create EnvRef on stack
3765 EnvRef::create(L, env);
3766 int envref = lua_gettop(L);
3768 // minetest.env = envref
3769 lua_getglobal(L, "minetest");
3770 luaL_checktype(L, -1, LUA_TTABLE);
3771 lua_pushvalue(L, envref);
3772 lua_setfield(L, -2, "env");
3774 // Store environment as light userdata in registry
3775 lua_pushlightuserdata(L, env);
3776 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3779 Add ActiveBlockModifiers to environment
3782 // Get minetest.registered_abms
3783 lua_getglobal(L, "minetest");
3784 lua_getfield(L, -1, "registered_abms");
3785 luaL_checktype(L, -1, LUA_TTABLE);
3786 int registered_abms = lua_gettop(L);
3788 if(lua_istable(L, registered_abms)){
3789 int table = lua_gettop(L);
3791 while(lua_next(L, table) != 0){
3792 // key at index -2 and value at index -1
3793 int id = lua_tonumber(L, -2);
3794 int current_abm = lua_gettop(L);
3796 std::set<std::string> trigger_contents;
3797 lua_getfield(L, current_abm, "nodenames");
3798 if(lua_istable(L, -1)){
3799 int table = lua_gettop(L);
3801 while(lua_next(L, table) != 0){
3802 // key at index -2 and value at index -1
3803 luaL_checktype(L, -1, LUA_TSTRING);
3804 trigger_contents.insert(lua_tostring(L, -1));
3805 // removes value, keeps key for next iteration
3808 } else if(lua_isstring(L, -1)){
3809 trigger_contents.insert(lua_tostring(L, -1));
3813 std::set<std::string> required_neighbors;
3814 lua_getfield(L, current_abm, "neighbors");
3815 if(lua_istable(L, -1)){
3816 int table = lua_gettop(L);
3818 while(lua_next(L, table) != 0){
3819 // key at index -2 and value at index -1
3820 luaL_checktype(L, -1, LUA_TSTRING);
3821 required_neighbors.insert(lua_tostring(L, -1));
3822 // removes value, keeps key for next iteration
3825 } else if(lua_isstring(L, -1)){
3826 required_neighbors.insert(lua_tostring(L, -1));
3830 float trigger_interval = 10.0;
3831 getfloatfield(L, current_abm, "interval", trigger_interval);
3833 int trigger_chance = 50;
3834 getintfield(L, current_abm, "chance", trigger_chance);
3836 LuaABM *abm = new LuaABM(L, id, trigger_contents,
3837 required_neighbors, trigger_interval, trigger_chance);
3839 env->addActiveBlockModifier(abm);
3841 // removes value, keeps key for next iteration
3849 // Dump stack top with the dump2 function
3850 static void dump2(lua_State *L, const char *name)
3852 // Dump object (debug)
3853 lua_getglobal(L, "dump2");
3854 luaL_checktype(L, -1, LUA_TFUNCTION);
3855 lua_pushvalue(L, -2); // Get previous stack top as first parameter
3856 lua_pushstring(L, name);
3857 if(lua_pcall(L, 2, 0, 0))
3858 script_error(L, "error: %s", lua_tostring(L, -1));
3866 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
3869 assert(lua_checkstack(L, 20));
3870 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
3871 StackUnroller stack_unroller(L);
3873 // Create object on stack
3874 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
3875 int object = lua_gettop(L);
3877 // Get minetest.object_refs table
3878 lua_getglobal(L, "minetest");
3879 lua_getfield(L, -1, "object_refs");
3880 luaL_checktype(L, -1, LUA_TTABLE);
3881 int objectstable = lua_gettop(L);
3883 // object_refs[id] = object
3884 lua_pushnumber(L, cobj->getId()); // Push id
3885 lua_pushvalue(L, object); // Copy object to top of stack
3886 lua_settable(L, objectstable);
3889 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
3892 assert(lua_checkstack(L, 20));
3893 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
3894 StackUnroller stack_unroller(L);
3896 // Get minetest.object_refs table
3897 lua_getglobal(L, "minetest");
3898 lua_getfield(L, -1, "object_refs");
3899 luaL_checktype(L, -1, LUA_TTABLE);
3900 int objectstable = lua_gettop(L);
3902 // Get object_refs[id]
3903 lua_pushnumber(L, cobj->getId()); // Push id
3904 lua_gettable(L, objectstable);
3905 // Set object reference to NULL
3906 ObjectRef::set_null(L);
3907 lua_pop(L, 1); // pop object
3909 // Set object_refs[id] = nil
3910 lua_pushnumber(L, cobj->getId()); // Push id
3912 lua_settable(L, objectstable);
3915 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
3916 const std::string &message)
3919 assert(lua_checkstack(L, 20));
3920 StackUnroller stack_unroller(L);
3922 // Get minetest.registered_on_chat_messages
3923 lua_getglobal(L, "minetest");
3924 lua_getfield(L, -1, "registered_on_chat_messages");
3925 luaL_checktype(L, -1, LUA_TTABLE);
3926 int table = lua_gettop(L);
3929 while(lua_next(L, table) != 0){
3930 // key at index -2 and value at index -1
3931 luaL_checktype(L, -1, LUA_TFUNCTION);
3933 lua_pushstring(L, name.c_str());
3934 lua_pushstring(L, message.c_str());
3935 if(lua_pcall(L, 2, 1, 0))
3936 script_error(L, "error: %s", lua_tostring(L, -1));
3937 bool ate = lua_toboolean(L, -1);
3941 // value removed, keep key for next iteration
3950 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
3953 assert(lua_checkstack(L, 20));
3954 StackUnroller stack_unroller(L);
3956 // Get minetest.registered_on_newplayers
3957 lua_getglobal(L, "minetest");
3958 lua_getfield(L, -1, "registered_on_newplayers");
3959 luaL_checktype(L, -1, LUA_TTABLE);
3960 int table = lua_gettop(L);
3963 while(lua_next(L, table) != 0){
3964 // key at index -2 and value at index -1
3965 luaL_checktype(L, -1, LUA_TFUNCTION);
3967 objectref_get_or_create(L, player);
3968 if(lua_pcall(L, 1, 0, 0))
3969 script_error(L, "error: %s", lua_tostring(L, -1));
3970 // value removed, keep key for next iteration
3974 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
3977 assert(lua_checkstack(L, 20));
3978 StackUnroller stack_unroller(L);
3980 // Get minetest.registered_on_dieplayers
3981 lua_getglobal(L, "minetest");
3982 lua_getfield(L, -1, "registered_on_dieplayers");
3983 luaL_checktype(L, -1, LUA_TTABLE);
3984 int table = lua_gettop(L);
3987 while(lua_next(L, table) != 0){
3988 // key at index -2 and value at index -1
3989 luaL_checktype(L, -1, LUA_TFUNCTION);
3991 objectref_get_or_create(L, player);
3992 if(lua_pcall(L, 1, 0, 0))
3993 script_error(L, "error: %s", lua_tostring(L, -1));
3994 // value removed, keep key for next iteration
3999 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4002 assert(lua_checkstack(L, 20));
4003 StackUnroller stack_unroller(L);
4005 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
4007 bool positioning_handled_by_some = false;
4009 // Get minetest.registered_on_respawnplayers
4010 lua_getglobal(L, "minetest");
4011 lua_getfield(L, -1, "registered_on_respawnplayers");
4012 luaL_checktype(L, -1, LUA_TTABLE);
4013 int table = lua_gettop(L);
4016 while(lua_next(L, table) != 0){
4017 // key at index -2 and value at index -1
4018 luaL_checktype(L, -1, LUA_TFUNCTION);
4020 objectref_get_or_create(L, player);
4021 if(lua_pcall(L, 1, 1, 0))
4022 script_error(L, "error: %s", lua_tostring(L, -1));
4023 bool positioning_handled = lua_toboolean(L, -1);
4025 if(positioning_handled)
4026 positioning_handled_by_some = true;
4027 // value removed, keep key for next iteration
4029 return positioning_handled_by_some;
4032 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4034 lua_getglobal(L, "minetest");
4035 lua_getfield(L, -1, "creative_inventory");
4036 luaL_checktype(L, -1, LUA_TTABLE);
4037 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4038 PLAYER_INVENTORY_SIZE);
4042 item callbacks and node callbacks
4045 // Retrieves minetest.registered_items[name][callbackname]
4046 // If that is nil or on error, return false and stack is unchanged
4047 // If that is a function, returns true and pushes the
4048 // function onto the stack
4049 static bool get_item_callback(lua_State *L,
4050 const char *name, const char *callbackname)
4052 lua_getglobal(L, "minetest");
4053 lua_getfield(L, -1, "registered_items");
4055 luaL_checktype(L, -1, LUA_TTABLE);
4056 lua_getfield(L, -1, name);
4058 // Should be a table
4059 if(lua_type(L, -1) != LUA_TTABLE)
4061 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4065 lua_getfield(L, -1, callbackname);
4067 // Should be a function or nil
4068 if(lua_type(L, -1) == LUA_TFUNCTION)
4072 else if(lua_isnil(L, -1))
4079 errorstream<<"Item \""<<name<<"\" callback \""
4080 <<callbackname<<" is not a function"<<std::endl;
4086 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4087 ServerActiveObject *dropper, v3f pos)
4090 assert(lua_checkstack(L, 20));
4091 StackUnroller stack_unroller(L);
4093 // Push callback function on stack
4094 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4098 LuaItemStack::create(L, item);
4099 objectref_get_or_create(L, dropper);
4100 pushFloatPos(L, pos);
4101 if(lua_pcall(L, 3, 1, 0))
4102 script_error(L, "error: %s", lua_tostring(L, -1));
4103 if(!lua_isnil(L, -1))
4104 item = read_item(L, -1);
4108 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4109 ServerActiveObject *placer, const PointedThing &pointed)
4112 assert(lua_checkstack(L, 20));
4113 StackUnroller stack_unroller(L);
4115 // Push callback function on stack
4116 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4120 LuaItemStack::create(L, item);
4121 objectref_get_or_create(L, placer);
4122 push_pointed_thing(L, pointed);
4123 if(lua_pcall(L, 3, 1, 0))
4124 script_error(L, "error: %s", lua_tostring(L, -1));
4125 if(!lua_isnil(L, -1))
4126 item = read_item(L, -1);
4130 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4131 ServerActiveObject *user, const PointedThing &pointed)
4134 assert(lua_checkstack(L, 20));
4135 StackUnroller stack_unroller(L);
4137 // Push callback function on stack
4138 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4142 LuaItemStack::create(L, item);
4143 objectref_get_or_create(L, user);
4144 push_pointed_thing(L, pointed);
4145 if(lua_pcall(L, 3, 1, 0))
4146 script_error(L, "error: %s", lua_tostring(L, -1));
4147 if(!lua_isnil(L, -1))
4148 item = read_item(L, -1);
4152 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4153 ServerActiveObject *puncher)
4156 assert(lua_checkstack(L, 20));
4157 StackUnroller stack_unroller(L);
4159 INodeDefManager *ndef = get_server(L)->ndef();
4161 // Push callback function on stack
4162 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4167 pushnode(L, node, ndef);
4168 objectref_get_or_create(L, puncher);
4169 if(lua_pcall(L, 3, 0, 0))
4170 script_error(L, "error: %s", lua_tostring(L, -1));
4174 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4175 ServerActiveObject *digger)
4178 assert(lua_checkstack(L, 20));
4179 StackUnroller stack_unroller(L);
4181 INodeDefManager *ndef = get_server(L)->ndef();
4183 // Push callback function on stack
4184 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4189 pushnode(L, node, ndef);
4190 objectref_get_or_create(L, digger);
4191 if(lua_pcall(L, 3, 0, 0))
4192 script_error(L, "error: %s", lua_tostring(L, -1));
4200 void scriptapi_environment_step(lua_State *L, float dtime)
4203 assert(lua_checkstack(L, 20));
4204 //infostream<<"scriptapi_environment_step"<<std::endl;
4205 StackUnroller stack_unroller(L);
4207 // Get minetest.registered_globalsteps
4208 lua_getglobal(L, "minetest");
4209 lua_getfield(L, -1, "registered_globalsteps");
4210 luaL_checktype(L, -1, LUA_TTABLE);
4211 int table = lua_gettop(L);
4214 while(lua_next(L, table) != 0){
4215 // key at index -2 and value at index -1
4216 luaL_checktype(L, -1, LUA_TFUNCTION);
4218 lua_pushnumber(L, dtime);
4219 if(lua_pcall(L, 1, 0, 0))
4220 script_error(L, "error: %s", lua_tostring(L, -1));
4221 // value removed, keep key for next iteration
4225 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
4228 assert(lua_checkstack(L, 20));
4229 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4230 StackUnroller stack_unroller(L);
4232 // Get minetest.registered_on_generateds
4233 lua_getglobal(L, "minetest");
4234 lua_getfield(L, -1, "registered_on_generateds");
4235 luaL_checktype(L, -1, LUA_TTABLE);
4236 int table = lua_gettop(L);
4239 while(lua_next(L, table) != 0){
4240 // key at index -2 and value at index -1
4241 luaL_checktype(L, -1, LUA_TFUNCTION);
4243 push_v3s16(L, minp);
4244 push_v3s16(L, maxp);
4245 if(lua_pcall(L, 2, 0, 0))
4246 script_error(L, "error: %s", lua_tostring(L, -1));
4247 // value removed, keep key for next iteration
4255 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4258 assert(lua_checkstack(L, 20));
4259 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4260 <<name<<"\""<<std::endl;
4261 StackUnroller stack_unroller(L);
4263 // Get minetest.registered_entities[name]
4264 lua_getglobal(L, "minetest");
4265 lua_getfield(L, -1, "registered_entities");
4266 luaL_checktype(L, -1, LUA_TTABLE);
4267 lua_pushstring(L, name);
4268 lua_gettable(L, -2);
4269 // Should be a table, which we will use as a prototype
4270 //luaL_checktype(L, -1, LUA_TTABLE);
4271 if(lua_type(L, -1) != LUA_TTABLE){
4272 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4275 int prototype_table = lua_gettop(L);
4276 //dump2(L, "prototype_table");
4278 // Create entity object
4280 int object = lua_gettop(L);
4282 // Set object metatable
4283 lua_pushvalue(L, prototype_table);
4284 lua_setmetatable(L, -2);
4286 // Add object reference
4287 // This should be userdata with metatable ObjectRef
4288 objectref_get(L, id);
4289 luaL_checktype(L, -1, LUA_TUSERDATA);
4290 if(!luaL_checkudata(L, -1, "ObjectRef"))
4291 luaL_typerror(L, -1, "ObjectRef");
4292 lua_setfield(L, -2, "object");
4294 // minetest.luaentities[id] = object
4295 lua_getglobal(L, "minetest");
4296 lua_getfield(L, -1, "luaentities");
4297 luaL_checktype(L, -1, LUA_TTABLE);
4298 lua_pushnumber(L, id); // Push id
4299 lua_pushvalue(L, object); // Copy object to top of stack
4300 lua_settable(L, -3);
4305 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4306 const std::string &staticdata)
4309 assert(lua_checkstack(L, 20));
4310 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4311 StackUnroller stack_unroller(L);
4313 // Get minetest.luaentities[id]
4314 luaentity_get(L, id);
4315 int object = lua_gettop(L);
4317 // Get on_activate function
4318 lua_pushvalue(L, object);
4319 lua_getfield(L, -1, "on_activate");
4320 if(!lua_isnil(L, -1)){
4321 luaL_checktype(L, -1, LUA_TFUNCTION);
4322 lua_pushvalue(L, object); // self
4323 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4324 // Call with 2 arguments, 0 results
4325 if(lua_pcall(L, 2, 0, 0))
4326 script_error(L, "error running function on_activate: %s\n",
4327 lua_tostring(L, -1));
4331 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4334 assert(lua_checkstack(L, 20));
4335 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4337 // Get minetest.luaentities table
4338 lua_getglobal(L, "minetest");
4339 lua_getfield(L, -1, "luaentities");
4340 luaL_checktype(L, -1, LUA_TTABLE);
4341 int objectstable = lua_gettop(L);
4343 // Set luaentities[id] = nil
4344 lua_pushnumber(L, id); // Push id
4346 lua_settable(L, objectstable);
4348 lua_pop(L, 2); // pop luaentities, minetest
4351 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4354 assert(lua_checkstack(L, 20));
4355 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4356 StackUnroller stack_unroller(L);
4358 // Get minetest.luaentities[id]
4359 luaentity_get(L, id);
4360 int object = lua_gettop(L);
4362 // Get get_staticdata function
4363 lua_pushvalue(L, object);
4364 lua_getfield(L, -1, "get_staticdata");
4365 if(lua_isnil(L, -1))
4368 luaL_checktype(L, -1, LUA_TFUNCTION);
4369 lua_pushvalue(L, object); // self
4370 // Call with 1 arguments, 1 results
4371 if(lua_pcall(L, 1, 1, 0))
4372 script_error(L, "error running function get_staticdata: %s\n",
4373 lua_tostring(L, -1));
4376 const char *s = lua_tolstring(L, -1, &len);
4377 return std::string(s, len);
4380 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4381 LuaEntityProperties *prop)
4384 assert(lua_checkstack(L, 20));
4385 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4386 StackUnroller stack_unroller(L);
4388 // Get minetest.luaentities[id]
4389 luaentity_get(L, id);
4390 //int object = lua_gettop(L);
4394 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4396 getboolfield(L, -1, "physical", prop->physical);
4398 getfloatfield(L, -1, "weight", prop->weight);
4400 lua_getfield(L, -1, "collisionbox");
4401 if(lua_istable(L, -1))
4402 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4405 getstringfield(L, -1, "visual", prop->visual);
4407 lua_getfield(L, -1, "visual_size");
4408 if(lua_istable(L, -1))
4409 prop->visual_size = read_v2f(L, -1);
4412 lua_getfield(L, -1, "textures");
4413 if(lua_istable(L, -1)){
4414 prop->textures.clear();
4415 int table = lua_gettop(L);
4417 while(lua_next(L, table) != 0){
4418 // key at index -2 and value at index -1
4419 if(lua_isstring(L, -1))
4420 prop->textures.push_back(lua_tostring(L, -1));
4422 prop->textures.push_back("");
4423 // removes value, keeps key for next iteration
4429 lua_getfield(L, -1, "spritediv");
4430 if(lua_istable(L, -1))
4431 prop->spritediv = read_v2s16(L, -1);
4434 lua_getfield(L, -1, "initial_sprite_basepos");
4435 if(lua_istable(L, -1))
4436 prop->initial_sprite_basepos = read_v2s16(L, -1);
4440 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4443 assert(lua_checkstack(L, 20));
4444 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4445 StackUnroller stack_unroller(L);
4447 // Get minetest.luaentities[id]
4448 luaentity_get(L, id);
4449 int object = lua_gettop(L);
4450 // State: object is at top of stack
4451 // Get step function
4452 lua_getfield(L, -1, "on_step");
4453 if(lua_isnil(L, -1))
4455 luaL_checktype(L, -1, LUA_TFUNCTION);
4456 lua_pushvalue(L, object); // self
4457 lua_pushnumber(L, dtime); // dtime
4458 // Call with 2 arguments, 0 results
4459 if(lua_pcall(L, 2, 0, 0))
4460 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4463 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4464 // tool_capabilities, direction)
4465 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4466 ServerActiveObject *puncher, float time_from_last_punch,
4467 const ToolCapabilities *toolcap, v3f dir)
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_punch");
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, puncher); // Clicker reference
4485 lua_pushnumber(L, time_from_last_punch);
4486 push_tool_capabilities(L, *toolcap);
4488 // Call with 5 arguments, 0 results
4489 if(lua_pcall(L, 5, 0, 0))
4490 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4493 // Calls entity:on_rightclick(ObjectRef clicker)
4494 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4495 ServerActiveObject *clicker)
4498 assert(lua_checkstack(L, 20));
4499 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4500 StackUnroller stack_unroller(L);
4502 // Get minetest.luaentities[id]
4503 luaentity_get(L, id);
4504 int object = lua_gettop(L);
4505 // State: object is at top of stack
4507 lua_getfield(L, -1, "on_rightclick");
4508 if(lua_isnil(L, -1))
4510 luaL_checktype(L, -1, LUA_TFUNCTION);
4511 lua_pushvalue(L, object); // self
4512 objectref_get_or_create(L, clicker); // Clicker reference
4513 // Call with 2 arguments, 0 results
4514 if(lua_pcall(L, 2, 0, 0))
4515 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));