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:set_node(pos, node)
2795 // pos = {x=num, y=num, z=num}
2796 static int l_set_node(lua_State *L)
2798 //infostream<<"EnvRef::l_set_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 static int l_add_node(lua_State *L)
2814 return l_set_node(L);
2817 // EnvRef:remove_node(pos)
2818 // pos = {x=num, y=num, z=num}
2819 static int l_remove_node(lua_State *L)
2821 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2822 EnvRef *o = checkobject(L, 1);
2823 ServerEnvironment *env = o->m_env;
2824 if(env == NULL) return 0;
2826 v3s16 pos = read_v3s16(L, 2);
2828 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2829 lua_pushboolean(L, succeeded);
2833 // EnvRef:get_node(pos)
2834 // pos = {x=num, y=num, z=num}
2835 static int l_get_node(lua_State *L)
2837 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2838 EnvRef *o = checkobject(L, 1);
2839 ServerEnvironment *env = o->m_env;
2840 if(env == NULL) return 0;
2842 v3s16 pos = read_v3s16(L, 2);
2844 MapNode n = env->getMap().getNodeNoEx(pos);
2846 pushnode(L, n, env->getGameDef()->ndef());
2850 // EnvRef:get_node_or_nil(pos)
2851 // pos = {x=num, y=num, z=num}
2852 static int l_get_node_or_nil(lua_State *L)
2854 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2855 EnvRef *o = checkobject(L, 1);
2856 ServerEnvironment *env = o->m_env;
2857 if(env == NULL) return 0;
2859 v3s16 pos = read_v3s16(L, 2);
2862 MapNode n = env->getMap().getNode(pos);
2864 pushnode(L, n, env->getGameDef()->ndef());
2866 } catch(InvalidPositionException &e)
2873 // EnvRef:get_node_light(pos, timeofday)
2874 // pos = {x=num, y=num, z=num}
2875 // timeofday: nil = current time, 0 = night, 0.5 = day
2876 static int l_get_node_light(lua_State *L)
2878 EnvRef *o = checkobject(L, 1);
2879 ServerEnvironment *env = o->m_env;
2880 if(env == NULL) return 0;
2882 v3s16 pos = read_v3s16(L, 2);
2883 u32 time_of_day = env->getTimeOfDay();
2884 if(lua_isnumber(L, 3))
2885 time_of_day = 24000.0 * lua_tonumber(L, 3);
2886 time_of_day %= 24000;
2887 u32 dnr = time_to_daynight_ratio(time_of_day);
2888 MapNode n = env->getMap().getNodeNoEx(pos);
2890 MapNode n = env->getMap().getNode(pos);
2891 INodeDefManager *ndef = env->getGameDef()->ndef();
2892 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2894 } catch(InvalidPositionException &e)
2901 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2902 // pos = {x=num, y=num, z=num}
2903 static int l_add_entity(lua_State *L)
2905 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2906 EnvRef *o = checkobject(L, 1);
2907 ServerEnvironment *env = o->m_env;
2908 if(env == NULL) return 0;
2910 v3f pos = checkFloatPos(L, 2);
2912 const char *name = luaL_checkstring(L, 3);
2914 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
2915 int objectid = env->addActiveObject(obj);
2916 // If failed to add, return nothing (reads as nil)
2920 objectref_get_or_create(L, obj);
2924 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
2925 // pos = {x=num, y=num, z=num}
2926 static int l_add_item(lua_State *L)
2928 //infostream<<"EnvRef::l_add_item()"<<std::endl;
2929 EnvRef *o = checkobject(L, 1);
2930 ServerEnvironment *env = o->m_env;
2931 if(env == NULL) return 0;
2933 v3f pos = checkFloatPos(L, 2);
2935 ItemStack item = read_item(L, 3);
2936 if(item.empty() || !item.isKnown(get_server(L)->idef()))
2939 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
2940 int objectid = env->addActiveObject(obj);
2941 // If failed to add, return nothing (reads as nil)
2945 objectref_get_or_create(L, obj);
2949 // EnvRef:add_rat(pos)
2950 // pos = {x=num, y=num, z=num}
2951 static int l_add_rat(lua_State *L)
2953 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
2954 <<" Doing nothing."<<std::endl;
2958 // EnvRef:add_firefly(pos)
2959 // pos = {x=num, y=num, z=num}
2960 static int l_add_firefly(lua_State *L)
2962 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
2963 <<" Doing nothing."<<std::endl;
2967 // EnvRef:get_meta(pos)
2968 static int l_get_meta(lua_State *L)
2970 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
2971 EnvRef *o = checkobject(L, 1);
2972 ServerEnvironment *env = o->m_env;
2973 if(env == NULL) return 0;
2975 v3s16 p = read_v3s16(L, 2);
2976 NodeMetaRef::create(L, p, env);
2980 // EnvRef:get_player_by_name(name)
2981 static int l_get_player_by_name(lua_State *L)
2983 EnvRef *o = checkobject(L, 1);
2984 ServerEnvironment *env = o->m_env;
2985 if(env == NULL) return 0;
2987 const char *name = luaL_checkstring(L, 2);
2988 ServerRemotePlayer *player =
2989 static_cast<ServerRemotePlayer*>(env->getPlayer(name));
2994 // Put player on stack
2995 objectref_get_or_create(L, player);
2999 // EnvRef:get_objects_inside_radius(pos, radius)
3000 static int l_get_objects_inside_radius(lua_State *L)
3002 // Get the table insert function
3003 lua_getglobal(L, "table");
3004 lua_getfield(L, -1, "insert");
3005 int table_insert = lua_gettop(L);
3007 EnvRef *o = checkobject(L, 1);
3008 ServerEnvironment *env = o->m_env;
3009 if(env == NULL) return 0;
3011 v3f pos = checkFloatPos(L, 2);
3012 float radius = luaL_checknumber(L, 3) * BS;
3013 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3015 int table = lua_gettop(L);
3016 for(std::set<u16>::const_iterator
3017 i = ids.begin(); i != ids.end(); i++){
3018 ServerActiveObject *obj = env->getActiveObject(*i);
3019 // Insert object reference into table
3020 lua_pushvalue(L, table_insert);
3021 lua_pushvalue(L, table);
3022 objectref_get_or_create(L, obj);
3023 if(lua_pcall(L, 2, 0, 0))
3024 script_error(L, "error: %s", lua_tostring(L, -1));
3029 // EnvRef:set_timeofday(val)
3031 static int l_set_timeofday(lua_State *L)
3033 EnvRef *o = checkobject(L, 1);
3034 ServerEnvironment *env = o->m_env;
3035 if(env == NULL) return 0;
3037 float timeofday_f = luaL_checknumber(L, 2);
3038 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3039 int timeofday_mh = (int)(timeofday_f * 24000.0);
3040 // This should be set directly in the environment but currently
3041 // such changes aren't immediately sent to the clients, so call
3042 // the server instead.
3043 //env->setTimeOfDay(timeofday_mh);
3044 get_server(L)->setTimeOfDay(timeofday_mh);
3048 // EnvRef:get_timeofday() -> 0...1
3049 static int l_get_timeofday(lua_State *L)
3051 EnvRef *o = checkobject(L, 1);
3052 ServerEnvironment *env = o->m_env;
3053 if(env == NULL) return 0;
3055 int timeofday_mh = env->getTimeOfDay();
3056 float timeofday_f = (float)timeofday_mh / 24000.0;
3057 lua_pushnumber(L, timeofday_f);
3061 static int gc_object(lua_State *L) {
3062 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3068 EnvRef(ServerEnvironment *env):
3071 //infostream<<"EnvRef created"<<std::endl;
3076 //infostream<<"EnvRef destructing"<<std::endl;
3079 // Creates an EnvRef and leaves it on top of stack
3080 // Not callable from Lua; all references are created on the C side.
3081 static void create(lua_State *L, ServerEnvironment *env)
3083 EnvRef *o = new EnvRef(env);
3084 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3085 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3086 luaL_getmetatable(L, className);
3087 lua_setmetatable(L, -2);
3090 static void set_null(lua_State *L)
3092 EnvRef *o = checkobject(L, -1);
3096 static void Register(lua_State *L)
3099 int methodtable = lua_gettop(L);
3100 luaL_newmetatable(L, className);
3101 int metatable = lua_gettop(L);
3103 lua_pushliteral(L, "__metatable");
3104 lua_pushvalue(L, methodtable);
3105 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3107 lua_pushliteral(L, "__index");
3108 lua_pushvalue(L, methodtable);
3109 lua_settable(L, metatable);
3111 lua_pushliteral(L, "__gc");
3112 lua_pushcfunction(L, gc_object);
3113 lua_settable(L, metatable);
3115 lua_pop(L, 1); // drop metatable
3117 luaL_openlib(L, 0, methods, 0); // fill methodtable
3118 lua_pop(L, 1); // drop methodtable
3120 // Cannot be created from Lua
3121 //lua_register(L, className, create_object);
3124 const char EnvRef::className[] = "EnvRef";
3125 const luaL_reg EnvRef::methods[] = {
3126 method(EnvRef, set_node),
3127 method(EnvRef, add_node),
3128 method(EnvRef, remove_node),
3129 method(EnvRef, get_node),
3130 method(EnvRef, get_node_or_nil),
3131 method(EnvRef, get_node_light),
3132 method(EnvRef, add_entity),
3133 method(EnvRef, add_item),
3134 method(EnvRef, add_rat),
3135 method(EnvRef, add_firefly),
3136 method(EnvRef, get_meta),
3137 method(EnvRef, get_player_by_name),
3138 method(EnvRef, get_objects_inside_radius),
3139 method(EnvRef, set_timeofday),
3140 method(EnvRef, get_timeofday),
3148 class LuaPseudoRandom
3151 PseudoRandom m_pseudo;
3153 static const char className[];
3154 static const luaL_reg methods[];
3156 // Exported functions
3158 // garbage collector
3159 static int gc_object(lua_State *L)
3161 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3166 // next(self, min=0, max=32767) -> get next value
3167 static int l_next(lua_State *L)
3169 LuaPseudoRandom *o = checkobject(L, 1);
3172 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3173 if(!lua_isnil(L, 2))
3174 min = luaL_checkinteger(L, 2);
3175 if(!lua_isnil(L, 3))
3176 max = luaL_checkinteger(L, 3);
3177 if(max - min != 32767 && max - min > 32767/5)
3178 throw LuaError(L, "PseudoRandom.next() max-min is not 32767 and is > 32768/5. This is disallowed due to the bad random distribution the implementation would otherwise make.");
3179 PseudoRandom &pseudo = o->m_pseudo;
3180 int val = pseudo.next();
3181 val = (val % (max-min+1)) + min;
3182 lua_pushinteger(L, val);
3187 LuaPseudoRandom(int seed):
3196 const PseudoRandom& getItem() const
3200 PseudoRandom& getItem()
3205 // LuaPseudoRandom(seed)
3206 // Creates an LuaPseudoRandom and leaves it on top of stack
3207 static int create_object(lua_State *L)
3209 int seed = luaL_checknumber(L, 1);
3210 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3211 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3212 luaL_getmetatable(L, className);
3213 lua_setmetatable(L, -2);
3217 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3219 luaL_checktype(L, narg, LUA_TUSERDATA);
3220 void *ud = luaL_checkudata(L, narg, className);
3221 if(!ud) luaL_typerror(L, narg, className);
3222 return *(LuaPseudoRandom**)ud; // unbox pointer
3225 static void Register(lua_State *L)
3228 int methodtable = lua_gettop(L);
3229 luaL_newmetatable(L, className);
3230 int metatable = lua_gettop(L);
3232 lua_pushliteral(L, "__metatable");
3233 lua_pushvalue(L, methodtable);
3234 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3236 lua_pushliteral(L, "__index");
3237 lua_pushvalue(L, methodtable);
3238 lua_settable(L, metatable);
3240 lua_pushliteral(L, "__gc");
3241 lua_pushcfunction(L, gc_object);
3242 lua_settable(L, metatable);
3244 lua_pop(L, 1); // drop metatable
3246 luaL_openlib(L, 0, methods, 0); // fill methodtable
3247 lua_pop(L, 1); // drop methodtable
3249 // Can be created from Lua (LuaPseudoRandom(seed))
3250 lua_register(L, className, create_object);
3253 const char LuaPseudoRandom::className[] = "PseudoRandom";
3254 const luaL_reg LuaPseudoRandom::methods[] = {
3255 method(LuaPseudoRandom, next),
3263 class LuaABM : public ActiveBlockModifier
3269 std::set<std::string> m_trigger_contents;
3270 std::set<std::string> m_required_neighbors;
3271 float m_trigger_interval;
3272 u32 m_trigger_chance;
3274 LuaABM(lua_State *L, int id,
3275 const std::set<std::string> &trigger_contents,
3276 const std::set<std::string> &required_neighbors,
3277 float trigger_interval, u32 trigger_chance):
3280 m_trigger_contents(trigger_contents),
3281 m_required_neighbors(required_neighbors),
3282 m_trigger_interval(trigger_interval),
3283 m_trigger_chance(trigger_chance)
3286 virtual std::set<std::string> getTriggerContents()
3288 return m_trigger_contents;
3290 virtual std::set<std::string> getRequiredNeighbors()
3292 return m_required_neighbors;
3294 virtual float getTriggerInterval()
3296 return m_trigger_interval;
3298 virtual u32 getTriggerChance()
3300 return m_trigger_chance;
3302 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3303 u32 active_object_count, u32 active_object_count_wider)
3305 lua_State *L = m_lua;
3308 assert(lua_checkstack(L, 20));
3309 StackUnroller stack_unroller(L);
3311 // Get minetest.registered_abms
3312 lua_getglobal(L, "minetest");
3313 lua_getfield(L, -1, "registered_abms");
3314 luaL_checktype(L, -1, LUA_TTABLE);
3315 int registered_abms = lua_gettop(L);
3317 // Get minetest.registered_abms[m_id]
3318 lua_pushnumber(L, m_id);
3319 lua_gettable(L, registered_abms);
3320 if(lua_isnil(L, -1))
3324 luaL_checktype(L, -1, LUA_TTABLE);
3325 lua_getfield(L, -1, "action");
3326 luaL_checktype(L, -1, LUA_TFUNCTION);
3328 pushnode(L, n, env->getGameDef()->ndef());
3329 lua_pushnumber(L, active_object_count);
3330 lua_pushnumber(L, active_object_count_wider);
3331 if(lua_pcall(L, 4, 0, 0))
3332 script_error(L, "error: %s", lua_tostring(L, -1));
3340 static void read_server_sound_params(lua_State *L, int index,
3341 ServerSoundParams ¶ms)
3344 index = lua_gettop(L) + 1 + index;
3346 params = ServerSoundParams();
3347 if(lua_istable(L, index)){
3348 getfloatfield(L, index, "gain", params.gain);
3349 getstringfield(L, index, "to_player", params.to_player);
3350 lua_getfield(L, index, "pos");
3351 if(!lua_isnil(L, -1)){
3352 v3f p = read_v3f(L, -1)*BS;
3354 params.type = ServerSoundParams::SSP_POSITIONAL;
3357 lua_getfield(L, index, "object");
3358 if(!lua_isnil(L, -1)){
3359 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3360 ServerActiveObject *sao = ObjectRef::getobject(ref);
3362 params.object = sao->getId();
3363 params.type = ServerSoundParams::SSP_OBJECT;
3367 params.max_hear_distance = BS*getfloatfield_default(L, index,
3368 "max_hear_distance", params.max_hear_distance/BS);
3369 getboolfield(L, index, "loop", params.loop);
3378 // Writes a line to dstream
3379 static int l_debug(lua_State *L)
3381 std::string text = lua_tostring(L, 1);
3382 dstream << text << std::endl;
3386 // log([level,] text)
3387 // Writes a line to the logger.
3388 // The one-argument version logs to infostream.
3389 // The two-argument version accept a log level: error, action, info, or verbose.
3390 static int l_log(lua_State *L)
3393 LogMessageLevel level = LMT_INFO;
3394 if(lua_isnone(L, 2))
3396 text = lua_tostring(L, 1);
3400 std::string levelname = lua_tostring(L, 1);
3401 text = lua_tostring(L, 2);
3402 if(levelname == "error")
3404 else if(levelname == "action")
3406 else if(levelname == "verbose")
3407 level = LMT_VERBOSE;
3409 log_printline(level, text);
3413 // register_item_raw({lots of stuff})
3414 static int l_register_item_raw(lua_State *L)
3416 luaL_checktype(L, 1, LUA_TTABLE);
3419 // Get the writable item and node definition managers from the server
3420 IWritableItemDefManager *idef =
3421 get_server(L)->getWritableItemDefManager();
3422 IWritableNodeDefManager *ndef =
3423 get_server(L)->getWritableNodeDefManager();
3425 // Check if name is defined
3426 lua_getfield(L, table, "name");
3427 if(lua_isstring(L, -1)){
3428 std::string name = lua_tostring(L, -1);
3429 verbosestream<<"register_item_raw: "<<name<<std::endl;
3431 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3434 // Check if on_use is defined
3436 // Read the item definition and register it
3437 ItemDefinition def = read_item_definition(L, table);
3438 idef->registerItem(def);
3440 // Read the node definition (content features) and register it
3441 if(def.type == ITEM_NODE)
3443 ContentFeatures f = read_content_features(L, table);
3444 ndef->set(f.name, f);
3447 return 0; /* number of results */
3450 // register_alias_raw(name, convert_to_name)
3451 static int l_register_alias_raw(lua_State *L)
3453 std::string name = luaL_checkstring(L, 1);
3454 std::string convert_to = luaL_checkstring(L, 2);
3456 // Get the writable item definition manager from the server
3457 IWritableItemDefManager *idef =
3458 get_server(L)->getWritableItemDefManager();
3460 idef->registerAlias(name, convert_to);
3462 return 0; /* number of results */
3465 // helper for register_craft
3466 static bool read_craft_recipe_shaped(lua_State *L, int index,
3467 int &width, std::vector<std::string> &recipe)
3470 index = lua_gettop(L) + 1 + index;
3472 if(!lua_istable(L, index))
3477 while(lua_next(L, index) != 0){
3479 // key at index -2 and value at index -1
3480 if(!lua_istable(L, -1))
3482 int table2 = lua_gettop(L);
3484 while(lua_next(L, table2) != 0){
3485 // key at index -2 and value at index -1
3486 if(!lua_isstring(L, -1))
3488 recipe.push_back(lua_tostring(L, -1));
3489 // removes value, keeps key for next iteration
3496 if(colcount != width)
3499 // removes value, keeps key for next iteration
3506 // helper for register_craft
3507 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3508 std::vector<std::string> &recipe)
3511 index = lua_gettop(L) + 1 + index;
3513 if(!lua_istable(L, index))
3517 while(lua_next(L, index) != 0){
3518 // key at index -2 and value at index -1
3519 if(!lua_isstring(L, -1))
3521 recipe.push_back(lua_tostring(L, -1));
3522 // removes value, keeps key for next iteration
3528 // helper for register_craft
3529 static bool read_craft_replacements(lua_State *L, int index,
3530 CraftReplacements &replacements)
3533 index = lua_gettop(L) + 1 + index;
3535 if(!lua_istable(L, index))
3539 while(lua_next(L, index) != 0){
3540 // key at index -2 and value at index -1
3541 if(!lua_istable(L, -1))
3543 lua_rawgeti(L, -1, 1);
3544 if(!lua_isstring(L, -1))
3546 std::string replace_from = lua_tostring(L, -1);
3548 lua_rawgeti(L, -1, 2);
3549 if(!lua_isstring(L, -1))
3551 std::string replace_to = lua_tostring(L, -1);
3553 replacements.pairs.push_back(
3554 std::make_pair(replace_from, replace_to));
3555 // removes value, keeps key for next iteration
3560 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3561 static int l_register_craft(lua_State *L)
3563 //infostream<<"register_craft"<<std::endl;
3564 luaL_checktype(L, 1, LUA_TTABLE);
3567 // Get the writable craft definition manager from the server
3568 IWritableCraftDefManager *craftdef =
3569 get_server(L)->getWritableCraftDefManager();
3571 std::string type = getstringfield_default(L, table, "type", "shaped");
3574 CraftDefinitionShaped
3576 if(type == "shaped"){
3577 std::string output = getstringfield_default(L, table, "output", "");
3579 throw LuaError(L, "Crafting definition is missing an output");
3582 std::vector<std::string> recipe;
3583 lua_getfield(L, table, "recipe");
3584 if(lua_isnil(L, -1))
3585 throw LuaError(L, "Crafting definition is missing a recipe"
3586 " (output=\"" + output + "\")");
3587 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3588 throw LuaError(L, "Invalid crafting recipe"
3589 " (output=\"" + output + "\")");
3591 CraftReplacements replacements;
3592 lua_getfield(L, table, "replacements");
3593 if(!lua_isnil(L, -1))
3595 if(!read_craft_replacements(L, -1, replacements))
3596 throw LuaError(L, "Invalid replacements"
3597 " (output=\"" + output + "\")");
3600 CraftDefinition *def = new CraftDefinitionShaped(
3601 output, width, recipe, replacements);
3602 craftdef->registerCraft(def);
3605 CraftDefinitionShapeless
3607 else if(type == "shapeless"){
3608 std::string output = getstringfield_default(L, table, "output", "");
3610 throw LuaError(L, "Crafting definition (shapeless)"
3611 " is missing an output");
3613 std::vector<std::string> recipe;
3614 lua_getfield(L, table, "recipe");
3615 if(lua_isnil(L, -1))
3616 throw LuaError(L, "Crafting definition (shapeless)"
3617 " is missing a recipe"
3618 " (output=\"" + output + "\")");
3619 if(!read_craft_recipe_shapeless(L, -1, recipe))
3620 throw LuaError(L, "Invalid crafting recipe"
3621 " (output=\"" + output + "\")");
3623 CraftReplacements replacements;
3624 lua_getfield(L, table, "replacements");
3625 if(!lua_isnil(L, -1))
3627 if(!read_craft_replacements(L, -1, replacements))
3628 throw LuaError(L, "Invalid replacements"
3629 " (output=\"" + output + "\")");
3632 CraftDefinition *def = new CraftDefinitionShapeless(
3633 output, recipe, replacements);
3634 craftdef->registerCraft(def);
3637 CraftDefinitionToolRepair
3639 else if(type == "toolrepair"){
3640 float additional_wear = getfloatfield_default(L, table,
3641 "additional_wear", 0.0);
3643 CraftDefinition *def = new CraftDefinitionToolRepair(
3645 craftdef->registerCraft(def);
3648 CraftDefinitionCooking
3650 else if(type == "cooking"){
3651 std::string output = getstringfield_default(L, table, "output", "");
3653 throw LuaError(L, "Crafting definition (cooking)"
3654 " is missing an output");
3656 std::string recipe = getstringfield_default(L, table, "recipe", "");
3658 throw LuaError(L, "Crafting definition (cooking)"
3659 " is missing a recipe"
3660 " (output=\"" + output + "\")");
3662 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3664 CraftDefinition *def = new CraftDefinitionCooking(
3665 output, recipe, cooktime);
3666 craftdef->registerCraft(def);
3671 else if(type == "fuel"){
3672 std::string recipe = getstringfield_default(L, table, "recipe", "");
3674 throw LuaError(L, "Crafting definition (fuel)"
3675 " is missing a recipe");
3677 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3679 CraftDefinition *def = new CraftDefinitionFuel(
3681 craftdef->registerCraft(def);
3685 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3689 return 0; /* number of results */
3692 // setting_get(name)
3693 static int l_setting_get(lua_State *L)
3695 const char *name = luaL_checkstring(L, 1);
3697 std::string value = g_settings->get(name);
3698 lua_pushstring(L, value.c_str());
3699 } catch(SettingNotFoundException &e){
3705 // setting_getbool(name)
3706 static int l_setting_getbool(lua_State *L)
3708 const char *name = luaL_checkstring(L, 1);
3710 bool value = g_settings->getBool(name);
3711 lua_pushboolean(L, value);
3712 } catch(SettingNotFoundException &e){
3718 // chat_send_all(text)
3719 static int l_chat_send_all(lua_State *L)
3721 const char *text = luaL_checkstring(L, 1);
3722 // Get server from registry
3723 Server *server = get_server(L);
3725 server->notifyPlayers(narrow_to_wide(text));
3729 // chat_send_player(name, text)
3730 static int l_chat_send_player(lua_State *L)
3732 const char *name = luaL_checkstring(L, 1);
3733 const char *text = luaL_checkstring(L, 2);
3734 // Get server from registry
3735 Server *server = get_server(L);
3737 server->notifyPlayer(name, narrow_to_wide(text));
3741 // get_player_privs(name, text)
3742 static int l_get_player_privs(lua_State *L)
3744 const char *name = luaL_checkstring(L, 1);
3745 // Get server from registry
3746 Server *server = get_server(L);
3749 int table = lua_gettop(L);
3750 u64 privs_i = server->getPlayerEffectivePrivs(name);
3751 std::set<std::string> privs_s = privsToSet(privs_i);
3752 for(std::set<std::string>::const_iterator
3753 i = privs_s.begin(); i != privs_s.end(); i++){
3754 lua_pushboolean(L, true);
3755 lua_setfield(L, table, i->c_str());
3757 lua_pushvalue(L, table);
3761 // get_inventory(location)
3762 static int l_get_inventory(lua_State *L)
3764 InventoryLocation loc;
3766 std::string type = checkstringfield(L, 1, "type");
3767 if(type == "player"){
3768 std::string name = checkstringfield(L, 1, "name");
3769 loc.setPlayer(name);
3770 } else if(type == "node"){
3771 lua_getfield(L, 1, "pos");
3772 v3s16 pos = check_v3s16(L, -1);
3773 loc.setNodeMeta(pos);
3776 if(get_server(L)->getInventory(loc) != NULL)
3777 InvRef::create(L, loc);
3783 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3784 static int l_get_dig_params(lua_State *L)
3786 std::map<std::string, int> groups;
3787 read_groups(L, 1, groups);
3788 ToolCapabilities tp = read_tool_capabilities(L, 2);
3789 if(lua_isnoneornil(L, 3))
3790 push_dig_params(L, getDigParams(groups, &tp));
3792 push_dig_params(L, getDigParams(groups, &tp,
3793 luaL_checknumber(L, 3)));
3797 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3798 static int l_get_hit_params(lua_State *L)
3800 std::map<std::string, int> groups;
3801 read_groups(L, 1, groups);
3802 ToolCapabilities tp = read_tool_capabilities(L, 2);
3803 if(lua_isnoneornil(L, 3))
3804 push_hit_params(L, getHitParams(groups, &tp));
3806 push_hit_params(L, getHitParams(groups, &tp,
3807 luaL_checknumber(L, 3)));
3811 // get_current_modname()
3812 static int l_get_current_modname(lua_State *L)
3814 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3818 // get_modpath(modname)
3819 static int l_get_modpath(lua_State *L)
3821 const char *modname = luaL_checkstring(L, 1);
3823 const ModSpec *mod = get_server(L)->getModSpec(modname);
3828 lua_pushstring(L, mod->path.c_str());
3833 static int l_get_worldpath(lua_State *L)
3835 std::string worldpath = get_server(L)->getWorldPath();
3836 lua_pushstring(L, worldpath.c_str());
3840 // sound_play(spec, parameters)
3841 static int l_sound_play(lua_State *L)
3843 SimpleSoundSpec spec;
3844 read_soundspec(L, 1, spec);
3845 ServerSoundParams params;
3846 read_server_sound_params(L, 2, params);
3847 s32 handle = get_server(L)->playSound(spec, params);
3848 lua_pushinteger(L, handle);
3852 // sound_stop(handle)
3853 static int l_sound_stop(lua_State *L)
3855 int handle = luaL_checkinteger(L, 1);
3856 get_server(L)->stopSound(handle);
3860 // is_singleplayer()
3861 static int l_is_singleplayer(lua_State *L)
3863 lua_pushboolean(L, get_server(L)->isSingleplayer());
3867 static const struct luaL_Reg minetest_f [] = {
3870 {"register_item_raw", l_register_item_raw},
3871 {"register_alias_raw", l_register_alias_raw},
3872 {"register_craft", l_register_craft},
3873 {"setting_get", l_setting_get},
3874 {"setting_getbool", l_setting_getbool},
3875 {"chat_send_all", l_chat_send_all},
3876 {"chat_send_player", l_chat_send_player},
3877 {"get_player_privs", l_get_player_privs},
3878 {"get_inventory", l_get_inventory},
3879 {"get_dig_params", l_get_dig_params},
3880 {"get_hit_params", l_get_hit_params},
3881 {"get_current_modname", l_get_current_modname},
3882 {"get_modpath", l_get_modpath},
3883 {"get_worldpath", l_get_worldpath},
3884 {"sound_play", l_sound_play},
3885 {"sound_stop", l_sound_stop},
3886 {"is_singleplayer", l_is_singleplayer},
3891 Main export function
3894 void scriptapi_export(lua_State *L, Server *server)
3897 assert(lua_checkstack(L, 20));
3898 verbosestream<<"scriptapi_export()"<<std::endl;
3899 StackUnroller stack_unroller(L);
3901 // Store server as light userdata in registry
3902 lua_pushlightuserdata(L, server);
3903 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3905 // Register global functions in table minetest
3907 luaL_register(L, NULL, minetest_f);
3908 lua_setglobal(L, "minetest");
3910 // Get the main minetest table
3911 lua_getglobal(L, "minetest");
3913 // Add tables to minetest
3916 lua_setfield(L, -2, "object_refs");
3918 lua_setfield(L, -2, "luaentities");
3920 // Register wrappers
3921 LuaItemStack::Register(L);
3922 InvRef::Register(L);
3923 NodeMetaRef::Register(L);
3924 ObjectRef::Register(L);
3925 EnvRef::Register(L);
3926 LuaPseudoRandom::Register(L);
3929 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
3930 const std::string &modname)
3932 ModNameStorer modnamestorer(L, modname);
3934 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
3936 errorstream<<"Error loading mod \""<<modname
3937 <<"\": modname does not follow naming conventions: "
3938 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
3942 bool success = false;
3945 success = script_load(L, scriptpath.c_str());
3948 errorstream<<"Error loading mod \""<<modname
3949 <<"\": "<<e.what()<<std::endl;
3955 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
3958 assert(lua_checkstack(L, 20));
3959 verbosestream<<"scriptapi_add_environment"<<std::endl;
3960 StackUnroller stack_unroller(L);
3962 // Create EnvRef on stack
3963 EnvRef::create(L, env);
3964 int envref = lua_gettop(L);
3966 // minetest.env = envref
3967 lua_getglobal(L, "minetest");
3968 luaL_checktype(L, -1, LUA_TTABLE);
3969 lua_pushvalue(L, envref);
3970 lua_setfield(L, -2, "env");
3972 // Store environment as light userdata in registry
3973 lua_pushlightuserdata(L, env);
3974 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
3977 Add ActiveBlockModifiers to environment
3980 // Get minetest.registered_abms
3981 lua_getglobal(L, "minetest");
3982 lua_getfield(L, -1, "registered_abms");
3983 luaL_checktype(L, -1, LUA_TTABLE);
3984 int registered_abms = lua_gettop(L);
3986 if(lua_istable(L, registered_abms)){
3987 int table = lua_gettop(L);
3989 while(lua_next(L, table) != 0){
3990 // key at index -2 and value at index -1
3991 int id = lua_tonumber(L, -2);
3992 int current_abm = lua_gettop(L);
3994 std::set<std::string> trigger_contents;
3995 lua_getfield(L, current_abm, "nodenames");
3996 if(lua_istable(L, -1)){
3997 int table = lua_gettop(L);
3999 while(lua_next(L, table) != 0){
4000 // key at index -2 and value at index -1
4001 luaL_checktype(L, -1, LUA_TSTRING);
4002 trigger_contents.insert(lua_tostring(L, -1));
4003 // removes value, keeps key for next iteration
4006 } else if(lua_isstring(L, -1)){
4007 trigger_contents.insert(lua_tostring(L, -1));
4011 std::set<std::string> required_neighbors;
4012 lua_getfield(L, current_abm, "neighbors");
4013 if(lua_istable(L, -1)){
4014 int table = lua_gettop(L);
4016 while(lua_next(L, table) != 0){
4017 // key at index -2 and value at index -1
4018 luaL_checktype(L, -1, LUA_TSTRING);
4019 required_neighbors.insert(lua_tostring(L, -1));
4020 // removes value, keeps key for next iteration
4023 } else if(lua_isstring(L, -1)){
4024 required_neighbors.insert(lua_tostring(L, -1));
4028 float trigger_interval = 10.0;
4029 getfloatfield(L, current_abm, "interval", trigger_interval);
4031 int trigger_chance = 50;
4032 getintfield(L, current_abm, "chance", trigger_chance);
4034 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4035 required_neighbors, trigger_interval, trigger_chance);
4037 env->addActiveBlockModifier(abm);
4039 // removes value, keeps key for next iteration
4047 // Dump stack top with the dump2 function
4048 static void dump2(lua_State *L, const char *name)
4050 // Dump object (debug)
4051 lua_getglobal(L, "dump2");
4052 luaL_checktype(L, -1, LUA_TFUNCTION);
4053 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4054 lua_pushstring(L, name);
4055 if(lua_pcall(L, 2, 0, 0))
4056 script_error(L, "error: %s", lua_tostring(L, -1));
4064 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4067 assert(lua_checkstack(L, 20));
4068 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4069 StackUnroller stack_unroller(L);
4071 // Create object on stack
4072 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4073 int object = lua_gettop(L);
4075 // Get minetest.object_refs table
4076 lua_getglobal(L, "minetest");
4077 lua_getfield(L, -1, "object_refs");
4078 luaL_checktype(L, -1, LUA_TTABLE);
4079 int objectstable = lua_gettop(L);
4081 // object_refs[id] = object
4082 lua_pushnumber(L, cobj->getId()); // Push id
4083 lua_pushvalue(L, object); // Copy object to top of stack
4084 lua_settable(L, objectstable);
4087 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4090 assert(lua_checkstack(L, 20));
4091 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4092 StackUnroller stack_unroller(L);
4094 // Get minetest.object_refs table
4095 lua_getglobal(L, "minetest");
4096 lua_getfield(L, -1, "object_refs");
4097 luaL_checktype(L, -1, LUA_TTABLE);
4098 int objectstable = lua_gettop(L);
4100 // Get object_refs[id]
4101 lua_pushnumber(L, cobj->getId()); // Push id
4102 lua_gettable(L, objectstable);
4103 // Set object reference to NULL
4104 ObjectRef::set_null(L);
4105 lua_pop(L, 1); // pop object
4107 // Set object_refs[id] = nil
4108 lua_pushnumber(L, cobj->getId()); // Push id
4110 lua_settable(L, objectstable);
4113 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4114 const std::string &message)
4117 assert(lua_checkstack(L, 20));
4118 StackUnroller stack_unroller(L);
4120 // Get minetest.registered_on_chat_messages
4121 lua_getglobal(L, "minetest");
4122 lua_getfield(L, -1, "registered_on_chat_messages");
4123 luaL_checktype(L, -1, LUA_TTABLE);
4124 int table = lua_gettop(L);
4127 while(lua_next(L, table) != 0){
4128 // key at index -2 and value at index -1
4129 luaL_checktype(L, -1, LUA_TFUNCTION);
4131 lua_pushstring(L, name.c_str());
4132 lua_pushstring(L, message.c_str());
4133 if(lua_pcall(L, 2, 1, 0))
4134 script_error(L, "error: %s", lua_tostring(L, -1));
4135 bool ate = lua_toboolean(L, -1);
4139 // value removed, keep key for next iteration
4148 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4151 assert(lua_checkstack(L, 20));
4152 StackUnroller stack_unroller(L);
4154 // Get minetest.registered_on_newplayers
4155 lua_getglobal(L, "minetest");
4156 lua_getfield(L, -1, "registered_on_newplayers");
4157 luaL_checktype(L, -1, LUA_TTABLE);
4158 int table = lua_gettop(L);
4161 while(lua_next(L, table) != 0){
4162 // key at index -2 and value at index -1
4163 luaL_checktype(L, -1, LUA_TFUNCTION);
4165 objectref_get_or_create(L, player);
4166 if(lua_pcall(L, 1, 0, 0))
4167 script_error(L, "error: %s", lua_tostring(L, -1));
4168 // value removed, keep key for next iteration
4172 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4175 assert(lua_checkstack(L, 20));
4176 StackUnroller stack_unroller(L);
4178 // Get minetest.registered_on_dieplayers
4179 lua_getglobal(L, "minetest");
4180 lua_getfield(L, -1, "registered_on_dieplayers");
4181 luaL_checktype(L, -1, LUA_TTABLE);
4182 int table = lua_gettop(L);
4185 while(lua_next(L, table) != 0){
4186 // key at index -2 and value at index -1
4187 luaL_checktype(L, -1, LUA_TFUNCTION);
4189 objectref_get_or_create(L, player);
4190 if(lua_pcall(L, 1, 0, 0))
4191 script_error(L, "error: %s", lua_tostring(L, -1));
4192 // value removed, keep key for next iteration
4197 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4200 assert(lua_checkstack(L, 20));
4201 StackUnroller stack_unroller(L);
4203 dstream<<"player: "<<player<<" id: "<<player->getId()<<std::endl;
4205 bool positioning_handled_by_some = false;
4207 // Get minetest.registered_on_respawnplayers
4208 lua_getglobal(L, "minetest");
4209 lua_getfield(L, -1, "registered_on_respawnplayers");
4210 luaL_checktype(L, -1, LUA_TTABLE);
4211 int table = lua_gettop(L);
4214 while(lua_next(L, table) != 0){
4215 // key at index -2 and value at index -1
4216 luaL_checktype(L, -1, LUA_TFUNCTION);
4218 objectref_get_or_create(L, player);
4219 if(lua_pcall(L, 1, 1, 0))
4220 script_error(L, "error: %s", lua_tostring(L, -1));
4221 bool positioning_handled = lua_toboolean(L, -1);
4223 if(positioning_handled)
4224 positioning_handled_by_some = true;
4225 // value removed, keep key for next iteration
4227 return positioning_handled_by_some;
4230 void scriptapi_get_creative_inventory(lua_State *L, ServerRemotePlayer *player)
4232 lua_getglobal(L, "minetest");
4233 lua_getfield(L, -1, "creative_inventory");
4234 luaL_checktype(L, -1, LUA_TTABLE);
4235 inventory_set_list_from_lua(&player->inventory, "main", L, -1,
4236 PLAYER_INVENTORY_SIZE);
4240 item callbacks and node callbacks
4243 // Retrieves minetest.registered_items[name][callbackname]
4244 // If that is nil or on error, return false and stack is unchanged
4245 // If that is a function, returns true and pushes the
4246 // function onto the stack
4247 static bool get_item_callback(lua_State *L,
4248 const char *name, const char *callbackname)
4250 lua_getglobal(L, "minetest");
4251 lua_getfield(L, -1, "registered_items");
4253 luaL_checktype(L, -1, LUA_TTABLE);
4254 lua_getfield(L, -1, name);
4256 // Should be a table
4257 if(lua_type(L, -1) != LUA_TTABLE)
4259 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4263 lua_getfield(L, -1, callbackname);
4265 // Should be a function or nil
4266 if(lua_type(L, -1) == LUA_TFUNCTION)
4270 else if(lua_isnil(L, -1))
4277 errorstream<<"Item \""<<name<<"\" callback \""
4278 <<callbackname<<" is not a function"<<std::endl;
4284 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4285 ServerActiveObject *dropper, v3f pos)
4288 assert(lua_checkstack(L, 20));
4289 StackUnroller stack_unroller(L);
4291 // Push callback function on stack
4292 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4296 LuaItemStack::create(L, item);
4297 objectref_get_or_create(L, dropper);
4298 pushFloatPos(L, pos);
4299 if(lua_pcall(L, 3, 1, 0))
4300 script_error(L, "error: %s", lua_tostring(L, -1));
4301 if(!lua_isnil(L, -1))
4302 item = read_item(L, -1);
4306 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4307 ServerActiveObject *placer, const PointedThing &pointed)
4310 assert(lua_checkstack(L, 20));
4311 StackUnroller stack_unroller(L);
4313 // Push callback function on stack
4314 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4318 LuaItemStack::create(L, item);
4319 objectref_get_or_create(L, placer);
4320 push_pointed_thing(L, pointed);
4321 if(lua_pcall(L, 3, 1, 0))
4322 script_error(L, "error: %s", lua_tostring(L, -1));
4323 if(!lua_isnil(L, -1))
4324 item = read_item(L, -1);
4328 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4329 ServerActiveObject *user, const PointedThing &pointed)
4332 assert(lua_checkstack(L, 20));
4333 StackUnroller stack_unroller(L);
4335 // Push callback function on stack
4336 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4340 LuaItemStack::create(L, item);
4341 objectref_get_or_create(L, user);
4342 push_pointed_thing(L, pointed);
4343 if(lua_pcall(L, 3, 1, 0))
4344 script_error(L, "error: %s", lua_tostring(L, -1));
4345 if(!lua_isnil(L, -1))
4346 item = read_item(L, -1);
4350 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4351 ServerActiveObject *puncher)
4354 assert(lua_checkstack(L, 20));
4355 StackUnroller stack_unroller(L);
4357 INodeDefManager *ndef = get_server(L)->ndef();
4359 // Push callback function on stack
4360 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4365 pushnode(L, node, ndef);
4366 objectref_get_or_create(L, puncher);
4367 if(lua_pcall(L, 3, 0, 0))
4368 script_error(L, "error: %s", lua_tostring(L, -1));
4372 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4373 ServerActiveObject *digger)
4376 assert(lua_checkstack(L, 20));
4377 StackUnroller stack_unroller(L);
4379 INodeDefManager *ndef = get_server(L)->ndef();
4381 // Push callback function on stack
4382 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4387 pushnode(L, node, ndef);
4388 objectref_get_or_create(L, digger);
4389 if(lua_pcall(L, 3, 0, 0))
4390 script_error(L, "error: %s", lua_tostring(L, -1));
4398 void scriptapi_environment_step(lua_State *L, float dtime)
4401 assert(lua_checkstack(L, 20));
4402 //infostream<<"scriptapi_environment_step"<<std::endl;
4403 StackUnroller stack_unroller(L);
4405 // Get minetest.registered_globalsteps
4406 lua_getglobal(L, "minetest");
4407 lua_getfield(L, -1, "registered_globalsteps");
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 lua_pushnumber(L, dtime);
4417 if(lua_pcall(L, 1, 0, 0))
4418 script_error(L, "error: %s", lua_tostring(L, -1));
4419 // value removed, keep key for next iteration
4423 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
4427 assert(lua_checkstack(L, 20));
4428 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4429 StackUnroller stack_unroller(L);
4431 // Get minetest.registered_on_generateds
4432 lua_getglobal(L, "minetest");
4433 lua_getfield(L, -1, "registered_on_generateds");
4434 luaL_checktype(L, -1, LUA_TTABLE);
4435 int table = lua_gettop(L);
4438 while(lua_next(L, table) != 0){
4439 // key at index -2 and value at index -1
4440 luaL_checktype(L, -1, LUA_TFUNCTION);
4442 push_v3s16(L, minp);
4443 push_v3s16(L, maxp);
4444 lua_pushnumber(L, blockseed);
4445 if(lua_pcall(L, 3, 0, 0))
4446 script_error(L, "error: %s", lua_tostring(L, -1));
4447 // value removed, keep key for next iteration
4455 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4458 assert(lua_checkstack(L, 20));
4459 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4460 <<name<<"\""<<std::endl;
4461 StackUnroller stack_unroller(L);
4463 // Get minetest.registered_entities[name]
4464 lua_getglobal(L, "minetest");
4465 lua_getfield(L, -1, "registered_entities");
4466 luaL_checktype(L, -1, LUA_TTABLE);
4467 lua_pushstring(L, name);
4468 lua_gettable(L, -2);
4469 // Should be a table, which we will use as a prototype
4470 //luaL_checktype(L, -1, LUA_TTABLE);
4471 if(lua_type(L, -1) != LUA_TTABLE){
4472 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4475 int prototype_table = lua_gettop(L);
4476 //dump2(L, "prototype_table");
4478 // Create entity object
4480 int object = lua_gettop(L);
4482 // Set object metatable
4483 lua_pushvalue(L, prototype_table);
4484 lua_setmetatable(L, -2);
4486 // Add object reference
4487 // This should be userdata with metatable ObjectRef
4488 objectref_get(L, id);
4489 luaL_checktype(L, -1, LUA_TUSERDATA);
4490 if(!luaL_checkudata(L, -1, "ObjectRef"))
4491 luaL_typerror(L, -1, "ObjectRef");
4492 lua_setfield(L, -2, "object");
4494 // minetest.luaentities[id] = object
4495 lua_getglobal(L, "minetest");
4496 lua_getfield(L, -1, "luaentities");
4497 luaL_checktype(L, -1, LUA_TTABLE);
4498 lua_pushnumber(L, id); // Push id
4499 lua_pushvalue(L, object); // Copy object to top of stack
4500 lua_settable(L, -3);
4505 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4506 const std::string &staticdata)
4509 assert(lua_checkstack(L, 20));
4510 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4511 StackUnroller stack_unroller(L);
4513 // Get minetest.luaentities[id]
4514 luaentity_get(L, id);
4515 int object = lua_gettop(L);
4517 // Get on_activate function
4518 lua_pushvalue(L, object);
4519 lua_getfield(L, -1, "on_activate");
4520 if(!lua_isnil(L, -1)){
4521 luaL_checktype(L, -1, LUA_TFUNCTION);
4522 lua_pushvalue(L, object); // self
4523 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4524 // Call with 2 arguments, 0 results
4525 if(lua_pcall(L, 2, 0, 0))
4526 script_error(L, "error running function on_activate: %s\n",
4527 lua_tostring(L, -1));
4531 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4534 assert(lua_checkstack(L, 20));
4535 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4537 // Get minetest.luaentities table
4538 lua_getglobal(L, "minetest");
4539 lua_getfield(L, -1, "luaentities");
4540 luaL_checktype(L, -1, LUA_TTABLE);
4541 int objectstable = lua_gettop(L);
4543 // Set luaentities[id] = nil
4544 lua_pushnumber(L, id); // Push id
4546 lua_settable(L, objectstable);
4548 lua_pop(L, 2); // pop luaentities, minetest
4551 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4554 assert(lua_checkstack(L, 20));
4555 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4556 StackUnroller stack_unroller(L);
4558 // Get minetest.luaentities[id]
4559 luaentity_get(L, id);
4560 int object = lua_gettop(L);
4562 // Get get_staticdata function
4563 lua_pushvalue(L, object);
4564 lua_getfield(L, -1, "get_staticdata");
4565 if(lua_isnil(L, -1))
4568 luaL_checktype(L, -1, LUA_TFUNCTION);
4569 lua_pushvalue(L, object); // self
4570 // Call with 1 arguments, 1 results
4571 if(lua_pcall(L, 1, 1, 0))
4572 script_error(L, "error running function get_staticdata: %s\n",
4573 lua_tostring(L, -1));
4576 const char *s = lua_tolstring(L, -1, &len);
4577 return std::string(s, len);
4580 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4581 LuaEntityProperties *prop)
4584 assert(lua_checkstack(L, 20));
4585 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4586 StackUnroller stack_unroller(L);
4588 // Get minetest.luaentities[id]
4589 luaentity_get(L, id);
4590 //int object = lua_gettop(L);
4594 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
4596 getboolfield(L, -1, "physical", prop->physical);
4598 getfloatfield(L, -1, "weight", prop->weight);
4600 lua_getfield(L, -1, "collisionbox");
4601 if(lua_istable(L, -1))
4602 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
4605 getstringfield(L, -1, "visual", prop->visual);
4607 lua_getfield(L, -1, "visual_size");
4608 if(lua_istable(L, -1))
4609 prop->visual_size = read_v2f(L, -1);
4612 lua_getfield(L, -1, "textures");
4613 if(lua_istable(L, -1)){
4614 prop->textures.clear();
4615 int table = lua_gettop(L);
4617 while(lua_next(L, table) != 0){
4618 // key at index -2 and value at index -1
4619 if(lua_isstring(L, -1))
4620 prop->textures.push_back(lua_tostring(L, -1));
4622 prop->textures.push_back("");
4623 // removes value, keeps key for next iteration
4629 lua_getfield(L, -1, "spritediv");
4630 if(lua_istable(L, -1))
4631 prop->spritediv = read_v2s16(L, -1);
4634 lua_getfield(L, -1, "initial_sprite_basepos");
4635 if(lua_istable(L, -1))
4636 prop->initial_sprite_basepos = read_v2s16(L, -1);
4640 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
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
4651 // Get step function
4652 lua_getfield(L, -1, "on_step");
4653 if(lua_isnil(L, -1))
4655 luaL_checktype(L, -1, LUA_TFUNCTION);
4656 lua_pushvalue(L, object); // self
4657 lua_pushnumber(L, dtime); // dtime
4658 // Call with 2 arguments, 0 results
4659 if(lua_pcall(L, 2, 0, 0))
4660 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4663 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4664 // tool_capabilities, direction)
4665 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4666 ServerActiveObject *puncher, float time_from_last_punch,
4667 const ToolCapabilities *toolcap, v3f dir)
4670 assert(lua_checkstack(L, 20));
4671 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4672 StackUnroller stack_unroller(L);
4674 // Get minetest.luaentities[id]
4675 luaentity_get(L, id);
4676 int object = lua_gettop(L);
4677 // State: object is at top of stack
4679 lua_getfield(L, -1, "on_punch");
4680 if(lua_isnil(L, -1))
4682 luaL_checktype(L, -1, LUA_TFUNCTION);
4683 lua_pushvalue(L, object); // self
4684 objectref_get_or_create(L, puncher); // Clicker reference
4685 lua_pushnumber(L, time_from_last_punch);
4686 push_tool_capabilities(L, *toolcap);
4688 // Call with 5 arguments, 0 results
4689 if(lua_pcall(L, 5, 0, 0))
4690 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4693 // Calls entity:on_rightclick(ObjectRef clicker)
4694 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4695 ServerActiveObject *clicker)
4698 assert(lua_checkstack(L, 20));
4699 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4700 StackUnroller stack_unroller(L);
4702 // Get minetest.luaentities[id]
4703 luaentity_get(L, id);
4704 int object = lua_gettop(L);
4705 // State: object is at top of stack
4707 lua_getfield(L, -1, "on_rightclick");
4708 if(lua_isnil(L, -1))
4710 luaL_checktype(L, -1, LUA_TFUNCTION);
4711 lua_pushvalue(L, object); // self
4712 objectref_get_or_create(L, clicker); // Clicker reference
4713 // Call with 2 arguments, 0 results
4714 if(lua_pcall(L, 2, 0, 0))
4715 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));