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 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
817 index = lua_gettop(L) + 1 + index;
818 if(lua_isnil(L, index)){
819 } else if(lua_istable(L, index)){
820 getstringfield(L, index, "name", spec.name);
821 getfloatfield(L, index, "gain", spec.gain);
822 } else if(lua_isstring(L, index)){
823 spec.name = lua_tostring(L, index);
831 static ItemDefinition read_item_definition(lua_State *L, int index)
834 index = lua_gettop(L) + 1 + index;
836 // Read the item definition
839 def.type = (ItemType)getenumfield(L, index, "type",
840 es_ItemType, ITEM_NONE);
841 getstringfield(L, index, "name", def.name);
842 getstringfield(L, index, "description", def.description);
843 getstringfield(L, index, "inventory_image", def.inventory_image);
844 getstringfield(L, index, "wield_image", def.wield_image);
846 lua_getfield(L, index, "wield_scale");
847 if(lua_istable(L, -1)){
848 def.wield_scale = check_v3f(L, -1);
852 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
853 if(def.stack_max == 0)
856 lua_getfield(L, index, "on_use");
857 def.usable = lua_isfunction(L, -1);
860 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
862 warn_if_field_exists(L, index, "tool_digging_properties",
863 "deprecated: use tool_capabilities");
865 lua_getfield(L, index, "tool_capabilities");
866 if(lua_istable(L, -1)){
867 def.tool_capabilities = new ToolCapabilities(
868 read_tool_capabilities(L, -1));
871 // If name is "" (hand), ensure there are ToolCapabilities
872 // because it will be looked up there whenever any other item has
873 // no ToolCapabilities
874 if(def.name == "" && def.tool_capabilities == NULL){
875 def.tool_capabilities = new ToolCapabilities();
878 lua_getfield(L, index, "groups");
879 read_groups(L, -1, def.groups);
889 static ContentFeatures read_content_features(lua_State *L, int index)
892 index = lua_gettop(L) + 1 + index;
896 getstringfield(L, index, "name", f.name);
899 lua_getfield(L, index, "groups");
900 read_groups(L, -1, f.groups);
903 /* Visual definition */
905 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
907 getfloatfield(L, index, "visual_scale", f.visual_scale);
909 lua_getfield(L, index, "tile_images");
910 if(lua_istable(L, -1)){
911 int table = lua_gettop(L);
914 while(lua_next(L, table) != 0){
915 // key at index -2 and value at index -1
916 if(lua_isstring(L, -1))
917 f.tname_tiles[i] = lua_tostring(L, -1);
919 f.tname_tiles[i] = "";
920 // removes value, keeps key for next iteration
928 // Copy last value to all remaining textures
930 std::string lastname = f.tname_tiles[i-1];
932 f.tname_tiles[i] = lastname;
939 lua_getfield(L, index, "special_materials");
940 if(lua_istable(L, -1)){
941 int table = lua_gettop(L);
944 while(lua_next(L, table) != 0){
945 // key at index -2 and value at index -1
946 int smtable = lua_gettop(L);
947 std::string tname = getstringfield_default(
948 L, smtable, "image", "");
949 bool backface_culling = getboolfield_default(
950 L, smtable, "backface_culling", true);
951 MaterialSpec mspec(tname, backface_culling);
952 f.mspec_special[i] = mspec;
953 // removes value, keeps key for next iteration
964 f.alpha = getintfield_default(L, index, "alpha", 255);
968 lua_getfield(L, index, "post_effect_color");
969 if(!lua_isnil(L, -1))
970 f.post_effect_color = readARGB8(L, -1);
973 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
974 es_ContentParamType, CPT_NONE);
975 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
976 es_ContentParamType2, CPT2_NONE);
978 // Warn about some deprecated fields
979 warn_if_field_exists(L, index, "wall_mounted",
980 "deprecated: use paramtype2 = 'wallmounted'");
981 warn_if_field_exists(L, index, "light_propagates",
982 "deprecated: determined from paramtype");
983 warn_if_field_exists(L, index, "dug_item",
984 "deprecated: use 'drop' field");
985 warn_if_field_exists(L, index, "extra_dug_item",
986 "deprecated: use 'drop' field");
987 warn_if_field_exists(L, index, "extra_dug_item_rarity",
988 "deprecated: use 'drop' field");
990 // True for all ground-like things like stone and mud, false for eg. trees
991 getboolfield(L, index, "is_ground_content", f.is_ground_content);
992 f.light_propagates = (f.param_type == CPT_LIGHT);
993 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
994 // This is used for collision detection.
995 // Also for general solidness queries.
996 getboolfield(L, index, "walkable", f.walkable);
997 // Player can point to these
998 getboolfield(L, index, "pointable", f.pointable);
999 // Player can dig these
1000 getboolfield(L, index, "diggable", f.diggable);
1001 // Player can climb these
1002 getboolfield(L, index, "climbable", f.climbable);
1003 // Player can build on these
1004 getboolfield(L, index, "buildable_to", f.buildable_to);
1005 // Metadata name of node (eg. "furnace")
1006 getstringfield(L, index, "metadata_name", f.metadata_name);
1007 // Whether the node is non-liquid, source liquid or flowing liquid
1008 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1009 es_LiquidType, LIQUID_NONE);
1010 // If the content is liquid, this is the flowing version of the liquid.
1011 getstringfield(L, index, "liquid_alternative_flowing",
1012 f.liquid_alternative_flowing);
1013 // If the content is liquid, this is the source version of the liquid.
1014 getstringfield(L, index, "liquid_alternative_source",
1015 f.liquid_alternative_source);
1016 // Viscosity for fluid flow, ranging from 1 to 7, with
1017 // 1 giving almost instantaneous propagation and 7 being
1018 // the slowest possible
1019 f.liquid_viscosity = getintfield_default(L, index,
1020 "liquid_viscosity", f.liquid_viscosity);
1021 // Amount of light the node emits
1022 f.light_source = getintfield_default(L, index,
1023 "light_source", f.light_source);
1024 f.damage_per_second = getintfield_default(L, index,
1025 "damage_per_second", f.damage_per_second);
1027 lua_getfield(L, index, "selection_box");
1028 if(lua_istable(L, -1)){
1029 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1030 es_NodeBoxType, NODEBOX_REGULAR);
1032 lua_getfield(L, -1, "fixed");
1033 if(lua_istable(L, -1))
1034 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1037 lua_getfield(L, -1, "wall_top");
1038 if(lua_istable(L, -1))
1039 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1042 lua_getfield(L, -1, "wall_bottom");
1043 if(lua_istable(L, -1))
1044 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1047 lua_getfield(L, -1, "wall_side");
1048 if(lua_istable(L, -1))
1049 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1054 // Set to true if paramtype used to be 'facedir_simple'
1055 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1056 // Set to true if wall_mounted used to be set to true
1057 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1060 lua_getfield(L, index, "sounds");
1061 if(lua_istable(L, -1)){
1062 lua_getfield(L, -1, "footstep");
1063 read_soundspec(L, -1, f.sound_footstep);
1065 lua_getfield(L, -1, "dug");
1066 read_soundspec(L, -1, f.sound_dug);
1078 static ItemStack read_item(lua_State *L, int index);
1080 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1081 lua_State *L, int tableindex, int forcesize=-1)
1083 dstream<<"inventory_set_list_from_lua\n";
1085 tableindex = lua_gettop(L) + 1 + tableindex;
1086 // If nil, delete list
1087 if(lua_isnil(L, tableindex)){
1088 inv->deleteList(name);
1091 // Otherwise set list
1092 std::vector<ItemStack> items;
1093 luaL_checktype(L, tableindex, LUA_TTABLE);
1095 while(lua_next(L, tableindex) != 0){
1096 // key at index -2 and value at index -1
1097 items.push_back(read_item(L, -1));
1098 // removes value, keeps key for next iteration
1101 int listsize = (forcesize != -1) ? forcesize : items.size();
1102 InventoryList *invlist = inv->addList(name, listsize);
1104 for(std::vector<ItemStack>::const_iterator
1105 i = items.begin(); i != items.end(); i++){
1106 if(forcesize != -1 && index == forcesize)
1108 invlist->changeItem(index, *i);
1111 while(forcesize != -1 && index < forcesize){
1112 invlist->deleteItem(index);
1115 dstream<<"inventory_set_list_from_lua done\n";
1118 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1121 InventoryList *invlist = inv->getList(name);
1122 if(invlist == NULL){
1126 // Get the table insert function
1127 lua_getglobal(L, "table");
1128 lua_getfield(L, -1, "insert");
1129 int table_insert = lua_gettop(L);
1130 // Create and fill table
1132 int table = lua_gettop(L);
1133 for(u32 i=0; i<invlist->getSize(); i++){
1134 ItemStack item = invlist->getItem(i);
1135 lua_pushvalue(L, table_insert);
1136 lua_pushvalue(L, table);
1137 lua_pushstring(L, item.getItemString().c_str());
1138 if(lua_pcall(L, 2, 0, 0))
1139 script_error(L, "error: %s", lua_tostring(L, -1));
1144 Helpful macros for userdata classes
1147 #define method(class, name) {#name, class::l_##name}
1158 static const char className[];
1159 static const luaL_reg methods[];
1161 // Exported functions
1163 // garbage collector
1164 static int gc_object(lua_State *L)
1166 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1171 // is_empty(self) -> true/false
1172 static int l_is_empty(lua_State *L)
1174 LuaItemStack *o = checkobject(L, 1);
1175 ItemStack &item = o->m_stack;
1176 lua_pushboolean(L, item.empty());
1180 // get_name(self) -> string
1181 static int l_get_name(lua_State *L)
1183 LuaItemStack *o = checkobject(L, 1);
1184 ItemStack &item = o->m_stack;
1185 lua_pushstring(L, item.name.c_str());
1189 // get_count(self) -> number
1190 static int l_get_count(lua_State *L)
1192 LuaItemStack *o = checkobject(L, 1);
1193 ItemStack &item = o->m_stack;
1194 lua_pushinteger(L, item.count);
1198 // get_wear(self) -> number
1199 static int l_get_wear(lua_State *L)
1201 LuaItemStack *o = checkobject(L, 1);
1202 ItemStack &item = o->m_stack;
1203 lua_pushinteger(L, item.wear);
1207 // get_metadata(self) -> string
1208 static int l_get_metadata(lua_State *L)
1210 LuaItemStack *o = checkobject(L, 1);
1211 ItemStack &item = o->m_stack;
1212 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1216 // clear(self) -> true
1217 static int l_clear(lua_State *L)
1219 LuaItemStack *o = checkobject(L, 1);
1221 lua_pushboolean(L, true);
1225 // replace(self, itemstack or itemstring or table or nil) -> true
1226 static int l_replace(lua_State *L)
1228 LuaItemStack *o = checkobject(L, 1);
1229 o->m_stack = read_item(L, 2);
1230 lua_pushboolean(L, true);
1234 // to_string(self) -> string
1235 static int l_to_string(lua_State *L)
1237 LuaItemStack *o = checkobject(L, 1);
1238 std::string itemstring = o->m_stack.getItemString();
1239 lua_pushstring(L, itemstring.c_str());
1243 // to_table(self) -> table or nil
1244 static int l_to_table(lua_State *L)
1246 LuaItemStack *o = checkobject(L, 1);
1247 const ItemStack &item = o->m_stack;
1255 lua_pushstring(L, item.name.c_str());
1256 lua_setfield(L, -2, "name");
1257 lua_pushinteger(L, item.count);
1258 lua_setfield(L, -2, "count");
1259 lua_pushinteger(L, item.wear);
1260 lua_setfield(L, -2, "wear");
1261 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1262 lua_setfield(L, -2, "metadata");
1267 // get_stack_max(self) -> number
1268 static int l_get_stack_max(lua_State *L)
1270 LuaItemStack *o = checkobject(L, 1);
1271 ItemStack &item = o->m_stack;
1272 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1276 // get_free_space(self) -> number
1277 static int l_get_free_space(lua_State *L)
1279 LuaItemStack *o = checkobject(L, 1);
1280 ItemStack &item = o->m_stack;
1281 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1285 // is_known(self) -> true/false
1286 // Checks if the item is defined.
1287 static int l_is_known(lua_State *L)
1289 LuaItemStack *o = checkobject(L, 1);
1290 ItemStack &item = o->m_stack;
1291 bool is_known = item.isKnown(get_server(L)->idef());
1292 lua_pushboolean(L, is_known);
1296 // get_definition(self) -> table
1297 // Returns the item definition table from minetest.registered_items,
1298 // or a fallback one (name="unknown")
1299 static int l_get_definition(lua_State *L)
1301 LuaItemStack *o = checkobject(L, 1);
1302 ItemStack &item = o->m_stack;
1304 // Get minetest.registered_items[name]
1305 lua_getglobal(L, "minetest");
1306 lua_getfield(L, -1, "registered_items");
1307 luaL_checktype(L, -1, LUA_TTABLE);
1308 lua_getfield(L, -1, item.name.c_str());
1309 if(lua_isnil(L, -1))
1312 lua_getfield(L, -1, "unknown");
1317 // get_tool_capabilities(self) -> table
1318 // Returns the effective tool digging properties.
1319 // Returns those of the hand ("") if this item has none associated.
1320 static int l_get_tool_capabilities(lua_State *L)
1322 LuaItemStack *o = checkobject(L, 1);
1323 ItemStack &item = o->m_stack;
1324 const ToolCapabilities &prop =
1325 item.getToolCapabilities(get_server(L)->idef());
1326 push_tool_capabilities(L, prop);
1330 // add_wear(self, amount) -> true/false
1331 // The range for "amount" is [0,65535]. Wear is only added if the item
1332 // is a tool. Adding wear might destroy the item.
1333 // Returns true if the item is (or was) a tool.
1334 static int l_add_wear(lua_State *L)
1336 LuaItemStack *o = checkobject(L, 1);
1337 ItemStack &item = o->m_stack;
1338 int amount = lua_tointeger(L, 2);
1339 bool result = item.addWear(amount, get_server(L)->idef());
1340 lua_pushboolean(L, result);
1344 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1345 // Returns leftover item stack
1346 static int l_add_item(lua_State *L)
1348 LuaItemStack *o = checkobject(L, 1);
1349 ItemStack &item = o->m_stack;
1350 ItemStack newitem = read_item(L, 2);
1351 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1352 create(L, leftover);
1356 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1357 // First return value is true iff the new item fits fully into the stack
1358 // Second return value is the would-be-left-over item stack
1359 static int l_item_fits(lua_State *L)
1361 LuaItemStack *o = checkobject(L, 1);
1362 ItemStack &item = o->m_stack;
1363 ItemStack newitem = read_item(L, 2);
1365 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1366 lua_pushboolean(L, fits); // first return value
1367 create(L, restitem); // second return value
1371 // take_item(self, takecount=1) -> itemstack
1372 static int l_take_item(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1377 if(!lua_isnone(L, 2))
1378 takecount = lua_tointeger(L, 2);
1379 ItemStack taken = item.takeItem(takecount);
1384 // peek_item(self, peekcount=1) -> itemstack
1385 static int l_peek_item(lua_State *L)
1387 LuaItemStack *o = checkobject(L, 1);
1388 ItemStack &item = o->m_stack;
1390 if(!lua_isnone(L, 2))
1391 peekcount = lua_tointeger(L, 2);
1392 ItemStack peekaboo = item.peekItem(peekcount);
1393 create(L, peekaboo);
1398 LuaItemStack(const ItemStack &item):
1407 const ItemStack& getItem() const
1411 ItemStack& getItem()
1416 // LuaItemStack(itemstack or itemstring or table or nil)
1417 // Creates an LuaItemStack and leaves it on top of stack
1418 static int create_object(lua_State *L)
1420 ItemStack item = read_item(L, 1);
1421 LuaItemStack *o = new LuaItemStack(item);
1422 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1423 luaL_getmetatable(L, className);
1424 lua_setmetatable(L, -2);
1427 // Not callable from Lua
1428 static int create(lua_State *L, const ItemStack &item)
1430 LuaItemStack *o = new LuaItemStack(item);
1431 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1432 luaL_getmetatable(L, className);
1433 lua_setmetatable(L, -2);
1437 static LuaItemStack* checkobject(lua_State *L, int narg)
1439 luaL_checktype(L, narg, LUA_TUSERDATA);
1440 void *ud = luaL_checkudata(L, narg, className);
1441 if(!ud) luaL_typerror(L, narg, className);
1442 return *(LuaItemStack**)ud; // unbox pointer
1445 static void Register(lua_State *L)
1448 int methodtable = lua_gettop(L);
1449 luaL_newmetatable(L, className);
1450 int metatable = lua_gettop(L);
1452 lua_pushliteral(L, "__metatable");
1453 lua_pushvalue(L, methodtable);
1454 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1456 lua_pushliteral(L, "__index");
1457 lua_pushvalue(L, methodtable);
1458 lua_settable(L, metatable);
1460 lua_pushliteral(L, "__gc");
1461 lua_pushcfunction(L, gc_object);
1462 lua_settable(L, metatable);
1464 lua_pop(L, 1); // drop metatable
1466 luaL_openlib(L, 0, methods, 0); // fill methodtable
1467 lua_pop(L, 1); // drop methodtable
1469 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1470 lua_register(L, className, create_object);
1473 const char LuaItemStack::className[] = "ItemStack";
1474 const luaL_reg LuaItemStack::methods[] = {
1475 method(LuaItemStack, is_empty),
1476 method(LuaItemStack, get_name),
1477 method(LuaItemStack, get_count),
1478 method(LuaItemStack, get_wear),
1479 method(LuaItemStack, get_metadata),
1480 method(LuaItemStack, clear),
1481 method(LuaItemStack, replace),
1482 method(LuaItemStack, to_string),
1483 method(LuaItemStack, to_table),
1484 method(LuaItemStack, get_stack_max),
1485 method(LuaItemStack, get_free_space),
1486 method(LuaItemStack, is_known),
1487 method(LuaItemStack, get_definition),
1488 method(LuaItemStack, get_tool_capabilities),
1489 method(LuaItemStack, add_wear),
1490 method(LuaItemStack, add_item),
1491 method(LuaItemStack, item_fits),
1492 method(LuaItemStack, take_item),
1493 method(LuaItemStack, peek_item),
1497 static ItemStack read_item(lua_State *L, int index)
1500 index = lua_gettop(L) + 1 + index;
1502 if(lua_isnil(L, index))
1506 else if(lua_isuserdata(L, index))
1508 // Convert from LuaItemStack
1509 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1510 return o->getItem();
1512 else if(lua_isstring(L, index))
1514 // Convert from itemstring
1515 std::string itemstring = lua_tostring(L, index);
1516 IItemDefManager *idef = get_server(L)->idef();
1520 item.deSerialize(itemstring, idef);
1523 catch(SerializationError &e)
1525 infostream<<"WARNING: unable to create item from itemstring"
1526 <<": "<<itemstring<<std::endl;
1530 else if(lua_istable(L, index))
1532 // Convert from table
1533 IItemDefManager *idef = get_server(L)->idef();
1534 std::string name = getstringfield_default(L, index, "name", "");
1535 int count = getintfield_default(L, index, "count", 1);
1536 int wear = getintfield_default(L, index, "wear", 0);
1537 std::string metadata = getstringfield_default(L, index, "metadata", "");
1538 return ItemStack(name, count, wear, metadata, idef);
1542 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1553 InventoryLocation m_loc;
1555 static const char className[];
1556 static const luaL_reg methods[];
1558 static InvRef *checkobject(lua_State *L, int narg)
1560 luaL_checktype(L, narg, LUA_TUSERDATA);
1561 void *ud = luaL_checkudata(L, narg, className);
1562 if(!ud) luaL_typerror(L, narg, className);
1563 return *(InvRef**)ud; // unbox pointer
1566 static Inventory* getinv(lua_State *L, InvRef *ref)
1568 return get_server(L)->getInventory(ref->m_loc);
1571 static InventoryList* getlist(lua_State *L, InvRef *ref,
1572 const char *listname)
1574 Inventory *inv = getinv(L, ref);
1577 return inv->getList(listname);
1580 static void reportInventoryChange(lua_State *L, InvRef *ref)
1582 // Inform other things that the inventory has changed
1583 get_server(L)->setInventoryModified(ref->m_loc);
1586 // Exported functions
1588 // garbage collector
1589 static int gc_object(lua_State *L) {
1590 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1595 // get_size(self, listname)
1596 static int l_get_size(lua_State *L)
1598 InvRef *ref = checkobject(L, 1);
1599 const char *listname = luaL_checkstring(L, 2);
1600 InventoryList *list = getlist(L, ref, listname);
1602 lua_pushinteger(L, list->getSize());
1604 lua_pushinteger(L, 0);
1609 // set_size(self, listname, size)
1610 static int l_set_size(lua_State *L)
1612 InvRef *ref = checkobject(L, 1);
1613 const char *listname = luaL_checkstring(L, 2);
1614 int newsize = luaL_checknumber(L, 3);
1615 Inventory *inv = getinv(L, ref);
1617 inv->deleteList(listname);
1618 reportInventoryChange(L, ref);
1621 InventoryList *list = inv->getList(listname);
1623 list->setSize(newsize);
1625 list = inv->addList(listname, newsize);
1627 reportInventoryChange(L, ref);
1631 // get_stack(self, listname, i) -> itemstack
1632 static int l_get_stack(lua_State *L)
1634 InvRef *ref = checkobject(L, 1);
1635 const char *listname = luaL_checkstring(L, 2);
1636 int i = luaL_checknumber(L, 3) - 1;
1637 InventoryList *list = getlist(L, ref, listname);
1639 if(list != NULL && i >= 0 && i < (int) list->getSize())
1640 item = list->getItem(i);
1641 LuaItemStack::create(L, item);
1645 // set_stack(self, listname, i, stack) -> true/false
1646 static int l_set_stack(lua_State *L)
1648 InvRef *ref = checkobject(L, 1);
1649 const char *listname = luaL_checkstring(L, 2);
1650 int i = luaL_checknumber(L, 3) - 1;
1651 ItemStack newitem = read_item(L, 4);
1652 InventoryList *list = getlist(L, ref, listname);
1653 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1654 list->changeItem(i, newitem);
1655 reportInventoryChange(L, ref);
1656 lua_pushboolean(L, true);
1658 lua_pushboolean(L, false);
1663 // get_list(self, listname) -> list or nil
1664 static int l_get_list(lua_State *L)
1666 InvRef *ref = checkobject(L, 1);
1667 const char *listname = luaL_checkstring(L, 2);
1668 Inventory *inv = getinv(L, ref);
1669 inventory_get_list_to_lua(inv, listname, L);
1673 // set_list(self, listname, list)
1674 static int l_set_list(lua_State *L)
1676 InvRef *ref = checkobject(L, 1);
1677 const char *listname = luaL_checkstring(L, 2);
1678 Inventory *inv = getinv(L, ref);
1679 InventoryList *list = inv->getList(listname);
1681 inventory_set_list_from_lua(inv, listname, L, 3,
1684 inventory_set_list_from_lua(inv, listname, L, 3);
1685 reportInventoryChange(L, ref);
1689 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1690 // Returns the leftover stack
1691 static int l_add_item(lua_State *L)
1693 InvRef *ref = checkobject(L, 1);
1694 const char *listname = luaL_checkstring(L, 2);
1695 ItemStack item = read_item(L, 3);
1696 InventoryList *list = getlist(L, ref, listname);
1698 ItemStack leftover = list->addItem(item);
1699 if(leftover.count != item.count)
1700 reportInventoryChange(L, ref);
1701 LuaItemStack::create(L, leftover);
1703 LuaItemStack::create(L, item);
1708 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1709 // Returns true if the item completely fits into the list
1710 static int l_room_for_item(lua_State *L)
1712 InvRef *ref = checkobject(L, 1);
1713 const char *listname = luaL_checkstring(L, 2);
1714 ItemStack item = read_item(L, 3);
1715 InventoryList *list = getlist(L, ref, listname);
1717 lua_pushboolean(L, list->roomForItem(item));
1719 lua_pushboolean(L, false);
1724 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1725 // Returns true if the list contains the given count of the given item name
1726 static int l_contains_item(lua_State *L)
1728 InvRef *ref = checkobject(L, 1);
1729 const char *listname = luaL_checkstring(L, 2);
1730 ItemStack item = read_item(L, 3);
1731 InventoryList *list = getlist(L, ref, listname);
1733 lua_pushboolean(L, list->containsItem(item));
1735 lua_pushboolean(L, false);
1740 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1741 // Returns the items that were actually removed
1742 static int l_remove_item(lua_State *L)
1744 InvRef *ref = checkobject(L, 1);
1745 const char *listname = luaL_checkstring(L, 2);
1746 ItemStack item = read_item(L, 3);
1747 InventoryList *list = getlist(L, ref, listname);
1749 ItemStack removed = list->removeItem(item);
1750 if(!removed.empty())
1751 reportInventoryChange(L, ref);
1752 LuaItemStack::create(L, removed);
1754 LuaItemStack::create(L, ItemStack());
1760 InvRef(const InventoryLocation &loc):
1769 // Creates an InvRef and leaves it on top of stack
1770 // Not callable from Lua; all references are created on the C side.
1771 static void create(lua_State *L, const InventoryLocation &loc)
1773 InvRef *o = new InvRef(loc);
1774 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1775 luaL_getmetatable(L, className);
1776 lua_setmetatable(L, -2);
1778 static void createPlayer(lua_State *L, Player *player)
1780 InventoryLocation loc;
1781 loc.setPlayer(player->getName());
1784 static void createNodeMeta(lua_State *L, v3s16 p)
1786 InventoryLocation loc;
1791 static void Register(lua_State *L)
1794 int methodtable = lua_gettop(L);
1795 luaL_newmetatable(L, className);
1796 int metatable = lua_gettop(L);
1798 lua_pushliteral(L, "__metatable");
1799 lua_pushvalue(L, methodtable);
1800 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1802 lua_pushliteral(L, "__index");
1803 lua_pushvalue(L, methodtable);
1804 lua_settable(L, metatable);
1806 lua_pushliteral(L, "__gc");
1807 lua_pushcfunction(L, gc_object);
1808 lua_settable(L, metatable);
1810 lua_pop(L, 1); // drop metatable
1812 luaL_openlib(L, 0, methods, 0); // fill methodtable
1813 lua_pop(L, 1); // drop methodtable
1815 // Cannot be created from Lua
1816 //lua_register(L, className, create_object);
1819 const char InvRef::className[] = "InvRef";
1820 const luaL_reg InvRef::methods[] = {
1821 method(InvRef, get_size),
1822 method(InvRef, set_size),
1823 method(InvRef, get_stack),
1824 method(InvRef, set_stack),
1825 method(InvRef, get_list),
1826 method(InvRef, set_list),
1827 method(InvRef, add_item),
1828 method(InvRef, room_for_item),
1829 method(InvRef, contains_item),
1830 method(InvRef, remove_item),
1842 ServerEnvironment *m_env;
1844 static const char className[];
1845 static const luaL_reg methods[];
1847 static NodeMetaRef *checkobject(lua_State *L, int narg)
1849 luaL_checktype(L, narg, LUA_TUSERDATA);
1850 void *ud = luaL_checkudata(L, narg, className);
1851 if(!ud) luaL_typerror(L, narg, className);
1852 return *(NodeMetaRef**)ud; // unbox pointer
1855 static NodeMetadata* getmeta(NodeMetaRef *ref)
1857 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1861 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1863 NodeMetadata *meta = getmeta(ref);
1866 if(meta->typeId() != NODEMETA_GENERIC)
1868 return (IGenericNodeMetadata*)meta;
1871 static void reportMetadataChange(NodeMetaRef *ref)
1873 // Inform other things that the metadata has changed
1874 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1876 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1878 ref->m_env->getMap().dispatchEvent(&event);
1879 // Set the block to be saved
1880 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1882 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1883 "NodeMetaRef::reportMetadataChange");
1886 // Exported functions
1888 // garbage collector
1889 static int gc_object(lua_State *L) {
1890 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1896 static int l_get_type(lua_State *L)
1898 NodeMetaRef *ref = checkobject(L, 1);
1899 NodeMetadata *meta = getmeta(ref);
1905 lua_pushstring(L, meta->typeName());
1909 // allows_text_input(self)
1910 static int l_allows_text_input(lua_State *L)
1912 NodeMetaRef *ref = checkobject(L, 1);
1913 NodeMetadata *meta = getmeta(ref);
1914 if(meta == NULL) return 0;
1916 lua_pushboolean(L, meta->allowsTextInput());
1920 // set_text(self, text)
1921 static int l_set_text(lua_State *L)
1923 NodeMetaRef *ref = checkobject(L, 1);
1924 NodeMetadata *meta = getmeta(ref);
1925 if(meta == NULL) return 0;
1927 std::string text = luaL_checkstring(L, 2);
1928 meta->setText(text);
1929 reportMetadataChange(ref);
1934 static int l_get_text(lua_State *L)
1936 NodeMetaRef *ref = checkobject(L, 1);
1937 NodeMetadata *meta = getmeta(ref);
1938 if(meta == NULL) return 0;
1940 std::string text = meta->getText();
1941 lua_pushstring(L, text.c_str());
1946 static int l_get_owner(lua_State *L)
1948 NodeMetaRef *ref = checkobject(L, 1);
1949 NodeMetadata *meta = getmeta(ref);
1950 if(meta == NULL) return 0;
1952 std::string owner = meta->getOwner();
1953 lua_pushstring(L, owner.c_str());
1957 // set_owner(self, string)
1958 static int l_set_owner(lua_State *L)
1960 NodeMetaRef *ref = checkobject(L, 1);
1961 NodeMetadata *meta = getmeta(ref);
1962 if(meta == NULL) return 0;
1964 std::string owner = luaL_checkstring(L, 2);
1965 meta->setOwner(owner);
1966 reportMetadataChange(ref);
1970 // get_allow_removal(self)
1971 static int l_get_allow_removal(lua_State *L)
1973 NodeMetaRef *ref = checkobject(L, 1);
1974 NodeMetadata *meta = getmeta(ref);
1976 lua_pushboolean(L, true);
1980 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1984 /* IGenericNodeMetadata interface */
1986 // set_infotext(self, text)
1987 static int l_set_infotext(lua_State *L)
1989 NodeMetaRef *ref = checkobject(L, 1);
1990 NodeMetadata *meta = getmeta(ref);
1991 if(meta == NULL) return 0;
1993 std::string text = luaL_checkstring(L, 2);
1994 meta->setInfoText(text);
1995 reportMetadataChange(ref);
1999 // get_inventory(self)
2000 static int l_get_inventory(lua_State *L)
2002 NodeMetaRef *ref = checkobject(L, 1);
2003 NodeMetadata *meta = getmeta(ref);
2004 if(meta == NULL) return 0;
2006 InvRef::createNodeMeta(L, ref->m_p);
2010 // set_inventory_draw_spec(self, text)
2011 static int l_set_inventory_draw_spec(lua_State *L)
2013 NodeMetaRef *ref = checkobject(L, 1);
2014 NodeMetadata *meta = getmeta(ref);
2015 if(meta == NULL) return 0;
2017 std::string text = luaL_checkstring(L, 2);
2018 meta->setInventoryDrawSpec(text);
2019 reportMetadataChange(ref);
2023 // set_allow_text_input(self, text)
2024 static int l_set_allow_text_input(lua_State *L)
2026 NodeMetaRef *ref = checkobject(L, 1);
2027 NodeMetadata *meta = getmeta(ref);
2028 if(meta == NULL) return 0;
2030 bool b = lua_toboolean(L, 2);
2031 meta->setAllowTextInput(b);
2032 reportMetadataChange(ref);
2036 // set_allow_removal(self, text)
2037 static int l_set_allow_removal(lua_State *L)
2039 NodeMetaRef *ref = checkobject(L, 1);
2040 NodeMetadata *meta = getmeta(ref);
2041 if(meta == NULL) return 0;
2043 bool b = lua_toboolean(L, 2);
2044 meta->setRemovalDisabled(!b);
2045 reportMetadataChange(ref);
2049 // set_enforce_owner(self, text)
2050 static int l_set_enforce_owner(lua_State *L)
2052 NodeMetaRef *ref = checkobject(L, 1);
2053 NodeMetadata *meta = getmeta(ref);
2054 if(meta == NULL) return 0;
2056 bool b = lua_toboolean(L, 2);
2057 meta->setEnforceOwner(b);
2058 reportMetadataChange(ref);
2062 // is_inventory_modified(self)
2063 static int l_is_inventory_modified(lua_State *L)
2065 NodeMetaRef *ref = checkobject(L, 1);
2066 NodeMetadata *meta = getmeta(ref);
2067 if(meta == NULL) return 0;
2069 lua_pushboolean(L, meta->isInventoryModified());
2073 // reset_inventory_modified(self)
2074 static int l_reset_inventory_modified(lua_State *L)
2076 NodeMetaRef *ref = checkobject(L, 1);
2077 NodeMetadata *meta = getmeta(ref);
2078 if(meta == NULL) return 0;
2080 meta->resetInventoryModified();
2081 reportMetadataChange(ref);
2085 // is_text_modified(self)
2086 static int l_is_text_modified(lua_State *L)
2088 NodeMetaRef *ref = checkobject(L, 1);
2089 NodeMetadata *meta = getmeta(ref);
2090 if(meta == NULL) return 0;
2092 lua_pushboolean(L, meta->isTextModified());
2096 // reset_text_modified(self)
2097 static int l_reset_text_modified(lua_State *L)
2099 NodeMetaRef *ref = checkobject(L, 1);
2100 NodeMetadata *meta = getmeta(ref);
2101 if(meta == NULL) return 0;
2103 meta->resetTextModified();
2104 reportMetadataChange(ref);
2108 // set_string(self, name, var)
2109 static int l_set_string(lua_State *L)
2111 NodeMetaRef *ref = checkobject(L, 1);
2112 NodeMetadata *meta = getmeta(ref);
2113 if(meta == NULL) return 0;
2115 std::string name = luaL_checkstring(L, 2);
2117 const char *s = lua_tolstring(L, 3, &len);
2118 std::string str(s, len);
2119 meta->setString(name, str);
2120 reportMetadataChange(ref);
2124 // get_string(self, name)
2125 static int l_get_string(lua_State *L)
2127 NodeMetaRef *ref = checkobject(L, 1);
2128 NodeMetadata *meta = getmeta(ref);
2129 if(meta == NULL) return 0;
2131 std::string name = luaL_checkstring(L, 2);
2132 std::string str = meta->getString(name);
2133 lua_pushlstring(L, str.c_str(), str.size());
2138 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2148 // Creates an NodeMetaRef and leaves it on top of stack
2149 // Not callable from Lua; all references are created on the C side.
2150 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2152 NodeMetaRef *o = new NodeMetaRef(p, env);
2153 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2154 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2155 luaL_getmetatable(L, className);
2156 lua_setmetatable(L, -2);
2159 static void Register(lua_State *L)
2162 int methodtable = lua_gettop(L);
2163 luaL_newmetatable(L, className);
2164 int metatable = lua_gettop(L);
2166 lua_pushliteral(L, "__metatable");
2167 lua_pushvalue(L, methodtable);
2168 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2170 lua_pushliteral(L, "__index");
2171 lua_pushvalue(L, methodtable);
2172 lua_settable(L, metatable);
2174 lua_pushliteral(L, "__gc");
2175 lua_pushcfunction(L, gc_object);
2176 lua_settable(L, metatable);
2178 lua_pop(L, 1); // drop metatable
2180 luaL_openlib(L, 0, methods, 0); // fill methodtable
2181 lua_pop(L, 1); // drop methodtable
2183 // Cannot be created from Lua
2184 //lua_register(L, className, create_object);
2187 const char NodeMetaRef::className[] = "NodeMetaRef";
2188 const luaL_reg NodeMetaRef::methods[] = {
2189 method(NodeMetaRef, get_type),
2190 method(NodeMetaRef, allows_text_input),
2191 method(NodeMetaRef, set_text),
2192 method(NodeMetaRef, get_text),
2193 method(NodeMetaRef, get_owner),
2194 method(NodeMetaRef, set_owner),
2195 method(NodeMetaRef, get_allow_removal),
2196 method(NodeMetaRef, set_infotext),
2197 method(NodeMetaRef, get_inventory),
2198 method(NodeMetaRef, set_inventory_draw_spec),
2199 method(NodeMetaRef, set_allow_text_input),
2200 method(NodeMetaRef, set_allow_removal),
2201 method(NodeMetaRef, set_enforce_owner),
2202 method(NodeMetaRef, is_inventory_modified),
2203 method(NodeMetaRef, reset_inventory_modified),
2204 method(NodeMetaRef, is_text_modified),
2205 method(NodeMetaRef, reset_text_modified),
2206 method(NodeMetaRef, set_string),
2207 method(NodeMetaRef, get_string),
2218 ServerActiveObject *m_object;
2220 static const char className[];
2221 static const luaL_reg methods[];
2223 static ObjectRef *checkobject(lua_State *L, int narg)
2225 luaL_checktype(L, narg, LUA_TUSERDATA);
2226 void *ud = luaL_checkudata(L, narg, className);
2227 if(!ud) luaL_typerror(L, narg, className);
2228 return *(ObjectRef**)ud; // unbox pointer
2231 static ServerActiveObject* getobject(ObjectRef *ref)
2233 ServerActiveObject *co = ref->m_object;
2237 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2239 ServerActiveObject *obj = getobject(ref);
2242 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2244 return (LuaEntitySAO*)obj;
2247 static ServerRemotePlayer* getplayer(ObjectRef *ref)
2249 ServerActiveObject *obj = getobject(ref);
2252 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2254 return static_cast<ServerRemotePlayer*>(obj);
2257 // Exported functions
2259 // garbage collector
2260 static int gc_object(lua_State *L) {
2261 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2262 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2268 static int l_remove(lua_State *L)
2270 ObjectRef *ref = checkobject(L, 1);
2271 ServerActiveObject *co = getobject(ref);
2272 if(co == NULL) return 0;
2273 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2274 co->m_removed = true;
2279 // returns: {x=num, y=num, z=num}
2280 static int l_getpos(lua_State *L)
2282 ObjectRef *ref = checkobject(L, 1);
2283 ServerActiveObject *co = getobject(ref);
2284 if(co == NULL) return 0;
2285 v3f pos = co->getBasePosition() / BS;
2287 lua_pushnumber(L, pos.X);
2288 lua_setfield(L, -2, "x");
2289 lua_pushnumber(L, pos.Y);
2290 lua_setfield(L, -2, "y");
2291 lua_pushnumber(L, pos.Z);
2292 lua_setfield(L, -2, "z");
2296 // setpos(self, pos)
2297 static int l_setpos(lua_State *L)
2299 ObjectRef *ref = checkobject(L, 1);
2300 //LuaEntitySAO *co = getluaobject(ref);
2301 ServerActiveObject *co = getobject(ref);
2302 if(co == NULL) return 0;
2304 v3f pos = checkFloatPos(L, 2);
2307 // Move player if applicable
2308 ServerRemotePlayer *player = getplayer(ref);
2310 get_server(L)->SendMovePlayer(player);
2314 // moveto(self, pos, continuous=false)
2315 static int l_moveto(lua_State *L)
2317 ObjectRef *ref = checkobject(L, 1);
2318 //LuaEntitySAO *co = getluaobject(ref);
2319 ServerActiveObject *co = getobject(ref);
2320 if(co == NULL) return 0;
2322 v3f pos = checkFloatPos(L, 2);
2324 bool continuous = lua_toboolean(L, 3);
2326 co->moveTo(pos, continuous);
2330 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2331 static int l_punch(lua_State *L)
2333 ObjectRef *ref = checkobject(L, 1);
2334 ObjectRef *puncher_ref = checkobject(L, 2);
2335 ServerActiveObject *co = getobject(ref);
2336 ServerActiveObject *puncher = getobject(puncher_ref);
2337 if(co == NULL) return 0;
2338 if(puncher == NULL) return 0;
2339 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2340 v3f dir = read_v3f(L, 4);
2341 float time_from_last_punch = 1000000;
2342 if(lua_isnumber(L, 5))
2343 time_from_last_punch = lua_tonumber(L, 5);
2345 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2349 // right_click(self, clicker); clicker = an another ObjectRef
2350 static int l_right_click(lua_State *L)
2352 ObjectRef *ref = checkobject(L, 1);
2353 ObjectRef *ref2 = checkobject(L, 2);
2354 ServerActiveObject *co = getobject(ref);
2355 ServerActiveObject *co2 = getobject(ref2);
2356 if(co == NULL) return 0;
2357 if(co2 == NULL) return 0;
2359 co->rightClick(co2);
2364 // hp = number of hitpoints (2 * number of hearts)
2366 static int l_set_hp(lua_State *L)
2368 ObjectRef *ref = checkobject(L, 1);
2369 luaL_checknumber(L, 2);
2370 ServerActiveObject *co = getobject(ref);
2371 if(co == NULL) return 0;
2372 int hp = lua_tonumber(L, 2);
2373 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2374 <<" hp="<<hp<<std::endl;*/
2382 // returns: number of hitpoints (2 * number of hearts)
2383 // 0 if not applicable to this type of object
2384 static int l_get_hp(lua_State *L)
2386 ObjectRef *ref = checkobject(L, 1);
2387 ServerActiveObject *co = getobject(ref);
2388 if(co == NULL) return 0;
2389 int hp = co->getHP();
2390 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2391 <<" hp="<<hp<<std::endl;*/
2393 lua_pushnumber(L, hp);
2397 // get_inventory(self)
2398 static int l_get_inventory(lua_State *L)
2400 ObjectRef *ref = checkobject(L, 1);
2401 ServerActiveObject *co = getobject(ref);
2402 if(co == NULL) return 0;
2404 InventoryLocation loc = co->getInventoryLocation();
2405 if(get_server(L)->getInventory(loc) != NULL)
2406 InvRef::create(L, loc);
2412 // get_wield_list(self)
2413 static int l_get_wield_list(lua_State *L)
2415 ObjectRef *ref = checkobject(L, 1);
2416 ServerActiveObject *co = getobject(ref);
2417 if(co == NULL) return 0;
2419 lua_pushstring(L, co->getWieldList().c_str());
2423 // get_wield_index(self)
2424 static int l_get_wield_index(lua_State *L)
2426 ObjectRef *ref = checkobject(L, 1);
2427 ServerActiveObject *co = getobject(ref);
2428 if(co == NULL) return 0;
2430 lua_pushinteger(L, co->getWieldIndex() + 1);
2434 // get_wielded_item(self)
2435 static int l_get_wielded_item(lua_State *L)
2437 ObjectRef *ref = checkobject(L, 1);
2438 ServerActiveObject *co = getobject(ref);
2439 if(co == NULL) return 0;
2441 LuaItemStack::create(L, co->getWieldedItem());
2445 // set_wielded_item(self, itemstack or itemstring or table or nil)
2446 static int l_set_wielded_item(lua_State *L)
2448 ObjectRef *ref = checkobject(L, 1);
2449 ServerActiveObject *co = getobject(ref);
2450 if(co == NULL) return 0;
2452 ItemStack item = read_item(L, 2);
2453 bool success = co->setWieldedItem(item);
2454 lua_pushboolean(L, success);
2458 /* LuaEntitySAO-only */
2460 // setvelocity(self, {x=num, y=num, z=num})
2461 static int l_setvelocity(lua_State *L)
2463 ObjectRef *ref = checkobject(L, 1);
2464 LuaEntitySAO *co = getluaobject(ref);
2465 if(co == NULL) return 0;
2467 v3f pos = checkFloatPos(L, 2);
2469 co->setVelocity(pos);
2473 // getvelocity(self)
2474 static int l_getvelocity(lua_State *L)
2476 ObjectRef *ref = checkobject(L, 1);
2477 LuaEntitySAO *co = getluaobject(ref);
2478 if(co == NULL) return 0;
2480 v3f v = co->getVelocity();
2485 // setacceleration(self, {x=num, y=num, z=num})
2486 static int l_setacceleration(lua_State *L)
2488 ObjectRef *ref = checkobject(L, 1);
2489 LuaEntitySAO *co = getluaobject(ref);
2490 if(co == NULL) return 0;
2492 v3f pos = checkFloatPos(L, 2);
2494 co->setAcceleration(pos);
2498 // getacceleration(self)
2499 static int l_getacceleration(lua_State *L)
2501 ObjectRef *ref = checkobject(L, 1);
2502 LuaEntitySAO *co = getluaobject(ref);
2503 if(co == NULL) return 0;
2505 v3f v = co->getAcceleration();
2510 // setyaw(self, radians)
2511 static int l_setyaw(lua_State *L)
2513 ObjectRef *ref = checkobject(L, 1);
2514 LuaEntitySAO *co = getluaobject(ref);
2515 if(co == NULL) return 0;
2517 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2524 static int l_getyaw(lua_State *L)
2526 ObjectRef *ref = checkobject(L, 1);
2527 LuaEntitySAO *co = getluaobject(ref);
2528 if(co == NULL) return 0;
2530 float yaw = co->getYaw() * core::DEGTORAD;
2531 lua_pushnumber(L, yaw);
2535 // settexturemod(self, mod)
2536 static int l_settexturemod(lua_State *L)
2538 ObjectRef *ref = checkobject(L, 1);
2539 LuaEntitySAO *co = getluaobject(ref);
2540 if(co == NULL) return 0;
2542 std::string mod = luaL_checkstring(L, 2);
2543 co->setTextureMod(mod);
2547 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2548 // select_horiz_by_yawpitch=false)
2549 static int l_setsprite(lua_State *L)
2551 ObjectRef *ref = checkobject(L, 1);
2552 LuaEntitySAO *co = getluaobject(ref);
2553 if(co == NULL) return 0;
2556 if(!lua_isnil(L, 2))
2557 p = read_v2s16(L, 2);
2559 if(!lua_isnil(L, 3))
2560 num_frames = lua_tonumber(L, 3);
2561 float framelength = 0.2;
2562 if(!lua_isnil(L, 4))
2563 framelength = lua_tonumber(L, 4);
2564 bool select_horiz_by_yawpitch = false;
2565 if(!lua_isnil(L, 5))
2566 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2567 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2571 // set_armor_groups(self, groups)
2572 static int l_set_armor_groups(lua_State *L)
2574 ObjectRef *ref = checkobject(L, 1);
2575 LuaEntitySAO *co = getluaobject(ref);
2576 if(co == NULL) return 0;
2578 ItemGroupList groups;
2579 read_groups(L, 2, groups);
2580 co->setArmorGroups(groups);
2585 // get_entity_name(self)
2586 static int l_get_entity_name(lua_State *L)
2588 ObjectRef *ref = checkobject(L, 1);
2589 LuaEntitySAO *co = getluaobject(ref);
2590 if(co == NULL) return 0;
2592 std::string name = co->getName();
2593 lua_pushstring(L, name.c_str());
2597 // get_luaentity(self)
2598 static int l_get_luaentity(lua_State *L)
2600 ObjectRef *ref = checkobject(L, 1);
2601 LuaEntitySAO *co = getluaobject(ref);
2602 if(co == NULL) return 0;
2604 luaentity_get(L, co->getId());
2610 // get_player_name(self)
2611 static int l_get_player_name(lua_State *L)
2613 ObjectRef *ref = checkobject(L, 1);
2614 ServerRemotePlayer *player = getplayer(ref);
2620 lua_pushstring(L, player->getName());
2624 // get_look_dir(self)
2625 static int l_get_look_dir(lua_State *L)
2627 ObjectRef *ref = checkobject(L, 1);
2628 ServerRemotePlayer *player = getplayer(ref);
2629 if(player == NULL) return 0;
2631 float pitch = player->getRadPitch();
2632 float yaw = player->getRadYaw();
2633 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2638 // get_look_pitch(self)
2639 static int l_get_look_pitch(lua_State *L)
2641 ObjectRef *ref = checkobject(L, 1);
2642 ServerRemotePlayer *player = getplayer(ref);
2643 if(player == NULL) return 0;
2645 lua_pushnumber(L, player->getRadPitch());
2649 // get_look_yaw(self)
2650 static int l_get_look_yaw(lua_State *L)
2652 ObjectRef *ref = checkobject(L, 1);
2653 ServerRemotePlayer *player = getplayer(ref);
2654 if(player == NULL) return 0;
2656 lua_pushnumber(L, player->getRadYaw());
2661 ObjectRef(ServerActiveObject *object):
2664 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2670 infostream<<"ObjectRef destructing for id="
2671 <<m_object->getId()<<std::endl;
2673 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2676 // Creates an ObjectRef and leaves it on top of stack
2677 // Not callable from Lua; all references are created on the C side.
2678 static void create(lua_State *L, ServerActiveObject *object)
2680 ObjectRef *o = new ObjectRef(object);
2681 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2682 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2683 luaL_getmetatable(L, className);
2684 lua_setmetatable(L, -2);
2687 static void set_null(lua_State *L)
2689 ObjectRef *o = checkobject(L, -1);
2693 static void Register(lua_State *L)
2696 int methodtable = lua_gettop(L);
2697 luaL_newmetatable(L, className);
2698 int metatable = lua_gettop(L);
2700 lua_pushliteral(L, "__metatable");
2701 lua_pushvalue(L, methodtable);
2702 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2704 lua_pushliteral(L, "__index");
2705 lua_pushvalue(L, methodtable);
2706 lua_settable(L, metatable);
2708 lua_pushliteral(L, "__gc");
2709 lua_pushcfunction(L, gc_object);
2710 lua_settable(L, metatable);
2712 lua_pop(L, 1); // drop metatable
2714 luaL_openlib(L, 0, methods, 0); // fill methodtable
2715 lua_pop(L, 1); // drop methodtable
2717 // Cannot be created from Lua
2718 //lua_register(L, className, create_object);
2721 const char ObjectRef::className[] = "ObjectRef";
2722 const luaL_reg ObjectRef::methods[] = {
2723 // ServerActiveObject
2724 method(ObjectRef, remove),
2725 method(ObjectRef, getpos),
2726 method(ObjectRef, setpos),
2727 method(ObjectRef, moveto),
2728 method(ObjectRef, punch),
2729 method(ObjectRef, right_click),
2730 method(ObjectRef, set_hp),
2731 method(ObjectRef, get_hp),
2732 method(ObjectRef, get_inventory),
2733 method(ObjectRef, get_wield_list),
2734 method(ObjectRef, get_wield_index),
2735 method(ObjectRef, get_wielded_item),
2736 method(ObjectRef, set_wielded_item),
2737 // LuaEntitySAO-only
2738 method(ObjectRef, setvelocity),
2739 method(ObjectRef, getvelocity),
2740 method(ObjectRef, setacceleration),
2741 method(ObjectRef, getacceleration),
2742 method(ObjectRef, setyaw),
2743 method(ObjectRef, getyaw),
2744 method(ObjectRef, settexturemod),
2745 method(ObjectRef, setsprite),
2746 method(ObjectRef, set_armor_groups),
2747 method(ObjectRef, get_entity_name),
2748 method(ObjectRef, get_luaentity),
2750 method(ObjectRef, get_player_name),
2751 method(ObjectRef, get_look_dir),
2752 method(ObjectRef, get_look_pitch),
2753 method(ObjectRef, get_look_yaw),
2757 // Creates a new anonymous reference if id=0
2758 static void objectref_get_or_create(lua_State *L,
2759 ServerActiveObject *cobj)
2761 if(cobj->getId() == 0){
2762 ObjectRef::create(L, cobj);
2764 objectref_get(L, cobj->getId());
2775 ServerEnvironment *m_env;
2777 static const char className[];
2778 static const luaL_reg methods[];
2780 static EnvRef *checkobject(lua_State *L, int narg)
2782 luaL_checktype(L, narg, LUA_TUSERDATA);
2783 void *ud = luaL_checkudata(L, narg, className);
2784 if(!ud) luaL_typerror(L, narg, className);
2785 return *(EnvRef**)ud; // unbox pointer
2788 // Exported functions
2790 // EnvRef:add_node(pos, node)
2791 // pos = {x=num, y=num, z=num}
2792 static int l_add_node(lua_State *L)
2794 //infostream<<"EnvRef::l_add_node()"<<std::endl;
2795 EnvRef *o = checkobject(L, 1);
2796 ServerEnvironment *env = o->m_env;
2797 if(env == NULL) return 0;
2799 v3s16 pos = read_v3s16(L, 2);
2801 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2803 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2804 lua_pushboolean(L, succeeded);
2808 // EnvRef:remove_node(pos)
2809 // pos = {x=num, y=num, z=num}
2810 static int l_remove_node(lua_State *L)
2812 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2813 EnvRef *o = checkobject(L, 1);
2814 ServerEnvironment *env = o->m_env;
2815 if(env == NULL) return 0;
2817 v3s16 pos = read_v3s16(L, 2);
2819 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2820 lua_pushboolean(L, succeeded);
2824 // EnvRef:get_node(pos)
2825 // pos = {x=num, y=num, z=num}
2826 static int l_get_node(lua_State *L)
2828 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2829 EnvRef *o = checkobject(L, 1);
2830 ServerEnvironment *env = o->m_env;
2831 if(env == NULL) return 0;
2833 v3s16 pos = read_v3s16(L, 2);
2835 MapNode n = env->getMap().getNodeNoEx(pos);
2837 pushnode(L, n, env->getGameDef()->ndef());
2841 // EnvRef:get_node_or_nil(pos)
2842 // pos = {x=num, y=num, z=num}
2843 static int l_get_node_or_nil(lua_State *L)
2845 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2846 EnvRef *o = checkobject(L, 1);
2847 ServerEnvironment *env = o->m_env;
2848 if(env == NULL) return 0;
2850 v3s16 pos = read_v3s16(L, 2);
2853 MapNode n = env->getMap().getNode(pos);
2855 pushnode(L, n, env->getGameDef()->ndef());
2857 } catch(InvalidPositionException &e)
2864 // EnvRef:get_node_light(pos, timeofday)
2865 // pos = {x=num, y=num, z=num}
2866 // timeofday: nil = current time, 0 = night, 0.5 = day
2867 static int l_get_node_light(lua_State *L)
2869 EnvRef *o = checkobject(L, 1);
2870 ServerEnvironment *env = o->m_env;
2871 if(env == NULL) return 0;
2873 v3s16 pos = read_v3s16(L, 2);
2874 u32 time_of_day = env->getTimeOfDay();
2875 if(lua_isnumber(L, 3))
2876 time_of_day = 24000.0 * lua_tonumber(L, 3);
2877 time_of_day %= 24000;
2878 u32 dnr = time_to_daynight_ratio(time_of_day);
2879 MapNode n = env->getMap().getNodeNoEx(pos);
2881 MapNode n = env->getMap().getNode(pos);
2882 INodeDefManager *ndef = env->getGameDef()->ndef();
2883 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2885 } catch(InvalidPositionException &e)
2892 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2893 // pos = {x=num, y=num, z=num}
2894 static int l_add_entity(lua_State *L)
2896 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2897 EnvRef *o = checkobject(L, 1);
2898 ServerEnvironment *env = o->m_env;
2899 if(env == NULL) return 0;
2901 v3f pos = checkFloatPos(L, 2);
2903 const char *name = luaL_checkstring(L, 3);
2905 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2906 int objectid = env->addActiveObject(obj);
2907 // If failed to add, return nothing (reads as nil)
2911 objectref_get_or_create(L, obj);
2915 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2916 // pos = {x=num, y=num, z=num}
2917 static int l_add_item(lua_State *L)
2919 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2920 EnvRef *o = checkobject(L, 1);
2921 ServerEnvironment *env = o->m_env;
2922 if(env == NULL) return 0;
2924 v3f pos = checkFloatPos(L, 2);
2926 ItemStack item = read_item(L, 3);
2927 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2930 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2931 int objectid = env->addActiveObject(obj);
2932 // If failed to add, return nothing (reads as nil)
2936 objectref_get_or_create(L, obj);
2940 // EnvRef:add_rat(pos)
2941 // pos = {x=num, y=num, z=num}
2942 static int l_add_rat(lua_State *L)
2944 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2945 <<" Doing nothing."<<std::endl;
2949 // EnvRef:add_firefly(pos)
2950 // pos = {x=num, y=num, z=num}
2951 static int l_add_firefly(lua_State *L)
2953 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2954 <<" Doing nothing."<<std::endl;
2958 // EnvRef:get_meta(pos)
2959 static int l_get_meta(lua_State *L)
2961 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2962 EnvRef *o = checkobject(L, 1);
2963 ServerEnvironment *env = o->m_env;
2964 if(env == NULL) return 0;
2966 v3s16 p = read_v3s16(L, 2);
2967 NodeMetaRef::create(L, p, env);
2971 // EnvRef:get_player_by_name(name)
2972 static int l_get_player_by_name(lua_State *L)
2974 EnvRef *o = checkobject(L, 1);
2975 ServerEnvironment *env = o->m_env;
2976 if(env == NULL) return 0;
2978 const char *name = luaL_checkstring(L, 2);
2979 ServerRemotePlayer *player =
2980 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2985 // Put player on stack
2986 objectref_get_or_create(L, player);
2990 // EnvRef:get_objects_inside_radius(pos, radius)
2991 static int l_get_objects_inside_radius(lua_State *L)
2993 // Get the table insert function
2994 lua_getglobal(L, "table");
2995 lua_getfield(L, -1, "insert");
2996 int table_insert = lua_gettop(L);
2998 EnvRef *o = checkobject(L, 1);
2999 ServerEnvironment *env = o->m_env;
3000 if(env == NULL) return 0;
3002 v3f pos = checkFloatPos(L, 2);
3003 float radius = luaL_checknumber(L, 3) * BS;
3004 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3006 int table = lua_gettop(L);
3007 for(std::set<u16>::const_iterator
3008 i = ids.begin(); i != ids.end(); i++){
3009 ServerActiveObject *obj = env->getActiveObject(*i);
3010 // Insert object reference into table
3011 lua_pushvalue(L, table_insert);
3012 lua_pushvalue(L, table);
3013 objectref_get_or_create(L, obj);
3014 if(lua_pcall(L, 2, 0, 0))
3015 script_error(L, "error: %s", lua_tostring(L, -1));
3020 // EnvRef:set_timeofday(val)
3022 static int l_set_timeofday(lua_State *L)
3024 EnvRef *o = checkobject(L, 1);
3025 ServerEnvironment *env = o->m_env;
3026 if(env == NULL) return 0;
3028 float timeofday_f = luaL_checknumber(L, 2);
3029 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3030 int timeofday_mh = (int)(timeofday_f * 24000.0);
3031 // This should be set directly in the environment but currently
3032 // such changes aren't immediately sent to the clients, so call
3033 // the server instead.
3034 //env->setTimeOfDay(timeofday_mh);
3035 get_server(L)->setTimeOfDay(timeofday_mh);
3039 // EnvRef:get_timeofday() -> 0...1
3040 static int l_get_timeofday(lua_State *L)
3042 EnvRef *o = checkobject(L, 1);
3043 ServerEnvironment *env = o->m_env;
3044 if(env == NULL) return 0;
3046 int timeofday_mh = env->getTimeOfDay();
3047 float timeofday_f = (float)timeofday_mh / 24000.0;
3048 lua_pushnumber(L, timeofday_f);
3052 static int gc_object(lua_State *L) {
3053 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3059 EnvRef(ServerEnvironment *env):
3062 //infostream<<"EnvRef created"<<std::endl;
3067 //infostream<<"EnvRef destructing"<<std::endl;
3070 // Creates an EnvRef and leaves it on top of stack
3071 // Not callable from Lua; all references are created on the C side.
3072 static void create(lua_State *L, ServerEnvironment *env)
3074 EnvRef *o = new EnvRef(env);
3075 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3076 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3077 luaL_getmetatable(L, className);
3078 lua_setmetatable(L, -2);
3081 static void set_null(lua_State *L)
3083 EnvRef *o = checkobject(L, -1);
3087 static void Register(lua_State *L)
3090 int methodtable = lua_gettop(L);
3091 luaL_newmetatable(L, className);
3092 int metatable = lua_gettop(L);
3094 lua_pushliteral(L, "__metatable");
3095 lua_pushvalue(L, methodtable);
3096 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3098 lua_pushliteral(L, "__index");
3099 lua_pushvalue(L, methodtable);
3100 lua_settable(L, metatable);
3102 lua_pushliteral(L, "__gc");
3103 lua_pushcfunction(L, gc_object);
3104 lua_settable(L, metatable);
3106 lua_pop(L, 1); // drop metatable
3108 luaL_openlib(L, 0, methods, 0); // fill methodtable
3109 lua_pop(L, 1); // drop methodtable
3111 // Cannot be created from Lua
3112 //lua_register(L, className, create_object);
3115 const char EnvRef::className[] = "EnvRef";
3116 const luaL_reg EnvRef::methods[] = {
3117 method(EnvRef, add_node),
3118 method(EnvRef, remove_node),
3119 method(EnvRef, get_node),
3120 method(EnvRef, get_node_or_nil),
3121 method(EnvRef, get_node_light),
3122 method(EnvRef, add_entity),
3123 method(EnvRef, add_item),
3124 method(EnvRef, add_rat),
3125 method(EnvRef, add_firefly),
3126 method(EnvRef, get_meta),
3127 method(EnvRef, get_player_by_name),
3128 method(EnvRef, get_objects_inside_radius),
3129 method(EnvRef, set_timeofday),
3130 method(EnvRef, get_timeofday),
3138 class LuaABM : public ActiveBlockModifier
3144 std::set<std::string> m_trigger_contents;
3145 std::set<std::string> m_required_neighbors;
3146 float m_trigger_interval;
3147 u32 m_trigger_chance;
3149 LuaABM(lua_State *L, int id,
3150 const std::set<std::string> &trigger_contents,
3151 const std::set<std::string> &required_neighbors,
3152 float trigger_interval, u32 trigger_chance):
3155 m_trigger_contents(trigger_contents),
3156 m_required_neighbors(required_neighbors),
3157 m_trigger_interval(trigger_interval),
3158 m_trigger_chance(trigger_chance)
3161 virtual std::set<std::string> getTriggerContents()
3163 return m_trigger_contents;
3165 virtual std::set<std::string> getRequiredNeighbors()
3167 return m_required_neighbors;
3169 virtual float getTriggerInterval()
3171 return m_trigger_interval;
3173 virtual u32 getTriggerChance()
3175 return m_trigger_chance;
3177 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3178 u32 active_object_count, u32 active_object_count_wider)
3180 lua_State *L = m_lua;
3183 assert(lua_checkstack(L, 20));
3184 StackUnroller stack_unroller(L);
3186 // Get minetest.registered_abms
3187 lua_getglobal(L, "minetest");
3188 lua_getfield(L, -1, "registered_abms");
3189 luaL_checktype(L, -1, LUA_TTABLE);
3190 int registered_abms = lua_gettop(L);
3192 // Get minetest.registered_abms[m_id]
3193 lua_pushnumber(L, m_id);
3194 lua_gettable(L, registered_abms);
3195 if(lua_isnil(L, -1))
3199 luaL_checktype(L, -1, LUA_TTABLE);
3200 lua_getfield(L, -1, "action");
3201 luaL_checktype(L, -1, LUA_TFUNCTION);
3203 pushnode(L, n, env->getGameDef()->ndef());
3204 lua_pushnumber(L, active_object_count);
3205 lua_pushnumber(L, active_object_count_wider);
3206 if(lua_pcall(L, 4, 0, 0))
3207 script_error(L, "error: %s", lua_tostring(L, -1));
3212 // Writes a line to dstream
3213 static int l_debug(lua_State *L)
3215 std::string text = lua_tostring(L, 1);
3216 dstream << text << std::endl;
3220 // log([level,] text)
3221 // Writes a line to the logger.
3222 // The one-argument version logs to infostream.
3223 // The two-argument version accept a log level: error, action, info, or verbose.
3224 static int l_log(lua_State *L)
3227 LogMessageLevel level = LMT_INFO;
3228 if(lua_isnone(L, 2))
3230 text = lua_tostring(L, 1);
3234 std::string levelname = lua_tostring(L, 1);
3235 text = lua_tostring(L, 2);
3236 if(levelname == "error")
3238 else if(levelname == "action")
3240 else if(levelname == "verbose")
3241 level = LMT_VERBOSE;
3243 log_printline(level, text);
3247 // register_item_raw({lots of stuff})
3248 static int l_register_item_raw(lua_State *L)
3250 luaL_checktype(L, 1, LUA_TTABLE);
3253 // Get the writable item and node definition managers from the server
3254 IWritableItemDefManager *idef =
3255 get_server(L)->getWritableItemDefManager();
3256 IWritableNodeDefManager *ndef =
3257 get_server(L)->getWritableNodeDefManager();
3259 // Check if name is defined
3260 lua_getfield(L, table, "name");
3261 if(lua_isstring(L, -1)){
3262 std::string name = lua_tostring(L, -1);
3263 verbosestream<<"register_item_raw: "<<name<<std::endl;
3265 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3268 // Check if on_use is defined
3270 // Read the item definition and register it
3271 ItemDefinition def = read_item_definition(L, table);
3272 idef->registerItem(def);
3274 // Read the node definition (content features) and register it
3275 if(def.type == ITEM_NODE)
3277 ContentFeatures f = read_content_features(L, table);
3278 ndef->set(f.name, f);
3281 return 0; /* number of results */
3284 // register_alias_raw(name, convert_to_name)
3285 static int l_register_alias_raw(lua_State *L)
3287 std::string name = luaL_checkstring(L, 1);
3288 std::string convert_to = luaL_checkstring(L, 2);
3290 // Get the writable item definition manager from the server
3291 IWritableItemDefManager *idef =
3292 get_server(L)->getWritableItemDefManager();
3294 idef->registerAlias(name, convert_to);
3296 return 0; /* number of results */
3299 // helper for register_craft
3300 static bool read_craft_recipe_shaped(lua_State *L, int index,
3301 int &width, std::vector<std::string> &recipe)
3304 index = lua_gettop(L) + 1 + index;
3306 if(!lua_istable(L, index))
3311 while(lua_next(L, index) != 0){
3313 // key at index -2 and value at index -1
3314 if(!lua_istable(L, -1))
3316 int table2 = lua_gettop(L);
3318 while(lua_next(L, table2) != 0){
3319 // key at index -2 and value at index -1
3320 if(!lua_isstring(L, -1))
3322 recipe.push_back(lua_tostring(L, -1));
3323 // removes value, keeps key for next iteration
3330 if(colcount != width)
3333 // removes value, keeps key for next iteration
3340 // helper for register_craft
3341 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3342 std::vector<std::string> &recipe)
3345 index = lua_gettop(L) + 1 + index;
3347 if(!lua_istable(L, index))
3351 while(lua_next(L, index) != 0){
3352 // key at index -2 and value at index -1
3353 if(!lua_isstring(L, -1))
3355 recipe.push_back(lua_tostring(L, -1));
3356 // removes value, keeps key for next iteration
3362 // helper for register_craft
3363 static bool read_craft_replacements(lua_State *L, int index,
3364 CraftReplacements &replacements)
3367 index = lua_gettop(L) + 1 + index;
3369 if(!lua_istable(L, index))
3373 while(lua_next(L, index) != 0){
3374 // key at index -2 and value at index -1
3375 if(!lua_istable(L, -1))
3377 lua_rawgeti(L, -1, 1);
3378 if(!lua_isstring(L, -1))
3380 std::string replace_from = lua_tostring(L, -1);
3382 lua_rawgeti(L, -1, 2);
3383 if(!lua_isstring(L, -1))
3385 std::string replace_to = lua_tostring(L, -1);
3387 replacements.pairs.push_back(
3388 std::make_pair(replace_from, replace_to));
3389 // removes value, keeps key for next iteration
3394 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3395 static int l_register_craft(lua_State *L)
3397 //infostream<<"register_craft"<<std::endl;
3398 luaL_checktype(L, 1, LUA_TTABLE);
3401 // Get the writable craft definition manager from the server
3402 IWritableCraftDefManager *craftdef =
3403 get_server(L)->getWritableCraftDefManager();
3405 std::string type = getstringfield_default(L, table, "type", "shaped");
3408 CraftDefinitionShaped
3410 if(type == "shaped"){
3411 std::string output = getstringfield_default(L, table, "output", "");
3413 throw LuaError(L, "Crafting definition is missing an output");
3416 std::vector<std::string> recipe;
3417 lua_getfield(L, table, "recipe");
3418 if(lua_isnil(L, -1))
3419 throw LuaError(L, "Crafting definition is missing a recipe"
3420 " (output=\"" + output + "\")");
3421 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3422 throw LuaError(L, "Invalid crafting recipe"
3423 " (output=\"" + output + "\")");
3425 CraftReplacements replacements;
3426 lua_getfield(L, table, "replacements");
3427 if(!lua_isnil(L, -1))
3429 if(!read_craft_replacements(L, -1, replacements))
3430 throw LuaError(L, "Invalid replacements"
3431 " (output=\"" + output + "\")");
3434 CraftDefinition *def = new CraftDefinitionShaped(
3435 output, width, recipe, replacements);
3436 craftdef->registerCraft(def);
3439 CraftDefinitionShapeless
3441 else if(type == "shapeless"){
3442 std::string output = getstringfield_default(L, table, "output", "");
3444 throw LuaError(L, "Crafting definition (shapeless)"
3445 " is missing an output");
3447 std::vector<std::string> recipe;
3448 lua_getfield(L, table, "recipe");
3449 if(lua_isnil(L, -1))
3450 throw LuaError(L, "Crafting definition (shapeless)"
3451 " is missing a recipe"
3452 " (output=\"" + output + "\")");
3453 if(!read_craft_recipe_shapeless(L, -1, recipe))
3454 throw LuaError(L, "Invalid crafting recipe"
3455 " (output=\"" + output + "\")");
3457 CraftReplacements replacements;
3458 lua_getfield(L, table, "replacements");
3459 if(!lua_isnil(L, -1))
3461 if(!read_craft_replacements(L, -1, replacements))
3462 throw LuaError(L, "Invalid replacements"
3463 " (output=\"" + output + "\")");
3466 CraftDefinition *def = new CraftDefinitionShapeless(
3467 output, recipe, replacements);
3468 craftdef->registerCraft(def);
3471 CraftDefinitionToolRepair
3473 else if(type == "toolrepair"){
3474 float additional_wear = getfloatfield_default(L, table,
3475 "additional_wear", 0.0);
3477 CraftDefinition *def = new CraftDefinitionToolRepair(
3479 craftdef->registerCraft(def);
3482 CraftDefinitionCooking
3484 else if(type == "cooking"){
3485 std::string output = getstringfield_default(L, table, "output", "");
3487 throw LuaError(L, "Crafting definition (cooking)"
3488 " is missing an output");
3490 std::string recipe = getstringfield_default(L, table, "recipe", "");
3492 throw LuaError(L, "Crafting definition (cooking)"
3493 " is missing a recipe"
3494 " (output=\"" + output + "\")");
3496 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3498 CraftDefinition *def = new CraftDefinitionCooking(
3499 output, recipe, cooktime);
3500 craftdef->registerCraft(def);
3505 else if(type == "fuel"){
3506 std::string recipe = getstringfield_default(L, table, "recipe", "");
3508 throw LuaError(L, "Crafting definition (fuel)"
3509 " is missing a recipe");
3511 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3513 CraftDefinition *def = new CraftDefinitionFuel(
3515 craftdef->registerCraft(def);
3519 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3523 return 0; /* number of results */
3526 // setting_get(name)
3527 static int l_setting_get(lua_State *L)
3529 const char *name = luaL_checkstring(L, 1);
3531 std::string value = g_settings->get(name);
3532 lua_pushstring(L, value.c_str());
3533 } catch(SettingNotFoundException &e){
3539 // setting_getbool(name)
3540 static int l_setting_getbool(lua_State *L)
3542 const char *name = luaL_checkstring(L, 1);
3544 bool value = g_settings->getBool(name);
3545 lua_pushboolean(L, value);
3546 } catch(SettingNotFoundException &e){
3552 // chat_send_all(text)
3553 static int l_chat_send_all(lua_State *L)
3555 const char *text = luaL_checkstring(L, 1);
3556 // Get server from registry
3557 Server *server = get_server(L);
3559 server->notifyPlayers(narrow_to_wide(text));
3563 // chat_send_player(name, text)
3564 static int l_chat_send_player(lua_State *L)
3566 const char *name = luaL_checkstring(L, 1);
3567 const char *text = luaL_checkstring(L, 2);
3568 // Get server from registry
3569 Server *server = get_server(L);
3571 server->notifyPlayer(name, narrow_to_wide(text));
3575 // get_player_privs(name, text)
3576 static int l_get_player_privs(lua_State *L)
3578 const char *name = luaL_checkstring(L, 1);
3579 // Get server from registry
3580 Server *server = get_server(L);
3583 int table = lua_gettop(L);
3584 u64 privs_i = server->getPlayerEffectivePrivs(name);
3585 std::set<std::string> privs_s = privsToSet(privs_i);
3586 for(std::set<std::string>::const_iterator
3587 i = privs_s.begin(); i != privs_s.end(); i++){
3588 lua_pushboolean(L, true);
3589 lua_setfield(L, table, i->c_str());
3591 lua_pushvalue(L, table);
3595 // get_inventory(location)
3596 static int l_get_inventory(lua_State *L)
3598 InventoryLocation loc;
3600 std::string type = checkstringfield(L, 1, "type");
3601 if(type == "player"){
3602 std::string name = checkstringfield(L, 1, "name");
3603 loc.setPlayer(name);
3604 } else if(type == "node"){
3605 lua_getfield(L, 1, "pos");
3606 v3s16 pos = check_v3s16(L, -1);
3607 loc.setNodeMeta(pos);
3610 if(get_server(L)->getInventory(loc) != NULL)
3611 InvRef::create(L, loc);
3617 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3618 static int l_get_dig_params(lua_State *L)
3620 std::map<std::string, int> groups;
3621 read_groups(L, 1, groups);
3622 ToolCapabilities tp = read_tool_capabilities(L, 2);
3623 if(lua_isnoneornil(L, 3))
3624 push_dig_params(L, getDigParams(groups, &tp));
3626 push_dig_params(L, getDigParams(groups, &tp,
3627 luaL_checknumber(L, 3)));
3631 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3632 static int l_get_hit_params(lua_State *L)
3634 std::map<std::string, int> groups;
3635 read_groups(L, 1, groups);
3636 ToolCapabilities tp = read_tool_capabilities(L, 2);
3637 if(lua_isnoneornil(L, 3))
3638 push_hit_params(L, getHitParams(groups, &tp));
3640 push_hit_params(L, getHitParams(groups, &tp,
3641 luaL_checknumber(L, 3)));
3645 // get_current_modname()
3646 static int l_get_current_modname(lua_State *L)
3648 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3652 // get_modpath(modname)
3653 static int l_get_modpath(lua_State *L)
3655 const char *modname = luaL_checkstring(L, 1);
3657 const ModSpec *mod = get_server(L)->getModSpec(modname);
3662 lua_pushstring(L, mod->path.c_str());
3667 static int l_get_worldpath(lua_State *L)
3669 std::string worldpath = get_server(L)->getWorldPath();
3670 lua_pushstring(L, worldpath.c_str());
3674 static const struct luaL_Reg minetest_f [] = {
3677 {"register_item_raw", l_register_item_raw},
3678 {"register_alias_raw", l_register_alias_raw},
3679 {"register_craft", l_register_craft},
3680 {"setting_get", l_setting_get},
3681 {"setting_getbool", l_setting_getbool},
3682 {"chat_send_all", l_chat_send_all},
3683 {"chat_send_player", l_chat_send_player},
3684 {"get_player_privs", l_get_player_privs},
3685 {"get_inventory", l_get_inventory},
3686 {"get_dig_params", l_get_dig_params},
3687 {"get_hit_params", l_get_hit_params},
3688 {"get_current_modname", l_get_current_modname},
3689 {"get_modpath", l_get_modpath},
3690 {"get_worldpath", l_get_worldpath},
3695 Main export function
3698 void scriptapi_export(lua_State *L, Server *server)
3701 assert(lua_checkstack(L, 20));
3702 verbosestream<<"scriptapi_export()"<<std::endl;
3703 StackUnroller stack_unroller(L);
3705 // Store server as light userdata in registry
3706 lua_pushlightuserdata(L, server);
3707 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3709 // Register global functions in table minetest
3711 luaL_register(L, NULL, minetest_f);
3712 lua_setglobal(L, "minetest");
3714 // Get the main minetest table
3715 lua_getglobal(L, "minetest");
3717 // Add tables to minetest
3720 lua_setfield(L, -2, "object_refs");
3722 lua_setfield(L, -2, "luaentities");
3724 // Register wrappers
3725 LuaItemStack::Register(L);
3726 InvRef::Register(L);
3727 NodeMetaRef::Register(L);
3728 ObjectRef::Register(L);
3729 EnvRef::Register(L);
3732 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3733 const std::string &modname)
3735 ModNameStorer modnamestorer(L, modname);
3737 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3739 errorstream<<"Error loading mod \""<<modname
3740 <<"\": modname does not follow naming conventions: "
3741 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3745 bool success = false;
3748 success = script_load(L, scriptpath.c_str());
3751 errorstream<<"Error loading mod \""<<modname
3752 <<"\": "<<e.what()<<std::endl;
3758 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3761 assert(lua_checkstack(L, 20));
3762 verbosestream<<"scriptapi_add_environment"<<std::endl;
3763 StackUnroller stack_unroller(L);
3765 // Create EnvRef on stack
3766 EnvRef::create(L, env);
3767 int envref = lua_gettop(L);
3769 // minetest.env = envref
3770 lua_getglobal(L, "minetest");
3771 luaL_checktype(L, -1, LUA_TTABLE);
3772 lua_pushvalue(L, envref);
3773 lua_setfield(L, -2, "env");
3775 // Store environment as light userdata in registry
3776 lua_pushlightuserdata(L, env);
3777 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3780 Add ActiveBlockModifiers to environment
3783 // Get minetest.registered_abms
3784 lua_getglobal(L, "minetest");
3785 lua_getfield(L, -1, "registered_abms");
3786 luaL_checktype(L, -1, LUA_TTABLE);
3787 int registered_abms = lua_gettop(L);
3789 if(lua_istable(L, registered_abms)){
3790 int table = lua_gettop(L);
3792 while(lua_next(L, table) != 0){
3793 // key at index -2 and value at index -1
3794 int id = lua_tonumber(L, -2);
3795 int current_abm = lua_gettop(L);
3797 std::set<std::string> trigger_contents;
3798 lua_getfield(L, current_abm, "nodenames");
3799 if(lua_istable(L, -1)){
3800 int table = lua_gettop(L);
3802 while(lua_next(L, table) != 0){
3803 // key at index -2 and value at index -1
3804 luaL_checktype(L, -1, LUA_TSTRING);
3805 trigger_contents.insert(lua_tostring(L, -1));
3806 // removes value, keeps key for next iteration
3809 } else if(lua_isstring(L, -1)){
3810 trigger_contents.insert(lua_tostring(L, -1));
3814 std::set<std::string> required_neighbors;
3815 lua_getfield(L, current_abm, "neighbors");
3816 if(lua_istable(L, -1)){
3817 int table = lua_gettop(L);
3819 while(lua_next(L, table) != 0){
3820 // key at index -2 and value at index -1
3821 luaL_checktype(L, -1, LUA_TSTRING);
3822 required_neighbors.insert(lua_tostring(L, -1));
3823 // removes value, keeps key for next iteration
3826 } else if(lua_isstring(L, -1)){
3827 required_neighbors.insert(lua_tostring(L, -1));
3831 float trigger_interval = 10.0;
3832 getfloatfield(L, current_abm, "interval", trigger_interval);
3834 int trigger_chance = 50;
3835 getintfield(L, current_abm, "chance", trigger_chance);
3837 LuaABM *abm = new LuaABM(L, id, trigger_contents,
3838 required_neighbors, trigger_interval, trigger_chance);
3840 env->addActiveBlockModifier(abm);
3842 // removes value, keeps key for next iteration
3850 // Dump stack top with the dump2 function
3851 static void dump2(lua_State *L, const char *name)
3853 // Dump object (debug)
3854 lua_getglobal(L, "dump2");
3855 luaL_checktype(L, -1, LUA_TFUNCTION);
3856 lua_pushvalue(L, -2); // Get previous stack top as first parameter
3857 lua_pushstring(L, name);
3858 if(lua_pcall(L, 2, 0, 0))
3859 script_error(L, "error: %s", lua_tostring(L, -1));
3867 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
3870 assert(lua_checkstack(L, 20));
3871 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
3872 StackUnroller stack_unroller(L);
3874 // Create object on stack
3875 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
3876 int object = lua_gettop(L);
3878 // Get minetest.object_refs table
3879 lua_getglobal(L, "minetest");
3880 lua_getfield(L, -1, "object_refs");
3881 luaL_checktype(L, -1, LUA_TTABLE);
3882 int objectstable = lua_gettop(L);
3884 // object_refs[id] = object
3885 lua_pushnumber(L, cobj->getId()); // Push id
3886 lua_pushvalue(L, object); // Copy object to top of stack
3887 lua_settable(L, objectstable);
3890 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
3893 assert(lua_checkstack(L, 20));
3894 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
3895 StackUnroller stack_unroller(L);
3897 // Get minetest.object_refs table
3898 lua_getglobal(L, "minetest");
3899 lua_getfield(L, -1, "object_refs");
3900 luaL_checktype(L, -1, LUA_TTABLE);
3901 int objectstable = lua_gettop(L);
3903 // Get object_refs[id]
3904 lua_pushnumber(L, cobj->getId()); // Push id
3905 lua_gettable(L, objectstable);
3906 // Set object reference to NULL
3907 ObjectRef::set_null(L);
3908 lua_pop(L, 1); // pop object
3910 // Set object_refs[id] = nil
3911 lua_pushnumber(L, cobj->getId()); // Push id
3913 lua_settable(L, objectstable);
3916 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
3917 const std::string &message)
3920 assert(lua_checkstack(L, 20));
3921 StackUnroller stack_unroller(L);
3923 // Get minetest.registered_on_chat_messages
3924 lua_getglobal(L, "minetest");
3925 lua_getfield(L, -1, "registered_on_chat_messages");
3926 luaL_checktype(L, -1, LUA_TTABLE);
3927 int table = lua_gettop(L);
3930 while(lua_next(L, table) != 0){
3931 // key at index -2 and value at index -1
3932 luaL_checktype(L, -1, LUA_TFUNCTION);
3934 lua_pushstring(L, name.c_str());
3935 lua_pushstring(L, message.c_str());
3936 if(lua_pcall(L, 2, 1, 0))
3937 script_error(L, "error: %s", lua_tostring(L, -1));
3938 bool ate = lua_toboolean(L, -1);
3942 // value removed, keep key for next iteration
3951 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
3954 assert(lua_checkstack(L, 20));
3955 StackUnroller stack_unroller(L);
3957 // Get minetest.registered_on_newplayers
3958 lua_getglobal(L, "minetest");
3959 lua_getfield(L, -1, "registered_on_newplayers");
3960 luaL_checktype(L, -1, LUA_TTABLE);
3961 int table = lua_gettop(L);
3964 while(lua_next(L, table) != 0){
3965 // key at index -2 and value at index -1
3966 luaL_checktype(L, -1, LUA_TFUNCTION);
3968 objectref_get_or_create(L, player);
3969 if(lua_pcall(L, 1, 0, 0))
3970 script_error(L, "error: %s", lua_tostring(L, -1));
3971 // value removed, keep key for next iteration
3975 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
3978 assert(lua_checkstack(L, 20));
3979 StackUnroller stack_unroller(L);
3981 // Get minetest.registered_on_dieplayers
3982 lua_getglobal(L, "minetest");
3983 lua_getfield(L, -1, "registered_on_dieplayers");
3984 luaL_checktype(L, -1, LUA_TTABLE);
3985 int table = lua_gettop(L);
3988 while(lua_next(L, table) != 0){
3989 // key at index -2 and value at index -1
3990 luaL_checktype(L, -1, LUA_TFUNCTION);
3992 objectref_get_or_create(L, player);
3993 if(lua_pcall(L, 1, 0, 0))
3994 script_error(L, "error: %s", lua_tostring(L, -1));
3995 // value removed, keep key for next iteration
4000 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4003 assert(lua_checkstack(L, 20));
4004 StackUnroller stack_unroller(L);
4006 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
4008 bool positioning_handled_by_some = false;
4010 // Get minetest.registered_on_respawnplayers
4011 lua_getglobal(L, "minetest");
4012 lua_getfield(L, -1, "registered_on_respawnplayers");
4013 luaL_checktype(L, -1, LUA_TTABLE);
4014 int table = lua_gettop(L);
4017 while(lua_next(L, table) != 0){
4018 // key at index -2 and value at index -1
4019 luaL_checktype(L, -1, LUA_TFUNCTION);
4021 objectref_get_or_create(L, player);
4022 if(lua_pcall(L, 1, 1, 0))
4023 script_error(L, "error: %s", lua_tostring(L, -1));
4024 bool positioning_handled = lua_toboolean(L, -1);
4026 if(positioning_handled)
4027 positioning_handled_by_some = true;
4028 // value removed, keep key for next iteration
4030 return positioning_handled_by_some;
4033 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4035 lua_getglobal(L, "minetest");
4036 lua_getfield(L, -1, "creative_inventory");
4037 luaL_checktype(L, -1, LUA_TTABLE);
4038 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4039 PLAYER_INVENTORY_SIZE);
4043 item callbacks and node callbacks
4046 // Retrieves minetest.registered_items[name][callbackname]
4047 // If that is nil or on error, return false and stack is unchanged
4048 // If that is a function, returns true and pushes the
4049 // function onto the stack
4050 static bool get_item_callback(lua_State *L,
4051 const char *name, const char *callbackname)
4053 lua_getglobal(L, "minetest");
4054 lua_getfield(L, -1, "registered_items");
4056 luaL_checktype(L, -1, LUA_TTABLE);
4057 lua_getfield(L, -1, name);
4059 // Should be a table
4060 if(lua_type(L, -1) != LUA_TTABLE)
4062 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4066 lua_getfield(L, -1, callbackname);
4068 // Should be a function or nil
4069 if(lua_type(L, -1) == LUA_TFUNCTION)
4073 else if(lua_isnil(L, -1))
4080 errorstream<<"Item \""<<name<<"\" callback \""
4081 <<callbackname<<" is not a function"<<std::endl;
4087 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4088 ServerActiveObject *dropper, v3f pos)
4091 assert(lua_checkstack(L, 20));
4092 StackUnroller stack_unroller(L);
4094 // Push callback function on stack
4095 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4099 LuaItemStack::create(L, item);
4100 objectref_get_or_create(L, dropper);
4101 pushFloatPos(L, pos);
4102 if(lua_pcall(L, 3, 1, 0))
4103 script_error(L, "error: %s", lua_tostring(L, -1));
4104 if(!lua_isnil(L, -1))
4105 item = read_item(L, -1);
4109 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4110 ServerActiveObject *placer, const PointedThing &pointed)
4113 assert(lua_checkstack(L, 20));
4114 StackUnroller stack_unroller(L);
4116 // Push callback function on stack
4117 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4121 LuaItemStack::create(L, item);
4122 objectref_get_or_create(L, placer);
4123 push_pointed_thing(L, pointed);
4124 if(lua_pcall(L, 3, 1, 0))
4125 script_error(L, "error: %s", lua_tostring(L, -1));
4126 if(!lua_isnil(L, -1))
4127 item = read_item(L, -1);
4131 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4132 ServerActiveObject *user, const PointedThing &pointed)
4135 assert(lua_checkstack(L, 20));
4136 StackUnroller stack_unroller(L);
4138 // Push callback function on stack
4139 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4143 LuaItemStack::create(L, item);
4144 objectref_get_or_create(L, user);
4145 push_pointed_thing(L, pointed);
4146 if(lua_pcall(L, 3, 1, 0))
4147 script_error(L, "error: %s", lua_tostring(L, -1));
4148 if(!lua_isnil(L, -1))
4149 item = read_item(L, -1);
4153 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4154 ServerActiveObject *puncher)
4157 assert(lua_checkstack(L, 20));
4158 StackUnroller stack_unroller(L);
4160 INodeDefManager *ndef = get_server(L)->ndef();
4162 // Push callback function on stack
4163 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4168 pushnode(L, node, ndef);
4169 objectref_get_or_create(L, puncher);
4170 if(lua_pcall(L, 3, 0, 0))
4171 script_error(L, "error: %s", lua_tostring(L, -1));
4175 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4176 ServerActiveObject *digger)
4179 assert(lua_checkstack(L, 20));
4180 StackUnroller stack_unroller(L);
4182 INodeDefManager *ndef = get_server(L)->ndef();
4184 // Push callback function on stack
4185 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4190 pushnode(L, node, ndef);
4191 objectref_get_or_create(L, digger);
4192 if(lua_pcall(L, 3, 0, 0))
4193 script_error(L, "error: %s", lua_tostring(L, -1));
4201 void scriptapi_environment_step(lua_State *L, float dtime)
4204 assert(lua_checkstack(L, 20));
4205 //infostream<<"scriptapi_environment_step"<<std::endl;
4206 StackUnroller stack_unroller(L);
4208 // Get minetest.registered_globalsteps
4209 lua_getglobal(L, "minetest");
4210 lua_getfield(L, -1, "registered_globalsteps");
4211 luaL_checktype(L, -1, LUA_TTABLE);
4212 int table = lua_gettop(L);
4215 while(lua_next(L, table) != 0){
4216 // key at index -2 and value at index -1
4217 luaL_checktype(L, -1, LUA_TFUNCTION);
4219 lua_pushnumber(L, dtime);
4220 if(lua_pcall(L, 1, 0, 0))
4221 script_error(L, "error: %s", lua_tostring(L, -1));
4222 // value removed, keep key for next iteration
4226 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
4229 assert(lua_checkstack(L, 20));
4230 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4231 StackUnroller stack_unroller(L);
4233 // Get minetest.registered_on_generateds
4234 lua_getglobal(L, "minetest");
4235 lua_getfield(L, -1, "registered_on_generateds");
4236 luaL_checktype(L, -1, LUA_TTABLE);
4237 int table = lua_gettop(L);
4240 while(lua_next(L, table) != 0){
4241 // key at index -2 and value at index -1
4242 luaL_checktype(L, -1, LUA_TFUNCTION);
4244 push_v3s16(L, minp);
4245 push_v3s16(L, maxp);
4246 if(lua_pcall(L, 2, 0, 0))
4247 script_error(L, "error: %s", lua_tostring(L, -1));
4248 // value removed, keep key for next iteration
4256 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4259 assert(lua_checkstack(L, 20));
4260 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4261 <<name<<"\""<<std::endl;
4262 StackUnroller stack_unroller(L);
4264 // Get minetest.registered_entities[name]
4265 lua_getglobal(L, "minetest");
4266 lua_getfield(L, -1, "registered_entities");
4267 luaL_checktype(L, -1, LUA_TTABLE);
4268 lua_pushstring(L, name);
4269 lua_gettable(L, -2);
4270 // Should be a table, which we will use as a prototype
4271 //luaL_checktype(L, -1, LUA_TTABLE);
4272 if(lua_type(L, -1) != LUA_TTABLE){
4273 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4276 int prototype_table = lua_gettop(L);
4277 //dump2(L, "prototype_table");
4279 // Create entity object
4281 int object = lua_gettop(L);
4283 // Set object metatable
4284 lua_pushvalue(L, prototype_table);
4285 lua_setmetatable(L, -2);
4287 // Add object reference
4288 // This should be userdata with metatable ObjectRef
4289 objectref_get(L, id);
4290 luaL_checktype(L, -1, LUA_TUSERDATA);
4291 if(!luaL_checkudata(L, -1, "ObjectRef"))
4292 luaL_typerror(L, -1, "ObjectRef");
4293 lua_setfield(L, -2, "object");
4295 // minetest.luaentities[id] = object
4296 lua_getglobal(L, "minetest");
4297 lua_getfield(L, -1, "luaentities");
4298 luaL_checktype(L, -1, LUA_TTABLE);
4299 lua_pushnumber(L, id); // Push id
4300 lua_pushvalue(L, object); // Copy object to top of stack
4301 lua_settable(L, -3);
4306 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4307 const std::string &staticdata)
4310 assert(lua_checkstack(L, 20));
4311 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4312 StackUnroller stack_unroller(L);
4314 // Get minetest.luaentities[id]
4315 luaentity_get(L, id);
4316 int object = lua_gettop(L);
4318 // Get on_activate function
4319 lua_pushvalue(L, object);
4320 lua_getfield(L, -1, "on_activate");
4321 if(!lua_isnil(L, -1)){
4322 luaL_checktype(L, -1, LUA_TFUNCTION);
4323 lua_pushvalue(L, object); // self
4324 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4325 // Call with 2 arguments, 0 results
4326 if(lua_pcall(L, 2, 0, 0))
4327 script_error(L, "error running function on_activate: %s\n",
4328 lua_tostring(L, -1));
4332 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4335 assert(lua_checkstack(L, 20));
4336 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4338 // Get minetest.luaentities table
4339 lua_getglobal(L, "minetest");
4340 lua_getfield(L, -1, "luaentities");
4341 luaL_checktype(L, -1, LUA_TTABLE);
4342 int objectstable = lua_gettop(L);
4344 // Set luaentities[id] = nil
4345 lua_pushnumber(L, id); // Push id
4347 lua_settable(L, objectstable);
4349 lua_pop(L, 2); // pop luaentities, minetest
4352 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4355 assert(lua_checkstack(L, 20));
4356 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4357 StackUnroller stack_unroller(L);
4359 // Get minetest.luaentities[id]
4360 luaentity_get(L, id);
4361 int object = lua_gettop(L);
4363 // Get get_staticdata function
4364 lua_pushvalue(L, object);
4365 lua_getfield(L, -1, "get_staticdata");
4366 if(lua_isnil(L, -1))
4369 luaL_checktype(L, -1, LUA_TFUNCTION);
4370 lua_pushvalue(L, object); // self
4371 // Call with 1 arguments, 1 results
4372 if(lua_pcall(L, 1, 1, 0))
4373 script_error(L, "error running function get_staticdata: %s\n",
4374 lua_tostring(L, -1));
4377 const char *s = lua_tolstring(L, -1, &len);
4378 return std::string(s, len);
4381 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4382 LuaEntityProperties *prop)
4385 assert(lua_checkstack(L, 20));
4386 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4387 StackUnroller stack_unroller(L);
4389 // Get minetest.luaentities[id]
4390 luaentity_get(L, id);
4391 //int object = lua_gettop(L);
4395 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4397 getboolfield(L, -1, "physical", prop->physical);
4399 getfloatfield(L, -1, "weight", prop->weight);
4401 lua_getfield(L, -1, "collisionbox");
4402 if(lua_istable(L, -1))
4403 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4406 getstringfield(L, -1, "visual", prop->visual);
4408 lua_getfield(L, -1, "visual_size");
4409 if(lua_istable(L, -1))
4410 prop->visual_size = read_v2f(L, -1);
4413 lua_getfield(L, -1, "textures");
4414 if(lua_istable(L, -1)){
4415 prop->textures.clear();
4416 int table = lua_gettop(L);
4418 while(lua_next(L, table) != 0){
4419 // key at index -2 and value at index -1
4420 if(lua_isstring(L, -1))
4421 prop->textures.push_back(lua_tostring(L, -1));
4423 prop->textures.push_back("");
4424 // removes value, keeps key for next iteration
4430 lua_getfield(L, -1, "spritediv");
4431 if(lua_istable(L, -1))
4432 prop->spritediv = read_v2s16(L, -1);
4435 lua_getfield(L, -1, "initial_sprite_basepos");
4436 if(lua_istable(L, -1))
4437 prop->initial_sprite_basepos = read_v2s16(L, -1);
4441 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4444 assert(lua_checkstack(L, 20));
4445 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4446 StackUnroller stack_unroller(L);
4448 // Get minetest.luaentities[id]
4449 luaentity_get(L, id);
4450 int object = lua_gettop(L);
4451 // State: object is at top of stack
4452 // Get step function
4453 lua_getfield(L, -1, "on_step");
4454 if(lua_isnil(L, -1))
4456 luaL_checktype(L, -1, LUA_TFUNCTION);
4457 lua_pushvalue(L, object); // self
4458 lua_pushnumber(L, dtime); // dtime
4459 // Call with 2 arguments, 0 results
4460 if(lua_pcall(L, 2, 0, 0))
4461 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4464 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4465 // tool_capabilities, direction)
4466 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4467 ServerActiveObject *puncher, float time_from_last_punch,
4468 const ToolCapabilities *toolcap, v3f dir)
4471 assert(lua_checkstack(L, 20));
4472 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4473 StackUnroller stack_unroller(L);
4475 // Get minetest.luaentities[id]
4476 luaentity_get(L, id);
4477 int object = lua_gettop(L);
4478 // State: object is at top of stack
4480 lua_getfield(L, -1, "on_punch");
4481 if(lua_isnil(L, -1))
4483 luaL_checktype(L, -1, LUA_TFUNCTION);
4484 lua_pushvalue(L, object); // self
4485 objectref_get_or_create(L, puncher); // Clicker reference
4486 lua_pushnumber(L, time_from_last_punch);
4487 push_tool_capabilities(L, *toolcap);
4489 // Call with 5 arguments, 0 results
4490 if(lua_pcall(L, 5, 0, 0))
4491 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4494 // Calls entity:on_rightclick(ObjectRef clicker)
4495 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4496 ServerActiveObject *clicker)
4499 assert(lua_checkstack(L, 20));
4500 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4501 StackUnroller stack_unroller(L);
4503 // Get minetest.luaentities[id]
4504 luaentity_get(L, id);
4505 int object = lua_gettop(L);
4506 // State: object is at top of stack
4508 lua_getfield(L, -1, "on_rightclick");
4509 if(lua_isnil(L, -1))
4511 luaL_checktype(L, -1, LUA_TFUNCTION);
4512 lua_pushvalue(L, object); // self
4513 objectref_get_or_create(L, clicker); // Clicker reference
4514 // Call with 2 arguments, 0 results
4515 if(lua_pcall(L, 2, 0, 0))
4516 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));