3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "scriptapi.h"
34 #include "serverobject.h"
37 #include "luaentity_common.h"
38 #include "content_sao.h" // For LuaEntitySAO
42 #include "main.h" // For g_settings
43 #include "settings.h" // For accessing g_settings
44 #include "nodemetadata.h"
45 #include "mapblock.h" // For getNodeBlockPos
46 #include "content_nodemeta.h"
49 #include "daynightratio.h"
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)
1098 dstream<<"inventory_set_list_from_lua\n";
1100 tableindex = lua_gettop(L) + 1 + tableindex;
1101 // If nil, delete list
1102 if(lua_isnil(L, tableindex)){
1103 inv->deleteList(name);
1106 // Otherwise set list
1107 std::vector<ItemStack> items;
1108 luaL_checktype(L, tableindex, LUA_TTABLE);
1110 while(lua_next(L, tableindex) != 0){
1111 // key at index -2 and value at index -1
1112 items.push_back(read_item(L, -1));
1113 // removes value, keeps key for next iteration
1116 int listsize = (forcesize != -1) ? forcesize : items.size();
1117 InventoryList *invlist = inv->addList(name, listsize);
1119 for(std::vector<ItemStack>::const_iterator
1120 i = items.begin(); i != items.end(); i++){
1121 if(forcesize != -1 && index == forcesize)
1123 invlist->changeItem(index, *i);
1126 while(forcesize != -1 && index < forcesize){
1127 invlist->deleteItem(index);
1130 dstream<<"inventory_set_list_from_lua done\n";
1133 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1136 InventoryList *invlist = inv->getList(name);
1137 if(invlist == NULL){
1141 // Get the table insert function
1142 lua_getglobal(L, "table");
1143 lua_getfield(L, -1, "insert");
1144 int table_insert = lua_gettop(L);
1145 // Create and fill table
1147 int table = lua_gettop(L);
1148 for(u32 i=0; i<invlist->getSize(); i++){
1149 ItemStack item = invlist->getItem(i);
1150 lua_pushvalue(L, table_insert);
1151 lua_pushvalue(L, table);
1152 lua_pushstring(L, item.getItemString().c_str());
1153 if(lua_pcall(L, 2, 0, 0))
1154 script_error(L, "error: %s", lua_tostring(L, -1));
1159 Helpful macros for userdata classes
1162 #define method(class, name) {#name, class::l_##name}
1173 static const char className[];
1174 static const luaL_reg methods[];
1176 // Exported functions
1178 // garbage collector
1179 static int gc_object(lua_State *L)
1181 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1186 // is_empty(self) -> true/false
1187 static int l_is_empty(lua_State *L)
1189 LuaItemStack *o = checkobject(L, 1);
1190 ItemStack &item = o->m_stack;
1191 lua_pushboolean(L, item.empty());
1195 // get_name(self) -> string
1196 static int l_get_name(lua_State *L)
1198 LuaItemStack *o = checkobject(L, 1);
1199 ItemStack &item = o->m_stack;
1200 lua_pushstring(L, item.name.c_str());
1204 // get_count(self) -> number
1205 static int l_get_count(lua_State *L)
1207 LuaItemStack *o = checkobject(L, 1);
1208 ItemStack &item = o->m_stack;
1209 lua_pushinteger(L, item.count);
1213 // get_wear(self) -> number
1214 static int l_get_wear(lua_State *L)
1216 LuaItemStack *o = checkobject(L, 1);
1217 ItemStack &item = o->m_stack;
1218 lua_pushinteger(L, item.wear);
1222 // get_metadata(self) -> string
1223 static int l_get_metadata(lua_State *L)
1225 LuaItemStack *o = checkobject(L, 1);
1226 ItemStack &item = o->m_stack;
1227 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1231 // clear(self) -> true
1232 static int l_clear(lua_State *L)
1234 LuaItemStack *o = checkobject(L, 1);
1236 lua_pushboolean(L, true);
1240 // replace(self, itemstack or itemstring or table or nil) -> true
1241 static int l_replace(lua_State *L)
1243 LuaItemStack *o = checkobject(L, 1);
1244 o->m_stack = read_item(L, 2);
1245 lua_pushboolean(L, true);
1249 // to_string(self) -> string
1250 static int l_to_string(lua_State *L)
1252 LuaItemStack *o = checkobject(L, 1);
1253 std::string itemstring = o->m_stack.getItemString();
1254 lua_pushstring(L, itemstring.c_str());
1258 // to_table(self) -> table or nil
1259 static int l_to_table(lua_State *L)
1261 LuaItemStack *o = checkobject(L, 1);
1262 const ItemStack &item = o->m_stack;
1270 lua_pushstring(L, item.name.c_str());
1271 lua_setfield(L, -2, "name");
1272 lua_pushinteger(L, item.count);
1273 lua_setfield(L, -2, "count");
1274 lua_pushinteger(L, item.wear);
1275 lua_setfield(L, -2, "wear");
1276 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1277 lua_setfield(L, -2, "metadata");
1282 // get_stack_max(self) -> number
1283 static int l_get_stack_max(lua_State *L)
1285 LuaItemStack *o = checkobject(L, 1);
1286 ItemStack &item = o->m_stack;
1287 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1291 // get_free_space(self) -> number
1292 static int l_get_free_space(lua_State *L)
1294 LuaItemStack *o = checkobject(L, 1);
1295 ItemStack &item = o->m_stack;
1296 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1300 // is_known(self) -> true/false
1301 // Checks if the item is defined.
1302 static int l_is_known(lua_State *L)
1304 LuaItemStack *o = checkobject(L, 1);
1305 ItemStack &item = o->m_stack;
1306 bool is_known = item.isKnown(get_server(L)->idef());
1307 lua_pushboolean(L, is_known);
1311 // get_definition(self) -> table
1312 // Returns the item definition table from minetest.registered_items,
1313 // or a fallback one (name="unknown")
1314 static int l_get_definition(lua_State *L)
1316 LuaItemStack *o = checkobject(L, 1);
1317 ItemStack &item = o->m_stack;
1319 // Get minetest.registered_items[name]
1320 lua_getglobal(L, "minetest");
1321 lua_getfield(L, -1, "registered_items");
1322 luaL_checktype(L, -1, LUA_TTABLE);
1323 lua_getfield(L, -1, item.name.c_str());
1324 if(lua_isnil(L, -1))
1327 lua_getfield(L, -1, "unknown");
1332 // get_tool_capabilities(self) -> table
1333 // Returns the effective tool digging properties.
1334 // Returns those of the hand ("") if this item has none associated.
1335 static int l_get_tool_capabilities(lua_State *L)
1337 LuaItemStack *o = checkobject(L, 1);
1338 ItemStack &item = o->m_stack;
1339 const ToolCapabilities &prop =
1340 item.getToolCapabilities(get_server(L)->idef());
1341 push_tool_capabilities(L, prop);
1345 // add_wear(self, amount) -> true/false
1346 // The range for "amount" is [0,65535]. Wear is only added if the item
1347 // is a tool. Adding wear might destroy the item.
1348 // Returns true if the item is (or was) a tool.
1349 static int l_add_wear(lua_State *L)
1351 LuaItemStack *o = checkobject(L, 1);
1352 ItemStack &item = o->m_stack;
1353 int amount = lua_tointeger(L, 2);
1354 bool result = item.addWear(amount, get_server(L)->idef());
1355 lua_pushboolean(L, result);
1359 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1360 // Returns leftover item stack
1361 static int l_add_item(lua_State *L)
1363 LuaItemStack *o = checkobject(L, 1);
1364 ItemStack &item = o->m_stack;
1365 ItemStack newitem = read_item(L, 2);
1366 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1367 create(L, leftover);
1371 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1372 // First return value is true iff the new item fits fully into the stack
1373 // Second return value is the would-be-left-over item stack
1374 static int l_item_fits(lua_State *L)
1376 LuaItemStack *o = checkobject(L, 1);
1377 ItemStack &item = o->m_stack;
1378 ItemStack newitem = read_item(L, 2);
1380 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1381 lua_pushboolean(L, fits); // first return value
1382 create(L, restitem); // second return value
1386 // take_item(self, takecount=1) -> itemstack
1387 static int l_take_item(lua_State *L)
1389 LuaItemStack *o = checkobject(L, 1);
1390 ItemStack &item = o->m_stack;
1392 if(!lua_isnone(L, 2))
1393 takecount = lua_tointeger(L, 2);
1394 ItemStack taken = item.takeItem(takecount);
1399 // peek_item(self, peekcount=1) -> itemstack
1400 static int l_peek_item(lua_State *L)
1402 LuaItemStack *o = checkobject(L, 1);
1403 ItemStack &item = o->m_stack;
1405 if(!lua_isnone(L, 2))
1406 peekcount = lua_tointeger(L, 2);
1407 ItemStack peekaboo = item.peekItem(peekcount);
1408 create(L, peekaboo);
1413 LuaItemStack(const ItemStack &item):
1422 const ItemStack& getItem() const
1426 ItemStack& getItem()
1431 // LuaItemStack(itemstack or itemstring or table or nil)
1432 // Creates an LuaItemStack and leaves it on top of stack
1433 static int create_object(lua_State *L)
1435 ItemStack item = read_item(L, 1);
1436 LuaItemStack *o = new LuaItemStack(item);
1437 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1438 luaL_getmetatable(L, className);
1439 lua_setmetatable(L, -2);
1442 // Not callable from Lua
1443 static int create(lua_State *L, const ItemStack &item)
1445 LuaItemStack *o = new LuaItemStack(item);
1446 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1447 luaL_getmetatable(L, className);
1448 lua_setmetatable(L, -2);
1452 static LuaItemStack* checkobject(lua_State *L, int narg)
1454 luaL_checktype(L, narg, LUA_TUSERDATA);
1455 void *ud = luaL_checkudata(L, narg, className);
1456 if(!ud) luaL_typerror(L, narg, className);
1457 return *(LuaItemStack**)ud; // unbox pointer
1460 static void Register(lua_State *L)
1463 int methodtable = lua_gettop(L);
1464 luaL_newmetatable(L, className);
1465 int metatable = lua_gettop(L);
1467 lua_pushliteral(L, "__metatable");
1468 lua_pushvalue(L, methodtable);
1469 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1471 lua_pushliteral(L, "__index");
1472 lua_pushvalue(L, methodtable);
1473 lua_settable(L, metatable);
1475 lua_pushliteral(L, "__gc");
1476 lua_pushcfunction(L, gc_object);
1477 lua_settable(L, metatable);
1479 lua_pop(L, 1); // drop metatable
1481 luaL_openlib(L, 0, methods, 0); // fill methodtable
1482 lua_pop(L, 1); // drop methodtable
1484 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1485 lua_register(L, className, create_object);
1488 const char LuaItemStack::className[] = "ItemStack";
1489 const luaL_reg LuaItemStack::methods[] = {
1490 method(LuaItemStack, is_empty),
1491 method(LuaItemStack, get_name),
1492 method(LuaItemStack, get_count),
1493 method(LuaItemStack, get_wear),
1494 method(LuaItemStack, get_metadata),
1495 method(LuaItemStack, clear),
1496 method(LuaItemStack, replace),
1497 method(LuaItemStack, to_string),
1498 method(LuaItemStack, to_table),
1499 method(LuaItemStack, get_stack_max),
1500 method(LuaItemStack, get_free_space),
1501 method(LuaItemStack, is_known),
1502 method(LuaItemStack, get_definition),
1503 method(LuaItemStack, get_tool_capabilities),
1504 method(LuaItemStack, add_wear),
1505 method(LuaItemStack, add_item),
1506 method(LuaItemStack, item_fits),
1507 method(LuaItemStack, take_item),
1508 method(LuaItemStack, peek_item),
1512 static ItemStack read_item(lua_State *L, int index)
1515 index = lua_gettop(L) + 1 + index;
1517 if(lua_isnil(L, index))
1521 else if(lua_isuserdata(L, index))
1523 // Convert from LuaItemStack
1524 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1525 return o->getItem();
1527 else if(lua_isstring(L, index))
1529 // Convert from itemstring
1530 std::string itemstring = lua_tostring(L, index);
1531 IItemDefManager *idef = get_server(L)->idef();
1535 item.deSerialize(itemstring, idef);
1538 catch(SerializationError &e)
1540 infostream<<"WARNING: unable to create item from itemstring"
1541 <<": "<<itemstring<<std::endl;
1545 else if(lua_istable(L, index))
1547 // Convert from table
1548 IItemDefManager *idef = get_server(L)->idef();
1549 std::string name = getstringfield_default(L, index, "name", "");
1550 int count = getintfield_default(L, index, "count", 1);
1551 int wear = getintfield_default(L, index, "wear", 0);
1552 std::string metadata = getstringfield_default(L, index, "metadata", "");
1553 return ItemStack(name, count, wear, metadata, idef);
1557 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1568 InventoryLocation m_loc;
1570 static const char className[];
1571 static const luaL_reg methods[];
1573 static InvRef *checkobject(lua_State *L, int narg)
1575 luaL_checktype(L, narg, LUA_TUSERDATA);
1576 void *ud = luaL_checkudata(L, narg, className);
1577 if(!ud) luaL_typerror(L, narg, className);
1578 return *(InvRef**)ud; // unbox pointer
1581 static Inventory* getinv(lua_State *L, InvRef *ref)
1583 return get_server(L)->getInventory(ref->m_loc);
1586 static InventoryList* getlist(lua_State *L, InvRef *ref,
1587 const char *listname)
1589 Inventory *inv = getinv(L, ref);
1592 return inv->getList(listname);
1595 static void reportInventoryChange(lua_State *L, InvRef *ref)
1597 // Inform other things that the inventory has changed
1598 get_server(L)->setInventoryModified(ref->m_loc);
1601 // Exported functions
1603 // garbage collector
1604 static int gc_object(lua_State *L) {
1605 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1610 // get_size(self, listname)
1611 static int l_get_size(lua_State *L)
1613 InvRef *ref = checkobject(L, 1);
1614 const char *listname = luaL_checkstring(L, 2);
1615 InventoryList *list = getlist(L, ref, listname);
1617 lua_pushinteger(L, list->getSize());
1619 lua_pushinteger(L, 0);
1624 // set_size(self, listname, size)
1625 static int l_set_size(lua_State *L)
1627 InvRef *ref = checkobject(L, 1);
1628 const char *listname = luaL_checkstring(L, 2);
1629 int newsize = luaL_checknumber(L, 3);
1630 Inventory *inv = getinv(L, ref);
1632 inv->deleteList(listname);
1633 reportInventoryChange(L, ref);
1636 InventoryList *list = inv->getList(listname);
1638 list->setSize(newsize);
1640 list = inv->addList(listname, newsize);
1642 reportInventoryChange(L, ref);
1646 // get_stack(self, listname, i) -> itemstack
1647 static int l_get_stack(lua_State *L)
1649 InvRef *ref = checkobject(L, 1);
1650 const char *listname = luaL_checkstring(L, 2);
1651 int i = luaL_checknumber(L, 3) - 1;
1652 InventoryList *list = getlist(L, ref, listname);
1654 if(list != NULL && i >= 0 && i < (int) list->getSize())
1655 item = list->getItem(i);
1656 LuaItemStack::create(L, item);
1660 // set_stack(self, listname, i, stack) -> true/false
1661 static int l_set_stack(lua_State *L)
1663 InvRef *ref = checkobject(L, 1);
1664 const char *listname = luaL_checkstring(L, 2);
1665 int i = luaL_checknumber(L, 3) - 1;
1666 ItemStack newitem = read_item(L, 4);
1667 InventoryList *list = getlist(L, ref, listname);
1668 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1669 list->changeItem(i, newitem);
1670 reportInventoryChange(L, ref);
1671 lua_pushboolean(L, true);
1673 lua_pushboolean(L, false);
1678 // get_list(self, listname) -> list or nil
1679 static int l_get_list(lua_State *L)
1681 InvRef *ref = checkobject(L, 1);
1682 const char *listname = luaL_checkstring(L, 2);
1683 Inventory *inv = getinv(L, ref);
1684 inventory_get_list_to_lua(inv, listname, L);
1688 // set_list(self, listname, list)
1689 static int l_set_list(lua_State *L)
1691 InvRef *ref = checkobject(L, 1);
1692 const char *listname = luaL_checkstring(L, 2);
1693 Inventory *inv = getinv(L, ref);
1694 InventoryList *list = inv->getList(listname);
1696 inventory_set_list_from_lua(inv, listname, L, 3,
1699 inventory_set_list_from_lua(inv, listname, L, 3);
1700 reportInventoryChange(L, ref);
1704 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1705 // Returns the leftover stack
1706 static int l_add_item(lua_State *L)
1708 InvRef *ref = checkobject(L, 1);
1709 const char *listname = luaL_checkstring(L, 2);
1710 ItemStack item = read_item(L, 3);
1711 InventoryList *list = getlist(L, ref, listname);
1713 ItemStack leftover = list->addItem(item);
1714 if(leftover.count != item.count)
1715 reportInventoryChange(L, ref);
1716 LuaItemStack::create(L, leftover);
1718 LuaItemStack::create(L, item);
1723 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1724 // Returns true if the item completely fits into the list
1725 static int l_room_for_item(lua_State *L)
1727 InvRef *ref = checkobject(L, 1);
1728 const char *listname = luaL_checkstring(L, 2);
1729 ItemStack item = read_item(L, 3);
1730 InventoryList *list = getlist(L, ref, listname);
1732 lua_pushboolean(L, list->roomForItem(item));
1734 lua_pushboolean(L, false);
1739 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1740 // Returns true if the list contains the given count of the given item name
1741 static int l_contains_item(lua_State *L)
1743 InvRef *ref = checkobject(L, 1);
1744 const char *listname = luaL_checkstring(L, 2);
1745 ItemStack item = read_item(L, 3);
1746 InventoryList *list = getlist(L, ref, listname);
1748 lua_pushboolean(L, list->containsItem(item));
1750 lua_pushboolean(L, false);
1755 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1756 // Returns the items that were actually removed
1757 static int l_remove_item(lua_State *L)
1759 InvRef *ref = checkobject(L, 1);
1760 const char *listname = luaL_checkstring(L, 2);
1761 ItemStack item = read_item(L, 3);
1762 InventoryList *list = getlist(L, ref, listname);
1764 ItemStack removed = list->removeItem(item);
1765 if(!removed.empty())
1766 reportInventoryChange(L, ref);
1767 LuaItemStack::create(L, removed);
1769 LuaItemStack::create(L, ItemStack());
1775 InvRef(const InventoryLocation &loc):
1784 // Creates an InvRef and leaves it on top of stack
1785 // Not callable from Lua; all references are created on the C side.
1786 static void create(lua_State *L, const InventoryLocation &loc)
1788 InvRef *o = new InvRef(loc);
1789 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1790 luaL_getmetatable(L, className);
1791 lua_setmetatable(L, -2);
1793 static void createPlayer(lua_State *L, Player *player)
1795 InventoryLocation loc;
1796 loc.setPlayer(player->getName());
1799 static void createNodeMeta(lua_State *L, v3s16 p)
1801 InventoryLocation loc;
1806 static void Register(lua_State *L)
1809 int methodtable = lua_gettop(L);
1810 luaL_newmetatable(L, className);
1811 int metatable = lua_gettop(L);
1813 lua_pushliteral(L, "__metatable");
1814 lua_pushvalue(L, methodtable);
1815 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1817 lua_pushliteral(L, "__index");
1818 lua_pushvalue(L, methodtable);
1819 lua_settable(L, metatable);
1821 lua_pushliteral(L, "__gc");
1822 lua_pushcfunction(L, gc_object);
1823 lua_settable(L, metatable);
1825 lua_pop(L, 1); // drop metatable
1827 luaL_openlib(L, 0, methods, 0); // fill methodtable
1828 lua_pop(L, 1); // drop methodtable
1830 // Cannot be created from Lua
1831 //lua_register(L, className, create_object);
1834 const char InvRef::className[] = "InvRef";
1835 const luaL_reg InvRef::methods[] = {
1836 method(InvRef, get_size),
1837 method(InvRef, set_size),
1838 method(InvRef, get_stack),
1839 method(InvRef, set_stack),
1840 method(InvRef, get_list),
1841 method(InvRef, set_list),
1842 method(InvRef, add_item),
1843 method(InvRef, room_for_item),
1844 method(InvRef, contains_item),
1845 method(InvRef, remove_item),
1857 ServerEnvironment *m_env;
1859 static const char className[];
1860 static const luaL_reg methods[];
1862 static NodeMetaRef *checkobject(lua_State *L, int narg)
1864 luaL_checktype(L, narg, LUA_TUSERDATA);
1865 void *ud = luaL_checkudata(L, narg, className);
1866 if(!ud) luaL_typerror(L, narg, className);
1867 return *(NodeMetaRef**)ud; // unbox pointer
1870 static NodeMetadata* getmeta(NodeMetaRef *ref)
1872 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1876 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1878 NodeMetadata *meta = getmeta(ref);
1881 if(meta->typeId() != NODEMETA_GENERIC)
1883 return (IGenericNodeMetadata*)meta;
1886 static void reportMetadataChange(NodeMetaRef *ref)
1888 // Inform other things that the metadata has changed
1889 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1891 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1893 ref->m_env->getMap().dispatchEvent(&event);
1894 // Set the block to be saved
1895 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1897 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1898 "NodeMetaRef::reportMetadataChange");
1901 // Exported functions
1903 // garbage collector
1904 static int gc_object(lua_State *L) {
1905 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1911 static int l_get_type(lua_State *L)
1913 NodeMetaRef *ref = checkobject(L, 1);
1914 NodeMetadata *meta = getmeta(ref);
1920 lua_pushstring(L, meta->typeName());
1924 // allows_text_input(self)
1925 static int l_allows_text_input(lua_State *L)
1927 NodeMetaRef *ref = checkobject(L, 1);
1928 NodeMetadata *meta = getmeta(ref);
1929 if(meta == NULL) return 0;
1931 lua_pushboolean(L, meta->allowsTextInput());
1935 // set_text(self, text)
1936 static int l_set_text(lua_State *L)
1938 NodeMetaRef *ref = checkobject(L, 1);
1939 NodeMetadata *meta = getmeta(ref);
1940 if(meta == NULL) return 0;
1942 std::string text = luaL_checkstring(L, 2);
1943 meta->setText(text);
1944 reportMetadataChange(ref);
1949 static int l_get_text(lua_State *L)
1951 NodeMetaRef *ref = checkobject(L, 1);
1952 NodeMetadata *meta = getmeta(ref);
1953 if(meta == NULL) return 0;
1955 std::string text = meta->getText();
1956 lua_pushstring(L, text.c_str());
1961 static int l_get_owner(lua_State *L)
1963 NodeMetaRef *ref = checkobject(L, 1);
1964 NodeMetadata *meta = getmeta(ref);
1965 if(meta == NULL) return 0;
1967 std::string owner = meta->getOwner();
1968 lua_pushstring(L, owner.c_str());
1972 // set_owner(self, string)
1973 static int l_set_owner(lua_State *L)
1975 NodeMetaRef *ref = checkobject(L, 1);
1976 NodeMetadata *meta = getmeta(ref);
1977 if(meta == NULL) return 0;
1979 std::string owner = luaL_checkstring(L, 2);
1980 meta->setOwner(owner);
1981 reportMetadataChange(ref);
1985 // get_allow_removal(self)
1986 static int l_get_allow_removal(lua_State *L)
1988 NodeMetaRef *ref = checkobject(L, 1);
1989 NodeMetadata *meta = getmeta(ref);
1991 lua_pushboolean(L, true);
1995 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1999 /* IGenericNodeMetadata interface */
2001 // set_infotext(self, text)
2002 static int l_set_infotext(lua_State *L)
2004 NodeMetaRef *ref = checkobject(L, 1);
2005 NodeMetadata *meta = getmeta(ref);
2006 if(meta == NULL) return 0;
2008 std::string text = luaL_checkstring(L, 2);
2009 meta->setInfoText(text);
2010 reportMetadataChange(ref);
2014 // get_inventory(self)
2015 static int l_get_inventory(lua_State *L)
2017 NodeMetaRef *ref = checkobject(L, 1);
2018 NodeMetadata *meta = getmeta(ref);
2019 if(meta == NULL) return 0;
2021 InvRef::createNodeMeta(L, ref->m_p);
2025 // set_inventory_draw_spec(self, text)
2026 static int l_set_inventory_draw_spec(lua_State *L)
2028 NodeMetaRef *ref = checkobject(L, 1);
2029 NodeMetadata *meta = getmeta(ref);
2030 if(meta == NULL) return 0;
2032 std::string text = luaL_checkstring(L, 2);
2033 meta->setInventoryDrawSpec(text);
2034 reportMetadataChange(ref);
2038 // set_allow_text_input(self, text)
2039 static int l_set_allow_text_input(lua_State *L)
2041 NodeMetaRef *ref = checkobject(L, 1);
2042 NodeMetadata *meta = getmeta(ref);
2043 if(meta == NULL) return 0;
2045 bool b = lua_toboolean(L, 2);
2046 meta->setAllowTextInput(b);
2047 reportMetadataChange(ref);
2051 // set_allow_removal(self, text)
2052 static int l_set_allow_removal(lua_State *L)
2054 NodeMetaRef *ref = checkobject(L, 1);
2055 NodeMetadata *meta = getmeta(ref);
2056 if(meta == NULL) return 0;
2058 bool b = lua_toboolean(L, 2);
2059 meta->setRemovalDisabled(!b);
2060 reportMetadataChange(ref);
2064 // set_enforce_owner(self, text)
2065 static int l_set_enforce_owner(lua_State *L)
2067 NodeMetaRef *ref = checkobject(L, 1);
2068 NodeMetadata *meta = getmeta(ref);
2069 if(meta == NULL) return 0;
2071 bool b = lua_toboolean(L, 2);
2072 meta->setEnforceOwner(b);
2073 reportMetadataChange(ref);
2077 // is_inventory_modified(self)
2078 static int l_is_inventory_modified(lua_State *L)
2080 NodeMetaRef *ref = checkobject(L, 1);
2081 NodeMetadata *meta = getmeta(ref);
2082 if(meta == NULL) return 0;
2084 lua_pushboolean(L, meta->isInventoryModified());
2088 // reset_inventory_modified(self)
2089 static int l_reset_inventory_modified(lua_State *L)
2091 NodeMetaRef *ref = checkobject(L, 1);
2092 NodeMetadata *meta = getmeta(ref);
2093 if(meta == NULL) return 0;
2095 meta->resetInventoryModified();
2096 reportMetadataChange(ref);
2100 // is_text_modified(self)
2101 static int l_is_text_modified(lua_State *L)
2103 NodeMetaRef *ref = checkobject(L, 1);
2104 NodeMetadata *meta = getmeta(ref);
2105 if(meta == NULL) return 0;
2107 lua_pushboolean(L, meta->isTextModified());
2111 // reset_text_modified(self)
2112 static int l_reset_text_modified(lua_State *L)
2114 NodeMetaRef *ref = checkobject(L, 1);
2115 NodeMetadata *meta = getmeta(ref);
2116 if(meta == NULL) return 0;
2118 meta->resetTextModified();
2119 reportMetadataChange(ref);
2123 // set_string(self, name, var)
2124 static int l_set_string(lua_State *L)
2126 NodeMetaRef *ref = checkobject(L, 1);
2127 NodeMetadata *meta = getmeta(ref);
2128 if(meta == NULL) return 0;
2130 std::string name = luaL_checkstring(L, 2);
2132 const char *s = lua_tolstring(L, 3, &len);
2133 std::string str(s, len);
2134 meta->setString(name, str);
2135 reportMetadataChange(ref);
2139 // get_string(self, name)
2140 static int l_get_string(lua_State *L)
2142 NodeMetaRef *ref = checkobject(L, 1);
2143 NodeMetadata *meta = getmeta(ref);
2144 if(meta == NULL) return 0;
2146 std::string name = luaL_checkstring(L, 2);
2147 std::string str = meta->getString(name);
2148 lua_pushlstring(L, str.c_str(), str.size());
2153 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2163 // Creates an NodeMetaRef and leaves it on top of stack
2164 // Not callable from Lua; all references are created on the C side.
2165 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2167 NodeMetaRef *o = new NodeMetaRef(p, env);
2168 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2169 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2170 luaL_getmetatable(L, className);
2171 lua_setmetatable(L, -2);
2174 static void Register(lua_State *L)
2177 int methodtable = lua_gettop(L);
2178 luaL_newmetatable(L, className);
2179 int metatable = lua_gettop(L);
2181 lua_pushliteral(L, "__metatable");
2182 lua_pushvalue(L, methodtable);
2183 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2185 lua_pushliteral(L, "__index");
2186 lua_pushvalue(L, methodtable);
2187 lua_settable(L, metatable);
2189 lua_pushliteral(L, "__gc");
2190 lua_pushcfunction(L, gc_object);
2191 lua_settable(L, metatable);
2193 lua_pop(L, 1); // drop metatable
2195 luaL_openlib(L, 0, methods, 0); // fill methodtable
2196 lua_pop(L, 1); // drop methodtable
2198 // Cannot be created from Lua
2199 //lua_register(L, className, create_object);
2202 const char NodeMetaRef::className[] = "NodeMetaRef";
2203 const luaL_reg NodeMetaRef::methods[] = {
2204 method(NodeMetaRef, get_type),
2205 method(NodeMetaRef, allows_text_input),
2206 method(NodeMetaRef, set_text),
2207 method(NodeMetaRef, get_text),
2208 method(NodeMetaRef, get_owner),
2209 method(NodeMetaRef, set_owner),
2210 method(NodeMetaRef, get_allow_removal),
2211 method(NodeMetaRef, set_infotext),
2212 method(NodeMetaRef, get_inventory),
2213 method(NodeMetaRef, set_inventory_draw_spec),
2214 method(NodeMetaRef, set_allow_text_input),
2215 method(NodeMetaRef, set_allow_removal),
2216 method(NodeMetaRef, set_enforce_owner),
2217 method(NodeMetaRef, is_inventory_modified),
2218 method(NodeMetaRef, reset_inventory_modified),
2219 method(NodeMetaRef, is_text_modified),
2220 method(NodeMetaRef, reset_text_modified),
2221 method(NodeMetaRef, set_string),
2222 method(NodeMetaRef, get_string),
2233 ServerActiveObject *m_object;
2235 static const char className[];
2236 static const luaL_reg methods[];
2238 static ObjectRef *checkobject(lua_State *L, int narg)
2240 luaL_checktype(L, narg, LUA_TUSERDATA);
2241 void *ud = luaL_checkudata(L, narg, className);
2242 if(!ud) luaL_typerror(L, narg, className);
2243 return *(ObjectRef**)ud; // unbox pointer
2246 static ServerActiveObject* getobject(ObjectRef *ref)
2248 ServerActiveObject *co = ref->m_object;
2252 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2254 ServerActiveObject *obj = getobject(ref);
2257 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2259 return (LuaEntitySAO*)obj;
2262 static ServerRemotePlayer* getplayer(ObjectRef *ref)
2264 ServerActiveObject *obj = getobject(ref);
2267 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2269 return static_cast<ServerRemotePlayer*>(obj);
2272 // Exported functions
2274 // garbage collector
2275 static int gc_object(lua_State *L) {
2276 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2277 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2283 static int l_remove(lua_State *L)
2285 ObjectRef *ref = checkobject(L, 1);
2286 ServerActiveObject *co = getobject(ref);
2287 if(co == NULL) return 0;
2288 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2289 co->m_removed = true;
2294 // returns: {x=num, y=num, z=num}
2295 static int l_getpos(lua_State *L)
2297 ObjectRef *ref = checkobject(L, 1);
2298 ServerActiveObject *co = getobject(ref);
2299 if(co == NULL) return 0;
2300 v3f pos = co->getBasePosition() / BS;
2302 lua_pushnumber(L, pos.X);
2303 lua_setfield(L, -2, "x");
2304 lua_pushnumber(L, pos.Y);
2305 lua_setfield(L, -2, "y");
2306 lua_pushnumber(L, pos.Z);
2307 lua_setfield(L, -2, "z");
2311 // setpos(self, pos)
2312 static int l_setpos(lua_State *L)
2314 ObjectRef *ref = checkobject(L, 1);
2315 //LuaEntitySAO *co = getluaobject(ref);
2316 ServerActiveObject *co = getobject(ref);
2317 if(co == NULL) return 0;
2319 v3f pos = checkFloatPos(L, 2);
2322 // Move player if applicable
2323 ServerRemotePlayer *player = getplayer(ref);
2325 get_server(L)->SendMovePlayer(player);
2329 // moveto(self, pos, continuous=false)
2330 static int l_moveto(lua_State *L)
2332 ObjectRef *ref = checkobject(L, 1);
2333 //LuaEntitySAO *co = getluaobject(ref);
2334 ServerActiveObject *co = getobject(ref);
2335 if(co == NULL) return 0;
2337 v3f pos = checkFloatPos(L, 2);
2339 bool continuous = lua_toboolean(L, 3);
2341 co->moveTo(pos, continuous);
2345 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2346 static int l_punch(lua_State *L)
2348 ObjectRef *ref = checkobject(L, 1);
2349 ObjectRef *puncher_ref = checkobject(L, 2);
2350 ServerActiveObject *co = getobject(ref);
2351 ServerActiveObject *puncher = getobject(puncher_ref);
2352 if(co == NULL) return 0;
2353 if(puncher == NULL) return 0;
2354 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2355 v3f dir = read_v3f(L, 4);
2356 float time_from_last_punch = 1000000;
2357 if(lua_isnumber(L, 5))
2358 time_from_last_punch = lua_tonumber(L, 5);
2360 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2364 // right_click(self, clicker); clicker = an another ObjectRef
2365 static int l_right_click(lua_State *L)
2367 ObjectRef *ref = checkobject(L, 1);
2368 ObjectRef *ref2 = checkobject(L, 2);
2369 ServerActiveObject *co = getobject(ref);
2370 ServerActiveObject *co2 = getobject(ref2);
2371 if(co == NULL) return 0;
2372 if(co2 == NULL) return 0;
2374 co->rightClick(co2);
2379 // hp = number of hitpoints (2 * number of hearts)
2381 static int l_set_hp(lua_State *L)
2383 ObjectRef *ref = checkobject(L, 1);
2384 luaL_checknumber(L, 2);
2385 ServerActiveObject *co = getobject(ref);
2386 if(co == NULL) return 0;
2387 int hp = lua_tonumber(L, 2);
2388 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2389 <<" hp="<<hp<<std::endl;*/
2397 // returns: number of hitpoints (2 * number of hearts)
2398 // 0 if not applicable to this type of object
2399 static int l_get_hp(lua_State *L)
2401 ObjectRef *ref = checkobject(L, 1);
2402 ServerActiveObject *co = getobject(ref);
2403 if(co == NULL) return 0;
2404 int hp = co->getHP();
2405 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2406 <<" hp="<<hp<<std::endl;*/
2408 lua_pushnumber(L, hp);
2412 // get_inventory(self)
2413 static int l_get_inventory(lua_State *L)
2415 ObjectRef *ref = checkobject(L, 1);
2416 ServerActiveObject *co = getobject(ref);
2417 if(co == NULL) return 0;
2419 InventoryLocation loc = co->getInventoryLocation();
2420 if(get_server(L)->getInventory(loc) != NULL)
2421 InvRef::create(L, loc);
2427 // get_wield_list(self)
2428 static int l_get_wield_list(lua_State *L)
2430 ObjectRef *ref = checkobject(L, 1);
2431 ServerActiveObject *co = getobject(ref);
2432 if(co == NULL) return 0;
2434 lua_pushstring(L, co->getWieldList().c_str());
2438 // get_wield_index(self)
2439 static int l_get_wield_index(lua_State *L)
2441 ObjectRef *ref = checkobject(L, 1);
2442 ServerActiveObject *co = getobject(ref);
2443 if(co == NULL) return 0;
2445 lua_pushinteger(L, co->getWieldIndex() + 1);
2449 // get_wielded_item(self)
2450 static int l_get_wielded_item(lua_State *L)
2452 ObjectRef *ref = checkobject(L, 1);
2453 ServerActiveObject *co = getobject(ref);
2454 if(co == NULL) return 0;
2456 LuaItemStack::create(L, co->getWieldedItem());
2460 // set_wielded_item(self, itemstack or itemstring or table or nil)
2461 static int l_set_wielded_item(lua_State *L)
2463 ObjectRef *ref = checkobject(L, 1);
2464 ServerActiveObject *co = getobject(ref);
2465 if(co == NULL) return 0;
2467 ItemStack item = read_item(L, 2);
2468 bool success = co->setWieldedItem(item);
2469 lua_pushboolean(L, success);
2473 /* LuaEntitySAO-only */
2475 // setvelocity(self, {x=num, y=num, z=num})
2476 static int l_setvelocity(lua_State *L)
2478 ObjectRef *ref = checkobject(L, 1);
2479 LuaEntitySAO *co = getluaobject(ref);
2480 if(co == NULL) return 0;
2482 v3f pos = checkFloatPos(L, 2);
2484 co->setVelocity(pos);
2488 // getvelocity(self)
2489 static int l_getvelocity(lua_State *L)
2491 ObjectRef *ref = checkobject(L, 1);
2492 LuaEntitySAO *co = getluaobject(ref);
2493 if(co == NULL) return 0;
2495 v3f v = co->getVelocity();
2500 // setacceleration(self, {x=num, y=num, z=num})
2501 static int l_setacceleration(lua_State *L)
2503 ObjectRef *ref = checkobject(L, 1);
2504 LuaEntitySAO *co = getluaobject(ref);
2505 if(co == NULL) return 0;
2507 v3f pos = checkFloatPos(L, 2);
2509 co->setAcceleration(pos);
2513 // getacceleration(self)
2514 static int l_getacceleration(lua_State *L)
2516 ObjectRef *ref = checkobject(L, 1);
2517 LuaEntitySAO *co = getluaobject(ref);
2518 if(co == NULL) return 0;
2520 v3f v = co->getAcceleration();
2525 // setyaw(self, radians)
2526 static int l_setyaw(lua_State *L)
2528 ObjectRef *ref = checkobject(L, 1);
2529 LuaEntitySAO *co = getluaobject(ref);
2530 if(co == NULL) return 0;
2532 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2539 static int l_getyaw(lua_State *L)
2541 ObjectRef *ref = checkobject(L, 1);
2542 LuaEntitySAO *co = getluaobject(ref);
2543 if(co == NULL) return 0;
2545 float yaw = co->getYaw() * core::DEGTORAD;
2546 lua_pushnumber(L, yaw);
2550 // settexturemod(self, mod)
2551 static int l_settexturemod(lua_State *L)
2553 ObjectRef *ref = checkobject(L, 1);
2554 LuaEntitySAO *co = getluaobject(ref);
2555 if(co == NULL) return 0;
2557 std::string mod = luaL_checkstring(L, 2);
2558 co->setTextureMod(mod);
2562 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2563 // select_horiz_by_yawpitch=false)
2564 static int l_setsprite(lua_State *L)
2566 ObjectRef *ref = checkobject(L, 1);
2567 LuaEntitySAO *co = getluaobject(ref);
2568 if(co == NULL) return 0;
2571 if(!lua_isnil(L, 2))
2572 p = read_v2s16(L, 2);
2574 if(!lua_isnil(L, 3))
2575 num_frames = lua_tonumber(L, 3);
2576 float framelength = 0.2;
2577 if(!lua_isnil(L, 4))
2578 framelength = lua_tonumber(L, 4);
2579 bool select_horiz_by_yawpitch = false;
2580 if(!lua_isnil(L, 5))
2581 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2582 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2586 // set_armor_groups(self, groups)
2587 static int l_set_armor_groups(lua_State *L)
2589 ObjectRef *ref = checkobject(L, 1);
2590 LuaEntitySAO *co = getluaobject(ref);
2591 if(co == NULL) return 0;
2593 ItemGroupList groups;
2594 read_groups(L, 2, groups);
2595 co->setArmorGroups(groups);
2600 // get_entity_name(self)
2601 static int l_get_entity_name(lua_State *L)
2603 ObjectRef *ref = checkobject(L, 1);
2604 LuaEntitySAO *co = getluaobject(ref);
2605 if(co == NULL) return 0;
2607 std::string name = co->getName();
2608 lua_pushstring(L, name.c_str());
2612 // get_luaentity(self)
2613 static int l_get_luaentity(lua_State *L)
2615 ObjectRef *ref = checkobject(L, 1);
2616 LuaEntitySAO *co = getluaobject(ref);
2617 if(co == NULL) return 0;
2619 luaentity_get(L, co->getId());
2625 // get_player_name(self)
2626 static int l_get_player_name(lua_State *L)
2628 ObjectRef *ref = checkobject(L, 1);
2629 ServerRemotePlayer *player = getplayer(ref);
2635 lua_pushstring(L, player->getName());
2639 // get_look_dir(self)
2640 static int l_get_look_dir(lua_State *L)
2642 ObjectRef *ref = checkobject(L, 1);
2643 ServerRemotePlayer *player = getplayer(ref);
2644 if(player == NULL) return 0;
2646 float pitch = player->getRadPitch();
2647 float yaw = player->getRadYaw();
2648 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2653 // get_look_pitch(self)
2654 static int l_get_look_pitch(lua_State *L)
2656 ObjectRef *ref = checkobject(L, 1);
2657 ServerRemotePlayer *player = getplayer(ref);
2658 if(player == NULL) return 0;
2660 lua_pushnumber(L, player->getRadPitch());
2664 // get_look_yaw(self)
2665 static int l_get_look_yaw(lua_State *L)
2667 ObjectRef *ref = checkobject(L, 1);
2668 ServerRemotePlayer *player = getplayer(ref);
2669 if(player == NULL) return 0;
2671 lua_pushnumber(L, player->getRadYaw());
2676 ObjectRef(ServerActiveObject *object):
2679 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2685 infostream<<"ObjectRef destructing for id="
2686 <<m_object->getId()<<std::endl;
2688 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2691 // Creates an ObjectRef and leaves it on top of stack
2692 // Not callable from Lua; all references are created on the C side.
2693 static void create(lua_State *L, ServerActiveObject *object)
2695 ObjectRef *o = new ObjectRef(object);
2696 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2697 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2698 luaL_getmetatable(L, className);
2699 lua_setmetatable(L, -2);
2702 static void set_null(lua_State *L)
2704 ObjectRef *o = checkobject(L, -1);
2708 static void Register(lua_State *L)
2711 int methodtable = lua_gettop(L);
2712 luaL_newmetatable(L, className);
2713 int metatable = lua_gettop(L);
2715 lua_pushliteral(L, "__metatable");
2716 lua_pushvalue(L, methodtable);
2717 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2719 lua_pushliteral(L, "__index");
2720 lua_pushvalue(L, methodtable);
2721 lua_settable(L, metatable);
2723 lua_pushliteral(L, "__gc");
2724 lua_pushcfunction(L, gc_object);
2725 lua_settable(L, metatable);
2727 lua_pop(L, 1); // drop metatable
2729 luaL_openlib(L, 0, methods, 0); // fill methodtable
2730 lua_pop(L, 1); // drop methodtable
2732 // Cannot be created from Lua
2733 //lua_register(L, className, create_object);
2736 const char ObjectRef::className[] = "ObjectRef";
2737 const luaL_reg ObjectRef::methods[] = {
2738 // ServerActiveObject
2739 method(ObjectRef, remove),
2740 method(ObjectRef, getpos),
2741 method(ObjectRef, setpos),
2742 method(ObjectRef, moveto),
2743 method(ObjectRef, punch),
2744 method(ObjectRef, right_click),
2745 method(ObjectRef, set_hp),
2746 method(ObjectRef, get_hp),
2747 method(ObjectRef, get_inventory),
2748 method(ObjectRef, get_wield_list),
2749 method(ObjectRef, get_wield_index),
2750 method(ObjectRef, get_wielded_item),
2751 method(ObjectRef, set_wielded_item),
2752 // LuaEntitySAO-only
2753 method(ObjectRef, setvelocity),
2754 method(ObjectRef, getvelocity),
2755 method(ObjectRef, setacceleration),
2756 method(ObjectRef, getacceleration),
2757 method(ObjectRef, setyaw),
2758 method(ObjectRef, getyaw),
2759 method(ObjectRef, settexturemod),
2760 method(ObjectRef, setsprite),
2761 method(ObjectRef, set_armor_groups),
2762 method(ObjectRef, get_entity_name),
2763 method(ObjectRef, get_luaentity),
2765 method(ObjectRef, get_player_name),
2766 method(ObjectRef, get_look_dir),
2767 method(ObjectRef, get_look_pitch),
2768 method(ObjectRef, get_look_yaw),
2772 // Creates a new anonymous reference if id=0
2773 static void objectref_get_or_create(lua_State *L,
2774 ServerActiveObject *cobj)
2776 if(cobj->getId() == 0){
2777 ObjectRef::create(L, cobj);
2779 objectref_get(L, cobj->getId());
2790 ServerEnvironment *m_env;
2792 static const char className[];
2793 static const luaL_reg methods[];
2795 static EnvRef *checkobject(lua_State *L, int narg)
2797 luaL_checktype(L, narg, LUA_TUSERDATA);
2798 void *ud = luaL_checkudata(L, narg, className);
2799 if(!ud) luaL_typerror(L, narg, className);
2800 return *(EnvRef**)ud; // unbox pointer
2803 // Exported functions
2805 // EnvRef:set_node(pos, node)
2806 // pos = {x=num, y=num, z=num}
2807 static int l_set_node(lua_State *L)
2809 //infostream<<"EnvRef::l_set_node()"<<std::endl;
2810 EnvRef *o = checkobject(L, 1);
2811 ServerEnvironment *env = o->m_env;
2812 if(env == NULL) return 0;
2814 v3s16 pos = read_v3s16(L, 2);
2816 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2818 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2819 lua_pushboolean(L, succeeded);
2823 static int l_add_node(lua_State *L)
2825 return l_set_node(L);
2828 // EnvRef:remove_node(pos)
2829 // pos = {x=num, y=num, z=num}
2830 static int l_remove_node(lua_State *L)
2832 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2833 EnvRef *o = checkobject(L, 1);
2834 ServerEnvironment *env = o->m_env;
2835 if(env == NULL) return 0;
2837 v3s16 pos = read_v3s16(L, 2);
2839 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2840 lua_pushboolean(L, succeeded);
2844 // EnvRef:get_node(pos)
2845 // pos = {x=num, y=num, z=num}
2846 static int l_get_node(lua_State *L)
2848 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2849 EnvRef *o = checkobject(L, 1);
2850 ServerEnvironment *env = o->m_env;
2851 if(env == NULL) return 0;
2853 v3s16 pos = read_v3s16(L, 2);
2855 MapNode n = env->getMap().getNodeNoEx(pos);
2857 pushnode(L, n, env->getGameDef()->ndef());
2861 // EnvRef:get_node_or_nil(pos)
2862 // pos = {x=num, y=num, z=num}
2863 static int l_get_node_or_nil(lua_State *L)
2865 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2866 EnvRef *o = checkobject(L, 1);
2867 ServerEnvironment *env = o->m_env;
2868 if(env == NULL) return 0;
2870 v3s16 pos = read_v3s16(L, 2);
2873 MapNode n = env->getMap().getNode(pos);
2875 pushnode(L, n, env->getGameDef()->ndef());
2877 } catch(InvalidPositionException &e)
2884 // EnvRef:get_node_light(pos, timeofday)
2885 // pos = {x=num, y=num, z=num}
2886 // timeofday: nil = current time, 0 = night, 0.5 = day
2887 static int l_get_node_light(lua_State *L)
2889 EnvRef *o = checkobject(L, 1);
2890 ServerEnvironment *env = o->m_env;
2891 if(env == NULL) return 0;
2893 v3s16 pos = read_v3s16(L, 2);
2894 u32 time_of_day = env->getTimeOfDay();
2895 if(lua_isnumber(L, 3))
2896 time_of_day = 24000.0 * lua_tonumber(L, 3);
2897 time_of_day %= 24000;
2898 u32 dnr = time_to_daynight_ratio(time_of_day);
2899 MapNode n = env->getMap().getNodeNoEx(pos);
2901 MapNode n = env->getMap().getNode(pos);
2902 INodeDefManager *ndef = env->getGameDef()->ndef();
2903 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2905 } catch(InvalidPositionException &e)
2912 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2913 // pos = {x=num, y=num, z=num}
2914 static int l_add_entity(lua_State *L)
2916 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2917 EnvRef *o = checkobject(L, 1);
2918 ServerEnvironment *env = o->m_env;
2919 if(env == NULL) return 0;
2921 v3f pos = checkFloatPos(L, 2);
2923 const char *name = luaL_checkstring(L, 3);
2925 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2926 int objectid = env->addActiveObject(obj);
2927 // If failed to add, return nothing (reads as nil)
2931 objectref_get_or_create(L, obj);
2935 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2936 // pos = {x=num, y=num, z=num}
2937 static int l_add_item(lua_State *L)
2939 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2940 EnvRef *o = checkobject(L, 1);
2941 ServerEnvironment *env = o->m_env;
2942 if(env == NULL) return 0;
2944 v3f pos = checkFloatPos(L, 2);
2946 ItemStack item = read_item(L, 3);
2947 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2950 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2951 int objectid = env->addActiveObject(obj);
2952 // If failed to add, return nothing (reads as nil)
2956 objectref_get_or_create(L, obj);
2960 // EnvRef:add_rat(pos)
2961 // pos = {x=num, y=num, z=num}
2962 static int l_add_rat(lua_State *L)
2964 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2965 <<" Doing nothing."<<std::endl;
2969 // EnvRef:add_firefly(pos)
2970 // pos = {x=num, y=num, z=num}
2971 static int l_add_firefly(lua_State *L)
2973 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2974 <<" Doing nothing."<<std::endl;
2978 // EnvRef:get_meta(pos)
2979 static int l_get_meta(lua_State *L)
2981 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2982 EnvRef *o = checkobject(L, 1);
2983 ServerEnvironment *env = o->m_env;
2984 if(env == NULL) return 0;
2986 v3s16 p = read_v3s16(L, 2);
2987 NodeMetaRef::create(L, p, env);
2991 // EnvRef:get_player_by_name(name)
2992 static int l_get_player_by_name(lua_State *L)
2994 EnvRef *o = checkobject(L, 1);
2995 ServerEnvironment *env = o->m_env;
2996 if(env == NULL) return 0;
2998 const char *name = luaL_checkstring(L, 2);
2999 ServerRemotePlayer *player =
3000 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
3005 // Put player on stack
3006 objectref_get_or_create(L, player);
3010 // EnvRef:get_objects_inside_radius(pos, radius)
3011 static int l_get_objects_inside_radius(lua_State *L)
3013 // Get the table insert function
3014 lua_getglobal(L, "table");
3015 lua_getfield(L, -1, "insert");
3016 int table_insert = lua_gettop(L);
3018 EnvRef *o = checkobject(L, 1);
3019 ServerEnvironment *env = o->m_env;
3020 if(env == NULL) return 0;
3022 v3f pos = checkFloatPos(L, 2);
3023 float radius = luaL_checknumber(L, 3) * BS;
3024 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3026 int table = lua_gettop(L);
3027 for(std::set<u16>::const_iterator
3028 i = ids.begin(); i != ids.end(); i++){
3029 ServerActiveObject *obj = env->getActiveObject(*i);
3030 // Insert object reference into table
3031 lua_pushvalue(L, table_insert);
3032 lua_pushvalue(L, table);
3033 objectref_get_or_create(L, obj);
3034 if(lua_pcall(L, 2, 0, 0))
3035 script_error(L, "error: %s", lua_tostring(L, -1));
3040 // EnvRef:set_timeofday(val)
3042 static int l_set_timeofday(lua_State *L)
3044 EnvRef *o = checkobject(L, 1);
3045 ServerEnvironment *env = o->m_env;
3046 if(env == NULL) return 0;
3048 float timeofday_f = luaL_checknumber(L, 2);
3049 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3050 int timeofday_mh = (int)(timeofday_f * 24000.0);
3051 // This should be set directly in the environment but currently
3052 // such changes aren't immediately sent to the clients, so call
3053 // the server instead.
3054 //env->setTimeOfDay(timeofday_mh);
3055 get_server(L)->setTimeOfDay(timeofday_mh);
3059 // EnvRef:get_timeofday() -> 0...1
3060 static int l_get_timeofday(lua_State *L)
3062 EnvRef *o = checkobject(L, 1);
3063 ServerEnvironment *env = o->m_env;
3064 if(env == NULL) return 0;
3066 int timeofday_mh = env->getTimeOfDay();
3067 float timeofday_f = (float)timeofday_mh / 24000.0;
3068 lua_pushnumber(L, timeofday_f);
3072 static int gc_object(lua_State *L) {
3073 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3079 EnvRef(ServerEnvironment *env):
3082 //infostream<<"EnvRef created"<<std::endl;
3087 //infostream<<"EnvRef destructing"<<std::endl;
3090 // Creates an EnvRef and leaves it on top of stack
3091 // Not callable from Lua; all references are created on the C side.
3092 static void create(lua_State *L, ServerEnvironment *env)
3094 EnvRef *o = new EnvRef(env);
3095 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3096 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3097 luaL_getmetatable(L, className);
3098 lua_setmetatable(L, -2);
3101 static void set_null(lua_State *L)
3103 EnvRef *o = checkobject(L, -1);
3107 static void Register(lua_State *L)
3110 int methodtable = lua_gettop(L);
3111 luaL_newmetatable(L, className);
3112 int metatable = lua_gettop(L);
3114 lua_pushliteral(L, "__metatable");
3115 lua_pushvalue(L, methodtable);
3116 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3118 lua_pushliteral(L, "__index");
3119 lua_pushvalue(L, methodtable);
3120 lua_settable(L, metatable);
3122 lua_pushliteral(L, "__gc");
3123 lua_pushcfunction(L, gc_object);
3124 lua_settable(L, metatable);
3126 lua_pop(L, 1); // drop metatable
3128 luaL_openlib(L, 0, methods, 0); // fill methodtable
3129 lua_pop(L, 1); // drop methodtable
3131 // Cannot be created from Lua
3132 //lua_register(L, className, create_object);
3135 const char EnvRef::className[] = "EnvRef";
3136 const luaL_reg EnvRef::methods[] = {
3137 method(EnvRef, set_node),
3138 method(EnvRef, add_node),
3139 method(EnvRef, remove_node),
3140 method(EnvRef, get_node),
3141 method(EnvRef, get_node_or_nil),
3142 method(EnvRef, get_node_light),
3143 method(EnvRef, add_entity),
3144 method(EnvRef, add_item),
3145 method(EnvRef, add_rat),
3146 method(EnvRef, add_firefly),
3147 method(EnvRef, get_meta),
3148 method(EnvRef, get_player_by_name),
3149 method(EnvRef, get_objects_inside_radius),
3150 method(EnvRef, set_timeofday),
3151 method(EnvRef, get_timeofday),
3159 class LuaPseudoRandom
3162 PseudoRandom m_pseudo;
3164 static const char className[];
3165 static const luaL_reg methods[];
3167 // Exported functions
3169 // garbage collector
3170 static int gc_object(lua_State *L)
3172 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3177 // next(self, min=0, max=32767) -> get next value
3178 static int l_next(lua_State *L)
3180 LuaPseudoRandom *o = checkobject(L, 1);
3183 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3184 if(!lua_isnil(L, 2))
3185 min = luaL_checkinteger(L, 2);
3186 if(!lua_isnil(L, 3))
3187 max = luaL_checkinteger(L, 3);
3188 if(max - min != 32767 && max - min > 32767/5)
3189 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.");
3190 PseudoRandom &pseudo = o->m_pseudo;
3191 int val = pseudo.next();
3192 val = (val % (max-min+1)) + min;
3193 lua_pushinteger(L, val);
3198 LuaPseudoRandom(int seed):
3207 const PseudoRandom& getItem() const
3211 PseudoRandom& getItem()
3216 // LuaPseudoRandom(seed)
3217 // Creates an LuaPseudoRandom and leaves it on top of stack
3218 static int create_object(lua_State *L)
3220 int seed = luaL_checknumber(L, 1);
3221 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3222 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3223 luaL_getmetatable(L, className);
3224 lua_setmetatable(L, -2);
3228 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3230 luaL_checktype(L, narg, LUA_TUSERDATA);
3231 void *ud = luaL_checkudata(L, narg, className);
3232 if(!ud) luaL_typerror(L, narg, className);
3233 return *(LuaPseudoRandom**)ud; // unbox pointer
3236 static void Register(lua_State *L)
3239 int methodtable = lua_gettop(L);
3240 luaL_newmetatable(L, className);
3241 int metatable = lua_gettop(L);
3243 lua_pushliteral(L, "__metatable");
3244 lua_pushvalue(L, methodtable);
3245 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3247 lua_pushliteral(L, "__index");
3248 lua_pushvalue(L, methodtable);
3249 lua_settable(L, metatable);
3251 lua_pushliteral(L, "__gc");
3252 lua_pushcfunction(L, gc_object);
3253 lua_settable(L, metatable);
3255 lua_pop(L, 1); // drop metatable
3257 luaL_openlib(L, 0, methods, 0); // fill methodtable
3258 lua_pop(L, 1); // drop methodtable
3260 // Can be created from Lua (LuaPseudoRandom(seed))
3261 lua_register(L, className, create_object);
3264 const char LuaPseudoRandom::className[] = "PseudoRandom";
3265 const luaL_reg LuaPseudoRandom::methods[] = {
3266 method(LuaPseudoRandom, next),
3274 class LuaABM : public ActiveBlockModifier
3280 std::set<std::string> m_trigger_contents;
3281 std::set<std::string> m_required_neighbors;
3282 float m_trigger_interval;
3283 u32 m_trigger_chance;
3285 LuaABM(lua_State *L, int id,
3286 const std::set<std::string> &trigger_contents,
3287 const std::set<std::string> &required_neighbors,
3288 float trigger_interval, u32 trigger_chance):
3291 m_trigger_contents(trigger_contents),
3292 m_required_neighbors(required_neighbors),
3293 m_trigger_interval(trigger_interval),
3294 m_trigger_chance(trigger_chance)
3297 virtual std::set<std::string> getTriggerContents()
3299 return m_trigger_contents;
3301 virtual std::set<std::string> getRequiredNeighbors()
3303 return m_required_neighbors;
3305 virtual float getTriggerInterval()
3307 return m_trigger_interval;
3309 virtual u32 getTriggerChance()
3311 return m_trigger_chance;
3313 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3314 u32 active_object_count, u32 active_object_count_wider)
3316 lua_State *L = m_lua;
3319 assert(lua_checkstack(L, 20));
3320 StackUnroller stack_unroller(L);
3322 // Get minetest.registered_abms
3323 lua_getglobal(L, "minetest");
3324 lua_getfield(L, -1, "registered_abms");
3325 luaL_checktype(L, -1, LUA_TTABLE);
3326 int registered_abms = lua_gettop(L);
3328 // Get minetest.registered_abms[m_id]
3329 lua_pushnumber(L, m_id);
3330 lua_gettable(L, registered_abms);
3331 if(lua_isnil(L, -1))
3335 luaL_checktype(L, -1, LUA_TTABLE);
3336 lua_getfield(L, -1, "action");
3337 luaL_checktype(L, -1, LUA_TFUNCTION);
3339 pushnode(L, n, env->getGameDef()->ndef());
3340 lua_pushnumber(L, active_object_count);
3341 lua_pushnumber(L, active_object_count_wider);
3342 if(lua_pcall(L, 4, 0, 0))
3343 script_error(L, "error: %s", lua_tostring(L, -1));
3351 static void read_server_sound_params(lua_State *L, int index,
3352 ServerSoundParams ¶ms)
3355 index = lua_gettop(L) + 1 + index;
3357 params = ServerSoundParams();
3358 if(lua_istable(L, index)){
3359 getfloatfield(L, index, "gain", params.gain);
3360 getstringfield(L, index, "to_player", params.to_player);
3361 lua_getfield(L, index, "pos");
3362 if(!lua_isnil(L, -1)){
3363 v3f p = read_v3f(L, -1)*BS;
3365 params.type = ServerSoundParams::SSP_POSITIONAL;
3368 lua_getfield(L, index, "object");
3369 if(!lua_isnil(L, -1)){
3370 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3371 ServerActiveObject *sao = ObjectRef::getobject(ref);
3373 params.object = sao->getId();
3374 params.type = ServerSoundParams::SSP_OBJECT;
3378 params.max_hear_distance = BS*getfloatfield_default(L, index,
3379 "max_hear_distance", params.max_hear_distance/BS);
3380 getboolfield(L, index, "loop", params.loop);
3389 // Writes a line to dstream
3390 static int l_debug(lua_State *L)
3392 std::string text = lua_tostring(L, 1);
3393 dstream << text << std::endl;
3397 // log([level,] text)
3398 // Writes a line to the logger.
3399 // The one-argument version logs to infostream.
3400 // The two-argument version accept a log level: error, action, info, or verbose.
3401 static int l_log(lua_State *L)
3404 LogMessageLevel level = LMT_INFO;
3405 if(lua_isnone(L, 2))
3407 text = lua_tostring(L, 1);
3411 std::string levelname = lua_tostring(L, 1);
3412 text = lua_tostring(L, 2);
3413 if(levelname == "error")
3415 else if(levelname == "action")
3417 else if(levelname == "verbose")
3418 level = LMT_VERBOSE;
3420 log_printline(level, text);
3424 // register_item_raw({lots of stuff})
3425 static int l_register_item_raw(lua_State *L)
3427 luaL_checktype(L, 1, LUA_TTABLE);
3430 // Get the writable item and node definition managers from the server
3431 IWritableItemDefManager *idef =
3432 get_server(L)->getWritableItemDefManager();
3433 IWritableNodeDefManager *ndef =
3434 get_server(L)->getWritableNodeDefManager();
3436 // Check if name is defined
3437 lua_getfield(L, table, "name");
3438 if(lua_isstring(L, -1)){
3439 std::string name = lua_tostring(L, -1);
3440 verbosestream<<"register_item_raw: "<<name<<std::endl;
3442 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3445 // Check if on_use is defined
3447 // Read the item definition and register it
3448 ItemDefinition def = read_item_definition(L, table);
3449 idef->registerItem(def);
3451 // Read the node definition (content features) and register it
3452 if(def.type == ITEM_NODE)
3454 ContentFeatures f = read_content_features(L, table);
3455 ndef->set(f.name, f);
3458 return 0; /* number of results */
3461 // register_alias_raw(name, convert_to_name)
3462 static int l_register_alias_raw(lua_State *L)
3464 std::string name = luaL_checkstring(L, 1);
3465 std::string convert_to = luaL_checkstring(L, 2);
3467 // Get the writable item definition manager from the server
3468 IWritableItemDefManager *idef =
3469 get_server(L)->getWritableItemDefManager();
3471 idef->registerAlias(name, convert_to);
3473 return 0; /* number of results */
3476 // helper for register_craft
3477 static bool read_craft_recipe_shaped(lua_State *L, int index,
3478 int &width, std::vector<std::string> &recipe)
3481 index = lua_gettop(L) + 1 + index;
3483 if(!lua_istable(L, index))
3488 while(lua_next(L, index) != 0){
3490 // key at index -2 and value at index -1
3491 if(!lua_istable(L, -1))
3493 int table2 = lua_gettop(L);
3495 while(lua_next(L, table2) != 0){
3496 // key at index -2 and value at index -1
3497 if(!lua_isstring(L, -1))
3499 recipe.push_back(lua_tostring(L, -1));
3500 // removes value, keeps key for next iteration
3507 if(colcount != width)
3510 // removes value, keeps key for next iteration
3517 // helper for register_craft
3518 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3519 std::vector<std::string> &recipe)
3522 index = lua_gettop(L) + 1 + index;
3524 if(!lua_istable(L, index))
3528 while(lua_next(L, index) != 0){
3529 // key at index -2 and value at index -1
3530 if(!lua_isstring(L, -1))
3532 recipe.push_back(lua_tostring(L, -1));
3533 // removes value, keeps key for next iteration
3539 // helper for register_craft
3540 static bool read_craft_replacements(lua_State *L, int index,
3541 CraftReplacements &replacements)
3544 index = lua_gettop(L) + 1 + index;
3546 if(!lua_istable(L, index))
3550 while(lua_next(L, index) != 0){
3551 // key at index -2 and value at index -1
3552 if(!lua_istable(L, -1))
3554 lua_rawgeti(L, -1, 1);
3555 if(!lua_isstring(L, -1))
3557 std::string replace_from = lua_tostring(L, -1);
3559 lua_rawgeti(L, -1, 2);
3560 if(!lua_isstring(L, -1))
3562 std::string replace_to = lua_tostring(L, -1);
3564 replacements.pairs.push_back(
3565 std::make_pair(replace_from, replace_to));
3566 // removes value, keeps key for next iteration
3571 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3572 static int l_register_craft(lua_State *L)
3574 //infostream<<"register_craft"<<std::endl;
3575 luaL_checktype(L, 1, LUA_TTABLE);
3578 // Get the writable craft definition manager from the server
3579 IWritableCraftDefManager *craftdef =
3580 get_server(L)->getWritableCraftDefManager();
3582 std::string type = getstringfield_default(L, table, "type", "shaped");
3585 CraftDefinitionShaped
3587 if(type == "shaped"){
3588 std::string output = getstringfield_default(L, table, "output", "");
3590 throw LuaError(L, "Crafting definition is missing an output");
3593 std::vector<std::string> recipe;
3594 lua_getfield(L, table, "recipe");
3595 if(lua_isnil(L, -1))
3596 throw LuaError(L, "Crafting definition is missing a recipe"
3597 " (output=\"" + output + "\")");
3598 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3599 throw LuaError(L, "Invalid crafting recipe"
3600 " (output=\"" + output + "\")");
3602 CraftReplacements replacements;
3603 lua_getfield(L, table, "replacements");
3604 if(!lua_isnil(L, -1))
3606 if(!read_craft_replacements(L, -1, replacements))
3607 throw LuaError(L, "Invalid replacements"
3608 " (output=\"" + output + "\")");
3611 CraftDefinition *def = new CraftDefinitionShaped(
3612 output, width, recipe, replacements);
3613 craftdef->registerCraft(def);
3616 CraftDefinitionShapeless
3618 else if(type == "shapeless"){
3619 std::string output = getstringfield_default(L, table, "output", "");
3621 throw LuaError(L, "Crafting definition (shapeless)"
3622 " is missing an output");
3624 std::vector<std::string> recipe;
3625 lua_getfield(L, table, "recipe");
3626 if(lua_isnil(L, -1))
3627 throw LuaError(L, "Crafting definition (shapeless)"
3628 " is missing a recipe"
3629 " (output=\"" + output + "\")");
3630 if(!read_craft_recipe_shapeless(L, -1, recipe))
3631 throw LuaError(L, "Invalid crafting recipe"
3632 " (output=\"" + output + "\")");
3634 CraftReplacements replacements;
3635 lua_getfield(L, table, "replacements");
3636 if(!lua_isnil(L, -1))
3638 if(!read_craft_replacements(L, -1, replacements))
3639 throw LuaError(L, "Invalid replacements"
3640 " (output=\"" + output + "\")");
3643 CraftDefinition *def = new CraftDefinitionShapeless(
3644 output, recipe, replacements);
3645 craftdef->registerCraft(def);
3648 CraftDefinitionToolRepair
3650 else if(type == "toolrepair"){
3651 float additional_wear = getfloatfield_default(L, table,
3652 "additional_wear", 0.0);
3654 CraftDefinition *def = new CraftDefinitionToolRepair(
3656 craftdef->registerCraft(def);
3659 CraftDefinitionCooking
3661 else if(type == "cooking"){
3662 std::string output = getstringfield_default(L, table, "output", "");
3664 throw LuaError(L, "Crafting definition (cooking)"
3665 " is missing an output");
3667 std::string recipe = getstringfield_default(L, table, "recipe", "");
3669 throw LuaError(L, "Crafting definition (cooking)"
3670 " is missing a recipe"
3671 " (output=\"" + output + "\")");
3673 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3675 CraftDefinition *def = new CraftDefinitionCooking(
3676 output, recipe, cooktime);
3677 craftdef->registerCraft(def);
3682 else if(type == "fuel"){
3683 std::string recipe = getstringfield_default(L, table, "recipe", "");
3685 throw LuaError(L, "Crafting definition (fuel)"
3686 " is missing a recipe");
3688 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3690 CraftDefinition *def = new CraftDefinitionFuel(
3692 craftdef->registerCraft(def);
3696 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3700 return 0; /* number of results */
3703 // setting_get(name)
3704 static int l_setting_get(lua_State *L)
3706 const char *name = luaL_checkstring(L, 1);
3708 std::string value = g_settings->get(name);
3709 lua_pushstring(L, value.c_str());
3710 } catch(SettingNotFoundException &e){
3716 // setting_getbool(name)
3717 static int l_setting_getbool(lua_State *L)
3719 const char *name = luaL_checkstring(L, 1);
3721 bool value = g_settings->getBool(name);
3722 lua_pushboolean(L, value);
3723 } catch(SettingNotFoundException &e){
3729 // chat_send_all(text)
3730 static int l_chat_send_all(lua_State *L)
3732 const char *text = luaL_checkstring(L, 1);
3733 // Get server from registry
3734 Server *server = get_server(L);
3736 server->notifyPlayers(narrow_to_wide(text));
3740 // chat_send_player(name, text)
3741 static int l_chat_send_player(lua_State *L)
3743 const char *name = luaL_checkstring(L, 1);
3744 const char *text = luaL_checkstring(L, 2);
3745 // Get server from registry
3746 Server *server = get_server(L);
3748 server->notifyPlayer(name, narrow_to_wide(text));
3752 // get_player_privs(name, text)
3753 static int l_get_player_privs(lua_State *L)
3755 const char *name = luaL_checkstring(L, 1);
3756 // Get server from registry
3757 Server *server = get_server(L);
3760 int table = lua_gettop(L);
3761 u64 privs_i = server->getPlayerEffectivePrivs(name);
3762 std::set<std::string> privs_s = privsToSet(privs_i);
3763 for(std::set<std::string>::const_iterator
3764 i = privs_s.begin(); i != privs_s.end(); i++){
3765 lua_pushboolean(L, true);
3766 lua_setfield(L, table, i->c_str());
3768 lua_pushvalue(L, table);
3772 // get_inventory(location)
3773 static int l_get_inventory(lua_State *L)
3775 InventoryLocation loc;
3777 std::string type = checkstringfield(L, 1, "type");
3778 if(type == "player"){
3779 std::string name = checkstringfield(L, 1, "name");
3780 loc.setPlayer(name);
3781 } else if(type == "node"){
3782 lua_getfield(L, 1, "pos");
3783 v3s16 pos = check_v3s16(L, -1);
3784 loc.setNodeMeta(pos);
3787 if(get_server(L)->getInventory(loc) != NULL)
3788 InvRef::create(L, loc);
3794 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3795 static int l_get_dig_params(lua_State *L)
3797 std::map<std::string, int> groups;
3798 read_groups(L, 1, groups);
3799 ToolCapabilities tp = read_tool_capabilities(L, 2);
3800 if(lua_isnoneornil(L, 3))
3801 push_dig_params(L, getDigParams(groups, &tp));
3803 push_dig_params(L, getDigParams(groups, &tp,
3804 luaL_checknumber(L, 3)));
3808 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3809 static int l_get_hit_params(lua_State *L)
3811 std::map<std::string, int> groups;
3812 read_groups(L, 1, groups);
3813 ToolCapabilities tp = read_tool_capabilities(L, 2);
3814 if(lua_isnoneornil(L, 3))
3815 push_hit_params(L, getHitParams(groups, &tp));
3817 push_hit_params(L, getHitParams(groups, &tp,
3818 luaL_checknumber(L, 3)));
3822 // get_current_modname()
3823 static int l_get_current_modname(lua_State *L)
3825 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3829 // get_modpath(modname)
3830 static int l_get_modpath(lua_State *L)
3832 const char *modname = luaL_checkstring(L, 1);
3834 const ModSpec *mod = get_server(L)->getModSpec(modname);
3839 lua_pushstring(L, mod->path.c_str());
3844 static int l_get_worldpath(lua_State *L)
3846 std::string worldpath = get_server(L)->getWorldPath();
3847 lua_pushstring(L, worldpath.c_str());
3851 // sound_play(spec, parameters)
3852 static int l_sound_play(lua_State *L)
3854 SimpleSoundSpec spec;
3855 read_soundspec(L, 1, spec);
3856 ServerSoundParams params;
3857 read_server_sound_params(L, 2, params);
3858 s32 handle = get_server(L)->playSound(spec, params);
3859 lua_pushinteger(L, handle);
3863 // sound_stop(handle)
3864 static int l_sound_stop(lua_State *L)
3866 int handle = luaL_checkinteger(L, 1);
3867 get_server(L)->stopSound(handle);
3871 // is_singleplayer()
3872 static int l_is_singleplayer(lua_State *L)
3874 lua_pushboolean(L, get_server(L)->isSingleplayer());
3878 static const struct luaL_Reg minetest_f [] = {
3881 {"register_item_raw", l_register_item_raw},
3882 {"register_alias_raw", l_register_alias_raw},
3883 {"register_craft", l_register_craft},
3884 {"setting_get", l_setting_get},
3885 {"setting_getbool", l_setting_getbool},
3886 {"chat_send_all", l_chat_send_all},
3887 {"chat_send_player", l_chat_send_player},
3888 {"get_player_privs", l_get_player_privs},
3889 {"get_inventory", l_get_inventory},
3890 {"get_dig_params", l_get_dig_params},
3891 {"get_hit_params", l_get_hit_params},
3892 {"get_current_modname", l_get_current_modname},
3893 {"get_modpath", l_get_modpath},
3894 {"get_worldpath", l_get_worldpath},
3895 {"sound_play", l_sound_play},
3896 {"sound_stop", l_sound_stop},
3897 {"is_singleplayer", l_is_singleplayer},
3902 Main export function
3905 void scriptapi_export(lua_State *L, Server *server)
3908 assert(lua_checkstack(L, 20));
3909 verbosestream<<"scriptapi_export()"<<std::endl;
3910 StackUnroller stack_unroller(L);
3912 // Store server as light userdata in registry
3913 lua_pushlightuserdata(L, server);
3914 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3916 // Register global functions in table minetest
3918 luaL_register(L, NULL, minetest_f);
3919 lua_setglobal(L, "minetest");
3921 // Get the main minetest table
3922 lua_getglobal(L, "minetest");
3924 // Add tables to minetest
3927 lua_setfield(L, -2, "object_refs");
3929 lua_setfield(L, -2, "luaentities");
3931 // Register wrappers
3932 LuaItemStack::Register(L);
3933 InvRef::Register(L);
3934 NodeMetaRef::Register(L);
3935 ObjectRef::Register(L);
3936 EnvRef::Register(L);
3937 LuaPseudoRandom::Register(L);
3940 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3941 const std::string &modname)
3943 ModNameStorer modnamestorer(L, modname);
3945 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3947 errorstream<<"Error loading mod \""<<modname
3948 <<"\": modname does not follow naming conventions: "
3949 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3953 bool success = false;
3956 success = script_load(L, scriptpath.c_str());
3959 errorstream<<"Error loading mod \""<<modname
3960 <<"\": "<<e.what()<<std::endl;
3966 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3969 assert(lua_checkstack(L, 20));
3970 verbosestream<<"scriptapi_add_environment"<<std::endl;
3971 StackUnroller stack_unroller(L);
3973 // Create EnvRef on stack
3974 EnvRef::create(L, env);
3975 int envref = lua_gettop(L);
3977 // minetest.env = envref
3978 lua_getglobal(L, "minetest");
3979 luaL_checktype(L, -1, LUA_TTABLE);
3980 lua_pushvalue(L, envref);
3981 lua_setfield(L, -2, "env");
3983 // Store environment as light userdata in registry
3984 lua_pushlightuserdata(L, env);
3985 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3988 Add ActiveBlockModifiers to environment
3991 // Get minetest.registered_abms
3992 lua_getglobal(L, "minetest");
3993 lua_getfield(L, -1, "registered_abms");
3994 luaL_checktype(L, -1, LUA_TTABLE);
3995 int registered_abms = lua_gettop(L);
3997 if(lua_istable(L, registered_abms)){
3998 int table = lua_gettop(L);
4000 while(lua_next(L, table) != 0){
4001 // key at index -2 and value at index -1
4002 int id = lua_tonumber(L, -2);
4003 int current_abm = lua_gettop(L);
4005 std::set<std::string> trigger_contents;
4006 lua_getfield(L, current_abm, "nodenames");
4007 if(lua_istable(L, -1)){
4008 int table = lua_gettop(L);
4010 while(lua_next(L, table) != 0){
4011 // key at index -2 and value at index -1
4012 luaL_checktype(L, -1, LUA_TSTRING);
4013 trigger_contents.insert(lua_tostring(L, -1));
4014 // removes value, keeps key for next iteration
4017 } else if(lua_isstring(L, -1)){
4018 trigger_contents.insert(lua_tostring(L, -1));
4022 std::set<std::string> required_neighbors;
4023 lua_getfield(L, current_abm, "neighbors");
4024 if(lua_istable(L, -1)){
4025 int table = lua_gettop(L);
4027 while(lua_next(L, table) != 0){
4028 // key at index -2 and value at index -1
4029 luaL_checktype(L, -1, LUA_TSTRING);
4030 required_neighbors.insert(lua_tostring(L, -1));
4031 // removes value, keeps key for next iteration
4034 } else if(lua_isstring(L, -1)){
4035 required_neighbors.insert(lua_tostring(L, -1));
4039 float trigger_interval = 10.0;
4040 getfloatfield(L, current_abm, "interval", trigger_interval);
4042 int trigger_chance = 50;
4043 getintfield(L, current_abm, "chance", trigger_chance);
4045 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4046 required_neighbors, trigger_interval, trigger_chance);
4048 env->addActiveBlockModifier(abm);
4050 // removes value, keeps key for next iteration
4058 // Dump stack top with the dump2 function
4059 static void dump2(lua_State *L, const char *name)
4061 // Dump object (debug)
4062 lua_getglobal(L, "dump2");
4063 luaL_checktype(L, -1, LUA_TFUNCTION);
4064 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4065 lua_pushstring(L, name);
4066 if(lua_pcall(L, 2, 0, 0))
4067 script_error(L, "error: %s", lua_tostring(L, -1));
4075 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4078 assert(lua_checkstack(L, 20));
4079 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4080 StackUnroller stack_unroller(L);
4082 // Create object on stack
4083 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4084 int object = lua_gettop(L);
4086 // Get minetest.object_refs table
4087 lua_getglobal(L, "minetest");
4088 lua_getfield(L, -1, "object_refs");
4089 luaL_checktype(L, -1, LUA_TTABLE);
4090 int objectstable = lua_gettop(L);
4092 // object_refs[id] = object
4093 lua_pushnumber(L, cobj->getId()); // Push id
4094 lua_pushvalue(L, object); // Copy object to top of stack
4095 lua_settable(L, objectstable);
4098 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4101 assert(lua_checkstack(L, 20));
4102 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4103 StackUnroller stack_unroller(L);
4105 // Get minetest.object_refs table
4106 lua_getglobal(L, "minetest");
4107 lua_getfield(L, -1, "object_refs");
4108 luaL_checktype(L, -1, LUA_TTABLE);
4109 int objectstable = lua_gettop(L);
4111 // Get object_refs[id]
4112 lua_pushnumber(L, cobj->getId()); // Push id
4113 lua_gettable(L, objectstable);
4114 // Set object reference to NULL
4115 ObjectRef::set_null(L);
4116 lua_pop(L, 1); // pop object
4118 // Set object_refs[id] = nil
4119 lua_pushnumber(L, cobj->getId()); // Push id
4121 lua_settable(L, objectstable);
4124 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4125 const std::string &message)
4128 assert(lua_checkstack(L, 20));
4129 StackUnroller stack_unroller(L);
4131 // Get minetest.registered_on_chat_messages
4132 lua_getglobal(L, "minetest");
4133 lua_getfield(L, -1, "registered_on_chat_messages");
4134 luaL_checktype(L, -1, LUA_TTABLE);
4135 int table = lua_gettop(L);
4138 while(lua_next(L, table) != 0){
4139 // key at index -2 and value at index -1
4140 luaL_checktype(L, -1, LUA_TFUNCTION);
4142 lua_pushstring(L, name.c_str());
4143 lua_pushstring(L, message.c_str());
4144 if(lua_pcall(L, 2, 1, 0))
4145 script_error(L, "error: %s", lua_tostring(L, -1));
4146 bool ate = lua_toboolean(L, -1);
4150 // value removed, keep key for next iteration
4159 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4162 assert(lua_checkstack(L, 20));
4163 StackUnroller stack_unroller(L);
4165 // Get minetest.registered_on_newplayers
4166 lua_getglobal(L, "minetest");
4167 lua_getfield(L, -1, "registered_on_newplayers");
4168 luaL_checktype(L, -1, LUA_TTABLE);
4169 int table = lua_gettop(L);
4172 while(lua_next(L, table) != 0){
4173 // key at index -2 and value at index -1
4174 luaL_checktype(L, -1, LUA_TFUNCTION);
4176 objectref_get_or_create(L, player);
4177 if(lua_pcall(L, 1, 0, 0))
4178 script_error(L, "error: %s", lua_tostring(L, -1));
4179 // value removed, keep key for next iteration
4183 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4186 assert(lua_checkstack(L, 20));
4187 StackUnroller stack_unroller(L);
4189 // Get minetest.registered_on_dieplayers
4190 lua_getglobal(L, "minetest");
4191 lua_getfield(L, -1, "registered_on_dieplayers");
4192 luaL_checktype(L, -1, LUA_TTABLE);
4193 int table = lua_gettop(L);
4196 while(lua_next(L, table) != 0){
4197 // key at index -2 and value at index -1
4198 luaL_checktype(L, -1, LUA_TFUNCTION);
4200 objectref_get_or_create(L, player);
4201 if(lua_pcall(L, 1, 0, 0))
4202 script_error(L, "error: %s", lua_tostring(L, -1));
4203 // value removed, keep key for next iteration
4208 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4211 assert(lua_checkstack(L, 20));
4212 StackUnroller stack_unroller(L);
4214 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
4216 bool positioning_handled_by_some = false;
4218 // Get minetest.registered_on_respawnplayers
4219 lua_getglobal(L, "minetest");
4220 lua_getfield(L, -1, "registered_on_respawnplayers");
4221 luaL_checktype(L, -1, LUA_TTABLE);
4222 int table = lua_gettop(L);
4225 while(lua_next(L, table) != 0){
4226 // key at index -2 and value at index -1
4227 luaL_checktype(L, -1, LUA_TFUNCTION);
4229 objectref_get_or_create(L, player);
4230 if(lua_pcall(L, 1, 1, 0))
4231 script_error(L, "error: %s", lua_tostring(L, -1));
4232 bool positioning_handled = lua_toboolean(L, -1);
4234 if(positioning_handled)
4235 positioning_handled_by_some = true;
4236 // value removed, keep key for next iteration
4238 return positioning_handled_by_some;
4241 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4243 lua_getglobal(L, "minetest");
4244 lua_getfield(L, -1, "creative_inventory");
4245 luaL_checktype(L, -1, LUA_TTABLE);
4246 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4247 PLAYER_INVENTORY_SIZE);
4251 item callbacks and node callbacks
4254 // Retrieves minetest.registered_items[name][callbackname]
4255 // If that is nil or on error, return false and stack is unchanged
4256 // If that is a function, returns true and pushes the
4257 // function onto the stack
4258 static bool get_item_callback(lua_State *L,
4259 const char *name, const char *callbackname)
4261 lua_getglobal(L, "minetest");
4262 lua_getfield(L, -1, "registered_items");
4264 luaL_checktype(L, -1, LUA_TTABLE);
4265 lua_getfield(L, -1, name);
4267 // Should be a table
4268 if(lua_type(L, -1) != LUA_TTABLE)
4270 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4274 lua_getfield(L, -1, callbackname);
4276 // Should be a function or nil
4277 if(lua_type(L, -1) == LUA_TFUNCTION)
4281 else if(lua_isnil(L, -1))
4288 errorstream<<"Item \""<<name<<"\" callback \""
4289 <<callbackname<<" is not a function"<<std::endl;
4295 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4296 ServerActiveObject *dropper, v3f pos)
4299 assert(lua_checkstack(L, 20));
4300 StackUnroller stack_unroller(L);
4302 // Push callback function on stack
4303 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4307 LuaItemStack::create(L, item);
4308 objectref_get_or_create(L, dropper);
4309 pushFloatPos(L, pos);
4310 if(lua_pcall(L, 3, 1, 0))
4311 script_error(L, "error: %s", lua_tostring(L, -1));
4312 if(!lua_isnil(L, -1))
4313 item = read_item(L, -1);
4317 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4318 ServerActiveObject *placer, const PointedThing &pointed)
4321 assert(lua_checkstack(L, 20));
4322 StackUnroller stack_unroller(L);
4324 // Push callback function on stack
4325 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4329 LuaItemStack::create(L, item);
4330 objectref_get_or_create(L, placer);
4331 push_pointed_thing(L, pointed);
4332 if(lua_pcall(L, 3, 1, 0))
4333 script_error(L, "error: %s", lua_tostring(L, -1));
4334 if(!lua_isnil(L, -1))
4335 item = read_item(L, -1);
4339 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4340 ServerActiveObject *user, const PointedThing &pointed)
4343 assert(lua_checkstack(L, 20));
4344 StackUnroller stack_unroller(L);
4346 // Push callback function on stack
4347 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4351 LuaItemStack::create(L, item);
4352 objectref_get_or_create(L, user);
4353 push_pointed_thing(L, pointed);
4354 if(lua_pcall(L, 3, 1, 0))
4355 script_error(L, "error: %s", lua_tostring(L, -1));
4356 if(!lua_isnil(L, -1))
4357 item = read_item(L, -1);
4361 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4362 ServerActiveObject *puncher)
4365 assert(lua_checkstack(L, 20));
4366 StackUnroller stack_unroller(L);
4368 INodeDefManager *ndef = get_server(L)->ndef();
4370 // Push callback function on stack
4371 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4376 pushnode(L, node, ndef);
4377 objectref_get_or_create(L, puncher);
4378 if(lua_pcall(L, 3, 0, 0))
4379 script_error(L, "error: %s", lua_tostring(L, -1));
4383 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4384 ServerActiveObject *digger)
4387 assert(lua_checkstack(L, 20));
4388 StackUnroller stack_unroller(L);
4390 INodeDefManager *ndef = get_server(L)->ndef();
4392 // Push callback function on stack
4393 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4398 pushnode(L, node, ndef);
4399 objectref_get_or_create(L, digger);
4400 if(lua_pcall(L, 3, 0, 0))
4401 script_error(L, "error: %s", lua_tostring(L, -1));
4409 void scriptapi_environment_step(lua_State *L, float dtime)
4412 assert(lua_checkstack(L, 20));
4413 //infostream<<"scriptapi_environment_step"<<std::endl;
4414 StackUnroller stack_unroller(L);
4416 // Get minetest.registered_globalsteps
4417 lua_getglobal(L, "minetest");
4418 lua_getfield(L, -1, "registered_globalsteps");
4419 luaL_checktype(L, -1, LUA_TTABLE);
4420 int table = lua_gettop(L);
4423 while(lua_next(L, table) != 0){
4424 // key at index -2 and value at index -1
4425 luaL_checktype(L, -1, LUA_TFUNCTION);
4427 lua_pushnumber(L, dtime);
4428 if(lua_pcall(L, 1, 0, 0))
4429 script_error(L, "error: %s", lua_tostring(L, -1));
4430 // value removed, keep key for next iteration
4434 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
4438 assert(lua_checkstack(L, 20));
4439 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4440 StackUnroller stack_unroller(L);
4442 // Get minetest.registered_on_generateds
4443 lua_getglobal(L, "minetest");
4444 lua_getfield(L, -1, "registered_on_generateds");
4445 luaL_checktype(L, -1, LUA_TTABLE);
4446 int table = lua_gettop(L);
4449 while(lua_next(L, table) != 0){
4450 // key at index -2 and value at index -1
4451 luaL_checktype(L, -1, LUA_TFUNCTION);
4453 push_v3s16(L, minp);
4454 push_v3s16(L, maxp);
4455 lua_pushnumber(L, blockseed);
4456 if(lua_pcall(L, 3, 0, 0))
4457 script_error(L, "error: %s", lua_tostring(L, -1));
4458 // value removed, keep key for next iteration
4466 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4469 assert(lua_checkstack(L, 20));
4470 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4471 <<name<<"\""<<std::endl;
4472 StackUnroller stack_unroller(L);
4474 // Get minetest.registered_entities[name]
4475 lua_getglobal(L, "minetest");
4476 lua_getfield(L, -1, "registered_entities");
4477 luaL_checktype(L, -1, LUA_TTABLE);
4478 lua_pushstring(L, name);
4479 lua_gettable(L, -2);
4480 // Should be a table, which we will use as a prototype
4481 //luaL_checktype(L, -1, LUA_TTABLE);
4482 if(lua_type(L, -1) != LUA_TTABLE){
4483 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4486 int prototype_table = lua_gettop(L);
4487 //dump2(L, "prototype_table");
4489 // Create entity object
4491 int object = lua_gettop(L);
4493 // Set object metatable
4494 lua_pushvalue(L, prototype_table);
4495 lua_setmetatable(L, -2);
4497 // Add object reference
4498 // This should be userdata with metatable ObjectRef
4499 objectref_get(L, id);
4500 luaL_checktype(L, -1, LUA_TUSERDATA);
4501 if(!luaL_checkudata(L, -1, "ObjectRef"))
4502 luaL_typerror(L, -1, "ObjectRef");
4503 lua_setfield(L, -2, "object");
4505 // minetest.luaentities[id] = object
4506 lua_getglobal(L, "minetest");
4507 lua_getfield(L, -1, "luaentities");
4508 luaL_checktype(L, -1, LUA_TTABLE);
4509 lua_pushnumber(L, id); // Push id
4510 lua_pushvalue(L, object); // Copy object to top of stack
4511 lua_settable(L, -3);
4516 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4517 const std::string &staticdata)
4520 assert(lua_checkstack(L, 20));
4521 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4522 StackUnroller stack_unroller(L);
4524 // Get minetest.luaentities[id]
4525 luaentity_get(L, id);
4526 int object = lua_gettop(L);
4528 // Get on_activate function
4529 lua_pushvalue(L, object);
4530 lua_getfield(L, -1, "on_activate");
4531 if(!lua_isnil(L, -1)){
4532 luaL_checktype(L, -1, LUA_TFUNCTION);
4533 lua_pushvalue(L, object); // self
4534 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4535 // Call with 2 arguments, 0 results
4536 if(lua_pcall(L, 2, 0, 0))
4537 script_error(L, "error running function on_activate: %s\n",
4538 lua_tostring(L, -1));
4542 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4545 assert(lua_checkstack(L, 20));
4546 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4548 // Get minetest.luaentities table
4549 lua_getglobal(L, "minetest");
4550 lua_getfield(L, -1, "luaentities");
4551 luaL_checktype(L, -1, LUA_TTABLE);
4552 int objectstable = lua_gettop(L);
4554 // Set luaentities[id] = nil
4555 lua_pushnumber(L, id); // Push id
4557 lua_settable(L, objectstable);
4559 lua_pop(L, 2); // pop luaentities, minetest
4562 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4565 assert(lua_checkstack(L, 20));
4566 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4567 StackUnroller stack_unroller(L);
4569 // Get minetest.luaentities[id]
4570 luaentity_get(L, id);
4571 int object = lua_gettop(L);
4573 // Get get_staticdata function
4574 lua_pushvalue(L, object);
4575 lua_getfield(L, -1, "get_staticdata");
4576 if(lua_isnil(L, -1))
4579 luaL_checktype(L, -1, LUA_TFUNCTION);
4580 lua_pushvalue(L, object); // self
4581 // Call with 1 arguments, 1 results
4582 if(lua_pcall(L, 1, 1, 0))
4583 script_error(L, "error running function get_staticdata: %s\n",
4584 lua_tostring(L, -1));
4587 const char *s = lua_tolstring(L, -1, &len);
4588 return std::string(s, len);
4591 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4592 LuaEntityProperties *prop)
4595 assert(lua_checkstack(L, 20));
4596 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4597 StackUnroller stack_unroller(L);
4599 // Get minetest.luaentities[id]
4600 luaentity_get(L, id);
4601 //int object = lua_gettop(L);
4605 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4607 getboolfield(L, -1, "physical", prop->physical);
4609 getfloatfield(L, -1, "weight", prop->weight);
4611 lua_getfield(L, -1, "collisionbox");
4612 if(lua_istable(L, -1))
4613 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4616 getstringfield(L, -1, "visual", prop->visual);
4618 lua_getfield(L, -1, "visual_size");
4619 if(lua_istable(L, -1))
4620 prop->visual_size = read_v2f(L, -1);
4623 lua_getfield(L, -1, "textures");
4624 if(lua_istable(L, -1)){
4625 prop->textures.clear();
4626 int table = lua_gettop(L);
4628 while(lua_next(L, table) != 0){
4629 // key at index -2 and value at index -1
4630 if(lua_isstring(L, -1))
4631 prop->textures.push_back(lua_tostring(L, -1));
4633 prop->textures.push_back("");
4634 // removes value, keeps key for next iteration
4640 lua_getfield(L, -1, "spritediv");
4641 if(lua_istable(L, -1))
4642 prop->spritediv = read_v2s16(L, -1);
4645 lua_getfield(L, -1, "initial_sprite_basepos");
4646 if(lua_istable(L, -1))
4647 prop->initial_sprite_basepos = read_v2s16(L, -1);
4651 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4654 assert(lua_checkstack(L, 20));
4655 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4656 StackUnroller stack_unroller(L);
4658 // Get minetest.luaentities[id]
4659 luaentity_get(L, id);
4660 int object = lua_gettop(L);
4661 // State: object is at top of stack
4662 // Get step function
4663 lua_getfield(L, -1, "on_step");
4664 if(lua_isnil(L, -1))
4666 luaL_checktype(L, -1, LUA_TFUNCTION);
4667 lua_pushvalue(L, object); // self
4668 lua_pushnumber(L, dtime); // dtime
4669 // Call with 2 arguments, 0 results
4670 if(lua_pcall(L, 2, 0, 0))
4671 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4674 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4675 // tool_capabilities, direction)
4676 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4677 ServerActiveObject *puncher, float time_from_last_punch,
4678 const ToolCapabilities *toolcap, v3f dir)
4681 assert(lua_checkstack(L, 20));
4682 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4683 StackUnroller stack_unroller(L);
4685 // Get minetest.luaentities[id]
4686 luaentity_get(L, id);
4687 int object = lua_gettop(L);
4688 // State: object is at top of stack
4690 lua_getfield(L, -1, "on_punch");
4691 if(lua_isnil(L, -1))
4693 luaL_checktype(L, -1, LUA_TFUNCTION);
4694 lua_pushvalue(L, object); // self
4695 objectref_get_or_create(L, puncher); // Clicker reference
4696 lua_pushnumber(L, time_from_last_punch);
4697 push_tool_capabilities(L, *toolcap);
4699 // Call with 5 arguments, 0 results
4700 if(lua_pcall(L, 5, 0, 0))
4701 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4704 // Calls entity:on_rightclick(ObjectRef clicker)
4705 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4706 ServerActiveObject *clicker)
4709 assert(lua_checkstack(L, 20));
4710 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4711 StackUnroller stack_unroller(L);
4713 // Get minetest.luaentities[id]
4714 luaentity_get(L, id);
4715 int object = lua_gettop(L);
4716 // State: object is at top of stack
4718 lua_getfield(L, -1, "on_rightclick");
4719 if(lua_isnil(L, -1))
4721 luaL_checktype(L, -1, LUA_TFUNCTION);
4722 lua_pushvalue(L, object); // self
4723 objectref_get_or_create(L, clicker); // Clicker reference
4724 // Call with 2 arguments, 0 results
4725 if(lua_pcall(L, 2, 0, 0))
4726 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));