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 getfloatfield(L, table_groupcap, "maxwear", groupcap.maxwear);
674 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
675 // Read "times" table
676 lua_getfield(L, table_groupcap, "times");
677 if(lua_istable(L, -1)){
678 int table_times = lua_gettop(L);
680 while(lua_next(L, table_times) != 0){
681 // key at index -2 and value at index -1
682 int rating = luaL_checkinteger(L, -2);
683 float time = luaL_checknumber(L, -1);
684 groupcap.times[rating] = time;
685 // removes value, keeps key for next iteration
690 // Insert groupcap into toolcap
691 toolcap.groupcaps[groupname] = groupcap;
693 // removes value, keeps key for next iteration
701 static void set_tool_capabilities(lua_State *L, int table,
702 const ToolCapabilities &toolcap)
704 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
705 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
706 // Create groupcaps table
709 for(std::map<std::string, ToolGroupCap>::const_iterator
710 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
711 // Create groupcap table
713 const std::string &name = i->first;
714 const ToolGroupCap &groupcap = i->second;
715 // Create subtable "times"
717 for(std::map<int, float>::const_iterator
718 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
719 int rating = i->first;
720 float time = i->second;
721 lua_pushinteger(L, rating);
722 lua_pushnumber(L, time);
725 // Set subtable "times"
726 lua_setfield(L, -2, "times");
727 // Set simple parameters
728 setfloatfield(L, -1, "maxwear", groupcap.maxwear);
729 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
730 // Insert groupcap table into groupcaps table
731 lua_setfield(L, -2, name.c_str());
733 // Set groupcaps table
734 lua_setfield(L, -2, "groupcaps");
737 static void push_tool_capabilities(lua_State *L,
738 const ToolCapabilities &prop)
741 set_tool_capabilities(L, -1, prop);
748 static void set_dig_params(lua_State *L, int table,
749 const DigParams ¶ms)
751 setboolfield(L, table, "diggable", params.diggable);
752 setfloatfield(L, table, "time", params.time);
753 setintfield(L, table, "wear", params.wear);
756 static void push_dig_params(lua_State *L,
757 const DigParams ¶ms)
760 set_dig_params(L, -1, params);
767 static void set_hit_params(lua_State *L, int table,
768 const HitParams ¶ms)
770 setintfield(L, table, "hp", params.hp);
771 setintfield(L, table, "wear", params.wear);
774 static void push_hit_params(lua_State *L,
775 const HitParams ¶ms)
778 set_hit_params(L, -1, params);
785 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
788 if(pointed.type == POINTEDTHING_NODE)
790 lua_pushstring(L, "node");
791 lua_setfield(L, -2, "type");
792 push_v3s16(L, pointed.node_undersurface);
793 lua_setfield(L, -2, "under");
794 push_v3s16(L, pointed.node_abovesurface);
795 lua_setfield(L, -2, "above");
797 else if(pointed.type == POINTEDTHING_OBJECT)
799 lua_pushstring(L, "object");
800 lua_setfield(L, -2, "type");
801 objectref_get(L, pointed.object_id);
802 lua_setfield(L, -2, "ref");
806 lua_pushstring(L, "nothing");
807 lua_setfield(L, -2, "type");
815 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
818 index = lua_gettop(L) + 1 + index;
819 if(lua_isnil(L, index)){
820 } else if(lua_istable(L, index)){
821 getstringfield(L, index, "name", spec.name);
822 getfloatfield(L, index, "gain", spec.gain);
823 } else if(lua_isstring(L, index)){
824 spec.name = lua_tostring(L, index);
832 static ItemDefinition read_item_definition(lua_State *L, int index)
835 index = lua_gettop(L) + 1 + index;
837 // Read the item definition
840 def.type = (ItemType)getenumfield(L, index, "type",
841 es_ItemType, ITEM_NONE);
842 getstringfield(L, index, "name", def.name);
843 getstringfield(L, index, "description", def.description);
844 getstringfield(L, index, "inventory_image", def.inventory_image);
845 getstringfield(L, index, "wield_image", def.wield_image);
847 lua_getfield(L, index, "wield_scale");
848 if(lua_istable(L, -1)){
849 def.wield_scale = check_v3f(L, -1);
853 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
854 if(def.stack_max == 0)
857 lua_getfield(L, index, "on_use");
858 def.usable = lua_isfunction(L, -1);
861 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
863 warn_if_field_exists(L, index, "tool_digging_properties",
864 "deprecated: use tool_capabilities");
866 lua_getfield(L, index, "tool_capabilities");
867 if(lua_istable(L, -1)){
868 def.tool_capabilities = new ToolCapabilities(
869 read_tool_capabilities(L, -1));
872 // If name is "" (hand), ensure there are ToolCapabilities
873 // because it will be looked up there whenever any other item has
874 // no ToolCapabilities
875 if(def.name == "" && def.tool_capabilities == NULL){
876 def.tool_capabilities = new ToolCapabilities();
879 lua_getfield(L, index, "groups");
880 read_groups(L, -1, def.groups);
890 static ContentFeatures read_content_features(lua_State *L, int index)
893 index = lua_gettop(L) + 1 + index;
897 getstringfield(L, index, "name", f.name);
900 lua_getfield(L, index, "groups");
901 read_groups(L, -1, f.groups);
904 /* Visual definition */
906 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
908 getfloatfield(L, index, "visual_scale", f.visual_scale);
910 lua_getfield(L, index, "tile_images");
911 if(lua_istable(L, -1)){
912 int table = lua_gettop(L);
915 while(lua_next(L, table) != 0){
916 // key at index -2 and value at index -1
917 if(lua_isstring(L, -1))
918 f.tname_tiles[i] = lua_tostring(L, -1);
920 f.tname_tiles[i] = "";
921 // removes value, keeps key for next iteration
929 // Copy last value to all remaining textures
931 std::string lastname = f.tname_tiles[i-1];
933 f.tname_tiles[i] = lastname;
940 lua_getfield(L, index, "special_materials");
941 if(lua_istable(L, -1)){
942 int table = lua_gettop(L);
945 while(lua_next(L, table) != 0){
946 // key at index -2 and value at index -1
947 int smtable = lua_gettop(L);
948 std::string tname = getstringfield_default(
949 L, smtable, "image", "");
950 bool backface_culling = getboolfield_default(
951 L, smtable, "backface_culling", true);
952 MaterialSpec mspec(tname, backface_culling);
953 f.mspec_special[i] = mspec;
954 // removes value, keeps key for next iteration
965 f.alpha = getintfield_default(L, index, "alpha", 255);
969 lua_getfield(L, index, "post_effect_color");
970 if(!lua_isnil(L, -1))
971 f.post_effect_color = readARGB8(L, -1);
974 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
975 es_ContentParamType, CPT_NONE);
976 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
977 es_ContentParamType2, CPT2_NONE);
979 // Warn about some deprecated fields
980 warn_if_field_exists(L, index, "wall_mounted",
981 "deprecated: use paramtype2 = 'wallmounted'");
982 warn_if_field_exists(L, index, "light_propagates",
983 "deprecated: determined from paramtype");
984 warn_if_field_exists(L, index, "dug_item",
985 "deprecated: use 'drop' field");
986 warn_if_field_exists(L, index, "extra_dug_item",
987 "deprecated: use 'drop' field");
988 warn_if_field_exists(L, index, "extra_dug_item_rarity",
989 "deprecated: use 'drop' field");
991 // True for all ground-like things like stone and mud, false for eg. trees
992 getboolfield(L, index, "is_ground_content", f.is_ground_content);
993 f.light_propagates = (f.param_type == CPT_LIGHT);
994 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
995 // This is used for collision detection.
996 // Also for general solidness queries.
997 getboolfield(L, index, "walkable", f.walkable);
998 // Player can point to these
999 getboolfield(L, index, "pointable", f.pointable);
1000 // Player can dig these
1001 getboolfield(L, index, "diggable", f.diggable);
1002 // Player can climb these
1003 getboolfield(L, index, "climbable", f.climbable);
1004 // Player can build on these
1005 getboolfield(L, index, "buildable_to", f.buildable_to);
1006 // Metadata name of node (eg. "furnace")
1007 getstringfield(L, index, "metadata_name", f.metadata_name);
1008 // Whether the node is non-liquid, source liquid or flowing liquid
1009 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1010 es_LiquidType, LIQUID_NONE);
1011 // If the content is liquid, this is the flowing version of the liquid.
1012 getstringfield(L, index, "liquid_alternative_flowing",
1013 f.liquid_alternative_flowing);
1014 // If the content is liquid, this is the source version of the liquid.
1015 getstringfield(L, index, "liquid_alternative_source",
1016 f.liquid_alternative_source);
1017 // Viscosity for fluid flow, ranging from 1 to 7, with
1018 // 1 giving almost instantaneous propagation and 7 being
1019 // the slowest possible
1020 f.liquid_viscosity = getintfield_default(L, index,
1021 "liquid_viscosity", f.liquid_viscosity);
1022 // Amount of light the node emits
1023 f.light_source = getintfield_default(L, index,
1024 "light_source", f.light_source);
1025 f.damage_per_second = getintfield_default(L, index,
1026 "damage_per_second", f.damage_per_second);
1028 lua_getfield(L, index, "selection_box");
1029 if(lua_istable(L, -1)){
1030 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1031 es_NodeBoxType, NODEBOX_REGULAR);
1033 lua_getfield(L, -1, "fixed");
1034 if(lua_istable(L, -1))
1035 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1038 lua_getfield(L, -1, "wall_top");
1039 if(lua_istable(L, -1))
1040 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1043 lua_getfield(L, -1, "wall_bottom");
1044 if(lua_istable(L, -1))
1045 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1048 lua_getfield(L, -1, "wall_side");
1049 if(lua_istable(L, -1))
1050 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1055 // Set to true if paramtype used to be 'facedir_simple'
1056 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1057 // Set to true if wall_mounted used to be set to true
1058 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1061 lua_getfield(L, index, "sounds");
1062 if(lua_istable(L, -1)){
1063 lua_getfield(L, -1, "footstep");
1064 read_soundspec(L, -1, f.sound_footstep);
1066 lua_getfield(L, -1, "dig");
1067 read_soundspec(L, -1, f.sound_dig);
1069 lua_getfield(L, -1, "dug");
1070 read_soundspec(L, -1, f.sound_dug);
1082 static ItemStack read_item(lua_State *L, int index);
1084 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1085 lua_State *L, int tableindex, int forcesize=-1)
1087 dstream<<"inventory_set_list_from_lua\n";
1089 tableindex = lua_gettop(L) + 1 + tableindex;
1090 // If nil, delete list
1091 if(lua_isnil(L, tableindex)){
1092 inv->deleteList(name);
1095 // Otherwise set list
1096 std::vector<ItemStack> items;
1097 luaL_checktype(L, tableindex, LUA_TTABLE);
1099 while(lua_next(L, tableindex) != 0){
1100 // key at index -2 and value at index -1
1101 items.push_back(read_item(L, -1));
1102 // removes value, keeps key for next iteration
1105 int listsize = (forcesize != -1) ? forcesize : items.size();
1106 InventoryList *invlist = inv->addList(name, listsize);
1108 for(std::vector<ItemStack>::const_iterator
1109 i = items.begin(); i != items.end(); i++){
1110 if(forcesize != -1 && index == forcesize)
1112 invlist->changeItem(index, *i);
1115 while(forcesize != -1 && index < forcesize){
1116 invlist->deleteItem(index);
1119 dstream<<"inventory_set_list_from_lua done\n";
1122 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1125 InventoryList *invlist = inv->getList(name);
1126 if(invlist == NULL){
1130 // Get the table insert function
1131 lua_getglobal(L, "table");
1132 lua_getfield(L, -1, "insert");
1133 int table_insert = lua_gettop(L);
1134 // Create and fill table
1136 int table = lua_gettop(L);
1137 for(u32 i=0; i<invlist->getSize(); i++){
1138 ItemStack item = invlist->getItem(i);
1139 lua_pushvalue(L, table_insert);
1140 lua_pushvalue(L, table);
1141 lua_pushstring(L, item.getItemString().c_str());
1142 if(lua_pcall(L, 2, 0, 0))
1143 script_error(L, "error: %s", lua_tostring(L, -1));
1148 Helpful macros for userdata classes
1151 #define method(class, name) {#name, class::l_##name}
1162 static const char className[];
1163 static const luaL_reg methods[];
1165 // Exported functions
1167 // garbage collector
1168 static int gc_object(lua_State *L)
1170 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1175 // is_empty(self) -> true/false
1176 static int l_is_empty(lua_State *L)
1178 LuaItemStack *o = checkobject(L, 1);
1179 ItemStack &item = o->m_stack;
1180 lua_pushboolean(L, item.empty());
1184 // get_name(self) -> string
1185 static int l_get_name(lua_State *L)
1187 LuaItemStack *o = checkobject(L, 1);
1188 ItemStack &item = o->m_stack;
1189 lua_pushstring(L, item.name.c_str());
1193 // get_count(self) -> number
1194 static int l_get_count(lua_State *L)
1196 LuaItemStack *o = checkobject(L, 1);
1197 ItemStack &item = o->m_stack;
1198 lua_pushinteger(L, item.count);
1202 // get_wear(self) -> number
1203 static int l_get_wear(lua_State *L)
1205 LuaItemStack *o = checkobject(L, 1);
1206 ItemStack &item = o->m_stack;
1207 lua_pushinteger(L, item.wear);
1211 // get_metadata(self) -> string
1212 static int l_get_metadata(lua_State *L)
1214 LuaItemStack *o = checkobject(L, 1);
1215 ItemStack &item = o->m_stack;
1216 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1220 // clear(self) -> true
1221 static int l_clear(lua_State *L)
1223 LuaItemStack *o = checkobject(L, 1);
1225 lua_pushboolean(L, true);
1229 // replace(self, itemstack or itemstring or table or nil) -> true
1230 static int l_replace(lua_State *L)
1232 LuaItemStack *o = checkobject(L, 1);
1233 o->m_stack = read_item(L, 2);
1234 lua_pushboolean(L, true);
1238 // to_string(self) -> string
1239 static int l_to_string(lua_State *L)
1241 LuaItemStack *o = checkobject(L, 1);
1242 std::string itemstring = o->m_stack.getItemString();
1243 lua_pushstring(L, itemstring.c_str());
1247 // to_table(self) -> table or nil
1248 static int l_to_table(lua_State *L)
1250 LuaItemStack *o = checkobject(L, 1);
1251 const ItemStack &item = o->m_stack;
1259 lua_pushstring(L, item.name.c_str());
1260 lua_setfield(L, -2, "name");
1261 lua_pushinteger(L, item.count);
1262 lua_setfield(L, -2, "count");
1263 lua_pushinteger(L, item.wear);
1264 lua_setfield(L, -2, "wear");
1265 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1266 lua_setfield(L, -2, "metadata");
1271 // get_stack_max(self) -> number
1272 static int l_get_stack_max(lua_State *L)
1274 LuaItemStack *o = checkobject(L, 1);
1275 ItemStack &item = o->m_stack;
1276 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1280 // get_free_space(self) -> number
1281 static int l_get_free_space(lua_State *L)
1283 LuaItemStack *o = checkobject(L, 1);
1284 ItemStack &item = o->m_stack;
1285 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1289 // is_known(self) -> true/false
1290 // Checks if the item is defined.
1291 static int l_is_known(lua_State *L)
1293 LuaItemStack *o = checkobject(L, 1);
1294 ItemStack &item = o->m_stack;
1295 bool is_known = item.isKnown(get_server(L)->idef());
1296 lua_pushboolean(L, is_known);
1300 // get_definition(self) -> table
1301 // Returns the item definition table from minetest.registered_items,
1302 // or a fallback one (name="unknown")
1303 static int l_get_definition(lua_State *L)
1305 LuaItemStack *o = checkobject(L, 1);
1306 ItemStack &item = o->m_stack;
1308 // Get minetest.registered_items[name]
1309 lua_getglobal(L, "minetest");
1310 lua_getfield(L, -1, "registered_items");
1311 luaL_checktype(L, -1, LUA_TTABLE);
1312 lua_getfield(L, -1, item.name.c_str());
1313 if(lua_isnil(L, -1))
1316 lua_getfield(L, -1, "unknown");
1321 // get_tool_capabilities(self) -> table
1322 // Returns the effective tool digging properties.
1323 // Returns those of the hand ("") if this item has none associated.
1324 static int l_get_tool_capabilities(lua_State *L)
1326 LuaItemStack *o = checkobject(L, 1);
1327 ItemStack &item = o->m_stack;
1328 const ToolCapabilities &prop =
1329 item.getToolCapabilities(get_server(L)->idef());
1330 push_tool_capabilities(L, prop);
1334 // add_wear(self, amount) -> true/false
1335 // The range for "amount" is [0,65535]. Wear is only added if the item
1336 // is a tool. Adding wear might destroy the item.
1337 // Returns true if the item is (or was) a tool.
1338 static int l_add_wear(lua_State *L)
1340 LuaItemStack *o = checkobject(L, 1);
1341 ItemStack &item = o->m_stack;
1342 int amount = lua_tointeger(L, 2);
1343 bool result = item.addWear(amount, get_server(L)->idef());
1344 lua_pushboolean(L, result);
1348 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1349 // Returns leftover item stack
1350 static int l_add_item(lua_State *L)
1352 LuaItemStack *o = checkobject(L, 1);
1353 ItemStack &item = o->m_stack;
1354 ItemStack newitem = read_item(L, 2);
1355 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1356 create(L, leftover);
1360 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1361 // First return value is true iff the new item fits fully into the stack
1362 // Second return value is the would-be-left-over item stack
1363 static int l_item_fits(lua_State *L)
1365 LuaItemStack *o = checkobject(L, 1);
1366 ItemStack &item = o->m_stack;
1367 ItemStack newitem = read_item(L, 2);
1369 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1370 lua_pushboolean(L, fits); // first return value
1371 create(L, restitem); // second return value
1375 // take_item(self, takecount=1) -> itemstack
1376 static int l_take_item(lua_State *L)
1378 LuaItemStack *o = checkobject(L, 1);
1379 ItemStack &item = o->m_stack;
1381 if(!lua_isnone(L, 2))
1382 takecount = lua_tointeger(L, 2);
1383 ItemStack taken = item.takeItem(takecount);
1388 // peek_item(self, peekcount=1) -> itemstack
1389 static int l_peek_item(lua_State *L)
1391 LuaItemStack *o = checkobject(L, 1);
1392 ItemStack &item = o->m_stack;
1394 if(!lua_isnone(L, 2))
1395 peekcount = lua_tointeger(L, 2);
1396 ItemStack peekaboo = item.peekItem(peekcount);
1397 create(L, peekaboo);
1402 LuaItemStack(const ItemStack &item):
1411 const ItemStack& getItem() const
1415 ItemStack& getItem()
1420 // LuaItemStack(itemstack or itemstring or table or nil)
1421 // Creates an LuaItemStack and leaves it on top of stack
1422 static int create_object(lua_State *L)
1424 ItemStack item = read_item(L, 1);
1425 LuaItemStack *o = new LuaItemStack(item);
1426 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1427 luaL_getmetatable(L, className);
1428 lua_setmetatable(L, -2);
1431 // Not callable from Lua
1432 static int create(lua_State *L, const ItemStack &item)
1434 LuaItemStack *o = new LuaItemStack(item);
1435 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1436 luaL_getmetatable(L, className);
1437 lua_setmetatable(L, -2);
1441 static LuaItemStack* checkobject(lua_State *L, int narg)
1443 luaL_checktype(L, narg, LUA_TUSERDATA);
1444 void *ud = luaL_checkudata(L, narg, className);
1445 if(!ud) luaL_typerror(L, narg, className);
1446 return *(LuaItemStack**)ud; // unbox pointer
1449 static void Register(lua_State *L)
1452 int methodtable = lua_gettop(L);
1453 luaL_newmetatable(L, className);
1454 int metatable = lua_gettop(L);
1456 lua_pushliteral(L, "__metatable");
1457 lua_pushvalue(L, methodtable);
1458 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1460 lua_pushliteral(L, "__index");
1461 lua_pushvalue(L, methodtable);
1462 lua_settable(L, metatable);
1464 lua_pushliteral(L, "__gc");
1465 lua_pushcfunction(L, gc_object);
1466 lua_settable(L, metatable);
1468 lua_pop(L, 1); // drop metatable
1470 luaL_openlib(L, 0, methods, 0); // fill methodtable
1471 lua_pop(L, 1); // drop methodtable
1473 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1474 lua_register(L, className, create_object);
1477 const char LuaItemStack::className[] = "ItemStack";
1478 const luaL_reg LuaItemStack::methods[] = {
1479 method(LuaItemStack, is_empty),
1480 method(LuaItemStack, get_name),
1481 method(LuaItemStack, get_count),
1482 method(LuaItemStack, get_wear),
1483 method(LuaItemStack, get_metadata),
1484 method(LuaItemStack, clear),
1485 method(LuaItemStack, replace),
1486 method(LuaItemStack, to_string),
1487 method(LuaItemStack, to_table),
1488 method(LuaItemStack, get_stack_max),
1489 method(LuaItemStack, get_free_space),
1490 method(LuaItemStack, is_known),
1491 method(LuaItemStack, get_definition),
1492 method(LuaItemStack, get_tool_capabilities),
1493 method(LuaItemStack, add_wear),
1494 method(LuaItemStack, add_item),
1495 method(LuaItemStack, item_fits),
1496 method(LuaItemStack, take_item),
1497 method(LuaItemStack, peek_item),
1501 static ItemStack read_item(lua_State *L, int index)
1504 index = lua_gettop(L) + 1 + index;
1506 if(lua_isnil(L, index))
1510 else if(lua_isuserdata(L, index))
1512 // Convert from LuaItemStack
1513 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1514 return o->getItem();
1516 else if(lua_isstring(L, index))
1518 // Convert from itemstring
1519 std::string itemstring = lua_tostring(L, index);
1520 IItemDefManager *idef = get_server(L)->idef();
1524 item.deSerialize(itemstring, idef);
1527 catch(SerializationError &e)
1529 infostream<<"WARNING: unable to create item from itemstring"
1530 <<": "<<itemstring<<std::endl;
1534 else if(lua_istable(L, index))
1536 // Convert from table
1537 IItemDefManager *idef = get_server(L)->idef();
1538 std::string name = getstringfield_default(L, index, "name", "");
1539 int count = getintfield_default(L, index, "count", 1);
1540 int wear = getintfield_default(L, index, "wear", 0);
1541 std::string metadata = getstringfield_default(L, index, "metadata", "");
1542 return ItemStack(name, count, wear, metadata, idef);
1546 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1557 InventoryLocation m_loc;
1559 static const char className[];
1560 static const luaL_reg methods[];
1562 static InvRef *checkobject(lua_State *L, int narg)
1564 luaL_checktype(L, narg, LUA_TUSERDATA);
1565 void *ud = luaL_checkudata(L, narg, className);
1566 if(!ud) luaL_typerror(L, narg, className);
1567 return *(InvRef**)ud; // unbox pointer
1570 static Inventory* getinv(lua_State *L, InvRef *ref)
1572 return get_server(L)->getInventory(ref->m_loc);
1575 static InventoryList* getlist(lua_State *L, InvRef *ref,
1576 const char *listname)
1578 Inventory *inv = getinv(L, ref);
1581 return inv->getList(listname);
1584 static void reportInventoryChange(lua_State *L, InvRef *ref)
1586 // Inform other things that the inventory has changed
1587 get_server(L)->setInventoryModified(ref->m_loc);
1590 // Exported functions
1592 // garbage collector
1593 static int gc_object(lua_State *L) {
1594 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1599 // get_size(self, listname)
1600 static int l_get_size(lua_State *L)
1602 InvRef *ref = checkobject(L, 1);
1603 const char *listname = luaL_checkstring(L, 2);
1604 InventoryList *list = getlist(L, ref, listname);
1606 lua_pushinteger(L, list->getSize());
1608 lua_pushinteger(L, 0);
1613 // set_size(self, listname, size)
1614 static int l_set_size(lua_State *L)
1616 InvRef *ref = checkobject(L, 1);
1617 const char *listname = luaL_checkstring(L, 2);
1618 int newsize = luaL_checknumber(L, 3);
1619 Inventory *inv = getinv(L, ref);
1621 inv->deleteList(listname);
1622 reportInventoryChange(L, ref);
1625 InventoryList *list = inv->getList(listname);
1627 list->setSize(newsize);
1629 list = inv->addList(listname, newsize);
1631 reportInventoryChange(L, ref);
1635 // get_stack(self, listname, i) -> itemstack
1636 static int l_get_stack(lua_State *L)
1638 InvRef *ref = checkobject(L, 1);
1639 const char *listname = luaL_checkstring(L, 2);
1640 int i = luaL_checknumber(L, 3) - 1;
1641 InventoryList *list = getlist(L, ref, listname);
1643 if(list != NULL && i >= 0 && i < (int) list->getSize())
1644 item = list->getItem(i);
1645 LuaItemStack::create(L, item);
1649 // set_stack(self, listname, i, stack) -> true/false
1650 static int l_set_stack(lua_State *L)
1652 InvRef *ref = checkobject(L, 1);
1653 const char *listname = luaL_checkstring(L, 2);
1654 int i = luaL_checknumber(L, 3) - 1;
1655 ItemStack newitem = read_item(L, 4);
1656 InventoryList *list = getlist(L, ref, listname);
1657 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1658 list->changeItem(i, newitem);
1659 reportInventoryChange(L, ref);
1660 lua_pushboolean(L, true);
1662 lua_pushboolean(L, false);
1667 // get_list(self, listname) -> list or nil
1668 static int l_get_list(lua_State *L)
1670 InvRef *ref = checkobject(L, 1);
1671 const char *listname = luaL_checkstring(L, 2);
1672 Inventory *inv = getinv(L, ref);
1673 inventory_get_list_to_lua(inv, listname, L);
1677 // set_list(self, listname, list)
1678 static int l_set_list(lua_State *L)
1680 InvRef *ref = checkobject(L, 1);
1681 const char *listname = luaL_checkstring(L, 2);
1682 Inventory *inv = getinv(L, ref);
1683 InventoryList *list = inv->getList(listname);
1685 inventory_set_list_from_lua(inv, listname, L, 3,
1688 inventory_set_list_from_lua(inv, listname, L, 3);
1689 reportInventoryChange(L, ref);
1693 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1694 // Returns the leftover stack
1695 static int l_add_item(lua_State *L)
1697 InvRef *ref = checkobject(L, 1);
1698 const char *listname = luaL_checkstring(L, 2);
1699 ItemStack item = read_item(L, 3);
1700 InventoryList *list = getlist(L, ref, listname);
1702 ItemStack leftover = list->addItem(item);
1703 if(leftover.count != item.count)
1704 reportInventoryChange(L, ref);
1705 LuaItemStack::create(L, leftover);
1707 LuaItemStack::create(L, item);
1712 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1713 // Returns true if the item completely fits into the list
1714 static int l_room_for_item(lua_State *L)
1716 InvRef *ref = checkobject(L, 1);
1717 const char *listname = luaL_checkstring(L, 2);
1718 ItemStack item = read_item(L, 3);
1719 InventoryList *list = getlist(L, ref, listname);
1721 lua_pushboolean(L, list->roomForItem(item));
1723 lua_pushboolean(L, false);
1728 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1729 // Returns true if the list contains the given count of the given item name
1730 static int l_contains_item(lua_State *L)
1732 InvRef *ref = checkobject(L, 1);
1733 const char *listname = luaL_checkstring(L, 2);
1734 ItemStack item = read_item(L, 3);
1735 InventoryList *list = getlist(L, ref, listname);
1737 lua_pushboolean(L, list->containsItem(item));
1739 lua_pushboolean(L, false);
1744 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1745 // Returns the items that were actually removed
1746 static int l_remove_item(lua_State *L)
1748 InvRef *ref = checkobject(L, 1);
1749 const char *listname = luaL_checkstring(L, 2);
1750 ItemStack item = read_item(L, 3);
1751 InventoryList *list = getlist(L, ref, listname);
1753 ItemStack removed = list->removeItem(item);
1754 if(!removed.empty())
1755 reportInventoryChange(L, ref);
1756 LuaItemStack::create(L, removed);
1758 LuaItemStack::create(L, ItemStack());
1764 InvRef(const InventoryLocation &loc):
1773 // Creates an InvRef and leaves it on top of stack
1774 // Not callable from Lua; all references are created on the C side.
1775 static void create(lua_State *L, const InventoryLocation &loc)
1777 InvRef *o = new InvRef(loc);
1778 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1779 luaL_getmetatable(L, className);
1780 lua_setmetatable(L, -2);
1782 static void createPlayer(lua_State *L, Player *player)
1784 InventoryLocation loc;
1785 loc.setPlayer(player->getName());
1788 static void createNodeMeta(lua_State *L, v3s16 p)
1790 InventoryLocation loc;
1795 static void Register(lua_State *L)
1798 int methodtable = lua_gettop(L);
1799 luaL_newmetatable(L, className);
1800 int metatable = lua_gettop(L);
1802 lua_pushliteral(L, "__metatable");
1803 lua_pushvalue(L, methodtable);
1804 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1806 lua_pushliteral(L, "__index");
1807 lua_pushvalue(L, methodtable);
1808 lua_settable(L, metatable);
1810 lua_pushliteral(L, "__gc");
1811 lua_pushcfunction(L, gc_object);
1812 lua_settable(L, metatable);
1814 lua_pop(L, 1); // drop metatable
1816 luaL_openlib(L, 0, methods, 0); // fill methodtable
1817 lua_pop(L, 1); // drop methodtable
1819 // Cannot be created from Lua
1820 //lua_register(L, className, create_object);
1823 const char InvRef::className[] = "InvRef";
1824 const luaL_reg InvRef::methods[] = {
1825 method(InvRef, get_size),
1826 method(InvRef, set_size),
1827 method(InvRef, get_stack),
1828 method(InvRef, set_stack),
1829 method(InvRef, get_list),
1830 method(InvRef, set_list),
1831 method(InvRef, add_item),
1832 method(InvRef, room_for_item),
1833 method(InvRef, contains_item),
1834 method(InvRef, remove_item),
1846 ServerEnvironment *m_env;
1848 static const char className[];
1849 static const luaL_reg methods[];
1851 static NodeMetaRef *checkobject(lua_State *L, int narg)
1853 luaL_checktype(L, narg, LUA_TUSERDATA);
1854 void *ud = luaL_checkudata(L, narg, className);
1855 if(!ud) luaL_typerror(L, narg, className);
1856 return *(NodeMetaRef**)ud; // unbox pointer
1859 static NodeMetadata* getmeta(NodeMetaRef *ref)
1861 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1865 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1867 NodeMetadata *meta = getmeta(ref);
1870 if(meta->typeId() != NODEMETA_GENERIC)
1872 return (IGenericNodeMetadata*)meta;
1875 static void reportMetadataChange(NodeMetaRef *ref)
1877 // Inform other things that the metadata has changed
1878 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1880 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1882 ref->m_env->getMap().dispatchEvent(&event);
1883 // Set the block to be saved
1884 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1886 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1887 "NodeMetaRef::reportMetadataChange");
1890 // Exported functions
1892 // garbage collector
1893 static int gc_object(lua_State *L) {
1894 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1900 static int l_get_type(lua_State *L)
1902 NodeMetaRef *ref = checkobject(L, 1);
1903 NodeMetadata *meta = getmeta(ref);
1909 lua_pushstring(L, meta->typeName());
1913 // allows_text_input(self)
1914 static int l_allows_text_input(lua_State *L)
1916 NodeMetaRef *ref = checkobject(L, 1);
1917 NodeMetadata *meta = getmeta(ref);
1918 if(meta == NULL) return 0;
1920 lua_pushboolean(L, meta->allowsTextInput());
1924 // set_text(self, text)
1925 static int l_set_text(lua_State *L)
1927 NodeMetaRef *ref = checkobject(L, 1);
1928 NodeMetadata *meta = getmeta(ref);
1929 if(meta == NULL) return 0;
1931 std::string text = luaL_checkstring(L, 2);
1932 meta->setText(text);
1933 reportMetadataChange(ref);
1938 static int l_get_text(lua_State *L)
1940 NodeMetaRef *ref = checkobject(L, 1);
1941 NodeMetadata *meta = getmeta(ref);
1942 if(meta == NULL) return 0;
1944 std::string text = meta->getText();
1945 lua_pushstring(L, text.c_str());
1950 static int l_get_owner(lua_State *L)
1952 NodeMetaRef *ref = checkobject(L, 1);
1953 NodeMetadata *meta = getmeta(ref);
1954 if(meta == NULL) return 0;
1956 std::string owner = meta->getOwner();
1957 lua_pushstring(L, owner.c_str());
1961 // set_owner(self, string)
1962 static int l_set_owner(lua_State *L)
1964 NodeMetaRef *ref = checkobject(L, 1);
1965 NodeMetadata *meta = getmeta(ref);
1966 if(meta == NULL) return 0;
1968 std::string owner = luaL_checkstring(L, 2);
1969 meta->setOwner(owner);
1970 reportMetadataChange(ref);
1974 // get_allow_removal(self)
1975 static int l_get_allow_removal(lua_State *L)
1977 NodeMetaRef *ref = checkobject(L, 1);
1978 NodeMetadata *meta = getmeta(ref);
1980 lua_pushboolean(L, true);
1984 lua_pushboolean(L, !meta->nodeRemovalDisabled());
1988 /* IGenericNodeMetadata interface */
1990 // set_infotext(self, text)
1991 static int l_set_infotext(lua_State *L)
1993 NodeMetaRef *ref = checkobject(L, 1);
1994 NodeMetadata *meta = getmeta(ref);
1995 if(meta == NULL) return 0;
1997 std::string text = luaL_checkstring(L, 2);
1998 meta->setInfoText(text);
1999 reportMetadataChange(ref);
2003 // get_inventory(self)
2004 static int l_get_inventory(lua_State *L)
2006 NodeMetaRef *ref = checkobject(L, 1);
2007 NodeMetadata *meta = getmeta(ref);
2008 if(meta == NULL) return 0;
2010 InvRef::createNodeMeta(L, ref->m_p);
2014 // set_inventory_draw_spec(self, text)
2015 static int l_set_inventory_draw_spec(lua_State *L)
2017 NodeMetaRef *ref = checkobject(L, 1);
2018 NodeMetadata *meta = getmeta(ref);
2019 if(meta == NULL) return 0;
2021 std::string text = luaL_checkstring(L, 2);
2022 meta->setInventoryDrawSpec(text);
2023 reportMetadataChange(ref);
2027 // set_allow_text_input(self, text)
2028 static int l_set_allow_text_input(lua_State *L)
2030 NodeMetaRef *ref = checkobject(L, 1);
2031 NodeMetadata *meta = getmeta(ref);
2032 if(meta == NULL) return 0;
2034 bool b = lua_toboolean(L, 2);
2035 meta->setAllowTextInput(b);
2036 reportMetadataChange(ref);
2040 // set_allow_removal(self, text)
2041 static int l_set_allow_removal(lua_State *L)
2043 NodeMetaRef *ref = checkobject(L, 1);
2044 NodeMetadata *meta = getmeta(ref);
2045 if(meta == NULL) return 0;
2047 bool b = lua_toboolean(L, 2);
2048 meta->setRemovalDisabled(!b);
2049 reportMetadataChange(ref);
2053 // set_enforce_owner(self, text)
2054 static int l_set_enforce_owner(lua_State *L)
2056 NodeMetaRef *ref = checkobject(L, 1);
2057 NodeMetadata *meta = getmeta(ref);
2058 if(meta == NULL) return 0;
2060 bool b = lua_toboolean(L, 2);
2061 meta->setEnforceOwner(b);
2062 reportMetadataChange(ref);
2066 // is_inventory_modified(self)
2067 static int l_is_inventory_modified(lua_State *L)
2069 NodeMetaRef *ref = checkobject(L, 1);
2070 NodeMetadata *meta = getmeta(ref);
2071 if(meta == NULL) return 0;
2073 lua_pushboolean(L, meta->isInventoryModified());
2077 // reset_inventory_modified(self)
2078 static int l_reset_inventory_modified(lua_State *L)
2080 NodeMetaRef *ref = checkobject(L, 1);
2081 NodeMetadata *meta = getmeta(ref);
2082 if(meta == NULL) return 0;
2084 meta->resetInventoryModified();
2085 reportMetadataChange(ref);
2089 // is_text_modified(self)
2090 static int l_is_text_modified(lua_State *L)
2092 NodeMetaRef *ref = checkobject(L, 1);
2093 NodeMetadata *meta = getmeta(ref);
2094 if(meta == NULL) return 0;
2096 lua_pushboolean(L, meta->isTextModified());
2100 // reset_text_modified(self)
2101 static int l_reset_text_modified(lua_State *L)
2103 NodeMetaRef *ref = checkobject(L, 1);
2104 NodeMetadata *meta = getmeta(ref);
2105 if(meta == NULL) return 0;
2107 meta->resetTextModified();
2108 reportMetadataChange(ref);
2112 // set_string(self, name, var)
2113 static int l_set_string(lua_State *L)
2115 NodeMetaRef *ref = checkobject(L, 1);
2116 NodeMetadata *meta = getmeta(ref);
2117 if(meta == NULL) return 0;
2119 std::string name = luaL_checkstring(L, 2);
2121 const char *s = lua_tolstring(L, 3, &len);
2122 std::string str(s, len);
2123 meta->setString(name, str);
2124 reportMetadataChange(ref);
2128 // get_string(self, name)
2129 static int l_get_string(lua_State *L)
2131 NodeMetaRef *ref = checkobject(L, 1);
2132 NodeMetadata *meta = getmeta(ref);
2133 if(meta == NULL) return 0;
2135 std::string name = luaL_checkstring(L, 2);
2136 std::string str = meta->getString(name);
2137 lua_pushlstring(L, str.c_str(), str.size());
2142 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2152 // Creates an NodeMetaRef and leaves it on top of stack
2153 // Not callable from Lua; all references are created on the C side.
2154 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2156 NodeMetaRef *o = new NodeMetaRef(p, env);
2157 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2158 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2159 luaL_getmetatable(L, className);
2160 lua_setmetatable(L, -2);
2163 static void Register(lua_State *L)
2166 int methodtable = lua_gettop(L);
2167 luaL_newmetatable(L, className);
2168 int metatable = lua_gettop(L);
2170 lua_pushliteral(L, "__metatable");
2171 lua_pushvalue(L, methodtable);
2172 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2174 lua_pushliteral(L, "__index");
2175 lua_pushvalue(L, methodtable);
2176 lua_settable(L, metatable);
2178 lua_pushliteral(L, "__gc");
2179 lua_pushcfunction(L, gc_object);
2180 lua_settable(L, metatable);
2182 lua_pop(L, 1); // drop metatable
2184 luaL_openlib(L, 0, methods, 0); // fill methodtable
2185 lua_pop(L, 1); // drop methodtable
2187 // Cannot be created from Lua
2188 //lua_register(L, className, create_object);
2191 const char NodeMetaRef::className[] = "NodeMetaRef";
2192 const luaL_reg NodeMetaRef::methods[] = {
2193 method(NodeMetaRef, get_type),
2194 method(NodeMetaRef, allows_text_input),
2195 method(NodeMetaRef, set_text),
2196 method(NodeMetaRef, get_text),
2197 method(NodeMetaRef, get_owner),
2198 method(NodeMetaRef, set_owner),
2199 method(NodeMetaRef, get_allow_removal),
2200 method(NodeMetaRef, set_infotext),
2201 method(NodeMetaRef, get_inventory),
2202 method(NodeMetaRef, set_inventory_draw_spec),
2203 method(NodeMetaRef, set_allow_text_input),
2204 method(NodeMetaRef, set_allow_removal),
2205 method(NodeMetaRef, set_enforce_owner),
2206 method(NodeMetaRef, is_inventory_modified),
2207 method(NodeMetaRef, reset_inventory_modified),
2208 method(NodeMetaRef, is_text_modified),
2209 method(NodeMetaRef, reset_text_modified),
2210 method(NodeMetaRef, set_string),
2211 method(NodeMetaRef, get_string),
2222 ServerActiveObject *m_object;
2224 static const char className[];
2225 static const luaL_reg methods[];
2227 static ObjectRef *checkobject(lua_State *L, int narg)
2229 luaL_checktype(L, narg, LUA_TUSERDATA);
2230 void *ud = luaL_checkudata(L, narg, className);
2231 if(!ud) luaL_typerror(L, narg, className);
2232 return *(ObjectRef**)ud; // unbox pointer
2235 static ServerActiveObject* getobject(ObjectRef *ref)
2237 ServerActiveObject *co = ref->m_object;
2241 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2243 ServerActiveObject *obj = getobject(ref);
2246 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2248 return (LuaEntitySAO*)obj;
2251 static ServerRemotePlayer* getplayer(ObjectRef *ref)
2253 ServerActiveObject *obj = getobject(ref);
2256 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2258 return static_cast<ServerRemotePlayer*>(obj);
2261 // Exported functions
2263 // garbage collector
2264 static int gc_object(lua_State *L) {
2265 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2266 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2272 static int l_remove(lua_State *L)
2274 ObjectRef *ref = checkobject(L, 1);
2275 ServerActiveObject *co = getobject(ref);
2276 if(co == NULL) return 0;
2277 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2278 co->m_removed = true;
2283 // returns: {x=num, y=num, z=num}
2284 static int l_getpos(lua_State *L)
2286 ObjectRef *ref = checkobject(L, 1);
2287 ServerActiveObject *co = getobject(ref);
2288 if(co == NULL) return 0;
2289 v3f pos = co->getBasePosition() / BS;
2291 lua_pushnumber(L, pos.X);
2292 lua_setfield(L, -2, "x");
2293 lua_pushnumber(L, pos.Y);
2294 lua_setfield(L, -2, "y");
2295 lua_pushnumber(L, pos.Z);
2296 lua_setfield(L, -2, "z");
2300 // setpos(self, pos)
2301 static int l_setpos(lua_State *L)
2303 ObjectRef *ref = checkobject(L, 1);
2304 //LuaEntitySAO *co = getluaobject(ref);
2305 ServerActiveObject *co = getobject(ref);
2306 if(co == NULL) return 0;
2308 v3f pos = checkFloatPos(L, 2);
2311 // Move player if applicable
2312 ServerRemotePlayer *player = getplayer(ref);
2314 get_server(L)->SendMovePlayer(player);
2318 // moveto(self, pos, continuous=false)
2319 static int l_moveto(lua_State *L)
2321 ObjectRef *ref = checkobject(L, 1);
2322 //LuaEntitySAO *co = getluaobject(ref);
2323 ServerActiveObject *co = getobject(ref);
2324 if(co == NULL) return 0;
2326 v3f pos = checkFloatPos(L, 2);
2328 bool continuous = lua_toboolean(L, 3);
2330 co->moveTo(pos, continuous);
2334 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2335 static int l_punch(lua_State *L)
2337 ObjectRef *ref = checkobject(L, 1);
2338 ObjectRef *puncher_ref = checkobject(L, 2);
2339 ServerActiveObject *co = getobject(ref);
2340 ServerActiveObject *puncher = getobject(puncher_ref);
2341 if(co == NULL) return 0;
2342 if(puncher == NULL) return 0;
2343 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2344 v3f dir = read_v3f(L, 4);
2345 float time_from_last_punch = 1000000;
2346 if(lua_isnumber(L, 5))
2347 time_from_last_punch = lua_tonumber(L, 5);
2349 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2353 // right_click(self, clicker); clicker = an another ObjectRef
2354 static int l_right_click(lua_State *L)
2356 ObjectRef *ref = checkobject(L, 1);
2357 ObjectRef *ref2 = checkobject(L, 2);
2358 ServerActiveObject *co = getobject(ref);
2359 ServerActiveObject *co2 = getobject(ref2);
2360 if(co == NULL) return 0;
2361 if(co2 == NULL) return 0;
2363 co->rightClick(co2);
2368 // hp = number of hitpoints (2 * number of hearts)
2370 static int l_set_hp(lua_State *L)
2372 ObjectRef *ref = checkobject(L, 1);
2373 luaL_checknumber(L, 2);
2374 ServerActiveObject *co = getobject(ref);
2375 if(co == NULL) return 0;
2376 int hp = lua_tonumber(L, 2);
2377 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2378 <<" hp="<<hp<<std::endl;*/
2386 // returns: number of hitpoints (2 * number of hearts)
2387 // 0 if not applicable to this type of object
2388 static int l_get_hp(lua_State *L)
2390 ObjectRef *ref = checkobject(L, 1);
2391 ServerActiveObject *co = getobject(ref);
2392 if(co == NULL) return 0;
2393 int hp = co->getHP();
2394 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2395 <<" hp="<<hp<<std::endl;*/
2397 lua_pushnumber(L, hp);
2401 // get_inventory(self)
2402 static int l_get_inventory(lua_State *L)
2404 ObjectRef *ref = checkobject(L, 1);
2405 ServerActiveObject *co = getobject(ref);
2406 if(co == NULL) return 0;
2408 InventoryLocation loc = co->getInventoryLocation();
2409 if(get_server(L)->getInventory(loc) != NULL)
2410 InvRef::create(L, loc);
2416 // get_wield_list(self)
2417 static int l_get_wield_list(lua_State *L)
2419 ObjectRef *ref = checkobject(L, 1);
2420 ServerActiveObject *co = getobject(ref);
2421 if(co == NULL) return 0;
2423 lua_pushstring(L, co->getWieldList().c_str());
2427 // get_wield_index(self)
2428 static int l_get_wield_index(lua_State *L)
2430 ObjectRef *ref = checkobject(L, 1);
2431 ServerActiveObject *co = getobject(ref);
2432 if(co == NULL) return 0;
2434 lua_pushinteger(L, co->getWieldIndex() + 1);
2438 // get_wielded_item(self)
2439 static int l_get_wielded_item(lua_State *L)
2441 ObjectRef *ref = checkobject(L, 1);
2442 ServerActiveObject *co = getobject(ref);
2443 if(co == NULL) return 0;
2445 LuaItemStack::create(L, co->getWieldedItem());
2449 // set_wielded_item(self, itemstack or itemstring or table or nil)
2450 static int l_set_wielded_item(lua_State *L)
2452 ObjectRef *ref = checkobject(L, 1);
2453 ServerActiveObject *co = getobject(ref);
2454 if(co == NULL) return 0;
2456 ItemStack item = read_item(L, 2);
2457 bool success = co->setWieldedItem(item);
2458 lua_pushboolean(L, success);
2462 /* LuaEntitySAO-only */
2464 // setvelocity(self, {x=num, y=num, z=num})
2465 static int l_setvelocity(lua_State *L)
2467 ObjectRef *ref = checkobject(L, 1);
2468 LuaEntitySAO *co = getluaobject(ref);
2469 if(co == NULL) return 0;
2471 v3f pos = checkFloatPos(L, 2);
2473 co->setVelocity(pos);
2477 // getvelocity(self)
2478 static int l_getvelocity(lua_State *L)
2480 ObjectRef *ref = checkobject(L, 1);
2481 LuaEntitySAO *co = getluaobject(ref);
2482 if(co == NULL) return 0;
2484 v3f v = co->getVelocity();
2489 // setacceleration(self, {x=num, y=num, z=num})
2490 static int l_setacceleration(lua_State *L)
2492 ObjectRef *ref = checkobject(L, 1);
2493 LuaEntitySAO *co = getluaobject(ref);
2494 if(co == NULL) return 0;
2496 v3f pos = checkFloatPos(L, 2);
2498 co->setAcceleration(pos);
2502 // getacceleration(self)
2503 static int l_getacceleration(lua_State *L)
2505 ObjectRef *ref = checkobject(L, 1);
2506 LuaEntitySAO *co = getluaobject(ref);
2507 if(co == NULL) return 0;
2509 v3f v = co->getAcceleration();
2514 // setyaw(self, radians)
2515 static int l_setyaw(lua_State *L)
2517 ObjectRef *ref = checkobject(L, 1);
2518 LuaEntitySAO *co = getluaobject(ref);
2519 if(co == NULL) return 0;
2521 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2528 static int l_getyaw(lua_State *L)
2530 ObjectRef *ref = checkobject(L, 1);
2531 LuaEntitySAO *co = getluaobject(ref);
2532 if(co == NULL) return 0;
2534 float yaw = co->getYaw() * core::DEGTORAD;
2535 lua_pushnumber(L, yaw);
2539 // settexturemod(self, mod)
2540 static int l_settexturemod(lua_State *L)
2542 ObjectRef *ref = checkobject(L, 1);
2543 LuaEntitySAO *co = getluaobject(ref);
2544 if(co == NULL) return 0;
2546 std::string mod = luaL_checkstring(L, 2);
2547 co->setTextureMod(mod);
2551 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2552 // select_horiz_by_yawpitch=false)
2553 static int l_setsprite(lua_State *L)
2555 ObjectRef *ref = checkobject(L, 1);
2556 LuaEntitySAO *co = getluaobject(ref);
2557 if(co == NULL) return 0;
2560 if(!lua_isnil(L, 2))
2561 p = read_v2s16(L, 2);
2563 if(!lua_isnil(L, 3))
2564 num_frames = lua_tonumber(L, 3);
2565 float framelength = 0.2;
2566 if(!lua_isnil(L, 4))
2567 framelength = lua_tonumber(L, 4);
2568 bool select_horiz_by_yawpitch = false;
2569 if(!lua_isnil(L, 5))
2570 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2571 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2575 // set_armor_groups(self, groups)
2576 static int l_set_armor_groups(lua_State *L)
2578 ObjectRef *ref = checkobject(L, 1);
2579 LuaEntitySAO *co = getluaobject(ref);
2580 if(co == NULL) return 0;
2582 ItemGroupList groups;
2583 read_groups(L, 2, groups);
2584 co->setArmorGroups(groups);
2589 // get_entity_name(self)
2590 static int l_get_entity_name(lua_State *L)
2592 ObjectRef *ref = checkobject(L, 1);
2593 LuaEntitySAO *co = getluaobject(ref);
2594 if(co == NULL) return 0;
2596 std::string name = co->getName();
2597 lua_pushstring(L, name.c_str());
2601 // get_luaentity(self)
2602 static int l_get_luaentity(lua_State *L)
2604 ObjectRef *ref = checkobject(L, 1);
2605 LuaEntitySAO *co = getluaobject(ref);
2606 if(co == NULL) return 0;
2608 luaentity_get(L, co->getId());
2614 // get_player_name(self)
2615 static int l_get_player_name(lua_State *L)
2617 ObjectRef *ref = checkobject(L, 1);
2618 ServerRemotePlayer *player = getplayer(ref);
2624 lua_pushstring(L, player->getName());
2628 // get_look_dir(self)
2629 static int l_get_look_dir(lua_State *L)
2631 ObjectRef *ref = checkobject(L, 1);
2632 ServerRemotePlayer *player = getplayer(ref);
2633 if(player == NULL) return 0;
2635 float pitch = player->getRadPitch();
2636 float yaw = player->getRadYaw();
2637 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2642 // get_look_pitch(self)
2643 static int l_get_look_pitch(lua_State *L)
2645 ObjectRef *ref = checkobject(L, 1);
2646 ServerRemotePlayer *player = getplayer(ref);
2647 if(player == NULL) return 0;
2649 lua_pushnumber(L, player->getRadPitch());
2653 // get_look_yaw(self)
2654 static int l_get_look_yaw(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->getRadYaw());
2665 ObjectRef(ServerActiveObject *object):
2668 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2674 infostream<<"ObjectRef destructing for id="
2675 <<m_object->getId()<<std::endl;
2677 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2680 // Creates an ObjectRef and leaves it on top of stack
2681 // Not callable from Lua; all references are created on the C side.
2682 static void create(lua_State *L, ServerActiveObject *object)
2684 ObjectRef *o = new ObjectRef(object);
2685 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2686 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2687 luaL_getmetatable(L, className);
2688 lua_setmetatable(L, -2);
2691 static void set_null(lua_State *L)
2693 ObjectRef *o = checkobject(L, -1);
2697 static void Register(lua_State *L)
2700 int methodtable = lua_gettop(L);
2701 luaL_newmetatable(L, className);
2702 int metatable = lua_gettop(L);
2704 lua_pushliteral(L, "__metatable");
2705 lua_pushvalue(L, methodtable);
2706 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2708 lua_pushliteral(L, "__index");
2709 lua_pushvalue(L, methodtable);
2710 lua_settable(L, metatable);
2712 lua_pushliteral(L, "__gc");
2713 lua_pushcfunction(L, gc_object);
2714 lua_settable(L, metatable);
2716 lua_pop(L, 1); // drop metatable
2718 luaL_openlib(L, 0, methods, 0); // fill methodtable
2719 lua_pop(L, 1); // drop methodtable
2721 // Cannot be created from Lua
2722 //lua_register(L, className, create_object);
2725 const char ObjectRef::className[] = "ObjectRef";
2726 const luaL_reg ObjectRef::methods[] = {
2727 // ServerActiveObject
2728 method(ObjectRef, remove),
2729 method(ObjectRef, getpos),
2730 method(ObjectRef, setpos),
2731 method(ObjectRef, moveto),
2732 method(ObjectRef, punch),
2733 method(ObjectRef, right_click),
2734 method(ObjectRef, set_hp),
2735 method(ObjectRef, get_hp),
2736 method(ObjectRef, get_inventory),
2737 method(ObjectRef, get_wield_list),
2738 method(ObjectRef, get_wield_index),
2739 method(ObjectRef, get_wielded_item),
2740 method(ObjectRef, set_wielded_item),
2741 // LuaEntitySAO-only
2742 method(ObjectRef, setvelocity),
2743 method(ObjectRef, getvelocity),
2744 method(ObjectRef, setacceleration),
2745 method(ObjectRef, getacceleration),
2746 method(ObjectRef, setyaw),
2747 method(ObjectRef, getyaw),
2748 method(ObjectRef, settexturemod),
2749 method(ObjectRef, setsprite),
2750 method(ObjectRef, set_armor_groups),
2751 method(ObjectRef, get_entity_name),
2752 method(ObjectRef, get_luaentity),
2754 method(ObjectRef, get_player_name),
2755 method(ObjectRef, get_look_dir),
2756 method(ObjectRef, get_look_pitch),
2757 method(ObjectRef, get_look_yaw),
2761 // Creates a new anonymous reference if id=0
2762 static void objectref_get_or_create(lua_State *L,
2763 ServerActiveObject *cobj)
2765 if(cobj->getId() == 0){
2766 ObjectRef::create(L, cobj);
2768 objectref_get(L, cobj->getId());
2779 ServerEnvironment *m_env;
2781 static const char className[];
2782 static const luaL_reg methods[];
2784 static EnvRef *checkobject(lua_State *L, int narg)
2786 luaL_checktype(L, narg, LUA_TUSERDATA);
2787 void *ud = luaL_checkudata(L, narg, className);
2788 if(!ud) luaL_typerror(L, narg, className);
2789 return *(EnvRef**)ud; // unbox pointer
2792 // Exported functions
2794 // EnvRef:add_node(pos, node)
2795 // pos = {x=num, y=num, z=num}
2796 static int l_add_node(lua_State *L)
2798 //infostream<<"EnvRef::l_add_node()"<<std::endl;
2799 EnvRef *o = checkobject(L, 1);
2800 ServerEnvironment *env = o->m_env;
2801 if(env == NULL) return 0;
2803 v3s16 pos = read_v3s16(L, 2);
2805 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2807 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2808 lua_pushboolean(L, succeeded);
2812 // EnvRef:remove_node(pos)
2813 // pos = {x=num, y=num, z=num}
2814 static int l_remove_node(lua_State *L)
2816 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2817 EnvRef *o = checkobject(L, 1);
2818 ServerEnvironment *env = o->m_env;
2819 if(env == NULL) return 0;
2821 v3s16 pos = read_v3s16(L, 2);
2823 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2824 lua_pushboolean(L, succeeded);
2828 // EnvRef:get_node(pos)
2829 // pos = {x=num, y=num, z=num}
2830 static int l_get_node(lua_State *L)
2832 //infostream<<"EnvRef::l_get_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 MapNode n = env->getMap().getNodeNoEx(pos);
2841 pushnode(L, n, env->getGameDef()->ndef());
2845 // EnvRef:get_node_or_nil(pos)
2846 // pos = {x=num, y=num, z=num}
2847 static int l_get_node_or_nil(lua_State *L)
2849 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2850 EnvRef *o = checkobject(L, 1);
2851 ServerEnvironment *env = o->m_env;
2852 if(env == NULL) return 0;
2854 v3s16 pos = read_v3s16(L, 2);
2857 MapNode n = env->getMap().getNode(pos);
2859 pushnode(L, n, env->getGameDef()->ndef());
2861 } catch(InvalidPositionException &e)
2868 // EnvRef:get_node_light(pos, timeofday)
2869 // pos = {x=num, y=num, z=num}
2870 // timeofday: nil = current time, 0 = night, 0.5 = day
2871 static int l_get_node_light(lua_State *L)
2873 EnvRef *o = checkobject(L, 1);
2874 ServerEnvironment *env = o->m_env;
2875 if(env == NULL) return 0;
2877 v3s16 pos = read_v3s16(L, 2);
2878 u32 time_of_day = env->getTimeOfDay();
2879 if(lua_isnumber(L, 3))
2880 time_of_day = 24000.0 * lua_tonumber(L, 3);
2881 time_of_day %= 24000;
2882 u32 dnr = time_to_daynight_ratio(time_of_day);
2883 MapNode n = env->getMap().getNodeNoEx(pos);
2885 MapNode n = env->getMap().getNode(pos);
2886 INodeDefManager *ndef = env->getGameDef()->ndef();
2887 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2889 } catch(InvalidPositionException &e)
2896 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2897 // pos = {x=num, y=num, z=num}
2898 static int l_add_entity(lua_State *L)
2900 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2901 EnvRef *o = checkobject(L, 1);
2902 ServerEnvironment *env = o->m_env;
2903 if(env == NULL) return 0;
2905 v3f pos = checkFloatPos(L, 2);
2907 const char *name = luaL_checkstring(L, 3);
2909 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2910 int objectid = env->addActiveObject(obj);
2911 // If failed to add, return nothing (reads as nil)
2915 objectref_get_or_create(L, obj);
2919 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2920 // pos = {x=num, y=num, z=num}
2921 static int l_add_item(lua_State *L)
2923 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2924 EnvRef *o = checkobject(L, 1);
2925 ServerEnvironment *env = o->m_env;
2926 if(env == NULL) return 0;
2928 v3f pos = checkFloatPos(L, 2);
2930 ItemStack item = read_item(L, 3);
2931 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2934 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2935 int objectid = env->addActiveObject(obj);
2936 // If failed to add, return nothing (reads as nil)
2940 objectref_get_or_create(L, obj);
2944 // EnvRef:add_rat(pos)
2945 // pos = {x=num, y=num, z=num}
2946 static int l_add_rat(lua_State *L)
2948 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2949 <<" Doing nothing."<<std::endl;
2953 // EnvRef:add_firefly(pos)
2954 // pos = {x=num, y=num, z=num}
2955 static int l_add_firefly(lua_State *L)
2957 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2958 <<" Doing nothing."<<std::endl;
2962 // EnvRef:get_meta(pos)
2963 static int l_get_meta(lua_State *L)
2965 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2966 EnvRef *o = checkobject(L, 1);
2967 ServerEnvironment *env = o->m_env;
2968 if(env == NULL) return 0;
2970 v3s16 p = read_v3s16(L, 2);
2971 NodeMetaRef::create(L, p, env);
2975 // EnvRef:get_player_by_name(name)
2976 static int l_get_player_by_name(lua_State *L)
2978 EnvRef *o = checkobject(L, 1);
2979 ServerEnvironment *env = o->m_env;
2980 if(env == NULL) return 0;
2982 const char *name = luaL_checkstring(L, 2);
2983 ServerRemotePlayer *player =
2984 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2989 // Put player on stack
2990 objectref_get_or_create(L, player);
2994 // EnvRef:get_objects_inside_radius(pos, radius)
2995 static int l_get_objects_inside_radius(lua_State *L)
2997 // Get the table insert function
2998 lua_getglobal(L, "table");
2999 lua_getfield(L, -1, "insert");
3000 int table_insert = lua_gettop(L);
3002 EnvRef *o = checkobject(L, 1);
3003 ServerEnvironment *env = o->m_env;
3004 if(env == NULL) return 0;
3006 v3f pos = checkFloatPos(L, 2);
3007 float radius = luaL_checknumber(L, 3) * BS;
3008 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3010 int table = lua_gettop(L);
3011 for(std::set<u16>::const_iterator
3012 i = ids.begin(); i != ids.end(); i++){
3013 ServerActiveObject *obj = env->getActiveObject(*i);
3014 // Insert object reference into table
3015 lua_pushvalue(L, table_insert);
3016 lua_pushvalue(L, table);
3017 objectref_get_or_create(L, obj);
3018 if(lua_pcall(L, 2, 0, 0))
3019 script_error(L, "error: %s", lua_tostring(L, -1));
3024 // EnvRef:set_timeofday(val)
3026 static int l_set_timeofday(lua_State *L)
3028 EnvRef *o = checkobject(L, 1);
3029 ServerEnvironment *env = o->m_env;
3030 if(env == NULL) return 0;
3032 float timeofday_f = luaL_checknumber(L, 2);
3033 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3034 int timeofday_mh = (int)(timeofday_f * 24000.0);
3035 // This should be set directly in the environment but currently
3036 // such changes aren't immediately sent to the clients, so call
3037 // the server instead.
3038 //env->setTimeOfDay(timeofday_mh);
3039 get_server(L)->setTimeOfDay(timeofday_mh);
3043 // EnvRef:get_timeofday() -> 0...1
3044 static int l_get_timeofday(lua_State *L)
3046 EnvRef *o = checkobject(L, 1);
3047 ServerEnvironment *env = o->m_env;
3048 if(env == NULL) return 0;
3050 int timeofday_mh = env->getTimeOfDay();
3051 float timeofday_f = (float)timeofday_mh / 24000.0;
3052 lua_pushnumber(L, timeofday_f);
3056 static int gc_object(lua_State *L) {
3057 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3063 EnvRef(ServerEnvironment *env):
3066 //infostream<<"EnvRef created"<<std::endl;
3071 //infostream<<"EnvRef destructing"<<std::endl;
3074 // Creates an EnvRef and leaves it on top of stack
3075 // Not callable from Lua; all references are created on the C side.
3076 static void create(lua_State *L, ServerEnvironment *env)
3078 EnvRef *o = new EnvRef(env);
3079 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3080 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3081 luaL_getmetatable(L, className);
3082 lua_setmetatable(L, -2);
3085 static void set_null(lua_State *L)
3087 EnvRef *o = checkobject(L, -1);
3091 static void Register(lua_State *L)
3094 int methodtable = lua_gettop(L);
3095 luaL_newmetatable(L, className);
3096 int metatable = lua_gettop(L);
3098 lua_pushliteral(L, "__metatable");
3099 lua_pushvalue(L, methodtable);
3100 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3102 lua_pushliteral(L, "__index");
3103 lua_pushvalue(L, methodtable);
3104 lua_settable(L, metatable);
3106 lua_pushliteral(L, "__gc");
3107 lua_pushcfunction(L, gc_object);
3108 lua_settable(L, metatable);
3110 lua_pop(L, 1); // drop metatable
3112 luaL_openlib(L, 0, methods, 0); // fill methodtable
3113 lua_pop(L, 1); // drop methodtable
3115 // Cannot be created from Lua
3116 //lua_register(L, className, create_object);
3119 const char EnvRef::className[] = "EnvRef";
3120 const luaL_reg EnvRef::methods[] = {
3121 method(EnvRef, add_node),
3122 method(EnvRef, remove_node),
3123 method(EnvRef, get_node),
3124 method(EnvRef, get_node_or_nil),
3125 method(EnvRef, get_node_light),
3126 method(EnvRef, add_entity),
3127 method(EnvRef, add_item),
3128 method(EnvRef, add_rat),
3129 method(EnvRef, add_firefly),
3130 method(EnvRef, get_meta),
3131 method(EnvRef, get_player_by_name),
3132 method(EnvRef, get_objects_inside_radius),
3133 method(EnvRef, set_timeofday),
3134 method(EnvRef, get_timeofday),
3142 class LuaPseudoRandom
3145 PseudoRandom m_pseudo;
3147 static const char className[];
3148 static const luaL_reg methods[];
3150 // Exported functions
3152 // garbage collector
3153 static int gc_object(lua_State *L)
3155 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3160 // next(self) -> get next value
3161 static int l_next(lua_State *L)
3163 LuaPseudoRandom *o = checkobject(L, 1);
3164 PseudoRandom &pseudo = o->m_pseudo;
3165 lua_pushinteger(L, pseudo.next());
3170 LuaPseudoRandom(int seed):
3179 const PseudoRandom& getItem() const
3183 PseudoRandom& getItem()
3188 // LuaPseudoRandom(seed)
3189 // Creates an LuaPseudoRandom and leaves it on top of stack
3190 static int create_object(lua_State *L)
3192 int seed = luaL_checknumber(L, 1);
3193 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3194 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3195 luaL_getmetatable(L, className);
3196 lua_setmetatable(L, -2);
3200 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3202 luaL_checktype(L, narg, LUA_TUSERDATA);
3203 void *ud = luaL_checkudata(L, narg, className);
3204 if(!ud) luaL_typerror(L, narg, className);
3205 return *(LuaPseudoRandom**)ud; // unbox pointer
3208 static void Register(lua_State *L)
3211 int methodtable = lua_gettop(L);
3212 luaL_newmetatable(L, className);
3213 int metatable = lua_gettop(L);
3215 lua_pushliteral(L, "__metatable");
3216 lua_pushvalue(L, methodtable);
3217 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3219 lua_pushliteral(L, "__index");
3220 lua_pushvalue(L, methodtable);
3221 lua_settable(L, metatable);
3223 lua_pushliteral(L, "__gc");
3224 lua_pushcfunction(L, gc_object);
3225 lua_settable(L, metatable);
3227 lua_pop(L, 1); // drop metatable
3229 luaL_openlib(L, 0, methods, 0); // fill methodtable
3230 lua_pop(L, 1); // drop methodtable
3232 // Can be created from Lua (LuaPseudoRandom(seed))
3233 lua_register(L, className, create_object);
3236 const char LuaPseudoRandom::className[] = "PseudoRandom";
3237 const luaL_reg LuaPseudoRandom::methods[] = {
3238 method(LuaPseudoRandom, next),
3246 class LuaABM : public ActiveBlockModifier
3252 std::set<std::string> m_trigger_contents;
3253 std::set<std::string> m_required_neighbors;
3254 float m_trigger_interval;
3255 u32 m_trigger_chance;
3257 LuaABM(lua_State *L, int id,
3258 const std::set<std::string> &trigger_contents,
3259 const std::set<std::string> &required_neighbors,
3260 float trigger_interval, u32 trigger_chance):
3263 m_trigger_contents(trigger_contents),
3264 m_required_neighbors(required_neighbors),
3265 m_trigger_interval(trigger_interval),
3266 m_trigger_chance(trigger_chance)
3269 virtual std::set<std::string> getTriggerContents()
3271 return m_trigger_contents;
3273 virtual std::set<std::string> getRequiredNeighbors()
3275 return m_required_neighbors;
3277 virtual float getTriggerInterval()
3279 return m_trigger_interval;
3281 virtual u32 getTriggerChance()
3283 return m_trigger_chance;
3285 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3286 u32 active_object_count, u32 active_object_count_wider)
3288 lua_State *L = m_lua;
3291 assert(lua_checkstack(L, 20));
3292 StackUnroller stack_unroller(L);
3294 // Get minetest.registered_abms
3295 lua_getglobal(L, "minetest");
3296 lua_getfield(L, -1, "registered_abms");
3297 luaL_checktype(L, -1, LUA_TTABLE);
3298 int registered_abms = lua_gettop(L);
3300 // Get minetest.registered_abms[m_id]
3301 lua_pushnumber(L, m_id);
3302 lua_gettable(L, registered_abms);
3303 if(lua_isnil(L, -1))
3307 luaL_checktype(L, -1, LUA_TTABLE);
3308 lua_getfield(L, -1, "action");
3309 luaL_checktype(L, -1, LUA_TFUNCTION);
3311 pushnode(L, n, env->getGameDef()->ndef());
3312 lua_pushnumber(L, active_object_count);
3313 lua_pushnumber(L, active_object_count_wider);
3314 if(lua_pcall(L, 4, 0, 0))
3315 script_error(L, "error: %s", lua_tostring(L, -1));
3323 static void read_server_sound_params(lua_State *L, int index,
3324 ServerSoundParams ¶ms)
3327 index = lua_gettop(L) + 1 + index;
3329 params = ServerSoundParams();
3330 if(lua_istable(L, index)){
3331 getfloatfield(L, index, "gain", params.gain);
3332 getstringfield(L, index, "to_player", params.to_player);
3333 lua_getfield(L, index, "pos");
3334 if(!lua_isnil(L, -1)){
3335 v3f p = read_v3f(L, -1)*BS;
3337 params.type = ServerSoundParams::SSP_POSITIONAL;
3340 lua_getfield(L, index, "object");
3341 if(!lua_isnil(L, -1)){
3342 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3343 ServerActiveObject *sao = ObjectRef::getobject(ref);
3345 params.object = sao->getId();
3346 params.type = ServerSoundParams::SSP_OBJECT;
3350 params.max_hear_distance = BS*getfloatfield_default(L, index,
3351 "max_hear_distance", params.max_hear_distance/BS);
3352 getboolfield(L, index, "loop", params.loop);
3361 // Writes a line to dstream
3362 static int l_debug(lua_State *L)
3364 std::string text = lua_tostring(L, 1);
3365 dstream << text << std::endl;
3369 // log([level,] text)
3370 // Writes a line to the logger.
3371 // The one-argument version logs to infostream.
3372 // The two-argument version accept a log level: error, action, info, or verbose.
3373 static int l_log(lua_State *L)
3376 LogMessageLevel level = LMT_INFO;
3377 if(lua_isnone(L, 2))
3379 text = lua_tostring(L, 1);
3383 std::string levelname = lua_tostring(L, 1);
3384 text = lua_tostring(L, 2);
3385 if(levelname == "error")
3387 else if(levelname == "action")
3389 else if(levelname == "verbose")
3390 level = LMT_VERBOSE;
3392 log_printline(level, text);
3396 // register_item_raw({lots of stuff})
3397 static int l_register_item_raw(lua_State *L)
3399 luaL_checktype(L, 1, LUA_TTABLE);
3402 // Get the writable item and node definition managers from the server
3403 IWritableItemDefManager *idef =
3404 get_server(L)->getWritableItemDefManager();
3405 IWritableNodeDefManager *ndef =
3406 get_server(L)->getWritableNodeDefManager();
3408 // Check if name is defined
3409 lua_getfield(L, table, "name");
3410 if(lua_isstring(L, -1)){
3411 std::string name = lua_tostring(L, -1);
3412 verbosestream<<"register_item_raw: "<<name<<std::endl;
3414 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3417 // Check if on_use is defined
3419 // Read the item definition and register it
3420 ItemDefinition def = read_item_definition(L, table);
3421 idef->registerItem(def);
3423 // Read the node definition (content features) and register it
3424 if(def.type == ITEM_NODE)
3426 ContentFeatures f = read_content_features(L, table);
3427 ndef->set(f.name, f);
3430 return 0; /* number of results */
3433 // register_alias_raw(name, convert_to_name)
3434 static int l_register_alias_raw(lua_State *L)
3436 std::string name = luaL_checkstring(L, 1);
3437 std::string convert_to = luaL_checkstring(L, 2);
3439 // Get the writable item definition manager from the server
3440 IWritableItemDefManager *idef =
3441 get_server(L)->getWritableItemDefManager();
3443 idef->registerAlias(name, convert_to);
3445 return 0; /* number of results */
3448 // helper for register_craft
3449 static bool read_craft_recipe_shaped(lua_State *L, int index,
3450 int &width, std::vector<std::string> &recipe)
3453 index = lua_gettop(L) + 1 + index;
3455 if(!lua_istable(L, index))
3460 while(lua_next(L, index) != 0){
3462 // key at index -2 and value at index -1
3463 if(!lua_istable(L, -1))
3465 int table2 = lua_gettop(L);
3467 while(lua_next(L, table2) != 0){
3468 // key at index -2 and value at index -1
3469 if(!lua_isstring(L, -1))
3471 recipe.push_back(lua_tostring(L, -1));
3472 // removes value, keeps key for next iteration
3479 if(colcount != width)
3482 // removes value, keeps key for next iteration
3489 // helper for register_craft
3490 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3491 std::vector<std::string> &recipe)
3494 index = lua_gettop(L) + 1 + index;
3496 if(!lua_istable(L, index))
3500 while(lua_next(L, index) != 0){
3501 // key at index -2 and value at index -1
3502 if(!lua_isstring(L, -1))
3504 recipe.push_back(lua_tostring(L, -1));
3505 // removes value, keeps key for next iteration
3511 // helper for register_craft
3512 static bool read_craft_replacements(lua_State *L, int index,
3513 CraftReplacements &replacements)
3516 index = lua_gettop(L) + 1 + index;
3518 if(!lua_istable(L, index))
3522 while(lua_next(L, index) != 0){
3523 // key at index -2 and value at index -1
3524 if(!lua_istable(L, -1))
3526 lua_rawgeti(L, -1, 1);
3527 if(!lua_isstring(L, -1))
3529 std::string replace_from = lua_tostring(L, -1);
3531 lua_rawgeti(L, -1, 2);
3532 if(!lua_isstring(L, -1))
3534 std::string replace_to = lua_tostring(L, -1);
3536 replacements.pairs.push_back(
3537 std::make_pair(replace_from, replace_to));
3538 // removes value, keeps key for next iteration
3543 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3544 static int l_register_craft(lua_State *L)
3546 //infostream<<"register_craft"<<std::endl;
3547 luaL_checktype(L, 1, LUA_TTABLE);
3550 // Get the writable craft definition manager from the server
3551 IWritableCraftDefManager *craftdef =
3552 get_server(L)->getWritableCraftDefManager();
3554 std::string type = getstringfield_default(L, table, "type", "shaped");
3557 CraftDefinitionShaped
3559 if(type == "shaped"){
3560 std::string output = getstringfield_default(L, table, "output", "");
3562 throw LuaError(L, "Crafting definition is missing an output");
3565 std::vector<std::string> recipe;
3566 lua_getfield(L, table, "recipe");
3567 if(lua_isnil(L, -1))
3568 throw LuaError(L, "Crafting definition is missing a recipe"
3569 " (output=\"" + output + "\")");
3570 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3571 throw LuaError(L, "Invalid crafting recipe"
3572 " (output=\"" + output + "\")");
3574 CraftReplacements replacements;
3575 lua_getfield(L, table, "replacements");
3576 if(!lua_isnil(L, -1))
3578 if(!read_craft_replacements(L, -1, replacements))
3579 throw LuaError(L, "Invalid replacements"
3580 " (output=\"" + output + "\")");
3583 CraftDefinition *def = new CraftDefinitionShaped(
3584 output, width, recipe, replacements);
3585 craftdef->registerCraft(def);
3588 CraftDefinitionShapeless
3590 else if(type == "shapeless"){
3591 std::string output = getstringfield_default(L, table, "output", "");
3593 throw LuaError(L, "Crafting definition (shapeless)"
3594 " is missing an output");
3596 std::vector<std::string> recipe;
3597 lua_getfield(L, table, "recipe");
3598 if(lua_isnil(L, -1))
3599 throw LuaError(L, "Crafting definition (shapeless)"
3600 " is missing a recipe"
3601 " (output=\"" + output + "\")");
3602 if(!read_craft_recipe_shapeless(L, -1, recipe))
3603 throw LuaError(L, "Invalid crafting recipe"
3604 " (output=\"" + output + "\")");
3606 CraftReplacements replacements;
3607 lua_getfield(L, table, "replacements");
3608 if(!lua_isnil(L, -1))
3610 if(!read_craft_replacements(L, -1, replacements))
3611 throw LuaError(L, "Invalid replacements"
3612 " (output=\"" + output + "\")");
3615 CraftDefinition *def = new CraftDefinitionShapeless(
3616 output, recipe, replacements);
3617 craftdef->registerCraft(def);
3620 CraftDefinitionToolRepair
3622 else if(type == "toolrepair"){
3623 float additional_wear = getfloatfield_default(L, table,
3624 "additional_wear", 0.0);
3626 CraftDefinition *def = new CraftDefinitionToolRepair(
3628 craftdef->registerCraft(def);
3631 CraftDefinitionCooking
3633 else if(type == "cooking"){
3634 std::string output = getstringfield_default(L, table, "output", "");
3636 throw LuaError(L, "Crafting definition (cooking)"
3637 " is missing an output");
3639 std::string recipe = getstringfield_default(L, table, "recipe", "");
3641 throw LuaError(L, "Crafting definition (cooking)"
3642 " is missing a recipe"
3643 " (output=\"" + output + "\")");
3645 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3647 CraftDefinition *def = new CraftDefinitionCooking(
3648 output, recipe, cooktime);
3649 craftdef->registerCraft(def);
3654 else if(type == "fuel"){
3655 std::string recipe = getstringfield_default(L, table, "recipe", "");
3657 throw LuaError(L, "Crafting definition (fuel)"
3658 " is missing a recipe");
3660 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3662 CraftDefinition *def = new CraftDefinitionFuel(
3664 craftdef->registerCraft(def);
3668 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3672 return 0; /* number of results */
3675 // setting_get(name)
3676 static int l_setting_get(lua_State *L)
3678 const char *name = luaL_checkstring(L, 1);
3680 std::string value = g_settings->get(name);
3681 lua_pushstring(L, value.c_str());
3682 } catch(SettingNotFoundException &e){
3688 // setting_getbool(name)
3689 static int l_setting_getbool(lua_State *L)
3691 const char *name = luaL_checkstring(L, 1);
3693 bool value = g_settings->getBool(name);
3694 lua_pushboolean(L, value);
3695 } catch(SettingNotFoundException &e){
3701 // chat_send_all(text)
3702 static int l_chat_send_all(lua_State *L)
3704 const char *text = luaL_checkstring(L, 1);
3705 // Get server from registry
3706 Server *server = get_server(L);
3708 server->notifyPlayers(narrow_to_wide(text));
3712 // chat_send_player(name, text)
3713 static int l_chat_send_player(lua_State *L)
3715 const char *name = luaL_checkstring(L, 1);
3716 const char *text = luaL_checkstring(L, 2);
3717 // Get server from registry
3718 Server *server = get_server(L);
3720 server->notifyPlayer(name, narrow_to_wide(text));
3724 // get_player_privs(name, text)
3725 static int l_get_player_privs(lua_State *L)
3727 const char *name = luaL_checkstring(L, 1);
3728 // Get server from registry
3729 Server *server = get_server(L);
3732 int table = lua_gettop(L);
3733 u64 privs_i = server->getPlayerEffectivePrivs(name);
3734 std::set<std::string> privs_s = privsToSet(privs_i);
3735 for(std::set<std::string>::const_iterator
3736 i = privs_s.begin(); i != privs_s.end(); i++){
3737 lua_pushboolean(L, true);
3738 lua_setfield(L, table, i->c_str());
3740 lua_pushvalue(L, table);
3744 // get_inventory(location)
3745 static int l_get_inventory(lua_State *L)
3747 InventoryLocation loc;
3749 std::string type = checkstringfield(L, 1, "type");
3750 if(type == "player"){
3751 std::string name = checkstringfield(L, 1, "name");
3752 loc.setPlayer(name);
3753 } else if(type == "node"){
3754 lua_getfield(L, 1, "pos");
3755 v3s16 pos = check_v3s16(L, -1);
3756 loc.setNodeMeta(pos);
3759 if(get_server(L)->getInventory(loc) != NULL)
3760 InvRef::create(L, loc);
3766 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3767 static int l_get_dig_params(lua_State *L)
3769 std::map<std::string, int> groups;
3770 read_groups(L, 1, groups);
3771 ToolCapabilities tp = read_tool_capabilities(L, 2);
3772 if(lua_isnoneornil(L, 3))
3773 push_dig_params(L, getDigParams(groups, &tp));
3775 push_dig_params(L, getDigParams(groups, &tp,
3776 luaL_checknumber(L, 3)));
3780 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3781 static int l_get_hit_params(lua_State *L)
3783 std::map<std::string, int> groups;
3784 read_groups(L, 1, groups);
3785 ToolCapabilities tp = read_tool_capabilities(L, 2);
3786 if(lua_isnoneornil(L, 3))
3787 push_hit_params(L, getHitParams(groups, &tp));
3789 push_hit_params(L, getHitParams(groups, &tp,
3790 luaL_checknumber(L, 3)));
3794 // get_current_modname()
3795 static int l_get_current_modname(lua_State *L)
3797 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3801 // get_modpath(modname)
3802 static int l_get_modpath(lua_State *L)
3804 const char *modname = luaL_checkstring(L, 1);
3806 const ModSpec *mod = get_server(L)->getModSpec(modname);
3811 lua_pushstring(L, mod->path.c_str());
3816 static int l_get_worldpath(lua_State *L)
3818 std::string worldpath = get_server(L)->getWorldPath();
3819 lua_pushstring(L, worldpath.c_str());
3823 // sound_play(spec, parameters)
3824 static int l_sound_play(lua_State *L)
3826 SimpleSoundSpec spec;
3827 read_soundspec(L, 1, spec);
3828 ServerSoundParams params;
3829 read_server_sound_params(L, 2, params);
3830 s32 handle = get_server(L)->playSound(spec, params);
3831 lua_pushinteger(L, handle);
3835 // sound_stop(handle)
3836 static int l_sound_stop(lua_State *L)
3838 int handle = luaL_checkinteger(L, 1);
3839 get_server(L)->stopSound(handle);
3843 static const struct luaL_Reg minetest_f [] = {
3846 {"register_item_raw", l_register_item_raw},
3847 {"register_alias_raw", l_register_alias_raw},
3848 {"register_craft", l_register_craft},
3849 {"setting_get", l_setting_get},
3850 {"setting_getbool", l_setting_getbool},
3851 {"chat_send_all", l_chat_send_all},
3852 {"chat_send_player", l_chat_send_player},
3853 {"get_player_privs", l_get_player_privs},
3854 {"get_inventory", l_get_inventory},
3855 {"get_dig_params", l_get_dig_params},
3856 {"get_hit_params", l_get_hit_params},
3857 {"get_current_modname", l_get_current_modname},
3858 {"get_modpath", l_get_modpath},
3859 {"get_worldpath", l_get_worldpath},
3860 {"sound_play", l_sound_play},
3861 {"sound_stop", l_sound_stop},
3866 Main export function
3869 void scriptapi_export(lua_State *L, Server *server)
3872 assert(lua_checkstack(L, 20));
3873 verbosestream<<"scriptapi_export()"<<std::endl;
3874 StackUnroller stack_unroller(L);
3876 // Store server as light userdata in registry
3877 lua_pushlightuserdata(L, server);
3878 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3880 // Register global functions in table minetest
3882 luaL_register(L, NULL, minetest_f);
3883 lua_setglobal(L, "minetest");
3885 // Get the main minetest table
3886 lua_getglobal(L, "minetest");
3888 // Add tables to minetest
3891 lua_setfield(L, -2, "object_refs");
3893 lua_setfield(L, -2, "luaentities");
3895 // Register wrappers
3896 LuaItemStack::Register(L);
3897 InvRef::Register(L);
3898 NodeMetaRef::Register(L);
3899 ObjectRef::Register(L);
3900 EnvRef::Register(L);
3901 LuaPseudoRandom::Register(L);
3904 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3905 const std::string &modname)
3907 ModNameStorer modnamestorer(L, modname);
3909 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3911 errorstream<<"Error loading mod \""<<modname
3912 <<"\": modname does not follow naming conventions: "
3913 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3917 bool success = false;
3920 success = script_load(L, scriptpath.c_str());
3923 errorstream<<"Error loading mod \""<<modname
3924 <<"\": "<<e.what()<<std::endl;
3930 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3933 assert(lua_checkstack(L, 20));
3934 verbosestream<<"scriptapi_add_environment"<<std::endl;
3935 StackUnroller stack_unroller(L);
3937 // Create EnvRef on stack
3938 EnvRef::create(L, env);
3939 int envref = lua_gettop(L);
3941 // minetest.env = envref
3942 lua_getglobal(L, "minetest");
3943 luaL_checktype(L, -1, LUA_TTABLE);
3944 lua_pushvalue(L, envref);
3945 lua_setfield(L, -2, "env");
3947 // Store environment as light userdata in registry
3948 lua_pushlightuserdata(L, env);
3949 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3952 Add ActiveBlockModifiers to environment
3955 // Get minetest.registered_abms
3956 lua_getglobal(L, "minetest");
3957 lua_getfield(L, -1, "registered_abms");
3958 luaL_checktype(L, -1, LUA_TTABLE);
3959 int registered_abms = lua_gettop(L);
3961 if(lua_istable(L, registered_abms)){
3962 int table = lua_gettop(L);
3964 while(lua_next(L, table) != 0){
3965 // key at index -2 and value at index -1
3966 int id = lua_tonumber(L, -2);
3967 int current_abm = lua_gettop(L);
3969 std::set<std::string> trigger_contents;
3970 lua_getfield(L, current_abm, "nodenames");
3971 if(lua_istable(L, -1)){
3972 int table = lua_gettop(L);
3974 while(lua_next(L, table) != 0){
3975 // key at index -2 and value at index -1
3976 luaL_checktype(L, -1, LUA_TSTRING);
3977 trigger_contents.insert(lua_tostring(L, -1));
3978 // removes value, keeps key for next iteration
3981 } else if(lua_isstring(L, -1)){
3982 trigger_contents.insert(lua_tostring(L, -1));
3986 std::set<std::string> required_neighbors;
3987 lua_getfield(L, current_abm, "neighbors");
3988 if(lua_istable(L, -1)){
3989 int table = lua_gettop(L);
3991 while(lua_next(L, table) != 0){
3992 // key at index -2 and value at index -1
3993 luaL_checktype(L, -1, LUA_TSTRING);
3994 required_neighbors.insert(lua_tostring(L, -1));
3995 // removes value, keeps key for next iteration
3998 } else if(lua_isstring(L, -1)){
3999 required_neighbors.insert(lua_tostring(L, -1));
4003 float trigger_interval = 10.0;
4004 getfloatfield(L, current_abm, "interval", trigger_interval);
4006 int trigger_chance = 50;
4007 getintfield(L, current_abm, "chance", trigger_chance);
4009 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4010 required_neighbors, trigger_interval, trigger_chance);
4012 env->addActiveBlockModifier(abm);
4014 // removes value, keeps key for next iteration
4022 // Dump stack top with the dump2 function
4023 static void dump2(lua_State *L, const char *name)
4025 // Dump object (debug)
4026 lua_getglobal(L, "dump2");
4027 luaL_checktype(L, -1, LUA_TFUNCTION);
4028 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4029 lua_pushstring(L, name);
4030 if(lua_pcall(L, 2, 0, 0))
4031 script_error(L, "error: %s", lua_tostring(L, -1));
4039 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4042 assert(lua_checkstack(L, 20));
4043 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4044 StackUnroller stack_unroller(L);
4046 // Create object on stack
4047 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4048 int object = lua_gettop(L);
4050 // Get minetest.object_refs table
4051 lua_getglobal(L, "minetest");
4052 lua_getfield(L, -1, "object_refs");
4053 luaL_checktype(L, -1, LUA_TTABLE);
4054 int objectstable = lua_gettop(L);
4056 // object_refs[id] = object
4057 lua_pushnumber(L, cobj->getId()); // Push id
4058 lua_pushvalue(L, object); // Copy object to top of stack
4059 lua_settable(L, objectstable);
4062 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4065 assert(lua_checkstack(L, 20));
4066 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4067 StackUnroller stack_unroller(L);
4069 // Get minetest.object_refs table
4070 lua_getglobal(L, "minetest");
4071 lua_getfield(L, -1, "object_refs");
4072 luaL_checktype(L, -1, LUA_TTABLE);
4073 int objectstable = lua_gettop(L);
4075 // Get object_refs[id]
4076 lua_pushnumber(L, cobj->getId()); // Push id
4077 lua_gettable(L, objectstable);
4078 // Set object reference to NULL
4079 ObjectRef::set_null(L);
4080 lua_pop(L, 1); // pop object
4082 // Set object_refs[id] = nil
4083 lua_pushnumber(L, cobj->getId()); // Push id
4085 lua_settable(L, objectstable);
4088 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4089 const std::string &message)
4092 assert(lua_checkstack(L, 20));
4093 StackUnroller stack_unroller(L);
4095 // Get minetest.registered_on_chat_messages
4096 lua_getglobal(L, "minetest");
4097 lua_getfield(L, -1, "registered_on_chat_messages");
4098 luaL_checktype(L, -1, LUA_TTABLE);
4099 int table = lua_gettop(L);
4102 while(lua_next(L, table) != 0){
4103 // key at index -2 and value at index -1
4104 luaL_checktype(L, -1, LUA_TFUNCTION);
4106 lua_pushstring(L, name.c_str());
4107 lua_pushstring(L, message.c_str());
4108 if(lua_pcall(L, 2, 1, 0))
4109 script_error(L, "error: %s", lua_tostring(L, -1));
4110 bool ate = lua_toboolean(L, -1);
4114 // value removed, keep key for next iteration
4123 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4126 assert(lua_checkstack(L, 20));
4127 StackUnroller stack_unroller(L);
4129 // Get minetest.registered_on_newplayers
4130 lua_getglobal(L, "minetest");
4131 lua_getfield(L, -1, "registered_on_newplayers");
4132 luaL_checktype(L, -1, LUA_TTABLE);
4133 int table = lua_gettop(L);
4136 while(lua_next(L, table) != 0){
4137 // key at index -2 and value at index -1
4138 luaL_checktype(L, -1, LUA_TFUNCTION);
4140 objectref_get_or_create(L, player);
4141 if(lua_pcall(L, 1, 0, 0))
4142 script_error(L, "error: %s", lua_tostring(L, -1));
4143 // value removed, keep key for next iteration
4147 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4150 assert(lua_checkstack(L, 20));
4151 StackUnroller stack_unroller(L);
4153 // Get minetest.registered_on_dieplayers
4154 lua_getglobal(L, "minetest");
4155 lua_getfield(L, -1, "registered_on_dieplayers");
4156 luaL_checktype(L, -1, LUA_TTABLE);
4157 int table = lua_gettop(L);
4160 while(lua_next(L, table) != 0){
4161 // key at index -2 and value at index -1
4162 luaL_checktype(L, -1, LUA_TFUNCTION);
4164 objectref_get_or_create(L, player);
4165 if(lua_pcall(L, 1, 0, 0))
4166 script_error(L, "error: %s", lua_tostring(L, -1));
4167 // value removed, keep key for next iteration
4172 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4175 assert(lua_checkstack(L, 20));
4176 StackUnroller stack_unroller(L);
4178 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
4180 bool positioning_handled_by_some = false;
4182 // Get minetest.registered_on_respawnplayers
4183 lua_getglobal(L, "minetest");
4184 lua_getfield(L, -1, "registered_on_respawnplayers");
4185 luaL_checktype(L, -1, LUA_TTABLE);
4186 int table = lua_gettop(L);
4189 while(lua_next(L, table) != 0){
4190 // key at index -2 and value at index -1
4191 luaL_checktype(L, -1, LUA_TFUNCTION);
4193 objectref_get_or_create(L, player);
4194 if(lua_pcall(L, 1, 1, 0))
4195 script_error(L, "error: %s", lua_tostring(L, -1));
4196 bool positioning_handled = lua_toboolean(L, -1);
4198 if(positioning_handled)
4199 positioning_handled_by_some = true;
4200 // value removed, keep key for next iteration
4202 return positioning_handled_by_some;
4205 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4207 lua_getglobal(L, "minetest");
4208 lua_getfield(L, -1, "creative_inventory");
4209 luaL_checktype(L, -1, LUA_TTABLE);
4210 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4211 PLAYER_INVENTORY_SIZE);
4215 item callbacks and node callbacks
4218 // Retrieves minetest.registered_items[name][callbackname]
4219 // If that is nil or on error, return false and stack is unchanged
4220 // If that is a function, returns true and pushes the
4221 // function onto the stack
4222 static bool get_item_callback(lua_State *L,
4223 const char *name, const char *callbackname)
4225 lua_getglobal(L, "minetest");
4226 lua_getfield(L, -1, "registered_items");
4228 luaL_checktype(L, -1, LUA_TTABLE);
4229 lua_getfield(L, -1, name);
4231 // Should be a table
4232 if(lua_type(L, -1) != LUA_TTABLE)
4234 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4238 lua_getfield(L, -1, callbackname);
4240 // Should be a function or nil
4241 if(lua_type(L, -1) == LUA_TFUNCTION)
4245 else if(lua_isnil(L, -1))
4252 errorstream<<"Item \""<<name<<"\" callback \""
4253 <<callbackname<<" is not a function"<<std::endl;
4259 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4260 ServerActiveObject *dropper, v3f pos)
4263 assert(lua_checkstack(L, 20));
4264 StackUnroller stack_unroller(L);
4266 // Push callback function on stack
4267 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4271 LuaItemStack::create(L, item);
4272 objectref_get_or_create(L, dropper);
4273 pushFloatPos(L, pos);
4274 if(lua_pcall(L, 3, 1, 0))
4275 script_error(L, "error: %s", lua_tostring(L, -1));
4276 if(!lua_isnil(L, -1))
4277 item = read_item(L, -1);
4281 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4282 ServerActiveObject *placer, const PointedThing &pointed)
4285 assert(lua_checkstack(L, 20));
4286 StackUnroller stack_unroller(L);
4288 // Push callback function on stack
4289 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4293 LuaItemStack::create(L, item);
4294 objectref_get_or_create(L, placer);
4295 push_pointed_thing(L, pointed);
4296 if(lua_pcall(L, 3, 1, 0))
4297 script_error(L, "error: %s", lua_tostring(L, -1));
4298 if(!lua_isnil(L, -1))
4299 item = read_item(L, -1);
4303 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4304 ServerActiveObject *user, const PointedThing &pointed)
4307 assert(lua_checkstack(L, 20));
4308 StackUnroller stack_unroller(L);
4310 // Push callback function on stack
4311 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4315 LuaItemStack::create(L, item);
4316 objectref_get_or_create(L, user);
4317 push_pointed_thing(L, pointed);
4318 if(lua_pcall(L, 3, 1, 0))
4319 script_error(L, "error: %s", lua_tostring(L, -1));
4320 if(!lua_isnil(L, -1))
4321 item = read_item(L, -1);
4325 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4326 ServerActiveObject *puncher)
4329 assert(lua_checkstack(L, 20));
4330 StackUnroller stack_unroller(L);
4332 INodeDefManager *ndef = get_server(L)->ndef();
4334 // Push callback function on stack
4335 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4340 pushnode(L, node, ndef);
4341 objectref_get_or_create(L, puncher);
4342 if(lua_pcall(L, 3, 0, 0))
4343 script_error(L, "error: %s", lua_tostring(L, -1));
4347 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4348 ServerActiveObject *digger)
4351 assert(lua_checkstack(L, 20));
4352 StackUnroller stack_unroller(L);
4354 INodeDefManager *ndef = get_server(L)->ndef();
4356 // Push callback function on stack
4357 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4362 pushnode(L, node, ndef);
4363 objectref_get_or_create(L, digger);
4364 if(lua_pcall(L, 3, 0, 0))
4365 script_error(L, "error: %s", lua_tostring(L, -1));
4373 void scriptapi_environment_step(lua_State *L, float dtime)
4376 assert(lua_checkstack(L, 20));
4377 //infostream<<"scriptapi_environment_step"<<std::endl;
4378 StackUnroller stack_unroller(L);
4380 // Get minetest.registered_globalsteps
4381 lua_getglobal(L, "minetest");
4382 lua_getfield(L, -1, "registered_globalsteps");
4383 luaL_checktype(L, -1, LUA_TTABLE);
4384 int table = lua_gettop(L);
4387 while(lua_next(L, table) != 0){
4388 // key at index -2 and value at index -1
4389 luaL_checktype(L, -1, LUA_TFUNCTION);
4391 lua_pushnumber(L, dtime);
4392 if(lua_pcall(L, 1, 0, 0))
4393 script_error(L, "error: %s", lua_tostring(L, -1));
4394 // value removed, keep key for next iteration
4398 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
4401 assert(lua_checkstack(L, 20));
4402 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4403 StackUnroller stack_unroller(L);
4405 // Get minetest.registered_on_generateds
4406 lua_getglobal(L, "minetest");
4407 lua_getfield(L, -1, "registered_on_generateds");
4408 luaL_checktype(L, -1, LUA_TTABLE);
4409 int table = lua_gettop(L);
4412 while(lua_next(L, table) != 0){
4413 // key at index -2 and value at index -1
4414 luaL_checktype(L, -1, LUA_TFUNCTION);
4416 push_v3s16(L, minp);
4417 push_v3s16(L, maxp);
4418 if(lua_pcall(L, 2, 0, 0))
4419 script_error(L, "error: %s", lua_tostring(L, -1));
4420 // value removed, keep key for next iteration
4428 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4431 assert(lua_checkstack(L, 20));
4432 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4433 <<name<<"\""<<std::endl;
4434 StackUnroller stack_unroller(L);
4436 // Get minetest.registered_entities[name]
4437 lua_getglobal(L, "minetest");
4438 lua_getfield(L, -1, "registered_entities");
4439 luaL_checktype(L, -1, LUA_TTABLE);
4440 lua_pushstring(L, name);
4441 lua_gettable(L, -2);
4442 // Should be a table, which we will use as a prototype
4443 //luaL_checktype(L, -1, LUA_TTABLE);
4444 if(lua_type(L, -1) != LUA_TTABLE){
4445 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4448 int prototype_table = lua_gettop(L);
4449 //dump2(L, "prototype_table");
4451 // Create entity object
4453 int object = lua_gettop(L);
4455 // Set object metatable
4456 lua_pushvalue(L, prototype_table);
4457 lua_setmetatable(L, -2);
4459 // Add object reference
4460 // This should be userdata with metatable ObjectRef
4461 objectref_get(L, id);
4462 luaL_checktype(L, -1, LUA_TUSERDATA);
4463 if(!luaL_checkudata(L, -1, "ObjectRef"))
4464 luaL_typerror(L, -1, "ObjectRef");
4465 lua_setfield(L, -2, "object");
4467 // minetest.luaentities[id] = object
4468 lua_getglobal(L, "minetest");
4469 lua_getfield(L, -1, "luaentities");
4470 luaL_checktype(L, -1, LUA_TTABLE);
4471 lua_pushnumber(L, id); // Push id
4472 lua_pushvalue(L, object); // Copy object to top of stack
4473 lua_settable(L, -3);
4478 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4479 const std::string &staticdata)
4482 assert(lua_checkstack(L, 20));
4483 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4484 StackUnroller stack_unroller(L);
4486 // Get minetest.luaentities[id]
4487 luaentity_get(L, id);
4488 int object = lua_gettop(L);
4490 // Get on_activate function
4491 lua_pushvalue(L, object);
4492 lua_getfield(L, -1, "on_activate");
4493 if(!lua_isnil(L, -1)){
4494 luaL_checktype(L, -1, LUA_TFUNCTION);
4495 lua_pushvalue(L, object); // self
4496 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4497 // Call with 2 arguments, 0 results
4498 if(lua_pcall(L, 2, 0, 0))
4499 script_error(L, "error running function on_activate: %s\n",
4500 lua_tostring(L, -1));
4504 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4507 assert(lua_checkstack(L, 20));
4508 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4510 // Get minetest.luaentities table
4511 lua_getglobal(L, "minetest");
4512 lua_getfield(L, -1, "luaentities");
4513 luaL_checktype(L, -1, LUA_TTABLE);
4514 int objectstable = lua_gettop(L);
4516 // Set luaentities[id] = nil
4517 lua_pushnumber(L, id); // Push id
4519 lua_settable(L, objectstable);
4521 lua_pop(L, 2); // pop luaentities, minetest
4524 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4527 assert(lua_checkstack(L, 20));
4528 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4529 StackUnroller stack_unroller(L);
4531 // Get minetest.luaentities[id]
4532 luaentity_get(L, id);
4533 int object = lua_gettop(L);
4535 // Get get_staticdata function
4536 lua_pushvalue(L, object);
4537 lua_getfield(L, -1, "get_staticdata");
4538 if(lua_isnil(L, -1))
4541 luaL_checktype(L, -1, LUA_TFUNCTION);
4542 lua_pushvalue(L, object); // self
4543 // Call with 1 arguments, 1 results
4544 if(lua_pcall(L, 1, 1, 0))
4545 script_error(L, "error running function get_staticdata: %s\n",
4546 lua_tostring(L, -1));
4549 const char *s = lua_tolstring(L, -1, &len);
4550 return std::string(s, len);
4553 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4554 LuaEntityProperties *prop)
4557 assert(lua_checkstack(L, 20));
4558 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4559 StackUnroller stack_unroller(L);
4561 // Get minetest.luaentities[id]
4562 luaentity_get(L, id);
4563 //int object = lua_gettop(L);
4567 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4569 getboolfield(L, -1, "physical", prop->physical);
4571 getfloatfield(L, -1, "weight", prop->weight);
4573 lua_getfield(L, -1, "collisionbox");
4574 if(lua_istable(L, -1))
4575 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4578 getstringfield(L, -1, "visual", prop->visual);
4580 lua_getfield(L, -1, "visual_size");
4581 if(lua_istable(L, -1))
4582 prop->visual_size = read_v2f(L, -1);
4585 lua_getfield(L, -1, "textures");
4586 if(lua_istable(L, -1)){
4587 prop->textures.clear();
4588 int table = lua_gettop(L);
4590 while(lua_next(L, table) != 0){
4591 // key at index -2 and value at index -1
4592 if(lua_isstring(L, -1))
4593 prop->textures.push_back(lua_tostring(L, -1));
4595 prop->textures.push_back("");
4596 // removes value, keeps key for next iteration
4602 lua_getfield(L, -1, "spritediv");
4603 if(lua_istable(L, -1))
4604 prop->spritediv = read_v2s16(L, -1);
4607 lua_getfield(L, -1, "initial_sprite_basepos");
4608 if(lua_istable(L, -1))
4609 prop->initial_sprite_basepos = read_v2s16(L, -1);
4613 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4616 assert(lua_checkstack(L, 20));
4617 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4618 StackUnroller stack_unroller(L);
4620 // Get minetest.luaentities[id]
4621 luaentity_get(L, id);
4622 int object = lua_gettop(L);
4623 // State: object is at top of stack
4624 // Get step function
4625 lua_getfield(L, -1, "on_step");
4626 if(lua_isnil(L, -1))
4628 luaL_checktype(L, -1, LUA_TFUNCTION);
4629 lua_pushvalue(L, object); // self
4630 lua_pushnumber(L, dtime); // dtime
4631 // Call with 2 arguments, 0 results
4632 if(lua_pcall(L, 2, 0, 0))
4633 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4636 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4637 // tool_capabilities, direction)
4638 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4639 ServerActiveObject *puncher, float time_from_last_punch,
4640 const ToolCapabilities *toolcap, v3f dir)
4643 assert(lua_checkstack(L, 20));
4644 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4645 StackUnroller stack_unroller(L);
4647 // Get minetest.luaentities[id]
4648 luaentity_get(L, id);
4649 int object = lua_gettop(L);
4650 // State: object is at top of stack
4652 lua_getfield(L, -1, "on_punch");
4653 if(lua_isnil(L, -1))
4655 luaL_checktype(L, -1, LUA_TFUNCTION);
4656 lua_pushvalue(L, object); // self
4657 objectref_get_or_create(L, puncher); // Clicker reference
4658 lua_pushnumber(L, time_from_last_punch);
4659 push_tool_capabilities(L, *toolcap);
4661 // Call with 5 arguments, 0 results
4662 if(lua_pcall(L, 5, 0, 0))
4663 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4666 // Calls entity:on_rightclick(ObjectRef clicker)
4667 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4668 ServerActiveObject *clicker)
4671 assert(lua_checkstack(L, 20));
4672 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4673 StackUnroller stack_unroller(L);
4675 // Get minetest.luaentities[id]
4676 luaentity_get(L, id);
4677 int object = lua_gettop(L);
4678 // State: object is at top of stack
4680 lua_getfield(L, -1, "on_rightclick");
4681 if(lua_isnil(L, -1))
4683 luaL_checktype(L, -1, LUA_TFUNCTION);
4684 lua_pushvalue(L, object); // self
4685 objectref_get_or_create(L, clicker); // Clicker reference
4686 // Call with 2 arguments, 0 results
4687 if(lua_pcall(L, 2, 0, 0))
4688 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));