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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser 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"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
41 #include "main.h" // For g_settings
42 #include "settings.h" // For accessing g_settings
43 #include "nodemetadata.h"
44 #include "mapblock.h" // For getNodeBlockPos
45 #include "content_nodemeta.h"
47 #include "daynightratio.h"
48 #include "noise.h" // PseudoRandom for LuaPseudoRandom
49 #include "util/pointedthing.h"
51 static void stackDump(lua_State *L, std::ostream &o)
54 int top = lua_gettop(L);
55 for (i = 1; i <= top; i++) { /* repeat for each level */
56 int t = lua_type(L, i);
59 case LUA_TSTRING: /* strings */
60 o<<"\""<<lua_tostring(L, i)<<"\"";
63 case LUA_TBOOLEAN: /* booleans */
64 o<<(lua_toboolean(L, i) ? "true" : "false");
67 case LUA_TNUMBER: /* numbers */ {
69 snprintf(buf, 10, "%g", lua_tonumber(L, i));
73 default: /* other values */
74 o<<lua_typename(L, t);
83 static void realitycheck(lua_State *L)
85 int top = lua_gettop(L);
87 dstream<<"Stack is over 30:"<<std::endl;
88 stackDump(L, dstream);
89 script_error(L, "Stack is over 30 (reality check)");
99 StackUnroller(lua_State *L):
103 m_original_top = lua_gettop(m_lua); // store stack height
107 lua_settop(m_lua, m_original_top); // restore stack height
116 ModNameStorer(lua_State *L_, const std::string modname):
119 // Store current modname in registry
120 lua_pushstring(L, modname.c_str());
121 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
125 // Clear current modname in registry
127 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
132 Getters for stuff in main tables
135 static Server* get_server(lua_State *L)
137 // Get server from registry
138 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
139 Server *server = (Server*)lua_touserdata(L, -1);
144 static ServerEnvironment* get_env(lua_State *L)
146 // Get environment from registry
147 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
148 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
153 static void objectref_get(lua_State *L, u16 id)
155 // Get minetest.object_refs[i]
156 lua_getglobal(L, "minetest");
157 lua_getfield(L, -1, "object_refs");
158 luaL_checktype(L, -1, LUA_TTABLE);
159 lua_pushnumber(L, id);
161 lua_remove(L, -2); // object_refs
162 lua_remove(L, -2); // minetest
165 static void luaentity_get(lua_State *L, u16 id)
167 // Get minetest.luaentities[i]
168 lua_getglobal(L, "minetest");
169 lua_getfield(L, -1, "luaentities");
170 luaL_checktype(L, -1, LUA_TTABLE);
171 lua_pushnumber(L, id);
173 lua_remove(L, -2); // luaentities
174 lua_remove(L, -2); // minetest
181 static bool getstringfield(lua_State *L, int table,
182 const char *fieldname, std::string &result)
184 lua_getfield(L, table, fieldname);
186 if(lua_isstring(L, -1)){
188 const char *ptr = lua_tolstring(L, -1, &len);
189 result.assign(ptr, len);
196 static bool getintfield(lua_State *L, int table,
197 const char *fieldname, int &result)
199 lua_getfield(L, table, fieldname);
201 if(lua_isnumber(L, -1)){
202 result = lua_tonumber(L, -1);
209 static bool getfloatfield(lua_State *L, int table,
210 const char *fieldname, float &result)
212 lua_getfield(L, table, fieldname);
214 if(lua_isnumber(L, -1)){
215 result = lua_tonumber(L, -1);
222 static bool getboolfield(lua_State *L, int table,
223 const char *fieldname, bool &result)
225 lua_getfield(L, table, fieldname);
227 if(lua_isboolean(L, -1)){
228 result = lua_toboolean(L, -1);
235 static std::string checkstringfield(lua_State *L, int table,
236 const char *fieldname)
238 lua_getfield(L, table, fieldname);
239 std::string s = luaL_checkstring(L, -1);
244 static std::string getstringfield_default(lua_State *L, int table,
245 const char *fieldname, const std::string &default_)
247 std::string result = default_;
248 getstringfield(L, table, fieldname, result);
252 static int getintfield_default(lua_State *L, int table,
253 const char *fieldname, int default_)
255 int result = default_;
256 getintfield(L, table, fieldname, result);
260 static float getfloatfield_default(lua_State *L, int table,
261 const char *fieldname, float default_)
263 float result = default_;
264 getfloatfield(L, table, fieldname, result);
268 static bool getboolfield_default(lua_State *L, int table,
269 const char *fieldname, bool default_)
271 bool result = default_;
272 getboolfield(L, table, fieldname, result);
282 static bool string_to_enum(const EnumString *spec, int &result,
283 const std::string &str)
285 const EnumString *esp = spec;
287 if(str == std::string(esp->str)){
296 /*static bool enum_to_string(const EnumString *spec, std::string &result,
299 const EnumString *esp = spec;
310 static int getenumfield(lua_State *L, int table,
311 const char *fieldname, const EnumString *spec, int default_)
313 int result = default_;
314 string_to_enum(spec, result,
315 getstringfield_default(L, table, fieldname, ""));
319 static void setintfield(lua_State *L, int table,
320 const char *fieldname, int value)
322 lua_pushinteger(L, value);
325 lua_setfield(L, table, fieldname);
328 static void setfloatfield(lua_State *L, int table,
329 const char *fieldname, float value)
331 lua_pushnumber(L, value);
334 lua_setfield(L, table, fieldname);
337 static void setboolfield(lua_State *L, int table,
338 const char *fieldname, bool value)
340 lua_pushboolean(L, value);
343 lua_setfield(L, table, fieldname);
346 static void warn_if_field_exists(lua_State *L, int table,
347 const char *fieldname, const std::string &message)
349 lua_getfield(L, table, fieldname);
350 if(!lua_isnil(L, -1)){
351 infostream<<script_get_backtrace(L)<<std::endl;
352 infostream<<"WARNING: field \""<<fieldname<<"\": "
353 <<message<<std::endl;
359 EnumString definitions
362 struct EnumString es_ItemType[] =
366 {ITEM_CRAFT, "craft"},
371 struct EnumString es_DrawType[] =
373 {NDT_NORMAL, "normal"},
374 {NDT_AIRLIKE, "airlike"},
375 {NDT_LIQUID, "liquid"},
376 {NDT_FLOWINGLIQUID, "flowingliquid"},
377 {NDT_GLASSLIKE, "glasslike"},
378 {NDT_ALLFACES, "allfaces"},
379 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
380 {NDT_TORCHLIKE, "torchlike"},
381 {NDT_SIGNLIKE, "signlike"},
382 {NDT_PLANTLIKE, "plantlike"},
383 {NDT_FENCELIKE, "fencelike"},
384 {NDT_RAILLIKE, "raillike"},
388 struct EnumString es_ContentParamType[] =
391 {CPT_LIGHT, "light"},
395 struct EnumString es_ContentParamType2[] =
399 {CPT2_FLOWINGLIQUID, "flowingliquid"},
400 {CPT2_FACEDIR, "facedir"},
401 {CPT2_WALLMOUNTED, "wallmounted"},
405 struct EnumString es_LiquidType[] =
407 {LIQUID_NONE, "none"},
408 {LIQUID_FLOWING, "flowing"},
409 {LIQUID_SOURCE, "source"},
413 struct EnumString es_NodeBoxType[] =
415 {NODEBOX_REGULAR, "regular"},
416 {NODEBOX_FIXED, "fixed"},
417 {NODEBOX_WALLMOUNTED, "wallmounted"},
421 struct EnumString es_CraftMethod[] =
423 {CRAFT_METHOD_NORMAL, "normal"},
424 {CRAFT_METHOD_COOKING, "cooking"},
425 {CRAFT_METHOD_FUEL, "fuel"},
429 struct EnumString es_TileAnimationType[] =
432 {TAT_VERTICAL_FRAMES, "vertical_frames"},
437 C struct <-> Lua table converter functions
440 static void push_v3f(lua_State *L, v3f p)
443 lua_pushnumber(L, p.X);
444 lua_setfield(L, -2, "x");
445 lua_pushnumber(L, p.Y);
446 lua_setfield(L, -2, "y");
447 lua_pushnumber(L, p.Z);
448 lua_setfield(L, -2, "z");
451 static v2s16 read_v2s16(lua_State *L, int index)
454 luaL_checktype(L, index, LUA_TTABLE);
455 lua_getfield(L, index, "x");
456 p.X = lua_tonumber(L, -1);
458 lua_getfield(L, index, "y");
459 p.Y = lua_tonumber(L, -1);
464 static v2f read_v2f(lua_State *L, int index)
467 luaL_checktype(L, index, LUA_TTABLE);
468 lua_getfield(L, index, "x");
469 p.X = lua_tonumber(L, -1);
471 lua_getfield(L, index, "y");
472 p.Y = lua_tonumber(L, -1);
477 static v3f read_v3f(lua_State *L, int index)
480 luaL_checktype(L, index, LUA_TTABLE);
481 lua_getfield(L, index, "x");
482 pos.X = lua_tonumber(L, -1);
484 lua_getfield(L, index, "y");
485 pos.Y = lua_tonumber(L, -1);
487 lua_getfield(L, index, "z");
488 pos.Z = lua_tonumber(L, -1);
493 static v3f check_v3f(lua_State *L, int index)
496 luaL_checktype(L, index, LUA_TTABLE);
497 lua_getfield(L, index, "x");
498 pos.X = luaL_checknumber(L, -1);
500 lua_getfield(L, index, "y");
501 pos.Y = luaL_checknumber(L, -1);
503 lua_getfield(L, index, "z");
504 pos.Z = luaL_checknumber(L, -1);
509 static void pushFloatPos(lua_State *L, v3f p)
515 static v3f checkFloatPos(lua_State *L, int index)
517 return check_v3f(L, index) * BS;
520 static void push_v3s16(lua_State *L, v3s16 p)
523 lua_pushnumber(L, p.X);
524 lua_setfield(L, -2, "x");
525 lua_pushnumber(L, p.Y);
526 lua_setfield(L, -2, "y");
527 lua_pushnumber(L, p.Z);
528 lua_setfield(L, -2, "z");
531 static v3s16 read_v3s16(lua_State *L, int index)
533 // Correct rounding at <0
534 v3f pf = read_v3f(L, index);
535 return floatToInt(pf, 1.0);
538 static v3s16 check_v3s16(lua_State *L, int index)
540 // Correct rounding at <0
541 v3f pf = check_v3f(L, index);
542 return floatToInt(pf, 1.0);
545 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
548 lua_pushstring(L, ndef->get(n).name.c_str());
549 lua_setfield(L, -2, "name");
550 lua_pushnumber(L, n.getParam1());
551 lua_setfield(L, -2, "param1");
552 lua_pushnumber(L, n.getParam2());
553 lua_setfield(L, -2, "param2");
556 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
558 lua_getfield(L, index, "name");
559 const char *name = luaL_checkstring(L, -1);
562 lua_getfield(L, index, "param1");
566 param1 = lua_tonumber(L, -1);
569 lua_getfield(L, index, "param2");
573 param2 = lua_tonumber(L, -1);
575 return MapNode(ndef, name, param1, param2);
578 static video::SColor readARGB8(lua_State *L, int index)
581 luaL_checktype(L, index, LUA_TTABLE);
582 lua_getfield(L, index, "a");
583 if(lua_isnumber(L, -1))
584 color.setAlpha(lua_tonumber(L, -1));
586 lua_getfield(L, index, "r");
587 color.setRed(lua_tonumber(L, -1));
589 lua_getfield(L, index, "g");
590 color.setGreen(lua_tonumber(L, -1));
592 lua_getfield(L, index, "b");
593 color.setBlue(lua_tonumber(L, -1));
598 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
600 core::aabbox3d<f32> box;
601 if(lua_istable(L, -1)){
602 lua_rawgeti(L, -1, 1);
603 box.MinEdge.X = lua_tonumber(L, -1) * scale;
605 lua_rawgeti(L, -1, 2);
606 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
608 lua_rawgeti(L, -1, 3);
609 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
611 lua_rawgeti(L, -1, 4);
612 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
614 lua_rawgeti(L, -1, 5);
615 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
617 lua_rawgeti(L, -1, 6);
618 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
629 static MaterialProperties read_material_properties(
630 lua_State *L, int table)
632 MaterialProperties prop;
633 prop.diggability = (Diggability)getenumfield(L, -1, "diggability",
634 es_Diggability, DIGGABLE_NORMAL);
635 getfloatfield(L, -1, "constant_time", prop.constant_time);
636 getfloatfield(L, -1, "weight", prop.weight);
637 getfloatfield(L, -1, "crackiness", prop.crackiness);
638 getfloatfield(L, -1, "crumbliness", prop.crumbliness);
639 getfloatfield(L, -1, "cuttability", prop.cuttability);
640 getfloatfield(L, -1, "flammability", prop.flammability);
648 static void read_groups(lua_State *L, int index,
649 std::map<std::string, int> &result)
655 while(lua_next(L, index) != 0){
656 // key at index -2 and value at index -1
657 std::string name = luaL_checkstring(L, -2);
658 int rating = luaL_checkinteger(L, -1);
659 result[name] = rating;
660 // removes value, keeps key for next iteration
668 static void read_privileges(lua_State *L, int index,
669 std::set<std::string> &result)
675 while(lua_next(L, index) != 0){
676 // key at index -2 and value at index -1
677 std::string key = luaL_checkstring(L, -2);
678 bool value = lua_toboolean(L, -1);
681 // removes value, keeps key for next iteration
690 static ToolCapabilities read_tool_capabilities(
691 lua_State *L, int table)
693 ToolCapabilities toolcap;
694 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
695 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
696 lua_getfield(L, table, "groupcaps");
697 if(lua_istable(L, -1)){
698 int table_groupcaps = lua_gettop(L);
700 while(lua_next(L, table_groupcaps) != 0){
701 // key at index -2 and value at index -1
702 std::string groupname = luaL_checkstring(L, -2);
703 if(lua_istable(L, -1)){
704 int table_groupcap = lua_gettop(L);
705 // This will be created
706 ToolGroupCap groupcap;
707 // Read simple parameters
708 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
709 getintfield(L, table_groupcap, "uses", groupcap.uses);
710 // DEPRECATED: maxwear
712 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
714 groupcap.uses = 1.0/maxwear;
717 infostream<<script_get_backtrace(L)<<std::endl;
718 infostream<<"WARNING: field \"maxwear\" is deprecated; "
719 <<"should replace with uses=1/maxwear"<<std::endl;
721 // Read "times" table
722 lua_getfield(L, table_groupcap, "times");
723 if(lua_istable(L, -1)){
724 int table_times = lua_gettop(L);
726 while(lua_next(L, table_times) != 0){
727 // key at index -2 and value at index -1
728 int rating = luaL_checkinteger(L, -2);
729 float time = luaL_checknumber(L, -1);
730 groupcap.times[rating] = time;
731 // removes value, keeps key for next iteration
736 // Insert groupcap into toolcap
737 toolcap.groupcaps[groupname] = groupcap;
739 // removes value, keeps key for next iteration
747 static void set_tool_capabilities(lua_State *L, int table,
748 const ToolCapabilities &toolcap)
750 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
751 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
752 // Create groupcaps table
755 for(std::map<std::string, ToolGroupCap>::const_iterator
756 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
757 // Create groupcap table
759 const std::string &name = i->first;
760 const ToolGroupCap &groupcap = i->second;
761 // Create subtable "times"
763 for(std::map<int, float>::const_iterator
764 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
765 int rating = i->first;
766 float time = i->second;
767 lua_pushinteger(L, rating);
768 lua_pushnumber(L, time);
771 // Set subtable "times"
772 lua_setfield(L, -2, "times");
773 // Set simple parameters
774 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
775 setintfield(L, -1, "uses", groupcap.uses);
776 // Insert groupcap table into groupcaps table
777 lua_setfield(L, -2, name.c_str());
779 // Set groupcaps table
780 lua_setfield(L, -2, "groupcaps");
783 static void push_tool_capabilities(lua_State *L,
784 const ToolCapabilities &prop)
787 set_tool_capabilities(L, -1, prop);
794 static void set_dig_params(lua_State *L, int table,
795 const DigParams ¶ms)
797 setboolfield(L, table, "diggable", params.diggable);
798 setfloatfield(L, table, "time", params.time);
799 setintfield(L, table, "wear", params.wear);
802 static void push_dig_params(lua_State *L,
803 const DigParams ¶ms)
806 set_dig_params(L, -1, params);
813 static void set_hit_params(lua_State *L, int table,
814 const HitParams ¶ms)
816 setintfield(L, table, "hp", params.hp);
817 setintfield(L, table, "wear", params.wear);
820 static void push_hit_params(lua_State *L,
821 const HitParams ¶ms)
824 set_hit_params(L, -1, params);
831 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
834 if(pointed.type == POINTEDTHING_NODE)
836 lua_pushstring(L, "node");
837 lua_setfield(L, -2, "type");
838 push_v3s16(L, pointed.node_undersurface);
839 lua_setfield(L, -2, "under");
840 push_v3s16(L, pointed.node_abovesurface);
841 lua_setfield(L, -2, "above");
843 else if(pointed.type == POINTEDTHING_OBJECT)
845 lua_pushstring(L, "object");
846 lua_setfield(L, -2, "type");
847 objectref_get(L, pointed.object_id);
848 lua_setfield(L, -2, "ref");
852 lua_pushstring(L, "nothing");
853 lua_setfield(L, -2, "type");
861 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
864 index = lua_gettop(L) + 1 + index;
865 if(lua_isnil(L, index)){
866 } else if(lua_istable(L, index)){
867 getstringfield(L, index, "name", spec.name);
868 getfloatfield(L, index, "gain", spec.gain);
869 } else if(lua_isstring(L, index)){
870 spec.name = lua_tostring(L, index);
878 static void read_object_properties(lua_State *L, int index,
879 ObjectProperties *prop)
882 index = lua_gettop(L) + 1 + index;
883 if(!lua_istable(L, index))
886 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
888 getboolfield(L, -1, "physical", prop->physical);
890 getfloatfield(L, -1, "weight", prop->weight);
892 lua_getfield(L, -1, "collisionbox");
893 if(lua_istable(L, -1))
894 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
897 getstringfield(L, -1, "visual", prop->visual);
899 lua_getfield(L, -1, "visual_size");
900 if(lua_istable(L, -1))
901 prop->visual_size = read_v2f(L, -1);
904 lua_getfield(L, -1, "textures");
905 if(lua_istable(L, -1)){
906 prop->textures.clear();
907 int table = lua_gettop(L);
909 while(lua_next(L, table) != 0){
910 // key at index -2 and value at index -1
911 if(lua_isstring(L, -1))
912 prop->textures.push_back(lua_tostring(L, -1));
914 prop->textures.push_back("");
915 // removes value, keeps key for next iteration
921 lua_getfield(L, -1, "spritediv");
922 if(lua_istable(L, -1))
923 prop->spritediv = read_v2s16(L, -1);
926 lua_getfield(L, -1, "initial_sprite_basepos");
927 if(lua_istable(L, -1))
928 prop->initial_sprite_basepos = read_v2s16(L, -1);
931 getboolfield(L, -1, "is_visible", prop->is_visible);
932 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
933 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
940 static ItemDefinition read_item_definition(lua_State *L, int index,
941 ItemDefinition default_def = ItemDefinition())
944 index = lua_gettop(L) + 1 + index;
946 // Read the item definition
947 ItemDefinition def = default_def;
949 def.type = (ItemType)getenumfield(L, index, "type",
950 es_ItemType, ITEM_NONE);
951 getstringfield(L, index, "name", def.name);
952 getstringfield(L, index, "description", def.description);
953 getstringfield(L, index, "inventory_image", def.inventory_image);
954 getstringfield(L, index, "wield_image", def.wield_image);
956 lua_getfield(L, index, "wield_scale");
957 if(lua_istable(L, -1)){
958 def.wield_scale = check_v3f(L, -1);
962 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
963 if(def.stack_max == 0)
966 lua_getfield(L, index, "on_use");
967 def.usable = lua_isfunction(L, -1);
970 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
972 warn_if_field_exists(L, index, "tool_digging_properties",
973 "deprecated: use tool_capabilities");
975 lua_getfield(L, index, "tool_capabilities");
976 if(lua_istable(L, -1)){
977 def.tool_capabilities = new ToolCapabilities(
978 read_tool_capabilities(L, -1));
981 // If name is "" (hand), ensure there are ToolCapabilities
982 // because it will be looked up there whenever any other item has
983 // no ToolCapabilities
984 if(def.name == "" && def.tool_capabilities == NULL){
985 def.tool_capabilities = new ToolCapabilities();
988 lua_getfield(L, index, "groups");
989 read_groups(L, -1, def.groups);
992 // Client shall immediately place this node when player places the item.
993 // Server will update the precise end result a moment later.
994 // "" = no prediction
995 getstringfield(L, index, "node_placement_prediction",
996 def.node_placement_prediction);
1005 static TileDef read_tiledef(lua_State *L, int index)
1008 index = lua_gettop(L) + 1 + index;
1012 // key at index -2 and value at index
1013 if(lua_isstring(L, index)){
1014 // "default_lava.png"
1015 tiledef.name = lua_tostring(L, index);
1017 else if(lua_istable(L, index))
1019 // {name="default_lava.png", animation={}}
1021 getstringfield(L, index, "name", tiledef.name);
1022 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1023 tiledef.backface_culling = getboolfield_default(
1024 L, index, "backface_culling", true);
1026 lua_getfield(L, index, "animation");
1027 if(lua_istable(L, -1)){
1028 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1029 tiledef.animation.type = (TileAnimationType)
1030 getenumfield(L, -1, "type", es_TileAnimationType,
1032 tiledef.animation.aspect_w =
1033 getintfield_default(L, -1, "aspect_w", 16);
1034 tiledef.animation.aspect_h =
1035 getintfield_default(L, -1, "aspect_h", 16);
1036 tiledef.animation.length =
1037 getfloatfield_default(L, -1, "length", 1.0);
1049 static ContentFeatures read_content_features(lua_State *L, int index)
1052 index = lua_gettop(L) + 1 + index;
1056 /* Cache existence of some callbacks */
1057 lua_getfield(L, index, "on_construct");
1058 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1060 lua_getfield(L, index, "on_destruct");
1061 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1063 lua_getfield(L, index, "after_destruct");
1064 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1068 getstringfield(L, index, "name", f.name);
1071 lua_getfield(L, index, "groups");
1072 read_groups(L, -1, f.groups);
1075 /* Visual definition */
1077 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1079 getfloatfield(L, index, "visual_scale", f.visual_scale);
1082 lua_getfield(L, index, "tiles");
1083 // If nil, try the deprecated name "tile_images" instead
1084 if(lua_isnil(L, -1)){
1086 warn_if_field_exists(L, index, "tile_images",
1087 "Deprecated; new name is \"tiles\".");
1088 lua_getfield(L, index, "tile_images");
1090 if(lua_istable(L, -1)){
1091 int table = lua_gettop(L);
1094 while(lua_next(L, table) != 0){
1095 // Read tiledef from value
1096 f.tiledef[i] = read_tiledef(L, -1);
1097 // removes value, keeps key for next iteration
1105 // Copy last value to all remaining textures
1107 TileDef lasttile = f.tiledef[i-1];
1109 f.tiledef[i] = lasttile;
1116 // special_tiles = {}
1117 lua_getfield(L, index, "special_tiles");
1118 // If nil, try the deprecated name "special_materials" instead
1119 if(lua_isnil(L, -1)){
1121 warn_if_field_exists(L, index, "special_materials",
1122 "Deprecated; new name is \"special_tiles\".");
1123 lua_getfield(L, index, "special_materials");
1125 if(lua_istable(L, -1)){
1126 int table = lua_gettop(L);
1129 while(lua_next(L, table) != 0){
1130 // Read tiledef from value
1131 f.tiledef_special[i] = read_tiledef(L, -1);
1132 // removes value, keeps key for next iteration
1143 f.alpha = getintfield_default(L, index, "alpha", 255);
1147 lua_getfield(L, index, "post_effect_color");
1148 if(!lua_isnil(L, -1))
1149 f.post_effect_color = readARGB8(L, -1);
1152 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1153 es_ContentParamType, CPT_NONE);
1154 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1155 es_ContentParamType2, CPT2_NONE);
1157 // Warn about some deprecated fields
1158 warn_if_field_exists(L, index, "wall_mounted",
1159 "deprecated: use paramtype2 = 'wallmounted'");
1160 warn_if_field_exists(L, index, "light_propagates",
1161 "deprecated: determined from paramtype");
1162 warn_if_field_exists(L, index, "dug_item",
1163 "deprecated: use 'drop' field");
1164 warn_if_field_exists(L, index, "extra_dug_item",
1165 "deprecated: use 'drop' field");
1166 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1167 "deprecated: use 'drop' field");
1168 warn_if_field_exists(L, index, "metadata_name",
1169 "deprecated: use on_add and metadata callbacks");
1171 // True for all ground-like things like stone and mud, false for eg. trees
1172 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1173 f.light_propagates = (f.param_type == CPT_LIGHT);
1174 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1175 // This is used for collision detection.
1176 // Also for general solidness queries.
1177 getboolfield(L, index, "walkable", f.walkable);
1178 // Player can point to these
1179 getboolfield(L, index, "pointable", f.pointable);
1180 // Player can dig these
1181 getboolfield(L, index, "diggable", f.diggable);
1182 // Player can climb these
1183 getboolfield(L, index, "climbable", f.climbable);
1184 // Player can build on these
1185 getboolfield(L, index, "buildable_to", f.buildable_to);
1186 // Whether the node is non-liquid, source liquid or flowing liquid
1187 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1188 es_LiquidType, LIQUID_NONE);
1189 // If the content is liquid, this is the flowing version of the liquid.
1190 getstringfield(L, index, "liquid_alternative_flowing",
1191 f.liquid_alternative_flowing);
1192 // If the content is liquid, this is the source version of the liquid.
1193 getstringfield(L, index, "liquid_alternative_source",
1194 f.liquid_alternative_source);
1195 // Viscosity for fluid flow, ranging from 1 to 7, with
1196 // 1 giving almost instantaneous propagation and 7 being
1197 // the slowest possible
1198 f.liquid_viscosity = getintfield_default(L, index,
1199 "liquid_viscosity", f.liquid_viscosity);
1200 // Amount of light the node emits
1201 f.light_source = getintfield_default(L, index,
1202 "light_source", f.light_source);
1203 f.damage_per_second = getintfield_default(L, index,
1204 "damage_per_second", f.damage_per_second);
1206 lua_getfield(L, index, "selection_box");
1207 if(lua_istable(L, -1)){
1208 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1209 es_NodeBoxType, NODEBOX_REGULAR);
1211 lua_getfield(L, -1, "fixed");
1212 if(lua_istable(L, -1))
1213 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1216 lua_getfield(L, -1, "wall_top");
1217 if(lua_istable(L, -1))
1218 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1221 lua_getfield(L, -1, "wall_bottom");
1222 if(lua_istable(L, -1))
1223 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1226 lua_getfield(L, -1, "wall_side");
1227 if(lua_istable(L, -1))
1228 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1233 // Set to true if paramtype used to be 'facedir_simple'
1234 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1235 // Set to true if wall_mounted used to be set to true
1236 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1239 lua_getfield(L, index, "sounds");
1240 if(lua_istable(L, -1)){
1241 lua_getfield(L, -1, "footstep");
1242 read_soundspec(L, -1, f.sound_footstep);
1244 lua_getfield(L, -1, "dig");
1245 read_soundspec(L, -1, f.sound_dig);
1247 lua_getfield(L, -1, "dug");
1248 read_soundspec(L, -1, f.sound_dug);
1260 static ItemStack read_item(lua_State *L, int index);
1261 static std::vector<ItemStack> read_items(lua_State *L, int index);
1262 // creates a table of ItemStacks
1263 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1265 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1266 lua_State *L, int tableindex, int forcesize=-1)
1269 tableindex = lua_gettop(L) + 1 + tableindex;
1270 // If nil, delete list
1271 if(lua_isnil(L, tableindex)){
1272 inv->deleteList(name);
1275 // Otherwise set list
1276 std::vector<ItemStack> items = read_items(L, tableindex);
1277 int listsize = (forcesize != -1) ? forcesize : items.size();
1278 InventoryList *invlist = inv->addList(name, listsize);
1280 for(std::vector<ItemStack>::const_iterator
1281 i = items.begin(); i != items.end(); i++){
1282 if(forcesize != -1 && index == forcesize)
1284 invlist->changeItem(index, *i);
1287 while(forcesize != -1 && index < forcesize){
1288 invlist->deleteItem(index);
1293 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1296 InventoryList *invlist = inv->getList(name);
1297 if(invlist == NULL){
1301 std::vector<ItemStack> items;
1302 for(u32 i=0; i<invlist->getSize(); i++)
1303 items.push_back(invlist->getItem(i));
1304 push_items(L, items);
1308 Helpful macros for userdata classes
1311 #define method(class, name) {#name, class::l_##name}
1322 static const char className[];
1323 static const luaL_reg methods[];
1325 // Exported functions
1327 // garbage collector
1328 static int gc_object(lua_State *L)
1330 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1335 // is_empty(self) -> true/false
1336 static int l_is_empty(lua_State *L)
1338 LuaItemStack *o = checkobject(L, 1);
1339 ItemStack &item = o->m_stack;
1340 lua_pushboolean(L, item.empty());
1344 // get_name(self) -> string
1345 static int l_get_name(lua_State *L)
1347 LuaItemStack *o = checkobject(L, 1);
1348 ItemStack &item = o->m_stack;
1349 lua_pushstring(L, item.name.c_str());
1353 // get_count(self) -> number
1354 static int l_get_count(lua_State *L)
1356 LuaItemStack *o = checkobject(L, 1);
1357 ItemStack &item = o->m_stack;
1358 lua_pushinteger(L, item.count);
1362 // get_wear(self) -> number
1363 static int l_get_wear(lua_State *L)
1365 LuaItemStack *o = checkobject(L, 1);
1366 ItemStack &item = o->m_stack;
1367 lua_pushinteger(L, item.wear);
1371 // get_metadata(self) -> string
1372 static int l_get_metadata(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1376 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1380 // clear(self) -> true
1381 static int l_clear(lua_State *L)
1383 LuaItemStack *o = checkobject(L, 1);
1385 lua_pushboolean(L, true);
1389 // replace(self, itemstack or itemstring or table or nil) -> true
1390 static int l_replace(lua_State *L)
1392 LuaItemStack *o = checkobject(L, 1);
1393 o->m_stack = read_item(L, 2);
1394 lua_pushboolean(L, true);
1398 // to_string(self) -> string
1399 static int l_to_string(lua_State *L)
1401 LuaItemStack *o = checkobject(L, 1);
1402 std::string itemstring = o->m_stack.getItemString();
1403 lua_pushstring(L, itemstring.c_str());
1407 // to_table(self) -> table or nil
1408 static int l_to_table(lua_State *L)
1410 LuaItemStack *o = checkobject(L, 1);
1411 const ItemStack &item = o->m_stack;
1419 lua_pushstring(L, item.name.c_str());
1420 lua_setfield(L, -2, "name");
1421 lua_pushinteger(L, item.count);
1422 lua_setfield(L, -2, "count");
1423 lua_pushinteger(L, item.wear);
1424 lua_setfield(L, -2, "wear");
1425 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1426 lua_setfield(L, -2, "metadata");
1431 // get_stack_max(self) -> number
1432 static int l_get_stack_max(lua_State *L)
1434 LuaItemStack *o = checkobject(L, 1);
1435 ItemStack &item = o->m_stack;
1436 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1440 // get_free_space(self) -> number
1441 static int l_get_free_space(lua_State *L)
1443 LuaItemStack *o = checkobject(L, 1);
1444 ItemStack &item = o->m_stack;
1445 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1449 // is_known(self) -> true/false
1450 // Checks if the item is defined.
1451 static int l_is_known(lua_State *L)
1453 LuaItemStack *o = checkobject(L, 1);
1454 ItemStack &item = o->m_stack;
1455 bool is_known = item.isKnown(get_server(L)->idef());
1456 lua_pushboolean(L, is_known);
1460 // get_definition(self) -> table
1461 // Returns the item definition table from minetest.registered_items,
1462 // or a fallback one (name="unknown")
1463 static int l_get_definition(lua_State *L)
1465 LuaItemStack *o = checkobject(L, 1);
1466 ItemStack &item = o->m_stack;
1468 // Get minetest.registered_items[name]
1469 lua_getglobal(L, "minetest");
1470 lua_getfield(L, -1, "registered_items");
1471 luaL_checktype(L, -1, LUA_TTABLE);
1472 lua_getfield(L, -1, item.name.c_str());
1473 if(lua_isnil(L, -1))
1476 lua_getfield(L, -1, "unknown");
1481 // get_tool_capabilities(self) -> table
1482 // Returns the effective tool digging properties.
1483 // Returns those of the hand ("") if this item has none associated.
1484 static int l_get_tool_capabilities(lua_State *L)
1486 LuaItemStack *o = checkobject(L, 1);
1487 ItemStack &item = o->m_stack;
1488 const ToolCapabilities &prop =
1489 item.getToolCapabilities(get_server(L)->idef());
1490 push_tool_capabilities(L, prop);
1494 // add_wear(self, amount) -> true/false
1495 // The range for "amount" is [0,65535]. Wear is only added if the item
1496 // is a tool. Adding wear might destroy the item.
1497 // Returns true if the item is (or was) a tool.
1498 static int l_add_wear(lua_State *L)
1500 LuaItemStack *o = checkobject(L, 1);
1501 ItemStack &item = o->m_stack;
1502 int amount = lua_tointeger(L, 2);
1503 bool result = item.addWear(amount, get_server(L)->idef());
1504 lua_pushboolean(L, result);
1508 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1509 // Returns leftover item stack
1510 static int l_add_item(lua_State *L)
1512 LuaItemStack *o = checkobject(L, 1);
1513 ItemStack &item = o->m_stack;
1514 ItemStack newitem = read_item(L, 2);
1515 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1516 create(L, leftover);
1520 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1521 // First return value is true iff the new item fits fully into the stack
1522 // Second return value is the would-be-left-over item stack
1523 static int l_item_fits(lua_State *L)
1525 LuaItemStack *o = checkobject(L, 1);
1526 ItemStack &item = o->m_stack;
1527 ItemStack newitem = read_item(L, 2);
1529 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1530 lua_pushboolean(L, fits); // first return value
1531 create(L, restitem); // second return value
1535 // take_item(self, takecount=1) -> itemstack
1536 static int l_take_item(lua_State *L)
1538 LuaItemStack *o = checkobject(L, 1);
1539 ItemStack &item = o->m_stack;
1541 if(!lua_isnone(L, 2))
1542 takecount = luaL_checkinteger(L, 2);
1543 ItemStack taken = item.takeItem(takecount);
1548 // peek_item(self, peekcount=1) -> itemstack
1549 static int l_peek_item(lua_State *L)
1551 LuaItemStack *o = checkobject(L, 1);
1552 ItemStack &item = o->m_stack;
1554 if(!lua_isnone(L, 2))
1555 peekcount = lua_tointeger(L, 2);
1556 ItemStack peekaboo = item.peekItem(peekcount);
1557 create(L, peekaboo);
1562 LuaItemStack(const ItemStack &item):
1571 const ItemStack& getItem() const
1575 ItemStack& getItem()
1580 // LuaItemStack(itemstack or itemstring or table or nil)
1581 // Creates an LuaItemStack and leaves it on top of stack
1582 static int create_object(lua_State *L)
1584 ItemStack item = read_item(L, 1);
1585 LuaItemStack *o = new LuaItemStack(item);
1586 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1587 luaL_getmetatable(L, className);
1588 lua_setmetatable(L, -2);
1591 // Not callable from Lua
1592 static int create(lua_State *L, const ItemStack &item)
1594 LuaItemStack *o = new LuaItemStack(item);
1595 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1596 luaL_getmetatable(L, className);
1597 lua_setmetatable(L, -2);
1601 static LuaItemStack* checkobject(lua_State *L, int narg)
1603 luaL_checktype(L, narg, LUA_TUSERDATA);
1604 void *ud = luaL_checkudata(L, narg, className);
1605 if(!ud) luaL_typerror(L, narg, className);
1606 return *(LuaItemStack**)ud; // unbox pointer
1609 static void Register(lua_State *L)
1612 int methodtable = lua_gettop(L);
1613 luaL_newmetatable(L, className);
1614 int metatable = lua_gettop(L);
1616 lua_pushliteral(L, "__metatable");
1617 lua_pushvalue(L, methodtable);
1618 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1620 lua_pushliteral(L, "__index");
1621 lua_pushvalue(L, methodtable);
1622 lua_settable(L, metatable);
1624 lua_pushliteral(L, "__gc");
1625 lua_pushcfunction(L, gc_object);
1626 lua_settable(L, metatable);
1628 lua_pop(L, 1); // drop metatable
1630 luaL_openlib(L, 0, methods, 0); // fill methodtable
1631 lua_pop(L, 1); // drop methodtable
1633 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1634 lua_register(L, className, create_object);
1637 const char LuaItemStack::className[] = "ItemStack";
1638 const luaL_reg LuaItemStack::methods[] = {
1639 method(LuaItemStack, is_empty),
1640 method(LuaItemStack, get_name),
1641 method(LuaItemStack, get_count),
1642 method(LuaItemStack, get_wear),
1643 method(LuaItemStack, get_metadata),
1644 method(LuaItemStack, clear),
1645 method(LuaItemStack, replace),
1646 method(LuaItemStack, to_string),
1647 method(LuaItemStack, to_table),
1648 method(LuaItemStack, get_stack_max),
1649 method(LuaItemStack, get_free_space),
1650 method(LuaItemStack, is_known),
1651 method(LuaItemStack, get_definition),
1652 method(LuaItemStack, get_tool_capabilities),
1653 method(LuaItemStack, add_wear),
1654 method(LuaItemStack, add_item),
1655 method(LuaItemStack, item_fits),
1656 method(LuaItemStack, take_item),
1657 method(LuaItemStack, peek_item),
1661 static ItemStack read_item(lua_State *L, int index)
1664 index = lua_gettop(L) + 1 + index;
1666 if(lua_isnil(L, index))
1670 else if(lua_isuserdata(L, index))
1672 // Convert from LuaItemStack
1673 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1674 return o->getItem();
1676 else if(lua_isstring(L, index))
1678 // Convert from itemstring
1679 std::string itemstring = lua_tostring(L, index);
1680 IItemDefManager *idef = get_server(L)->idef();
1684 item.deSerialize(itemstring, idef);
1687 catch(SerializationError &e)
1689 infostream<<"WARNING: unable to create item from itemstring"
1690 <<": "<<itemstring<<std::endl;
1694 else if(lua_istable(L, index))
1696 // Convert from table
1697 IItemDefManager *idef = get_server(L)->idef();
1698 std::string name = getstringfield_default(L, index, "name", "");
1699 int count = getintfield_default(L, index, "count", 1);
1700 int wear = getintfield_default(L, index, "wear", 0);
1701 std::string metadata = getstringfield_default(L, index, "metadata", "");
1702 return ItemStack(name, count, wear, metadata, idef);
1706 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1710 static std::vector<ItemStack> read_items(lua_State *L, int index)
1713 index = lua_gettop(L) + 1 + index;
1715 std::vector<ItemStack> items;
1716 luaL_checktype(L, index, LUA_TTABLE);
1718 while(lua_next(L, index) != 0){
1719 // key at index -2 and value at index -1
1720 items.push_back(read_item(L, -1));
1721 // removes value, keeps key for next iteration
1727 // creates a table of ItemStacks
1728 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1730 // Get the table insert function
1731 lua_getglobal(L, "table");
1732 lua_getfield(L, -1, "insert");
1733 int table_insert = lua_gettop(L);
1734 // Create and fill table
1736 int table = lua_gettop(L);
1737 for(u32 i=0; i<items.size(); i++){
1738 ItemStack item = items[i];
1739 lua_pushvalue(L, table_insert);
1740 lua_pushvalue(L, table);
1741 LuaItemStack::create(L, item);
1742 if(lua_pcall(L, 2, 0, 0))
1743 script_error(L, "error: %s", lua_tostring(L, -1));
1745 lua_remove(L, -2); // Remove table
1746 lua_remove(L, -2); // Remove insert
1756 InventoryLocation m_loc;
1758 static const char className[];
1759 static const luaL_reg methods[];
1761 static InvRef *checkobject(lua_State *L, int narg)
1763 luaL_checktype(L, narg, LUA_TUSERDATA);
1764 void *ud = luaL_checkudata(L, narg, className);
1765 if(!ud) luaL_typerror(L, narg, className);
1766 return *(InvRef**)ud; // unbox pointer
1769 static Inventory* getinv(lua_State *L, InvRef *ref)
1771 return get_server(L)->getInventory(ref->m_loc);
1774 static InventoryList* getlist(lua_State *L, InvRef *ref,
1775 const char *listname)
1777 Inventory *inv = getinv(L, ref);
1780 return inv->getList(listname);
1783 static void reportInventoryChange(lua_State *L, InvRef *ref)
1785 // Inform other things that the inventory has changed
1786 get_server(L)->setInventoryModified(ref->m_loc);
1789 // Exported functions
1791 // garbage collector
1792 static int gc_object(lua_State *L) {
1793 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1798 // is_empty(self, listname) -> true/false
1799 static int l_is_empty(lua_State *L)
1801 InvRef *ref = checkobject(L, 1);
1802 const char *listname = luaL_checkstring(L, 2);
1803 InventoryList *list = getlist(L, ref, listname);
1804 if(list && list->getUsedSlots() > 0){
1805 lua_pushboolean(L, false);
1807 lua_pushboolean(L, true);
1812 // get_size(self, listname)
1813 static int l_get_size(lua_State *L)
1815 InvRef *ref = checkobject(L, 1);
1816 const char *listname = luaL_checkstring(L, 2);
1817 InventoryList *list = getlist(L, ref, listname);
1819 lua_pushinteger(L, list->getSize());
1821 lua_pushinteger(L, 0);
1826 // set_size(self, listname, size)
1827 static int l_set_size(lua_State *L)
1829 InvRef *ref = checkobject(L, 1);
1830 const char *listname = luaL_checkstring(L, 2);
1831 int newsize = luaL_checknumber(L, 3);
1832 Inventory *inv = getinv(L, ref);
1834 inv->deleteList(listname);
1835 reportInventoryChange(L, ref);
1838 InventoryList *list = inv->getList(listname);
1840 list->setSize(newsize);
1842 list = inv->addList(listname, newsize);
1844 reportInventoryChange(L, ref);
1848 // get_stack(self, listname, i) -> itemstack
1849 static int l_get_stack(lua_State *L)
1851 InvRef *ref = checkobject(L, 1);
1852 const char *listname = luaL_checkstring(L, 2);
1853 int i = luaL_checknumber(L, 3) - 1;
1854 InventoryList *list = getlist(L, ref, listname);
1856 if(list != NULL && i >= 0 && i < (int) list->getSize())
1857 item = list->getItem(i);
1858 LuaItemStack::create(L, item);
1862 // set_stack(self, listname, i, stack) -> true/false
1863 static int l_set_stack(lua_State *L)
1865 InvRef *ref = checkobject(L, 1);
1866 const char *listname = luaL_checkstring(L, 2);
1867 int i = luaL_checknumber(L, 3) - 1;
1868 ItemStack newitem = read_item(L, 4);
1869 InventoryList *list = getlist(L, ref, listname);
1870 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1871 list->changeItem(i, newitem);
1872 reportInventoryChange(L, ref);
1873 lua_pushboolean(L, true);
1875 lua_pushboolean(L, false);
1880 // get_list(self, listname) -> list or nil
1881 static int l_get_list(lua_State *L)
1883 InvRef *ref = checkobject(L, 1);
1884 const char *listname = luaL_checkstring(L, 2);
1885 Inventory *inv = getinv(L, ref);
1886 inventory_get_list_to_lua(inv, listname, L);
1890 // set_list(self, listname, list)
1891 static int l_set_list(lua_State *L)
1893 InvRef *ref = checkobject(L, 1);
1894 const char *listname = luaL_checkstring(L, 2);
1895 Inventory *inv = getinv(L, ref);
1896 InventoryList *list = inv->getList(listname);
1898 inventory_set_list_from_lua(inv, listname, L, 3,
1901 inventory_set_list_from_lua(inv, listname, L, 3);
1902 reportInventoryChange(L, ref);
1906 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1907 // Returns the leftover stack
1908 static int l_add_item(lua_State *L)
1910 InvRef *ref = checkobject(L, 1);
1911 const char *listname = luaL_checkstring(L, 2);
1912 ItemStack item = read_item(L, 3);
1913 InventoryList *list = getlist(L, ref, listname);
1915 ItemStack leftover = list->addItem(item);
1916 if(leftover.count != item.count)
1917 reportInventoryChange(L, ref);
1918 LuaItemStack::create(L, leftover);
1920 LuaItemStack::create(L, item);
1925 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1926 // Returns true if the item completely fits into the list
1927 static int l_room_for_item(lua_State *L)
1929 InvRef *ref = checkobject(L, 1);
1930 const char *listname = luaL_checkstring(L, 2);
1931 ItemStack item = read_item(L, 3);
1932 InventoryList *list = getlist(L, ref, listname);
1934 lua_pushboolean(L, list->roomForItem(item));
1936 lua_pushboolean(L, false);
1941 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1942 // Returns true if the list contains the given count of the given item name
1943 static int l_contains_item(lua_State *L)
1945 InvRef *ref = checkobject(L, 1);
1946 const char *listname = luaL_checkstring(L, 2);
1947 ItemStack item = read_item(L, 3);
1948 InventoryList *list = getlist(L, ref, listname);
1950 lua_pushboolean(L, list->containsItem(item));
1952 lua_pushboolean(L, false);
1957 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1958 // Returns the items that were actually removed
1959 static int l_remove_item(lua_State *L)
1961 InvRef *ref = checkobject(L, 1);
1962 const char *listname = luaL_checkstring(L, 2);
1963 ItemStack item = read_item(L, 3);
1964 InventoryList *list = getlist(L, ref, listname);
1966 ItemStack removed = list->removeItem(item);
1967 if(!removed.empty())
1968 reportInventoryChange(L, ref);
1969 LuaItemStack::create(L, removed);
1971 LuaItemStack::create(L, ItemStack());
1977 InvRef(const InventoryLocation &loc):
1986 // Creates an InvRef and leaves it on top of stack
1987 // Not callable from Lua; all references are created on the C side.
1988 static void create(lua_State *L, const InventoryLocation &loc)
1990 InvRef *o = new InvRef(loc);
1991 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1992 luaL_getmetatable(L, className);
1993 lua_setmetatable(L, -2);
1995 static void createPlayer(lua_State *L, Player *player)
1997 InventoryLocation loc;
1998 loc.setPlayer(player->getName());
2001 static void createNodeMeta(lua_State *L, v3s16 p)
2003 InventoryLocation loc;
2008 static void Register(lua_State *L)
2011 int methodtable = lua_gettop(L);
2012 luaL_newmetatable(L, className);
2013 int metatable = lua_gettop(L);
2015 lua_pushliteral(L, "__metatable");
2016 lua_pushvalue(L, methodtable);
2017 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2019 lua_pushliteral(L, "__index");
2020 lua_pushvalue(L, methodtable);
2021 lua_settable(L, metatable);
2023 lua_pushliteral(L, "__gc");
2024 lua_pushcfunction(L, gc_object);
2025 lua_settable(L, metatable);
2027 lua_pop(L, 1); // drop metatable
2029 luaL_openlib(L, 0, methods, 0); // fill methodtable
2030 lua_pop(L, 1); // drop methodtable
2032 // Cannot be created from Lua
2033 //lua_register(L, className, create_object);
2036 const char InvRef::className[] = "InvRef";
2037 const luaL_reg InvRef::methods[] = {
2038 method(InvRef, is_empty),
2039 method(InvRef, get_size),
2040 method(InvRef, set_size),
2041 method(InvRef, get_stack),
2042 method(InvRef, set_stack),
2043 method(InvRef, get_list),
2044 method(InvRef, set_list),
2045 method(InvRef, add_item),
2046 method(InvRef, room_for_item),
2047 method(InvRef, contains_item),
2048 method(InvRef, remove_item),
2060 ServerEnvironment *m_env;
2062 static const char className[];
2063 static const luaL_reg methods[];
2065 static NodeMetaRef *checkobject(lua_State *L, int narg)
2067 luaL_checktype(L, narg, LUA_TUSERDATA);
2068 void *ud = luaL_checkudata(L, narg, className);
2069 if(!ud) luaL_typerror(L, narg, className);
2070 return *(NodeMetaRef**)ud; // unbox pointer
2073 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2075 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2076 if(meta == NULL && auto_create)
2078 meta = new NodeMetadata(ref->m_env->getGameDef());
2079 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2084 static void reportMetadataChange(NodeMetaRef *ref)
2086 // Inform other things that the metadata has changed
2087 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2089 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2091 ref->m_env->getMap().dispatchEvent(&event);
2092 // Set the block to be saved
2093 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2095 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2096 "NodeMetaRef::reportMetadataChange");
2099 // Exported functions
2101 // garbage collector
2102 static int gc_object(lua_State *L) {
2103 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2108 // get_string(self, name)
2109 static int l_get_string(lua_State *L)
2111 NodeMetaRef *ref = checkobject(L, 1);
2112 std::string name = luaL_checkstring(L, 2);
2114 NodeMetadata *meta = getmeta(ref, false);
2116 lua_pushlstring(L, "", 0);
2119 std::string str = meta->getString(name);
2120 lua_pushlstring(L, str.c_str(), str.size());
2124 // set_string(self, name, var)
2125 static int l_set_string(lua_State *L)
2127 NodeMetaRef *ref = checkobject(L, 1);
2128 std::string name = luaL_checkstring(L, 2);
2130 const char *s = lua_tolstring(L, 3, &len);
2131 std::string str(s, len);
2133 NodeMetadata *meta = getmeta(ref, !str.empty());
2134 if(meta == NULL || str == meta->getString(name))
2136 meta->setString(name, str);
2137 reportMetadataChange(ref);
2141 // get_int(self, name)
2142 static int l_get_int(lua_State *L)
2144 NodeMetaRef *ref = checkobject(L, 1);
2145 std::string name = lua_tostring(L, 2);
2147 NodeMetadata *meta = getmeta(ref, false);
2149 lua_pushnumber(L, 0);
2152 std::string str = meta->getString(name);
2153 lua_pushnumber(L, stoi(str));
2157 // set_int(self, name, var)
2158 static int l_set_int(lua_State *L)
2160 NodeMetaRef *ref = checkobject(L, 1);
2161 std::string name = lua_tostring(L, 2);
2162 int a = lua_tointeger(L, 3);
2163 std::string str = itos(a);
2165 NodeMetadata *meta = getmeta(ref, true);
2166 if(meta == NULL || str == meta->getString(name))
2168 meta->setString(name, str);
2169 reportMetadataChange(ref);
2173 // get_float(self, name)
2174 static int l_get_float(lua_State *L)
2176 NodeMetaRef *ref = checkobject(L, 1);
2177 std::string name = lua_tostring(L, 2);
2179 NodeMetadata *meta = getmeta(ref, false);
2181 lua_pushnumber(L, 0);
2184 std::string str = meta->getString(name);
2185 lua_pushnumber(L, stof(str));
2189 // set_float(self, name, var)
2190 static int l_set_float(lua_State *L)
2192 NodeMetaRef *ref = checkobject(L, 1);
2193 std::string name = lua_tostring(L, 2);
2194 float a = lua_tonumber(L, 3);
2195 std::string str = ftos(a);
2197 NodeMetadata *meta = getmeta(ref, true);
2198 if(meta == NULL || str == meta->getString(name))
2200 meta->setString(name, str);
2201 reportMetadataChange(ref);
2205 // get_inventory(self)
2206 static int l_get_inventory(lua_State *L)
2208 NodeMetaRef *ref = checkobject(L, 1);
2209 getmeta(ref, true); // try to ensure the metadata exists
2210 InvRef::createNodeMeta(L, ref->m_p);
2215 static int l_to_table(lua_State *L)
2217 NodeMetaRef *ref = checkobject(L, 1);
2219 NodeMetadata *meta = getmeta(ref, true);
2228 std::map<std::string, std::string> fields = meta->getStrings();
2229 for(std::map<std::string, std::string>::const_iterator
2230 i = fields.begin(); i != fields.end(); i++){
2231 const std::string &name = i->first;
2232 const std::string &value = i->second;
2233 lua_pushlstring(L, name.c_str(), name.size());
2234 lua_pushlstring(L, value.c_str(), value.size());
2235 lua_settable(L, -3);
2238 lua_setfield(L, -2, "fields");
2241 Inventory *inv = meta->getInventory();
2243 std::vector<const InventoryList*> lists = inv->getLists();
2244 for(std::vector<const InventoryList*>::const_iterator
2245 i = lists.begin(); i != lists.end(); i++){
2246 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2247 lua_setfield(L, -2, (*i)->getName().c_str());
2250 lua_setfield(L, -2, "inventory");
2254 // from_table(self, table)
2255 static int l_from_table(lua_State *L)
2257 NodeMetaRef *ref = checkobject(L, 1);
2260 if(lua_isnil(L, base)){
2262 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2263 lua_pushboolean(L, true);
2267 // Has metadata; clear old one first
2268 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2269 // Create new metadata
2270 NodeMetadata *meta = getmeta(ref, true);
2272 lua_getfield(L, base, "fields");
2273 int fieldstable = lua_gettop(L);
2275 while(lua_next(L, fieldstable) != 0){
2276 // key at index -2 and value at index -1
2277 std::string name = lua_tostring(L, -2);
2279 const char *cs = lua_tolstring(L, -1, &cl);
2280 std::string value(cs, cl);
2281 meta->setString(name, value);
2282 lua_pop(L, 1); // removes value, keeps key for next iteration
2285 Inventory *inv = meta->getInventory();
2286 lua_getfield(L, base, "inventory");
2287 int inventorytable = lua_gettop(L);
2289 while(lua_next(L, inventorytable) != 0){
2290 // key at index -2 and value at index -1
2291 std::string name = lua_tostring(L, -2);
2292 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2293 lua_pop(L, 1); // removes value, keeps key for next iteration
2295 reportMetadataChange(ref);
2296 lua_pushboolean(L, true);
2301 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2311 // Creates an NodeMetaRef and leaves it on top of stack
2312 // Not callable from Lua; all references are created on the C side.
2313 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2315 NodeMetaRef *o = new NodeMetaRef(p, env);
2316 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2317 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2318 luaL_getmetatable(L, className);
2319 lua_setmetatable(L, -2);
2322 static void Register(lua_State *L)
2325 int methodtable = lua_gettop(L);
2326 luaL_newmetatable(L, className);
2327 int metatable = lua_gettop(L);
2329 lua_pushliteral(L, "__metatable");
2330 lua_pushvalue(L, methodtable);
2331 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2333 lua_pushliteral(L, "__index");
2334 lua_pushvalue(L, methodtable);
2335 lua_settable(L, metatable);
2337 lua_pushliteral(L, "__gc");
2338 lua_pushcfunction(L, gc_object);
2339 lua_settable(L, metatable);
2341 lua_pop(L, 1); // drop metatable
2343 luaL_openlib(L, 0, methods, 0); // fill methodtable
2344 lua_pop(L, 1); // drop methodtable
2346 // Cannot be created from Lua
2347 //lua_register(L, className, create_object);
2350 const char NodeMetaRef::className[] = "NodeMetaRef";
2351 const luaL_reg NodeMetaRef::methods[] = {
2352 method(NodeMetaRef, get_string),
2353 method(NodeMetaRef, set_string),
2354 method(NodeMetaRef, get_int),
2355 method(NodeMetaRef, set_int),
2356 method(NodeMetaRef, get_float),
2357 method(NodeMetaRef, set_float),
2358 method(NodeMetaRef, get_inventory),
2359 method(NodeMetaRef, to_table),
2360 method(NodeMetaRef, from_table),
2371 ServerActiveObject *m_object;
2373 static const char className[];
2374 static const luaL_reg methods[];
2376 static ObjectRef *checkobject(lua_State *L, int narg)
2378 luaL_checktype(L, narg, LUA_TUSERDATA);
2379 void *ud = luaL_checkudata(L, narg, className);
2380 if(!ud) luaL_typerror(L, narg, className);
2381 return *(ObjectRef**)ud; // unbox pointer
2384 static ServerActiveObject* getobject(ObjectRef *ref)
2386 ServerActiveObject *co = ref->m_object;
2390 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2392 ServerActiveObject *obj = getobject(ref);
2395 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2397 return (LuaEntitySAO*)obj;
2400 static PlayerSAO* getplayersao(ObjectRef *ref)
2402 ServerActiveObject *obj = getobject(ref);
2405 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2407 return (PlayerSAO*)obj;
2410 static Player* getplayer(ObjectRef *ref)
2412 PlayerSAO *playersao = getplayersao(ref);
2413 if(playersao == NULL)
2415 return playersao->getPlayer();
2418 // Exported functions
2420 // garbage collector
2421 static int gc_object(lua_State *L) {
2422 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2423 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2429 static int l_remove(lua_State *L)
2431 ObjectRef *ref = checkobject(L, 1);
2432 ServerActiveObject *co = getobject(ref);
2433 if(co == NULL) return 0;
2434 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2435 co->m_removed = true;
2440 // returns: {x=num, y=num, z=num}
2441 static int l_getpos(lua_State *L)
2443 ObjectRef *ref = checkobject(L, 1);
2444 ServerActiveObject *co = getobject(ref);
2445 if(co == NULL) return 0;
2446 v3f pos = co->getBasePosition() / BS;
2448 lua_pushnumber(L, pos.X);
2449 lua_setfield(L, -2, "x");
2450 lua_pushnumber(L, pos.Y);
2451 lua_setfield(L, -2, "y");
2452 lua_pushnumber(L, pos.Z);
2453 lua_setfield(L, -2, "z");
2457 // setpos(self, pos)
2458 static int l_setpos(lua_State *L)
2460 ObjectRef *ref = checkobject(L, 1);
2461 //LuaEntitySAO *co = getluaobject(ref);
2462 ServerActiveObject *co = getobject(ref);
2463 if(co == NULL) return 0;
2465 v3f pos = checkFloatPos(L, 2);
2471 // moveto(self, pos, continuous=false)
2472 static int l_moveto(lua_State *L)
2474 ObjectRef *ref = checkobject(L, 1);
2475 //LuaEntitySAO *co = getluaobject(ref);
2476 ServerActiveObject *co = getobject(ref);
2477 if(co == NULL) return 0;
2479 v3f pos = checkFloatPos(L, 2);
2481 bool continuous = lua_toboolean(L, 3);
2483 co->moveTo(pos, continuous);
2487 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2488 static int l_punch(lua_State *L)
2490 ObjectRef *ref = checkobject(L, 1);
2491 ObjectRef *puncher_ref = checkobject(L, 2);
2492 ServerActiveObject *co = getobject(ref);
2493 ServerActiveObject *puncher = getobject(puncher_ref);
2494 if(co == NULL) return 0;
2495 if(puncher == NULL) return 0;
2496 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2497 v3f dir = read_v3f(L, 4);
2498 float time_from_last_punch = 1000000;
2499 if(lua_isnumber(L, 5))
2500 time_from_last_punch = lua_tonumber(L, 5);
2502 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2506 // right_click(self, clicker); clicker = an another ObjectRef
2507 static int l_right_click(lua_State *L)
2509 ObjectRef *ref = checkobject(L, 1);
2510 ObjectRef *ref2 = checkobject(L, 2);
2511 ServerActiveObject *co = getobject(ref);
2512 ServerActiveObject *co2 = getobject(ref2);
2513 if(co == NULL) return 0;
2514 if(co2 == NULL) return 0;
2516 co->rightClick(co2);
2521 // hp = number of hitpoints (2 * number of hearts)
2523 static int l_set_hp(lua_State *L)
2525 ObjectRef *ref = checkobject(L, 1);
2526 luaL_checknumber(L, 2);
2527 ServerActiveObject *co = getobject(ref);
2528 if(co == NULL) return 0;
2529 int hp = lua_tonumber(L, 2);
2530 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2531 <<" hp="<<hp<<std::endl;*/
2539 // returns: number of hitpoints (2 * number of hearts)
2540 // 0 if not applicable to this type of object
2541 static int l_get_hp(lua_State *L)
2543 ObjectRef *ref = checkobject(L, 1);
2544 ServerActiveObject *co = getobject(ref);
2547 lua_pushnumber(L, 1);
2550 int hp = co->getHP();
2551 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2552 <<" hp="<<hp<<std::endl;*/
2554 lua_pushnumber(L, hp);
2558 // get_inventory(self)
2559 static int l_get_inventory(lua_State *L)
2561 ObjectRef *ref = checkobject(L, 1);
2562 ServerActiveObject *co = getobject(ref);
2563 if(co == NULL) return 0;
2565 InventoryLocation loc = co->getInventoryLocation();
2566 if(get_server(L)->getInventory(loc) != NULL)
2567 InvRef::create(L, loc);
2569 lua_pushnil(L); // An object may have no inventory (nil)
2573 // get_wield_list(self)
2574 static int l_get_wield_list(lua_State *L)
2576 ObjectRef *ref = checkobject(L, 1);
2577 ServerActiveObject *co = getobject(ref);
2578 if(co == NULL) return 0;
2580 lua_pushstring(L, co->getWieldList().c_str());
2584 // get_wield_index(self)
2585 static int l_get_wield_index(lua_State *L)
2587 ObjectRef *ref = checkobject(L, 1);
2588 ServerActiveObject *co = getobject(ref);
2589 if(co == NULL) return 0;
2591 lua_pushinteger(L, co->getWieldIndex() + 1);
2595 // get_wielded_item(self)
2596 static int l_get_wielded_item(lua_State *L)
2598 ObjectRef *ref = checkobject(L, 1);
2599 ServerActiveObject *co = getobject(ref);
2602 LuaItemStack::create(L, ItemStack());
2606 LuaItemStack::create(L, co->getWieldedItem());
2610 // set_wielded_item(self, itemstack or itemstring or table or nil)
2611 static int l_set_wielded_item(lua_State *L)
2613 ObjectRef *ref = checkobject(L, 1);
2614 ServerActiveObject *co = getobject(ref);
2615 if(co == NULL) return 0;
2617 ItemStack item = read_item(L, 2);
2618 bool success = co->setWieldedItem(item);
2619 lua_pushboolean(L, success);
2623 // set_armor_groups(self, groups)
2624 static int l_set_armor_groups(lua_State *L)
2626 ObjectRef *ref = checkobject(L, 1);
2627 ServerActiveObject *co = getobject(ref);
2628 if(co == NULL) return 0;
2630 ItemGroupList groups;
2631 read_groups(L, 2, groups);
2632 co->setArmorGroups(groups);
2636 // set_properties(self, properties)
2637 static int l_set_properties(lua_State *L)
2639 ObjectRef *ref = checkobject(L, 1);
2640 ServerActiveObject *co = getobject(ref);
2641 if(co == NULL) return 0;
2642 ObjectProperties *prop = co->accessObjectProperties();
2645 read_object_properties(L, 2, prop);
2646 co->notifyObjectPropertiesModified();
2650 /* LuaEntitySAO-only */
2652 // setvelocity(self, {x=num, y=num, z=num})
2653 static int l_setvelocity(lua_State *L)
2655 ObjectRef *ref = checkobject(L, 1);
2656 LuaEntitySAO *co = getluaobject(ref);
2657 if(co == NULL) return 0;
2658 v3f pos = checkFloatPos(L, 2);
2660 co->setVelocity(pos);
2664 // getvelocity(self)
2665 static int l_getvelocity(lua_State *L)
2667 ObjectRef *ref = checkobject(L, 1);
2668 LuaEntitySAO *co = getluaobject(ref);
2669 if(co == NULL) return 0;
2671 v3f v = co->getVelocity();
2676 // setacceleration(self, {x=num, y=num, z=num})
2677 static int l_setacceleration(lua_State *L)
2679 ObjectRef *ref = checkobject(L, 1);
2680 LuaEntitySAO *co = getluaobject(ref);
2681 if(co == NULL) return 0;
2683 v3f pos = checkFloatPos(L, 2);
2685 co->setAcceleration(pos);
2689 // getacceleration(self)
2690 static int l_getacceleration(lua_State *L)
2692 ObjectRef *ref = checkobject(L, 1);
2693 LuaEntitySAO *co = getluaobject(ref);
2694 if(co == NULL) return 0;
2696 v3f v = co->getAcceleration();
2701 // setyaw(self, radians)
2702 static int l_setyaw(lua_State *L)
2704 ObjectRef *ref = checkobject(L, 1);
2705 LuaEntitySAO *co = getluaobject(ref);
2706 if(co == NULL) return 0;
2707 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2714 static int l_getyaw(lua_State *L)
2716 ObjectRef *ref = checkobject(L, 1);
2717 LuaEntitySAO *co = getluaobject(ref);
2718 if(co == NULL) return 0;
2720 float yaw = co->getYaw() * core::DEGTORAD;
2721 lua_pushnumber(L, yaw);
2725 // settexturemod(self, mod)
2726 static int l_settexturemod(lua_State *L)
2728 ObjectRef *ref = checkobject(L, 1);
2729 LuaEntitySAO *co = getluaobject(ref);
2730 if(co == NULL) return 0;
2732 std::string mod = luaL_checkstring(L, 2);
2733 co->setTextureMod(mod);
2737 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2738 // select_horiz_by_yawpitch=false)
2739 static int l_setsprite(lua_State *L)
2741 ObjectRef *ref = checkobject(L, 1);
2742 LuaEntitySAO *co = getluaobject(ref);
2743 if(co == NULL) return 0;
2746 if(!lua_isnil(L, 2))
2747 p = read_v2s16(L, 2);
2749 if(!lua_isnil(L, 3))
2750 num_frames = lua_tonumber(L, 3);
2751 float framelength = 0.2;
2752 if(!lua_isnil(L, 4))
2753 framelength = lua_tonumber(L, 4);
2754 bool select_horiz_by_yawpitch = false;
2755 if(!lua_isnil(L, 5))
2756 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2757 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2762 // get_entity_name(self)
2763 static int l_get_entity_name(lua_State *L)
2765 ObjectRef *ref = checkobject(L, 1);
2766 LuaEntitySAO *co = getluaobject(ref);
2767 if(co == NULL) return 0;
2769 std::string name = co->getName();
2770 lua_pushstring(L, name.c_str());
2774 // get_luaentity(self)
2775 static int l_get_luaentity(lua_State *L)
2777 ObjectRef *ref = checkobject(L, 1);
2778 LuaEntitySAO *co = getluaobject(ref);
2779 if(co == NULL) return 0;
2781 luaentity_get(L, co->getId());
2788 static int l_is_player(lua_State *L)
2790 ObjectRef *ref = checkobject(L, 1);
2791 Player *player = getplayer(ref);
2792 lua_pushboolean(L, (player != NULL));
2796 // get_player_name(self)
2797 static int l_get_player_name(lua_State *L)
2799 ObjectRef *ref = checkobject(L, 1);
2800 Player *player = getplayer(ref);
2802 lua_pushlstring(L, "", 0);
2806 lua_pushstring(L, player->getName());
2810 // get_look_dir(self)
2811 static int l_get_look_dir(lua_State *L)
2813 ObjectRef *ref = checkobject(L, 1);
2814 Player *player = getplayer(ref);
2815 if(player == NULL) return 0;
2817 float pitch = player->getRadPitch();
2818 float yaw = player->getRadYaw();
2819 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2824 // get_look_pitch(self)
2825 static int l_get_look_pitch(lua_State *L)
2827 ObjectRef *ref = checkobject(L, 1);
2828 Player *player = getplayer(ref);
2829 if(player == NULL) return 0;
2831 lua_pushnumber(L, player->getRadPitch());
2835 // get_look_yaw(self)
2836 static int l_get_look_yaw(lua_State *L)
2838 ObjectRef *ref = checkobject(L, 1);
2839 Player *player = getplayer(ref);
2840 if(player == NULL) return 0;
2842 lua_pushnumber(L, player->getRadYaw());
2847 ObjectRef(ServerActiveObject *object):
2850 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2856 infostream<<"ObjectRef destructing for id="
2857 <<m_object->getId()<<std::endl;
2859 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2862 // Creates an ObjectRef and leaves it on top of stack
2863 // Not callable from Lua; all references are created on the C side.
2864 static void create(lua_State *L, ServerActiveObject *object)
2866 ObjectRef *o = new ObjectRef(object);
2867 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2868 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2869 luaL_getmetatable(L, className);
2870 lua_setmetatable(L, -2);
2873 static void set_null(lua_State *L)
2875 ObjectRef *o = checkobject(L, -1);
2879 static void Register(lua_State *L)
2882 int methodtable = lua_gettop(L);
2883 luaL_newmetatable(L, className);
2884 int metatable = lua_gettop(L);
2886 lua_pushliteral(L, "__metatable");
2887 lua_pushvalue(L, methodtable);
2888 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2890 lua_pushliteral(L, "__index");
2891 lua_pushvalue(L, methodtable);
2892 lua_settable(L, metatable);
2894 lua_pushliteral(L, "__gc");
2895 lua_pushcfunction(L, gc_object);
2896 lua_settable(L, metatable);
2898 lua_pop(L, 1); // drop metatable
2900 luaL_openlib(L, 0, methods, 0); // fill methodtable
2901 lua_pop(L, 1); // drop methodtable
2903 // Cannot be created from Lua
2904 //lua_register(L, className, create_object);
2907 const char ObjectRef::className[] = "ObjectRef";
2908 const luaL_reg ObjectRef::methods[] = {
2909 // ServerActiveObject
2910 method(ObjectRef, remove),
2911 method(ObjectRef, getpos),
2912 method(ObjectRef, setpos),
2913 method(ObjectRef, moveto),
2914 method(ObjectRef, punch),
2915 method(ObjectRef, right_click),
2916 method(ObjectRef, set_hp),
2917 method(ObjectRef, get_hp),
2918 method(ObjectRef, get_inventory),
2919 method(ObjectRef, get_wield_list),
2920 method(ObjectRef, get_wield_index),
2921 method(ObjectRef, get_wielded_item),
2922 method(ObjectRef, set_wielded_item),
2923 method(ObjectRef, set_armor_groups),
2924 method(ObjectRef, set_properties),
2925 // LuaEntitySAO-only
2926 method(ObjectRef, setvelocity),
2927 method(ObjectRef, getvelocity),
2928 method(ObjectRef, setacceleration),
2929 method(ObjectRef, getacceleration),
2930 method(ObjectRef, setyaw),
2931 method(ObjectRef, getyaw),
2932 method(ObjectRef, settexturemod),
2933 method(ObjectRef, setsprite),
2934 method(ObjectRef, get_entity_name),
2935 method(ObjectRef, get_luaentity),
2937 method(ObjectRef, get_player_name),
2938 method(ObjectRef, get_look_dir),
2939 method(ObjectRef, get_look_pitch),
2940 method(ObjectRef, get_look_yaw),
2944 // Creates a new anonymous reference if cobj=NULL or id=0
2945 static void objectref_get_or_create(lua_State *L,
2946 ServerActiveObject *cobj)
2948 if(cobj == NULL || cobj->getId() == 0){
2949 ObjectRef::create(L, cobj);
2951 objectref_get(L, cobj->getId());
2960 class LuaPerlinNoise
2967 static const char className[];
2968 static const luaL_reg methods[];
2970 // Exported functions
2972 // garbage collector
2973 static int gc_object(lua_State *L)
2975 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
2980 static int l_get2d(lua_State *L)
2982 LuaPerlinNoise *o = checkobject(L, 1);
2983 v2f pos2d = read_v2f(L,2);
2984 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
2985 lua_pushnumber(L, val);
2988 static int l_get3d(lua_State *L)
2990 LuaPerlinNoise *o = checkobject(L, 1);
2991 v3f pos3d = read_v3f(L,2);
2992 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
2993 lua_pushnumber(L, val);
2998 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3002 persistence(a_persistence),
3011 // LuaPerlinNoise(seed, octaves, persistence, scale)
3012 // Creates an LuaPerlinNoise and leaves it on top of stack
3013 static int create_object(lua_State *L)
3015 int seed = luaL_checkint(L, 1);
3016 int octaves = luaL_checkint(L, 2);
3017 double persistence = luaL_checknumber(L, 3);
3018 double scale = luaL_checknumber(L, 4);
3019 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3020 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3021 luaL_getmetatable(L, className);
3022 lua_setmetatable(L, -2);
3026 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3028 luaL_checktype(L, narg, LUA_TUSERDATA);
3029 void *ud = luaL_checkudata(L, narg, className);
3030 if(!ud) luaL_typerror(L, narg, className);
3031 return *(LuaPerlinNoise**)ud; // unbox pointer
3034 static void Register(lua_State *L)
3037 int methodtable = lua_gettop(L);
3038 luaL_newmetatable(L, className);
3039 int metatable = lua_gettop(L);
3041 lua_pushliteral(L, "__metatable");
3042 lua_pushvalue(L, methodtable);
3043 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3045 lua_pushliteral(L, "__index");
3046 lua_pushvalue(L, methodtable);
3047 lua_settable(L, metatable);
3049 lua_pushliteral(L, "__gc");
3050 lua_pushcfunction(L, gc_object);
3051 lua_settable(L, metatable);
3053 lua_pop(L, 1); // drop metatable
3055 luaL_openlib(L, 0, methods, 0); // fill methodtable
3056 lua_pop(L, 1); // drop methodtable
3058 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3059 lua_register(L, className, create_object);
3062 const char LuaPerlinNoise::className[] = "PerlinNoise";
3063 const luaL_reg LuaPerlinNoise::methods[] = {
3064 method(LuaPerlinNoise, get2d),
3065 method(LuaPerlinNoise, get3d),
3076 ServerEnvironment *m_env;
3078 static const char className[];
3079 static const luaL_reg methods[];
3081 static int gc_object(lua_State *L) {
3082 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3087 static EnvRef *checkobject(lua_State *L, int narg)
3089 luaL_checktype(L, narg, LUA_TUSERDATA);
3090 void *ud = luaL_checkudata(L, narg, className);
3091 if(!ud) luaL_typerror(L, narg, className);
3092 return *(EnvRef**)ud; // unbox pointer
3095 // Exported functions
3097 // EnvRef:set_node(pos, node)
3098 // pos = {x=num, y=num, z=num}
3099 static int l_set_node(lua_State *L)
3101 EnvRef *o = checkobject(L, 1);
3102 ServerEnvironment *env = o->m_env;
3103 if(env == NULL) return 0;
3104 INodeDefManager *ndef = env->getGameDef()->ndef();
3106 v3s16 pos = read_v3s16(L, 2);
3107 MapNode n = readnode(L, 3, ndef);
3109 MapNode n_old = env->getMap().getNodeNoEx(pos);
3111 if(ndef->get(n_old).has_on_destruct)
3112 scriptapi_node_on_destruct(L, pos, n_old);
3114 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3116 // Call post-destructor
3117 if(ndef->get(n_old).has_after_destruct)
3118 scriptapi_node_after_destruct(L, pos, n_old);
3120 if(ndef->get(n).has_on_construct)
3121 scriptapi_node_on_construct(L, pos, n);
3123 lua_pushboolean(L, succeeded);
3127 static int l_add_node(lua_State *L)
3129 return l_set_node(L);
3132 // EnvRef:remove_node(pos)
3133 // pos = {x=num, y=num, z=num}
3134 static int l_remove_node(lua_State *L)
3136 EnvRef *o = checkobject(L, 1);
3137 ServerEnvironment *env = o->m_env;
3138 if(env == NULL) return 0;
3139 INodeDefManager *ndef = env->getGameDef()->ndef();
3141 v3s16 pos = read_v3s16(L, 2);
3143 MapNode n_old = env->getMap().getNodeNoEx(pos);
3145 if(ndef->get(n_old).has_on_destruct)
3146 scriptapi_node_on_destruct(L, pos, n_old);
3148 // This is slightly optimized compared to addNodeWithEvent(air)
3149 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3151 // Call post-destructor
3152 if(ndef->get(n_old).has_after_destruct)
3153 scriptapi_node_after_destruct(L, pos, n_old);
3155 lua_pushboolean(L, succeeded);
3156 // Air doesn't require constructor
3160 // EnvRef:get_node(pos)
3161 // pos = {x=num, y=num, z=num}
3162 static int l_get_node(lua_State *L)
3164 EnvRef *o = checkobject(L, 1);
3165 ServerEnvironment *env = o->m_env;
3166 if(env == NULL) return 0;
3168 v3s16 pos = read_v3s16(L, 2);
3170 MapNode n = env->getMap().getNodeNoEx(pos);
3172 pushnode(L, n, env->getGameDef()->ndef());
3176 // EnvRef:get_node_or_nil(pos)
3177 // pos = {x=num, y=num, z=num}
3178 static int l_get_node_or_nil(lua_State *L)
3180 EnvRef *o = checkobject(L, 1);
3181 ServerEnvironment *env = o->m_env;
3182 if(env == NULL) return 0;
3184 v3s16 pos = read_v3s16(L, 2);
3187 MapNode n = env->getMap().getNode(pos);
3189 pushnode(L, n, env->getGameDef()->ndef());
3191 } catch(InvalidPositionException &e)
3198 // EnvRef:get_node_light(pos, timeofday)
3199 // pos = {x=num, y=num, z=num}
3200 // timeofday: nil = current time, 0 = night, 0.5 = day
3201 static int l_get_node_light(lua_State *L)
3203 EnvRef *o = checkobject(L, 1);
3204 ServerEnvironment *env = o->m_env;
3205 if(env == NULL) return 0;
3207 v3s16 pos = read_v3s16(L, 2);
3208 u32 time_of_day = env->getTimeOfDay();
3209 if(lua_isnumber(L, 3))
3210 time_of_day = 24000.0 * lua_tonumber(L, 3);
3211 time_of_day %= 24000;
3212 u32 dnr = time_to_daynight_ratio(time_of_day);
3213 MapNode n = env->getMap().getNodeNoEx(pos);
3215 MapNode n = env->getMap().getNode(pos);
3216 INodeDefManager *ndef = env->getGameDef()->ndef();
3217 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3219 } catch(InvalidPositionException &e)
3226 // EnvRef:place_node(pos, node)
3227 // pos = {x=num, y=num, z=num}
3228 static int l_place_node(lua_State *L)
3230 EnvRef *o = checkobject(L, 1);
3231 ServerEnvironment *env = o->m_env;
3232 if(env == NULL) return 0;
3233 v3s16 pos = read_v3s16(L, 2);
3234 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3236 // Don't attempt to load non-loaded area as of now
3237 MapNode n_old = env->getMap().getNodeNoEx(pos);
3238 if(n_old.getContent() == CONTENT_IGNORE){
3239 lua_pushboolean(L, false);
3242 // Create item to place
3243 INodeDefManager *ndef = get_server(L)->ndef();
3244 IItemDefManager *idef = get_server(L)->idef();
3245 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3246 // Make pointed position
3247 PointedThing pointed;
3248 pointed.type = POINTEDTHING_NODE;
3249 pointed.node_abovesurface = pos;
3250 pointed.node_undersurface = pos + v3s16(0,-1,0);
3251 // Place it with a NULL placer (appears in Lua as a non-functional
3253 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3254 lua_pushboolean(L, success);
3258 // EnvRef:dig_node(pos)
3259 // pos = {x=num, y=num, z=num}
3260 static int l_dig_node(lua_State *L)
3262 EnvRef *o = checkobject(L, 1);
3263 ServerEnvironment *env = o->m_env;
3264 if(env == NULL) return 0;
3265 v3s16 pos = read_v3s16(L, 2);
3267 // Don't attempt to load non-loaded area as of now
3268 MapNode n = env->getMap().getNodeNoEx(pos);
3269 if(n.getContent() == CONTENT_IGNORE){
3270 lua_pushboolean(L, false);
3273 // Dig it out with a NULL digger (appears in Lua as a
3274 // non-functional ObjectRef)
3275 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3276 lua_pushboolean(L, success);
3280 // EnvRef:punch_node(pos)
3281 // pos = {x=num, y=num, z=num}
3282 static int l_punch_node(lua_State *L)
3284 EnvRef *o = checkobject(L, 1);
3285 ServerEnvironment *env = o->m_env;
3286 if(env == NULL) return 0;
3287 v3s16 pos = read_v3s16(L, 2);
3289 // Don't attempt to load non-loaded area as of now
3290 MapNode n = env->getMap().getNodeNoEx(pos);
3291 if(n.getContent() == CONTENT_IGNORE){
3292 lua_pushboolean(L, false);
3295 // Punch it with a NULL puncher (appears in Lua as a non-functional
3297 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3298 lua_pushboolean(L, success);
3302 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3303 // pos = {x=num, y=num, z=num}
3304 static int l_add_entity(lua_State *L)
3306 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3307 EnvRef *o = checkobject(L, 1);
3308 ServerEnvironment *env = o->m_env;
3309 if(env == NULL) return 0;
3311 v3f pos = checkFloatPos(L, 2);
3313 const char *name = luaL_checkstring(L, 3);
3315 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3316 int objectid = env->addActiveObject(obj);
3317 // If failed to add, return nothing (reads as nil)
3321 objectref_get_or_create(L, obj);
3325 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3326 // pos = {x=num, y=num, z=num}
3327 static int l_add_item(lua_State *L)
3329 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3330 EnvRef *o = checkobject(L, 1);
3331 ServerEnvironment *env = o->m_env;
3332 if(env == NULL) return 0;
3334 v3f pos = checkFloatPos(L, 2);
3336 ItemStack item = read_item(L, 3);
3337 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3339 // Use minetest.spawn_item to spawn a __builtin:item
3340 lua_getglobal(L, "minetest");
3341 lua_getfield(L, -1, "spawn_item");
3342 if(lua_isnil(L, -1))
3344 lua_pushvalue(L, 2);
3345 lua_pushstring(L, item.getItemString().c_str());
3346 if(lua_pcall(L, 2, 1, 0))
3347 script_error(L, "error: %s", lua_tostring(L, -1));
3349 /*lua_pushvalue(L, 1);
3350 lua_pushstring(L, "__builtin:item");
3351 lua_pushstring(L, item.getItemString().c_str());
3352 return l_add_entity(L);*/
3354 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3355 int objectid = env->addActiveObject(obj);
3356 // If failed to add, return nothing (reads as nil)
3360 objectref_get_or_create(L, obj);
3364 // EnvRef:add_rat(pos)
3365 // pos = {x=num, y=num, z=num}
3366 static int l_add_rat(lua_State *L)
3368 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3369 <<" Doing nothing."<<std::endl;
3373 // EnvRef:add_firefly(pos)
3374 // pos = {x=num, y=num, z=num}
3375 static int l_add_firefly(lua_State *L)
3377 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3378 <<" Doing nothing."<<std::endl;
3382 // EnvRef:get_meta(pos)
3383 static int l_get_meta(lua_State *L)
3385 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3386 EnvRef *o = checkobject(L, 1);
3387 ServerEnvironment *env = o->m_env;
3388 if(env == NULL) return 0;
3390 v3s16 p = read_v3s16(L, 2);
3391 NodeMetaRef::create(L, p, env);
3395 // EnvRef:get_player_by_name(name)
3396 static int l_get_player_by_name(lua_State *L)
3398 EnvRef *o = checkobject(L, 1);
3399 ServerEnvironment *env = o->m_env;
3400 if(env == NULL) return 0;
3402 const char *name = luaL_checkstring(L, 2);
3403 Player *player = env->getPlayer(name);
3408 PlayerSAO *sao = player->getPlayerSAO();
3413 // Put player on stack
3414 objectref_get_or_create(L, sao);
3418 // EnvRef:get_objects_inside_radius(pos, radius)
3419 static int l_get_objects_inside_radius(lua_State *L)
3421 // Get the table insert function
3422 lua_getglobal(L, "table");
3423 lua_getfield(L, -1, "insert");
3424 int table_insert = lua_gettop(L);
3426 EnvRef *o = checkobject(L, 1);
3427 ServerEnvironment *env = o->m_env;
3428 if(env == NULL) return 0;
3430 v3f pos = checkFloatPos(L, 2);
3431 float radius = luaL_checknumber(L, 3) * BS;
3432 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3434 int table = lua_gettop(L);
3435 for(std::set<u16>::const_iterator
3436 i = ids.begin(); i != ids.end(); i++){
3437 ServerActiveObject *obj = env->getActiveObject(*i);
3438 // Insert object reference into table
3439 lua_pushvalue(L, table_insert);
3440 lua_pushvalue(L, table);
3441 objectref_get_or_create(L, obj);
3442 if(lua_pcall(L, 2, 0, 0))
3443 script_error(L, "error: %s", lua_tostring(L, -1));
3448 // EnvRef:set_timeofday(val)
3450 static int l_set_timeofday(lua_State *L)
3452 EnvRef *o = checkobject(L, 1);
3453 ServerEnvironment *env = o->m_env;
3454 if(env == NULL) return 0;
3456 float timeofday_f = luaL_checknumber(L, 2);
3457 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3458 int timeofday_mh = (int)(timeofday_f * 24000.0);
3459 // This should be set directly in the environment but currently
3460 // such changes aren't immediately sent to the clients, so call
3461 // the server instead.
3462 //env->setTimeOfDay(timeofday_mh);
3463 get_server(L)->setTimeOfDay(timeofday_mh);
3467 // EnvRef:get_timeofday() -> 0...1
3468 static int l_get_timeofday(lua_State *L)
3470 EnvRef *o = checkobject(L, 1);
3471 ServerEnvironment *env = o->m_env;
3472 if(env == NULL) return 0;
3474 int timeofday_mh = env->getTimeOfDay();
3475 float timeofday_f = (float)timeofday_mh / 24000.0;
3476 lua_pushnumber(L, timeofday_f);
3481 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3482 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3483 static int l_find_node_near(lua_State *L)
3485 EnvRef *o = checkobject(L, 1);
3486 ServerEnvironment *env = o->m_env;
3487 if(env == NULL) return 0;
3488 INodeDefManager *ndef = get_server(L)->ndef();
3489 v3s16 pos = read_v3s16(L, 2);
3490 int radius = luaL_checkinteger(L, 3);
3491 std::set<content_t> filter;
3492 if(lua_istable(L, 4)){
3495 while(lua_next(L, table) != 0){
3496 // key at index -2 and value at index -1
3497 luaL_checktype(L, -1, LUA_TSTRING);
3498 ndef->getIds(lua_tostring(L, -1), filter);
3499 // removes value, keeps key for next iteration
3502 } else if(lua_isstring(L, 4)){
3503 ndef->getIds(lua_tostring(L, 4), filter);
3506 for(int d=1; d<=radius; d++){
3507 core::list<v3s16> list;
3508 getFacePositions(list, d);
3509 for(core::list<v3s16>::Iterator i = list.begin();
3510 i != list.end(); i++){
3511 v3s16 p = pos + (*i);
3512 content_t c = env->getMap().getNodeNoEx(p).getContent();
3513 if(filter.count(c) != 0){
3522 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3523 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3524 static int l_find_nodes_in_area(lua_State *L)
3526 EnvRef *o = checkobject(L, 1);
3527 ServerEnvironment *env = o->m_env;
3528 if(env == NULL) return 0;
3529 INodeDefManager *ndef = get_server(L)->ndef();
3530 v3s16 minp = read_v3s16(L, 2);
3531 v3s16 maxp = read_v3s16(L, 3);
3532 std::set<content_t> filter;
3533 if(lua_istable(L, 4)){
3536 while(lua_next(L, table) != 0){
3537 // key at index -2 and value at index -1
3538 luaL_checktype(L, -1, LUA_TSTRING);
3539 ndef->getIds(lua_tostring(L, -1), filter);
3540 // removes value, keeps key for next iteration
3543 } else if(lua_isstring(L, 4)){
3544 ndef->getIds(lua_tostring(L, 4), filter);
3547 // Get the table insert function
3548 lua_getglobal(L, "table");
3549 lua_getfield(L, -1, "insert");
3550 int table_insert = lua_gettop(L);
3553 int table = lua_gettop(L);
3554 for(s16 x=minp.X; x<=maxp.X; x++)
3555 for(s16 y=minp.Y; y<=maxp.Y; y++)
3556 for(s16 z=minp.Z; z<=maxp.Z; z++)
3559 content_t c = env->getMap().getNodeNoEx(p).getContent();
3560 if(filter.count(c) != 0){
3561 lua_pushvalue(L, table_insert);
3562 lua_pushvalue(L, table);
3564 if(lua_pcall(L, 2, 0, 0))
3565 script_error(L, "error: %s", lua_tostring(L, -1));
3571 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3572 // returns world-specific PerlinNoise
3573 static int l_get_perlin(lua_State *L)
3575 EnvRef *o = checkobject(L, 1);
3576 ServerEnvironment *env = o->m_env;
3577 if(env == NULL) return 0;
3579 int seeddiff = luaL_checkint(L, 2);
3580 int octaves = luaL_checkint(L, 3);
3581 double persistence = luaL_checknumber(L, 4);
3582 double scale = luaL_checknumber(L, 5);
3584 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3585 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3586 luaL_getmetatable(L, "PerlinNoise");
3587 lua_setmetatable(L, -2);
3592 EnvRef(ServerEnvironment *env):
3595 //infostream<<"EnvRef created"<<std::endl;
3600 //infostream<<"EnvRef destructing"<<std::endl;
3603 // Creates an EnvRef and leaves it on top of stack
3604 // Not callable from Lua; all references are created on the C side.
3605 static void create(lua_State *L, ServerEnvironment *env)
3607 EnvRef *o = new EnvRef(env);
3608 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3609 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3610 luaL_getmetatable(L, className);
3611 lua_setmetatable(L, -2);
3614 static void set_null(lua_State *L)
3616 EnvRef *o = checkobject(L, -1);
3620 static void Register(lua_State *L)
3623 int methodtable = lua_gettop(L);
3624 luaL_newmetatable(L, className);
3625 int metatable = lua_gettop(L);
3627 lua_pushliteral(L, "__metatable");
3628 lua_pushvalue(L, methodtable);
3629 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3631 lua_pushliteral(L, "__index");
3632 lua_pushvalue(L, methodtable);
3633 lua_settable(L, metatable);
3635 lua_pushliteral(L, "__gc");
3636 lua_pushcfunction(L, gc_object);
3637 lua_settable(L, metatable);
3639 lua_pop(L, 1); // drop metatable
3641 luaL_openlib(L, 0, methods, 0); // fill methodtable
3642 lua_pop(L, 1); // drop methodtable
3644 // Cannot be created from Lua
3645 //lua_register(L, className, create_object);
3648 const char EnvRef::className[] = "EnvRef";
3649 const luaL_reg EnvRef::methods[] = {
3650 method(EnvRef, set_node),
3651 method(EnvRef, add_node),
3652 method(EnvRef, remove_node),
3653 method(EnvRef, get_node),
3654 method(EnvRef, get_node_or_nil),
3655 method(EnvRef, get_node_light),
3656 method(EnvRef, place_node),
3657 method(EnvRef, dig_node),
3658 method(EnvRef, punch_node),
3659 method(EnvRef, add_entity),
3660 method(EnvRef, add_item),
3661 method(EnvRef, add_rat),
3662 method(EnvRef, add_firefly),
3663 method(EnvRef, get_meta),
3664 method(EnvRef, get_player_by_name),
3665 method(EnvRef, get_objects_inside_radius),
3666 method(EnvRef, set_timeofday),
3667 method(EnvRef, get_timeofday),
3668 method(EnvRef, find_node_near),
3669 method(EnvRef, find_nodes_in_area),
3670 method(EnvRef, get_perlin),
3679 class LuaPseudoRandom
3682 PseudoRandom m_pseudo;
3684 static const char className[];
3685 static const luaL_reg methods[];
3687 // Exported functions
3689 // garbage collector
3690 static int gc_object(lua_State *L)
3692 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3697 // next(self, min=0, max=32767) -> get next value
3698 static int l_next(lua_State *L)
3700 LuaPseudoRandom *o = checkobject(L, 1);
3703 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3704 if(!lua_isnil(L, 2))
3705 min = luaL_checkinteger(L, 2);
3706 if(!lua_isnil(L, 3))
3707 max = luaL_checkinteger(L, 3);
3708 if(max - min != 32767 && max - min > 32767/5)
3709 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.");
3710 PseudoRandom &pseudo = o->m_pseudo;
3711 int val = pseudo.next();
3712 val = (val % (max-min+1)) + min;
3713 lua_pushinteger(L, val);
3718 LuaPseudoRandom(int seed):
3727 const PseudoRandom& getItem() const
3731 PseudoRandom& getItem()
3736 // LuaPseudoRandom(seed)
3737 // Creates an LuaPseudoRandom and leaves it on top of stack
3738 static int create_object(lua_State *L)
3740 int seed = luaL_checknumber(L, 1);
3741 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3742 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3743 luaL_getmetatable(L, className);
3744 lua_setmetatable(L, -2);
3748 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3750 luaL_checktype(L, narg, LUA_TUSERDATA);
3751 void *ud = luaL_checkudata(L, narg, className);
3752 if(!ud) luaL_typerror(L, narg, className);
3753 return *(LuaPseudoRandom**)ud; // unbox pointer
3756 static void Register(lua_State *L)
3759 int methodtable = lua_gettop(L);
3760 luaL_newmetatable(L, className);
3761 int metatable = lua_gettop(L);
3763 lua_pushliteral(L, "__metatable");
3764 lua_pushvalue(L, methodtable);
3765 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3767 lua_pushliteral(L, "__index");
3768 lua_pushvalue(L, methodtable);
3769 lua_settable(L, metatable);
3771 lua_pushliteral(L, "__gc");
3772 lua_pushcfunction(L, gc_object);
3773 lua_settable(L, metatable);
3775 lua_pop(L, 1); // drop metatable
3777 luaL_openlib(L, 0, methods, 0); // fill methodtable
3778 lua_pop(L, 1); // drop methodtable
3780 // Can be created from Lua (LuaPseudoRandom(seed))
3781 lua_register(L, className, create_object);
3784 const char LuaPseudoRandom::className[] = "PseudoRandom";
3785 const luaL_reg LuaPseudoRandom::methods[] = {
3786 method(LuaPseudoRandom, next),
3796 class LuaABM : public ActiveBlockModifier
3802 std::set<std::string> m_trigger_contents;
3803 std::set<std::string> m_required_neighbors;
3804 float m_trigger_interval;
3805 u32 m_trigger_chance;
3807 LuaABM(lua_State *L, int id,
3808 const std::set<std::string> &trigger_contents,
3809 const std::set<std::string> &required_neighbors,
3810 float trigger_interval, u32 trigger_chance):
3813 m_trigger_contents(trigger_contents),
3814 m_required_neighbors(required_neighbors),
3815 m_trigger_interval(trigger_interval),
3816 m_trigger_chance(trigger_chance)
3819 virtual std::set<std::string> getTriggerContents()
3821 return m_trigger_contents;
3823 virtual std::set<std::string> getRequiredNeighbors()
3825 return m_required_neighbors;
3827 virtual float getTriggerInterval()
3829 return m_trigger_interval;
3831 virtual u32 getTriggerChance()
3833 return m_trigger_chance;
3835 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3836 u32 active_object_count, u32 active_object_count_wider)
3838 lua_State *L = m_lua;
3841 assert(lua_checkstack(L, 20));
3842 StackUnroller stack_unroller(L);
3844 // Get minetest.registered_abms
3845 lua_getglobal(L, "minetest");
3846 lua_getfield(L, -1, "registered_abms");
3847 luaL_checktype(L, -1, LUA_TTABLE);
3848 int registered_abms = lua_gettop(L);
3850 // Get minetest.registered_abms[m_id]
3851 lua_pushnumber(L, m_id);
3852 lua_gettable(L, registered_abms);
3853 if(lua_isnil(L, -1))
3857 luaL_checktype(L, -1, LUA_TTABLE);
3858 lua_getfield(L, -1, "action");
3859 luaL_checktype(L, -1, LUA_TFUNCTION);
3861 pushnode(L, n, env->getGameDef()->ndef());
3862 lua_pushnumber(L, active_object_count);
3863 lua_pushnumber(L, active_object_count_wider);
3864 if(lua_pcall(L, 4, 0, 0))
3865 script_error(L, "error: %s", lua_tostring(L, -1));
3873 static void read_server_sound_params(lua_State *L, int index,
3874 ServerSoundParams ¶ms)
3877 index = lua_gettop(L) + 1 + index;
3879 params = ServerSoundParams();
3880 if(lua_istable(L, index)){
3881 getfloatfield(L, index, "gain", params.gain);
3882 getstringfield(L, index, "to_player", params.to_player);
3883 lua_getfield(L, index, "pos");
3884 if(!lua_isnil(L, -1)){
3885 v3f p = read_v3f(L, -1)*BS;
3887 params.type = ServerSoundParams::SSP_POSITIONAL;
3890 lua_getfield(L, index, "object");
3891 if(!lua_isnil(L, -1)){
3892 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3893 ServerActiveObject *sao = ObjectRef::getobject(ref);
3895 params.object = sao->getId();
3896 params.type = ServerSoundParams::SSP_OBJECT;
3900 params.max_hear_distance = BS*getfloatfield_default(L, index,
3901 "max_hear_distance", params.max_hear_distance/BS);
3902 getboolfield(L, index, "loop", params.loop);
3911 // Writes a line to dstream
3912 static int l_debug(lua_State *L)
3914 std::string text = lua_tostring(L, 1);
3915 dstream << text << std::endl;
3919 // log([level,] text)
3920 // Writes a line to the logger.
3921 // The one-argument version logs to infostream.
3922 // The two-argument version accept a log level: error, action, info, or verbose.
3923 static int l_log(lua_State *L)
3926 LogMessageLevel level = LMT_INFO;
3927 if(lua_isnone(L, 2))
3929 text = lua_tostring(L, 1);
3933 std::string levelname = lua_tostring(L, 1);
3934 text = lua_tostring(L, 2);
3935 if(levelname == "error")
3937 else if(levelname == "action")
3939 else if(levelname == "verbose")
3940 level = LMT_VERBOSE;
3942 log_printline(level, text);
3946 // register_item_raw({lots of stuff})
3947 static int l_register_item_raw(lua_State *L)
3949 luaL_checktype(L, 1, LUA_TTABLE);
3952 // Get the writable item and node definition managers from the server
3953 IWritableItemDefManager *idef =
3954 get_server(L)->getWritableItemDefManager();
3955 IWritableNodeDefManager *ndef =
3956 get_server(L)->getWritableNodeDefManager();
3958 // Check if name is defined
3960 lua_getfield(L, table, "name");
3961 if(lua_isstring(L, -1)){
3962 name = lua_tostring(L, -1);
3963 verbosestream<<"register_item_raw: "<<name<<std::endl;
3965 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3968 // Check if on_use is defined
3971 // Set a distinctive default value to check if this is set
3972 def.node_placement_prediction = "__default";
3974 // Read the item definition
3975 def = read_item_definition(L, table, def);
3977 // Default to having client-side placement prediction for nodes
3978 // ("" in item definition sets it off)
3979 if(def.node_placement_prediction == "__default"){
3980 if(def.type == ITEM_NODE)
3981 def.node_placement_prediction = name;
3983 def.node_placement_prediction = "";
3986 // Register item definition
3987 idef->registerItem(def);
3989 // Read the node definition (content features) and register it
3990 if(def.type == ITEM_NODE)
3992 ContentFeatures f = read_content_features(L, table);
3993 ndef->set(f.name, f);
3996 return 0; /* number of results */
3999 // register_alias_raw(name, convert_to_name)
4000 static int l_register_alias_raw(lua_State *L)
4002 std::string name = luaL_checkstring(L, 1);
4003 std::string convert_to = luaL_checkstring(L, 2);
4005 // Get the writable item definition manager from the server
4006 IWritableItemDefManager *idef =
4007 get_server(L)->getWritableItemDefManager();
4009 idef->registerAlias(name, convert_to);
4011 return 0; /* number of results */
4014 // helper for register_craft
4015 static bool read_craft_recipe_shaped(lua_State *L, int index,
4016 int &width, std::vector<std::string> &recipe)
4019 index = lua_gettop(L) + 1 + index;
4021 if(!lua_istable(L, index))
4026 while(lua_next(L, index) != 0){
4028 // key at index -2 and value at index -1
4029 if(!lua_istable(L, -1))
4031 int table2 = lua_gettop(L);
4033 while(lua_next(L, table2) != 0){
4034 // key at index -2 and value at index -1
4035 if(!lua_isstring(L, -1))
4037 recipe.push_back(lua_tostring(L, -1));
4038 // removes value, keeps key for next iteration
4045 if(colcount != width)
4048 // removes value, keeps key for next iteration
4055 // helper for register_craft
4056 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4057 std::vector<std::string> &recipe)
4060 index = lua_gettop(L) + 1 + index;
4062 if(!lua_istable(L, index))
4066 while(lua_next(L, index) != 0){
4067 // key at index -2 and value at index -1
4068 if(!lua_isstring(L, -1))
4070 recipe.push_back(lua_tostring(L, -1));
4071 // removes value, keeps key for next iteration
4077 // helper for register_craft
4078 static bool read_craft_replacements(lua_State *L, int index,
4079 CraftReplacements &replacements)
4082 index = lua_gettop(L) + 1 + index;
4084 if(!lua_istable(L, index))
4088 while(lua_next(L, index) != 0){
4089 // key at index -2 and value at index -1
4090 if(!lua_istable(L, -1))
4092 lua_rawgeti(L, -1, 1);
4093 if(!lua_isstring(L, -1))
4095 std::string replace_from = lua_tostring(L, -1);
4097 lua_rawgeti(L, -1, 2);
4098 if(!lua_isstring(L, -1))
4100 std::string replace_to = lua_tostring(L, -1);
4102 replacements.pairs.push_back(
4103 std::make_pair(replace_from, replace_to));
4104 // removes value, keeps key for next iteration
4109 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4110 static int l_register_craft(lua_State *L)
4112 //infostream<<"register_craft"<<std::endl;
4113 luaL_checktype(L, 1, LUA_TTABLE);
4116 // Get the writable craft definition manager from the server
4117 IWritableCraftDefManager *craftdef =
4118 get_server(L)->getWritableCraftDefManager();
4120 std::string type = getstringfield_default(L, table, "type", "shaped");
4123 CraftDefinitionShaped
4125 if(type == "shaped"){
4126 std::string output = getstringfield_default(L, table, "output", "");
4128 throw LuaError(L, "Crafting definition is missing an output");
4131 std::vector<std::string> recipe;
4132 lua_getfield(L, table, "recipe");
4133 if(lua_isnil(L, -1))
4134 throw LuaError(L, "Crafting definition is missing a recipe"
4135 " (output=\"" + output + "\")");
4136 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4137 throw LuaError(L, "Invalid crafting recipe"
4138 " (output=\"" + output + "\")");
4140 CraftReplacements replacements;
4141 lua_getfield(L, table, "replacements");
4142 if(!lua_isnil(L, -1))
4144 if(!read_craft_replacements(L, -1, replacements))
4145 throw LuaError(L, "Invalid replacements"
4146 " (output=\"" + output + "\")");
4149 CraftDefinition *def = new CraftDefinitionShaped(
4150 output, width, recipe, replacements);
4151 craftdef->registerCraft(def);
4154 CraftDefinitionShapeless
4156 else if(type == "shapeless"){
4157 std::string output = getstringfield_default(L, table, "output", "");
4159 throw LuaError(L, "Crafting definition (shapeless)"
4160 " is missing an output");
4162 std::vector<std::string> recipe;
4163 lua_getfield(L, table, "recipe");
4164 if(lua_isnil(L, -1))
4165 throw LuaError(L, "Crafting definition (shapeless)"
4166 " is missing a recipe"
4167 " (output=\"" + output + "\")");
4168 if(!read_craft_recipe_shapeless(L, -1, recipe))
4169 throw LuaError(L, "Invalid crafting recipe"
4170 " (output=\"" + output + "\")");
4172 CraftReplacements replacements;
4173 lua_getfield(L, table, "replacements");
4174 if(!lua_isnil(L, -1))
4176 if(!read_craft_replacements(L, -1, replacements))
4177 throw LuaError(L, "Invalid replacements"
4178 " (output=\"" + output + "\")");
4181 CraftDefinition *def = new CraftDefinitionShapeless(
4182 output, recipe, replacements);
4183 craftdef->registerCraft(def);
4186 CraftDefinitionToolRepair
4188 else if(type == "toolrepair"){
4189 float additional_wear = getfloatfield_default(L, table,
4190 "additional_wear", 0.0);
4192 CraftDefinition *def = new CraftDefinitionToolRepair(
4194 craftdef->registerCraft(def);
4197 CraftDefinitionCooking
4199 else if(type == "cooking"){
4200 std::string output = getstringfield_default(L, table, "output", "");
4202 throw LuaError(L, "Crafting definition (cooking)"
4203 " is missing an output");
4205 std::string recipe = getstringfield_default(L, table, "recipe", "");
4207 throw LuaError(L, "Crafting definition (cooking)"
4208 " is missing a recipe"
4209 " (output=\"" + output + "\")");
4211 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4213 CraftReplacements replacements;
4214 lua_getfield(L, table, "replacements");
4215 if(!lua_isnil(L, -1))
4217 if(!read_craft_replacements(L, -1, replacements))
4218 throw LuaError(L, "Invalid replacements"
4219 " (cooking output=\"" + output + "\")");
4222 CraftDefinition *def = new CraftDefinitionCooking(
4223 output, recipe, cooktime, replacements);
4224 craftdef->registerCraft(def);
4229 else if(type == "fuel"){
4230 std::string recipe = getstringfield_default(L, table, "recipe", "");
4232 throw LuaError(L, "Crafting definition (fuel)"
4233 " is missing a recipe");
4235 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4237 CraftReplacements replacements;
4238 lua_getfield(L, table, "replacements");
4239 if(!lua_isnil(L, -1))
4241 if(!read_craft_replacements(L, -1, replacements))
4242 throw LuaError(L, "Invalid replacements"
4243 " (fuel recipe=\"" + recipe + "\")");
4246 CraftDefinition *def = new CraftDefinitionFuel(
4247 recipe, burntime, replacements);
4248 craftdef->registerCraft(def);
4252 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4256 return 0; /* number of results */
4259 // setting_set(name, value)
4260 static int l_setting_set(lua_State *L)
4262 const char *name = luaL_checkstring(L, 1);
4263 const char *value = luaL_checkstring(L, 2);
4264 g_settings->set(name, value);
4268 // setting_get(name)
4269 static int l_setting_get(lua_State *L)
4271 const char *name = luaL_checkstring(L, 1);
4273 std::string value = g_settings->get(name);
4274 lua_pushstring(L, value.c_str());
4275 } catch(SettingNotFoundException &e){
4281 // setting_getbool(name)
4282 static int l_setting_getbool(lua_State *L)
4284 const char *name = luaL_checkstring(L, 1);
4286 bool value = g_settings->getBool(name);
4287 lua_pushboolean(L, value);
4288 } catch(SettingNotFoundException &e){
4294 // chat_send_all(text)
4295 static int l_chat_send_all(lua_State *L)
4297 const char *text = luaL_checkstring(L, 1);
4298 // Get server from registry
4299 Server *server = get_server(L);
4301 server->notifyPlayers(narrow_to_wide(text));
4305 // chat_send_player(name, text)
4306 static int l_chat_send_player(lua_State *L)
4308 const char *name = luaL_checkstring(L, 1);
4309 const char *text = luaL_checkstring(L, 2);
4310 // Get server from registry
4311 Server *server = get_server(L);
4313 server->notifyPlayer(name, narrow_to_wide(text));
4317 // get_player_privs(name, text)
4318 static int l_get_player_privs(lua_State *L)
4320 const char *name = luaL_checkstring(L, 1);
4321 // Get server from registry
4322 Server *server = get_server(L);
4325 int table = lua_gettop(L);
4326 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4327 for(std::set<std::string>::const_iterator
4328 i = privs_s.begin(); i != privs_s.end(); i++){
4329 lua_pushboolean(L, true);
4330 lua_setfield(L, table, i->c_str());
4332 lua_pushvalue(L, table);
4336 // get_inventory(location)
4337 static int l_get_inventory(lua_State *L)
4339 InventoryLocation loc;
4341 std::string type = checkstringfield(L, 1, "type");
4342 if(type == "player"){
4343 std::string name = checkstringfield(L, 1, "name");
4344 loc.setPlayer(name);
4345 } else if(type == "node"){
4346 lua_getfield(L, 1, "pos");
4347 v3s16 pos = check_v3s16(L, -1);
4348 loc.setNodeMeta(pos);
4351 if(get_server(L)->getInventory(loc) != NULL)
4352 InvRef::create(L, loc);
4358 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4359 static int l_get_dig_params(lua_State *L)
4361 std::map<std::string, int> groups;
4362 read_groups(L, 1, groups);
4363 ToolCapabilities tp = read_tool_capabilities(L, 2);
4364 if(lua_isnoneornil(L, 3))
4365 push_dig_params(L, getDigParams(groups, &tp));
4367 push_dig_params(L, getDigParams(groups, &tp,
4368 luaL_checknumber(L, 3)));
4372 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4373 static int l_get_hit_params(lua_State *L)
4375 std::map<std::string, int> groups;
4376 read_groups(L, 1, groups);
4377 ToolCapabilities tp = read_tool_capabilities(L, 2);
4378 if(lua_isnoneornil(L, 3))
4379 push_hit_params(L, getHitParams(groups, &tp));
4381 push_hit_params(L, getHitParams(groups, &tp,
4382 luaL_checknumber(L, 3)));
4386 // get_current_modname()
4387 static int l_get_current_modname(lua_State *L)
4389 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4393 // get_modpath(modname)
4394 static int l_get_modpath(lua_State *L)
4396 std::string modname = luaL_checkstring(L, 1);
4398 if(modname == "__builtin"){
4399 std::string path = get_server(L)->getBuiltinLuaPath();
4400 lua_pushstring(L, path.c_str());
4403 const ModSpec *mod = get_server(L)->getModSpec(modname);
4408 lua_pushstring(L, mod->path.c_str());
4413 static int l_get_worldpath(lua_State *L)
4415 std::string worldpath = get_server(L)->getWorldPath();
4416 lua_pushstring(L, worldpath.c_str());
4420 // sound_play(spec, parameters)
4421 static int l_sound_play(lua_State *L)
4423 SimpleSoundSpec spec;
4424 read_soundspec(L, 1, spec);
4425 ServerSoundParams params;
4426 read_server_sound_params(L, 2, params);
4427 s32 handle = get_server(L)->playSound(spec, params);
4428 lua_pushinteger(L, handle);
4432 // sound_stop(handle)
4433 static int l_sound_stop(lua_State *L)
4435 int handle = luaL_checkinteger(L, 1);
4436 get_server(L)->stopSound(handle);
4440 // is_singleplayer()
4441 static int l_is_singleplayer(lua_State *L)
4443 lua_pushboolean(L, get_server(L)->isSingleplayer());
4447 // get_password_hash(name, raw_password)
4448 static int l_get_password_hash(lua_State *L)
4450 std::string name = luaL_checkstring(L, 1);
4451 std::string raw_password = luaL_checkstring(L, 2);
4452 std::string hash = translatePassword(name,
4453 narrow_to_wide(raw_password));
4454 lua_pushstring(L, hash.c_str());
4458 // notify_authentication_modified(name)
4459 static int l_notify_authentication_modified(lua_State *L)
4461 std::string name = "";
4462 if(lua_isstring(L, 1))
4463 name = lua_tostring(L, 1);
4464 get_server(L)->reportPrivsModified(name);
4468 // get_craft_result(input)
4469 static int l_get_craft_result(lua_State *L)
4472 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4473 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4474 es_CraftMethod, CRAFT_METHOD_NORMAL);
4476 lua_getfield(L, input_i, "width");
4477 if(lua_isnumber(L, -1))
4478 width = luaL_checkinteger(L, -1);
4480 lua_getfield(L, input_i, "items");
4481 std::vector<ItemStack> items = read_items(L, -1);
4482 lua_pop(L, 1); // items
4484 IGameDef *gdef = get_server(L);
4485 ICraftDefManager *cdef = gdef->cdef();
4486 CraftInput input(method, width, items);
4488 bool got = cdef->getCraftResult(input, output, true, gdef);
4489 lua_newtable(L); // output table
4492 item.deSerialize(output.item, gdef->idef());
4493 LuaItemStack::create(L, item);
4494 lua_setfield(L, -2, "item");
4495 setintfield(L, -1, "time", output.time);
4497 LuaItemStack::create(L, ItemStack());
4498 lua_setfield(L, -2, "item");
4499 setintfield(L, -1, "time", 0);
4501 lua_newtable(L); // decremented input table
4502 lua_pushstring(L, method_s.c_str());
4503 lua_setfield(L, -2, "method");
4504 lua_pushinteger(L, width);
4505 lua_setfield(L, -2, "width");
4506 push_items(L, input.items);
4507 lua_setfield(L, -2, "items");
4511 static const struct luaL_Reg minetest_f [] = {
4514 {"register_item_raw", l_register_item_raw},
4515 {"register_alias_raw", l_register_alias_raw},
4516 {"register_craft", l_register_craft},
4517 {"setting_set", l_setting_set},
4518 {"setting_get", l_setting_get},
4519 {"setting_getbool", l_setting_getbool},
4520 {"chat_send_all", l_chat_send_all},
4521 {"chat_send_player", l_chat_send_player},
4522 {"get_player_privs", l_get_player_privs},
4523 {"get_inventory", l_get_inventory},
4524 {"get_dig_params", l_get_dig_params},
4525 {"get_hit_params", l_get_hit_params},
4526 {"get_current_modname", l_get_current_modname},
4527 {"get_modpath", l_get_modpath},
4528 {"get_worldpath", l_get_worldpath},
4529 {"sound_play", l_sound_play},
4530 {"sound_stop", l_sound_stop},
4531 {"is_singleplayer", l_is_singleplayer},
4532 {"get_password_hash", l_get_password_hash},
4533 {"notify_authentication_modified", l_notify_authentication_modified},
4534 {"get_craft_result", l_get_craft_result},
4539 Main export function
4542 void scriptapi_export(lua_State *L, Server *server)
4545 assert(lua_checkstack(L, 20));
4546 verbosestream<<"scriptapi_export()"<<std::endl;
4547 StackUnroller stack_unroller(L);
4549 // Store server as light userdata in registry
4550 lua_pushlightuserdata(L, server);
4551 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4553 // Register global functions in table minetest
4555 luaL_register(L, NULL, minetest_f);
4556 lua_setglobal(L, "minetest");
4558 // Get the main minetest table
4559 lua_getglobal(L, "minetest");
4561 // Add tables to minetest
4563 lua_setfield(L, -2, "object_refs");
4565 lua_setfield(L, -2, "luaentities");
4567 // Register wrappers
4568 LuaItemStack::Register(L);
4569 InvRef::Register(L);
4570 NodeMetaRef::Register(L);
4571 ObjectRef::Register(L);
4572 EnvRef::Register(L);
4573 LuaPseudoRandom::Register(L);
4574 LuaPerlinNoise::Register(L);
4577 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4578 const std::string &modname)
4580 ModNameStorer modnamestorer(L, modname);
4582 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4584 errorstream<<"Error loading mod \""<<modname
4585 <<"\": modname does not follow naming conventions: "
4586 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4590 bool success = false;
4593 success = script_load(L, scriptpath.c_str());
4596 errorstream<<"Error loading mod \""<<modname
4597 <<"\": "<<e.what()<<std::endl;
4603 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4606 assert(lua_checkstack(L, 20));
4607 verbosestream<<"scriptapi_add_environment"<<std::endl;
4608 StackUnroller stack_unroller(L);
4610 // Create EnvRef on stack
4611 EnvRef::create(L, env);
4612 int envref = lua_gettop(L);
4614 // minetest.env = envref
4615 lua_getglobal(L, "minetest");
4616 luaL_checktype(L, -1, LUA_TTABLE);
4617 lua_pushvalue(L, envref);
4618 lua_setfield(L, -2, "env");
4620 // Store environment as light userdata in registry
4621 lua_pushlightuserdata(L, env);
4622 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4625 Add ActiveBlockModifiers to environment
4628 // Get minetest.registered_abms
4629 lua_getglobal(L, "minetest");
4630 lua_getfield(L, -1, "registered_abms");
4631 luaL_checktype(L, -1, LUA_TTABLE);
4632 int registered_abms = lua_gettop(L);
4634 if(lua_istable(L, registered_abms)){
4635 int table = lua_gettop(L);
4637 while(lua_next(L, table) != 0){
4638 // key at index -2 and value at index -1
4639 int id = lua_tonumber(L, -2);
4640 int current_abm = lua_gettop(L);
4642 std::set<std::string> trigger_contents;
4643 lua_getfield(L, current_abm, "nodenames");
4644 if(lua_istable(L, -1)){
4645 int table = lua_gettop(L);
4647 while(lua_next(L, table) != 0){
4648 // key at index -2 and value at index -1
4649 luaL_checktype(L, -1, LUA_TSTRING);
4650 trigger_contents.insert(lua_tostring(L, -1));
4651 // removes value, keeps key for next iteration
4654 } else if(lua_isstring(L, -1)){
4655 trigger_contents.insert(lua_tostring(L, -1));
4659 std::set<std::string> required_neighbors;
4660 lua_getfield(L, current_abm, "neighbors");
4661 if(lua_istable(L, -1)){
4662 int table = lua_gettop(L);
4664 while(lua_next(L, table) != 0){
4665 // key at index -2 and value at index -1
4666 luaL_checktype(L, -1, LUA_TSTRING);
4667 required_neighbors.insert(lua_tostring(L, -1));
4668 // removes value, keeps key for next iteration
4671 } else if(lua_isstring(L, -1)){
4672 required_neighbors.insert(lua_tostring(L, -1));
4676 float trigger_interval = 10.0;
4677 getfloatfield(L, current_abm, "interval", trigger_interval);
4679 int trigger_chance = 50;
4680 getintfield(L, current_abm, "chance", trigger_chance);
4682 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4683 required_neighbors, trigger_interval, trigger_chance);
4685 env->addActiveBlockModifier(abm);
4687 // removes value, keeps key for next iteration
4695 // Dump stack top with the dump2 function
4696 static void dump2(lua_State *L, const char *name)
4698 // Dump object (debug)
4699 lua_getglobal(L, "dump2");
4700 luaL_checktype(L, -1, LUA_TFUNCTION);
4701 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4702 lua_pushstring(L, name);
4703 if(lua_pcall(L, 2, 0, 0))
4704 script_error(L, "error: %s", lua_tostring(L, -1));
4712 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4715 assert(lua_checkstack(L, 20));
4716 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4717 StackUnroller stack_unroller(L);
4719 // Create object on stack
4720 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4721 int object = lua_gettop(L);
4723 // Get minetest.object_refs table
4724 lua_getglobal(L, "minetest");
4725 lua_getfield(L, -1, "object_refs");
4726 luaL_checktype(L, -1, LUA_TTABLE);
4727 int objectstable = lua_gettop(L);
4729 // object_refs[id] = object
4730 lua_pushnumber(L, cobj->getId()); // Push id
4731 lua_pushvalue(L, object); // Copy object to top of stack
4732 lua_settable(L, objectstable);
4735 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4738 assert(lua_checkstack(L, 20));
4739 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4740 StackUnroller stack_unroller(L);
4742 // Get minetest.object_refs table
4743 lua_getglobal(L, "minetest");
4744 lua_getfield(L, -1, "object_refs");
4745 luaL_checktype(L, -1, LUA_TTABLE);
4746 int objectstable = lua_gettop(L);
4748 // Get object_refs[id]
4749 lua_pushnumber(L, cobj->getId()); // Push id
4750 lua_gettable(L, objectstable);
4751 // Set object reference to NULL
4752 ObjectRef::set_null(L);
4753 lua_pop(L, 1); // pop object
4755 // Set object_refs[id] = nil
4756 lua_pushnumber(L, cobj->getId()); // Push id
4758 lua_settable(L, objectstable);
4765 // What scriptapi_run_callbacks does with the return values of callbacks.
4766 // Regardless of the mode, if only one callback is defined,
4767 // its return value is the total return value.
4768 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4769 enum RunCallbacksMode
4771 // Returns the return value of the first callback
4772 // Returns nil if list of callbacks is empty
4773 RUN_CALLBACKS_MODE_FIRST,
4774 // Returns the return value of the last callback
4775 // Returns nil if list of callbacks is empty
4776 RUN_CALLBACKS_MODE_LAST,
4777 // If any callback returns a false value, the first such is returned
4778 // Otherwise, the first callback's return value (trueish) is returned
4779 // Returns true if list of callbacks is empty
4780 RUN_CALLBACKS_MODE_AND,
4781 // Like above, but stops calling callbacks (short circuit)
4782 // after seeing the first false value
4783 RUN_CALLBACKS_MODE_AND_SC,
4784 // If any callback returns a true value, the first such is returned
4785 // Otherwise, the first callback's return value (falseish) is returned
4786 // Returns false if list of callbacks is empty
4787 RUN_CALLBACKS_MODE_OR,
4788 // Like above, but stops calling callbacks (short circuit)
4789 // after seeing the first true value
4790 RUN_CALLBACKS_MODE_OR_SC,
4791 // Note: "a true value" and "a false value" refer to values that
4792 // are converted by lua_toboolean to true or false, respectively.
4795 // Push the list of callbacks (a lua table).
4796 // Then push nargs arguments.
4797 // Then call this function, which
4798 // - runs the callbacks
4799 // - removes the table and arguments from the lua stack
4800 // - pushes the return value, computed depending on mode
4801 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4802 RunCallbacksMode mode)
4804 // Insert the return value into the lua stack, below the table
4805 assert(lua_gettop(L) >= nargs + 1);
4807 lua_insert(L, -(nargs + 1) - 1);
4808 // Stack now looks like this:
4809 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4811 int rv = lua_gettop(L) - nargs - 1;
4813 int arg = table + 1;
4815 luaL_checktype(L, table, LUA_TTABLE);
4819 bool first_loop = true;
4820 while(lua_next(L, table) != 0){
4821 // key at index -2 and value at index -1
4822 luaL_checktype(L, -1, LUA_TFUNCTION);
4824 for(int i = 0; i < nargs; i++)
4825 lua_pushvalue(L, arg+i);
4826 if(lua_pcall(L, nargs, 1, 0))
4827 script_error(L, "error: %s", lua_tostring(L, -1));
4829 // Move return value to designated space in stack
4832 // Result of first callback is always moved
4836 // Otherwise, what happens depends on the mode
4837 if(mode == RUN_CALLBACKS_MODE_FIRST)
4839 else if(mode == RUN_CALLBACKS_MODE_LAST)
4841 else if(mode == RUN_CALLBACKS_MODE_AND ||
4842 mode == RUN_CALLBACKS_MODE_AND_SC){
4843 if(lua_toboolean(L, rv) == true &&
4844 lua_toboolean(L, -1) == false)
4849 else if(mode == RUN_CALLBACKS_MODE_OR ||
4850 mode == RUN_CALLBACKS_MODE_OR_SC){
4851 if(lua_toboolean(L, rv) == false &&
4852 lua_toboolean(L, -1) == true)
4861 // Handle short circuit modes
4862 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4863 lua_toboolean(L, rv) == false)
4865 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4866 lua_toboolean(L, rv) == true)
4869 // value removed, keep key for next iteration
4872 // Remove stuff from stack, leaving only the return value
4875 // Fix return value in case no callbacks were called
4877 if(mode == RUN_CALLBACKS_MODE_AND ||
4878 mode == RUN_CALLBACKS_MODE_AND_SC){
4880 lua_pushboolean(L, true);
4882 else if(mode == RUN_CALLBACKS_MODE_OR ||
4883 mode == RUN_CALLBACKS_MODE_OR_SC){
4885 lua_pushboolean(L, false);
4890 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4891 const std::string &message)
4894 assert(lua_checkstack(L, 20));
4895 StackUnroller stack_unroller(L);
4897 // Get minetest.registered_on_chat_messages
4898 lua_getglobal(L, "minetest");
4899 lua_getfield(L, -1, "registered_on_chat_messages");
4901 lua_pushstring(L, name.c_str());
4902 lua_pushstring(L, message.c_str());
4903 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4904 bool ate = lua_toboolean(L, -1);
4908 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4911 assert(lua_checkstack(L, 20));
4912 StackUnroller stack_unroller(L);
4914 // Get minetest.registered_on_newplayers
4915 lua_getglobal(L, "minetest");
4916 lua_getfield(L, -1, "registered_on_newplayers");
4918 objectref_get_or_create(L, player);
4919 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4922 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4925 assert(lua_checkstack(L, 20));
4926 StackUnroller stack_unroller(L);
4928 // Get minetest.registered_on_dieplayers
4929 lua_getglobal(L, "minetest");
4930 lua_getfield(L, -1, "registered_on_dieplayers");
4932 objectref_get_or_create(L, player);
4933 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4936 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4939 assert(lua_checkstack(L, 20));
4940 StackUnroller stack_unroller(L);
4942 // Get minetest.registered_on_respawnplayers
4943 lua_getglobal(L, "minetest");
4944 lua_getfield(L, -1, "registered_on_respawnplayers");
4946 objectref_get_or_create(L, player);
4947 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4948 bool positioning_handled_by_some = lua_toboolean(L, -1);
4949 return positioning_handled_by_some;
4952 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4955 assert(lua_checkstack(L, 20));
4956 StackUnroller stack_unroller(L);
4958 // Get minetest.registered_on_joinplayers
4959 lua_getglobal(L, "minetest");
4960 lua_getfield(L, -1, "registered_on_joinplayers");
4962 objectref_get_or_create(L, player);
4963 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4966 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4969 assert(lua_checkstack(L, 20));
4970 StackUnroller stack_unroller(L);
4972 // Get minetest.registered_on_leaveplayers
4973 lua_getglobal(L, "minetest");
4974 lua_getfield(L, -1, "registered_on_leaveplayers");
4976 objectref_get_or_create(L, player);
4977 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4980 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4983 assert(lua_checkstack(L, 20));
4984 StackUnroller stack_unroller(L);
4986 Inventory *inv = player->getInventory();
4989 lua_getglobal(L, "minetest");
4990 lua_getfield(L, -1, "creative_inventory");
4991 luaL_checktype(L, -1, LUA_TTABLE);
4992 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4995 static void get_auth_handler(lua_State *L)
4997 lua_getglobal(L, "minetest");
4998 lua_getfield(L, -1, "registered_auth_handler");
4999 if(lua_isnil(L, -1)){
5001 lua_getfield(L, -1, "builtin_auth_handler");
5003 if(lua_type(L, -1) != LUA_TTABLE)
5004 throw LuaError(L, "Authentication handler table not valid");
5007 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5008 std::string *dst_password, std::set<std::string> *dst_privs)
5011 assert(lua_checkstack(L, 20));
5012 StackUnroller stack_unroller(L);
5014 get_auth_handler(L);
5015 lua_getfield(L, -1, "get_auth");
5016 if(lua_type(L, -1) != LUA_TFUNCTION)
5017 throw LuaError(L, "Authentication handler missing get_auth");
5018 lua_pushstring(L, playername.c_str());
5019 if(lua_pcall(L, 1, 1, 0))
5020 script_error(L, "error: %s", lua_tostring(L, -1));
5022 // nil = login not allowed
5023 if(lua_isnil(L, -1))
5025 luaL_checktype(L, -1, LUA_TTABLE);
5027 std::string password;
5028 bool found = getstringfield(L, -1, "password", password);
5030 throw LuaError(L, "Authentication handler didn't return password");
5032 *dst_password = password;
5034 lua_getfield(L, -1, "privileges");
5035 if(!lua_istable(L, -1))
5037 "Authentication handler didn't return privilege table");
5039 read_privileges(L, -1, *dst_privs);
5045 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5046 const std::string &password)
5049 assert(lua_checkstack(L, 20));
5050 StackUnroller stack_unroller(L);
5052 get_auth_handler(L);
5053 lua_getfield(L, -1, "create_auth");
5054 if(lua_type(L, -1) != LUA_TFUNCTION)
5055 throw LuaError(L, "Authentication handler missing create_auth");
5056 lua_pushstring(L, playername.c_str());
5057 lua_pushstring(L, password.c_str());
5058 if(lua_pcall(L, 2, 0, 0))
5059 script_error(L, "error: %s", lua_tostring(L, -1));
5062 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5063 const std::string &password)
5066 assert(lua_checkstack(L, 20));
5067 StackUnroller stack_unroller(L);
5069 get_auth_handler(L);
5070 lua_getfield(L, -1, "set_password");
5071 if(lua_type(L, -1) != LUA_TFUNCTION)
5072 throw LuaError(L, "Authentication handler missing set_password");
5073 lua_pushstring(L, playername.c_str());
5074 lua_pushstring(L, password.c_str());
5075 if(lua_pcall(L, 2, 1, 0))
5076 script_error(L, "error: %s", lua_tostring(L, -1));
5077 return lua_toboolean(L, -1);
5081 item callbacks and node callbacks
5084 // Retrieves minetest.registered_items[name][callbackname]
5085 // If that is nil or on error, return false and stack is unchanged
5086 // If that is a function, returns true and pushes the
5087 // function onto the stack
5088 static bool get_item_callback(lua_State *L,
5089 const char *name, const char *callbackname)
5091 lua_getglobal(L, "minetest");
5092 lua_getfield(L, -1, "registered_items");
5094 luaL_checktype(L, -1, LUA_TTABLE);
5095 lua_getfield(L, -1, name);
5097 // Should be a table
5098 if(lua_type(L, -1) != LUA_TTABLE)
5100 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5104 lua_getfield(L, -1, callbackname);
5106 // Should be a function or nil
5107 if(lua_type(L, -1) == LUA_TFUNCTION)
5111 else if(lua_isnil(L, -1))
5118 errorstream<<"Item \""<<name<<"\" callback \""
5119 <<callbackname<<" is not a function"<<std::endl;
5125 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5126 ServerActiveObject *dropper, v3f pos)
5129 assert(lua_checkstack(L, 20));
5130 StackUnroller stack_unroller(L);
5132 // Push callback function on stack
5133 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5137 LuaItemStack::create(L, item);
5138 objectref_get_or_create(L, dropper);
5139 pushFloatPos(L, pos);
5140 if(lua_pcall(L, 3, 1, 0))
5141 script_error(L, "error: %s", lua_tostring(L, -1));
5142 if(!lua_isnil(L, -1))
5143 item = read_item(L, -1);
5147 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5148 ServerActiveObject *placer, const PointedThing &pointed)
5151 assert(lua_checkstack(L, 20));
5152 StackUnroller stack_unroller(L);
5154 // Push callback function on stack
5155 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5159 LuaItemStack::create(L, item);
5160 objectref_get_or_create(L, placer);
5161 push_pointed_thing(L, pointed);
5162 if(lua_pcall(L, 3, 1, 0))
5163 script_error(L, "error: %s", lua_tostring(L, -1));
5164 if(!lua_isnil(L, -1))
5165 item = read_item(L, -1);
5169 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5170 ServerActiveObject *user, const PointedThing &pointed)
5173 assert(lua_checkstack(L, 20));
5174 StackUnroller stack_unroller(L);
5176 // Push callback function on stack
5177 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5181 LuaItemStack::create(L, item);
5182 objectref_get_or_create(L, user);
5183 push_pointed_thing(L, pointed);
5184 if(lua_pcall(L, 3, 1, 0))
5185 script_error(L, "error: %s", lua_tostring(L, -1));
5186 if(!lua_isnil(L, -1))
5187 item = read_item(L, -1);
5191 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5192 ServerActiveObject *puncher)
5195 assert(lua_checkstack(L, 20));
5196 StackUnroller stack_unroller(L);
5198 INodeDefManager *ndef = get_server(L)->ndef();
5200 // Push callback function on stack
5201 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5206 pushnode(L, node, ndef);
5207 objectref_get_or_create(L, puncher);
5208 if(lua_pcall(L, 3, 0, 0))
5209 script_error(L, "error: %s", lua_tostring(L, -1));
5213 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5214 ServerActiveObject *digger)
5217 assert(lua_checkstack(L, 20));
5218 StackUnroller stack_unroller(L);
5220 INodeDefManager *ndef = get_server(L)->ndef();
5222 // Push callback function on stack
5223 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5228 pushnode(L, node, ndef);
5229 objectref_get_or_create(L, digger);
5230 if(lua_pcall(L, 3, 0, 0))
5231 script_error(L, "error: %s", lua_tostring(L, -1));
5235 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5238 assert(lua_checkstack(L, 20));
5239 StackUnroller stack_unroller(L);
5241 INodeDefManager *ndef = get_server(L)->ndef();
5243 // Push callback function on stack
5244 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5249 if(lua_pcall(L, 1, 0, 0))
5250 script_error(L, "error: %s", lua_tostring(L, -1));
5253 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5256 assert(lua_checkstack(L, 20));
5257 StackUnroller stack_unroller(L);
5259 INodeDefManager *ndef = get_server(L)->ndef();
5261 // Push callback function on stack
5262 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5267 if(lua_pcall(L, 1, 0, 0))
5268 script_error(L, "error: %s", lua_tostring(L, -1));
5271 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5274 assert(lua_checkstack(L, 20));
5275 StackUnroller stack_unroller(L);
5277 INodeDefManager *ndef = get_server(L)->ndef();
5279 // Push callback function on stack
5280 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5285 pushnode(L, node, ndef);
5286 if(lua_pcall(L, 2, 0, 0))
5287 script_error(L, "error: %s", lua_tostring(L, -1));
5290 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5291 const std::string &formname,
5292 const std::map<std::string, std::string> &fields,
5293 ServerActiveObject *sender)
5296 assert(lua_checkstack(L, 20));
5297 StackUnroller stack_unroller(L);
5299 INodeDefManager *ndef = get_server(L)->ndef();
5301 // If node doesn't exist, we don't know what callback to call
5302 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5303 if(node.getContent() == CONTENT_IGNORE)
5306 // Push callback function on stack
5307 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5314 lua_pushstring(L, formname.c_str());
5317 for(std::map<std::string, std::string>::const_iterator
5318 i = fields.begin(); i != fields.end(); i++){
5319 const std::string &name = i->first;
5320 const std::string &value = i->second;
5321 lua_pushstring(L, name.c_str());
5322 lua_pushlstring(L, value.c_str(), value.size());
5323 lua_settable(L, -3);
5326 objectref_get_or_create(L, sender);
5327 if(lua_pcall(L, 4, 0, 0))
5328 script_error(L, "error: %s", lua_tostring(L, -1));
5331 void scriptapi_node_on_metadata_inventory_move(lua_State *L, v3s16 p,
5332 const std::string &from_list, int from_index,
5333 const std::string &to_list, int to_index,
5334 int count, ServerActiveObject *player)
5337 assert(lua_checkstack(L, 20));
5338 StackUnroller stack_unroller(L);
5340 INodeDefManager *ndef = get_server(L)->ndef();
5342 // If node doesn't exist, we don't know what callback to call
5343 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5344 if(node.getContent() == CONTENT_IGNORE)
5347 // Push callback function on stack
5348 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5349 "on_metadata_inventory_move"))
5352 // function(pos, from_list, from_index, to_list, to_index, count, player)
5354 lua_pushstring(L, from_list.c_str());
5355 lua_pushinteger(L, from_index + 1);
5356 lua_pushstring(L, to_list.c_str());
5357 lua_pushinteger(L, to_index + 1);
5358 lua_pushinteger(L, count);
5359 objectref_get_or_create(L, player);
5360 if(lua_pcall(L, 7, 0, 0))
5361 script_error(L, "error: %s", lua_tostring(L, -1));
5364 ItemStack scriptapi_node_on_metadata_inventory_offer(lua_State *L, v3s16 p,
5365 const std::string &listname, int index, ItemStack &stack,
5366 ServerActiveObject *player)
5369 assert(lua_checkstack(L, 20));
5370 StackUnroller stack_unroller(L);
5372 INodeDefManager *ndef = get_server(L)->ndef();
5374 // If node doesn't exist, we don't know what callback to call
5375 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5376 if(node.getContent() == CONTENT_IGNORE)
5379 // Push callback function on stack
5380 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5381 "on_metadata_inventory_offer"))
5384 // Call function(pos, listname, index, stack, player)
5386 lua_pushstring(L, listname.c_str());
5387 lua_pushinteger(L, index + 1);
5388 LuaItemStack::create(L, stack);
5389 objectref_get_or_create(L, player);
5390 if(lua_pcall(L, 5, 1, 0))
5391 script_error(L, "error: %s", lua_tostring(L, -1));
5392 return read_item(L, -1);
5395 ItemStack scriptapi_node_on_metadata_inventory_take(lua_State *L, v3s16 p,
5396 const std::string &listname, int index, int count,
5397 ServerActiveObject *player)
5400 assert(lua_checkstack(L, 20));
5401 StackUnroller stack_unroller(L);
5403 INodeDefManager *ndef = get_server(L)->ndef();
5405 // If node doesn't exist, we don't know what callback to call
5406 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5407 if(node.getContent() == CONTENT_IGNORE)
5410 // Push callback function on stack
5411 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5412 "on_metadata_inventory_take"))
5415 // Call function(pos, listname, index, count, player)
5417 lua_pushstring(L, listname.c_str());
5418 lua_pushinteger(L, index + 1);
5419 lua_pushinteger(L, count);
5420 objectref_get_or_create(L, player);
5421 if(lua_pcall(L, 5, 1, 0))
5422 script_error(L, "error: %s", lua_tostring(L, -1));
5423 return read_item(L, -1);
5430 void scriptapi_environment_step(lua_State *L, float dtime)
5433 assert(lua_checkstack(L, 20));
5434 //infostream<<"scriptapi_environment_step"<<std::endl;
5435 StackUnroller stack_unroller(L);
5437 // Get minetest.registered_globalsteps
5438 lua_getglobal(L, "minetest");
5439 lua_getfield(L, -1, "registered_globalsteps");
5441 lua_pushnumber(L, dtime);
5442 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5445 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5449 assert(lua_checkstack(L, 20));
5450 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5451 StackUnroller stack_unroller(L);
5453 // Get minetest.registered_on_generateds
5454 lua_getglobal(L, "minetest");
5455 lua_getfield(L, -1, "registered_on_generateds");
5457 push_v3s16(L, minp);
5458 push_v3s16(L, maxp);
5459 lua_pushnumber(L, blockseed);
5460 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5467 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5470 assert(lua_checkstack(L, 20));
5471 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5472 <<name<<"\""<<std::endl;
5473 StackUnroller stack_unroller(L);
5475 // Get minetest.registered_entities[name]
5476 lua_getglobal(L, "minetest");
5477 lua_getfield(L, -1, "registered_entities");
5478 luaL_checktype(L, -1, LUA_TTABLE);
5479 lua_pushstring(L, name);
5480 lua_gettable(L, -2);
5481 // Should be a table, which we will use as a prototype
5482 //luaL_checktype(L, -1, LUA_TTABLE);
5483 if(lua_type(L, -1) != LUA_TTABLE){
5484 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5487 int prototype_table = lua_gettop(L);
5488 //dump2(L, "prototype_table");
5490 // Create entity object
5492 int object = lua_gettop(L);
5494 // Set object metatable
5495 lua_pushvalue(L, prototype_table);
5496 lua_setmetatable(L, -2);
5498 // Add object reference
5499 // This should be userdata with metatable ObjectRef
5500 objectref_get(L, id);
5501 luaL_checktype(L, -1, LUA_TUSERDATA);
5502 if(!luaL_checkudata(L, -1, "ObjectRef"))
5503 luaL_typerror(L, -1, "ObjectRef");
5504 lua_setfield(L, -2, "object");
5506 // minetest.luaentities[id] = object
5507 lua_getglobal(L, "minetest");
5508 lua_getfield(L, -1, "luaentities");
5509 luaL_checktype(L, -1, LUA_TTABLE);
5510 lua_pushnumber(L, id); // Push id
5511 lua_pushvalue(L, object); // Copy object to top of stack
5512 lua_settable(L, -3);
5517 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5518 const std::string &staticdata)
5521 assert(lua_checkstack(L, 20));
5522 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5523 StackUnroller stack_unroller(L);
5525 // Get minetest.luaentities[id]
5526 luaentity_get(L, id);
5527 int object = lua_gettop(L);
5529 // Get on_activate function
5530 lua_pushvalue(L, object);
5531 lua_getfield(L, -1, "on_activate");
5532 if(!lua_isnil(L, -1)){
5533 luaL_checktype(L, -1, LUA_TFUNCTION);
5534 lua_pushvalue(L, object); // self
5535 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5536 // Call with 2 arguments, 0 results
5537 if(lua_pcall(L, 2, 0, 0))
5538 script_error(L, "error running function on_activate: %s\n",
5539 lua_tostring(L, -1));
5543 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5546 assert(lua_checkstack(L, 20));
5547 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5549 // Get minetest.luaentities table
5550 lua_getglobal(L, "minetest");
5551 lua_getfield(L, -1, "luaentities");
5552 luaL_checktype(L, -1, LUA_TTABLE);
5553 int objectstable = lua_gettop(L);
5555 // Set luaentities[id] = nil
5556 lua_pushnumber(L, id); // Push id
5558 lua_settable(L, objectstable);
5560 lua_pop(L, 2); // pop luaentities, minetest
5563 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5566 assert(lua_checkstack(L, 20));
5567 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5568 StackUnroller stack_unroller(L);
5570 // Get minetest.luaentities[id]
5571 luaentity_get(L, id);
5572 int object = lua_gettop(L);
5574 // Get get_staticdata function
5575 lua_pushvalue(L, object);
5576 lua_getfield(L, -1, "get_staticdata");
5577 if(lua_isnil(L, -1))
5580 luaL_checktype(L, -1, LUA_TFUNCTION);
5581 lua_pushvalue(L, object); // self
5582 // Call with 1 arguments, 1 results
5583 if(lua_pcall(L, 1, 1, 0))
5584 script_error(L, "error running function get_staticdata: %s\n",
5585 lua_tostring(L, -1));
5588 const char *s = lua_tolstring(L, -1, &len);
5589 return std::string(s, len);
5592 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5593 ObjectProperties *prop)
5596 assert(lua_checkstack(L, 20));
5597 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5598 StackUnroller stack_unroller(L);
5600 // Get minetest.luaentities[id]
5601 luaentity_get(L, id);
5602 //int object = lua_gettop(L);
5604 // Set default values that differ from ObjectProperties defaults
5607 // Deprecated: read object properties directly
5608 read_object_properties(L, -1, prop);
5610 // Read initial_properties
5611 lua_getfield(L, -1, "initial_properties");
5612 read_object_properties(L, -1, prop);
5616 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5619 assert(lua_checkstack(L, 20));
5620 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5621 StackUnroller stack_unroller(L);
5623 // Get minetest.luaentities[id]
5624 luaentity_get(L, id);
5625 int object = lua_gettop(L);
5626 // State: object is at top of stack
5627 // Get step function
5628 lua_getfield(L, -1, "on_step");
5629 if(lua_isnil(L, -1))
5631 luaL_checktype(L, -1, LUA_TFUNCTION);
5632 lua_pushvalue(L, object); // self
5633 lua_pushnumber(L, dtime); // dtime
5634 // Call with 2 arguments, 0 results
5635 if(lua_pcall(L, 2, 0, 0))
5636 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5639 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5640 // tool_capabilities, direction)
5641 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5642 ServerActiveObject *puncher, float time_from_last_punch,
5643 const ToolCapabilities *toolcap, v3f dir)
5646 assert(lua_checkstack(L, 20));
5647 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5648 StackUnroller stack_unroller(L);
5650 // Get minetest.luaentities[id]
5651 luaentity_get(L, id);
5652 int object = lua_gettop(L);
5653 // State: object is at top of stack
5655 lua_getfield(L, -1, "on_punch");
5656 if(lua_isnil(L, -1))
5658 luaL_checktype(L, -1, LUA_TFUNCTION);
5659 lua_pushvalue(L, object); // self
5660 objectref_get_or_create(L, puncher); // Clicker reference
5661 lua_pushnumber(L, time_from_last_punch);
5662 push_tool_capabilities(L, *toolcap);
5664 // Call with 5 arguments, 0 results
5665 if(lua_pcall(L, 5, 0, 0))
5666 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5669 // Calls entity:on_rightclick(ObjectRef clicker)
5670 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5671 ServerActiveObject *clicker)
5674 assert(lua_checkstack(L, 20));
5675 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5676 StackUnroller stack_unroller(L);
5678 // Get minetest.luaentities[id]
5679 luaentity_get(L, id);
5680 int object = lua_gettop(L);
5681 // State: object is at top of stack
5683 lua_getfield(L, -1, "on_rightclick");
5684 if(lua_isnil(L, -1))
5686 luaL_checktype(L, -1, LUA_TFUNCTION);
5687 lua_pushvalue(L, object); // self
5688 objectref_get_or_create(L, clicker); // Clicker reference
5689 // Call with 2 arguments, 0 results
5690 if(lua_pcall(L, 2, 0, 0))
5691 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));