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 and PlayerSAO
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"
50 #include "noise.h" // PseudoRandom for LuaPseudoRandom
52 static void stackDump(lua_State *L, std::ostream &o)
55 int top = lua_gettop(L);
56 for (i = 1; i <= top; i++) { /* repeat for each level */
57 int t = lua_type(L, i);
60 case LUA_TSTRING: /* strings */
61 o<<"\""<<lua_tostring(L, i)<<"\"";
64 case LUA_TBOOLEAN: /* booleans */
65 o<<(lua_toboolean(L, i) ? "true" : "false");
68 case LUA_TNUMBER: /* numbers */ {
70 snprintf(buf, 10, "%g", lua_tonumber(L, i));
74 default: /* other values */
75 o<<lua_typename(L, t);
84 static void realitycheck(lua_State *L)
86 int top = lua_gettop(L);
88 dstream<<"Stack is over 30:"<<std::endl;
89 stackDump(L, dstream);
90 script_error(L, "Stack is over 30 (reality check)");
100 StackUnroller(lua_State *L):
104 m_original_top = lua_gettop(m_lua); // store stack height
108 lua_settop(m_lua, m_original_top); // restore stack height
117 ModNameStorer(lua_State *L_, const std::string modname):
120 // Store current modname in registry
121 lua_pushstring(L, modname.c_str());
122 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
126 // Clear current modname in registry
128 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
133 Getters for stuff in main tables
136 static Server* get_server(lua_State *L)
138 // Get server from registry
139 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
140 Server *server = (Server*)lua_touserdata(L, -1);
145 static ServerEnvironment* get_env(lua_State *L)
147 // Get environment from registry
148 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
149 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
154 static void objectref_get(lua_State *L, u16 id)
156 // Get minetest.object_refs[i]
157 lua_getglobal(L, "minetest");
158 lua_getfield(L, -1, "object_refs");
159 luaL_checktype(L, -1, LUA_TTABLE);
160 lua_pushnumber(L, id);
162 lua_remove(L, -2); // object_refs
163 lua_remove(L, -2); // minetest
166 static void luaentity_get(lua_State *L, u16 id)
168 // Get minetest.luaentities[i]
169 lua_getglobal(L, "minetest");
170 lua_getfield(L, -1, "luaentities");
171 luaL_checktype(L, -1, LUA_TTABLE);
172 lua_pushnumber(L, id);
174 lua_remove(L, -2); // luaentities
175 lua_remove(L, -2); // minetest
182 static bool getstringfield(lua_State *L, int table,
183 const char *fieldname, std::string &result)
185 lua_getfield(L, table, fieldname);
187 if(lua_isstring(L, -1)){
189 const char *ptr = lua_tolstring(L, -1, &len);
190 result.assign(ptr, len);
197 static bool getintfield(lua_State *L, int table,
198 const char *fieldname, int &result)
200 lua_getfield(L, table, fieldname);
202 if(lua_isnumber(L, -1)){
203 result = lua_tonumber(L, -1);
210 static bool getfloatfield(lua_State *L, int table,
211 const char *fieldname, float &result)
213 lua_getfield(L, table, fieldname);
215 if(lua_isnumber(L, -1)){
216 result = lua_tonumber(L, -1);
223 static bool getboolfield(lua_State *L, int table,
224 const char *fieldname, bool &result)
226 lua_getfield(L, table, fieldname);
228 if(lua_isboolean(L, -1)){
229 result = lua_toboolean(L, -1);
236 static std::string checkstringfield(lua_State *L, int table,
237 const char *fieldname)
239 lua_getfield(L, table, fieldname);
240 std::string s = luaL_checkstring(L, -1);
245 static std::string getstringfield_default(lua_State *L, int table,
246 const char *fieldname, const std::string &default_)
248 std::string result = default_;
249 getstringfield(L, table, fieldname, result);
253 static int getintfield_default(lua_State *L, int table,
254 const char *fieldname, int default_)
256 int result = default_;
257 getintfield(L, table, fieldname, result);
261 static float getfloatfield_default(lua_State *L, int table,
262 const char *fieldname, float default_)
264 float result = default_;
265 getfloatfield(L, table, fieldname, result);
269 static bool getboolfield_default(lua_State *L, int table,
270 const char *fieldname, bool default_)
272 bool result = default_;
273 getboolfield(L, table, fieldname, result);
283 static bool string_to_enum(const EnumString *spec, int &result,
284 const std::string &str)
286 const EnumString *esp = spec;
288 if(str == std::string(esp->str)){
297 /*static bool enum_to_string(const EnumString *spec, std::string &result,
300 const EnumString *esp = spec;
311 static int getenumfield(lua_State *L, int table,
312 const char *fieldname, const EnumString *spec, int default_)
314 int result = default_;
315 string_to_enum(spec, result,
316 getstringfield_default(L, table, fieldname, ""));
320 static void setintfield(lua_State *L, int table,
321 const char *fieldname, int value)
323 lua_pushinteger(L, value);
326 lua_setfield(L, table, fieldname);
329 static void setfloatfield(lua_State *L, int table,
330 const char *fieldname, float value)
332 lua_pushnumber(L, value);
335 lua_setfield(L, table, fieldname);
338 static void setboolfield(lua_State *L, int table,
339 const char *fieldname, bool value)
341 lua_pushboolean(L, value);
344 lua_setfield(L, table, fieldname);
347 static void warn_if_field_exists(lua_State *L, int table,
348 const char *fieldname, const std::string &message)
350 lua_getfield(L, table, fieldname);
351 if(!lua_isnil(L, -1)){
352 infostream<<script_get_backtrace(L)<<std::endl;
353 infostream<<"WARNING: field \""<<fieldname<<"\": "
354 <<message<<std::endl;
360 EnumString definitions
363 struct EnumString es_ItemType[] =
367 {ITEM_CRAFT, "craft"},
372 struct EnumString es_DrawType[] =
374 {NDT_NORMAL, "normal"},
375 {NDT_AIRLIKE, "airlike"},
376 {NDT_LIQUID, "liquid"},
377 {NDT_FLOWINGLIQUID, "flowingliquid"},
378 {NDT_GLASSLIKE, "glasslike"},
379 {NDT_ALLFACES, "allfaces"},
380 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
381 {NDT_TORCHLIKE, "torchlike"},
382 {NDT_SIGNLIKE, "signlike"},
383 {NDT_PLANTLIKE, "plantlike"},
384 {NDT_FENCELIKE, "fencelike"},
385 {NDT_RAILLIKE, "raillike"},
389 struct EnumString es_ContentParamType[] =
392 {CPT_LIGHT, "light"},
396 struct EnumString es_ContentParamType2[] =
400 {CPT2_FLOWINGLIQUID, "flowingliquid"},
401 {CPT2_FACEDIR, "facedir"},
402 {CPT2_WALLMOUNTED, "wallmounted"},
406 struct EnumString es_LiquidType[] =
408 {LIQUID_NONE, "none"},
409 {LIQUID_FLOWING, "flowing"},
410 {LIQUID_SOURCE, "source"},
414 struct EnumString es_NodeBoxType[] =
416 {NODEBOX_REGULAR, "regular"},
417 {NODEBOX_FIXED, "fixed"},
418 {NODEBOX_WALLMOUNTED, "wallmounted"},
423 C struct <-> Lua table converter functions
426 static void push_v3f(lua_State *L, v3f p)
429 lua_pushnumber(L, p.X);
430 lua_setfield(L, -2, "x");
431 lua_pushnumber(L, p.Y);
432 lua_setfield(L, -2, "y");
433 lua_pushnumber(L, p.Z);
434 lua_setfield(L, -2, "z");
437 static v2s16 read_v2s16(lua_State *L, int index)
440 luaL_checktype(L, index, LUA_TTABLE);
441 lua_getfield(L, index, "x");
442 p.X = lua_tonumber(L, -1);
444 lua_getfield(L, index, "y");
445 p.Y = lua_tonumber(L, -1);
450 static v2f read_v2f(lua_State *L, int index)
453 luaL_checktype(L, index, LUA_TTABLE);
454 lua_getfield(L, index, "x");
455 p.X = lua_tonumber(L, -1);
457 lua_getfield(L, index, "y");
458 p.Y = lua_tonumber(L, -1);
463 static v3f read_v3f(lua_State *L, int index)
466 luaL_checktype(L, index, LUA_TTABLE);
467 lua_getfield(L, index, "x");
468 pos.X = lua_tonumber(L, -1);
470 lua_getfield(L, index, "y");
471 pos.Y = lua_tonumber(L, -1);
473 lua_getfield(L, index, "z");
474 pos.Z = lua_tonumber(L, -1);
479 static v3f check_v3f(lua_State *L, int index)
482 luaL_checktype(L, index, LUA_TTABLE);
483 lua_getfield(L, index, "x");
484 pos.X = luaL_checknumber(L, -1);
486 lua_getfield(L, index, "y");
487 pos.Y = luaL_checknumber(L, -1);
489 lua_getfield(L, index, "z");
490 pos.Z = luaL_checknumber(L, -1);
495 static void pushFloatPos(lua_State *L, v3f p)
501 static v3f checkFloatPos(lua_State *L, int index)
503 return check_v3f(L, index) * BS;
506 static void push_v3s16(lua_State *L, v3s16 p)
509 lua_pushnumber(L, p.X);
510 lua_setfield(L, -2, "x");
511 lua_pushnumber(L, p.Y);
512 lua_setfield(L, -2, "y");
513 lua_pushnumber(L, p.Z);
514 lua_setfield(L, -2, "z");
517 static v3s16 read_v3s16(lua_State *L, int index)
519 // Correct rounding at <0
520 v3f pf = read_v3f(L, index);
521 return floatToInt(pf, 1.0);
524 static v3s16 check_v3s16(lua_State *L, int index)
526 // Correct rounding at <0
527 v3f pf = check_v3f(L, index);
528 return floatToInt(pf, 1.0);
531 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
534 lua_pushstring(L, ndef->get(n).name.c_str());
535 lua_setfield(L, -2, "name");
536 lua_pushnumber(L, n.getParam1());
537 lua_setfield(L, -2, "param1");
538 lua_pushnumber(L, n.getParam2());
539 lua_setfield(L, -2, "param2");
542 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
544 lua_getfield(L, index, "name");
545 const char *name = luaL_checkstring(L, -1);
548 lua_getfield(L, index, "param1");
552 param1 = lua_tonumber(L, -1);
555 lua_getfield(L, index, "param2");
559 param2 = lua_tonumber(L, -1);
561 return MapNode(ndef, name, param1, param2);
564 static video::SColor readARGB8(lua_State *L, int index)
567 luaL_checktype(L, index, LUA_TTABLE);
568 lua_getfield(L, index, "a");
569 if(lua_isnumber(L, -1))
570 color.setAlpha(lua_tonumber(L, -1));
572 lua_getfield(L, index, "r");
573 color.setRed(lua_tonumber(L, -1));
575 lua_getfield(L, index, "g");
576 color.setGreen(lua_tonumber(L, -1));
578 lua_getfield(L, index, "b");
579 color.setBlue(lua_tonumber(L, -1));
584 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
586 core::aabbox3d<f32> box;
587 if(lua_istable(L, -1)){
588 lua_rawgeti(L, -1, 1);
589 box.MinEdge.X = lua_tonumber(L, -1) * scale;
591 lua_rawgeti(L, -1, 2);
592 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
594 lua_rawgeti(L, -1, 3);
595 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
597 lua_rawgeti(L, -1, 4);
598 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
600 lua_rawgeti(L, -1, 5);
601 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
603 lua_rawgeti(L, -1, 6);
604 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
615 static MaterialProperties read_material_properties(
616 lua_State *L, int table)
618 MaterialProperties prop;
619 prop.diggability = (Diggability)getenumfield(L, -1, "diggability",
620 es_Diggability, DIGGABLE_NORMAL);
621 getfloatfield(L, -1, "constant_time", prop.constant_time);
622 getfloatfield(L, -1, "weight", prop.weight);
623 getfloatfield(L, -1, "crackiness", prop.crackiness);
624 getfloatfield(L, -1, "crumbliness", prop.crumbliness);
625 getfloatfield(L, -1, "cuttability", prop.cuttability);
626 getfloatfield(L, -1, "flammability", prop.flammability);
634 static void read_groups(lua_State *L, int index,
635 std::map<std::string, int> &result)
641 while(lua_next(L, index) != 0){
642 // key at index -2 and value at index -1
643 std::string name = luaL_checkstring(L, -2);
644 int rating = luaL_checkinteger(L, -1);
645 result[name] = rating;
646 // removes value, keeps key for next iteration
655 static ToolCapabilities read_tool_capabilities(
656 lua_State *L, int table)
658 ToolCapabilities toolcap;
659 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
660 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
661 lua_getfield(L, table, "groupcaps");
662 if(lua_istable(L, -1)){
663 int table_groupcaps = lua_gettop(L);
665 while(lua_next(L, table_groupcaps) != 0){
666 // key at index -2 and value at index -1
667 std::string groupname = luaL_checkstring(L, -2);
668 if(lua_istable(L, -1)){
669 int table_groupcap = lua_gettop(L);
670 // This will be created
671 ToolGroupCap groupcap;
672 // Read simple parameters
673 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
674 getintfield(L, table_groupcap, "uses", groupcap.uses);
675 // DEPRECATED: maxwear
677 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
679 groupcap.uses = 1.0/maxwear;
682 infostream<<script_get_backtrace(L)<<std::endl;
683 infostream<<"WARNING: field \"maxwear\" is deprecated; "
684 <<"should replace with uses=1/maxwear"<<std::endl;
686 // Read "times" table
687 lua_getfield(L, table_groupcap, "times");
688 if(lua_istable(L, -1)){
689 int table_times = lua_gettop(L);
691 while(lua_next(L, table_times) != 0){
692 // key at index -2 and value at index -1
693 int rating = luaL_checkinteger(L, -2);
694 float time = luaL_checknumber(L, -1);
695 groupcap.times[rating] = time;
696 // removes value, keeps key for next iteration
701 // Insert groupcap into toolcap
702 toolcap.groupcaps[groupname] = groupcap;
704 // removes value, keeps key for next iteration
712 static void set_tool_capabilities(lua_State *L, int table,
713 const ToolCapabilities &toolcap)
715 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
716 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
717 // Create groupcaps table
720 for(std::map<std::string, ToolGroupCap>::const_iterator
721 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
722 // Create groupcap table
724 const std::string &name = i->first;
725 const ToolGroupCap &groupcap = i->second;
726 // Create subtable "times"
728 for(std::map<int, float>::const_iterator
729 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
730 int rating = i->first;
731 float time = i->second;
732 lua_pushinteger(L, rating);
733 lua_pushnumber(L, time);
736 // Set subtable "times"
737 lua_setfield(L, -2, "times");
738 // Set simple parameters
739 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
740 setintfield(L, -1, "uses", groupcap.uses);
741 // Insert groupcap table into groupcaps table
742 lua_setfield(L, -2, name.c_str());
744 // Set groupcaps table
745 lua_setfield(L, -2, "groupcaps");
748 static void push_tool_capabilities(lua_State *L,
749 const ToolCapabilities &prop)
752 set_tool_capabilities(L, -1, prop);
759 static void set_dig_params(lua_State *L, int table,
760 const DigParams ¶ms)
762 setboolfield(L, table, "diggable", params.diggable);
763 setfloatfield(L, table, "time", params.time);
764 setintfield(L, table, "wear", params.wear);
767 static void push_dig_params(lua_State *L,
768 const DigParams ¶ms)
771 set_dig_params(L, -1, params);
778 static void set_hit_params(lua_State *L, int table,
779 const HitParams ¶ms)
781 setintfield(L, table, "hp", params.hp);
782 setintfield(L, table, "wear", params.wear);
785 static void push_hit_params(lua_State *L,
786 const HitParams ¶ms)
789 set_hit_params(L, -1, params);
796 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
799 if(pointed.type == POINTEDTHING_NODE)
801 lua_pushstring(L, "node");
802 lua_setfield(L, -2, "type");
803 push_v3s16(L, pointed.node_undersurface);
804 lua_setfield(L, -2, "under");
805 push_v3s16(L, pointed.node_abovesurface);
806 lua_setfield(L, -2, "above");
808 else if(pointed.type == POINTEDTHING_OBJECT)
810 lua_pushstring(L, "object");
811 lua_setfield(L, -2, "type");
812 objectref_get(L, pointed.object_id);
813 lua_setfield(L, -2, "ref");
817 lua_pushstring(L, "nothing");
818 lua_setfield(L, -2, "type");
826 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
829 index = lua_gettop(L) + 1 + index;
830 if(lua_isnil(L, index)){
831 } else if(lua_istable(L, index)){
832 getstringfield(L, index, "name", spec.name);
833 getfloatfield(L, index, "gain", spec.gain);
834 } else if(lua_isstring(L, index)){
835 spec.name = lua_tostring(L, index);
843 static ItemDefinition read_item_definition(lua_State *L, int index)
846 index = lua_gettop(L) + 1 + index;
848 // Read the item definition
851 def.type = (ItemType)getenumfield(L, index, "type",
852 es_ItemType, ITEM_NONE);
853 getstringfield(L, index, "name", def.name);
854 getstringfield(L, index, "description", def.description);
855 getstringfield(L, index, "inventory_image", def.inventory_image);
856 getstringfield(L, index, "wield_image", def.wield_image);
858 lua_getfield(L, index, "wield_scale");
859 if(lua_istable(L, -1)){
860 def.wield_scale = check_v3f(L, -1);
864 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
865 if(def.stack_max == 0)
868 lua_getfield(L, index, "on_use");
869 def.usable = lua_isfunction(L, -1);
872 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
874 warn_if_field_exists(L, index, "tool_digging_properties",
875 "deprecated: use tool_capabilities");
877 lua_getfield(L, index, "tool_capabilities");
878 if(lua_istable(L, -1)){
879 def.tool_capabilities = new ToolCapabilities(
880 read_tool_capabilities(L, -1));
883 // If name is "" (hand), ensure there are ToolCapabilities
884 // because it will be looked up there whenever any other item has
885 // no ToolCapabilities
886 if(def.name == "" && def.tool_capabilities == NULL){
887 def.tool_capabilities = new ToolCapabilities();
890 lua_getfield(L, index, "groups");
891 read_groups(L, -1, def.groups);
901 static ContentFeatures read_content_features(lua_State *L, int index)
904 index = lua_gettop(L) + 1 + index;
908 getstringfield(L, index, "name", f.name);
911 lua_getfield(L, index, "groups");
912 read_groups(L, -1, f.groups);
915 /* Visual definition */
917 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
919 getfloatfield(L, index, "visual_scale", f.visual_scale);
921 lua_getfield(L, index, "tile_images");
922 if(lua_istable(L, -1)){
923 int table = lua_gettop(L);
926 while(lua_next(L, table) != 0){
927 // key at index -2 and value at index -1
928 if(lua_isstring(L, -1))
929 f.tname_tiles[i] = lua_tostring(L, -1);
931 f.tname_tiles[i] = "";
932 // removes value, keeps key for next iteration
940 // Copy last value to all remaining textures
942 std::string lastname = f.tname_tiles[i-1];
944 f.tname_tiles[i] = lastname;
951 lua_getfield(L, index, "special_materials");
952 if(lua_istable(L, -1)){
953 int table = lua_gettop(L);
956 while(lua_next(L, table) != 0){
957 // key at index -2 and value at index -1
958 int smtable = lua_gettop(L);
959 std::string tname = getstringfield_default(
960 L, smtable, "image", "");
961 bool backface_culling = getboolfield_default(
962 L, smtable, "backface_culling", true);
963 MaterialSpec mspec(tname, backface_culling);
964 f.mspec_special[i] = mspec;
965 // removes value, keeps key for next iteration
976 f.alpha = getintfield_default(L, index, "alpha", 255);
980 lua_getfield(L, index, "post_effect_color");
981 if(!lua_isnil(L, -1))
982 f.post_effect_color = readARGB8(L, -1);
985 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
986 es_ContentParamType, CPT_NONE);
987 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
988 es_ContentParamType2, CPT2_NONE);
990 // Warn about some deprecated fields
991 warn_if_field_exists(L, index, "wall_mounted",
992 "deprecated: use paramtype2 = 'wallmounted'");
993 warn_if_field_exists(L, index, "light_propagates",
994 "deprecated: determined from paramtype");
995 warn_if_field_exists(L, index, "dug_item",
996 "deprecated: use 'drop' field");
997 warn_if_field_exists(L, index, "extra_dug_item",
998 "deprecated: use 'drop' field");
999 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1000 "deprecated: use 'drop' field");
1002 // True for all ground-like things like stone and mud, false for eg. trees
1003 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1004 f.light_propagates = (f.param_type == CPT_LIGHT);
1005 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1006 // This is used for collision detection.
1007 // Also for general solidness queries.
1008 getboolfield(L, index, "walkable", f.walkable);
1009 // Player can point to these
1010 getboolfield(L, index, "pointable", f.pointable);
1011 // Player can dig these
1012 getboolfield(L, index, "diggable", f.diggable);
1013 // Player can climb these
1014 getboolfield(L, index, "climbable", f.climbable);
1015 // Player can build on these
1016 getboolfield(L, index, "buildable_to", f.buildable_to);
1017 // Metadata name of node (eg. "furnace")
1018 getstringfield(L, index, "metadata_name", f.metadata_name);
1019 // Whether the node is non-liquid, source liquid or flowing liquid
1020 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1021 es_LiquidType, LIQUID_NONE);
1022 // If the content is liquid, this is the flowing version of the liquid.
1023 getstringfield(L, index, "liquid_alternative_flowing",
1024 f.liquid_alternative_flowing);
1025 // If the content is liquid, this is the source version of the liquid.
1026 getstringfield(L, index, "liquid_alternative_source",
1027 f.liquid_alternative_source);
1028 // Viscosity for fluid flow, ranging from 1 to 7, with
1029 // 1 giving almost instantaneous propagation and 7 being
1030 // the slowest possible
1031 f.liquid_viscosity = getintfield_default(L, index,
1032 "liquid_viscosity", f.liquid_viscosity);
1033 // Amount of light the node emits
1034 f.light_source = getintfield_default(L, index,
1035 "light_source", f.light_source);
1036 f.damage_per_second = getintfield_default(L, index,
1037 "damage_per_second", f.damage_per_second);
1039 lua_getfield(L, index, "selection_box");
1040 if(lua_istable(L, -1)){
1041 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1042 es_NodeBoxType, NODEBOX_REGULAR);
1044 lua_getfield(L, -1, "fixed");
1045 if(lua_istable(L, -1))
1046 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1049 lua_getfield(L, -1, "wall_top");
1050 if(lua_istable(L, -1))
1051 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1054 lua_getfield(L, -1, "wall_bottom");
1055 if(lua_istable(L, -1))
1056 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1059 lua_getfield(L, -1, "wall_side");
1060 if(lua_istable(L, -1))
1061 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1066 // Set to true if paramtype used to be 'facedir_simple'
1067 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1068 // Set to true if wall_mounted used to be set to true
1069 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1072 lua_getfield(L, index, "sounds");
1073 if(lua_istable(L, -1)){
1074 lua_getfield(L, -1, "footstep");
1075 read_soundspec(L, -1, f.sound_footstep);
1077 lua_getfield(L, -1, "dig");
1078 read_soundspec(L, -1, f.sound_dig);
1080 lua_getfield(L, -1, "dug");
1081 read_soundspec(L, -1, f.sound_dug);
1093 static ItemStack read_item(lua_State *L, int index);
1095 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1096 lua_State *L, int tableindex, int forcesize=-1)
1099 tableindex = lua_gettop(L) + 1 + tableindex;
1100 // If nil, delete list
1101 if(lua_isnil(L, tableindex)){
1102 inv->deleteList(name);
1105 // Otherwise set list
1106 std::vector<ItemStack> items;
1107 luaL_checktype(L, tableindex, LUA_TTABLE);
1109 while(lua_next(L, tableindex) != 0){
1110 // key at index -2 and value at index -1
1111 items.push_back(read_item(L, -1));
1112 // removes value, keeps key for next iteration
1115 int listsize = (forcesize != -1) ? forcesize : items.size();
1116 InventoryList *invlist = inv->addList(name, listsize);
1118 for(std::vector<ItemStack>::const_iterator
1119 i = items.begin(); i != items.end(); i++){
1120 if(forcesize != -1 && index == forcesize)
1122 invlist->changeItem(index, *i);
1125 while(forcesize != -1 && index < forcesize){
1126 invlist->deleteItem(index);
1131 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1134 InventoryList *invlist = inv->getList(name);
1135 if(invlist == NULL){
1139 // Get the table insert function
1140 lua_getglobal(L, "table");
1141 lua_getfield(L, -1, "insert");
1142 int table_insert = lua_gettop(L);
1143 // Create and fill table
1145 int table = lua_gettop(L);
1146 for(u32 i=0; i<invlist->getSize(); i++){
1147 ItemStack item = invlist->getItem(i);
1148 lua_pushvalue(L, table_insert);
1149 lua_pushvalue(L, table);
1150 lua_pushstring(L, item.getItemString().c_str());
1151 if(lua_pcall(L, 2, 0, 0))
1152 script_error(L, "error: %s", lua_tostring(L, -1));
1157 Helpful macros for userdata classes
1160 #define method(class, name) {#name, class::l_##name}
1171 static const char className[];
1172 static const luaL_reg methods[];
1174 // Exported functions
1176 // garbage collector
1177 static int gc_object(lua_State *L)
1179 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1184 // is_empty(self) -> true/false
1185 static int l_is_empty(lua_State *L)
1187 LuaItemStack *o = checkobject(L, 1);
1188 ItemStack &item = o->m_stack;
1189 lua_pushboolean(L, item.empty());
1193 // get_name(self) -> string
1194 static int l_get_name(lua_State *L)
1196 LuaItemStack *o = checkobject(L, 1);
1197 ItemStack &item = o->m_stack;
1198 lua_pushstring(L, item.name.c_str());
1202 // get_count(self) -> number
1203 static int l_get_count(lua_State *L)
1205 LuaItemStack *o = checkobject(L, 1);
1206 ItemStack &item = o->m_stack;
1207 lua_pushinteger(L, item.count);
1211 // get_wear(self) -> number
1212 static int l_get_wear(lua_State *L)
1214 LuaItemStack *o = checkobject(L, 1);
1215 ItemStack &item = o->m_stack;
1216 lua_pushinteger(L, item.wear);
1220 // get_metadata(self) -> string
1221 static int l_get_metadata(lua_State *L)
1223 LuaItemStack *o = checkobject(L, 1);
1224 ItemStack &item = o->m_stack;
1225 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1229 // clear(self) -> true
1230 static int l_clear(lua_State *L)
1232 LuaItemStack *o = checkobject(L, 1);
1234 lua_pushboolean(L, true);
1238 // replace(self, itemstack or itemstring or table or nil) -> true
1239 static int l_replace(lua_State *L)
1241 LuaItemStack *o = checkobject(L, 1);
1242 o->m_stack = read_item(L, 2);
1243 lua_pushboolean(L, true);
1247 // to_string(self) -> string
1248 static int l_to_string(lua_State *L)
1250 LuaItemStack *o = checkobject(L, 1);
1251 std::string itemstring = o->m_stack.getItemString();
1252 lua_pushstring(L, itemstring.c_str());
1256 // to_table(self) -> table or nil
1257 static int l_to_table(lua_State *L)
1259 LuaItemStack *o = checkobject(L, 1);
1260 const ItemStack &item = o->m_stack;
1268 lua_pushstring(L, item.name.c_str());
1269 lua_setfield(L, -2, "name");
1270 lua_pushinteger(L, item.count);
1271 lua_setfield(L, -2, "count");
1272 lua_pushinteger(L, item.wear);
1273 lua_setfield(L, -2, "wear");
1274 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1275 lua_setfield(L, -2, "metadata");
1280 // get_stack_max(self) -> number
1281 static int l_get_stack_max(lua_State *L)
1283 LuaItemStack *o = checkobject(L, 1);
1284 ItemStack &item = o->m_stack;
1285 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1289 // get_free_space(self) -> number
1290 static int l_get_free_space(lua_State *L)
1292 LuaItemStack *o = checkobject(L, 1);
1293 ItemStack &item = o->m_stack;
1294 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1298 // is_known(self) -> true/false
1299 // Checks if the item is defined.
1300 static int l_is_known(lua_State *L)
1302 LuaItemStack *o = checkobject(L, 1);
1303 ItemStack &item = o->m_stack;
1304 bool is_known = item.isKnown(get_server(L)->idef());
1305 lua_pushboolean(L, is_known);
1309 // get_definition(self) -> table
1310 // Returns the item definition table from minetest.registered_items,
1311 // or a fallback one (name="unknown")
1312 static int l_get_definition(lua_State *L)
1314 LuaItemStack *o = checkobject(L, 1);
1315 ItemStack &item = o->m_stack;
1317 // Get minetest.registered_items[name]
1318 lua_getglobal(L, "minetest");
1319 lua_getfield(L, -1, "registered_items");
1320 luaL_checktype(L, -1, LUA_TTABLE);
1321 lua_getfield(L, -1, item.name.c_str());
1322 if(lua_isnil(L, -1))
1325 lua_getfield(L, -1, "unknown");
1330 // get_tool_capabilities(self) -> table
1331 // Returns the effective tool digging properties.
1332 // Returns those of the hand ("") if this item has none associated.
1333 static int l_get_tool_capabilities(lua_State *L)
1335 LuaItemStack *o = checkobject(L, 1);
1336 ItemStack &item = o->m_stack;
1337 const ToolCapabilities &prop =
1338 item.getToolCapabilities(get_server(L)->idef());
1339 push_tool_capabilities(L, prop);
1343 // add_wear(self, amount) -> true/false
1344 // The range for "amount" is [0,65535]. Wear is only added if the item
1345 // is a tool. Adding wear might destroy the item.
1346 // Returns true if the item is (or was) a tool.
1347 static int l_add_wear(lua_State *L)
1349 LuaItemStack *o = checkobject(L, 1);
1350 ItemStack &item = o->m_stack;
1351 int amount = lua_tointeger(L, 2);
1352 bool result = item.addWear(amount, get_server(L)->idef());
1353 lua_pushboolean(L, result);
1357 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1358 // Returns leftover item stack
1359 static int l_add_item(lua_State *L)
1361 LuaItemStack *o = checkobject(L, 1);
1362 ItemStack &item = o->m_stack;
1363 ItemStack newitem = read_item(L, 2);
1364 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1365 create(L, leftover);
1369 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1370 // First return value is true iff the new item fits fully into the stack
1371 // Second return value is the would-be-left-over item stack
1372 static int l_item_fits(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1376 ItemStack newitem = read_item(L, 2);
1378 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1379 lua_pushboolean(L, fits); // first return value
1380 create(L, restitem); // second return value
1384 // take_item(self, takecount=1) -> itemstack
1385 static int l_take_item(lua_State *L)
1387 LuaItemStack *o = checkobject(L, 1);
1388 ItemStack &item = o->m_stack;
1390 if(!lua_isnone(L, 2))
1391 takecount = lua_tointeger(L, 2);
1392 ItemStack taken = item.takeItem(takecount);
1397 // peek_item(self, peekcount=1) -> itemstack
1398 static int l_peek_item(lua_State *L)
1400 LuaItemStack *o = checkobject(L, 1);
1401 ItemStack &item = o->m_stack;
1403 if(!lua_isnone(L, 2))
1404 peekcount = lua_tointeger(L, 2);
1405 ItemStack peekaboo = item.peekItem(peekcount);
1406 create(L, peekaboo);
1411 LuaItemStack(const ItemStack &item):
1420 const ItemStack& getItem() const
1424 ItemStack& getItem()
1429 // LuaItemStack(itemstack or itemstring or table or nil)
1430 // Creates an LuaItemStack and leaves it on top of stack
1431 static int create_object(lua_State *L)
1433 ItemStack item = read_item(L, 1);
1434 LuaItemStack *o = new LuaItemStack(item);
1435 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1436 luaL_getmetatable(L, className);
1437 lua_setmetatable(L, -2);
1440 // Not callable from Lua
1441 static int create(lua_State *L, const ItemStack &item)
1443 LuaItemStack *o = new LuaItemStack(item);
1444 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1445 luaL_getmetatable(L, className);
1446 lua_setmetatable(L, -2);
1450 static LuaItemStack* checkobject(lua_State *L, int narg)
1452 luaL_checktype(L, narg, LUA_TUSERDATA);
1453 void *ud = luaL_checkudata(L, narg, className);
1454 if(!ud) luaL_typerror(L, narg, className);
1455 return *(LuaItemStack**)ud; // unbox pointer
1458 static void Register(lua_State *L)
1461 int methodtable = lua_gettop(L);
1462 luaL_newmetatable(L, className);
1463 int metatable = lua_gettop(L);
1465 lua_pushliteral(L, "__metatable");
1466 lua_pushvalue(L, methodtable);
1467 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1469 lua_pushliteral(L, "__index");
1470 lua_pushvalue(L, methodtable);
1471 lua_settable(L, metatable);
1473 lua_pushliteral(L, "__gc");
1474 lua_pushcfunction(L, gc_object);
1475 lua_settable(L, metatable);
1477 lua_pop(L, 1); // drop metatable
1479 luaL_openlib(L, 0, methods, 0); // fill methodtable
1480 lua_pop(L, 1); // drop methodtable
1482 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1483 lua_register(L, className, create_object);
1486 const char LuaItemStack::className[] = "ItemStack";
1487 const luaL_reg LuaItemStack::methods[] = {
1488 method(LuaItemStack, is_empty),
1489 method(LuaItemStack, get_name),
1490 method(LuaItemStack, get_count),
1491 method(LuaItemStack, get_wear),
1492 method(LuaItemStack, get_metadata),
1493 method(LuaItemStack, clear),
1494 method(LuaItemStack, replace),
1495 method(LuaItemStack, to_string),
1496 method(LuaItemStack, to_table),
1497 method(LuaItemStack, get_stack_max),
1498 method(LuaItemStack, get_free_space),
1499 method(LuaItemStack, is_known),
1500 method(LuaItemStack, get_definition),
1501 method(LuaItemStack, get_tool_capabilities),
1502 method(LuaItemStack, add_wear),
1503 method(LuaItemStack, add_item),
1504 method(LuaItemStack, item_fits),
1505 method(LuaItemStack, take_item),
1506 method(LuaItemStack, peek_item),
1510 static ItemStack read_item(lua_State *L, int index)
1513 index = lua_gettop(L) + 1 + index;
1515 if(lua_isnil(L, index))
1519 else if(lua_isuserdata(L, index))
1521 // Convert from LuaItemStack
1522 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1523 return o->getItem();
1525 else if(lua_isstring(L, index))
1527 // Convert from itemstring
1528 std::string itemstring = lua_tostring(L, index);
1529 IItemDefManager *idef = get_server(L)->idef();
1533 item.deSerialize(itemstring, idef);
1536 catch(SerializationError &e)
1538 infostream<<"WARNING: unable to create item from itemstring"
1539 <<": "<<itemstring<<std::endl;
1543 else if(lua_istable(L, index))
1545 // Convert from table
1546 IItemDefManager *idef = get_server(L)->idef();
1547 std::string name = getstringfield_default(L, index, "name", "");
1548 int count = getintfield_default(L, index, "count", 1);
1549 int wear = getintfield_default(L, index, "wear", 0);
1550 std::string metadata = getstringfield_default(L, index, "metadata", "");
1551 return ItemStack(name, count, wear, metadata, idef);
1555 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1566 InventoryLocation m_loc;
1568 static const char className[];
1569 static const luaL_reg methods[];
1571 static InvRef *checkobject(lua_State *L, int narg)
1573 luaL_checktype(L, narg, LUA_TUSERDATA);
1574 void *ud = luaL_checkudata(L, narg, className);
1575 if(!ud) luaL_typerror(L, narg, className);
1576 return *(InvRef**)ud; // unbox pointer
1579 static Inventory* getinv(lua_State *L, InvRef *ref)
1581 return get_server(L)->getInventory(ref->m_loc);
1584 static InventoryList* getlist(lua_State *L, InvRef *ref,
1585 const char *listname)
1587 Inventory *inv = getinv(L, ref);
1590 return inv->getList(listname);
1593 static void reportInventoryChange(lua_State *L, InvRef *ref)
1595 // Inform other things that the inventory has changed
1596 get_server(L)->setInventoryModified(ref->m_loc);
1599 // Exported functions
1601 // garbage collector
1602 static int gc_object(lua_State *L) {
1603 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1608 // get_size(self, listname)
1609 static int l_get_size(lua_State *L)
1611 InvRef *ref = checkobject(L, 1);
1612 const char *listname = luaL_checkstring(L, 2);
1613 InventoryList *list = getlist(L, ref, listname);
1615 lua_pushinteger(L, list->getSize());
1617 lua_pushinteger(L, 0);
1622 // set_size(self, listname, size)
1623 static int l_set_size(lua_State *L)
1625 InvRef *ref = checkobject(L, 1);
1626 const char *listname = luaL_checkstring(L, 2);
1627 int newsize = luaL_checknumber(L, 3);
1628 Inventory *inv = getinv(L, ref);
1630 inv->deleteList(listname);
1631 reportInventoryChange(L, ref);
1634 InventoryList *list = inv->getList(listname);
1636 list->setSize(newsize);
1638 list = inv->addList(listname, newsize);
1640 reportInventoryChange(L, ref);
1644 // get_stack(self, listname, i) -> itemstack
1645 static int l_get_stack(lua_State *L)
1647 InvRef *ref = checkobject(L, 1);
1648 const char *listname = luaL_checkstring(L, 2);
1649 int i = luaL_checknumber(L, 3) - 1;
1650 InventoryList *list = getlist(L, ref, listname);
1652 if(list != NULL && i >= 0 && i < (int) list->getSize())
1653 item = list->getItem(i);
1654 LuaItemStack::create(L, item);
1658 // set_stack(self, listname, i, stack) -> true/false
1659 static int l_set_stack(lua_State *L)
1661 InvRef *ref = checkobject(L, 1);
1662 const char *listname = luaL_checkstring(L, 2);
1663 int i = luaL_checknumber(L, 3) - 1;
1664 ItemStack newitem = read_item(L, 4);
1665 InventoryList *list = getlist(L, ref, listname);
1666 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1667 list->changeItem(i, newitem);
1668 reportInventoryChange(L, ref);
1669 lua_pushboolean(L, true);
1671 lua_pushboolean(L, false);
1676 // get_list(self, listname) -> list or nil
1677 static int l_get_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 inventory_get_list_to_lua(inv, listname, L);
1686 // set_list(self, listname, list)
1687 static int l_set_list(lua_State *L)
1689 InvRef *ref = checkobject(L, 1);
1690 const char *listname = luaL_checkstring(L, 2);
1691 Inventory *inv = getinv(L, ref);
1692 InventoryList *list = inv->getList(listname);
1694 inventory_set_list_from_lua(inv, listname, L, 3,
1697 inventory_set_list_from_lua(inv, listname, L, 3);
1698 reportInventoryChange(L, ref);
1702 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1703 // Returns the leftover stack
1704 static int l_add_item(lua_State *L)
1706 InvRef *ref = checkobject(L, 1);
1707 const char *listname = luaL_checkstring(L, 2);
1708 ItemStack item = read_item(L, 3);
1709 InventoryList *list = getlist(L, ref, listname);
1711 ItemStack leftover = list->addItem(item);
1712 if(leftover.count != item.count)
1713 reportInventoryChange(L, ref);
1714 LuaItemStack::create(L, leftover);
1716 LuaItemStack::create(L, item);
1721 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1722 // Returns true if the item completely fits into the list
1723 static int l_room_for_item(lua_State *L)
1725 InvRef *ref = checkobject(L, 1);
1726 const char *listname = luaL_checkstring(L, 2);
1727 ItemStack item = read_item(L, 3);
1728 InventoryList *list = getlist(L, ref, listname);
1730 lua_pushboolean(L, list->roomForItem(item));
1732 lua_pushboolean(L, false);
1737 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1738 // Returns true if the list contains the given count of the given item name
1739 static int l_contains_item(lua_State *L)
1741 InvRef *ref = checkobject(L, 1);
1742 const char *listname = luaL_checkstring(L, 2);
1743 ItemStack item = read_item(L, 3);
1744 InventoryList *list = getlist(L, ref, listname);
1746 lua_pushboolean(L, list->containsItem(item));
1748 lua_pushboolean(L, false);
1753 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1754 // Returns the items that were actually removed
1755 static int l_remove_item(lua_State *L)
1757 InvRef *ref = checkobject(L, 1);
1758 const char *listname = luaL_checkstring(L, 2);
1759 ItemStack item = read_item(L, 3);
1760 InventoryList *list = getlist(L, ref, listname);
1762 ItemStack removed = list->removeItem(item);
1763 if(!removed.empty())
1764 reportInventoryChange(L, ref);
1765 LuaItemStack::create(L, removed);
1767 LuaItemStack::create(L, ItemStack());
1773 InvRef(const InventoryLocation &loc):
1782 // Creates an InvRef and leaves it on top of stack
1783 // Not callable from Lua; all references are created on the C side.
1784 static void create(lua_State *L, const InventoryLocation &loc)
1786 InvRef *o = new InvRef(loc);
1787 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1788 luaL_getmetatable(L, className);
1789 lua_setmetatable(L, -2);
1791 static void createPlayer(lua_State *L, Player *player)
1793 InventoryLocation loc;
1794 loc.setPlayer(player->getName());
1797 static void createNodeMeta(lua_State *L, v3s16 p)
1799 InventoryLocation loc;
1804 static void Register(lua_State *L)
1807 int methodtable = lua_gettop(L);
1808 luaL_newmetatable(L, className);
1809 int metatable = lua_gettop(L);
1811 lua_pushliteral(L, "__metatable");
1812 lua_pushvalue(L, methodtable);
1813 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1815 lua_pushliteral(L, "__index");
1816 lua_pushvalue(L, methodtable);
1817 lua_settable(L, metatable);
1819 lua_pushliteral(L, "__gc");
1820 lua_pushcfunction(L, gc_object);
1821 lua_settable(L, metatable);
1823 lua_pop(L, 1); // drop metatable
1825 luaL_openlib(L, 0, methods, 0); // fill methodtable
1826 lua_pop(L, 1); // drop methodtable
1828 // Cannot be created from Lua
1829 //lua_register(L, className, create_object);
1832 const char InvRef::className[] = "InvRef";
1833 const luaL_reg InvRef::methods[] = {
1834 method(InvRef, get_size),
1835 method(InvRef, set_size),
1836 method(InvRef, get_stack),
1837 method(InvRef, set_stack),
1838 method(InvRef, get_list),
1839 method(InvRef, set_list),
1840 method(InvRef, add_item),
1841 method(InvRef, room_for_item),
1842 method(InvRef, contains_item),
1843 method(InvRef, remove_item),
1855 ServerEnvironment *m_env;
1857 static const char className[];
1858 static const luaL_reg methods[];
1860 static NodeMetaRef *checkobject(lua_State *L, int narg)
1862 luaL_checktype(L, narg, LUA_TUSERDATA);
1863 void *ud = luaL_checkudata(L, narg, className);
1864 if(!ud) luaL_typerror(L, narg, className);
1865 return *(NodeMetaRef**)ud; // unbox pointer
1868 static NodeMetadata* getmeta(NodeMetaRef *ref)
1870 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1874 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1876 NodeMetadata *meta = getmeta(ref);
1879 if(meta->typeId() != NODEMETA_GENERIC)
1881 return (IGenericNodeMetadata*)meta;
1884 static void reportMetadataChange(NodeMetaRef *ref)
1886 // Inform other things that the metadata has changed
1887 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1889 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1891 ref->m_env->getMap().dispatchEvent(&event);
1892 // Set the block to be saved
1893 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1895 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1896 "NodeMetaRef::reportMetadataChange");
1899 // Exported functions
1901 // garbage collector
1902 static int gc_object(lua_State *L) {
1903 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1909 static int l_get_type(lua_State *L)
1911 NodeMetaRef *ref = checkobject(L, 1);
1912 NodeMetadata *meta = getmeta(ref);
1918 lua_pushstring(L, meta->typeName());
1922 // allows_text_input(self)
1923 static int l_allows_text_input(lua_State *L)
1925 NodeMetaRef *ref = checkobject(L, 1);
1926 NodeMetadata *meta = getmeta(ref);
1927 if(meta == NULL) return 0;
1929 lua_pushboolean(L, meta->allowsTextInput());
1933 // set_text(self, text)
1934 static int l_set_text(lua_State *L)
1936 NodeMetaRef *ref = checkobject(L, 1);
1937 NodeMetadata *meta = getmeta(ref);
1938 if(meta == NULL) return 0;
1940 std::string text = luaL_checkstring(L, 2);
1941 meta->setText(text);
1942 reportMetadataChange(ref);
1947 static int l_get_text(lua_State *L)
1949 NodeMetaRef *ref = checkobject(L, 1);
1950 NodeMetadata *meta = getmeta(ref);
1951 if(meta == NULL) return 0;
1953 std::string text = meta->getText();
1954 lua_pushstring(L, text.c_str());
1959 static int l_get_owner(lua_State *L)
1961 NodeMetaRef *ref = checkobject(L, 1);
1962 NodeMetadata *meta = getmeta(ref);
1963 if(meta == NULL) return 0;
1965 std::string owner = meta->getOwner();
1966 lua_pushstring(L, owner.c_str());
1970 // set_owner(self, string)
1971 static int l_set_owner(lua_State *L)
1973 NodeMetaRef *ref = checkobject(L, 1);
1974 NodeMetadata *meta = getmeta(ref);
1975 if(meta == NULL) return 0;
1977 std::string owner = luaL_checkstring(L, 2);
1978 meta->setOwner(owner);
1979 reportMetadataChange(ref);
1983 // get_allow_removal(self)
1984 static int l_get_allow_removal(lua_State *L)
1986 NodeMetaRef *ref = checkobject(L, 1);
1987 NodeMetadata *meta = getmeta(ref);
1989 lua_pushboolean(L, true);
1993 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1997 /* IGenericNodeMetadata interface */
1999 // set_infotext(self, text)
2000 static int l_set_infotext(lua_State *L)
2002 NodeMetaRef *ref = checkobject(L, 1);
2003 NodeMetadata *meta = getmeta(ref);
2004 if(meta == NULL) return 0;
2006 std::string text = luaL_checkstring(L, 2);
2007 meta->setInfoText(text);
2008 reportMetadataChange(ref);
2012 // get_inventory(self)
2013 static int l_get_inventory(lua_State *L)
2015 NodeMetaRef *ref = checkobject(L, 1);
2016 NodeMetadata *meta = getmeta(ref);
2017 if(meta == NULL) return 0;
2019 InvRef::createNodeMeta(L, ref->m_p);
2023 // set_inventory_draw_spec(self, text)
2024 static int l_set_inventory_draw_spec(lua_State *L)
2026 NodeMetaRef *ref = checkobject(L, 1);
2027 NodeMetadata *meta = getmeta(ref);
2028 if(meta == NULL) return 0;
2030 std::string text = luaL_checkstring(L, 2);
2031 meta->setInventoryDrawSpec(text);
2032 reportMetadataChange(ref);
2036 // set_allow_text_input(self, text)
2037 static int l_set_allow_text_input(lua_State *L)
2039 NodeMetaRef *ref = checkobject(L, 1);
2040 NodeMetadata *meta = getmeta(ref);
2041 if(meta == NULL) return 0;
2043 bool b = lua_toboolean(L, 2);
2044 meta->setAllowTextInput(b);
2045 reportMetadataChange(ref);
2049 // set_allow_removal(self, text)
2050 static int l_set_allow_removal(lua_State *L)
2052 NodeMetaRef *ref = checkobject(L, 1);
2053 NodeMetadata *meta = getmeta(ref);
2054 if(meta == NULL) return 0;
2056 bool b = lua_toboolean(L, 2);
2057 meta->setRemovalDisabled(!b);
2058 reportMetadataChange(ref);
2062 // set_enforce_owner(self, text)
2063 static int l_set_enforce_owner(lua_State *L)
2065 NodeMetaRef *ref = checkobject(L, 1);
2066 NodeMetadata *meta = getmeta(ref);
2067 if(meta == NULL) return 0;
2069 bool b = lua_toboolean(L, 2);
2070 meta->setEnforceOwner(b);
2071 reportMetadataChange(ref);
2075 // is_inventory_modified(self)
2076 static int l_is_inventory_modified(lua_State *L)
2078 NodeMetaRef *ref = checkobject(L, 1);
2079 NodeMetadata *meta = getmeta(ref);
2080 if(meta == NULL) return 0;
2082 lua_pushboolean(L, meta->isInventoryModified());
2086 // reset_inventory_modified(self)
2087 static int l_reset_inventory_modified(lua_State *L)
2089 NodeMetaRef *ref = checkobject(L, 1);
2090 NodeMetadata *meta = getmeta(ref);
2091 if(meta == NULL) return 0;
2093 meta->resetInventoryModified();
2094 reportMetadataChange(ref);
2098 // is_text_modified(self)
2099 static int l_is_text_modified(lua_State *L)
2101 NodeMetaRef *ref = checkobject(L, 1);
2102 NodeMetadata *meta = getmeta(ref);
2103 if(meta == NULL) return 0;
2105 lua_pushboolean(L, meta->isTextModified());
2109 // reset_text_modified(self)
2110 static int l_reset_text_modified(lua_State *L)
2112 NodeMetaRef *ref = checkobject(L, 1);
2113 NodeMetadata *meta = getmeta(ref);
2114 if(meta == NULL) return 0;
2116 meta->resetTextModified();
2117 reportMetadataChange(ref);
2121 // set_string(self, name, var)
2122 static int l_set_string(lua_State *L)
2124 NodeMetaRef *ref = checkobject(L, 1);
2125 NodeMetadata *meta = getmeta(ref);
2126 if(meta == NULL) return 0;
2128 std::string name = luaL_checkstring(L, 2);
2130 const char *s = lua_tolstring(L, 3, &len);
2131 std::string str(s, len);
2132 meta->setString(name, str);
2133 reportMetadataChange(ref);
2137 // get_string(self, name)
2138 static int l_get_string(lua_State *L)
2140 NodeMetaRef *ref = checkobject(L, 1);
2141 NodeMetadata *meta = getmeta(ref);
2142 if(meta == NULL) return 0;
2144 std::string name = luaL_checkstring(L, 2);
2145 std::string str = meta->getString(name);
2146 lua_pushlstring(L, str.c_str(), str.size());
2151 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2161 // Creates an NodeMetaRef and leaves it on top of stack
2162 // Not callable from Lua; all references are created on the C side.
2163 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2165 NodeMetaRef *o = new NodeMetaRef(p, env);
2166 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2167 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2168 luaL_getmetatable(L, className);
2169 lua_setmetatable(L, -2);
2172 static void Register(lua_State *L)
2175 int methodtable = lua_gettop(L);
2176 luaL_newmetatable(L, className);
2177 int metatable = lua_gettop(L);
2179 lua_pushliteral(L, "__metatable");
2180 lua_pushvalue(L, methodtable);
2181 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2183 lua_pushliteral(L, "__index");
2184 lua_pushvalue(L, methodtable);
2185 lua_settable(L, metatable);
2187 lua_pushliteral(L, "__gc");
2188 lua_pushcfunction(L, gc_object);
2189 lua_settable(L, metatable);
2191 lua_pop(L, 1); // drop metatable
2193 luaL_openlib(L, 0, methods, 0); // fill methodtable
2194 lua_pop(L, 1); // drop methodtable
2196 // Cannot be created from Lua
2197 //lua_register(L, className, create_object);
2200 const char NodeMetaRef::className[] = "NodeMetaRef";
2201 const luaL_reg NodeMetaRef::methods[] = {
2202 method(NodeMetaRef, get_type),
2203 method(NodeMetaRef, allows_text_input),
2204 method(NodeMetaRef, set_text),
2205 method(NodeMetaRef, get_text),
2206 method(NodeMetaRef, get_owner),
2207 method(NodeMetaRef, set_owner),
2208 method(NodeMetaRef, get_allow_removal),
2209 method(NodeMetaRef, set_infotext),
2210 method(NodeMetaRef, get_inventory),
2211 method(NodeMetaRef, set_inventory_draw_spec),
2212 method(NodeMetaRef, set_allow_text_input),
2213 method(NodeMetaRef, set_allow_removal),
2214 method(NodeMetaRef, set_enforce_owner),
2215 method(NodeMetaRef, is_inventory_modified),
2216 method(NodeMetaRef, reset_inventory_modified),
2217 method(NodeMetaRef, is_text_modified),
2218 method(NodeMetaRef, reset_text_modified),
2219 method(NodeMetaRef, set_string),
2220 method(NodeMetaRef, get_string),
2231 ServerActiveObject *m_object;
2233 static const char className[];
2234 static const luaL_reg methods[];
2236 static ObjectRef *checkobject(lua_State *L, int narg)
2238 luaL_checktype(L, narg, LUA_TUSERDATA);
2239 void *ud = luaL_checkudata(L, narg, className);
2240 if(!ud) luaL_typerror(L, narg, className);
2241 return *(ObjectRef**)ud; // unbox pointer
2244 static ServerActiveObject* getobject(ObjectRef *ref)
2246 ServerActiveObject *co = ref->m_object;
2250 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2252 ServerActiveObject *obj = getobject(ref);
2255 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2257 return (LuaEntitySAO*)obj;
2260 static PlayerSAO* getplayersao(ObjectRef *ref)
2262 ServerActiveObject *obj = getobject(ref);
2265 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2267 return (PlayerSAO*)obj;
2270 static Player* getplayer(ObjectRef *ref)
2272 PlayerSAO *playersao = getplayersao(ref);
2273 if(playersao == NULL)
2275 return playersao->getPlayer();
2278 // Exported functions
2280 // garbage collector
2281 static int gc_object(lua_State *L) {
2282 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2283 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2289 static int l_remove(lua_State *L)
2291 ObjectRef *ref = checkobject(L, 1);
2292 ServerActiveObject *co = getobject(ref);
2293 if(co == NULL) return 0;
2294 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2295 co->m_removed = true;
2300 // returns: {x=num, y=num, z=num}
2301 static int l_getpos(lua_State *L)
2303 ObjectRef *ref = checkobject(L, 1);
2304 ServerActiveObject *co = getobject(ref);
2305 if(co == NULL) return 0;
2306 v3f pos = co->getBasePosition() / BS;
2308 lua_pushnumber(L, pos.X);
2309 lua_setfield(L, -2, "x");
2310 lua_pushnumber(L, pos.Y);
2311 lua_setfield(L, -2, "y");
2312 lua_pushnumber(L, pos.Z);
2313 lua_setfield(L, -2, "z");
2317 // setpos(self, pos)
2318 static int l_setpos(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);
2331 // moveto(self, pos, continuous=false)
2332 static int l_moveto(lua_State *L)
2334 ObjectRef *ref = checkobject(L, 1);
2335 //LuaEntitySAO *co = getluaobject(ref);
2336 ServerActiveObject *co = getobject(ref);
2337 if(co == NULL) return 0;
2339 v3f pos = checkFloatPos(L, 2);
2341 bool continuous = lua_toboolean(L, 3);
2343 co->moveTo(pos, continuous);
2347 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2348 static int l_punch(lua_State *L)
2350 ObjectRef *ref = checkobject(L, 1);
2351 ObjectRef *puncher_ref = checkobject(L, 2);
2352 ServerActiveObject *co = getobject(ref);
2353 ServerActiveObject *puncher = getobject(puncher_ref);
2354 if(co == NULL) return 0;
2355 if(puncher == NULL) return 0;
2356 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2357 v3f dir = read_v3f(L, 4);
2358 float time_from_last_punch = 1000000;
2359 if(lua_isnumber(L, 5))
2360 time_from_last_punch = lua_tonumber(L, 5);
2362 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2366 // right_click(self, clicker); clicker = an another ObjectRef
2367 static int l_right_click(lua_State *L)
2369 ObjectRef *ref = checkobject(L, 1);
2370 ObjectRef *ref2 = checkobject(L, 2);
2371 ServerActiveObject *co = getobject(ref);
2372 ServerActiveObject *co2 = getobject(ref2);
2373 if(co == NULL) return 0;
2374 if(co2 == NULL) return 0;
2376 co->rightClick(co2);
2381 // hp = number of hitpoints (2 * number of hearts)
2383 static int l_set_hp(lua_State *L)
2385 ObjectRef *ref = checkobject(L, 1);
2386 luaL_checknumber(L, 2);
2387 ServerActiveObject *co = getobject(ref);
2388 if(co == NULL) return 0;
2389 int hp = lua_tonumber(L, 2);
2390 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2391 <<" hp="<<hp<<std::endl;*/
2399 // returns: number of hitpoints (2 * number of hearts)
2400 // 0 if not applicable to this type of object
2401 static int l_get_hp(lua_State *L)
2403 ObjectRef *ref = checkobject(L, 1);
2404 ServerActiveObject *co = getobject(ref);
2405 if(co == NULL) return 0;
2406 int hp = co->getHP();
2407 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2408 <<" hp="<<hp<<std::endl;*/
2410 lua_pushnumber(L, hp);
2414 // get_inventory(self)
2415 static int l_get_inventory(lua_State *L)
2417 ObjectRef *ref = checkobject(L, 1);
2418 ServerActiveObject *co = getobject(ref);
2419 if(co == NULL) return 0;
2421 InventoryLocation loc = co->getInventoryLocation();
2422 if(get_server(L)->getInventory(loc) != NULL)
2423 InvRef::create(L, loc);
2429 // get_wield_list(self)
2430 static int l_get_wield_list(lua_State *L)
2432 ObjectRef *ref = checkobject(L, 1);
2433 ServerActiveObject *co = getobject(ref);
2434 if(co == NULL) return 0;
2436 lua_pushstring(L, co->getWieldList().c_str());
2440 // get_wield_index(self)
2441 static int l_get_wield_index(lua_State *L)
2443 ObjectRef *ref = checkobject(L, 1);
2444 ServerActiveObject *co = getobject(ref);
2445 if(co == NULL) return 0;
2447 lua_pushinteger(L, co->getWieldIndex() + 1);
2451 // get_wielded_item(self)
2452 static int l_get_wielded_item(lua_State *L)
2454 ObjectRef *ref = checkobject(L, 1);
2455 ServerActiveObject *co = getobject(ref);
2456 if(co == NULL) return 0;
2458 LuaItemStack::create(L, co->getWieldedItem());
2462 // set_wielded_item(self, itemstack or itemstring or table or nil)
2463 static int l_set_wielded_item(lua_State *L)
2465 ObjectRef *ref = checkobject(L, 1);
2466 ServerActiveObject *co = getobject(ref);
2467 if(co == NULL) return 0;
2469 ItemStack item = read_item(L, 2);
2470 bool success = co->setWieldedItem(item);
2471 lua_pushboolean(L, success);
2475 /* LuaEntitySAO-only */
2477 // setvelocity(self, {x=num, y=num, z=num})
2478 static int l_setvelocity(lua_State *L)
2480 ObjectRef *ref = checkobject(L, 1);
2481 LuaEntitySAO *co = getluaobject(ref);
2482 if(co == NULL) return 0;
2484 v3f pos = checkFloatPos(L, 2);
2486 co->setVelocity(pos);
2490 // getvelocity(self)
2491 static int l_getvelocity(lua_State *L)
2493 ObjectRef *ref = checkobject(L, 1);
2494 LuaEntitySAO *co = getluaobject(ref);
2495 if(co == NULL) return 0;
2497 v3f v = co->getVelocity();
2502 // setacceleration(self, {x=num, y=num, z=num})
2503 static int l_setacceleration(lua_State *L)
2505 ObjectRef *ref = checkobject(L, 1);
2506 LuaEntitySAO *co = getluaobject(ref);
2507 if(co == NULL) return 0;
2509 v3f pos = checkFloatPos(L, 2);
2511 co->setAcceleration(pos);
2515 // getacceleration(self)
2516 static int l_getacceleration(lua_State *L)
2518 ObjectRef *ref = checkobject(L, 1);
2519 LuaEntitySAO *co = getluaobject(ref);
2520 if(co == NULL) return 0;
2522 v3f v = co->getAcceleration();
2527 // setyaw(self, radians)
2528 static int l_setyaw(lua_State *L)
2530 ObjectRef *ref = checkobject(L, 1);
2531 LuaEntitySAO *co = getluaobject(ref);
2532 if(co == NULL) return 0;
2534 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2541 static int l_getyaw(lua_State *L)
2543 ObjectRef *ref = checkobject(L, 1);
2544 LuaEntitySAO *co = getluaobject(ref);
2545 if(co == NULL) return 0;
2547 float yaw = co->getYaw() * core::DEGTORAD;
2548 lua_pushnumber(L, yaw);
2552 // settexturemod(self, mod)
2553 static int l_settexturemod(lua_State *L)
2555 ObjectRef *ref = checkobject(L, 1);
2556 LuaEntitySAO *co = getluaobject(ref);
2557 if(co == NULL) return 0;
2559 std::string mod = luaL_checkstring(L, 2);
2560 co->setTextureMod(mod);
2564 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2565 // select_horiz_by_yawpitch=false)
2566 static int l_setsprite(lua_State *L)
2568 ObjectRef *ref = checkobject(L, 1);
2569 LuaEntitySAO *co = getluaobject(ref);
2570 if(co == NULL) return 0;
2573 if(!lua_isnil(L, 2))
2574 p = read_v2s16(L, 2);
2576 if(!lua_isnil(L, 3))
2577 num_frames = lua_tonumber(L, 3);
2578 float framelength = 0.2;
2579 if(!lua_isnil(L, 4))
2580 framelength = lua_tonumber(L, 4);
2581 bool select_horiz_by_yawpitch = false;
2582 if(!lua_isnil(L, 5))
2583 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2584 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2588 // set_armor_groups(self, groups)
2589 static int l_set_armor_groups(lua_State *L)
2591 ObjectRef *ref = checkobject(L, 1);
2592 LuaEntitySAO *co = getluaobject(ref);
2593 if(co == NULL) return 0;
2595 ItemGroupList groups;
2596 read_groups(L, 2, groups);
2597 co->setArmorGroups(groups);
2602 // get_entity_name(self)
2603 static int l_get_entity_name(lua_State *L)
2605 ObjectRef *ref = checkobject(L, 1);
2606 LuaEntitySAO *co = getluaobject(ref);
2607 if(co == NULL) return 0;
2609 std::string name = co->getName();
2610 lua_pushstring(L, name.c_str());
2614 // get_luaentity(self)
2615 static int l_get_luaentity(lua_State *L)
2617 ObjectRef *ref = checkobject(L, 1);
2618 LuaEntitySAO *co = getluaobject(ref);
2619 if(co == NULL) return 0;
2621 luaentity_get(L, co->getId());
2627 // get_player_name(self)
2628 static int l_get_player_name(lua_State *L)
2630 ObjectRef *ref = checkobject(L, 1);
2631 Player *player = getplayer(ref);
2637 lua_pushstring(L, player->getName());
2641 // get_look_dir(self)
2642 static int l_get_look_dir(lua_State *L)
2644 ObjectRef *ref = checkobject(L, 1);
2645 Player *player = getplayer(ref);
2646 if(player == NULL) return 0;
2648 float pitch = player->getRadPitch();
2649 float yaw = player->getRadYaw();
2650 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2655 // get_look_pitch(self)
2656 static int l_get_look_pitch(lua_State *L)
2658 ObjectRef *ref = checkobject(L, 1);
2659 Player *player = getplayer(ref);
2660 if(player == NULL) return 0;
2662 lua_pushnumber(L, player->getRadPitch());
2666 // get_look_yaw(self)
2667 static int l_get_look_yaw(lua_State *L)
2669 ObjectRef *ref = checkobject(L, 1);
2670 Player *player = getplayer(ref);
2671 if(player == NULL) return 0;
2673 lua_pushnumber(L, player->getRadYaw());
2678 ObjectRef(ServerActiveObject *object):
2681 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2687 infostream<<"ObjectRef destructing for id="
2688 <<m_object->getId()<<std::endl;
2690 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2693 // Creates an ObjectRef and leaves it on top of stack
2694 // Not callable from Lua; all references are created on the C side.
2695 static void create(lua_State *L, ServerActiveObject *object)
2697 ObjectRef *o = new ObjectRef(object);
2698 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2699 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2700 luaL_getmetatable(L, className);
2701 lua_setmetatable(L, -2);
2704 static void set_null(lua_State *L)
2706 ObjectRef *o = checkobject(L, -1);
2710 static void Register(lua_State *L)
2713 int methodtable = lua_gettop(L);
2714 luaL_newmetatable(L, className);
2715 int metatable = lua_gettop(L);
2717 lua_pushliteral(L, "__metatable");
2718 lua_pushvalue(L, methodtable);
2719 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2721 lua_pushliteral(L, "__index");
2722 lua_pushvalue(L, methodtable);
2723 lua_settable(L, metatable);
2725 lua_pushliteral(L, "__gc");
2726 lua_pushcfunction(L, gc_object);
2727 lua_settable(L, metatable);
2729 lua_pop(L, 1); // drop metatable
2731 luaL_openlib(L, 0, methods, 0); // fill methodtable
2732 lua_pop(L, 1); // drop methodtable
2734 // Cannot be created from Lua
2735 //lua_register(L, className, create_object);
2738 const char ObjectRef::className[] = "ObjectRef";
2739 const luaL_reg ObjectRef::methods[] = {
2740 // ServerActiveObject
2741 method(ObjectRef, remove),
2742 method(ObjectRef, getpos),
2743 method(ObjectRef, setpos),
2744 method(ObjectRef, moveto),
2745 method(ObjectRef, punch),
2746 method(ObjectRef, right_click),
2747 method(ObjectRef, set_hp),
2748 method(ObjectRef, get_hp),
2749 method(ObjectRef, get_inventory),
2750 method(ObjectRef, get_wield_list),
2751 method(ObjectRef, get_wield_index),
2752 method(ObjectRef, get_wielded_item),
2753 method(ObjectRef, set_wielded_item),
2754 // LuaEntitySAO-only
2755 method(ObjectRef, setvelocity),
2756 method(ObjectRef, getvelocity),
2757 method(ObjectRef, setacceleration),
2758 method(ObjectRef, getacceleration),
2759 method(ObjectRef, setyaw),
2760 method(ObjectRef, getyaw),
2761 method(ObjectRef, settexturemod),
2762 method(ObjectRef, setsprite),
2763 method(ObjectRef, set_armor_groups),
2764 method(ObjectRef, get_entity_name),
2765 method(ObjectRef, get_luaentity),
2767 method(ObjectRef, get_player_name),
2768 method(ObjectRef, get_look_dir),
2769 method(ObjectRef, get_look_pitch),
2770 method(ObjectRef, get_look_yaw),
2774 // Creates a new anonymous reference if id=0
2775 static void objectref_get_or_create(lua_State *L,
2776 ServerActiveObject *cobj)
2778 if(cobj->getId() == 0){
2779 ObjectRef::create(L, cobj);
2781 objectref_get(L, cobj->getId());
2792 ServerEnvironment *m_env;
2794 static const char className[];
2795 static const luaL_reg methods[];
2797 static EnvRef *checkobject(lua_State *L, int narg)
2799 luaL_checktype(L, narg, LUA_TUSERDATA);
2800 void *ud = luaL_checkudata(L, narg, className);
2801 if(!ud) luaL_typerror(L, narg, className);
2802 return *(EnvRef**)ud; // unbox pointer
2805 // Exported functions
2807 // EnvRef:set_node(pos, node)
2808 // pos = {x=num, y=num, z=num}
2809 static int l_set_node(lua_State *L)
2811 //infostream<<"EnvRef::l_set_node()"<<std::endl;
2812 EnvRef *o = checkobject(L, 1);
2813 ServerEnvironment *env = o->m_env;
2814 if(env == NULL) return 0;
2816 v3s16 pos = read_v3s16(L, 2);
2818 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2820 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2821 lua_pushboolean(L, succeeded);
2825 static int l_add_node(lua_State *L)
2827 return l_set_node(L);
2830 // EnvRef:remove_node(pos)
2831 // pos = {x=num, y=num, z=num}
2832 static int l_remove_node(lua_State *L)
2834 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2835 EnvRef *o = checkobject(L, 1);
2836 ServerEnvironment *env = o->m_env;
2837 if(env == NULL) return 0;
2839 v3s16 pos = read_v3s16(L, 2);
2841 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2842 lua_pushboolean(L, succeeded);
2846 // EnvRef:get_node(pos)
2847 // pos = {x=num, y=num, z=num}
2848 static int l_get_node(lua_State *L)
2850 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2851 EnvRef *o = checkobject(L, 1);
2852 ServerEnvironment *env = o->m_env;
2853 if(env == NULL) return 0;
2855 v3s16 pos = read_v3s16(L, 2);
2857 MapNode n = env->getMap().getNodeNoEx(pos);
2859 pushnode(L, n, env->getGameDef()->ndef());
2863 // EnvRef:get_node_or_nil(pos)
2864 // pos = {x=num, y=num, z=num}
2865 static int l_get_node_or_nil(lua_State *L)
2867 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2868 EnvRef *o = checkobject(L, 1);
2869 ServerEnvironment *env = o->m_env;
2870 if(env == NULL) return 0;
2872 v3s16 pos = read_v3s16(L, 2);
2875 MapNode n = env->getMap().getNode(pos);
2877 pushnode(L, n, env->getGameDef()->ndef());
2879 } catch(InvalidPositionException &e)
2886 // EnvRef:get_node_light(pos, timeofday)
2887 // pos = {x=num, y=num, z=num}
2888 // timeofday: nil = current time, 0 = night, 0.5 = day
2889 static int l_get_node_light(lua_State *L)
2891 EnvRef *o = checkobject(L, 1);
2892 ServerEnvironment *env = o->m_env;
2893 if(env == NULL) return 0;
2895 v3s16 pos = read_v3s16(L, 2);
2896 u32 time_of_day = env->getTimeOfDay();
2897 if(lua_isnumber(L, 3))
2898 time_of_day = 24000.0 * lua_tonumber(L, 3);
2899 time_of_day %= 24000;
2900 u32 dnr = time_to_daynight_ratio(time_of_day);
2901 MapNode n = env->getMap().getNodeNoEx(pos);
2903 MapNode n = env->getMap().getNode(pos);
2904 INodeDefManager *ndef = env->getGameDef()->ndef();
2905 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2907 } catch(InvalidPositionException &e)
2914 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2915 // pos = {x=num, y=num, z=num}
2916 static int l_add_entity(lua_State *L)
2918 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2919 EnvRef *o = checkobject(L, 1);
2920 ServerEnvironment *env = o->m_env;
2921 if(env == NULL) return 0;
2923 v3f pos = checkFloatPos(L, 2);
2925 const char *name = luaL_checkstring(L, 3);
2927 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2928 int objectid = env->addActiveObject(obj);
2929 // If failed to add, return nothing (reads as nil)
2933 objectref_get_or_create(L, obj);
2937 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2938 // pos = {x=num, y=num, z=num}
2939 static int l_add_item(lua_State *L)
2941 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2942 EnvRef *o = checkobject(L, 1);
2943 ServerEnvironment *env = o->m_env;
2944 if(env == NULL) return 0;
2946 v3f pos = checkFloatPos(L, 2);
2948 ItemStack item = read_item(L, 3);
2949 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2952 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2953 int objectid = env->addActiveObject(obj);
2954 // If failed to add, return nothing (reads as nil)
2958 objectref_get_or_create(L, obj);
2962 // EnvRef:add_rat(pos)
2963 // pos = {x=num, y=num, z=num}
2964 static int l_add_rat(lua_State *L)
2966 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2967 <<" Doing nothing."<<std::endl;
2971 // EnvRef:add_firefly(pos)
2972 // pos = {x=num, y=num, z=num}
2973 static int l_add_firefly(lua_State *L)
2975 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2976 <<" Doing nothing."<<std::endl;
2980 // EnvRef:get_meta(pos)
2981 static int l_get_meta(lua_State *L)
2983 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2984 EnvRef *o = checkobject(L, 1);
2985 ServerEnvironment *env = o->m_env;
2986 if(env == NULL) return 0;
2988 v3s16 p = read_v3s16(L, 2);
2989 NodeMetaRef::create(L, p, env);
2993 // EnvRef:get_player_by_name(name)
2994 static int l_get_player_by_name(lua_State *L)
2996 EnvRef *o = checkobject(L, 1);
2997 ServerEnvironment *env = o->m_env;
2998 if(env == NULL) return 0;
3000 const char *name = luaL_checkstring(L, 2);
3001 Player *player = env->getPlayer(name);
3006 PlayerSAO *sao = player->getPlayerSAO();
3011 // Put player on stack
3012 objectref_get_or_create(L, sao);
3016 // EnvRef:get_objects_inside_radius(pos, radius)
3017 static int l_get_objects_inside_radius(lua_State *L)
3019 // Get the table insert function
3020 lua_getglobal(L, "table");
3021 lua_getfield(L, -1, "insert");
3022 int table_insert = lua_gettop(L);
3024 EnvRef *o = checkobject(L, 1);
3025 ServerEnvironment *env = o->m_env;
3026 if(env == NULL) return 0;
3028 v3f pos = checkFloatPos(L, 2);
3029 float radius = luaL_checknumber(L, 3) * BS;
3030 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3032 int table = lua_gettop(L);
3033 for(std::set<u16>::const_iterator
3034 i = ids.begin(); i != ids.end(); i++){
3035 ServerActiveObject *obj = env->getActiveObject(*i);
3036 // Insert object reference into table
3037 lua_pushvalue(L, table_insert);
3038 lua_pushvalue(L, table);
3039 objectref_get_or_create(L, obj);
3040 if(lua_pcall(L, 2, 0, 0))
3041 script_error(L, "error: %s", lua_tostring(L, -1));
3046 // EnvRef:set_timeofday(val)
3048 static int l_set_timeofday(lua_State *L)
3050 EnvRef *o = checkobject(L, 1);
3051 ServerEnvironment *env = o->m_env;
3052 if(env == NULL) return 0;
3054 float timeofday_f = luaL_checknumber(L, 2);
3055 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3056 int timeofday_mh = (int)(timeofday_f * 24000.0);
3057 // This should be set directly in the environment but currently
3058 // such changes aren't immediately sent to the clients, so call
3059 // the server instead.
3060 //env->setTimeOfDay(timeofday_mh);
3061 get_server(L)->setTimeOfDay(timeofday_mh);
3065 // EnvRef:get_timeofday() -> 0...1
3066 static int l_get_timeofday(lua_State *L)
3068 EnvRef *o = checkobject(L, 1);
3069 ServerEnvironment *env = o->m_env;
3070 if(env == NULL) return 0;
3072 int timeofday_mh = env->getTimeOfDay();
3073 float timeofday_f = (float)timeofday_mh / 24000.0;
3074 lua_pushnumber(L, timeofday_f);
3078 static int gc_object(lua_State *L) {
3079 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3085 EnvRef(ServerEnvironment *env):
3088 //infostream<<"EnvRef created"<<std::endl;
3093 //infostream<<"EnvRef destructing"<<std::endl;
3096 // Creates an EnvRef and leaves it on top of stack
3097 // Not callable from Lua; all references are created on the C side.
3098 static void create(lua_State *L, ServerEnvironment *env)
3100 EnvRef *o = new EnvRef(env);
3101 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3102 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3103 luaL_getmetatable(L, className);
3104 lua_setmetatable(L, -2);
3107 static void set_null(lua_State *L)
3109 EnvRef *o = checkobject(L, -1);
3113 static void Register(lua_State *L)
3116 int methodtable = lua_gettop(L);
3117 luaL_newmetatable(L, className);
3118 int metatable = lua_gettop(L);
3120 lua_pushliteral(L, "__metatable");
3121 lua_pushvalue(L, methodtable);
3122 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3124 lua_pushliteral(L, "__index");
3125 lua_pushvalue(L, methodtable);
3126 lua_settable(L, metatable);
3128 lua_pushliteral(L, "__gc");
3129 lua_pushcfunction(L, gc_object);
3130 lua_settable(L, metatable);
3132 lua_pop(L, 1); // drop metatable
3134 luaL_openlib(L, 0, methods, 0); // fill methodtable
3135 lua_pop(L, 1); // drop methodtable
3137 // Cannot be created from Lua
3138 //lua_register(L, className, create_object);
3141 const char EnvRef::className[] = "EnvRef";
3142 const luaL_reg EnvRef::methods[] = {
3143 method(EnvRef, set_node),
3144 method(EnvRef, add_node),
3145 method(EnvRef, remove_node),
3146 method(EnvRef, get_node),
3147 method(EnvRef, get_node_or_nil),
3148 method(EnvRef, get_node_light),
3149 method(EnvRef, add_entity),
3150 method(EnvRef, add_item),
3151 method(EnvRef, add_rat),
3152 method(EnvRef, add_firefly),
3153 method(EnvRef, get_meta),
3154 method(EnvRef, get_player_by_name),
3155 method(EnvRef, get_objects_inside_radius),
3156 method(EnvRef, set_timeofday),
3157 method(EnvRef, get_timeofday),
3165 class LuaPseudoRandom
3168 PseudoRandom m_pseudo;
3170 static const char className[];
3171 static const luaL_reg methods[];
3173 // Exported functions
3175 // garbage collector
3176 static int gc_object(lua_State *L)
3178 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3183 // next(self, min=0, max=32767) -> get next value
3184 static int l_next(lua_State *L)
3186 LuaPseudoRandom *o = checkobject(L, 1);
3189 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3190 if(!lua_isnil(L, 2))
3191 min = luaL_checkinteger(L, 2);
3192 if(!lua_isnil(L, 3))
3193 max = luaL_checkinteger(L, 3);
3194 if(max - min != 32767 && max - min > 32767/5)
3195 throw LuaError(L, "PseudoRandom.next() max-min is not 32767 and is > 32768/5. This is disallowed due to the bad random distribution the implementation would otherwise make.");
3196 PseudoRandom &pseudo = o->m_pseudo;
3197 int val = pseudo.next();
3198 val = (val % (max-min+1)) + min;
3199 lua_pushinteger(L, val);
3204 LuaPseudoRandom(int seed):
3213 const PseudoRandom& getItem() const
3217 PseudoRandom& getItem()
3222 // LuaPseudoRandom(seed)
3223 // Creates an LuaPseudoRandom and leaves it on top of stack
3224 static int create_object(lua_State *L)
3226 int seed = luaL_checknumber(L, 1);
3227 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3228 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3229 luaL_getmetatable(L, className);
3230 lua_setmetatable(L, -2);
3234 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3236 luaL_checktype(L, narg, LUA_TUSERDATA);
3237 void *ud = luaL_checkudata(L, narg, className);
3238 if(!ud) luaL_typerror(L, narg, className);
3239 return *(LuaPseudoRandom**)ud; // unbox pointer
3242 static void Register(lua_State *L)
3245 int methodtable = lua_gettop(L);
3246 luaL_newmetatable(L, className);
3247 int metatable = lua_gettop(L);
3249 lua_pushliteral(L, "__metatable");
3250 lua_pushvalue(L, methodtable);
3251 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3253 lua_pushliteral(L, "__index");
3254 lua_pushvalue(L, methodtable);
3255 lua_settable(L, metatable);
3257 lua_pushliteral(L, "__gc");
3258 lua_pushcfunction(L, gc_object);
3259 lua_settable(L, metatable);
3261 lua_pop(L, 1); // drop metatable
3263 luaL_openlib(L, 0, methods, 0); // fill methodtable
3264 lua_pop(L, 1); // drop methodtable
3266 // Can be created from Lua (LuaPseudoRandom(seed))
3267 lua_register(L, className, create_object);
3270 const char LuaPseudoRandom::className[] = "PseudoRandom";
3271 const luaL_reg LuaPseudoRandom::methods[] = {
3272 method(LuaPseudoRandom, next),
3280 class LuaABM : public ActiveBlockModifier
3286 std::set<std::string> m_trigger_contents;
3287 std::set<std::string> m_required_neighbors;
3288 float m_trigger_interval;
3289 u32 m_trigger_chance;
3291 LuaABM(lua_State *L, int id,
3292 const std::set<std::string> &trigger_contents,
3293 const std::set<std::string> &required_neighbors,
3294 float trigger_interval, u32 trigger_chance):
3297 m_trigger_contents(trigger_contents),
3298 m_required_neighbors(required_neighbors),
3299 m_trigger_interval(trigger_interval),
3300 m_trigger_chance(trigger_chance)
3303 virtual std::set<std::string> getTriggerContents()
3305 return m_trigger_contents;
3307 virtual std::set<std::string> getRequiredNeighbors()
3309 return m_required_neighbors;
3311 virtual float getTriggerInterval()
3313 return m_trigger_interval;
3315 virtual u32 getTriggerChance()
3317 return m_trigger_chance;
3319 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3320 u32 active_object_count, u32 active_object_count_wider)
3322 lua_State *L = m_lua;
3325 assert(lua_checkstack(L, 20));
3326 StackUnroller stack_unroller(L);
3328 // Get minetest.registered_abms
3329 lua_getglobal(L, "minetest");
3330 lua_getfield(L, -1, "registered_abms");
3331 luaL_checktype(L, -1, LUA_TTABLE);
3332 int registered_abms = lua_gettop(L);
3334 // Get minetest.registered_abms[m_id]
3335 lua_pushnumber(L, m_id);
3336 lua_gettable(L, registered_abms);
3337 if(lua_isnil(L, -1))
3341 luaL_checktype(L, -1, LUA_TTABLE);
3342 lua_getfield(L, -1, "action");
3343 luaL_checktype(L, -1, LUA_TFUNCTION);
3345 pushnode(L, n, env->getGameDef()->ndef());
3346 lua_pushnumber(L, active_object_count);
3347 lua_pushnumber(L, active_object_count_wider);
3348 if(lua_pcall(L, 4, 0, 0))
3349 script_error(L, "error: %s", lua_tostring(L, -1));
3357 static void read_server_sound_params(lua_State *L, int index,
3358 ServerSoundParams ¶ms)
3361 index = lua_gettop(L) + 1 + index;
3363 params = ServerSoundParams();
3364 if(lua_istable(L, index)){
3365 getfloatfield(L, index, "gain", params.gain);
3366 getstringfield(L, index, "to_player", params.to_player);
3367 lua_getfield(L, index, "pos");
3368 if(!lua_isnil(L, -1)){
3369 v3f p = read_v3f(L, -1)*BS;
3371 params.type = ServerSoundParams::SSP_POSITIONAL;
3374 lua_getfield(L, index, "object");
3375 if(!lua_isnil(L, -1)){
3376 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3377 ServerActiveObject *sao = ObjectRef::getobject(ref);
3379 params.object = sao->getId();
3380 params.type = ServerSoundParams::SSP_OBJECT;
3384 params.max_hear_distance = BS*getfloatfield_default(L, index,
3385 "max_hear_distance", params.max_hear_distance/BS);
3386 getboolfield(L, index, "loop", params.loop);
3395 // Writes a line to dstream
3396 static int l_debug(lua_State *L)
3398 std::string text = lua_tostring(L, 1);
3399 dstream << text << std::endl;
3403 // log([level,] text)
3404 // Writes a line to the logger.
3405 // The one-argument version logs to infostream.
3406 // The two-argument version accept a log level: error, action, info, or verbose.
3407 static int l_log(lua_State *L)
3410 LogMessageLevel level = LMT_INFO;
3411 if(lua_isnone(L, 2))
3413 text = lua_tostring(L, 1);
3417 std::string levelname = lua_tostring(L, 1);
3418 text = lua_tostring(L, 2);
3419 if(levelname == "error")
3421 else if(levelname == "action")
3423 else if(levelname == "verbose")
3424 level = LMT_VERBOSE;
3426 log_printline(level, text);
3430 // register_item_raw({lots of stuff})
3431 static int l_register_item_raw(lua_State *L)
3433 luaL_checktype(L, 1, LUA_TTABLE);
3436 // Get the writable item and node definition managers from the server
3437 IWritableItemDefManager *idef =
3438 get_server(L)->getWritableItemDefManager();
3439 IWritableNodeDefManager *ndef =
3440 get_server(L)->getWritableNodeDefManager();
3442 // Check if name is defined
3443 lua_getfield(L, table, "name");
3444 if(lua_isstring(L, -1)){
3445 std::string name = lua_tostring(L, -1);
3446 verbosestream<<"register_item_raw: "<<name<<std::endl;
3448 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3451 // Check if on_use is defined
3453 // Read the item definition and register it
3454 ItemDefinition def = read_item_definition(L, table);
3455 idef->registerItem(def);
3457 // Read the node definition (content features) and register it
3458 if(def.type == ITEM_NODE)
3460 ContentFeatures f = read_content_features(L, table);
3461 ndef->set(f.name, f);
3464 return 0; /* number of results */
3467 // register_alias_raw(name, convert_to_name)
3468 static int l_register_alias_raw(lua_State *L)
3470 std::string name = luaL_checkstring(L, 1);
3471 std::string convert_to = luaL_checkstring(L, 2);
3473 // Get the writable item definition manager from the server
3474 IWritableItemDefManager *idef =
3475 get_server(L)->getWritableItemDefManager();
3477 idef->registerAlias(name, convert_to);
3479 return 0; /* number of results */
3482 // helper for register_craft
3483 static bool read_craft_recipe_shaped(lua_State *L, int index,
3484 int &width, std::vector<std::string> &recipe)
3487 index = lua_gettop(L) + 1 + index;
3489 if(!lua_istable(L, index))
3494 while(lua_next(L, index) != 0){
3496 // key at index -2 and value at index -1
3497 if(!lua_istable(L, -1))
3499 int table2 = lua_gettop(L);
3501 while(lua_next(L, table2) != 0){
3502 // key at index -2 and value at index -1
3503 if(!lua_isstring(L, -1))
3505 recipe.push_back(lua_tostring(L, -1));
3506 // removes value, keeps key for next iteration
3513 if(colcount != width)
3516 // removes value, keeps key for next iteration
3523 // helper for register_craft
3524 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3525 std::vector<std::string> &recipe)
3528 index = lua_gettop(L) + 1 + index;
3530 if(!lua_istable(L, index))
3534 while(lua_next(L, index) != 0){
3535 // key at index -2 and value at index -1
3536 if(!lua_isstring(L, -1))
3538 recipe.push_back(lua_tostring(L, -1));
3539 // removes value, keeps key for next iteration
3545 // helper for register_craft
3546 static bool read_craft_replacements(lua_State *L, int index,
3547 CraftReplacements &replacements)
3550 index = lua_gettop(L) + 1 + index;
3552 if(!lua_istable(L, index))
3556 while(lua_next(L, index) != 0){
3557 // key at index -2 and value at index -1
3558 if(!lua_istable(L, -1))
3560 lua_rawgeti(L, -1, 1);
3561 if(!lua_isstring(L, -1))
3563 std::string replace_from = lua_tostring(L, -1);
3565 lua_rawgeti(L, -1, 2);
3566 if(!lua_isstring(L, -1))
3568 std::string replace_to = lua_tostring(L, -1);
3570 replacements.pairs.push_back(
3571 std::make_pair(replace_from, replace_to));
3572 // removes value, keeps key for next iteration
3577 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3578 static int l_register_craft(lua_State *L)
3580 //infostream<<"register_craft"<<std::endl;
3581 luaL_checktype(L, 1, LUA_TTABLE);
3584 // Get the writable craft definition manager from the server
3585 IWritableCraftDefManager *craftdef =
3586 get_server(L)->getWritableCraftDefManager();
3588 std::string type = getstringfield_default(L, table, "type", "shaped");
3591 CraftDefinitionShaped
3593 if(type == "shaped"){
3594 std::string output = getstringfield_default(L, table, "output", "");
3596 throw LuaError(L, "Crafting definition is missing an output");
3599 std::vector<std::string> recipe;
3600 lua_getfield(L, table, "recipe");
3601 if(lua_isnil(L, -1))
3602 throw LuaError(L, "Crafting definition is missing a recipe"
3603 " (output=\"" + output + "\")");
3604 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3605 throw LuaError(L, "Invalid crafting recipe"
3606 " (output=\"" + output + "\")");
3608 CraftReplacements replacements;
3609 lua_getfield(L, table, "replacements");
3610 if(!lua_isnil(L, -1))
3612 if(!read_craft_replacements(L, -1, replacements))
3613 throw LuaError(L, "Invalid replacements"
3614 " (output=\"" + output + "\")");
3617 CraftDefinition *def = new CraftDefinitionShaped(
3618 output, width, recipe, replacements);
3619 craftdef->registerCraft(def);
3622 CraftDefinitionShapeless
3624 else if(type == "shapeless"){
3625 std::string output = getstringfield_default(L, table, "output", "");
3627 throw LuaError(L, "Crafting definition (shapeless)"
3628 " is missing an output");
3630 std::vector<std::string> recipe;
3631 lua_getfield(L, table, "recipe");
3632 if(lua_isnil(L, -1))
3633 throw LuaError(L, "Crafting definition (shapeless)"
3634 " is missing a recipe"
3635 " (output=\"" + output + "\")");
3636 if(!read_craft_recipe_shapeless(L, -1, recipe))
3637 throw LuaError(L, "Invalid crafting recipe"
3638 " (output=\"" + output + "\")");
3640 CraftReplacements replacements;
3641 lua_getfield(L, table, "replacements");
3642 if(!lua_isnil(L, -1))
3644 if(!read_craft_replacements(L, -1, replacements))
3645 throw LuaError(L, "Invalid replacements"
3646 " (output=\"" + output + "\")");
3649 CraftDefinition *def = new CraftDefinitionShapeless(
3650 output, recipe, replacements);
3651 craftdef->registerCraft(def);
3654 CraftDefinitionToolRepair
3656 else if(type == "toolrepair"){
3657 float additional_wear = getfloatfield_default(L, table,
3658 "additional_wear", 0.0);
3660 CraftDefinition *def = new CraftDefinitionToolRepair(
3662 craftdef->registerCraft(def);
3665 CraftDefinitionCooking
3667 else if(type == "cooking"){
3668 std::string output = getstringfield_default(L, table, "output", "");
3670 throw LuaError(L, "Crafting definition (cooking)"
3671 " is missing an output");
3673 std::string recipe = getstringfield_default(L, table, "recipe", "");
3675 throw LuaError(L, "Crafting definition (cooking)"
3676 " is missing a recipe"
3677 " (output=\"" + output + "\")");
3679 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3681 CraftDefinition *def = new CraftDefinitionCooking(
3682 output, recipe, cooktime);
3683 craftdef->registerCraft(def);
3688 else if(type == "fuel"){
3689 std::string recipe = getstringfield_default(L, table, "recipe", "");
3691 throw LuaError(L, "Crafting definition (fuel)"
3692 " is missing a recipe");
3694 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3696 CraftDefinition *def = new CraftDefinitionFuel(
3698 craftdef->registerCraft(def);
3702 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3706 return 0; /* number of results */
3709 // setting_get(name)
3710 static int l_setting_get(lua_State *L)
3712 const char *name = luaL_checkstring(L, 1);
3714 std::string value = g_settings->get(name);
3715 lua_pushstring(L, value.c_str());
3716 } catch(SettingNotFoundException &e){
3722 // setting_getbool(name)
3723 static int l_setting_getbool(lua_State *L)
3725 const char *name = luaL_checkstring(L, 1);
3727 bool value = g_settings->getBool(name);
3728 lua_pushboolean(L, value);
3729 } catch(SettingNotFoundException &e){
3735 // chat_send_all(text)
3736 static int l_chat_send_all(lua_State *L)
3738 const char *text = luaL_checkstring(L, 1);
3739 // Get server from registry
3740 Server *server = get_server(L);
3742 server->notifyPlayers(narrow_to_wide(text));
3746 // chat_send_player(name, text)
3747 static int l_chat_send_player(lua_State *L)
3749 const char *name = luaL_checkstring(L, 1);
3750 const char *text = luaL_checkstring(L, 2);
3751 // Get server from registry
3752 Server *server = get_server(L);
3754 server->notifyPlayer(name, narrow_to_wide(text));
3758 // get_player_privs(name, text)
3759 static int l_get_player_privs(lua_State *L)
3761 const char *name = luaL_checkstring(L, 1);
3762 // Get server from registry
3763 Server *server = get_server(L);
3766 int table = lua_gettop(L);
3767 u64 privs_i = server->getPlayerEffectivePrivs(name);
3768 std::set<std::string> privs_s = privsToSet(privs_i);
3769 for(std::set<std::string>::const_iterator
3770 i = privs_s.begin(); i != privs_s.end(); i++){
3771 lua_pushboolean(L, true);
3772 lua_setfield(L, table, i->c_str());
3774 lua_pushvalue(L, table);
3778 // get_inventory(location)
3779 static int l_get_inventory(lua_State *L)
3781 InventoryLocation loc;
3783 std::string type = checkstringfield(L, 1, "type");
3784 if(type == "player"){
3785 std::string name = checkstringfield(L, 1, "name");
3786 loc.setPlayer(name);
3787 } else if(type == "node"){
3788 lua_getfield(L, 1, "pos");
3789 v3s16 pos = check_v3s16(L, -1);
3790 loc.setNodeMeta(pos);
3793 if(get_server(L)->getInventory(loc) != NULL)
3794 InvRef::create(L, loc);
3800 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3801 static int l_get_dig_params(lua_State *L)
3803 std::map<std::string, int> groups;
3804 read_groups(L, 1, groups);
3805 ToolCapabilities tp = read_tool_capabilities(L, 2);
3806 if(lua_isnoneornil(L, 3))
3807 push_dig_params(L, getDigParams(groups, &tp));
3809 push_dig_params(L, getDigParams(groups, &tp,
3810 luaL_checknumber(L, 3)));
3814 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3815 static int l_get_hit_params(lua_State *L)
3817 std::map<std::string, int> groups;
3818 read_groups(L, 1, groups);
3819 ToolCapabilities tp = read_tool_capabilities(L, 2);
3820 if(lua_isnoneornil(L, 3))
3821 push_hit_params(L, getHitParams(groups, &tp));
3823 push_hit_params(L, getHitParams(groups, &tp,
3824 luaL_checknumber(L, 3)));
3828 // get_current_modname()
3829 static int l_get_current_modname(lua_State *L)
3831 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3835 // get_modpath(modname)
3836 static int l_get_modpath(lua_State *L)
3838 const char *modname = luaL_checkstring(L, 1);
3840 const ModSpec *mod = get_server(L)->getModSpec(modname);
3845 lua_pushstring(L, mod->path.c_str());
3850 static int l_get_worldpath(lua_State *L)
3852 std::string worldpath = get_server(L)->getWorldPath();
3853 lua_pushstring(L, worldpath.c_str());
3857 // sound_play(spec, parameters)
3858 static int l_sound_play(lua_State *L)
3860 SimpleSoundSpec spec;
3861 read_soundspec(L, 1, spec);
3862 ServerSoundParams params;
3863 read_server_sound_params(L, 2, params);
3864 s32 handle = get_server(L)->playSound(spec, params);
3865 lua_pushinteger(L, handle);
3869 // sound_stop(handle)
3870 static int l_sound_stop(lua_State *L)
3872 int handle = luaL_checkinteger(L, 1);
3873 get_server(L)->stopSound(handle);
3877 // is_singleplayer()
3878 static int l_is_singleplayer(lua_State *L)
3880 lua_pushboolean(L, get_server(L)->isSingleplayer());
3884 static const struct luaL_Reg minetest_f [] = {
3887 {"register_item_raw", l_register_item_raw},
3888 {"register_alias_raw", l_register_alias_raw},
3889 {"register_craft", l_register_craft},
3890 {"setting_get", l_setting_get},
3891 {"setting_getbool", l_setting_getbool},
3892 {"chat_send_all", l_chat_send_all},
3893 {"chat_send_player", l_chat_send_player},
3894 {"get_player_privs", l_get_player_privs},
3895 {"get_inventory", l_get_inventory},
3896 {"get_dig_params", l_get_dig_params},
3897 {"get_hit_params", l_get_hit_params},
3898 {"get_current_modname", l_get_current_modname},
3899 {"get_modpath", l_get_modpath},
3900 {"get_worldpath", l_get_worldpath},
3901 {"sound_play", l_sound_play},
3902 {"sound_stop", l_sound_stop},
3903 {"is_singleplayer", l_is_singleplayer},
3908 Main export function
3911 void scriptapi_export(lua_State *L, Server *server)
3914 assert(lua_checkstack(L, 20));
3915 verbosestream<<"scriptapi_export()"<<std::endl;
3916 StackUnroller stack_unroller(L);
3918 // Store server as light userdata in registry
3919 lua_pushlightuserdata(L, server);
3920 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3922 // Register global functions in table minetest
3924 luaL_register(L, NULL, minetest_f);
3925 lua_setglobal(L, "minetest");
3927 // Get the main minetest table
3928 lua_getglobal(L, "minetest");
3930 // Add tables to minetest
3933 lua_setfield(L, -2, "object_refs");
3935 lua_setfield(L, -2, "luaentities");
3937 // Register wrappers
3938 LuaItemStack::Register(L);
3939 InvRef::Register(L);
3940 NodeMetaRef::Register(L);
3941 ObjectRef::Register(L);
3942 EnvRef::Register(L);
3943 LuaPseudoRandom::Register(L);
3946 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3947 const std::string &modname)
3949 ModNameStorer modnamestorer(L, modname);
3951 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3953 errorstream<<"Error loading mod \""<<modname
3954 <<"\": modname does not follow naming conventions: "
3955 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3959 bool success = false;
3962 success = script_load(L, scriptpath.c_str());
3965 errorstream<<"Error loading mod \""<<modname
3966 <<"\": "<<e.what()<<std::endl;
3972 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3975 assert(lua_checkstack(L, 20));
3976 verbosestream<<"scriptapi_add_environment"<<std::endl;
3977 StackUnroller stack_unroller(L);
3979 // Create EnvRef on stack
3980 EnvRef::create(L, env);
3981 int envref = lua_gettop(L);
3983 // minetest.env = envref
3984 lua_getglobal(L, "minetest");
3985 luaL_checktype(L, -1, LUA_TTABLE);
3986 lua_pushvalue(L, envref);
3987 lua_setfield(L, -2, "env");
3989 // Store environment as light userdata in registry
3990 lua_pushlightuserdata(L, env);
3991 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3994 Add ActiveBlockModifiers to environment
3997 // Get minetest.registered_abms
3998 lua_getglobal(L, "minetest");
3999 lua_getfield(L, -1, "registered_abms");
4000 luaL_checktype(L, -1, LUA_TTABLE);
4001 int registered_abms = lua_gettop(L);
4003 if(lua_istable(L, registered_abms)){
4004 int table = lua_gettop(L);
4006 while(lua_next(L, table) != 0){
4007 // key at index -2 and value at index -1
4008 int id = lua_tonumber(L, -2);
4009 int current_abm = lua_gettop(L);
4011 std::set<std::string> trigger_contents;
4012 lua_getfield(L, current_abm, "nodenames");
4013 if(lua_istable(L, -1)){
4014 int table = lua_gettop(L);
4016 while(lua_next(L, table) != 0){
4017 // key at index -2 and value at index -1
4018 luaL_checktype(L, -1, LUA_TSTRING);
4019 trigger_contents.insert(lua_tostring(L, -1));
4020 // removes value, keeps key for next iteration
4023 } else if(lua_isstring(L, -1)){
4024 trigger_contents.insert(lua_tostring(L, -1));
4028 std::set<std::string> required_neighbors;
4029 lua_getfield(L, current_abm, "neighbors");
4030 if(lua_istable(L, -1)){
4031 int table = lua_gettop(L);
4033 while(lua_next(L, table) != 0){
4034 // key at index -2 and value at index -1
4035 luaL_checktype(L, -1, LUA_TSTRING);
4036 required_neighbors.insert(lua_tostring(L, -1));
4037 // removes value, keeps key for next iteration
4040 } else if(lua_isstring(L, -1)){
4041 required_neighbors.insert(lua_tostring(L, -1));
4045 float trigger_interval = 10.0;
4046 getfloatfield(L, current_abm, "interval", trigger_interval);
4048 int trigger_chance = 50;
4049 getintfield(L, current_abm, "chance", trigger_chance);
4051 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4052 required_neighbors, trigger_interval, trigger_chance);
4054 env->addActiveBlockModifier(abm);
4056 // removes value, keeps key for next iteration
4064 // Dump stack top with the dump2 function
4065 static void dump2(lua_State *L, const char *name)
4067 // Dump object (debug)
4068 lua_getglobal(L, "dump2");
4069 luaL_checktype(L, -1, LUA_TFUNCTION);
4070 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4071 lua_pushstring(L, name);
4072 if(lua_pcall(L, 2, 0, 0))
4073 script_error(L, "error: %s", lua_tostring(L, -1));
4081 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4084 assert(lua_checkstack(L, 20));
4085 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4086 StackUnroller stack_unroller(L);
4088 // Create object on stack
4089 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4090 int object = lua_gettop(L);
4092 // Get minetest.object_refs table
4093 lua_getglobal(L, "minetest");
4094 lua_getfield(L, -1, "object_refs");
4095 luaL_checktype(L, -1, LUA_TTABLE);
4096 int objectstable = lua_gettop(L);
4098 // object_refs[id] = object
4099 lua_pushnumber(L, cobj->getId()); // Push id
4100 lua_pushvalue(L, object); // Copy object to top of stack
4101 lua_settable(L, objectstable);
4104 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4107 assert(lua_checkstack(L, 20));
4108 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4109 StackUnroller stack_unroller(L);
4111 // Get minetest.object_refs table
4112 lua_getglobal(L, "minetest");
4113 lua_getfield(L, -1, "object_refs");
4114 luaL_checktype(L, -1, LUA_TTABLE);
4115 int objectstable = lua_gettop(L);
4117 // Get object_refs[id]
4118 lua_pushnumber(L, cobj->getId()); // Push id
4119 lua_gettable(L, objectstable);
4120 // Set object reference to NULL
4121 ObjectRef::set_null(L);
4122 lua_pop(L, 1); // pop object
4124 // Set object_refs[id] = nil
4125 lua_pushnumber(L, cobj->getId()); // Push id
4127 lua_settable(L, objectstable);
4134 // What scriptapi_run_callbacks does with the return values of callbacks.
4135 // Regardless of the mode, if only one callback is defined,
4136 // its return value is the total return value.
4137 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4138 enum RunCallbacksMode
4140 // Returns the return value of the first callback
4141 // Returns nil if list of callbacks is empty
4142 RUN_CALLBACKS_MODE_FIRST,
4143 // Returns the return value of the last callback
4144 // Returns nil if list of callbacks is empty
4145 RUN_CALLBACKS_MODE_LAST,
4146 // If any callback returns a false value, the first such is returned
4147 // Otherwise, the first callback's return value (trueish) is returned
4148 // Returns true if list of callbacks is empty
4149 RUN_CALLBACKS_MODE_AND,
4150 // Like above, but stops calling callbacks (short circuit)
4151 // after seeing the first false value
4152 RUN_CALLBACKS_MODE_AND_SC,
4153 // If any callback returns a true value, the first such is returned
4154 // Otherwise, the first callback's return value (falseish) is returned
4155 // Returns false if list of callbacks is empty
4156 RUN_CALLBACKS_MODE_OR,
4157 // Like above, but stops calling callbacks (short circuit)
4158 // after seeing the first true value
4159 RUN_CALLBACKS_MODE_OR_SC,
4160 // Note: "a true value" and "a false value" refer to values that
4161 // are converted by lua_toboolean to true or false, respectively.
4164 // Push the list of callbacks (a lua table).
4165 // Then push nargs arguments.
4166 // Then call this function, which
4167 // - runs the callbacks
4168 // - removes the table and arguments from the lua stack
4169 // - pushes the return value, computed depending on mode
4170 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4171 RunCallbacksMode mode)
4173 // Insert the return value into the lua stack, below the table
4174 assert(lua_gettop(L) >= nargs + 1);
4176 lua_insert(L, -(nargs + 1) - 1);
4177 // Stack now looks like this:
4178 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4180 int rv = lua_gettop(L) - nargs - 1;
4182 int arg = table + 1;
4184 luaL_checktype(L, table, LUA_TTABLE);
4188 bool first_loop = true;
4189 while(lua_next(L, table) != 0){
4190 // key at index -2 and value at index -1
4191 luaL_checktype(L, -1, LUA_TFUNCTION);
4193 for(int i = 0; i < nargs; i++)
4194 lua_pushvalue(L, arg+i);
4195 if(lua_pcall(L, nargs, 1, 0))
4196 script_error(L, "error: %s", lua_tostring(L, -1));
4198 // Move return value to designated space in stack
4201 // Result of first callback is always moved
4205 // Otherwise, what happens depends on the mode
4206 if(mode == RUN_CALLBACKS_MODE_FIRST)
4208 else if(mode == RUN_CALLBACKS_MODE_LAST)
4210 else if(mode == RUN_CALLBACKS_MODE_AND ||
4211 mode == RUN_CALLBACKS_MODE_AND_SC){
4212 if(lua_toboolean(L, rv) == true &&
4213 lua_toboolean(L, -1) == false)
4218 else if(mode == RUN_CALLBACKS_MODE_OR ||
4219 mode == RUN_CALLBACKS_MODE_OR_SC){
4220 if(lua_toboolean(L, rv) == false &&
4221 lua_toboolean(L, -1) == true)
4230 // Handle short circuit modes
4231 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4232 lua_toboolean(L, rv) == false)
4234 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4235 lua_toboolean(L, rv) == true)
4238 // value removed, keep key for next iteration
4241 // Remove stuff from stack, leaving only the return value
4244 // Fix return value in case no callbacks were called
4246 if(mode == RUN_CALLBACKS_MODE_AND ||
4247 mode == RUN_CALLBACKS_MODE_AND_SC){
4249 lua_pushboolean(L, true);
4251 else if(mode == RUN_CALLBACKS_MODE_OR ||
4252 mode == RUN_CALLBACKS_MODE_OR_SC){
4254 lua_pushboolean(L, false);
4259 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4260 const std::string &message)
4263 assert(lua_checkstack(L, 20));
4264 StackUnroller stack_unroller(L);
4266 // Get minetest.registered_on_chat_messages
4267 lua_getglobal(L, "minetest");
4268 lua_getfield(L, -1, "registered_on_chat_messages");
4270 lua_pushstring(L, name.c_str());
4271 lua_pushstring(L, message.c_str());
4272 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4273 bool ate = lua_toboolean(L, -1);
4277 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4280 assert(lua_checkstack(L, 20));
4281 StackUnroller stack_unroller(L);
4283 // Get minetest.registered_on_newplayers
4284 lua_getglobal(L, "minetest");
4285 lua_getfield(L, -1, "registered_on_newplayers");
4287 objectref_get_or_create(L, player);
4288 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4291 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4294 assert(lua_checkstack(L, 20));
4295 StackUnroller stack_unroller(L);
4297 // Get minetest.registered_on_dieplayers
4298 lua_getglobal(L, "minetest");
4299 lua_getfield(L, -1, "registered_on_dieplayers");
4301 objectref_get_or_create(L, player);
4302 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4305 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4308 assert(lua_checkstack(L, 20));
4309 StackUnroller stack_unroller(L);
4311 // Get minetest.registered_on_respawnplayers
4312 lua_getglobal(L, "minetest");
4313 lua_getfield(L, -1, "registered_on_respawnplayers");
4315 objectref_get_or_create(L, player);
4316 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4317 bool positioning_handled_by_some = lua_toboolean(L, -1);
4318 return positioning_handled_by_some;
4321 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4324 assert(lua_checkstack(L, 20));
4325 StackUnroller stack_unroller(L);
4327 // Get minetest.registered_on_joinplayers
4328 lua_getglobal(L, "minetest");
4329 lua_getfield(L, -1, "registered_on_joinplayers");
4331 objectref_get_or_create(L, player);
4332 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4335 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4338 assert(lua_checkstack(L, 20));
4339 StackUnroller stack_unroller(L);
4341 // Get minetest.registered_on_leaveplayers
4342 lua_getglobal(L, "minetest");
4343 lua_getfield(L, -1, "registered_on_leaveplayers");
4345 objectref_get_or_create(L, player);
4346 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4349 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4351 Inventory *inv = player->getInventory();
4354 lua_getglobal(L, "minetest");
4355 lua_getfield(L, -1, "creative_inventory");
4356 luaL_checktype(L, -1, LUA_TTABLE);
4357 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4361 item callbacks and node callbacks
4364 // Retrieves minetest.registered_items[name][callbackname]
4365 // If that is nil or on error, return false and stack is unchanged
4366 // If that is a function, returns true and pushes the
4367 // function onto the stack
4368 static bool get_item_callback(lua_State *L,
4369 const char *name, const char *callbackname)
4371 lua_getglobal(L, "minetest");
4372 lua_getfield(L, -1, "registered_items");
4374 luaL_checktype(L, -1, LUA_TTABLE);
4375 lua_getfield(L, -1, name);
4377 // Should be a table
4378 if(lua_type(L, -1) != LUA_TTABLE)
4380 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4384 lua_getfield(L, -1, callbackname);
4386 // Should be a function or nil
4387 if(lua_type(L, -1) == LUA_TFUNCTION)
4391 else if(lua_isnil(L, -1))
4398 errorstream<<"Item \""<<name<<"\" callback \""
4399 <<callbackname<<" is not a function"<<std::endl;
4405 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4406 ServerActiveObject *dropper, v3f pos)
4409 assert(lua_checkstack(L, 20));
4410 StackUnroller stack_unroller(L);
4412 // Push callback function on stack
4413 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4417 LuaItemStack::create(L, item);
4418 objectref_get_or_create(L, dropper);
4419 pushFloatPos(L, pos);
4420 if(lua_pcall(L, 3, 1, 0))
4421 script_error(L, "error: %s", lua_tostring(L, -1));
4422 if(!lua_isnil(L, -1))
4423 item = read_item(L, -1);
4427 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4428 ServerActiveObject *placer, const PointedThing &pointed)
4431 assert(lua_checkstack(L, 20));
4432 StackUnroller stack_unroller(L);
4434 // Push callback function on stack
4435 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4439 LuaItemStack::create(L, item);
4440 objectref_get_or_create(L, placer);
4441 push_pointed_thing(L, pointed);
4442 if(lua_pcall(L, 3, 1, 0))
4443 script_error(L, "error: %s", lua_tostring(L, -1));
4444 if(!lua_isnil(L, -1))
4445 item = read_item(L, -1);
4449 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4450 ServerActiveObject *user, const PointedThing &pointed)
4453 assert(lua_checkstack(L, 20));
4454 StackUnroller stack_unroller(L);
4456 // Push callback function on stack
4457 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4461 LuaItemStack::create(L, item);
4462 objectref_get_or_create(L, user);
4463 push_pointed_thing(L, pointed);
4464 if(lua_pcall(L, 3, 1, 0))
4465 script_error(L, "error: %s", lua_tostring(L, -1));
4466 if(!lua_isnil(L, -1))
4467 item = read_item(L, -1);
4471 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4472 ServerActiveObject *puncher)
4475 assert(lua_checkstack(L, 20));
4476 StackUnroller stack_unroller(L);
4478 INodeDefManager *ndef = get_server(L)->ndef();
4480 // Push callback function on stack
4481 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4486 pushnode(L, node, ndef);
4487 objectref_get_or_create(L, puncher);
4488 if(lua_pcall(L, 3, 0, 0))
4489 script_error(L, "error: %s", lua_tostring(L, -1));
4493 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4494 ServerActiveObject *digger)
4497 assert(lua_checkstack(L, 20));
4498 StackUnroller stack_unroller(L);
4500 INodeDefManager *ndef = get_server(L)->ndef();
4502 // Push callback function on stack
4503 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4508 pushnode(L, node, ndef);
4509 objectref_get_or_create(L, digger);
4510 if(lua_pcall(L, 3, 0, 0))
4511 script_error(L, "error: %s", lua_tostring(L, -1));
4519 void scriptapi_environment_step(lua_State *L, float dtime)
4522 assert(lua_checkstack(L, 20));
4523 //infostream<<"scriptapi_environment_step"<<std::endl;
4524 StackUnroller stack_unroller(L);
4526 // Get minetest.registered_globalsteps
4527 lua_getglobal(L, "minetest");
4528 lua_getfield(L, -1, "registered_globalsteps");
4530 lua_pushnumber(L, dtime);
4531 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4534 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
4538 assert(lua_checkstack(L, 20));
4539 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4540 StackUnroller stack_unroller(L);
4542 // Get minetest.registered_on_generateds
4543 lua_getglobal(L, "minetest");
4544 lua_getfield(L, -1, "registered_on_generateds");
4546 push_v3s16(L, minp);
4547 push_v3s16(L, maxp);
4548 lua_pushnumber(L, blockseed);
4549 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
4556 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4559 assert(lua_checkstack(L, 20));
4560 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4561 <<name<<"\""<<std::endl;
4562 StackUnroller stack_unroller(L);
4564 // Get minetest.registered_entities[name]
4565 lua_getglobal(L, "minetest");
4566 lua_getfield(L, -1, "registered_entities");
4567 luaL_checktype(L, -1, LUA_TTABLE);
4568 lua_pushstring(L, name);
4569 lua_gettable(L, -2);
4570 // Should be a table, which we will use as a prototype
4571 //luaL_checktype(L, -1, LUA_TTABLE);
4572 if(lua_type(L, -1) != LUA_TTABLE){
4573 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4576 int prototype_table = lua_gettop(L);
4577 //dump2(L, "prototype_table");
4579 // Create entity object
4581 int object = lua_gettop(L);
4583 // Set object metatable
4584 lua_pushvalue(L, prototype_table);
4585 lua_setmetatable(L, -2);
4587 // Add object reference
4588 // This should be userdata with metatable ObjectRef
4589 objectref_get(L, id);
4590 luaL_checktype(L, -1, LUA_TUSERDATA);
4591 if(!luaL_checkudata(L, -1, "ObjectRef"))
4592 luaL_typerror(L, -1, "ObjectRef");
4593 lua_setfield(L, -2, "object");
4595 // minetest.luaentities[id] = object
4596 lua_getglobal(L, "minetest");
4597 lua_getfield(L, -1, "luaentities");
4598 luaL_checktype(L, -1, LUA_TTABLE);
4599 lua_pushnumber(L, id); // Push id
4600 lua_pushvalue(L, object); // Copy object to top of stack
4601 lua_settable(L, -3);
4606 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4607 const std::string &staticdata)
4610 assert(lua_checkstack(L, 20));
4611 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4612 StackUnroller stack_unroller(L);
4614 // Get minetest.luaentities[id]
4615 luaentity_get(L, id);
4616 int object = lua_gettop(L);
4618 // Get on_activate function
4619 lua_pushvalue(L, object);
4620 lua_getfield(L, -1, "on_activate");
4621 if(!lua_isnil(L, -1)){
4622 luaL_checktype(L, -1, LUA_TFUNCTION);
4623 lua_pushvalue(L, object); // self
4624 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4625 // Call with 2 arguments, 0 results
4626 if(lua_pcall(L, 2, 0, 0))
4627 script_error(L, "error running function on_activate: %s\n",
4628 lua_tostring(L, -1));
4632 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4635 assert(lua_checkstack(L, 20));
4636 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4638 // Get minetest.luaentities table
4639 lua_getglobal(L, "minetest");
4640 lua_getfield(L, -1, "luaentities");
4641 luaL_checktype(L, -1, LUA_TTABLE);
4642 int objectstable = lua_gettop(L);
4644 // Set luaentities[id] = nil
4645 lua_pushnumber(L, id); // Push id
4647 lua_settable(L, objectstable);
4649 lua_pop(L, 2); // pop luaentities, minetest
4652 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4655 assert(lua_checkstack(L, 20));
4656 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4657 StackUnroller stack_unroller(L);
4659 // Get minetest.luaentities[id]
4660 luaentity_get(L, id);
4661 int object = lua_gettop(L);
4663 // Get get_staticdata function
4664 lua_pushvalue(L, object);
4665 lua_getfield(L, -1, "get_staticdata");
4666 if(lua_isnil(L, -1))
4669 luaL_checktype(L, -1, LUA_TFUNCTION);
4670 lua_pushvalue(L, object); // self
4671 // Call with 1 arguments, 1 results
4672 if(lua_pcall(L, 1, 1, 0))
4673 script_error(L, "error running function get_staticdata: %s\n",
4674 lua_tostring(L, -1));
4677 const char *s = lua_tolstring(L, -1, &len);
4678 return std::string(s, len);
4681 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4682 LuaEntityProperties *prop)
4685 assert(lua_checkstack(L, 20));
4686 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4687 StackUnroller stack_unroller(L);
4689 // Get minetest.luaentities[id]
4690 luaentity_get(L, id);
4691 //int object = lua_gettop(L);
4695 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4697 getboolfield(L, -1, "physical", prop->physical);
4699 getfloatfield(L, -1, "weight", prop->weight);
4701 lua_getfield(L, -1, "collisionbox");
4702 if(lua_istable(L, -1))
4703 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4706 getstringfield(L, -1, "visual", prop->visual);
4708 lua_getfield(L, -1, "visual_size");
4709 if(lua_istable(L, -1))
4710 prop->visual_size = read_v2f(L, -1);
4713 lua_getfield(L, -1, "textures");
4714 if(lua_istable(L, -1)){
4715 prop->textures.clear();
4716 int table = lua_gettop(L);
4718 while(lua_next(L, table) != 0){
4719 // key at index -2 and value at index -1
4720 if(lua_isstring(L, -1))
4721 prop->textures.push_back(lua_tostring(L, -1));
4723 prop->textures.push_back("");
4724 // removes value, keeps key for next iteration
4730 lua_getfield(L, -1, "spritediv");
4731 if(lua_istable(L, -1))
4732 prop->spritediv = read_v2s16(L, -1);
4735 lua_getfield(L, -1, "initial_sprite_basepos");
4736 if(lua_istable(L, -1))
4737 prop->initial_sprite_basepos = read_v2s16(L, -1);
4741 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4744 assert(lua_checkstack(L, 20));
4745 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4746 StackUnroller stack_unroller(L);
4748 // Get minetest.luaentities[id]
4749 luaentity_get(L, id);
4750 int object = lua_gettop(L);
4751 // State: object is at top of stack
4752 // Get step function
4753 lua_getfield(L, -1, "on_step");
4754 if(lua_isnil(L, -1))
4756 luaL_checktype(L, -1, LUA_TFUNCTION);
4757 lua_pushvalue(L, object); // self
4758 lua_pushnumber(L, dtime); // dtime
4759 // Call with 2 arguments, 0 results
4760 if(lua_pcall(L, 2, 0, 0))
4761 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4764 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4765 // tool_capabilities, direction)
4766 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4767 ServerActiveObject *puncher, float time_from_last_punch,
4768 const ToolCapabilities *toolcap, v3f dir)
4771 assert(lua_checkstack(L, 20));
4772 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4773 StackUnroller stack_unroller(L);
4775 // Get minetest.luaentities[id]
4776 luaentity_get(L, id);
4777 int object = lua_gettop(L);
4778 // State: object is at top of stack
4780 lua_getfield(L, -1, "on_punch");
4781 if(lua_isnil(L, -1))
4783 luaL_checktype(L, -1, LUA_TFUNCTION);
4784 lua_pushvalue(L, object); // self
4785 objectref_get_or_create(L, puncher); // Clicker reference
4786 lua_pushnumber(L, time_from_last_punch);
4787 push_tool_capabilities(L, *toolcap);
4789 // Call with 5 arguments, 0 results
4790 if(lua_pcall(L, 5, 0, 0))
4791 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4794 // Calls entity:on_rightclick(ObjectRef clicker)
4795 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4796 ServerActiveObject *clicker)
4799 assert(lua_checkstack(L, 20));
4800 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4801 StackUnroller stack_unroller(L);
4803 // Get minetest.luaentities[id]
4804 luaentity_get(L, id);
4805 int object = lua_gettop(L);
4806 // State: object is at top of stack
4808 lua_getfield(L, -1, "on_rightclick");
4809 if(lua_isnil(L, -1))
4811 luaL_checktype(L, -1, LUA_TFUNCTION);
4812 lua_pushvalue(L, object); // self
4813 objectref_get_or_create(L, clicker); // Clicker reference
4814 // Call with 2 arguments, 0 results
4815 if(lua_pcall(L, 2, 0, 0))
4816 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));