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, "dig");
1066 read_soundspec(L, -1, f.sound_dig);
1068 lua_getfield(L, -1, "dug");
1069 read_soundspec(L, -1, f.sound_dug);
1081 static ItemStack read_item(lua_State *L, int index);
1083 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1084 lua_State *L, int tableindex, int forcesize=-1)
1086 dstream<<"inventory_set_list_from_lua\n";
1088 tableindex = lua_gettop(L) + 1 + tableindex;
1089 // If nil, delete list
1090 if(lua_isnil(L, tableindex)){
1091 inv->deleteList(name);
1094 // Otherwise set list
1095 std::vector<ItemStack> items;
1096 luaL_checktype(L, tableindex, LUA_TTABLE);
1098 while(lua_next(L, tableindex) != 0){
1099 // key at index -2 and value at index -1
1100 items.push_back(read_item(L, -1));
1101 // removes value, keeps key for next iteration
1104 int listsize = (forcesize != -1) ? forcesize : items.size();
1105 InventoryList *invlist = inv->addList(name, listsize);
1107 for(std::vector<ItemStack>::const_iterator
1108 i = items.begin(); i != items.end(); i++){
1109 if(forcesize != -1 && index == forcesize)
1111 invlist->changeItem(index, *i);
1114 while(forcesize != -1 && index < forcesize){
1115 invlist->deleteItem(index);
1118 dstream<<"inventory_set_list_from_lua done\n";
1121 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1124 InventoryList *invlist = inv->getList(name);
1125 if(invlist == NULL){
1129 // Get the table insert function
1130 lua_getglobal(L, "table");
1131 lua_getfield(L, -1, "insert");
1132 int table_insert = lua_gettop(L);
1133 // Create and fill table
1135 int table = lua_gettop(L);
1136 for(u32 i=0; i<invlist->getSize(); i++){
1137 ItemStack item = invlist->getItem(i);
1138 lua_pushvalue(L, table_insert);
1139 lua_pushvalue(L, table);
1140 lua_pushstring(L, item.getItemString().c_str());
1141 if(lua_pcall(L, 2, 0, 0))
1142 script_error(L, "error: %s", lua_tostring(L, -1));
1147 Helpful macros for userdata classes
1150 #define method(class, name) {#name, class::l_##name}
1161 static const char className[];
1162 static const luaL_reg methods[];
1164 // Exported functions
1166 // garbage collector
1167 static int gc_object(lua_State *L)
1169 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1174 // is_empty(self) -> true/false
1175 static int l_is_empty(lua_State *L)
1177 LuaItemStack *o = checkobject(L, 1);
1178 ItemStack &item = o->m_stack;
1179 lua_pushboolean(L, item.empty());
1183 // get_name(self) -> string
1184 static int l_get_name(lua_State *L)
1186 LuaItemStack *o = checkobject(L, 1);
1187 ItemStack &item = o->m_stack;
1188 lua_pushstring(L, item.name.c_str());
1192 // get_count(self) -> number
1193 static int l_get_count(lua_State *L)
1195 LuaItemStack *o = checkobject(L, 1);
1196 ItemStack &item = o->m_stack;
1197 lua_pushinteger(L, item.count);
1201 // get_wear(self) -> number
1202 static int l_get_wear(lua_State *L)
1204 LuaItemStack *o = checkobject(L, 1);
1205 ItemStack &item = o->m_stack;
1206 lua_pushinteger(L, item.wear);
1210 // get_metadata(self) -> string
1211 static int l_get_metadata(lua_State *L)
1213 LuaItemStack *o = checkobject(L, 1);
1214 ItemStack &item = o->m_stack;
1215 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1219 // clear(self) -> true
1220 static int l_clear(lua_State *L)
1222 LuaItemStack *o = checkobject(L, 1);
1224 lua_pushboolean(L, true);
1228 // replace(self, itemstack or itemstring or table or nil) -> true
1229 static int l_replace(lua_State *L)
1231 LuaItemStack *o = checkobject(L, 1);
1232 o->m_stack = read_item(L, 2);
1233 lua_pushboolean(L, true);
1237 // to_string(self) -> string
1238 static int l_to_string(lua_State *L)
1240 LuaItemStack *o = checkobject(L, 1);
1241 std::string itemstring = o->m_stack.getItemString();
1242 lua_pushstring(L, itemstring.c_str());
1246 // to_table(self) -> table or nil
1247 static int l_to_table(lua_State *L)
1249 LuaItemStack *o = checkobject(L, 1);
1250 const ItemStack &item = o->m_stack;
1258 lua_pushstring(L, item.name.c_str());
1259 lua_setfield(L, -2, "name");
1260 lua_pushinteger(L, item.count);
1261 lua_setfield(L, -2, "count");
1262 lua_pushinteger(L, item.wear);
1263 lua_setfield(L, -2, "wear");
1264 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1265 lua_setfield(L, -2, "metadata");
1270 // get_stack_max(self) -> number
1271 static int l_get_stack_max(lua_State *L)
1273 LuaItemStack *o = checkobject(L, 1);
1274 ItemStack &item = o->m_stack;
1275 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1279 // get_free_space(self) -> number
1280 static int l_get_free_space(lua_State *L)
1282 LuaItemStack *o = checkobject(L, 1);
1283 ItemStack &item = o->m_stack;
1284 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1288 // is_known(self) -> true/false
1289 // Checks if the item is defined.
1290 static int l_is_known(lua_State *L)
1292 LuaItemStack *o = checkobject(L, 1);
1293 ItemStack &item = o->m_stack;
1294 bool is_known = item.isKnown(get_server(L)->idef());
1295 lua_pushboolean(L, is_known);
1299 // get_definition(self) -> table
1300 // Returns the item definition table from minetest.registered_items,
1301 // or a fallback one (name="unknown")
1302 static int l_get_definition(lua_State *L)
1304 LuaItemStack *o = checkobject(L, 1);
1305 ItemStack &item = o->m_stack;
1307 // Get minetest.registered_items[name]
1308 lua_getglobal(L, "minetest");
1309 lua_getfield(L, -1, "registered_items");
1310 luaL_checktype(L, -1, LUA_TTABLE);
1311 lua_getfield(L, -1, item.name.c_str());
1312 if(lua_isnil(L, -1))
1315 lua_getfield(L, -1, "unknown");
1320 // get_tool_capabilities(self) -> table
1321 // Returns the effective tool digging properties.
1322 // Returns those of the hand ("") if this item has none associated.
1323 static int l_get_tool_capabilities(lua_State *L)
1325 LuaItemStack *o = checkobject(L, 1);
1326 ItemStack &item = o->m_stack;
1327 const ToolCapabilities &prop =
1328 item.getToolCapabilities(get_server(L)->idef());
1329 push_tool_capabilities(L, prop);
1333 // add_wear(self, amount) -> true/false
1334 // The range for "amount" is [0,65535]. Wear is only added if the item
1335 // is a tool. Adding wear might destroy the item.
1336 // Returns true if the item is (or was) a tool.
1337 static int l_add_wear(lua_State *L)
1339 LuaItemStack *o = checkobject(L, 1);
1340 ItemStack &item = o->m_stack;
1341 int amount = lua_tointeger(L, 2);
1342 bool result = item.addWear(amount, get_server(L)->idef());
1343 lua_pushboolean(L, result);
1347 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1348 // Returns leftover item stack
1349 static int l_add_item(lua_State *L)
1351 LuaItemStack *o = checkobject(L, 1);
1352 ItemStack &item = o->m_stack;
1353 ItemStack newitem = read_item(L, 2);
1354 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1355 create(L, leftover);
1359 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1360 // First return value is true iff the new item fits fully into the stack
1361 // Second return value is the would-be-left-over item stack
1362 static int l_item_fits(lua_State *L)
1364 LuaItemStack *o = checkobject(L, 1);
1365 ItemStack &item = o->m_stack;
1366 ItemStack newitem = read_item(L, 2);
1368 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1369 lua_pushboolean(L, fits); // first return value
1370 create(L, restitem); // second return value
1374 // take_item(self, takecount=1) -> itemstack
1375 static int l_take_item(lua_State *L)
1377 LuaItemStack *o = checkobject(L, 1);
1378 ItemStack &item = o->m_stack;
1380 if(!lua_isnone(L, 2))
1381 takecount = lua_tointeger(L, 2);
1382 ItemStack taken = item.takeItem(takecount);
1387 // peek_item(self, peekcount=1) -> itemstack
1388 static int l_peek_item(lua_State *L)
1390 LuaItemStack *o = checkobject(L, 1);
1391 ItemStack &item = o->m_stack;
1393 if(!lua_isnone(L, 2))
1394 peekcount = lua_tointeger(L, 2);
1395 ItemStack peekaboo = item.peekItem(peekcount);
1396 create(L, peekaboo);
1401 LuaItemStack(const ItemStack &item):
1410 const ItemStack& getItem() const
1414 ItemStack& getItem()
1419 // LuaItemStack(itemstack or itemstring or table or nil)
1420 // Creates an LuaItemStack and leaves it on top of stack
1421 static int create_object(lua_State *L)
1423 ItemStack item = read_item(L, 1);
1424 LuaItemStack *o = new LuaItemStack(item);
1425 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1426 luaL_getmetatable(L, className);
1427 lua_setmetatable(L, -2);
1430 // Not callable from Lua
1431 static int create(lua_State *L, const ItemStack &item)
1433 LuaItemStack *o = new LuaItemStack(item);
1434 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1435 luaL_getmetatable(L, className);
1436 lua_setmetatable(L, -2);
1440 static LuaItemStack* checkobject(lua_State *L, int narg)
1442 luaL_checktype(L, narg, LUA_TUSERDATA);
1443 void *ud = luaL_checkudata(L, narg, className);
1444 if(!ud) luaL_typerror(L, narg, className);
1445 return *(LuaItemStack**)ud; // unbox pointer
1448 static void Register(lua_State *L)
1451 int methodtable = lua_gettop(L);
1452 luaL_newmetatable(L, className);
1453 int metatable = lua_gettop(L);
1455 lua_pushliteral(L, "__metatable");
1456 lua_pushvalue(L, methodtable);
1457 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1459 lua_pushliteral(L, "__index");
1460 lua_pushvalue(L, methodtable);
1461 lua_settable(L, metatable);
1463 lua_pushliteral(L, "__gc");
1464 lua_pushcfunction(L, gc_object);
1465 lua_settable(L, metatable);
1467 lua_pop(L, 1); // drop metatable
1469 luaL_openlib(L, 0, methods, 0); // fill methodtable
1470 lua_pop(L, 1); // drop methodtable
1472 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1473 lua_register(L, className, create_object);
1476 const char LuaItemStack::className[] = "ItemStack";
1477 const luaL_reg LuaItemStack::methods[] = {
1478 method(LuaItemStack, is_empty),
1479 method(LuaItemStack, get_name),
1480 method(LuaItemStack, get_count),
1481 method(LuaItemStack, get_wear),
1482 method(LuaItemStack, get_metadata),
1483 method(LuaItemStack, clear),
1484 method(LuaItemStack, replace),
1485 method(LuaItemStack, to_string),
1486 method(LuaItemStack, to_table),
1487 method(LuaItemStack, get_stack_max),
1488 method(LuaItemStack, get_free_space),
1489 method(LuaItemStack, is_known),
1490 method(LuaItemStack, get_definition),
1491 method(LuaItemStack, get_tool_capabilities),
1492 method(LuaItemStack, add_wear),
1493 method(LuaItemStack, add_item),
1494 method(LuaItemStack, item_fits),
1495 method(LuaItemStack, take_item),
1496 method(LuaItemStack, peek_item),
1500 static ItemStack read_item(lua_State *L, int index)
1503 index = lua_gettop(L) + 1 + index;
1505 if(lua_isnil(L, index))
1509 else if(lua_isuserdata(L, index))
1511 // Convert from LuaItemStack
1512 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1513 return o->getItem();
1515 else if(lua_isstring(L, index))
1517 // Convert from itemstring
1518 std::string itemstring = lua_tostring(L, index);
1519 IItemDefManager *idef = get_server(L)->idef();
1523 item.deSerialize(itemstring, idef);
1526 catch(SerializationError &e)
1528 infostream<<"WARNING: unable to create item from itemstring"
1529 <<": "<<itemstring<<std::endl;
1533 else if(lua_istable(L, index))
1535 // Convert from table
1536 IItemDefManager *idef = get_server(L)->idef();
1537 std::string name = getstringfield_default(L, index, "name", "");
1538 int count = getintfield_default(L, index, "count", 1);
1539 int wear = getintfield_default(L, index, "wear", 0);
1540 std::string metadata = getstringfield_default(L, index, "metadata", "");
1541 return ItemStack(name, count, wear, metadata, idef);
1545 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1556 InventoryLocation m_loc;
1558 static const char className[];
1559 static const luaL_reg methods[];
1561 static InvRef *checkobject(lua_State *L, int narg)
1563 luaL_checktype(L, narg, LUA_TUSERDATA);
1564 void *ud = luaL_checkudata(L, narg, className);
1565 if(!ud) luaL_typerror(L, narg, className);
1566 return *(InvRef**)ud; // unbox pointer
1569 static Inventory* getinv(lua_State *L, InvRef *ref)
1571 return get_server(L)->getInventory(ref->m_loc);
1574 static InventoryList* getlist(lua_State *L, InvRef *ref,
1575 const char *listname)
1577 Inventory *inv = getinv(L, ref);
1580 return inv->getList(listname);
1583 static void reportInventoryChange(lua_State *L, InvRef *ref)
1585 // Inform other things that the inventory has changed
1586 get_server(L)->setInventoryModified(ref->m_loc);
1589 // Exported functions
1591 // garbage collector
1592 static int gc_object(lua_State *L) {
1593 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1598 // get_size(self, listname)
1599 static int l_get_size(lua_State *L)
1601 InvRef *ref = checkobject(L, 1);
1602 const char *listname = luaL_checkstring(L, 2);
1603 InventoryList *list = getlist(L, ref, listname);
1605 lua_pushinteger(L, list->getSize());
1607 lua_pushinteger(L, 0);
1612 // set_size(self, listname, size)
1613 static int l_set_size(lua_State *L)
1615 InvRef *ref = checkobject(L, 1);
1616 const char *listname = luaL_checkstring(L, 2);
1617 int newsize = luaL_checknumber(L, 3);
1618 Inventory *inv = getinv(L, ref);
1620 inv->deleteList(listname);
1621 reportInventoryChange(L, ref);
1624 InventoryList *list = inv->getList(listname);
1626 list->setSize(newsize);
1628 list = inv->addList(listname, newsize);
1630 reportInventoryChange(L, ref);
1634 // get_stack(self, listname, i) -> itemstack
1635 static int l_get_stack(lua_State *L)
1637 InvRef *ref = checkobject(L, 1);
1638 const char *listname = luaL_checkstring(L, 2);
1639 int i = luaL_checknumber(L, 3) - 1;
1640 InventoryList *list = getlist(L, ref, listname);
1642 if(list != NULL && i >= 0 && i < (int) list->getSize())
1643 item = list->getItem(i);
1644 LuaItemStack::create(L, item);
1648 // set_stack(self, listname, i, stack) -> true/false
1649 static int l_set_stack(lua_State *L)
1651 InvRef *ref = checkobject(L, 1);
1652 const char *listname = luaL_checkstring(L, 2);
1653 int i = luaL_checknumber(L, 3) - 1;
1654 ItemStack newitem = read_item(L, 4);
1655 InventoryList *list = getlist(L, ref, listname);
1656 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1657 list->changeItem(i, newitem);
1658 reportInventoryChange(L, ref);
1659 lua_pushboolean(L, true);
1661 lua_pushboolean(L, false);
1666 // get_list(self, listname) -> list or nil
1667 static int l_get_list(lua_State *L)
1669 InvRef *ref = checkobject(L, 1);
1670 const char *listname = luaL_checkstring(L, 2);
1671 Inventory *inv = getinv(L, ref);
1672 inventory_get_list_to_lua(inv, listname, L);
1676 // set_list(self, listname, list)
1677 static int l_set_list(lua_State *L)
1679 InvRef *ref = checkobject(L, 1);
1680 const char *listname = luaL_checkstring(L, 2);
1681 Inventory *inv = getinv(L, ref);
1682 InventoryList *list = inv->getList(listname);
1684 inventory_set_list_from_lua(inv, listname, L, 3,
1687 inventory_set_list_from_lua(inv, listname, L, 3);
1688 reportInventoryChange(L, ref);
1692 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1693 // Returns the leftover stack
1694 static int l_add_item(lua_State *L)
1696 InvRef *ref = checkobject(L, 1);
1697 const char *listname = luaL_checkstring(L, 2);
1698 ItemStack item = read_item(L, 3);
1699 InventoryList *list = getlist(L, ref, listname);
1701 ItemStack leftover = list->addItem(item);
1702 if(leftover.count != item.count)
1703 reportInventoryChange(L, ref);
1704 LuaItemStack::create(L, leftover);
1706 LuaItemStack::create(L, item);
1711 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1712 // Returns true if the item completely fits into the list
1713 static int l_room_for_item(lua_State *L)
1715 InvRef *ref = checkobject(L, 1);
1716 const char *listname = luaL_checkstring(L, 2);
1717 ItemStack item = read_item(L, 3);
1718 InventoryList *list = getlist(L, ref, listname);
1720 lua_pushboolean(L, list->roomForItem(item));
1722 lua_pushboolean(L, false);
1727 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1728 // Returns true if the list contains the given count of the given item name
1729 static int l_contains_item(lua_State *L)
1731 InvRef *ref = checkobject(L, 1);
1732 const char *listname = luaL_checkstring(L, 2);
1733 ItemStack item = read_item(L, 3);
1734 InventoryList *list = getlist(L, ref, listname);
1736 lua_pushboolean(L, list->containsItem(item));
1738 lua_pushboolean(L, false);
1743 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1744 // Returns the items that were actually removed
1745 static int l_remove_item(lua_State *L)
1747 InvRef *ref = checkobject(L, 1);
1748 const char *listname = luaL_checkstring(L, 2);
1749 ItemStack item = read_item(L, 3);
1750 InventoryList *list = getlist(L, ref, listname);
1752 ItemStack removed = list->removeItem(item);
1753 if(!removed.empty())
1754 reportInventoryChange(L, ref);
1755 LuaItemStack::create(L, removed);
1757 LuaItemStack::create(L, ItemStack());
1763 InvRef(const InventoryLocation &loc):
1772 // Creates an InvRef and leaves it on top of stack
1773 // Not callable from Lua; all references are created on the C side.
1774 static void create(lua_State *L, const InventoryLocation &loc)
1776 InvRef *o = new InvRef(loc);
1777 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1778 luaL_getmetatable(L, className);
1779 lua_setmetatable(L, -2);
1781 static void createPlayer(lua_State *L, Player *player)
1783 InventoryLocation loc;
1784 loc.setPlayer(player->getName());
1787 static void createNodeMeta(lua_State *L, v3s16 p)
1789 InventoryLocation loc;
1794 static void Register(lua_State *L)
1797 int methodtable = lua_gettop(L);
1798 luaL_newmetatable(L, className);
1799 int metatable = lua_gettop(L);
1801 lua_pushliteral(L, "__metatable");
1802 lua_pushvalue(L, methodtable);
1803 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1805 lua_pushliteral(L, "__index");
1806 lua_pushvalue(L, methodtable);
1807 lua_settable(L, metatable);
1809 lua_pushliteral(L, "__gc");
1810 lua_pushcfunction(L, gc_object);
1811 lua_settable(L, metatable);
1813 lua_pop(L, 1); // drop metatable
1815 luaL_openlib(L, 0, methods, 0); // fill methodtable
1816 lua_pop(L, 1); // drop methodtable
1818 // Cannot be created from Lua
1819 //lua_register(L, className, create_object);
1822 const char InvRef::className[] = "InvRef";
1823 const luaL_reg InvRef::methods[] = {
1824 method(InvRef, get_size),
1825 method(InvRef, set_size),
1826 method(InvRef, get_stack),
1827 method(InvRef, set_stack),
1828 method(InvRef, get_list),
1829 method(InvRef, set_list),
1830 method(InvRef, add_item),
1831 method(InvRef, room_for_item),
1832 method(InvRef, contains_item),
1833 method(InvRef, remove_item),
1845 ServerEnvironment *m_env;
1847 static const char className[];
1848 static const luaL_reg methods[];
1850 static NodeMetaRef *checkobject(lua_State *L, int narg)
1852 luaL_checktype(L, narg, LUA_TUSERDATA);
1853 void *ud = luaL_checkudata(L, narg, className);
1854 if(!ud) luaL_typerror(L, narg, className);
1855 return *(NodeMetaRef**)ud; // unbox pointer
1858 static NodeMetadata* getmeta(NodeMetaRef *ref)
1860 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1864 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1866 NodeMetadata *meta = getmeta(ref);
1869 if(meta->typeId() != NODEMETA_GENERIC)
1871 return (IGenericNodeMetadata*)meta;
1874 static void reportMetadataChange(NodeMetaRef *ref)
1876 // Inform other things that the metadata has changed
1877 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1879 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1881 ref->m_env->getMap().dispatchEvent(&event);
1882 // Set the block to be saved
1883 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1885 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1886 "NodeMetaRef::reportMetadataChange");
1889 // Exported functions
1891 // garbage collector
1892 static int gc_object(lua_State *L) {
1893 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1899 static int l_get_type(lua_State *L)
1901 NodeMetaRef *ref = checkobject(L, 1);
1902 NodeMetadata *meta = getmeta(ref);
1908 lua_pushstring(L, meta->typeName());
1912 // allows_text_input(self)
1913 static int l_allows_text_input(lua_State *L)
1915 NodeMetaRef *ref = checkobject(L, 1);
1916 NodeMetadata *meta = getmeta(ref);
1917 if(meta == NULL) return 0;
1919 lua_pushboolean(L, meta->allowsTextInput());
1923 // set_text(self, text)
1924 static int l_set_text(lua_State *L)
1926 NodeMetaRef *ref = checkobject(L, 1);
1927 NodeMetadata *meta = getmeta(ref);
1928 if(meta == NULL) return 0;
1930 std::string text = luaL_checkstring(L, 2);
1931 meta->setText(text);
1932 reportMetadataChange(ref);
1937 static int l_get_text(lua_State *L)
1939 NodeMetaRef *ref = checkobject(L, 1);
1940 NodeMetadata *meta = getmeta(ref);
1941 if(meta == NULL) return 0;
1943 std::string text = meta->getText();
1944 lua_pushstring(L, text.c_str());
1949 static int l_get_owner(lua_State *L)
1951 NodeMetaRef *ref = checkobject(L, 1);
1952 NodeMetadata *meta = getmeta(ref);
1953 if(meta == NULL) return 0;
1955 std::string owner = meta->getOwner();
1956 lua_pushstring(L, owner.c_str());
1960 // set_owner(self, string)
1961 static int l_set_owner(lua_State *L)
1963 NodeMetaRef *ref = checkobject(L, 1);
1964 NodeMetadata *meta = getmeta(ref);
1965 if(meta == NULL) return 0;
1967 std::string owner = luaL_checkstring(L, 2);
1968 meta->setOwner(owner);
1969 reportMetadataChange(ref);
1973 // get_allow_removal(self)
1974 static int l_get_allow_removal(lua_State *L)
1976 NodeMetaRef *ref = checkobject(L, 1);
1977 NodeMetadata *meta = getmeta(ref);
1979 lua_pushboolean(L, true);
1983 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1987 /* IGenericNodeMetadata interface */
1989 // set_infotext(self, text)
1990 static int l_set_infotext(lua_State *L)
1992 NodeMetaRef *ref = checkobject(L, 1);
1993 NodeMetadata *meta = getmeta(ref);
1994 if(meta == NULL) return 0;
1996 std::string text = luaL_checkstring(L, 2);
1997 meta->setInfoText(text);
1998 reportMetadataChange(ref);
2002 // get_inventory(self)
2003 static int l_get_inventory(lua_State *L)
2005 NodeMetaRef *ref = checkobject(L, 1);
2006 NodeMetadata *meta = getmeta(ref);
2007 if(meta == NULL) return 0;
2009 InvRef::createNodeMeta(L, ref->m_p);
2013 // set_inventory_draw_spec(self, text)
2014 static int l_set_inventory_draw_spec(lua_State *L)
2016 NodeMetaRef *ref = checkobject(L, 1);
2017 NodeMetadata *meta = getmeta(ref);
2018 if(meta == NULL) return 0;
2020 std::string text = luaL_checkstring(L, 2);
2021 meta->setInventoryDrawSpec(text);
2022 reportMetadataChange(ref);
2026 // set_allow_text_input(self, text)
2027 static int l_set_allow_text_input(lua_State *L)
2029 NodeMetaRef *ref = checkobject(L, 1);
2030 NodeMetadata *meta = getmeta(ref);
2031 if(meta == NULL) return 0;
2033 bool b = lua_toboolean(L, 2);
2034 meta->setAllowTextInput(b);
2035 reportMetadataChange(ref);
2039 // set_allow_removal(self, text)
2040 static int l_set_allow_removal(lua_State *L)
2042 NodeMetaRef *ref = checkobject(L, 1);
2043 NodeMetadata *meta = getmeta(ref);
2044 if(meta == NULL) return 0;
2046 bool b = lua_toboolean(L, 2);
2047 meta->setRemovalDisabled(!b);
2048 reportMetadataChange(ref);
2052 // set_enforce_owner(self, text)
2053 static int l_set_enforce_owner(lua_State *L)
2055 NodeMetaRef *ref = checkobject(L, 1);
2056 NodeMetadata *meta = getmeta(ref);
2057 if(meta == NULL) return 0;
2059 bool b = lua_toboolean(L, 2);
2060 meta->setEnforceOwner(b);
2061 reportMetadataChange(ref);
2065 // is_inventory_modified(self)
2066 static int l_is_inventory_modified(lua_State *L)
2068 NodeMetaRef *ref = checkobject(L, 1);
2069 NodeMetadata *meta = getmeta(ref);
2070 if(meta == NULL) return 0;
2072 lua_pushboolean(L, meta->isInventoryModified());
2076 // reset_inventory_modified(self)
2077 static int l_reset_inventory_modified(lua_State *L)
2079 NodeMetaRef *ref = checkobject(L, 1);
2080 NodeMetadata *meta = getmeta(ref);
2081 if(meta == NULL) return 0;
2083 meta->resetInventoryModified();
2084 reportMetadataChange(ref);
2088 // is_text_modified(self)
2089 static int l_is_text_modified(lua_State *L)
2091 NodeMetaRef *ref = checkobject(L, 1);
2092 NodeMetadata *meta = getmeta(ref);
2093 if(meta == NULL) return 0;
2095 lua_pushboolean(L, meta->isTextModified());
2099 // reset_text_modified(self)
2100 static int l_reset_text_modified(lua_State *L)
2102 NodeMetaRef *ref = checkobject(L, 1);
2103 NodeMetadata *meta = getmeta(ref);
2104 if(meta == NULL) return 0;
2106 meta->resetTextModified();
2107 reportMetadataChange(ref);
2111 // set_string(self, name, var)
2112 static int l_set_string(lua_State *L)
2114 NodeMetaRef *ref = checkobject(L, 1);
2115 NodeMetadata *meta = getmeta(ref);
2116 if(meta == NULL) return 0;
2118 std::string name = luaL_checkstring(L, 2);
2120 const char *s = lua_tolstring(L, 3, &len);
2121 std::string str(s, len);
2122 meta->setString(name, str);
2123 reportMetadataChange(ref);
2127 // get_string(self, name)
2128 static int l_get_string(lua_State *L)
2130 NodeMetaRef *ref = checkobject(L, 1);
2131 NodeMetadata *meta = getmeta(ref);
2132 if(meta == NULL) return 0;
2134 std::string name = luaL_checkstring(L, 2);
2135 std::string str = meta->getString(name);
2136 lua_pushlstring(L, str.c_str(), str.size());
2141 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2151 // Creates an NodeMetaRef and leaves it on top of stack
2152 // Not callable from Lua; all references are created on the C side.
2153 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2155 NodeMetaRef *o = new NodeMetaRef(p, env);
2156 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2157 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2158 luaL_getmetatable(L, className);
2159 lua_setmetatable(L, -2);
2162 static void Register(lua_State *L)
2165 int methodtable = lua_gettop(L);
2166 luaL_newmetatable(L, className);
2167 int metatable = lua_gettop(L);
2169 lua_pushliteral(L, "__metatable");
2170 lua_pushvalue(L, methodtable);
2171 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2173 lua_pushliteral(L, "__index");
2174 lua_pushvalue(L, methodtable);
2175 lua_settable(L, metatable);
2177 lua_pushliteral(L, "__gc");
2178 lua_pushcfunction(L, gc_object);
2179 lua_settable(L, metatable);
2181 lua_pop(L, 1); // drop metatable
2183 luaL_openlib(L, 0, methods, 0); // fill methodtable
2184 lua_pop(L, 1); // drop methodtable
2186 // Cannot be created from Lua
2187 //lua_register(L, className, create_object);
2190 const char NodeMetaRef::className[] = "NodeMetaRef";
2191 const luaL_reg NodeMetaRef::methods[] = {
2192 method(NodeMetaRef, get_type),
2193 method(NodeMetaRef, allows_text_input),
2194 method(NodeMetaRef, set_text),
2195 method(NodeMetaRef, get_text),
2196 method(NodeMetaRef, get_owner),
2197 method(NodeMetaRef, set_owner),
2198 method(NodeMetaRef, get_allow_removal),
2199 method(NodeMetaRef, set_infotext),
2200 method(NodeMetaRef, get_inventory),
2201 method(NodeMetaRef, set_inventory_draw_spec),
2202 method(NodeMetaRef, set_allow_text_input),
2203 method(NodeMetaRef, set_allow_removal),
2204 method(NodeMetaRef, set_enforce_owner),
2205 method(NodeMetaRef, is_inventory_modified),
2206 method(NodeMetaRef, reset_inventory_modified),
2207 method(NodeMetaRef, is_text_modified),
2208 method(NodeMetaRef, reset_text_modified),
2209 method(NodeMetaRef, set_string),
2210 method(NodeMetaRef, get_string),
2221 ServerActiveObject *m_object;
2223 static const char className[];
2224 static const luaL_reg methods[];
2226 static ObjectRef *checkobject(lua_State *L, int narg)
2228 luaL_checktype(L, narg, LUA_TUSERDATA);
2229 void *ud = luaL_checkudata(L, narg, className);
2230 if(!ud) luaL_typerror(L, narg, className);
2231 return *(ObjectRef**)ud; // unbox pointer
2234 static ServerActiveObject* getobject(ObjectRef *ref)
2236 ServerActiveObject *co = ref->m_object;
2240 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2242 ServerActiveObject *obj = getobject(ref);
2245 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2247 return (LuaEntitySAO*)obj;
2250 static ServerRemotePlayer* getplayer(ObjectRef *ref)
2252 ServerActiveObject *obj = getobject(ref);
2255 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2257 return static_cast<ServerRemotePlayer*>(obj);
2260 // Exported functions
2262 // garbage collector
2263 static int gc_object(lua_State *L) {
2264 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2265 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2271 static int l_remove(lua_State *L)
2273 ObjectRef *ref = checkobject(L, 1);
2274 ServerActiveObject *co = getobject(ref);
2275 if(co == NULL) return 0;
2276 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2277 co->m_removed = true;
2282 // returns: {x=num, y=num, z=num}
2283 static int l_getpos(lua_State *L)
2285 ObjectRef *ref = checkobject(L, 1);
2286 ServerActiveObject *co = getobject(ref);
2287 if(co == NULL) return 0;
2288 v3f pos = co->getBasePosition() / BS;
2290 lua_pushnumber(L, pos.X);
2291 lua_setfield(L, -2, "x");
2292 lua_pushnumber(L, pos.Y);
2293 lua_setfield(L, -2, "y");
2294 lua_pushnumber(L, pos.Z);
2295 lua_setfield(L, -2, "z");
2299 // setpos(self, pos)
2300 static int l_setpos(lua_State *L)
2302 ObjectRef *ref = checkobject(L, 1);
2303 //LuaEntitySAO *co = getluaobject(ref);
2304 ServerActiveObject *co = getobject(ref);
2305 if(co == NULL) return 0;
2307 v3f pos = checkFloatPos(L, 2);
2310 // Move player if applicable
2311 ServerRemotePlayer *player = getplayer(ref);
2313 get_server(L)->SendMovePlayer(player);
2317 // moveto(self, pos, continuous=false)
2318 static int l_moveto(lua_State *L)
2320 ObjectRef *ref = checkobject(L, 1);
2321 //LuaEntitySAO *co = getluaobject(ref);
2322 ServerActiveObject *co = getobject(ref);
2323 if(co == NULL) return 0;
2325 v3f pos = checkFloatPos(L, 2);
2327 bool continuous = lua_toboolean(L, 3);
2329 co->moveTo(pos, continuous);
2333 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2334 static int l_punch(lua_State *L)
2336 ObjectRef *ref = checkobject(L, 1);
2337 ObjectRef *puncher_ref = checkobject(L, 2);
2338 ServerActiveObject *co = getobject(ref);
2339 ServerActiveObject *puncher = getobject(puncher_ref);
2340 if(co == NULL) return 0;
2341 if(puncher == NULL) return 0;
2342 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2343 v3f dir = read_v3f(L, 4);
2344 float time_from_last_punch = 1000000;
2345 if(lua_isnumber(L, 5))
2346 time_from_last_punch = lua_tonumber(L, 5);
2348 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2352 // right_click(self, clicker); clicker = an another ObjectRef
2353 static int l_right_click(lua_State *L)
2355 ObjectRef *ref = checkobject(L, 1);
2356 ObjectRef *ref2 = checkobject(L, 2);
2357 ServerActiveObject *co = getobject(ref);
2358 ServerActiveObject *co2 = getobject(ref2);
2359 if(co == NULL) return 0;
2360 if(co2 == NULL) return 0;
2362 co->rightClick(co2);
2367 // hp = number of hitpoints (2 * number of hearts)
2369 static int l_set_hp(lua_State *L)
2371 ObjectRef *ref = checkobject(L, 1);
2372 luaL_checknumber(L, 2);
2373 ServerActiveObject *co = getobject(ref);
2374 if(co == NULL) return 0;
2375 int hp = lua_tonumber(L, 2);
2376 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2377 <<" hp="<<hp<<std::endl;*/
2385 // returns: number of hitpoints (2 * number of hearts)
2386 // 0 if not applicable to this type of object
2387 static int l_get_hp(lua_State *L)
2389 ObjectRef *ref = checkobject(L, 1);
2390 ServerActiveObject *co = getobject(ref);
2391 if(co == NULL) return 0;
2392 int hp = co->getHP();
2393 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2394 <<" hp="<<hp<<std::endl;*/
2396 lua_pushnumber(L, hp);
2400 // get_inventory(self)
2401 static int l_get_inventory(lua_State *L)
2403 ObjectRef *ref = checkobject(L, 1);
2404 ServerActiveObject *co = getobject(ref);
2405 if(co == NULL) return 0;
2407 InventoryLocation loc = co->getInventoryLocation();
2408 if(get_server(L)->getInventory(loc) != NULL)
2409 InvRef::create(L, loc);
2415 // get_wield_list(self)
2416 static int l_get_wield_list(lua_State *L)
2418 ObjectRef *ref = checkobject(L, 1);
2419 ServerActiveObject *co = getobject(ref);
2420 if(co == NULL) return 0;
2422 lua_pushstring(L, co->getWieldList().c_str());
2426 // get_wield_index(self)
2427 static int l_get_wield_index(lua_State *L)
2429 ObjectRef *ref = checkobject(L, 1);
2430 ServerActiveObject *co = getobject(ref);
2431 if(co == NULL) return 0;
2433 lua_pushinteger(L, co->getWieldIndex() + 1);
2437 // get_wielded_item(self)
2438 static int l_get_wielded_item(lua_State *L)
2440 ObjectRef *ref = checkobject(L, 1);
2441 ServerActiveObject *co = getobject(ref);
2442 if(co == NULL) return 0;
2444 LuaItemStack::create(L, co->getWieldedItem());
2448 // set_wielded_item(self, itemstack or itemstring or table or nil)
2449 static int l_set_wielded_item(lua_State *L)
2451 ObjectRef *ref = checkobject(L, 1);
2452 ServerActiveObject *co = getobject(ref);
2453 if(co == NULL) return 0;
2455 ItemStack item = read_item(L, 2);
2456 bool success = co->setWieldedItem(item);
2457 lua_pushboolean(L, success);
2461 /* LuaEntitySAO-only */
2463 // setvelocity(self, {x=num, y=num, z=num})
2464 static int l_setvelocity(lua_State *L)
2466 ObjectRef *ref = checkobject(L, 1);
2467 LuaEntitySAO *co = getluaobject(ref);
2468 if(co == NULL) return 0;
2470 v3f pos = checkFloatPos(L, 2);
2472 co->setVelocity(pos);
2476 // getvelocity(self)
2477 static int l_getvelocity(lua_State *L)
2479 ObjectRef *ref = checkobject(L, 1);
2480 LuaEntitySAO *co = getluaobject(ref);
2481 if(co == NULL) return 0;
2483 v3f v = co->getVelocity();
2488 // setacceleration(self, {x=num, y=num, z=num})
2489 static int l_setacceleration(lua_State *L)
2491 ObjectRef *ref = checkobject(L, 1);
2492 LuaEntitySAO *co = getluaobject(ref);
2493 if(co == NULL) return 0;
2495 v3f pos = checkFloatPos(L, 2);
2497 co->setAcceleration(pos);
2501 // getacceleration(self)
2502 static int l_getacceleration(lua_State *L)
2504 ObjectRef *ref = checkobject(L, 1);
2505 LuaEntitySAO *co = getluaobject(ref);
2506 if(co == NULL) return 0;
2508 v3f v = co->getAcceleration();
2513 // setyaw(self, radians)
2514 static int l_setyaw(lua_State *L)
2516 ObjectRef *ref = checkobject(L, 1);
2517 LuaEntitySAO *co = getluaobject(ref);
2518 if(co == NULL) return 0;
2520 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2527 static int l_getyaw(lua_State *L)
2529 ObjectRef *ref = checkobject(L, 1);
2530 LuaEntitySAO *co = getluaobject(ref);
2531 if(co == NULL) return 0;
2533 float yaw = co->getYaw() * core::DEGTORAD;
2534 lua_pushnumber(L, yaw);
2538 // settexturemod(self, mod)
2539 static int l_settexturemod(lua_State *L)
2541 ObjectRef *ref = checkobject(L, 1);
2542 LuaEntitySAO *co = getluaobject(ref);
2543 if(co == NULL) return 0;
2545 std::string mod = luaL_checkstring(L, 2);
2546 co->setTextureMod(mod);
2550 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2551 // select_horiz_by_yawpitch=false)
2552 static int l_setsprite(lua_State *L)
2554 ObjectRef *ref = checkobject(L, 1);
2555 LuaEntitySAO *co = getluaobject(ref);
2556 if(co == NULL) return 0;
2559 if(!lua_isnil(L, 2))
2560 p = read_v2s16(L, 2);
2562 if(!lua_isnil(L, 3))
2563 num_frames = lua_tonumber(L, 3);
2564 float framelength = 0.2;
2565 if(!lua_isnil(L, 4))
2566 framelength = lua_tonumber(L, 4);
2567 bool select_horiz_by_yawpitch = false;
2568 if(!lua_isnil(L, 5))
2569 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2570 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2574 // set_armor_groups(self, groups)
2575 static int l_set_armor_groups(lua_State *L)
2577 ObjectRef *ref = checkobject(L, 1);
2578 LuaEntitySAO *co = getluaobject(ref);
2579 if(co == NULL) return 0;
2581 ItemGroupList groups;
2582 read_groups(L, 2, groups);
2583 co->setArmorGroups(groups);
2588 // get_entity_name(self)
2589 static int l_get_entity_name(lua_State *L)
2591 ObjectRef *ref = checkobject(L, 1);
2592 LuaEntitySAO *co = getluaobject(ref);
2593 if(co == NULL) return 0;
2595 std::string name = co->getName();
2596 lua_pushstring(L, name.c_str());
2600 // get_luaentity(self)
2601 static int l_get_luaentity(lua_State *L)
2603 ObjectRef *ref = checkobject(L, 1);
2604 LuaEntitySAO *co = getluaobject(ref);
2605 if(co == NULL) return 0;
2607 luaentity_get(L, co->getId());
2613 // get_player_name(self)
2614 static int l_get_player_name(lua_State *L)
2616 ObjectRef *ref = checkobject(L, 1);
2617 ServerRemotePlayer *player = getplayer(ref);
2623 lua_pushstring(L, player->getName());
2627 // get_look_dir(self)
2628 static int l_get_look_dir(lua_State *L)
2630 ObjectRef *ref = checkobject(L, 1);
2631 ServerRemotePlayer *player = getplayer(ref);
2632 if(player == NULL) return 0;
2634 float pitch = player->getRadPitch();
2635 float yaw = player->getRadYaw();
2636 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2641 // get_look_pitch(self)
2642 static int l_get_look_pitch(lua_State *L)
2644 ObjectRef *ref = checkobject(L, 1);
2645 ServerRemotePlayer *player = getplayer(ref);
2646 if(player == NULL) return 0;
2648 lua_pushnumber(L, player->getRadPitch());
2652 // get_look_yaw(self)
2653 static int l_get_look_yaw(lua_State *L)
2655 ObjectRef *ref = checkobject(L, 1);
2656 ServerRemotePlayer *player = getplayer(ref);
2657 if(player == NULL) return 0;
2659 lua_pushnumber(L, player->getRadYaw());
2664 ObjectRef(ServerActiveObject *object):
2667 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2673 infostream<<"ObjectRef destructing for id="
2674 <<m_object->getId()<<std::endl;
2676 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2679 // Creates an ObjectRef and leaves it on top of stack
2680 // Not callable from Lua; all references are created on the C side.
2681 static void create(lua_State *L, ServerActiveObject *object)
2683 ObjectRef *o = new ObjectRef(object);
2684 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2685 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2686 luaL_getmetatable(L, className);
2687 lua_setmetatable(L, -2);
2690 static void set_null(lua_State *L)
2692 ObjectRef *o = checkobject(L, -1);
2696 static void Register(lua_State *L)
2699 int methodtable = lua_gettop(L);
2700 luaL_newmetatable(L, className);
2701 int metatable = lua_gettop(L);
2703 lua_pushliteral(L, "__metatable");
2704 lua_pushvalue(L, methodtable);
2705 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2707 lua_pushliteral(L, "__index");
2708 lua_pushvalue(L, methodtable);
2709 lua_settable(L, metatable);
2711 lua_pushliteral(L, "__gc");
2712 lua_pushcfunction(L, gc_object);
2713 lua_settable(L, metatable);
2715 lua_pop(L, 1); // drop metatable
2717 luaL_openlib(L, 0, methods, 0); // fill methodtable
2718 lua_pop(L, 1); // drop methodtable
2720 // Cannot be created from Lua
2721 //lua_register(L, className, create_object);
2724 const char ObjectRef::className[] = "ObjectRef";
2725 const luaL_reg ObjectRef::methods[] = {
2726 // ServerActiveObject
2727 method(ObjectRef, remove),
2728 method(ObjectRef, getpos),
2729 method(ObjectRef, setpos),
2730 method(ObjectRef, moveto),
2731 method(ObjectRef, punch),
2732 method(ObjectRef, right_click),
2733 method(ObjectRef, set_hp),
2734 method(ObjectRef, get_hp),
2735 method(ObjectRef, get_inventory),
2736 method(ObjectRef, get_wield_list),
2737 method(ObjectRef, get_wield_index),
2738 method(ObjectRef, get_wielded_item),
2739 method(ObjectRef, set_wielded_item),
2740 // LuaEntitySAO-only
2741 method(ObjectRef, setvelocity),
2742 method(ObjectRef, getvelocity),
2743 method(ObjectRef, setacceleration),
2744 method(ObjectRef, getacceleration),
2745 method(ObjectRef, setyaw),
2746 method(ObjectRef, getyaw),
2747 method(ObjectRef, settexturemod),
2748 method(ObjectRef, setsprite),
2749 method(ObjectRef, set_armor_groups),
2750 method(ObjectRef, get_entity_name),
2751 method(ObjectRef, get_luaentity),
2753 method(ObjectRef, get_player_name),
2754 method(ObjectRef, get_look_dir),
2755 method(ObjectRef, get_look_pitch),
2756 method(ObjectRef, get_look_yaw),
2760 // Creates a new anonymous reference if id=0
2761 static void objectref_get_or_create(lua_State *L,
2762 ServerActiveObject *cobj)
2764 if(cobj->getId() == 0){
2765 ObjectRef::create(L, cobj);
2767 objectref_get(L, cobj->getId());
2778 ServerEnvironment *m_env;
2780 static const char className[];
2781 static const luaL_reg methods[];
2783 static EnvRef *checkobject(lua_State *L, int narg)
2785 luaL_checktype(L, narg, LUA_TUSERDATA);
2786 void *ud = luaL_checkudata(L, narg, className);
2787 if(!ud) luaL_typerror(L, narg, className);
2788 return *(EnvRef**)ud; // unbox pointer
2791 // Exported functions
2793 // EnvRef:add_node(pos, node)
2794 // pos = {x=num, y=num, z=num}
2795 static int l_add_node(lua_State *L)
2797 //infostream<<"EnvRef::l_add_node()"<<std::endl;
2798 EnvRef *o = checkobject(L, 1);
2799 ServerEnvironment *env = o->m_env;
2800 if(env == NULL) return 0;
2802 v3s16 pos = read_v3s16(L, 2);
2804 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2806 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2807 lua_pushboolean(L, succeeded);
2811 // EnvRef:remove_node(pos)
2812 // pos = {x=num, y=num, z=num}
2813 static int l_remove_node(lua_State *L)
2815 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2816 EnvRef *o = checkobject(L, 1);
2817 ServerEnvironment *env = o->m_env;
2818 if(env == NULL) return 0;
2820 v3s16 pos = read_v3s16(L, 2);
2822 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2823 lua_pushboolean(L, succeeded);
2827 // EnvRef:get_node(pos)
2828 // pos = {x=num, y=num, z=num}
2829 static int l_get_node(lua_State *L)
2831 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2832 EnvRef *o = checkobject(L, 1);
2833 ServerEnvironment *env = o->m_env;
2834 if(env == NULL) return 0;
2836 v3s16 pos = read_v3s16(L, 2);
2838 MapNode n = env->getMap().getNodeNoEx(pos);
2840 pushnode(L, n, env->getGameDef()->ndef());
2844 // EnvRef:get_node_or_nil(pos)
2845 // pos = {x=num, y=num, z=num}
2846 static int l_get_node_or_nil(lua_State *L)
2848 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2849 EnvRef *o = checkobject(L, 1);
2850 ServerEnvironment *env = o->m_env;
2851 if(env == NULL) return 0;
2853 v3s16 pos = read_v3s16(L, 2);
2856 MapNode n = env->getMap().getNode(pos);
2858 pushnode(L, n, env->getGameDef()->ndef());
2860 } catch(InvalidPositionException &e)
2867 // EnvRef:get_node_light(pos, timeofday)
2868 // pos = {x=num, y=num, z=num}
2869 // timeofday: nil = current time, 0 = night, 0.5 = day
2870 static int l_get_node_light(lua_State *L)
2872 EnvRef *o = checkobject(L, 1);
2873 ServerEnvironment *env = o->m_env;
2874 if(env == NULL) return 0;
2876 v3s16 pos = read_v3s16(L, 2);
2877 u32 time_of_day = env->getTimeOfDay();
2878 if(lua_isnumber(L, 3))
2879 time_of_day = 24000.0 * lua_tonumber(L, 3);
2880 time_of_day %= 24000;
2881 u32 dnr = time_to_daynight_ratio(time_of_day);
2882 MapNode n = env->getMap().getNodeNoEx(pos);
2884 MapNode n = env->getMap().getNode(pos);
2885 INodeDefManager *ndef = env->getGameDef()->ndef();
2886 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2888 } catch(InvalidPositionException &e)
2895 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2896 // pos = {x=num, y=num, z=num}
2897 static int l_add_entity(lua_State *L)
2899 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2900 EnvRef *o = checkobject(L, 1);
2901 ServerEnvironment *env = o->m_env;
2902 if(env == NULL) return 0;
2904 v3f pos = checkFloatPos(L, 2);
2906 const char *name = luaL_checkstring(L, 3);
2908 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2909 int objectid = env->addActiveObject(obj);
2910 // If failed to add, return nothing (reads as nil)
2914 objectref_get_or_create(L, obj);
2918 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2919 // pos = {x=num, y=num, z=num}
2920 static int l_add_item(lua_State *L)
2922 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2923 EnvRef *o = checkobject(L, 1);
2924 ServerEnvironment *env = o->m_env;
2925 if(env == NULL) return 0;
2927 v3f pos = checkFloatPos(L, 2);
2929 ItemStack item = read_item(L, 3);
2930 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2933 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2934 int objectid = env->addActiveObject(obj);
2935 // If failed to add, return nothing (reads as nil)
2939 objectref_get_or_create(L, obj);
2943 // EnvRef:add_rat(pos)
2944 // pos = {x=num, y=num, z=num}
2945 static int l_add_rat(lua_State *L)
2947 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2948 <<" Doing nothing."<<std::endl;
2952 // EnvRef:add_firefly(pos)
2953 // pos = {x=num, y=num, z=num}
2954 static int l_add_firefly(lua_State *L)
2956 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2957 <<" Doing nothing."<<std::endl;
2961 // EnvRef:get_meta(pos)
2962 static int l_get_meta(lua_State *L)
2964 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2965 EnvRef *o = checkobject(L, 1);
2966 ServerEnvironment *env = o->m_env;
2967 if(env == NULL) return 0;
2969 v3s16 p = read_v3s16(L, 2);
2970 NodeMetaRef::create(L, p, env);
2974 // EnvRef:get_player_by_name(name)
2975 static int l_get_player_by_name(lua_State *L)
2977 EnvRef *o = checkobject(L, 1);
2978 ServerEnvironment *env = o->m_env;
2979 if(env == NULL) return 0;
2981 const char *name = luaL_checkstring(L, 2);
2982 ServerRemotePlayer *player =
2983 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2988 // Put player on stack
2989 objectref_get_or_create(L, player);
2993 // EnvRef:get_objects_inside_radius(pos, radius)
2994 static int l_get_objects_inside_radius(lua_State *L)
2996 // Get the table insert function
2997 lua_getglobal(L, "table");
2998 lua_getfield(L, -1, "insert");
2999 int table_insert = lua_gettop(L);
3001 EnvRef *o = checkobject(L, 1);
3002 ServerEnvironment *env = o->m_env;
3003 if(env == NULL) return 0;
3005 v3f pos = checkFloatPos(L, 2);
3006 float radius = luaL_checknumber(L, 3) * BS;
3007 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3009 int table = lua_gettop(L);
3010 for(std::set<u16>::const_iterator
3011 i = ids.begin(); i != ids.end(); i++){
3012 ServerActiveObject *obj = env->getActiveObject(*i);
3013 // Insert object reference into table
3014 lua_pushvalue(L, table_insert);
3015 lua_pushvalue(L, table);
3016 objectref_get_or_create(L, obj);
3017 if(lua_pcall(L, 2, 0, 0))
3018 script_error(L, "error: %s", lua_tostring(L, -1));
3023 // EnvRef:set_timeofday(val)
3025 static int l_set_timeofday(lua_State *L)
3027 EnvRef *o = checkobject(L, 1);
3028 ServerEnvironment *env = o->m_env;
3029 if(env == NULL) return 0;
3031 float timeofday_f = luaL_checknumber(L, 2);
3032 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3033 int timeofday_mh = (int)(timeofday_f * 24000.0);
3034 // This should be set directly in the environment but currently
3035 // such changes aren't immediately sent to the clients, so call
3036 // the server instead.
3037 //env->setTimeOfDay(timeofday_mh);
3038 get_server(L)->setTimeOfDay(timeofday_mh);
3042 // EnvRef:get_timeofday() -> 0...1
3043 static int l_get_timeofday(lua_State *L)
3045 EnvRef *o = checkobject(L, 1);
3046 ServerEnvironment *env = o->m_env;
3047 if(env == NULL) return 0;
3049 int timeofday_mh = env->getTimeOfDay();
3050 float timeofday_f = (float)timeofday_mh / 24000.0;
3051 lua_pushnumber(L, timeofday_f);
3055 static int gc_object(lua_State *L) {
3056 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3062 EnvRef(ServerEnvironment *env):
3065 //infostream<<"EnvRef created"<<std::endl;
3070 //infostream<<"EnvRef destructing"<<std::endl;
3073 // Creates an EnvRef and leaves it on top of stack
3074 // Not callable from Lua; all references are created on the C side.
3075 static void create(lua_State *L, ServerEnvironment *env)
3077 EnvRef *o = new EnvRef(env);
3078 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3079 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3080 luaL_getmetatable(L, className);
3081 lua_setmetatable(L, -2);
3084 static void set_null(lua_State *L)
3086 EnvRef *o = checkobject(L, -1);
3090 static void Register(lua_State *L)
3093 int methodtable = lua_gettop(L);
3094 luaL_newmetatable(L, className);
3095 int metatable = lua_gettop(L);
3097 lua_pushliteral(L, "__metatable");
3098 lua_pushvalue(L, methodtable);
3099 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3101 lua_pushliteral(L, "__index");
3102 lua_pushvalue(L, methodtable);
3103 lua_settable(L, metatable);
3105 lua_pushliteral(L, "__gc");
3106 lua_pushcfunction(L, gc_object);
3107 lua_settable(L, metatable);
3109 lua_pop(L, 1); // drop metatable
3111 luaL_openlib(L, 0, methods, 0); // fill methodtable
3112 lua_pop(L, 1); // drop methodtable
3114 // Cannot be created from Lua
3115 //lua_register(L, className, create_object);
3118 const char EnvRef::className[] = "EnvRef";
3119 const luaL_reg EnvRef::methods[] = {
3120 method(EnvRef, add_node),
3121 method(EnvRef, remove_node),
3122 method(EnvRef, get_node),
3123 method(EnvRef, get_node_or_nil),
3124 method(EnvRef, get_node_light),
3125 method(EnvRef, add_entity),
3126 method(EnvRef, add_item),
3127 method(EnvRef, add_rat),
3128 method(EnvRef, add_firefly),
3129 method(EnvRef, get_meta),
3130 method(EnvRef, get_player_by_name),
3131 method(EnvRef, get_objects_inside_radius),
3132 method(EnvRef, set_timeofday),
3133 method(EnvRef, get_timeofday),
3137 class LuaABM : public ActiveBlockModifier
3143 std::set<std::string> m_trigger_contents;
3144 std::set<std::string> m_required_neighbors;
3145 float m_trigger_interval;
3146 u32 m_trigger_chance;
3148 LuaABM(lua_State *L, int id,
3149 const std::set<std::string> &trigger_contents,
3150 const std::set<std::string> &required_neighbors,
3151 float trigger_interval, u32 trigger_chance):
3154 m_trigger_contents(trigger_contents),
3155 m_required_neighbors(required_neighbors),
3156 m_trigger_interval(trigger_interval),
3157 m_trigger_chance(trigger_chance)
3160 virtual std::set<std::string> getTriggerContents()
3162 return m_trigger_contents;
3164 virtual std::set<std::string> getRequiredNeighbors()
3166 return m_required_neighbors;
3168 virtual float getTriggerInterval()
3170 return m_trigger_interval;
3172 virtual u32 getTriggerChance()
3174 return m_trigger_chance;
3176 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3177 u32 active_object_count, u32 active_object_count_wider)
3179 lua_State *L = m_lua;
3182 assert(lua_checkstack(L, 20));
3183 StackUnroller stack_unroller(L);
3185 // Get minetest.registered_abms
3186 lua_getglobal(L, "minetest");
3187 lua_getfield(L, -1, "registered_abms");
3188 luaL_checktype(L, -1, LUA_TTABLE);
3189 int registered_abms = lua_gettop(L);
3191 // Get minetest.registered_abms[m_id]
3192 lua_pushnumber(L, m_id);
3193 lua_gettable(L, registered_abms);
3194 if(lua_isnil(L, -1))
3198 luaL_checktype(L, -1, LUA_TTABLE);
3199 lua_getfield(L, -1, "action");
3200 luaL_checktype(L, -1, LUA_TFUNCTION);
3202 pushnode(L, n, env->getGameDef()->ndef());
3203 lua_pushnumber(L, active_object_count);
3204 lua_pushnumber(L, active_object_count_wider);
3205 if(lua_pcall(L, 4, 0, 0))
3206 script_error(L, "error: %s", lua_tostring(L, -1));
3214 static void read_server_sound_params(lua_State *L, int index,
3215 ServerSoundParams ¶ms)
3218 index = lua_gettop(L) + 1 + index;
3220 params = ServerSoundParams();
3221 if(lua_istable(L, index)){
3222 getfloatfield(L, index, "gain", params.gain);
3223 getstringfield(L, index, "to_player", params.to_player);
3224 lua_getfield(L, index, "pos");
3225 if(!lua_isnil(L, -1)){
3226 v3f p = read_v3f(L, -1)*BS;
3228 params.type = ServerSoundParams::SSP_POSITIONAL;
3231 lua_getfield(L, index, "object");
3232 if(!lua_isnil(L, -1)){
3233 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3234 ServerActiveObject *sao = ObjectRef::getobject(ref);
3236 params.object = sao->getId();
3237 params.type = ServerSoundParams::SSP_OBJECT;
3241 params.max_hear_distance = BS*getfloatfield_default(L, index,
3242 "max_hear_distance", params.max_hear_distance/BS);
3243 getboolfield(L, index, "loop", params.loop);
3252 // Writes a line to dstream
3253 static int l_debug(lua_State *L)
3255 std::string text = lua_tostring(L, 1);
3256 dstream << text << std::endl;
3260 // log([level,] text)
3261 // Writes a line to the logger.
3262 // The one-argument version logs to infostream.
3263 // The two-argument version accept a log level: error, action, info, or verbose.
3264 static int l_log(lua_State *L)
3267 LogMessageLevel level = LMT_INFO;
3268 if(lua_isnone(L, 2))
3270 text = lua_tostring(L, 1);
3274 std::string levelname = lua_tostring(L, 1);
3275 text = lua_tostring(L, 2);
3276 if(levelname == "error")
3278 else if(levelname == "action")
3280 else if(levelname == "verbose")
3281 level = LMT_VERBOSE;
3283 log_printline(level, text);
3287 // register_item_raw({lots of stuff})
3288 static int l_register_item_raw(lua_State *L)
3290 luaL_checktype(L, 1, LUA_TTABLE);
3293 // Get the writable item and node definition managers from the server
3294 IWritableItemDefManager *idef =
3295 get_server(L)->getWritableItemDefManager();
3296 IWritableNodeDefManager *ndef =
3297 get_server(L)->getWritableNodeDefManager();
3299 // Check if name is defined
3300 lua_getfield(L, table, "name");
3301 if(lua_isstring(L, -1)){
3302 std::string name = lua_tostring(L, -1);
3303 verbosestream<<"register_item_raw: "<<name<<std::endl;
3305 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3308 // Check if on_use is defined
3310 // Read the item definition and register it
3311 ItemDefinition def = read_item_definition(L, table);
3312 idef->registerItem(def);
3314 // Read the node definition (content features) and register it
3315 if(def.type == ITEM_NODE)
3317 ContentFeatures f = read_content_features(L, table);
3318 ndef->set(f.name, f);
3321 return 0; /* number of results */
3324 // register_alias_raw(name, convert_to_name)
3325 static int l_register_alias_raw(lua_State *L)
3327 std::string name = luaL_checkstring(L, 1);
3328 std::string convert_to = luaL_checkstring(L, 2);
3330 // Get the writable item definition manager from the server
3331 IWritableItemDefManager *idef =
3332 get_server(L)->getWritableItemDefManager();
3334 idef->registerAlias(name, convert_to);
3336 return 0; /* number of results */
3339 // helper for register_craft
3340 static bool read_craft_recipe_shaped(lua_State *L, int index,
3341 int &width, std::vector<std::string> &recipe)
3344 index = lua_gettop(L) + 1 + index;
3346 if(!lua_istable(L, index))
3351 while(lua_next(L, index) != 0){
3353 // key at index -2 and value at index -1
3354 if(!lua_istable(L, -1))
3356 int table2 = lua_gettop(L);
3358 while(lua_next(L, table2) != 0){
3359 // key at index -2 and value at index -1
3360 if(!lua_isstring(L, -1))
3362 recipe.push_back(lua_tostring(L, -1));
3363 // removes value, keeps key for next iteration
3370 if(colcount != width)
3373 // removes value, keeps key for next iteration
3380 // helper for register_craft
3381 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3382 std::vector<std::string> &recipe)
3385 index = lua_gettop(L) + 1 + index;
3387 if(!lua_istable(L, index))
3391 while(lua_next(L, index) != 0){
3392 // key at index -2 and value at index -1
3393 if(!lua_isstring(L, -1))
3395 recipe.push_back(lua_tostring(L, -1));
3396 // removes value, keeps key for next iteration
3402 // helper for register_craft
3403 static bool read_craft_replacements(lua_State *L, int index,
3404 CraftReplacements &replacements)
3407 index = lua_gettop(L) + 1 + index;
3409 if(!lua_istable(L, index))
3413 while(lua_next(L, index) != 0){
3414 // key at index -2 and value at index -1
3415 if(!lua_istable(L, -1))
3417 lua_rawgeti(L, -1, 1);
3418 if(!lua_isstring(L, -1))
3420 std::string replace_from = lua_tostring(L, -1);
3422 lua_rawgeti(L, -1, 2);
3423 if(!lua_isstring(L, -1))
3425 std::string replace_to = lua_tostring(L, -1);
3427 replacements.pairs.push_back(
3428 std::make_pair(replace_from, replace_to));
3429 // removes value, keeps key for next iteration
3434 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3435 static int l_register_craft(lua_State *L)
3437 //infostream<<"register_craft"<<std::endl;
3438 luaL_checktype(L, 1, LUA_TTABLE);
3441 // Get the writable craft definition manager from the server
3442 IWritableCraftDefManager *craftdef =
3443 get_server(L)->getWritableCraftDefManager();
3445 std::string type = getstringfield_default(L, table, "type", "shaped");
3448 CraftDefinitionShaped
3450 if(type == "shaped"){
3451 std::string output = getstringfield_default(L, table, "output", "");
3453 throw LuaError(L, "Crafting definition is missing an output");
3456 std::vector<std::string> recipe;
3457 lua_getfield(L, table, "recipe");
3458 if(lua_isnil(L, -1))
3459 throw LuaError(L, "Crafting definition is missing a recipe"
3460 " (output=\"" + output + "\")");
3461 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3462 throw LuaError(L, "Invalid crafting recipe"
3463 " (output=\"" + output + "\")");
3465 CraftReplacements replacements;
3466 lua_getfield(L, table, "replacements");
3467 if(!lua_isnil(L, -1))
3469 if(!read_craft_replacements(L, -1, replacements))
3470 throw LuaError(L, "Invalid replacements"
3471 " (output=\"" + output + "\")");
3474 CraftDefinition *def = new CraftDefinitionShaped(
3475 output, width, recipe, replacements);
3476 craftdef->registerCraft(def);
3479 CraftDefinitionShapeless
3481 else if(type == "shapeless"){
3482 std::string output = getstringfield_default(L, table, "output", "");
3484 throw LuaError(L, "Crafting definition (shapeless)"
3485 " is missing an output");
3487 std::vector<std::string> recipe;
3488 lua_getfield(L, table, "recipe");
3489 if(lua_isnil(L, -1))
3490 throw LuaError(L, "Crafting definition (shapeless)"
3491 " is missing a recipe"
3492 " (output=\"" + output + "\")");
3493 if(!read_craft_recipe_shapeless(L, -1, recipe))
3494 throw LuaError(L, "Invalid crafting recipe"
3495 " (output=\"" + output + "\")");
3497 CraftReplacements replacements;
3498 lua_getfield(L, table, "replacements");
3499 if(!lua_isnil(L, -1))
3501 if(!read_craft_replacements(L, -1, replacements))
3502 throw LuaError(L, "Invalid replacements"
3503 " (output=\"" + output + "\")");
3506 CraftDefinition *def = new CraftDefinitionShapeless(
3507 output, recipe, replacements);
3508 craftdef->registerCraft(def);
3511 CraftDefinitionToolRepair
3513 else if(type == "toolrepair"){
3514 float additional_wear = getfloatfield_default(L, table,
3515 "additional_wear", 0.0);
3517 CraftDefinition *def = new CraftDefinitionToolRepair(
3519 craftdef->registerCraft(def);
3522 CraftDefinitionCooking
3524 else if(type == "cooking"){
3525 std::string output = getstringfield_default(L, table, "output", "");
3527 throw LuaError(L, "Crafting definition (cooking)"
3528 " is missing an output");
3530 std::string recipe = getstringfield_default(L, table, "recipe", "");
3532 throw LuaError(L, "Crafting definition (cooking)"
3533 " is missing a recipe"
3534 " (output=\"" + output + "\")");
3536 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3538 CraftDefinition *def = new CraftDefinitionCooking(
3539 output, recipe, cooktime);
3540 craftdef->registerCraft(def);
3545 else if(type == "fuel"){
3546 std::string recipe = getstringfield_default(L, table, "recipe", "");
3548 throw LuaError(L, "Crafting definition (fuel)"
3549 " is missing a recipe");
3551 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3553 CraftDefinition *def = new CraftDefinitionFuel(
3555 craftdef->registerCraft(def);
3559 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3563 return 0; /* number of results */
3566 // setting_get(name)
3567 static int l_setting_get(lua_State *L)
3569 const char *name = luaL_checkstring(L, 1);
3571 std::string value = g_settings->get(name);
3572 lua_pushstring(L, value.c_str());
3573 } catch(SettingNotFoundException &e){
3579 // setting_getbool(name)
3580 static int l_setting_getbool(lua_State *L)
3582 const char *name = luaL_checkstring(L, 1);
3584 bool value = g_settings->getBool(name);
3585 lua_pushboolean(L, value);
3586 } catch(SettingNotFoundException &e){
3592 // chat_send_all(text)
3593 static int l_chat_send_all(lua_State *L)
3595 const char *text = luaL_checkstring(L, 1);
3596 // Get server from registry
3597 Server *server = get_server(L);
3599 server->notifyPlayers(narrow_to_wide(text));
3603 // chat_send_player(name, text)
3604 static int l_chat_send_player(lua_State *L)
3606 const char *name = luaL_checkstring(L, 1);
3607 const char *text = luaL_checkstring(L, 2);
3608 // Get server from registry
3609 Server *server = get_server(L);
3611 server->notifyPlayer(name, narrow_to_wide(text));
3615 // get_player_privs(name, text)
3616 static int l_get_player_privs(lua_State *L)
3618 const char *name = luaL_checkstring(L, 1);
3619 // Get server from registry
3620 Server *server = get_server(L);
3623 int table = lua_gettop(L);
3624 u64 privs_i = server->getPlayerEffectivePrivs(name);
3625 std::set<std::string> privs_s = privsToSet(privs_i);
3626 for(std::set<std::string>::const_iterator
3627 i = privs_s.begin(); i != privs_s.end(); i++){
3628 lua_pushboolean(L, true);
3629 lua_setfield(L, table, i->c_str());
3631 lua_pushvalue(L, table);
3635 // get_inventory(location)
3636 static int l_get_inventory(lua_State *L)
3638 InventoryLocation loc;
3640 std::string type = checkstringfield(L, 1, "type");
3641 if(type == "player"){
3642 std::string name = checkstringfield(L, 1, "name");
3643 loc.setPlayer(name);
3644 } else if(type == "node"){
3645 lua_getfield(L, 1, "pos");
3646 v3s16 pos = check_v3s16(L, -1);
3647 loc.setNodeMeta(pos);
3650 if(get_server(L)->getInventory(loc) != NULL)
3651 InvRef::create(L, loc);
3657 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3658 static int l_get_dig_params(lua_State *L)
3660 std::map<std::string, int> groups;
3661 read_groups(L, 1, groups);
3662 ToolCapabilities tp = read_tool_capabilities(L, 2);
3663 if(lua_isnoneornil(L, 3))
3664 push_dig_params(L, getDigParams(groups, &tp));
3666 push_dig_params(L, getDigParams(groups, &tp,
3667 luaL_checknumber(L, 3)));
3671 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3672 static int l_get_hit_params(lua_State *L)
3674 std::map<std::string, int> groups;
3675 read_groups(L, 1, groups);
3676 ToolCapabilities tp = read_tool_capabilities(L, 2);
3677 if(lua_isnoneornil(L, 3))
3678 push_hit_params(L, getHitParams(groups, &tp));
3680 push_hit_params(L, getHitParams(groups, &tp,
3681 luaL_checknumber(L, 3)));
3685 // get_current_modname()
3686 static int l_get_current_modname(lua_State *L)
3688 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3692 // get_modpath(modname)
3693 static int l_get_modpath(lua_State *L)
3695 const char *modname = luaL_checkstring(L, 1);
3697 const ModSpec *mod = get_server(L)->getModSpec(modname);
3702 lua_pushstring(L, mod->path.c_str());
3707 static int l_get_worldpath(lua_State *L)
3709 std::string worldpath = get_server(L)->getWorldPath();
3710 lua_pushstring(L, worldpath.c_str());
3714 // sound_play(spec, parameters)
3715 static int l_sound_play(lua_State *L)
3717 SimpleSoundSpec spec;
3718 read_soundspec(L, 1, spec);
3719 ServerSoundParams params;
3720 read_server_sound_params(L, 2, params);
3721 s32 handle = get_server(L)->playSound(spec, params);
3722 lua_pushinteger(L, handle);
3726 // sound_stop(handle)
3727 static int l_sound_stop(lua_State *L)
3729 int handle = luaL_checkinteger(L, 1);
3730 get_server(L)->stopSound(handle);
3734 static const struct luaL_Reg minetest_f [] = {
3737 {"register_item_raw", l_register_item_raw},
3738 {"register_alias_raw", l_register_alias_raw},
3739 {"register_craft", l_register_craft},
3740 {"setting_get", l_setting_get},
3741 {"setting_getbool", l_setting_getbool},
3742 {"chat_send_all", l_chat_send_all},
3743 {"chat_send_player", l_chat_send_player},
3744 {"get_player_privs", l_get_player_privs},
3745 {"get_inventory", l_get_inventory},
3746 {"get_dig_params", l_get_dig_params},
3747 {"get_hit_params", l_get_hit_params},
3748 {"get_current_modname", l_get_current_modname},
3749 {"get_modpath", l_get_modpath},
3750 {"get_worldpath", l_get_worldpath},
3751 {"sound_play", l_sound_play},
3752 {"sound_stop", l_sound_stop},
3757 Main export function
3760 void scriptapi_export(lua_State *L, Server *server)
3763 assert(lua_checkstack(L, 20));
3764 verbosestream<<"scriptapi_export()"<<std::endl;
3765 StackUnroller stack_unroller(L);
3767 // Store server as light userdata in registry
3768 lua_pushlightuserdata(L, server);
3769 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3771 // Register global functions in table minetest
3773 luaL_register(L, NULL, minetest_f);
3774 lua_setglobal(L, "minetest");
3776 // Get the main minetest table
3777 lua_getglobal(L, "minetest");
3779 // Add tables to minetest
3782 lua_setfield(L, -2, "object_refs");
3784 lua_setfield(L, -2, "luaentities");
3786 // Register wrappers
3787 LuaItemStack::Register(L);
3788 InvRef::Register(L);
3789 NodeMetaRef::Register(L);
3790 ObjectRef::Register(L);
3791 EnvRef::Register(L);
3794 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3795 const std::string &modname)
3797 ModNameStorer modnamestorer(L, modname);
3799 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3801 errorstream<<"Error loading mod \""<<modname
3802 <<"\": modname does not follow naming conventions: "
3803 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3807 bool success = false;
3810 success = script_load(L, scriptpath.c_str());
3813 errorstream<<"Error loading mod \""<<modname
3814 <<"\": "<<e.what()<<std::endl;
3820 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3823 assert(lua_checkstack(L, 20));
3824 verbosestream<<"scriptapi_add_environment"<<std::endl;
3825 StackUnroller stack_unroller(L);
3827 // Create EnvRef on stack
3828 EnvRef::create(L, env);
3829 int envref = lua_gettop(L);
3831 // minetest.env = envref
3832 lua_getglobal(L, "minetest");
3833 luaL_checktype(L, -1, LUA_TTABLE);
3834 lua_pushvalue(L, envref);
3835 lua_setfield(L, -2, "env");
3837 // Store environment as light userdata in registry
3838 lua_pushlightuserdata(L, env);
3839 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3842 Add ActiveBlockModifiers to environment
3845 // Get minetest.registered_abms
3846 lua_getglobal(L, "minetest");
3847 lua_getfield(L, -1, "registered_abms");
3848 luaL_checktype(L, -1, LUA_TTABLE);
3849 int registered_abms = lua_gettop(L);
3851 if(lua_istable(L, registered_abms)){
3852 int table = lua_gettop(L);
3854 while(lua_next(L, table) != 0){
3855 // key at index -2 and value at index -1
3856 int id = lua_tonumber(L, -2);
3857 int current_abm = lua_gettop(L);
3859 std::set<std::string> trigger_contents;
3860 lua_getfield(L, current_abm, "nodenames");
3861 if(lua_istable(L, -1)){
3862 int table = lua_gettop(L);
3864 while(lua_next(L, table) != 0){
3865 // key at index -2 and value at index -1
3866 luaL_checktype(L, -1, LUA_TSTRING);
3867 trigger_contents.insert(lua_tostring(L, -1));
3868 // removes value, keeps key for next iteration
3871 } else if(lua_isstring(L, -1)){
3872 trigger_contents.insert(lua_tostring(L, -1));
3876 std::set<std::string> required_neighbors;
3877 lua_getfield(L, current_abm, "neighbors");
3878 if(lua_istable(L, -1)){
3879 int table = lua_gettop(L);
3881 while(lua_next(L, table) != 0){
3882 // key at index -2 and value at index -1
3883 luaL_checktype(L, -1, LUA_TSTRING);
3884 required_neighbors.insert(lua_tostring(L, -1));
3885 // removes value, keeps key for next iteration
3888 } else if(lua_isstring(L, -1)){
3889 required_neighbors.insert(lua_tostring(L, -1));
3893 float trigger_interval = 10.0;
3894 getfloatfield(L, current_abm, "interval", trigger_interval);
3896 int trigger_chance = 50;
3897 getintfield(L, current_abm, "chance", trigger_chance);
3899 LuaABM *abm = new LuaABM(L, id, trigger_contents,
3900 required_neighbors, trigger_interval, trigger_chance);
3902 env->addActiveBlockModifier(abm);
3904 // removes value, keeps key for next iteration
3912 // Dump stack top with the dump2 function
3913 static void dump2(lua_State *L, const char *name)
3915 // Dump object (debug)
3916 lua_getglobal(L, "dump2");
3917 luaL_checktype(L, -1, LUA_TFUNCTION);
3918 lua_pushvalue(L, -2); // Get previous stack top as first parameter
3919 lua_pushstring(L, name);
3920 if(lua_pcall(L, 2, 0, 0))
3921 script_error(L, "error: %s", lua_tostring(L, -1));
3929 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
3932 assert(lua_checkstack(L, 20));
3933 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
3934 StackUnroller stack_unroller(L);
3936 // Create object on stack
3937 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
3938 int object = lua_gettop(L);
3940 // Get minetest.object_refs table
3941 lua_getglobal(L, "minetest");
3942 lua_getfield(L, -1, "object_refs");
3943 luaL_checktype(L, -1, LUA_TTABLE);
3944 int objectstable = lua_gettop(L);
3946 // object_refs[id] = object
3947 lua_pushnumber(L, cobj->getId()); // Push id
3948 lua_pushvalue(L, object); // Copy object to top of stack
3949 lua_settable(L, objectstable);
3952 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
3955 assert(lua_checkstack(L, 20));
3956 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
3957 StackUnroller stack_unroller(L);
3959 // Get minetest.object_refs table
3960 lua_getglobal(L, "minetest");
3961 lua_getfield(L, -1, "object_refs");
3962 luaL_checktype(L, -1, LUA_TTABLE);
3963 int objectstable = lua_gettop(L);
3965 // Get object_refs[id]
3966 lua_pushnumber(L, cobj->getId()); // Push id
3967 lua_gettable(L, objectstable);
3968 // Set object reference to NULL
3969 ObjectRef::set_null(L);
3970 lua_pop(L, 1); // pop object
3972 // Set object_refs[id] = nil
3973 lua_pushnumber(L, cobj->getId()); // Push id
3975 lua_settable(L, objectstable);
3978 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
3979 const std::string &message)
3982 assert(lua_checkstack(L, 20));
3983 StackUnroller stack_unroller(L);
3985 // Get minetest.registered_on_chat_messages
3986 lua_getglobal(L, "minetest");
3987 lua_getfield(L, -1, "registered_on_chat_messages");
3988 luaL_checktype(L, -1, LUA_TTABLE);
3989 int table = lua_gettop(L);
3992 while(lua_next(L, table) != 0){
3993 // key at index -2 and value at index -1
3994 luaL_checktype(L, -1, LUA_TFUNCTION);
3996 lua_pushstring(L, name.c_str());
3997 lua_pushstring(L, message.c_str());
3998 if(lua_pcall(L, 2, 1, 0))
3999 script_error(L, "error: %s", lua_tostring(L, -1));
4000 bool ate = lua_toboolean(L, -1);
4004 // value removed, keep key for next iteration
4013 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4016 assert(lua_checkstack(L, 20));
4017 StackUnroller stack_unroller(L);
4019 // Get minetest.registered_on_newplayers
4020 lua_getglobal(L, "minetest");
4021 lua_getfield(L, -1, "registered_on_newplayers");
4022 luaL_checktype(L, -1, LUA_TTABLE);
4023 int table = lua_gettop(L);
4026 while(lua_next(L, table) != 0){
4027 // key at index -2 and value at index -1
4028 luaL_checktype(L, -1, LUA_TFUNCTION);
4030 objectref_get_or_create(L, player);
4031 if(lua_pcall(L, 1, 0, 0))
4032 script_error(L, "error: %s", lua_tostring(L, -1));
4033 // value removed, keep key for next iteration
4037 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4040 assert(lua_checkstack(L, 20));
4041 StackUnroller stack_unroller(L);
4043 // Get minetest.registered_on_dieplayers
4044 lua_getglobal(L, "minetest");
4045 lua_getfield(L, -1, "registered_on_dieplayers");
4046 luaL_checktype(L, -1, LUA_TTABLE);
4047 int table = lua_gettop(L);
4050 while(lua_next(L, table) != 0){
4051 // key at index -2 and value at index -1
4052 luaL_checktype(L, -1, LUA_TFUNCTION);
4054 objectref_get_or_create(L, player);
4055 if(lua_pcall(L, 1, 0, 0))
4056 script_error(L, "error: %s", lua_tostring(L, -1));
4057 // value removed, keep key for next iteration
4062 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4065 assert(lua_checkstack(L, 20));
4066 StackUnroller stack_unroller(L);
4068 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
4070 bool positioning_handled_by_some = false;
4072 // Get minetest.registered_on_respawnplayers
4073 lua_getglobal(L, "minetest");
4074 lua_getfield(L, -1, "registered_on_respawnplayers");
4075 luaL_checktype(L, -1, LUA_TTABLE);
4076 int table = lua_gettop(L);
4079 while(lua_next(L, table) != 0){
4080 // key at index -2 and value at index -1
4081 luaL_checktype(L, -1, LUA_TFUNCTION);
4083 objectref_get_or_create(L, player);
4084 if(lua_pcall(L, 1, 1, 0))
4085 script_error(L, "error: %s", lua_tostring(L, -1));
4086 bool positioning_handled = lua_toboolean(L, -1);
4088 if(positioning_handled)
4089 positioning_handled_by_some = true;
4090 // value removed, keep key for next iteration
4092 return positioning_handled_by_some;
4095 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4097 lua_getglobal(L, "minetest");
4098 lua_getfield(L, -1, "creative_inventory");
4099 luaL_checktype(L, -1, LUA_TTABLE);
4100 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4101 PLAYER_INVENTORY_SIZE);
4105 item callbacks and node callbacks
4108 // Retrieves minetest.registered_items[name][callbackname]
4109 // If that is nil or on error, return false and stack is unchanged
4110 // If that is a function, returns true and pushes the
4111 // function onto the stack
4112 static bool get_item_callback(lua_State *L,
4113 const char *name, const char *callbackname)
4115 lua_getglobal(L, "minetest");
4116 lua_getfield(L, -1, "registered_items");
4118 luaL_checktype(L, -1, LUA_TTABLE);
4119 lua_getfield(L, -1, name);
4121 // Should be a table
4122 if(lua_type(L, -1) != LUA_TTABLE)
4124 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4128 lua_getfield(L, -1, callbackname);
4130 // Should be a function or nil
4131 if(lua_type(L, -1) == LUA_TFUNCTION)
4135 else if(lua_isnil(L, -1))
4142 errorstream<<"Item \""<<name<<"\" callback \""
4143 <<callbackname<<" is not a function"<<std::endl;
4149 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4150 ServerActiveObject *dropper, v3f pos)
4153 assert(lua_checkstack(L, 20));
4154 StackUnroller stack_unroller(L);
4156 // Push callback function on stack
4157 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4161 LuaItemStack::create(L, item);
4162 objectref_get_or_create(L, dropper);
4163 pushFloatPos(L, pos);
4164 if(lua_pcall(L, 3, 1, 0))
4165 script_error(L, "error: %s", lua_tostring(L, -1));
4166 if(!lua_isnil(L, -1))
4167 item = read_item(L, -1);
4171 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4172 ServerActiveObject *placer, const PointedThing &pointed)
4175 assert(lua_checkstack(L, 20));
4176 StackUnroller stack_unroller(L);
4178 // Push callback function on stack
4179 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4183 LuaItemStack::create(L, item);
4184 objectref_get_or_create(L, placer);
4185 push_pointed_thing(L, pointed);
4186 if(lua_pcall(L, 3, 1, 0))
4187 script_error(L, "error: %s", lua_tostring(L, -1));
4188 if(!lua_isnil(L, -1))
4189 item = read_item(L, -1);
4193 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4194 ServerActiveObject *user, const PointedThing &pointed)
4197 assert(lua_checkstack(L, 20));
4198 StackUnroller stack_unroller(L);
4200 // Push callback function on stack
4201 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4205 LuaItemStack::create(L, item);
4206 objectref_get_or_create(L, user);
4207 push_pointed_thing(L, pointed);
4208 if(lua_pcall(L, 3, 1, 0))
4209 script_error(L, "error: %s", lua_tostring(L, -1));
4210 if(!lua_isnil(L, -1))
4211 item = read_item(L, -1);
4215 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4216 ServerActiveObject *puncher)
4219 assert(lua_checkstack(L, 20));
4220 StackUnroller stack_unroller(L);
4222 INodeDefManager *ndef = get_server(L)->ndef();
4224 // Push callback function on stack
4225 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4230 pushnode(L, node, ndef);
4231 objectref_get_or_create(L, puncher);
4232 if(lua_pcall(L, 3, 0, 0))
4233 script_error(L, "error: %s", lua_tostring(L, -1));
4237 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4238 ServerActiveObject *digger)
4241 assert(lua_checkstack(L, 20));
4242 StackUnroller stack_unroller(L);
4244 INodeDefManager *ndef = get_server(L)->ndef();
4246 // Push callback function on stack
4247 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4252 pushnode(L, node, ndef);
4253 objectref_get_or_create(L, digger);
4254 if(lua_pcall(L, 3, 0, 0))
4255 script_error(L, "error: %s", lua_tostring(L, -1));
4263 void scriptapi_environment_step(lua_State *L, float dtime)
4266 assert(lua_checkstack(L, 20));
4267 //infostream<<"scriptapi_environment_step"<<std::endl;
4268 StackUnroller stack_unroller(L);
4270 // Get minetest.registered_globalsteps
4271 lua_getglobal(L, "minetest");
4272 lua_getfield(L, -1, "registered_globalsteps");
4273 luaL_checktype(L, -1, LUA_TTABLE);
4274 int table = lua_gettop(L);
4277 while(lua_next(L, table) != 0){
4278 // key at index -2 and value at index -1
4279 luaL_checktype(L, -1, LUA_TFUNCTION);
4281 lua_pushnumber(L, dtime);
4282 if(lua_pcall(L, 1, 0, 0))
4283 script_error(L, "error: %s", lua_tostring(L, -1));
4284 // value removed, keep key for next iteration
4288 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
4291 assert(lua_checkstack(L, 20));
4292 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4293 StackUnroller stack_unroller(L);
4295 // Get minetest.registered_on_generateds
4296 lua_getglobal(L, "minetest");
4297 lua_getfield(L, -1, "registered_on_generateds");
4298 luaL_checktype(L, -1, LUA_TTABLE);
4299 int table = lua_gettop(L);
4302 while(lua_next(L, table) != 0){
4303 // key at index -2 and value at index -1
4304 luaL_checktype(L, -1, LUA_TFUNCTION);
4306 push_v3s16(L, minp);
4307 push_v3s16(L, maxp);
4308 if(lua_pcall(L, 2, 0, 0))
4309 script_error(L, "error: %s", lua_tostring(L, -1));
4310 // value removed, keep key for next iteration
4318 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4321 assert(lua_checkstack(L, 20));
4322 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4323 <<name<<"\""<<std::endl;
4324 StackUnroller stack_unroller(L);
4326 // Get minetest.registered_entities[name]
4327 lua_getglobal(L, "minetest");
4328 lua_getfield(L, -1, "registered_entities");
4329 luaL_checktype(L, -1, LUA_TTABLE);
4330 lua_pushstring(L, name);
4331 lua_gettable(L, -2);
4332 // Should be a table, which we will use as a prototype
4333 //luaL_checktype(L, -1, LUA_TTABLE);
4334 if(lua_type(L, -1) != LUA_TTABLE){
4335 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4338 int prototype_table = lua_gettop(L);
4339 //dump2(L, "prototype_table");
4341 // Create entity object
4343 int object = lua_gettop(L);
4345 // Set object metatable
4346 lua_pushvalue(L, prototype_table);
4347 lua_setmetatable(L, -2);
4349 // Add object reference
4350 // This should be userdata with metatable ObjectRef
4351 objectref_get(L, id);
4352 luaL_checktype(L, -1, LUA_TUSERDATA);
4353 if(!luaL_checkudata(L, -1, "ObjectRef"))
4354 luaL_typerror(L, -1, "ObjectRef");
4355 lua_setfield(L, -2, "object");
4357 // minetest.luaentities[id] = object
4358 lua_getglobal(L, "minetest");
4359 lua_getfield(L, -1, "luaentities");
4360 luaL_checktype(L, -1, LUA_TTABLE);
4361 lua_pushnumber(L, id); // Push id
4362 lua_pushvalue(L, object); // Copy object to top of stack
4363 lua_settable(L, -3);
4368 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4369 const std::string &staticdata)
4372 assert(lua_checkstack(L, 20));
4373 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4374 StackUnroller stack_unroller(L);
4376 // Get minetest.luaentities[id]
4377 luaentity_get(L, id);
4378 int object = lua_gettop(L);
4380 // Get on_activate function
4381 lua_pushvalue(L, object);
4382 lua_getfield(L, -1, "on_activate");
4383 if(!lua_isnil(L, -1)){
4384 luaL_checktype(L, -1, LUA_TFUNCTION);
4385 lua_pushvalue(L, object); // self
4386 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4387 // Call with 2 arguments, 0 results
4388 if(lua_pcall(L, 2, 0, 0))
4389 script_error(L, "error running function on_activate: %s\n",
4390 lua_tostring(L, -1));
4394 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4397 assert(lua_checkstack(L, 20));
4398 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4400 // Get minetest.luaentities table
4401 lua_getglobal(L, "minetest");
4402 lua_getfield(L, -1, "luaentities");
4403 luaL_checktype(L, -1, LUA_TTABLE);
4404 int objectstable = lua_gettop(L);
4406 // Set luaentities[id] = nil
4407 lua_pushnumber(L, id); // Push id
4409 lua_settable(L, objectstable);
4411 lua_pop(L, 2); // pop luaentities, minetest
4414 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4417 assert(lua_checkstack(L, 20));
4418 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4419 StackUnroller stack_unroller(L);
4421 // Get minetest.luaentities[id]
4422 luaentity_get(L, id);
4423 int object = lua_gettop(L);
4425 // Get get_staticdata function
4426 lua_pushvalue(L, object);
4427 lua_getfield(L, -1, "get_staticdata");
4428 if(lua_isnil(L, -1))
4431 luaL_checktype(L, -1, LUA_TFUNCTION);
4432 lua_pushvalue(L, object); // self
4433 // Call with 1 arguments, 1 results
4434 if(lua_pcall(L, 1, 1, 0))
4435 script_error(L, "error running function get_staticdata: %s\n",
4436 lua_tostring(L, -1));
4439 const char *s = lua_tolstring(L, -1, &len);
4440 return std::string(s, len);
4443 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4444 LuaEntityProperties *prop)
4447 assert(lua_checkstack(L, 20));
4448 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4449 StackUnroller stack_unroller(L);
4451 // Get minetest.luaentities[id]
4452 luaentity_get(L, id);
4453 //int object = lua_gettop(L);
4457 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4459 getboolfield(L, -1, "physical", prop->physical);
4461 getfloatfield(L, -1, "weight", prop->weight);
4463 lua_getfield(L, -1, "collisionbox");
4464 if(lua_istable(L, -1))
4465 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4468 getstringfield(L, -1, "visual", prop->visual);
4470 lua_getfield(L, -1, "visual_size");
4471 if(lua_istable(L, -1))
4472 prop->visual_size = read_v2f(L, -1);
4475 lua_getfield(L, -1, "textures");
4476 if(lua_istable(L, -1)){
4477 prop->textures.clear();
4478 int table = lua_gettop(L);
4480 while(lua_next(L, table) != 0){
4481 // key at index -2 and value at index -1
4482 if(lua_isstring(L, -1))
4483 prop->textures.push_back(lua_tostring(L, -1));
4485 prop->textures.push_back("");
4486 // removes value, keeps key for next iteration
4492 lua_getfield(L, -1, "spritediv");
4493 if(lua_istable(L, -1))
4494 prop->spritediv = read_v2s16(L, -1);
4497 lua_getfield(L, -1, "initial_sprite_basepos");
4498 if(lua_istable(L, -1))
4499 prop->initial_sprite_basepos = read_v2s16(L, -1);
4503 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4506 assert(lua_checkstack(L, 20));
4507 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4508 StackUnroller stack_unroller(L);
4510 // Get minetest.luaentities[id]
4511 luaentity_get(L, id);
4512 int object = lua_gettop(L);
4513 // State: object is at top of stack
4514 // Get step function
4515 lua_getfield(L, -1, "on_step");
4516 if(lua_isnil(L, -1))
4518 luaL_checktype(L, -1, LUA_TFUNCTION);
4519 lua_pushvalue(L, object); // self
4520 lua_pushnumber(L, dtime); // dtime
4521 // Call with 2 arguments, 0 results
4522 if(lua_pcall(L, 2, 0, 0))
4523 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4526 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4527 // tool_capabilities, direction)
4528 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4529 ServerActiveObject *puncher, float time_from_last_punch,
4530 const ToolCapabilities *toolcap, v3f dir)
4533 assert(lua_checkstack(L, 20));
4534 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4535 StackUnroller stack_unroller(L);
4537 // Get minetest.luaentities[id]
4538 luaentity_get(L, id);
4539 int object = lua_gettop(L);
4540 // State: object is at top of stack
4542 lua_getfield(L, -1, "on_punch");
4543 if(lua_isnil(L, -1))
4545 luaL_checktype(L, -1, LUA_TFUNCTION);
4546 lua_pushvalue(L, object); // self
4547 objectref_get_or_create(L, puncher); // Clicker reference
4548 lua_pushnumber(L, time_from_last_punch);
4549 push_tool_capabilities(L, *toolcap);
4551 // Call with 5 arguments, 0 results
4552 if(lua_pcall(L, 5, 0, 0))
4553 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4556 // Calls entity:on_rightclick(ObjectRef clicker)
4557 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4558 ServerActiveObject *clicker)
4561 assert(lua_checkstack(L, 20));
4562 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4563 StackUnroller stack_unroller(L);
4565 // Get minetest.luaentities[id]
4566 luaentity_get(L, id);
4567 int object = lua_gettop(L);
4568 // State: object is at top of stack
4570 lua_getfield(L, -1, "on_rightclick");
4571 if(lua_isnil(L, -1))
4573 luaL_checktype(L, -1, LUA_TFUNCTION);
4574 lua_pushvalue(L, object); // self
4575 objectref_get_or_create(L, clicker); // Clicker reference
4576 // Call with 2 arguments, 0 results
4577 if(lua_pcall(L, 2, 0, 0))
4578 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));