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"
48 #include "daynightratio.h"
49 #include "noise.h" // PseudoRandom for LuaPseudoRandom
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.type == ITEM_NODE && def.node_placement_prediction == "__default"){
3980 def.node_placement_prediction = name;
3983 // Register item definition
3984 idef->registerItem(def);
3986 // Read the node definition (content features) and register it
3987 if(def.type == ITEM_NODE)
3989 ContentFeatures f = read_content_features(L, table);
3990 ndef->set(f.name, f);
3993 return 0; /* number of results */
3996 // register_alias_raw(name, convert_to_name)
3997 static int l_register_alias_raw(lua_State *L)
3999 std::string name = luaL_checkstring(L, 1);
4000 std::string convert_to = luaL_checkstring(L, 2);
4002 // Get the writable item definition manager from the server
4003 IWritableItemDefManager *idef =
4004 get_server(L)->getWritableItemDefManager();
4006 idef->registerAlias(name, convert_to);
4008 return 0; /* number of results */
4011 // helper for register_craft
4012 static bool read_craft_recipe_shaped(lua_State *L, int index,
4013 int &width, std::vector<std::string> &recipe)
4016 index = lua_gettop(L) + 1 + index;
4018 if(!lua_istable(L, index))
4023 while(lua_next(L, index) != 0){
4025 // key at index -2 and value at index -1
4026 if(!lua_istable(L, -1))
4028 int table2 = lua_gettop(L);
4030 while(lua_next(L, table2) != 0){
4031 // key at index -2 and value at index -1
4032 if(!lua_isstring(L, -1))
4034 recipe.push_back(lua_tostring(L, -1));
4035 // removes value, keeps key for next iteration
4042 if(colcount != width)
4045 // removes value, keeps key for next iteration
4052 // helper for register_craft
4053 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4054 std::vector<std::string> &recipe)
4057 index = lua_gettop(L) + 1 + index;
4059 if(!lua_istable(L, index))
4063 while(lua_next(L, index) != 0){
4064 // key at index -2 and value at index -1
4065 if(!lua_isstring(L, -1))
4067 recipe.push_back(lua_tostring(L, -1));
4068 // removes value, keeps key for next iteration
4074 // helper for register_craft
4075 static bool read_craft_replacements(lua_State *L, int index,
4076 CraftReplacements &replacements)
4079 index = lua_gettop(L) + 1 + index;
4081 if(!lua_istable(L, index))
4085 while(lua_next(L, index) != 0){
4086 // key at index -2 and value at index -1
4087 if(!lua_istable(L, -1))
4089 lua_rawgeti(L, -1, 1);
4090 if(!lua_isstring(L, -1))
4092 std::string replace_from = lua_tostring(L, -1);
4094 lua_rawgeti(L, -1, 2);
4095 if(!lua_isstring(L, -1))
4097 std::string replace_to = lua_tostring(L, -1);
4099 replacements.pairs.push_back(
4100 std::make_pair(replace_from, replace_to));
4101 // removes value, keeps key for next iteration
4106 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4107 static int l_register_craft(lua_State *L)
4109 //infostream<<"register_craft"<<std::endl;
4110 luaL_checktype(L, 1, LUA_TTABLE);
4113 // Get the writable craft definition manager from the server
4114 IWritableCraftDefManager *craftdef =
4115 get_server(L)->getWritableCraftDefManager();
4117 std::string type = getstringfield_default(L, table, "type", "shaped");
4120 CraftDefinitionShaped
4122 if(type == "shaped"){
4123 std::string output = getstringfield_default(L, table, "output", "");
4125 throw LuaError(L, "Crafting definition is missing an output");
4128 std::vector<std::string> recipe;
4129 lua_getfield(L, table, "recipe");
4130 if(lua_isnil(L, -1))
4131 throw LuaError(L, "Crafting definition is missing a recipe"
4132 " (output=\"" + output + "\")");
4133 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4134 throw LuaError(L, "Invalid crafting recipe"
4135 " (output=\"" + output + "\")");
4137 CraftReplacements replacements;
4138 lua_getfield(L, table, "replacements");
4139 if(!lua_isnil(L, -1))
4141 if(!read_craft_replacements(L, -1, replacements))
4142 throw LuaError(L, "Invalid replacements"
4143 " (output=\"" + output + "\")");
4146 CraftDefinition *def = new CraftDefinitionShaped(
4147 output, width, recipe, replacements);
4148 craftdef->registerCraft(def);
4151 CraftDefinitionShapeless
4153 else if(type == "shapeless"){
4154 std::string output = getstringfield_default(L, table, "output", "");
4156 throw LuaError(L, "Crafting definition (shapeless)"
4157 " is missing an output");
4159 std::vector<std::string> recipe;
4160 lua_getfield(L, table, "recipe");
4161 if(lua_isnil(L, -1))
4162 throw LuaError(L, "Crafting definition (shapeless)"
4163 " is missing a recipe"
4164 " (output=\"" + output + "\")");
4165 if(!read_craft_recipe_shapeless(L, -1, recipe))
4166 throw LuaError(L, "Invalid crafting recipe"
4167 " (output=\"" + output + "\")");
4169 CraftReplacements replacements;
4170 lua_getfield(L, table, "replacements");
4171 if(!lua_isnil(L, -1))
4173 if(!read_craft_replacements(L, -1, replacements))
4174 throw LuaError(L, "Invalid replacements"
4175 " (output=\"" + output + "\")");
4178 CraftDefinition *def = new CraftDefinitionShapeless(
4179 output, recipe, replacements);
4180 craftdef->registerCraft(def);
4183 CraftDefinitionToolRepair
4185 else if(type == "toolrepair"){
4186 float additional_wear = getfloatfield_default(L, table,
4187 "additional_wear", 0.0);
4189 CraftDefinition *def = new CraftDefinitionToolRepair(
4191 craftdef->registerCraft(def);
4194 CraftDefinitionCooking
4196 else if(type == "cooking"){
4197 std::string output = getstringfield_default(L, table, "output", "");
4199 throw LuaError(L, "Crafting definition (cooking)"
4200 " is missing an output");
4202 std::string recipe = getstringfield_default(L, table, "recipe", "");
4204 throw LuaError(L, "Crafting definition (cooking)"
4205 " is missing a recipe"
4206 " (output=\"" + output + "\")");
4208 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4210 CraftReplacements replacements;
4211 lua_getfield(L, table, "replacements");
4212 if(!lua_isnil(L, -1))
4214 if(!read_craft_replacements(L, -1, replacements))
4215 throw LuaError(L, "Invalid replacements"
4216 " (cooking output=\"" + output + "\")");
4219 CraftDefinition *def = new CraftDefinitionCooking(
4220 output, recipe, cooktime, replacements);
4221 craftdef->registerCraft(def);
4226 else if(type == "fuel"){
4227 std::string recipe = getstringfield_default(L, table, "recipe", "");
4229 throw LuaError(L, "Crafting definition (fuel)"
4230 " is missing a recipe");
4232 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4234 CraftReplacements replacements;
4235 lua_getfield(L, table, "replacements");
4236 if(!lua_isnil(L, -1))
4238 if(!read_craft_replacements(L, -1, replacements))
4239 throw LuaError(L, "Invalid replacements"
4240 " (fuel recipe=\"" + recipe + "\")");
4243 CraftDefinition *def = new CraftDefinitionFuel(
4244 recipe, burntime, replacements);
4245 craftdef->registerCraft(def);
4249 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4253 return 0; /* number of results */
4256 // setting_set(name, value)
4257 static int l_setting_set(lua_State *L)
4259 const char *name = luaL_checkstring(L, 1);
4260 const char *value = luaL_checkstring(L, 2);
4261 g_settings->set(name, value);
4265 // setting_get(name)
4266 static int l_setting_get(lua_State *L)
4268 const char *name = luaL_checkstring(L, 1);
4270 std::string value = g_settings->get(name);
4271 lua_pushstring(L, value.c_str());
4272 } catch(SettingNotFoundException &e){
4278 // setting_getbool(name)
4279 static int l_setting_getbool(lua_State *L)
4281 const char *name = luaL_checkstring(L, 1);
4283 bool value = g_settings->getBool(name);
4284 lua_pushboolean(L, value);
4285 } catch(SettingNotFoundException &e){
4291 // chat_send_all(text)
4292 static int l_chat_send_all(lua_State *L)
4294 const char *text = luaL_checkstring(L, 1);
4295 // Get server from registry
4296 Server *server = get_server(L);
4298 server->notifyPlayers(narrow_to_wide(text));
4302 // chat_send_player(name, text)
4303 static int l_chat_send_player(lua_State *L)
4305 const char *name = luaL_checkstring(L, 1);
4306 const char *text = luaL_checkstring(L, 2);
4307 // Get server from registry
4308 Server *server = get_server(L);
4310 server->notifyPlayer(name, narrow_to_wide(text));
4314 // get_player_privs(name, text)
4315 static int l_get_player_privs(lua_State *L)
4317 const char *name = luaL_checkstring(L, 1);
4318 // Get server from registry
4319 Server *server = get_server(L);
4322 int table = lua_gettop(L);
4323 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4324 for(std::set<std::string>::const_iterator
4325 i = privs_s.begin(); i != privs_s.end(); i++){
4326 lua_pushboolean(L, true);
4327 lua_setfield(L, table, i->c_str());
4329 lua_pushvalue(L, table);
4333 // get_inventory(location)
4334 static int l_get_inventory(lua_State *L)
4336 InventoryLocation loc;
4338 std::string type = checkstringfield(L, 1, "type");
4339 if(type == "player"){
4340 std::string name = checkstringfield(L, 1, "name");
4341 loc.setPlayer(name);
4342 } else if(type == "node"){
4343 lua_getfield(L, 1, "pos");
4344 v3s16 pos = check_v3s16(L, -1);
4345 loc.setNodeMeta(pos);
4348 if(get_server(L)->getInventory(loc) != NULL)
4349 InvRef::create(L, loc);
4355 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4356 static int l_get_dig_params(lua_State *L)
4358 std::map<std::string, int> groups;
4359 read_groups(L, 1, groups);
4360 ToolCapabilities tp = read_tool_capabilities(L, 2);
4361 if(lua_isnoneornil(L, 3))
4362 push_dig_params(L, getDigParams(groups, &tp));
4364 push_dig_params(L, getDigParams(groups, &tp,
4365 luaL_checknumber(L, 3)));
4369 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4370 static int l_get_hit_params(lua_State *L)
4372 std::map<std::string, int> groups;
4373 read_groups(L, 1, groups);
4374 ToolCapabilities tp = read_tool_capabilities(L, 2);
4375 if(lua_isnoneornil(L, 3))
4376 push_hit_params(L, getHitParams(groups, &tp));
4378 push_hit_params(L, getHitParams(groups, &tp,
4379 luaL_checknumber(L, 3)));
4383 // get_current_modname()
4384 static int l_get_current_modname(lua_State *L)
4386 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4390 // get_modpath(modname)
4391 static int l_get_modpath(lua_State *L)
4393 std::string modname = luaL_checkstring(L, 1);
4395 if(modname == "__builtin"){
4396 std::string path = get_server(L)->getBuiltinLuaPath();
4397 lua_pushstring(L, path.c_str());
4400 const ModSpec *mod = get_server(L)->getModSpec(modname);
4405 lua_pushstring(L, mod->path.c_str());
4410 static int l_get_worldpath(lua_State *L)
4412 std::string worldpath = get_server(L)->getWorldPath();
4413 lua_pushstring(L, worldpath.c_str());
4417 // sound_play(spec, parameters)
4418 static int l_sound_play(lua_State *L)
4420 SimpleSoundSpec spec;
4421 read_soundspec(L, 1, spec);
4422 ServerSoundParams params;
4423 read_server_sound_params(L, 2, params);
4424 s32 handle = get_server(L)->playSound(spec, params);
4425 lua_pushinteger(L, handle);
4429 // sound_stop(handle)
4430 static int l_sound_stop(lua_State *L)
4432 int handle = luaL_checkinteger(L, 1);
4433 get_server(L)->stopSound(handle);
4437 // is_singleplayer()
4438 static int l_is_singleplayer(lua_State *L)
4440 lua_pushboolean(L, get_server(L)->isSingleplayer());
4444 // get_password_hash(name, raw_password)
4445 static int l_get_password_hash(lua_State *L)
4447 std::string name = luaL_checkstring(L, 1);
4448 std::string raw_password = luaL_checkstring(L, 2);
4449 std::string hash = translatePassword(name,
4450 narrow_to_wide(raw_password));
4451 lua_pushstring(L, hash.c_str());
4455 // notify_authentication_modified(name)
4456 static int l_notify_authentication_modified(lua_State *L)
4458 std::string name = "";
4459 if(lua_isstring(L, 1))
4460 name = lua_tostring(L, 1);
4461 get_server(L)->reportPrivsModified(name);
4465 // get_craft_result(input)
4466 static int l_get_craft_result(lua_State *L)
4469 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4470 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4471 es_CraftMethod, CRAFT_METHOD_NORMAL);
4473 lua_getfield(L, input_i, "width");
4474 if(lua_isnumber(L, -1))
4475 width = luaL_checkinteger(L, -1);
4477 lua_getfield(L, input_i, "items");
4478 std::vector<ItemStack> items = read_items(L, -1);
4479 lua_pop(L, 1); // items
4481 IGameDef *gdef = get_server(L);
4482 ICraftDefManager *cdef = gdef->cdef();
4483 CraftInput input(method, width, items);
4485 bool got = cdef->getCraftResult(input, output, true, gdef);
4486 lua_newtable(L); // output table
4489 item.deSerialize(output.item, gdef->idef());
4490 LuaItemStack::create(L, item);
4491 lua_setfield(L, -2, "item");
4492 setintfield(L, -1, "time", output.time);
4494 LuaItemStack::create(L, ItemStack());
4495 lua_setfield(L, -2, "item");
4496 setintfield(L, -1, "time", 0);
4498 lua_newtable(L); // decremented input table
4499 lua_pushstring(L, method_s.c_str());
4500 lua_setfield(L, -2, "method");
4501 lua_pushinteger(L, width);
4502 lua_setfield(L, -2, "width");
4503 push_items(L, input.items);
4504 lua_setfield(L, -2, "items");
4508 static const struct luaL_Reg minetest_f [] = {
4511 {"register_item_raw", l_register_item_raw},
4512 {"register_alias_raw", l_register_alias_raw},
4513 {"register_craft", l_register_craft},
4514 {"setting_set", l_setting_set},
4515 {"setting_get", l_setting_get},
4516 {"setting_getbool", l_setting_getbool},
4517 {"chat_send_all", l_chat_send_all},
4518 {"chat_send_player", l_chat_send_player},
4519 {"get_player_privs", l_get_player_privs},
4520 {"get_inventory", l_get_inventory},
4521 {"get_dig_params", l_get_dig_params},
4522 {"get_hit_params", l_get_hit_params},
4523 {"get_current_modname", l_get_current_modname},
4524 {"get_modpath", l_get_modpath},
4525 {"get_worldpath", l_get_worldpath},
4526 {"sound_play", l_sound_play},
4527 {"sound_stop", l_sound_stop},
4528 {"is_singleplayer", l_is_singleplayer},
4529 {"get_password_hash", l_get_password_hash},
4530 {"notify_authentication_modified", l_notify_authentication_modified},
4531 {"get_craft_result", l_get_craft_result},
4536 Main export function
4539 void scriptapi_export(lua_State *L, Server *server)
4542 assert(lua_checkstack(L, 20));
4543 verbosestream<<"scriptapi_export()"<<std::endl;
4544 StackUnroller stack_unroller(L);
4546 // Store server as light userdata in registry
4547 lua_pushlightuserdata(L, server);
4548 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4550 // Register global functions in table minetest
4552 luaL_register(L, NULL, minetest_f);
4553 lua_setglobal(L, "minetest");
4555 // Get the main minetest table
4556 lua_getglobal(L, "minetest");
4558 // Add tables to minetest
4560 lua_setfield(L, -2, "object_refs");
4562 lua_setfield(L, -2, "luaentities");
4564 // Register wrappers
4565 LuaItemStack::Register(L);
4566 InvRef::Register(L);
4567 NodeMetaRef::Register(L);
4568 ObjectRef::Register(L);
4569 EnvRef::Register(L);
4570 LuaPseudoRandom::Register(L);
4571 LuaPerlinNoise::Register(L);
4574 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4575 const std::string &modname)
4577 ModNameStorer modnamestorer(L, modname);
4579 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4581 errorstream<<"Error loading mod \""<<modname
4582 <<"\": modname does not follow naming conventions: "
4583 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4587 bool success = false;
4590 success = script_load(L, scriptpath.c_str());
4593 errorstream<<"Error loading mod \""<<modname
4594 <<"\": "<<e.what()<<std::endl;
4600 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4603 assert(lua_checkstack(L, 20));
4604 verbosestream<<"scriptapi_add_environment"<<std::endl;
4605 StackUnroller stack_unroller(L);
4607 // Create EnvRef on stack
4608 EnvRef::create(L, env);
4609 int envref = lua_gettop(L);
4611 // minetest.env = envref
4612 lua_getglobal(L, "minetest");
4613 luaL_checktype(L, -1, LUA_TTABLE);
4614 lua_pushvalue(L, envref);
4615 lua_setfield(L, -2, "env");
4617 // Store environment as light userdata in registry
4618 lua_pushlightuserdata(L, env);
4619 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4622 Add ActiveBlockModifiers to environment
4625 // Get minetest.registered_abms
4626 lua_getglobal(L, "minetest");
4627 lua_getfield(L, -1, "registered_abms");
4628 luaL_checktype(L, -1, LUA_TTABLE);
4629 int registered_abms = lua_gettop(L);
4631 if(lua_istable(L, registered_abms)){
4632 int table = lua_gettop(L);
4634 while(lua_next(L, table) != 0){
4635 // key at index -2 and value at index -1
4636 int id = lua_tonumber(L, -2);
4637 int current_abm = lua_gettop(L);
4639 std::set<std::string> trigger_contents;
4640 lua_getfield(L, current_abm, "nodenames");
4641 if(lua_istable(L, -1)){
4642 int table = lua_gettop(L);
4644 while(lua_next(L, table) != 0){
4645 // key at index -2 and value at index -1
4646 luaL_checktype(L, -1, LUA_TSTRING);
4647 trigger_contents.insert(lua_tostring(L, -1));
4648 // removes value, keeps key for next iteration
4651 } else if(lua_isstring(L, -1)){
4652 trigger_contents.insert(lua_tostring(L, -1));
4656 std::set<std::string> required_neighbors;
4657 lua_getfield(L, current_abm, "neighbors");
4658 if(lua_istable(L, -1)){
4659 int table = lua_gettop(L);
4661 while(lua_next(L, table) != 0){
4662 // key at index -2 and value at index -1
4663 luaL_checktype(L, -1, LUA_TSTRING);
4664 required_neighbors.insert(lua_tostring(L, -1));
4665 // removes value, keeps key for next iteration
4668 } else if(lua_isstring(L, -1)){
4669 required_neighbors.insert(lua_tostring(L, -1));
4673 float trigger_interval = 10.0;
4674 getfloatfield(L, current_abm, "interval", trigger_interval);
4676 int trigger_chance = 50;
4677 getintfield(L, current_abm, "chance", trigger_chance);
4679 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4680 required_neighbors, trigger_interval, trigger_chance);
4682 env->addActiveBlockModifier(abm);
4684 // removes value, keeps key for next iteration
4692 // Dump stack top with the dump2 function
4693 static void dump2(lua_State *L, const char *name)
4695 // Dump object (debug)
4696 lua_getglobal(L, "dump2");
4697 luaL_checktype(L, -1, LUA_TFUNCTION);
4698 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4699 lua_pushstring(L, name);
4700 if(lua_pcall(L, 2, 0, 0))
4701 script_error(L, "error: %s", lua_tostring(L, -1));
4709 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4712 assert(lua_checkstack(L, 20));
4713 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4714 StackUnroller stack_unroller(L);
4716 // Create object on stack
4717 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4718 int object = lua_gettop(L);
4720 // Get minetest.object_refs table
4721 lua_getglobal(L, "minetest");
4722 lua_getfield(L, -1, "object_refs");
4723 luaL_checktype(L, -1, LUA_TTABLE);
4724 int objectstable = lua_gettop(L);
4726 // object_refs[id] = object
4727 lua_pushnumber(L, cobj->getId()); // Push id
4728 lua_pushvalue(L, object); // Copy object to top of stack
4729 lua_settable(L, objectstable);
4732 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4735 assert(lua_checkstack(L, 20));
4736 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4737 StackUnroller stack_unroller(L);
4739 // Get minetest.object_refs table
4740 lua_getglobal(L, "minetest");
4741 lua_getfield(L, -1, "object_refs");
4742 luaL_checktype(L, -1, LUA_TTABLE);
4743 int objectstable = lua_gettop(L);
4745 // Get object_refs[id]
4746 lua_pushnumber(L, cobj->getId()); // Push id
4747 lua_gettable(L, objectstable);
4748 // Set object reference to NULL
4749 ObjectRef::set_null(L);
4750 lua_pop(L, 1); // pop object
4752 // Set object_refs[id] = nil
4753 lua_pushnumber(L, cobj->getId()); // Push id
4755 lua_settable(L, objectstable);
4762 // What scriptapi_run_callbacks does with the return values of callbacks.
4763 // Regardless of the mode, if only one callback is defined,
4764 // its return value is the total return value.
4765 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4766 enum RunCallbacksMode
4768 // Returns the return value of the first callback
4769 // Returns nil if list of callbacks is empty
4770 RUN_CALLBACKS_MODE_FIRST,
4771 // Returns the return value of the last callback
4772 // Returns nil if list of callbacks is empty
4773 RUN_CALLBACKS_MODE_LAST,
4774 // If any callback returns a false value, the first such is returned
4775 // Otherwise, the first callback's return value (trueish) is returned
4776 // Returns true if list of callbacks is empty
4777 RUN_CALLBACKS_MODE_AND,
4778 // Like above, but stops calling callbacks (short circuit)
4779 // after seeing the first false value
4780 RUN_CALLBACKS_MODE_AND_SC,
4781 // If any callback returns a true value, the first such is returned
4782 // Otherwise, the first callback's return value (falseish) is returned
4783 // Returns false if list of callbacks is empty
4784 RUN_CALLBACKS_MODE_OR,
4785 // Like above, but stops calling callbacks (short circuit)
4786 // after seeing the first true value
4787 RUN_CALLBACKS_MODE_OR_SC,
4788 // Note: "a true value" and "a false value" refer to values that
4789 // are converted by lua_toboolean to true or false, respectively.
4792 // Push the list of callbacks (a lua table).
4793 // Then push nargs arguments.
4794 // Then call this function, which
4795 // - runs the callbacks
4796 // - removes the table and arguments from the lua stack
4797 // - pushes the return value, computed depending on mode
4798 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4799 RunCallbacksMode mode)
4801 // Insert the return value into the lua stack, below the table
4802 assert(lua_gettop(L) >= nargs + 1);
4804 lua_insert(L, -(nargs + 1) - 1);
4805 // Stack now looks like this:
4806 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4808 int rv = lua_gettop(L) - nargs - 1;
4810 int arg = table + 1;
4812 luaL_checktype(L, table, LUA_TTABLE);
4816 bool first_loop = true;
4817 while(lua_next(L, table) != 0){
4818 // key at index -2 and value at index -1
4819 luaL_checktype(L, -1, LUA_TFUNCTION);
4821 for(int i = 0; i < nargs; i++)
4822 lua_pushvalue(L, arg+i);
4823 if(lua_pcall(L, nargs, 1, 0))
4824 script_error(L, "error: %s", lua_tostring(L, -1));
4826 // Move return value to designated space in stack
4829 // Result of first callback is always moved
4833 // Otherwise, what happens depends on the mode
4834 if(mode == RUN_CALLBACKS_MODE_FIRST)
4836 else if(mode == RUN_CALLBACKS_MODE_LAST)
4838 else if(mode == RUN_CALLBACKS_MODE_AND ||
4839 mode == RUN_CALLBACKS_MODE_AND_SC){
4840 if(lua_toboolean(L, rv) == true &&
4841 lua_toboolean(L, -1) == false)
4846 else if(mode == RUN_CALLBACKS_MODE_OR ||
4847 mode == RUN_CALLBACKS_MODE_OR_SC){
4848 if(lua_toboolean(L, rv) == false &&
4849 lua_toboolean(L, -1) == true)
4858 // Handle short circuit modes
4859 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4860 lua_toboolean(L, rv) == false)
4862 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4863 lua_toboolean(L, rv) == true)
4866 // value removed, keep key for next iteration
4869 // Remove stuff from stack, leaving only the return value
4872 // Fix return value in case no callbacks were called
4874 if(mode == RUN_CALLBACKS_MODE_AND ||
4875 mode == RUN_CALLBACKS_MODE_AND_SC){
4877 lua_pushboolean(L, true);
4879 else if(mode == RUN_CALLBACKS_MODE_OR ||
4880 mode == RUN_CALLBACKS_MODE_OR_SC){
4882 lua_pushboolean(L, false);
4887 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4888 const std::string &message)
4891 assert(lua_checkstack(L, 20));
4892 StackUnroller stack_unroller(L);
4894 // Get minetest.registered_on_chat_messages
4895 lua_getglobal(L, "minetest");
4896 lua_getfield(L, -1, "registered_on_chat_messages");
4898 lua_pushstring(L, name.c_str());
4899 lua_pushstring(L, message.c_str());
4900 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4901 bool ate = lua_toboolean(L, -1);
4905 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4908 assert(lua_checkstack(L, 20));
4909 StackUnroller stack_unroller(L);
4911 // Get minetest.registered_on_newplayers
4912 lua_getglobal(L, "minetest");
4913 lua_getfield(L, -1, "registered_on_newplayers");
4915 objectref_get_or_create(L, player);
4916 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4919 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4922 assert(lua_checkstack(L, 20));
4923 StackUnroller stack_unroller(L);
4925 // Get minetest.registered_on_dieplayers
4926 lua_getglobal(L, "minetest");
4927 lua_getfield(L, -1, "registered_on_dieplayers");
4929 objectref_get_or_create(L, player);
4930 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4933 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4936 assert(lua_checkstack(L, 20));
4937 StackUnroller stack_unroller(L);
4939 // Get minetest.registered_on_respawnplayers
4940 lua_getglobal(L, "minetest");
4941 lua_getfield(L, -1, "registered_on_respawnplayers");
4943 objectref_get_or_create(L, player);
4944 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4945 bool positioning_handled_by_some = lua_toboolean(L, -1);
4946 return positioning_handled_by_some;
4949 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4952 assert(lua_checkstack(L, 20));
4953 StackUnroller stack_unroller(L);
4955 // Get minetest.registered_on_joinplayers
4956 lua_getglobal(L, "minetest");
4957 lua_getfield(L, -1, "registered_on_joinplayers");
4959 objectref_get_or_create(L, player);
4960 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4963 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4966 assert(lua_checkstack(L, 20));
4967 StackUnroller stack_unroller(L);
4969 // Get minetest.registered_on_leaveplayers
4970 lua_getglobal(L, "minetest");
4971 lua_getfield(L, -1, "registered_on_leaveplayers");
4973 objectref_get_or_create(L, player);
4974 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4977 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4980 assert(lua_checkstack(L, 20));
4981 StackUnroller stack_unroller(L);
4983 Inventory *inv = player->getInventory();
4986 lua_getglobal(L, "minetest");
4987 lua_getfield(L, -1, "creative_inventory");
4988 luaL_checktype(L, -1, LUA_TTABLE);
4989 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4992 static void get_auth_handler(lua_State *L)
4994 lua_getglobal(L, "minetest");
4995 lua_getfield(L, -1, "registered_auth_handler");
4996 if(lua_isnil(L, -1)){
4998 lua_getfield(L, -1, "builtin_auth_handler");
5000 if(lua_type(L, -1) != LUA_TTABLE)
5001 throw LuaError(L, "Authentication handler table not valid");
5004 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5005 std::string *dst_password, std::set<std::string> *dst_privs)
5008 assert(lua_checkstack(L, 20));
5009 StackUnroller stack_unroller(L);
5011 get_auth_handler(L);
5012 lua_getfield(L, -1, "get_auth");
5013 if(lua_type(L, -1) != LUA_TFUNCTION)
5014 throw LuaError(L, "Authentication handler missing get_auth");
5015 lua_pushstring(L, playername.c_str());
5016 if(lua_pcall(L, 1, 1, 0))
5017 script_error(L, "error: %s", lua_tostring(L, -1));
5019 // nil = login not allowed
5020 if(lua_isnil(L, -1))
5022 luaL_checktype(L, -1, LUA_TTABLE);
5024 std::string password;
5025 bool found = getstringfield(L, -1, "password", password);
5027 throw LuaError(L, "Authentication handler didn't return password");
5029 *dst_password = password;
5031 lua_getfield(L, -1, "privileges");
5032 if(!lua_istable(L, -1))
5034 "Authentication handler didn't return privilege table");
5036 read_privileges(L, -1, *dst_privs);
5042 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5043 const std::string &password)
5046 assert(lua_checkstack(L, 20));
5047 StackUnroller stack_unroller(L);
5049 get_auth_handler(L);
5050 lua_getfield(L, -1, "create_auth");
5051 if(lua_type(L, -1) != LUA_TFUNCTION)
5052 throw LuaError(L, "Authentication handler missing create_auth");
5053 lua_pushstring(L, playername.c_str());
5054 lua_pushstring(L, password.c_str());
5055 if(lua_pcall(L, 2, 0, 0))
5056 script_error(L, "error: %s", lua_tostring(L, -1));
5059 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5060 const std::string &password)
5063 assert(lua_checkstack(L, 20));
5064 StackUnroller stack_unroller(L);
5066 get_auth_handler(L);
5067 lua_getfield(L, -1, "set_password");
5068 if(lua_type(L, -1) != LUA_TFUNCTION)
5069 throw LuaError(L, "Authentication handler missing set_password");
5070 lua_pushstring(L, playername.c_str());
5071 lua_pushstring(L, password.c_str());
5072 if(lua_pcall(L, 2, 1, 0))
5073 script_error(L, "error: %s", lua_tostring(L, -1));
5074 return lua_toboolean(L, -1);
5078 item callbacks and node callbacks
5081 // Retrieves minetest.registered_items[name][callbackname]
5082 // If that is nil or on error, return false and stack is unchanged
5083 // If that is a function, returns true and pushes the
5084 // function onto the stack
5085 static bool get_item_callback(lua_State *L,
5086 const char *name, const char *callbackname)
5088 lua_getglobal(L, "minetest");
5089 lua_getfield(L, -1, "registered_items");
5091 luaL_checktype(L, -1, LUA_TTABLE);
5092 lua_getfield(L, -1, name);
5094 // Should be a table
5095 if(lua_type(L, -1) != LUA_TTABLE)
5097 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5101 lua_getfield(L, -1, callbackname);
5103 // Should be a function or nil
5104 if(lua_type(L, -1) == LUA_TFUNCTION)
5108 else if(lua_isnil(L, -1))
5115 errorstream<<"Item \""<<name<<"\" callback \""
5116 <<callbackname<<" is not a function"<<std::endl;
5122 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5123 ServerActiveObject *dropper, v3f pos)
5126 assert(lua_checkstack(L, 20));
5127 StackUnroller stack_unroller(L);
5129 // Push callback function on stack
5130 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5134 LuaItemStack::create(L, item);
5135 objectref_get_or_create(L, dropper);
5136 pushFloatPos(L, pos);
5137 if(lua_pcall(L, 3, 1, 0))
5138 script_error(L, "error: %s", lua_tostring(L, -1));
5139 if(!lua_isnil(L, -1))
5140 item = read_item(L, -1);
5144 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5145 ServerActiveObject *placer, const PointedThing &pointed)
5148 assert(lua_checkstack(L, 20));
5149 StackUnroller stack_unroller(L);
5151 // Push callback function on stack
5152 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5156 LuaItemStack::create(L, item);
5157 objectref_get_or_create(L, placer);
5158 push_pointed_thing(L, pointed);
5159 if(lua_pcall(L, 3, 1, 0))
5160 script_error(L, "error: %s", lua_tostring(L, -1));
5161 if(!lua_isnil(L, -1))
5162 item = read_item(L, -1);
5166 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5167 ServerActiveObject *user, const PointedThing &pointed)
5170 assert(lua_checkstack(L, 20));
5171 StackUnroller stack_unroller(L);
5173 // Push callback function on stack
5174 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5178 LuaItemStack::create(L, item);
5179 objectref_get_or_create(L, user);
5180 push_pointed_thing(L, pointed);
5181 if(lua_pcall(L, 3, 1, 0))
5182 script_error(L, "error: %s", lua_tostring(L, -1));
5183 if(!lua_isnil(L, -1))
5184 item = read_item(L, -1);
5188 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5189 ServerActiveObject *puncher)
5192 assert(lua_checkstack(L, 20));
5193 StackUnroller stack_unroller(L);
5195 INodeDefManager *ndef = get_server(L)->ndef();
5197 // Push callback function on stack
5198 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5203 pushnode(L, node, ndef);
5204 objectref_get_or_create(L, puncher);
5205 if(lua_pcall(L, 3, 0, 0))
5206 script_error(L, "error: %s", lua_tostring(L, -1));
5210 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5211 ServerActiveObject *digger)
5214 assert(lua_checkstack(L, 20));
5215 StackUnroller stack_unroller(L);
5217 INodeDefManager *ndef = get_server(L)->ndef();
5219 // Push callback function on stack
5220 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5225 pushnode(L, node, ndef);
5226 objectref_get_or_create(L, digger);
5227 if(lua_pcall(L, 3, 0, 0))
5228 script_error(L, "error: %s", lua_tostring(L, -1));
5232 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5235 assert(lua_checkstack(L, 20));
5236 StackUnroller stack_unroller(L);
5238 INodeDefManager *ndef = get_server(L)->ndef();
5240 // Push callback function on stack
5241 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5246 if(lua_pcall(L, 1, 0, 0))
5247 script_error(L, "error: %s", lua_tostring(L, -1));
5250 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5253 assert(lua_checkstack(L, 20));
5254 StackUnroller stack_unroller(L);
5256 INodeDefManager *ndef = get_server(L)->ndef();
5258 // Push callback function on stack
5259 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5264 if(lua_pcall(L, 1, 0, 0))
5265 script_error(L, "error: %s", lua_tostring(L, -1));
5268 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5271 assert(lua_checkstack(L, 20));
5272 StackUnroller stack_unroller(L);
5274 INodeDefManager *ndef = get_server(L)->ndef();
5276 // Push callback function on stack
5277 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5282 pushnode(L, node, ndef);
5283 if(lua_pcall(L, 2, 0, 0))
5284 script_error(L, "error: %s", lua_tostring(L, -1));
5287 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5288 const std::string &formname,
5289 const std::map<std::string, std::string> &fields,
5290 ServerActiveObject *sender)
5293 assert(lua_checkstack(L, 20));
5294 StackUnroller stack_unroller(L);
5296 INodeDefManager *ndef = get_server(L)->ndef();
5298 // If node doesn't exist, we don't know what callback to call
5299 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5300 if(node.getContent() == CONTENT_IGNORE)
5303 // Push callback function on stack
5304 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5311 lua_pushstring(L, formname.c_str());
5314 for(std::map<std::string, std::string>::const_iterator
5315 i = fields.begin(); i != fields.end(); i++){
5316 const std::string &name = i->first;
5317 const std::string &value = i->second;
5318 lua_pushstring(L, name.c_str());
5319 lua_pushlstring(L, value.c_str(), value.size());
5320 lua_settable(L, -3);
5323 objectref_get_or_create(L, sender);
5324 if(lua_pcall(L, 4, 0, 0))
5325 script_error(L, "error: %s", lua_tostring(L, -1));
5328 void scriptapi_node_on_metadata_inventory_move(lua_State *L, v3s16 p,
5329 const std::string &from_list, int from_index,
5330 const std::string &to_list, int to_index,
5331 int count, ServerActiveObject *player)
5334 assert(lua_checkstack(L, 20));
5335 StackUnroller stack_unroller(L);
5337 INodeDefManager *ndef = get_server(L)->ndef();
5339 // If node doesn't exist, we don't know what callback to call
5340 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5341 if(node.getContent() == CONTENT_IGNORE)
5344 // Push callback function on stack
5345 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5346 "on_metadata_inventory_move"))
5349 // function(pos, from_list, from_index, to_list, to_index, count, player)
5351 lua_pushstring(L, from_list.c_str());
5352 lua_pushinteger(L, from_index + 1);
5353 lua_pushstring(L, to_list.c_str());
5354 lua_pushinteger(L, to_index + 1);
5355 lua_pushinteger(L, count);
5356 objectref_get_or_create(L, player);
5357 if(lua_pcall(L, 7, 0, 0))
5358 script_error(L, "error: %s", lua_tostring(L, -1));
5361 ItemStack scriptapi_node_on_metadata_inventory_offer(lua_State *L, v3s16 p,
5362 const std::string &listname, int index, ItemStack &stack,
5363 ServerActiveObject *player)
5366 assert(lua_checkstack(L, 20));
5367 StackUnroller stack_unroller(L);
5369 INodeDefManager *ndef = get_server(L)->ndef();
5371 // If node doesn't exist, we don't know what callback to call
5372 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5373 if(node.getContent() == CONTENT_IGNORE)
5376 // Push callback function on stack
5377 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5378 "on_metadata_inventory_offer"))
5381 // Call function(pos, listname, index, stack, player)
5383 lua_pushstring(L, listname.c_str());
5384 lua_pushinteger(L, index + 1);
5385 LuaItemStack::create(L, stack);
5386 objectref_get_or_create(L, player);
5387 if(lua_pcall(L, 5, 1, 0))
5388 script_error(L, "error: %s", lua_tostring(L, -1));
5389 return read_item(L, -1);
5392 ItemStack scriptapi_node_on_metadata_inventory_take(lua_State *L, v3s16 p,
5393 const std::string &listname, int index, int count,
5394 ServerActiveObject *player)
5397 assert(lua_checkstack(L, 20));
5398 StackUnroller stack_unroller(L);
5400 INodeDefManager *ndef = get_server(L)->ndef();
5402 // If node doesn't exist, we don't know what callback to call
5403 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5404 if(node.getContent() == CONTENT_IGNORE)
5407 // Push callback function on stack
5408 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5409 "on_metadata_inventory_take"))
5412 // Call function(pos, listname, index, count, player)
5414 lua_pushstring(L, listname.c_str());
5415 lua_pushinteger(L, index + 1);
5416 lua_pushinteger(L, count);
5417 objectref_get_or_create(L, player);
5418 if(lua_pcall(L, 5, 1, 0))
5419 script_error(L, "error: %s", lua_tostring(L, -1));
5420 return read_item(L, -1);
5427 void scriptapi_environment_step(lua_State *L, float dtime)
5430 assert(lua_checkstack(L, 20));
5431 //infostream<<"scriptapi_environment_step"<<std::endl;
5432 StackUnroller stack_unroller(L);
5434 // Get minetest.registered_globalsteps
5435 lua_getglobal(L, "minetest");
5436 lua_getfield(L, -1, "registered_globalsteps");
5438 lua_pushnumber(L, dtime);
5439 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5442 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5446 assert(lua_checkstack(L, 20));
5447 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5448 StackUnroller stack_unroller(L);
5450 // Get minetest.registered_on_generateds
5451 lua_getglobal(L, "minetest");
5452 lua_getfield(L, -1, "registered_on_generateds");
5454 push_v3s16(L, minp);
5455 push_v3s16(L, maxp);
5456 lua_pushnumber(L, blockseed);
5457 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5464 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5467 assert(lua_checkstack(L, 20));
5468 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5469 <<name<<"\""<<std::endl;
5470 StackUnroller stack_unroller(L);
5472 // Get minetest.registered_entities[name]
5473 lua_getglobal(L, "minetest");
5474 lua_getfield(L, -1, "registered_entities");
5475 luaL_checktype(L, -1, LUA_TTABLE);
5476 lua_pushstring(L, name);
5477 lua_gettable(L, -2);
5478 // Should be a table, which we will use as a prototype
5479 //luaL_checktype(L, -1, LUA_TTABLE);
5480 if(lua_type(L, -1) != LUA_TTABLE){
5481 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5484 int prototype_table = lua_gettop(L);
5485 //dump2(L, "prototype_table");
5487 // Create entity object
5489 int object = lua_gettop(L);
5491 // Set object metatable
5492 lua_pushvalue(L, prototype_table);
5493 lua_setmetatable(L, -2);
5495 // Add object reference
5496 // This should be userdata with metatable ObjectRef
5497 objectref_get(L, id);
5498 luaL_checktype(L, -1, LUA_TUSERDATA);
5499 if(!luaL_checkudata(L, -1, "ObjectRef"))
5500 luaL_typerror(L, -1, "ObjectRef");
5501 lua_setfield(L, -2, "object");
5503 // minetest.luaentities[id] = object
5504 lua_getglobal(L, "minetest");
5505 lua_getfield(L, -1, "luaentities");
5506 luaL_checktype(L, -1, LUA_TTABLE);
5507 lua_pushnumber(L, id); // Push id
5508 lua_pushvalue(L, object); // Copy object to top of stack
5509 lua_settable(L, -3);
5514 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5515 const std::string &staticdata)
5518 assert(lua_checkstack(L, 20));
5519 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5520 StackUnroller stack_unroller(L);
5522 // Get minetest.luaentities[id]
5523 luaentity_get(L, id);
5524 int object = lua_gettop(L);
5526 // Get on_activate function
5527 lua_pushvalue(L, object);
5528 lua_getfield(L, -1, "on_activate");
5529 if(!lua_isnil(L, -1)){
5530 luaL_checktype(L, -1, LUA_TFUNCTION);
5531 lua_pushvalue(L, object); // self
5532 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5533 // Call with 2 arguments, 0 results
5534 if(lua_pcall(L, 2, 0, 0))
5535 script_error(L, "error running function on_activate: %s\n",
5536 lua_tostring(L, -1));
5540 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5543 assert(lua_checkstack(L, 20));
5544 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5546 // Get minetest.luaentities table
5547 lua_getglobal(L, "minetest");
5548 lua_getfield(L, -1, "luaentities");
5549 luaL_checktype(L, -1, LUA_TTABLE);
5550 int objectstable = lua_gettop(L);
5552 // Set luaentities[id] = nil
5553 lua_pushnumber(L, id); // Push id
5555 lua_settable(L, objectstable);
5557 lua_pop(L, 2); // pop luaentities, minetest
5560 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5563 assert(lua_checkstack(L, 20));
5564 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5565 StackUnroller stack_unroller(L);
5567 // Get minetest.luaentities[id]
5568 luaentity_get(L, id);
5569 int object = lua_gettop(L);
5571 // Get get_staticdata function
5572 lua_pushvalue(L, object);
5573 lua_getfield(L, -1, "get_staticdata");
5574 if(lua_isnil(L, -1))
5577 luaL_checktype(L, -1, LUA_TFUNCTION);
5578 lua_pushvalue(L, object); // self
5579 // Call with 1 arguments, 1 results
5580 if(lua_pcall(L, 1, 1, 0))
5581 script_error(L, "error running function get_staticdata: %s\n",
5582 lua_tostring(L, -1));
5585 const char *s = lua_tolstring(L, -1, &len);
5586 return std::string(s, len);
5589 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5590 ObjectProperties *prop)
5593 assert(lua_checkstack(L, 20));
5594 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5595 StackUnroller stack_unroller(L);
5597 // Get minetest.luaentities[id]
5598 luaentity_get(L, id);
5599 //int object = lua_gettop(L);
5601 // Set default values that differ from ObjectProperties defaults
5604 // Deprecated: read object properties directly
5605 read_object_properties(L, -1, prop);
5607 // Read initial_properties
5608 lua_getfield(L, -1, "initial_properties");
5609 read_object_properties(L, -1, prop);
5613 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5616 assert(lua_checkstack(L, 20));
5617 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5618 StackUnroller stack_unroller(L);
5620 // Get minetest.luaentities[id]
5621 luaentity_get(L, id);
5622 int object = lua_gettop(L);
5623 // State: object is at top of stack
5624 // Get step function
5625 lua_getfield(L, -1, "on_step");
5626 if(lua_isnil(L, -1))
5628 luaL_checktype(L, -1, LUA_TFUNCTION);
5629 lua_pushvalue(L, object); // self
5630 lua_pushnumber(L, dtime); // dtime
5631 // Call with 2 arguments, 0 results
5632 if(lua_pcall(L, 2, 0, 0))
5633 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5636 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5637 // tool_capabilities, direction)
5638 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5639 ServerActiveObject *puncher, float time_from_last_punch,
5640 const ToolCapabilities *toolcap, v3f dir)
5643 assert(lua_checkstack(L, 20));
5644 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5645 StackUnroller stack_unroller(L);
5647 // Get minetest.luaentities[id]
5648 luaentity_get(L, id);
5649 int object = lua_gettop(L);
5650 // State: object is at top of stack
5652 lua_getfield(L, -1, "on_punch");
5653 if(lua_isnil(L, -1))
5655 luaL_checktype(L, -1, LUA_TFUNCTION);
5656 lua_pushvalue(L, object); // self
5657 objectref_get_or_create(L, puncher); // Clicker reference
5658 lua_pushnumber(L, time_from_last_punch);
5659 push_tool_capabilities(L, *toolcap);
5661 // Call with 5 arguments, 0 results
5662 if(lua_pcall(L, 5, 0, 0))
5663 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5666 // Calls entity:on_rightclick(ObjectRef clicker)
5667 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5668 ServerActiveObject *clicker)
5671 assert(lua_checkstack(L, 20));
5672 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5673 StackUnroller stack_unroller(L);
5675 // Get minetest.luaentities[id]
5676 luaentity_get(L, id);
5677 int object = lua_gettop(L);
5678 // State: object is at top of stack
5680 lua_getfield(L, -1, "on_rightclick");
5681 if(lua_isnil(L, -1))
5683 luaL_checktype(L, -1, LUA_TFUNCTION);
5684 lua_pushvalue(L, object); // self
5685 objectref_get_or_create(L, clicker); // Clicker reference
5686 // Call with 2 arguments, 0 results
5687 if(lua_pcall(L, 2, 0, 0))
5688 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));