3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "scriptapi.h"
34 #include "serverobject.h"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
41 #include "main.h" // For g_settings
42 #include "settings.h" // For accessing g_settings
43 #include "nodemetadata.h"
44 #include "mapblock.h" // For getNodeBlockPos
45 #include "content_nodemeta.h"
47 #include "daynightratio.h"
48 #include "noise.h" // PseudoRandom for LuaPseudoRandom
49 #include "util/pointedthing.h"
53 static void stackDump(lua_State *L, std::ostream &o)
56 int top = lua_gettop(L);
57 for (i = 1; i <= top; i++) { /* repeat for each level */
58 int t = lua_type(L, i);
61 case LUA_TSTRING: /* strings */
62 o<<"\""<<lua_tostring(L, i)<<"\"";
65 case LUA_TBOOLEAN: /* booleans */
66 o<<(lua_toboolean(L, i) ? "true" : "false");
69 case LUA_TNUMBER: /* numbers */ {
71 snprintf(buf, 10, "%g", lua_tonumber(L, i));
75 default: /* other values */
76 o<<lua_typename(L, t);
85 static void realitycheck(lua_State *L)
87 int top = lua_gettop(L);
89 dstream<<"Stack is over 30:"<<std::endl;
90 stackDump(L, dstream);
91 script_error(L, "Stack is over 30 (reality check)");
101 StackUnroller(lua_State *L):
105 m_original_top = lua_gettop(m_lua); // store stack height
109 lua_settop(m_lua, m_original_top); // restore stack height
118 ModNameStorer(lua_State *L_, const std::string modname):
121 // Store current modname in registry
122 lua_pushstring(L, modname.c_str());
123 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
127 // Clear current modname in registry
129 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
134 Getters for stuff in main tables
137 static Server* get_server(lua_State *L)
139 // Get server from registry
140 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
141 Server *server = (Server*)lua_touserdata(L, -1);
146 static ServerEnvironment* get_env(lua_State *L)
148 // Get environment from registry
149 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
150 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
155 static void objectref_get(lua_State *L, u16 id)
157 // Get minetest.object_refs[i]
158 lua_getglobal(L, "minetest");
159 lua_getfield(L, -1, "object_refs");
160 luaL_checktype(L, -1, LUA_TTABLE);
161 lua_pushnumber(L, id);
163 lua_remove(L, -2); // object_refs
164 lua_remove(L, -2); // minetest
167 static void luaentity_get(lua_State *L, u16 id)
169 // Get minetest.luaentities[i]
170 lua_getglobal(L, "minetest");
171 lua_getfield(L, -1, "luaentities");
172 luaL_checktype(L, -1, LUA_TTABLE);
173 lua_pushnumber(L, id);
175 lua_remove(L, -2); // luaentities
176 lua_remove(L, -2); // minetest
183 static bool getstringfield(lua_State *L, int table,
184 const char *fieldname, std::string &result)
186 lua_getfield(L, table, fieldname);
188 if(lua_isstring(L, -1)){
190 const char *ptr = lua_tolstring(L, -1, &len);
191 result.assign(ptr, len);
198 static bool getintfield(lua_State *L, int table,
199 const char *fieldname, int &result)
201 lua_getfield(L, table, fieldname);
203 if(lua_isnumber(L, -1)){
204 result = lua_tonumber(L, -1);
211 static bool getfloatfield(lua_State *L, int table,
212 const char *fieldname, float &result)
214 lua_getfield(L, table, fieldname);
216 if(lua_isnumber(L, -1)){
217 result = lua_tonumber(L, -1);
224 static bool getboolfield(lua_State *L, int table,
225 const char *fieldname, bool &result)
227 lua_getfield(L, table, fieldname);
229 if(lua_isboolean(L, -1)){
230 result = lua_toboolean(L, -1);
237 static std::string checkstringfield(lua_State *L, int table,
238 const char *fieldname)
240 lua_getfield(L, table, fieldname);
241 std::string s = luaL_checkstring(L, -1);
246 static std::string getstringfield_default(lua_State *L, int table,
247 const char *fieldname, const std::string &default_)
249 std::string result = default_;
250 getstringfield(L, table, fieldname, result);
254 static int getintfield_default(lua_State *L, int table,
255 const char *fieldname, int default_)
257 int result = default_;
258 getintfield(L, table, fieldname, result);
262 static float getfloatfield_default(lua_State *L, int table,
263 const char *fieldname, float default_)
265 float result = default_;
266 getfloatfield(L, table, fieldname, result);
270 static bool getboolfield_default(lua_State *L, int table,
271 const char *fieldname, bool default_)
273 bool result = default_;
274 getboolfield(L, table, fieldname, result);
284 static bool string_to_enum(const EnumString *spec, int &result,
285 const std::string &str)
287 const EnumString *esp = spec;
289 if(str == std::string(esp->str)){
298 /*static bool enum_to_string(const EnumString *spec, std::string &result,
301 const EnumString *esp = spec;
312 static int getenumfield(lua_State *L, int table,
313 const char *fieldname, const EnumString *spec, int default_)
315 int result = default_;
316 string_to_enum(spec, result,
317 getstringfield_default(L, table, fieldname, ""));
321 static void setintfield(lua_State *L, int table,
322 const char *fieldname, int value)
324 lua_pushinteger(L, value);
327 lua_setfield(L, table, fieldname);
330 static void setfloatfield(lua_State *L, int table,
331 const char *fieldname, float value)
333 lua_pushnumber(L, value);
336 lua_setfield(L, table, fieldname);
339 static void setboolfield(lua_State *L, int table,
340 const char *fieldname, bool value)
342 lua_pushboolean(L, value);
345 lua_setfield(L, table, fieldname);
348 static void warn_if_field_exists(lua_State *L, int table,
349 const char *fieldname, const std::string &message)
351 lua_getfield(L, table, fieldname);
352 if(!lua_isnil(L, -1)){
353 infostream<<script_get_backtrace(L)<<std::endl;
354 infostream<<"WARNING: field \""<<fieldname<<"\": "
355 <<message<<std::endl;
361 EnumString definitions
364 struct EnumString es_ItemType[] =
368 {ITEM_CRAFT, "craft"},
373 struct EnumString es_DrawType[] =
375 {NDT_NORMAL, "normal"},
376 {NDT_AIRLIKE, "airlike"},
377 {NDT_LIQUID, "liquid"},
378 {NDT_FLOWINGLIQUID, "flowingliquid"},
379 {NDT_GLASSLIKE, "glasslike"},
380 {NDT_ALLFACES, "allfaces"},
381 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
382 {NDT_TORCHLIKE, "torchlike"},
383 {NDT_SIGNLIKE, "signlike"},
384 {NDT_PLANTLIKE, "plantlike"},
385 {NDT_FENCELIKE, "fencelike"},
386 {NDT_RAILLIKE, "raillike"},
387 {NDT_NODEBOX, "nodebox"},
391 struct EnumString es_ContentParamType[] =
394 {CPT_LIGHT, "light"},
398 struct EnumString es_ContentParamType2[] =
402 {CPT2_FLOWINGLIQUID, "flowingliquid"},
403 {CPT2_FACEDIR, "facedir"},
404 {CPT2_WALLMOUNTED, "wallmounted"},
408 struct EnumString es_LiquidType[] =
410 {LIQUID_NONE, "none"},
411 {LIQUID_FLOWING, "flowing"},
412 {LIQUID_SOURCE, "source"},
416 struct EnumString es_NodeBoxType[] =
418 {NODEBOX_REGULAR, "regular"},
419 {NODEBOX_FIXED, "fixed"},
420 {NODEBOX_WALLMOUNTED, "wallmounted"},
424 struct EnumString es_CraftMethod[] =
426 {CRAFT_METHOD_NORMAL, "normal"},
427 {CRAFT_METHOD_COOKING, "cooking"},
428 {CRAFT_METHOD_FUEL, "fuel"},
432 struct EnumString es_TileAnimationType[] =
435 {TAT_VERTICAL_FRAMES, "vertical_frames"},
440 C struct <-> Lua table converter functions
443 static void push_v3f(lua_State *L, v3f p)
446 lua_pushnumber(L, p.X);
447 lua_setfield(L, -2, "x");
448 lua_pushnumber(L, p.Y);
449 lua_setfield(L, -2, "y");
450 lua_pushnumber(L, p.Z);
451 lua_setfield(L, -2, "z");
454 static v2s16 read_v2s16(lua_State *L, int index)
457 luaL_checktype(L, index, LUA_TTABLE);
458 lua_getfield(L, index, "x");
459 p.X = lua_tonumber(L, -1);
461 lua_getfield(L, index, "y");
462 p.Y = lua_tonumber(L, -1);
467 static v2f read_v2f(lua_State *L, int index)
470 luaL_checktype(L, index, LUA_TTABLE);
471 lua_getfield(L, index, "x");
472 p.X = lua_tonumber(L, -1);
474 lua_getfield(L, index, "y");
475 p.Y = lua_tonumber(L, -1);
480 static v3f read_v3f(lua_State *L, int index)
483 luaL_checktype(L, index, LUA_TTABLE);
484 lua_getfield(L, index, "x");
485 pos.X = lua_tonumber(L, -1);
487 lua_getfield(L, index, "y");
488 pos.Y = lua_tonumber(L, -1);
490 lua_getfield(L, index, "z");
491 pos.Z = lua_tonumber(L, -1);
496 static v3f check_v3f(lua_State *L, int index)
499 luaL_checktype(L, index, LUA_TTABLE);
500 lua_getfield(L, index, "x");
501 pos.X = luaL_checknumber(L, -1);
503 lua_getfield(L, index, "y");
504 pos.Y = luaL_checknumber(L, -1);
506 lua_getfield(L, index, "z");
507 pos.Z = luaL_checknumber(L, -1);
512 static void pushFloatPos(lua_State *L, v3f p)
518 static v3f checkFloatPos(lua_State *L, int index)
520 return check_v3f(L, index) * BS;
523 static void push_v3s16(lua_State *L, v3s16 p)
526 lua_pushnumber(L, p.X);
527 lua_setfield(L, -2, "x");
528 lua_pushnumber(L, p.Y);
529 lua_setfield(L, -2, "y");
530 lua_pushnumber(L, p.Z);
531 lua_setfield(L, -2, "z");
534 static v3s16 read_v3s16(lua_State *L, int index)
536 // Correct rounding at <0
537 v3f pf = read_v3f(L, index);
538 return floatToInt(pf, 1.0);
541 static v3s16 check_v3s16(lua_State *L, int index)
543 // Correct rounding at <0
544 v3f pf = check_v3f(L, index);
545 return floatToInt(pf, 1.0);
548 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
551 lua_pushstring(L, ndef->get(n).name.c_str());
552 lua_setfield(L, -2, "name");
553 lua_pushnumber(L, n.getParam1());
554 lua_setfield(L, -2, "param1");
555 lua_pushnumber(L, n.getParam2());
556 lua_setfield(L, -2, "param2");
559 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
561 lua_getfield(L, index, "name");
562 const char *name = luaL_checkstring(L, -1);
565 lua_getfield(L, index, "param1");
569 param1 = lua_tonumber(L, -1);
572 lua_getfield(L, index, "param2");
576 param2 = lua_tonumber(L, -1);
578 return MapNode(ndef, name, param1, param2);
581 static video::SColor readARGB8(lua_State *L, int index)
584 luaL_checktype(L, index, LUA_TTABLE);
585 lua_getfield(L, index, "a");
586 if(lua_isnumber(L, -1))
587 color.setAlpha(lua_tonumber(L, -1));
589 lua_getfield(L, index, "r");
590 color.setRed(lua_tonumber(L, -1));
592 lua_getfield(L, index, "g");
593 color.setGreen(lua_tonumber(L, -1));
595 lua_getfield(L, index, "b");
596 color.setBlue(lua_tonumber(L, -1));
601 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
604 if(lua_istable(L, index)){
605 lua_rawgeti(L, index, 1);
606 box.MinEdge.X = lua_tonumber(L, -1) * scale;
608 lua_rawgeti(L, index, 2);
609 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
611 lua_rawgeti(L, index, 3);
612 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
614 lua_rawgeti(L, index, 4);
615 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
617 lua_rawgeti(L, index, 5);
618 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
620 lua_rawgeti(L, index, 6);
621 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
627 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
629 std::vector<aabb3f> boxes;
630 if(lua_istable(L, index)){
631 int n = lua_objlen(L, index);
632 // Check if it's a single box or a list of boxes
633 bool possibly_single_box = (n == 6);
634 for(int i = 1; i <= n && possibly_single_box; i++){
635 lua_rawgeti(L, index, i);
636 if(!lua_isnumber(L, -1))
637 possibly_single_box = false;
640 if(possibly_single_box){
642 boxes.push_back(read_aabb3f(L, index, scale));
644 // Read a list of boxes
645 for(int i = 1; i <= n; i++){
646 lua_rawgeti(L, index, i);
647 boxes.push_back(read_aabb3f(L, -1, scale));
655 static NodeBox read_nodebox(lua_State *L, int index)
658 if(lua_istable(L, -1)){
659 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
660 es_NodeBoxType, NODEBOX_REGULAR);
662 lua_getfield(L, index, "fixed");
663 if(lua_istable(L, -1))
664 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
667 lua_getfield(L, index, "wall_top");
668 if(lua_istable(L, -1))
669 nodebox.wall_top = read_aabb3f(L, -1, BS);
672 lua_getfield(L, index, "wall_bottom");
673 if(lua_istable(L, -1))
674 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
677 lua_getfield(L, index, "wall_side");
678 if(lua_istable(L, -1))
679 nodebox.wall_side = read_aabb3f(L, -1, BS);
688 static void read_groups(lua_State *L, int index,
689 std::map<std::string, int> &result)
691 if (!lua_istable(L,index))
697 while(lua_next(L, index) != 0){
698 // key at index -2 and value at index -1
699 std::string name = luaL_checkstring(L, -2);
700 int rating = luaL_checkinteger(L, -1);
701 result[name] = rating;
702 // removes value, keeps key for next iteration
710 static void read_privileges(lua_State *L, int index,
711 std::set<std::string> &result)
717 while(lua_next(L, index) != 0){
718 // key at index -2 and value at index -1
719 std::string key = luaL_checkstring(L, -2);
720 bool value = lua_toboolean(L, -1);
723 // removes value, keeps key for next iteration
732 static ToolCapabilities read_tool_capabilities(
733 lua_State *L, int table)
735 ToolCapabilities toolcap;
736 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
737 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
738 lua_getfield(L, table, "groupcaps");
739 if(lua_istable(L, -1)){
740 int table_groupcaps = lua_gettop(L);
742 while(lua_next(L, table_groupcaps) != 0){
743 // key at index -2 and value at index -1
744 std::string groupname = luaL_checkstring(L, -2);
745 if(lua_istable(L, -1)){
746 int table_groupcap = lua_gettop(L);
747 // This will be created
748 ToolGroupCap groupcap;
749 // Read simple parameters
750 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
751 getintfield(L, table_groupcap, "uses", groupcap.uses);
752 // DEPRECATED: maxwear
754 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
756 groupcap.uses = 1.0/maxwear;
759 infostream<<script_get_backtrace(L)<<std::endl;
760 infostream<<"WARNING: field \"maxwear\" is deprecated; "
761 <<"should replace with uses=1/maxwear"<<std::endl;
763 // Read "times" table
764 lua_getfield(L, table_groupcap, "times");
765 if(lua_istable(L, -1)){
766 int table_times = lua_gettop(L);
768 while(lua_next(L, table_times) != 0){
769 // key at index -2 and value at index -1
770 int rating = luaL_checkinteger(L, -2);
771 float time = luaL_checknumber(L, -1);
772 groupcap.times[rating] = time;
773 // removes value, keeps key for next iteration
778 // Insert groupcap into toolcap
779 toolcap.groupcaps[groupname] = groupcap;
781 // removes value, keeps key for next iteration
789 static void set_tool_capabilities(lua_State *L, int table,
790 const ToolCapabilities &toolcap)
792 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
793 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
794 // Create groupcaps table
797 for(std::map<std::string, ToolGroupCap>::const_iterator
798 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
799 // Create groupcap table
801 const std::string &name = i->first;
802 const ToolGroupCap &groupcap = i->second;
803 // Create subtable "times"
805 for(std::map<int, float>::const_iterator
806 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
807 int rating = i->first;
808 float time = i->second;
809 lua_pushinteger(L, rating);
810 lua_pushnumber(L, time);
813 // Set subtable "times"
814 lua_setfield(L, -2, "times");
815 // Set simple parameters
816 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
817 setintfield(L, -1, "uses", groupcap.uses);
818 // Insert groupcap table into groupcaps table
819 lua_setfield(L, -2, name.c_str());
821 // Set groupcaps table
822 lua_setfield(L, -2, "groupcaps");
825 static void push_tool_capabilities(lua_State *L,
826 const ToolCapabilities &prop)
829 set_tool_capabilities(L, -1, prop);
836 static void set_dig_params(lua_State *L, int table,
837 const DigParams ¶ms)
839 setboolfield(L, table, "diggable", params.diggable);
840 setfloatfield(L, table, "time", params.time);
841 setintfield(L, table, "wear", params.wear);
844 static void push_dig_params(lua_State *L,
845 const DigParams ¶ms)
848 set_dig_params(L, -1, params);
855 static void set_hit_params(lua_State *L, int table,
856 const HitParams ¶ms)
858 setintfield(L, table, "hp", params.hp);
859 setintfield(L, table, "wear", params.wear);
862 static void push_hit_params(lua_State *L,
863 const HitParams ¶ms)
866 set_hit_params(L, -1, params);
873 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
876 if(pointed.type == POINTEDTHING_NODE)
878 lua_pushstring(L, "node");
879 lua_setfield(L, -2, "type");
880 push_v3s16(L, pointed.node_undersurface);
881 lua_setfield(L, -2, "under");
882 push_v3s16(L, pointed.node_abovesurface);
883 lua_setfield(L, -2, "above");
885 else if(pointed.type == POINTEDTHING_OBJECT)
887 lua_pushstring(L, "object");
888 lua_setfield(L, -2, "type");
889 objectref_get(L, pointed.object_id);
890 lua_setfield(L, -2, "ref");
894 lua_pushstring(L, "nothing");
895 lua_setfield(L, -2, "type");
903 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
906 index = lua_gettop(L) + 1 + index;
907 if(lua_isnil(L, index)){
908 } else if(lua_istable(L, index)){
909 getstringfield(L, index, "name", spec.name);
910 getfloatfield(L, index, "gain", spec.gain);
911 } else if(lua_isstring(L, index)){
912 spec.name = lua_tostring(L, index);
920 static void read_object_properties(lua_State *L, int index,
921 ObjectProperties *prop)
924 index = lua_gettop(L) + 1 + index;
925 if(!lua_istable(L, index))
928 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
930 getboolfield(L, -1, "physical", prop->physical);
932 getfloatfield(L, -1, "weight", prop->weight);
934 lua_getfield(L, -1, "collisionbox");
935 if(lua_istable(L, -1))
936 prop->collisionbox = read_aabb3f(L, -1, 1.0);
939 getstringfield(L, -1, "visual", prop->visual);
941 getstringfield(L, -1, "mesh", prop->mesh);
943 lua_getfield(L, -1, "visual_size");
944 if(lua_istable(L, -1))
945 prop->visual_size = read_v2f(L, -1);
948 lua_getfield(L, -1, "textures");
949 if(lua_istable(L, -1)){
950 prop->textures.clear();
951 int table = lua_gettop(L);
953 while(lua_next(L, table) != 0){
954 // key at index -2 and value at index -1
955 if(lua_isstring(L, -1))
956 prop->textures.push_back(lua_tostring(L, -1));
958 prop->textures.push_back("");
959 // removes value, keeps key for next iteration
965 lua_getfield(L, -1, "colors");
966 if(lua_istable(L, -1)){
967 prop->colors.clear();
968 int table = lua_gettop(L);
970 while(lua_next(L, table) != 0){
971 // key at index -2 and value at index -1
972 if(lua_isstring(L, -1))
973 prop->colors.push_back(readARGB8(L, -1));
975 prop->colors.push_back(video::SColor(255, 255, 255, 255));
976 // removes value, keeps key for next iteration
982 lua_getfield(L, -1, "spritediv");
983 if(lua_istable(L, -1))
984 prop->spritediv = read_v2s16(L, -1);
987 lua_getfield(L, -1, "initial_sprite_basepos");
988 if(lua_istable(L, -1))
989 prop->initial_sprite_basepos = read_v2s16(L, -1);
992 getboolfield(L, -1, "is_visible", prop->is_visible);
993 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
994 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
1001 static ItemDefinition read_item_definition(lua_State *L, int index,
1002 ItemDefinition default_def = ItemDefinition())
1005 index = lua_gettop(L) + 1 + index;
1007 // Read the item definition
1008 ItemDefinition def = default_def;
1010 def.type = (ItemType)getenumfield(L, index, "type",
1011 es_ItemType, ITEM_NONE);
1012 getstringfield(L, index, "name", def.name);
1013 getstringfield(L, index, "description", def.description);
1014 getstringfield(L, index, "inventory_image", def.inventory_image);
1015 getstringfield(L, index, "wield_image", def.wield_image);
1017 lua_getfield(L, index, "wield_scale");
1018 if(lua_istable(L, -1)){
1019 def.wield_scale = check_v3f(L, -1);
1023 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1024 if(def.stack_max == 0)
1027 lua_getfield(L, index, "on_use");
1028 def.usable = lua_isfunction(L, -1);
1031 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1033 warn_if_field_exists(L, index, "tool_digging_properties",
1034 "deprecated: use tool_capabilities");
1036 lua_getfield(L, index, "tool_capabilities");
1037 if(lua_istable(L, -1)){
1038 def.tool_capabilities = new ToolCapabilities(
1039 read_tool_capabilities(L, -1));
1042 // If name is "" (hand), ensure there are ToolCapabilities
1043 // because it will be looked up there whenever any other item has
1044 // no ToolCapabilities
1045 if(def.name == "" && def.tool_capabilities == NULL){
1046 def.tool_capabilities = new ToolCapabilities();
1049 lua_getfield(L, index, "groups");
1050 read_groups(L, -1, def.groups);
1053 // Client shall immediately place this node when player places the item.
1054 // Server will update the precise end result a moment later.
1055 // "" = no prediction
1056 getstringfield(L, index, "node_placement_prediction",
1057 def.node_placement_prediction);
1066 static TileDef read_tiledef(lua_State *L, int index)
1069 index = lua_gettop(L) + 1 + index;
1073 // key at index -2 and value at index
1074 if(lua_isstring(L, index)){
1075 // "default_lava.png"
1076 tiledef.name = lua_tostring(L, index);
1078 else if(lua_istable(L, index))
1080 // {name="default_lava.png", animation={}}
1082 getstringfield(L, index, "name", tiledef.name);
1083 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1084 tiledef.backface_culling = getboolfield_default(
1085 L, index, "backface_culling", true);
1087 lua_getfield(L, index, "animation");
1088 if(lua_istable(L, -1)){
1089 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1090 tiledef.animation.type = (TileAnimationType)
1091 getenumfield(L, -1, "type", es_TileAnimationType,
1093 tiledef.animation.aspect_w =
1094 getintfield_default(L, -1, "aspect_w", 16);
1095 tiledef.animation.aspect_h =
1096 getintfield_default(L, -1, "aspect_h", 16);
1097 tiledef.animation.length =
1098 getfloatfield_default(L, -1, "length", 1.0);
1110 static ContentFeatures read_content_features(lua_State *L, int index)
1113 index = lua_gettop(L) + 1 + index;
1117 /* Cache existence of some callbacks */
1118 lua_getfield(L, index, "on_construct");
1119 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1121 lua_getfield(L, index, "on_destruct");
1122 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1124 lua_getfield(L, index, "after_destruct");
1125 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1129 getstringfield(L, index, "name", f.name);
1132 lua_getfield(L, index, "groups");
1133 read_groups(L, -1, f.groups);
1136 /* Visual definition */
1138 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1140 getfloatfield(L, index, "visual_scale", f.visual_scale);
1143 lua_getfield(L, index, "tiles");
1144 // If nil, try the deprecated name "tile_images" instead
1145 if(lua_isnil(L, -1)){
1147 warn_if_field_exists(L, index, "tile_images",
1148 "Deprecated; new name is \"tiles\".");
1149 lua_getfield(L, index, "tile_images");
1151 if(lua_istable(L, -1)){
1152 int table = lua_gettop(L);
1155 while(lua_next(L, table) != 0){
1156 // Read tiledef from value
1157 f.tiledef[i] = read_tiledef(L, -1);
1158 // removes value, keeps key for next iteration
1166 // Copy last value to all remaining textures
1168 TileDef lasttile = f.tiledef[i-1];
1170 f.tiledef[i] = lasttile;
1177 // special_tiles = {}
1178 lua_getfield(L, index, "special_tiles");
1179 // If nil, try the deprecated name "special_materials" instead
1180 if(lua_isnil(L, -1)){
1182 warn_if_field_exists(L, index, "special_materials",
1183 "Deprecated; new name is \"special_tiles\".");
1184 lua_getfield(L, index, "special_materials");
1186 if(lua_istable(L, -1)){
1187 int table = lua_gettop(L);
1190 while(lua_next(L, table) != 0){
1191 // Read tiledef from value
1192 f.tiledef_special[i] = read_tiledef(L, -1);
1193 // removes value, keeps key for next iteration
1204 f.alpha = getintfield_default(L, index, "alpha", 255);
1208 lua_getfield(L, index, "post_effect_color");
1209 if(!lua_isnil(L, -1))
1210 f.post_effect_color = readARGB8(L, -1);
1213 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1214 es_ContentParamType, CPT_NONE);
1215 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1216 es_ContentParamType2, CPT2_NONE);
1218 // Warn about some deprecated fields
1219 warn_if_field_exists(L, index, "wall_mounted",
1220 "deprecated: use paramtype2 = 'wallmounted'");
1221 warn_if_field_exists(L, index, "light_propagates",
1222 "deprecated: determined from paramtype");
1223 warn_if_field_exists(L, index, "dug_item",
1224 "deprecated: use 'drop' field");
1225 warn_if_field_exists(L, index, "extra_dug_item",
1226 "deprecated: use 'drop' field");
1227 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1228 "deprecated: use 'drop' field");
1229 warn_if_field_exists(L, index, "metadata_name",
1230 "deprecated: use on_add and metadata callbacks");
1232 // True for all ground-like things like stone and mud, false for eg. trees
1233 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1234 f.light_propagates = (f.param_type == CPT_LIGHT);
1235 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1236 // This is used for collision detection.
1237 // Also for general solidness queries.
1238 getboolfield(L, index, "walkable", f.walkable);
1239 // Player can point to these
1240 getboolfield(L, index, "pointable", f.pointable);
1241 // Player can dig these
1242 getboolfield(L, index, "diggable", f.diggable);
1243 // Player can climb these
1244 getboolfield(L, index, "climbable", f.climbable);
1245 // Player can build on these
1246 getboolfield(L, index, "buildable_to", f.buildable_to);
1247 // Whether the node is non-liquid, source liquid or flowing liquid
1248 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1249 es_LiquidType, LIQUID_NONE);
1250 // If the content is liquid, this is the flowing version of the liquid.
1251 getstringfield(L, index, "liquid_alternative_flowing",
1252 f.liquid_alternative_flowing);
1253 // If the content is liquid, this is the source version of the liquid.
1254 getstringfield(L, index, "liquid_alternative_source",
1255 f.liquid_alternative_source);
1256 // Viscosity for fluid flow, ranging from 1 to 7, with
1257 // 1 giving almost instantaneous propagation and 7 being
1258 // the slowest possible
1259 f.liquid_viscosity = getintfield_default(L, index,
1260 "liquid_viscosity", f.liquid_viscosity);
1261 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1262 // Amount of light the node emits
1263 f.light_source = getintfield_default(L, index,
1264 "light_source", f.light_source);
1265 f.damage_per_second = getintfield_default(L, index,
1266 "damage_per_second", f.damage_per_second);
1268 lua_getfield(L, index, "node_box");
1269 if(lua_istable(L, -1))
1270 f.node_box = read_nodebox(L, -1);
1273 lua_getfield(L, index, "selection_box");
1274 if(lua_istable(L, -1))
1275 f.selection_box = read_nodebox(L, -1);
1278 // Set to true if paramtype used to be 'facedir_simple'
1279 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1280 // Set to true if wall_mounted used to be set to true
1281 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1284 lua_getfield(L, index, "sounds");
1285 if(lua_istable(L, -1)){
1286 lua_getfield(L, -1, "footstep");
1287 read_soundspec(L, -1, f.sound_footstep);
1289 lua_getfield(L, -1, "dig");
1290 read_soundspec(L, -1, f.sound_dig);
1292 lua_getfield(L, -1, "dug");
1293 read_soundspec(L, -1, f.sound_dug);
1305 static ItemStack read_item(lua_State *L, int index);
1306 static std::vector<ItemStack> read_items(lua_State *L, int index);
1307 // creates a table of ItemStacks
1308 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1310 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1311 lua_State *L, int tableindex, int forcesize=-1)
1314 tableindex = lua_gettop(L) + 1 + tableindex;
1315 // If nil, delete list
1316 if(lua_isnil(L, tableindex)){
1317 inv->deleteList(name);
1320 // Otherwise set list
1321 std::vector<ItemStack> items = read_items(L, tableindex);
1322 int listsize = (forcesize != -1) ? forcesize : items.size();
1323 InventoryList *invlist = inv->addList(name, listsize);
1325 for(std::vector<ItemStack>::const_iterator
1326 i = items.begin(); i != items.end(); i++){
1327 if(forcesize != -1 && index == forcesize)
1329 invlist->changeItem(index, *i);
1332 while(forcesize != -1 && index < forcesize){
1333 invlist->deleteItem(index);
1338 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1341 InventoryList *invlist = inv->getList(name);
1342 if(invlist == NULL){
1346 std::vector<ItemStack> items;
1347 for(u32 i=0; i<invlist->getSize(); i++)
1348 items.push_back(invlist->getItem(i));
1349 push_items(L, items);
1353 Helpful macros for userdata classes
1356 #define method(class, name) {#name, class::l_##name}
1367 static const char className[];
1368 static const luaL_reg methods[];
1370 // Exported functions
1372 // garbage collector
1373 static int gc_object(lua_State *L)
1375 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1380 // is_empty(self) -> true/false
1381 static int l_is_empty(lua_State *L)
1383 LuaItemStack *o = checkobject(L, 1);
1384 ItemStack &item = o->m_stack;
1385 lua_pushboolean(L, item.empty());
1389 // get_name(self) -> string
1390 static int l_get_name(lua_State *L)
1392 LuaItemStack *o = checkobject(L, 1);
1393 ItemStack &item = o->m_stack;
1394 lua_pushstring(L, item.name.c_str());
1398 // get_count(self) -> number
1399 static int l_get_count(lua_State *L)
1401 LuaItemStack *o = checkobject(L, 1);
1402 ItemStack &item = o->m_stack;
1403 lua_pushinteger(L, item.count);
1407 // get_wear(self) -> number
1408 static int l_get_wear(lua_State *L)
1410 LuaItemStack *o = checkobject(L, 1);
1411 ItemStack &item = o->m_stack;
1412 lua_pushinteger(L, item.wear);
1416 // get_metadata(self) -> string
1417 static int l_get_metadata(lua_State *L)
1419 LuaItemStack *o = checkobject(L, 1);
1420 ItemStack &item = o->m_stack;
1421 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1425 // clear(self) -> true
1426 static int l_clear(lua_State *L)
1428 LuaItemStack *o = checkobject(L, 1);
1430 lua_pushboolean(L, true);
1434 // replace(self, itemstack or itemstring or table or nil) -> true
1435 static int l_replace(lua_State *L)
1437 LuaItemStack *o = checkobject(L, 1);
1438 o->m_stack = read_item(L, 2);
1439 lua_pushboolean(L, true);
1443 // to_string(self) -> string
1444 static int l_to_string(lua_State *L)
1446 LuaItemStack *o = checkobject(L, 1);
1447 std::string itemstring = o->m_stack.getItemString();
1448 lua_pushstring(L, itemstring.c_str());
1452 // to_table(self) -> table or nil
1453 static int l_to_table(lua_State *L)
1455 LuaItemStack *o = checkobject(L, 1);
1456 const ItemStack &item = o->m_stack;
1464 lua_pushstring(L, item.name.c_str());
1465 lua_setfield(L, -2, "name");
1466 lua_pushinteger(L, item.count);
1467 lua_setfield(L, -2, "count");
1468 lua_pushinteger(L, item.wear);
1469 lua_setfield(L, -2, "wear");
1470 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1471 lua_setfield(L, -2, "metadata");
1476 // get_stack_max(self) -> number
1477 static int l_get_stack_max(lua_State *L)
1479 LuaItemStack *o = checkobject(L, 1);
1480 ItemStack &item = o->m_stack;
1481 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1485 // get_free_space(self) -> number
1486 static int l_get_free_space(lua_State *L)
1488 LuaItemStack *o = checkobject(L, 1);
1489 ItemStack &item = o->m_stack;
1490 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1494 // is_known(self) -> true/false
1495 // Checks if the item is defined.
1496 static int l_is_known(lua_State *L)
1498 LuaItemStack *o = checkobject(L, 1);
1499 ItemStack &item = o->m_stack;
1500 bool is_known = item.isKnown(get_server(L)->idef());
1501 lua_pushboolean(L, is_known);
1505 // get_definition(self) -> table
1506 // Returns the item definition table from minetest.registered_items,
1507 // or a fallback one (name="unknown")
1508 static int l_get_definition(lua_State *L)
1510 LuaItemStack *o = checkobject(L, 1);
1511 ItemStack &item = o->m_stack;
1513 // Get minetest.registered_items[name]
1514 lua_getglobal(L, "minetest");
1515 lua_getfield(L, -1, "registered_items");
1516 luaL_checktype(L, -1, LUA_TTABLE);
1517 lua_getfield(L, -1, item.name.c_str());
1518 if(lua_isnil(L, -1))
1521 lua_getfield(L, -1, "unknown");
1526 // get_tool_capabilities(self) -> table
1527 // Returns the effective tool digging properties.
1528 // Returns those of the hand ("") if this item has none associated.
1529 static int l_get_tool_capabilities(lua_State *L)
1531 LuaItemStack *o = checkobject(L, 1);
1532 ItemStack &item = o->m_stack;
1533 const ToolCapabilities &prop =
1534 item.getToolCapabilities(get_server(L)->idef());
1535 push_tool_capabilities(L, prop);
1539 // add_wear(self, amount) -> true/false
1540 // The range for "amount" is [0,65535]. Wear is only added if the item
1541 // is a tool. Adding wear might destroy the item.
1542 // Returns true if the item is (or was) a tool.
1543 static int l_add_wear(lua_State *L)
1545 LuaItemStack *o = checkobject(L, 1);
1546 ItemStack &item = o->m_stack;
1547 int amount = lua_tointeger(L, 2);
1548 bool result = item.addWear(amount, get_server(L)->idef());
1549 lua_pushboolean(L, result);
1553 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1554 // Returns leftover item stack
1555 static int l_add_item(lua_State *L)
1557 LuaItemStack *o = checkobject(L, 1);
1558 ItemStack &item = o->m_stack;
1559 ItemStack newitem = read_item(L, 2);
1560 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1561 create(L, leftover);
1565 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1566 // First return value is true iff the new item fits fully into the stack
1567 // Second return value is the would-be-left-over item stack
1568 static int l_item_fits(lua_State *L)
1570 LuaItemStack *o = checkobject(L, 1);
1571 ItemStack &item = o->m_stack;
1572 ItemStack newitem = read_item(L, 2);
1574 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1575 lua_pushboolean(L, fits); // first return value
1576 create(L, restitem); // second return value
1580 // take_item(self, takecount=1) -> itemstack
1581 static int l_take_item(lua_State *L)
1583 LuaItemStack *o = checkobject(L, 1);
1584 ItemStack &item = o->m_stack;
1586 if(!lua_isnone(L, 2))
1587 takecount = luaL_checkinteger(L, 2);
1588 ItemStack taken = item.takeItem(takecount);
1593 // peek_item(self, peekcount=1) -> itemstack
1594 static int l_peek_item(lua_State *L)
1596 LuaItemStack *o = checkobject(L, 1);
1597 ItemStack &item = o->m_stack;
1599 if(!lua_isnone(L, 2))
1600 peekcount = lua_tointeger(L, 2);
1601 ItemStack peekaboo = item.peekItem(peekcount);
1602 create(L, peekaboo);
1607 LuaItemStack(const ItemStack &item):
1616 const ItemStack& getItem() const
1620 ItemStack& getItem()
1625 // LuaItemStack(itemstack or itemstring or table or nil)
1626 // Creates an LuaItemStack and leaves it on top of stack
1627 static int create_object(lua_State *L)
1629 ItemStack item = read_item(L, 1);
1630 LuaItemStack *o = new LuaItemStack(item);
1631 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1632 luaL_getmetatable(L, className);
1633 lua_setmetatable(L, -2);
1636 // Not callable from Lua
1637 static int create(lua_State *L, const ItemStack &item)
1639 LuaItemStack *o = new LuaItemStack(item);
1640 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1641 luaL_getmetatable(L, className);
1642 lua_setmetatable(L, -2);
1646 static LuaItemStack* checkobject(lua_State *L, int narg)
1648 luaL_checktype(L, narg, LUA_TUSERDATA);
1649 void *ud = luaL_checkudata(L, narg, className);
1650 if(!ud) luaL_typerror(L, narg, className);
1651 return *(LuaItemStack**)ud; // unbox pointer
1654 static void Register(lua_State *L)
1657 int methodtable = lua_gettop(L);
1658 luaL_newmetatable(L, className);
1659 int metatable = lua_gettop(L);
1661 lua_pushliteral(L, "__metatable");
1662 lua_pushvalue(L, methodtable);
1663 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1665 lua_pushliteral(L, "__index");
1666 lua_pushvalue(L, methodtable);
1667 lua_settable(L, metatable);
1669 lua_pushliteral(L, "__gc");
1670 lua_pushcfunction(L, gc_object);
1671 lua_settable(L, metatable);
1673 lua_pop(L, 1); // drop metatable
1675 luaL_openlib(L, 0, methods, 0); // fill methodtable
1676 lua_pop(L, 1); // drop methodtable
1678 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1679 lua_register(L, className, create_object);
1682 const char LuaItemStack::className[] = "ItemStack";
1683 const luaL_reg LuaItemStack::methods[] = {
1684 method(LuaItemStack, is_empty),
1685 method(LuaItemStack, get_name),
1686 method(LuaItemStack, get_count),
1687 method(LuaItemStack, get_wear),
1688 method(LuaItemStack, get_metadata),
1689 method(LuaItemStack, clear),
1690 method(LuaItemStack, replace),
1691 method(LuaItemStack, to_string),
1692 method(LuaItemStack, to_table),
1693 method(LuaItemStack, get_stack_max),
1694 method(LuaItemStack, get_free_space),
1695 method(LuaItemStack, is_known),
1696 method(LuaItemStack, get_definition),
1697 method(LuaItemStack, get_tool_capabilities),
1698 method(LuaItemStack, add_wear),
1699 method(LuaItemStack, add_item),
1700 method(LuaItemStack, item_fits),
1701 method(LuaItemStack, take_item),
1702 method(LuaItemStack, peek_item),
1706 static ItemStack read_item(lua_State *L, int index)
1709 index = lua_gettop(L) + 1 + index;
1711 if(lua_isnil(L, index))
1715 else if(lua_isuserdata(L, index))
1717 // Convert from LuaItemStack
1718 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1719 return o->getItem();
1721 else if(lua_isstring(L, index))
1723 // Convert from itemstring
1724 std::string itemstring = lua_tostring(L, index);
1725 IItemDefManager *idef = get_server(L)->idef();
1729 item.deSerialize(itemstring, idef);
1732 catch(SerializationError &e)
1734 infostream<<"WARNING: unable to create item from itemstring"
1735 <<": "<<itemstring<<std::endl;
1739 else if(lua_istable(L, index))
1741 // Convert from table
1742 IItemDefManager *idef = get_server(L)->idef();
1743 std::string name = getstringfield_default(L, index, "name", "");
1744 int count = getintfield_default(L, index, "count", 1);
1745 int wear = getintfield_default(L, index, "wear", 0);
1746 std::string metadata = getstringfield_default(L, index, "metadata", "");
1747 return ItemStack(name, count, wear, metadata, idef);
1751 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1755 static std::vector<ItemStack> read_items(lua_State *L, int index)
1758 index = lua_gettop(L) + 1 + index;
1760 std::vector<ItemStack> items;
1761 luaL_checktype(L, index, LUA_TTABLE);
1763 while(lua_next(L, index) != 0){
1764 // key at index -2 and value at index -1
1765 items.push_back(read_item(L, -1));
1766 // removes value, keeps key for next iteration
1772 // creates a table of ItemStacks
1773 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1775 // Get the table insert function
1776 lua_getglobal(L, "table");
1777 lua_getfield(L, -1, "insert");
1778 int table_insert = lua_gettop(L);
1779 // Create and fill table
1781 int table = lua_gettop(L);
1782 for(u32 i=0; i<items.size(); i++){
1783 ItemStack item = items[i];
1784 lua_pushvalue(L, table_insert);
1785 lua_pushvalue(L, table);
1786 LuaItemStack::create(L, item);
1787 if(lua_pcall(L, 2, 0, 0))
1788 script_error(L, "error: %s", lua_tostring(L, -1));
1790 lua_remove(L, -2); // Remove table
1791 lua_remove(L, -2); // Remove insert
1801 InventoryLocation m_loc;
1803 static const char className[];
1804 static const luaL_reg methods[];
1806 static InvRef *checkobject(lua_State *L, int narg)
1808 luaL_checktype(L, narg, LUA_TUSERDATA);
1809 void *ud = luaL_checkudata(L, narg, className);
1810 if(!ud) luaL_typerror(L, narg, className);
1811 return *(InvRef**)ud; // unbox pointer
1814 static Inventory* getinv(lua_State *L, InvRef *ref)
1816 return get_server(L)->getInventory(ref->m_loc);
1819 static InventoryList* getlist(lua_State *L, InvRef *ref,
1820 const char *listname)
1822 Inventory *inv = getinv(L, ref);
1825 return inv->getList(listname);
1828 static void reportInventoryChange(lua_State *L, InvRef *ref)
1830 // Inform other things that the inventory has changed
1831 get_server(L)->setInventoryModified(ref->m_loc);
1834 // Exported functions
1836 // garbage collector
1837 static int gc_object(lua_State *L) {
1838 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1843 // is_empty(self, listname) -> true/false
1844 static int l_is_empty(lua_State *L)
1846 InvRef *ref = checkobject(L, 1);
1847 const char *listname = luaL_checkstring(L, 2);
1848 InventoryList *list = getlist(L, ref, listname);
1849 if(list && list->getUsedSlots() > 0){
1850 lua_pushboolean(L, false);
1852 lua_pushboolean(L, true);
1857 // get_size(self, listname)
1858 static int l_get_size(lua_State *L)
1860 InvRef *ref = checkobject(L, 1);
1861 const char *listname = luaL_checkstring(L, 2);
1862 InventoryList *list = getlist(L, ref, listname);
1864 lua_pushinteger(L, list->getSize());
1866 lua_pushinteger(L, 0);
1871 // get_width(self, listname)
1872 static int l_get_width(lua_State *L)
1874 InvRef *ref = checkobject(L, 1);
1875 const char *listname = luaL_checkstring(L, 2);
1876 InventoryList *list = getlist(L, ref, listname);
1878 lua_pushinteger(L, list->getWidth());
1880 lua_pushinteger(L, 0);
1885 // set_size(self, listname, size)
1886 static int l_set_size(lua_State *L)
1888 InvRef *ref = checkobject(L, 1);
1889 const char *listname = luaL_checkstring(L, 2);
1890 int newsize = luaL_checknumber(L, 3);
1891 Inventory *inv = getinv(L, ref);
1893 inv->deleteList(listname);
1894 reportInventoryChange(L, ref);
1897 InventoryList *list = inv->getList(listname);
1899 list->setSize(newsize);
1901 list = inv->addList(listname, newsize);
1903 reportInventoryChange(L, ref);
1907 // set_width(self, listname, size)
1908 static int l_set_width(lua_State *L)
1910 InvRef *ref = checkobject(L, 1);
1911 const char *listname = luaL_checkstring(L, 2);
1912 int newwidth = luaL_checknumber(L, 3);
1913 Inventory *inv = getinv(L, ref);
1914 InventoryList *list = inv->getList(listname);
1916 list->setWidth(newwidth);
1920 reportInventoryChange(L, ref);
1924 // get_stack(self, listname, i) -> itemstack
1925 static int l_get_stack(lua_State *L)
1927 InvRef *ref = checkobject(L, 1);
1928 const char *listname = luaL_checkstring(L, 2);
1929 int i = luaL_checknumber(L, 3) - 1;
1930 InventoryList *list = getlist(L, ref, listname);
1932 if(list != NULL && i >= 0 && i < (int) list->getSize())
1933 item = list->getItem(i);
1934 LuaItemStack::create(L, item);
1938 // set_stack(self, listname, i, stack) -> true/false
1939 static int l_set_stack(lua_State *L)
1941 InvRef *ref = checkobject(L, 1);
1942 const char *listname = luaL_checkstring(L, 2);
1943 int i = luaL_checknumber(L, 3) - 1;
1944 ItemStack newitem = read_item(L, 4);
1945 InventoryList *list = getlist(L, ref, listname);
1946 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1947 list->changeItem(i, newitem);
1948 reportInventoryChange(L, ref);
1949 lua_pushboolean(L, true);
1951 lua_pushboolean(L, false);
1956 // get_list(self, listname) -> list or nil
1957 static int l_get_list(lua_State *L)
1959 InvRef *ref = checkobject(L, 1);
1960 const char *listname = luaL_checkstring(L, 2);
1961 Inventory *inv = getinv(L, ref);
1962 inventory_get_list_to_lua(inv, listname, L);
1966 // set_list(self, listname, list)
1967 static int l_set_list(lua_State *L)
1969 InvRef *ref = checkobject(L, 1);
1970 const char *listname = luaL_checkstring(L, 2);
1971 Inventory *inv = getinv(L, ref);
1972 InventoryList *list = inv->getList(listname);
1974 inventory_set_list_from_lua(inv, listname, L, 3,
1977 inventory_set_list_from_lua(inv, listname, L, 3);
1978 reportInventoryChange(L, ref);
1982 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1983 // Returns the leftover stack
1984 static int l_add_item(lua_State *L)
1986 InvRef *ref = checkobject(L, 1);
1987 const char *listname = luaL_checkstring(L, 2);
1988 ItemStack item = read_item(L, 3);
1989 InventoryList *list = getlist(L, ref, listname);
1991 ItemStack leftover = list->addItem(item);
1992 if(leftover.count != item.count)
1993 reportInventoryChange(L, ref);
1994 LuaItemStack::create(L, leftover);
1996 LuaItemStack::create(L, item);
2001 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2002 // Returns true if the item completely fits into the list
2003 static int l_room_for_item(lua_State *L)
2005 InvRef *ref = checkobject(L, 1);
2006 const char *listname = luaL_checkstring(L, 2);
2007 ItemStack item = read_item(L, 3);
2008 InventoryList *list = getlist(L, ref, listname);
2010 lua_pushboolean(L, list->roomForItem(item));
2012 lua_pushboolean(L, false);
2017 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2018 // Returns true if the list contains the given count of the given item name
2019 static int l_contains_item(lua_State *L)
2021 InvRef *ref = checkobject(L, 1);
2022 const char *listname = luaL_checkstring(L, 2);
2023 ItemStack item = read_item(L, 3);
2024 InventoryList *list = getlist(L, ref, listname);
2026 lua_pushboolean(L, list->containsItem(item));
2028 lua_pushboolean(L, false);
2033 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2034 // Returns the items that were actually removed
2035 static int l_remove_item(lua_State *L)
2037 InvRef *ref = checkobject(L, 1);
2038 const char *listname = luaL_checkstring(L, 2);
2039 ItemStack item = read_item(L, 3);
2040 InventoryList *list = getlist(L, ref, listname);
2042 ItemStack removed = list->removeItem(item);
2043 if(!removed.empty())
2044 reportInventoryChange(L, ref);
2045 LuaItemStack::create(L, removed);
2047 LuaItemStack::create(L, ItemStack());
2052 // get_location() -> location (like minetest.get_inventory(location))
2053 static int l_get_location(lua_State *L)
2055 InvRef *ref = checkobject(L, 1);
2056 const InventoryLocation &loc = ref->m_loc;
2058 case InventoryLocation::PLAYER:
2060 lua_pushstring(L, "player");
2061 lua_setfield(L, -2, "type");
2062 lua_pushstring(L, loc.name.c_str());
2063 lua_setfield(L, -2, "name");
2065 case InventoryLocation::NODEMETA:
2067 lua_pushstring(L, "nodemeta");
2068 lua_setfield(L, -2, "type");
2069 push_v3s16(L, loc.p);
2070 lua_setfield(L, -2, "name");
2072 case InventoryLocation::DETACHED:
2074 lua_pushstring(L, "detached");
2075 lua_setfield(L, -2, "type");
2076 lua_pushstring(L, loc.name.c_str());
2077 lua_setfield(L, -2, "name");
2079 case InventoryLocation::UNDEFINED:
2080 case InventoryLocation::CURRENT_PLAYER:
2084 lua_pushstring(L, "undefined");
2085 lua_setfield(L, -2, "type");
2090 InvRef(const InventoryLocation &loc):
2099 // Creates an InvRef and leaves it on top of stack
2100 // Not callable from Lua; all references are created on the C side.
2101 static void create(lua_State *L, const InventoryLocation &loc)
2103 InvRef *o = new InvRef(loc);
2104 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2105 luaL_getmetatable(L, className);
2106 lua_setmetatable(L, -2);
2108 static void createPlayer(lua_State *L, Player *player)
2110 InventoryLocation loc;
2111 loc.setPlayer(player->getName());
2114 static void createNodeMeta(lua_State *L, v3s16 p)
2116 InventoryLocation loc;
2121 static void Register(lua_State *L)
2124 int methodtable = lua_gettop(L);
2125 luaL_newmetatable(L, className);
2126 int metatable = lua_gettop(L);
2128 lua_pushliteral(L, "__metatable");
2129 lua_pushvalue(L, methodtable);
2130 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2132 lua_pushliteral(L, "__index");
2133 lua_pushvalue(L, methodtable);
2134 lua_settable(L, metatable);
2136 lua_pushliteral(L, "__gc");
2137 lua_pushcfunction(L, gc_object);
2138 lua_settable(L, metatable);
2140 lua_pop(L, 1); // drop metatable
2142 luaL_openlib(L, 0, methods, 0); // fill methodtable
2143 lua_pop(L, 1); // drop methodtable
2145 // Cannot be created from Lua
2146 //lua_register(L, className, create_object);
2149 const char InvRef::className[] = "InvRef";
2150 const luaL_reg InvRef::methods[] = {
2151 method(InvRef, is_empty),
2152 method(InvRef, get_size),
2153 method(InvRef, set_size),
2154 method(InvRef, get_width),
2155 method(InvRef, set_width),
2156 method(InvRef, get_stack),
2157 method(InvRef, set_stack),
2158 method(InvRef, get_list),
2159 method(InvRef, set_list),
2160 method(InvRef, add_item),
2161 method(InvRef, room_for_item),
2162 method(InvRef, contains_item),
2163 method(InvRef, remove_item),
2164 method(InvRef, get_location),
2176 ServerEnvironment *m_env;
2178 static const char className[];
2179 static const luaL_reg methods[];
2181 static NodeMetaRef *checkobject(lua_State *L, int narg)
2183 luaL_checktype(L, narg, LUA_TUSERDATA);
2184 void *ud = luaL_checkudata(L, narg, className);
2185 if(!ud) luaL_typerror(L, narg, className);
2186 return *(NodeMetaRef**)ud; // unbox pointer
2189 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2191 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2192 if(meta == NULL && auto_create)
2194 meta = new NodeMetadata(ref->m_env->getGameDef());
2195 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2200 static void reportMetadataChange(NodeMetaRef *ref)
2202 // NOTE: This same code is in rollback_interface.cpp
2203 // Inform other things that the metadata has changed
2204 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2206 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2208 ref->m_env->getMap().dispatchEvent(&event);
2209 // Set the block to be saved
2210 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2212 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2213 "NodeMetaRef::reportMetadataChange");
2216 // Exported functions
2218 // garbage collector
2219 static int gc_object(lua_State *L) {
2220 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2225 // get_string(self, name)
2226 static int l_get_string(lua_State *L)
2228 NodeMetaRef *ref = checkobject(L, 1);
2229 std::string name = luaL_checkstring(L, 2);
2231 NodeMetadata *meta = getmeta(ref, false);
2233 lua_pushlstring(L, "", 0);
2236 std::string str = meta->getString(name);
2237 lua_pushlstring(L, str.c_str(), str.size());
2241 // set_string(self, name, var)
2242 static int l_set_string(lua_State *L)
2244 NodeMetaRef *ref = checkobject(L, 1);
2245 std::string name = luaL_checkstring(L, 2);
2247 const char *s = lua_tolstring(L, 3, &len);
2248 std::string str(s, len);
2250 NodeMetadata *meta = getmeta(ref, !str.empty());
2251 if(meta == NULL || str == meta->getString(name))
2253 meta->setString(name, str);
2254 reportMetadataChange(ref);
2258 // get_int(self, name)
2259 static int l_get_int(lua_State *L)
2261 NodeMetaRef *ref = checkobject(L, 1);
2262 std::string name = lua_tostring(L, 2);
2264 NodeMetadata *meta = getmeta(ref, false);
2266 lua_pushnumber(L, 0);
2269 std::string str = meta->getString(name);
2270 lua_pushnumber(L, stoi(str));
2274 // set_int(self, name, var)
2275 static int l_set_int(lua_State *L)
2277 NodeMetaRef *ref = checkobject(L, 1);
2278 std::string name = lua_tostring(L, 2);
2279 int a = lua_tointeger(L, 3);
2280 std::string str = itos(a);
2282 NodeMetadata *meta = getmeta(ref, true);
2283 if(meta == NULL || str == meta->getString(name))
2285 meta->setString(name, str);
2286 reportMetadataChange(ref);
2290 // get_float(self, name)
2291 static int l_get_float(lua_State *L)
2293 NodeMetaRef *ref = checkobject(L, 1);
2294 std::string name = lua_tostring(L, 2);
2296 NodeMetadata *meta = getmeta(ref, false);
2298 lua_pushnumber(L, 0);
2301 std::string str = meta->getString(name);
2302 lua_pushnumber(L, stof(str));
2306 // set_float(self, name, var)
2307 static int l_set_float(lua_State *L)
2309 NodeMetaRef *ref = checkobject(L, 1);
2310 std::string name = lua_tostring(L, 2);
2311 float a = lua_tonumber(L, 3);
2312 std::string str = ftos(a);
2314 NodeMetadata *meta = getmeta(ref, true);
2315 if(meta == NULL || str == meta->getString(name))
2317 meta->setString(name, str);
2318 reportMetadataChange(ref);
2322 // get_inventory(self)
2323 static int l_get_inventory(lua_State *L)
2325 NodeMetaRef *ref = checkobject(L, 1);
2326 getmeta(ref, true); // try to ensure the metadata exists
2327 InvRef::createNodeMeta(L, ref->m_p);
2332 static int l_to_table(lua_State *L)
2334 NodeMetaRef *ref = checkobject(L, 1);
2336 NodeMetadata *meta = getmeta(ref, true);
2345 std::map<std::string, std::string> fields = meta->getStrings();
2346 for(std::map<std::string, std::string>::const_iterator
2347 i = fields.begin(); i != fields.end(); i++){
2348 const std::string &name = i->first;
2349 const std::string &value = i->second;
2350 lua_pushlstring(L, name.c_str(), name.size());
2351 lua_pushlstring(L, value.c_str(), value.size());
2352 lua_settable(L, -3);
2355 lua_setfield(L, -2, "fields");
2358 Inventory *inv = meta->getInventory();
2360 std::vector<const InventoryList*> lists = inv->getLists();
2361 for(std::vector<const InventoryList*>::const_iterator
2362 i = lists.begin(); i != lists.end(); i++){
2363 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2364 lua_setfield(L, -2, (*i)->getName().c_str());
2367 lua_setfield(L, -2, "inventory");
2371 // from_table(self, table)
2372 static int l_from_table(lua_State *L)
2374 NodeMetaRef *ref = checkobject(L, 1);
2377 if(lua_isnil(L, base)){
2379 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2380 lua_pushboolean(L, true);
2384 // Has metadata; clear old one first
2385 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2386 // Create new metadata
2387 NodeMetadata *meta = getmeta(ref, true);
2389 lua_getfield(L, base, "fields");
2390 int fieldstable = lua_gettop(L);
2392 while(lua_next(L, fieldstable) != 0){
2393 // key at index -2 and value at index -1
2394 std::string name = lua_tostring(L, -2);
2396 const char *cs = lua_tolstring(L, -1, &cl);
2397 std::string value(cs, cl);
2398 meta->setString(name, value);
2399 lua_pop(L, 1); // removes value, keeps key for next iteration
2402 Inventory *inv = meta->getInventory();
2403 lua_getfield(L, base, "inventory");
2404 int inventorytable = lua_gettop(L);
2406 while(lua_next(L, inventorytable) != 0){
2407 // key at index -2 and value at index -1
2408 std::string name = lua_tostring(L, -2);
2409 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2410 lua_pop(L, 1); // removes value, keeps key for next iteration
2412 reportMetadataChange(ref);
2413 lua_pushboolean(L, true);
2418 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2428 // Creates an NodeMetaRef and leaves it on top of stack
2429 // Not callable from Lua; all references are created on the C side.
2430 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2432 NodeMetaRef *o = new NodeMetaRef(p, env);
2433 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2434 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2435 luaL_getmetatable(L, className);
2436 lua_setmetatable(L, -2);
2439 static void Register(lua_State *L)
2442 int methodtable = lua_gettop(L);
2443 luaL_newmetatable(L, className);
2444 int metatable = lua_gettop(L);
2446 lua_pushliteral(L, "__metatable");
2447 lua_pushvalue(L, methodtable);
2448 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2450 lua_pushliteral(L, "__index");
2451 lua_pushvalue(L, methodtable);
2452 lua_settable(L, metatable);
2454 lua_pushliteral(L, "__gc");
2455 lua_pushcfunction(L, gc_object);
2456 lua_settable(L, metatable);
2458 lua_pop(L, 1); // drop metatable
2460 luaL_openlib(L, 0, methods, 0); // fill methodtable
2461 lua_pop(L, 1); // drop methodtable
2463 // Cannot be created from Lua
2464 //lua_register(L, className, create_object);
2467 const char NodeMetaRef::className[] = "NodeMetaRef";
2468 const luaL_reg NodeMetaRef::methods[] = {
2469 method(NodeMetaRef, get_string),
2470 method(NodeMetaRef, set_string),
2471 method(NodeMetaRef, get_int),
2472 method(NodeMetaRef, set_int),
2473 method(NodeMetaRef, get_float),
2474 method(NodeMetaRef, set_float),
2475 method(NodeMetaRef, get_inventory),
2476 method(NodeMetaRef, to_table),
2477 method(NodeMetaRef, from_table),
2488 ServerActiveObject *m_object;
2490 static const char className[];
2491 static const luaL_reg methods[];
2493 static ObjectRef *checkobject(lua_State *L, int narg)
2495 luaL_checktype(L, narg, LUA_TUSERDATA);
2496 void *ud = luaL_checkudata(L, narg, className);
2497 if(!ud) luaL_typerror(L, narg, className);
2498 return *(ObjectRef**)ud; // unbox pointer
2501 static ServerActiveObject* getobject(ObjectRef *ref)
2503 ServerActiveObject *co = ref->m_object;
2507 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2509 ServerActiveObject *obj = getobject(ref);
2512 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2514 return (LuaEntitySAO*)obj;
2517 static PlayerSAO* getplayersao(ObjectRef *ref)
2519 ServerActiveObject *obj = getobject(ref);
2522 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2524 return (PlayerSAO*)obj;
2527 static Player* getplayer(ObjectRef *ref)
2529 PlayerSAO *playersao = getplayersao(ref);
2530 if(playersao == NULL)
2532 return playersao->getPlayer();
2535 // Exported functions
2537 // garbage collector
2538 static int gc_object(lua_State *L) {
2539 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2540 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2546 static int l_remove(lua_State *L)
2548 ObjectRef *ref = checkobject(L, 1);
2549 ServerActiveObject *co = getobject(ref);
2550 if(co == NULL) return 0;
2551 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2552 co->m_removed = true;
2557 // returns: {x=num, y=num, z=num}
2558 static int l_getpos(lua_State *L)
2560 ObjectRef *ref = checkobject(L, 1);
2561 ServerActiveObject *co = getobject(ref);
2562 if(co == NULL) return 0;
2563 v3f pos = co->getBasePosition() / BS;
2565 lua_pushnumber(L, pos.X);
2566 lua_setfield(L, -2, "x");
2567 lua_pushnumber(L, pos.Y);
2568 lua_setfield(L, -2, "y");
2569 lua_pushnumber(L, pos.Z);
2570 lua_setfield(L, -2, "z");
2574 // setpos(self, pos)
2575 static int l_setpos(lua_State *L)
2577 ObjectRef *ref = checkobject(L, 1);
2578 //LuaEntitySAO *co = getluaobject(ref);
2579 ServerActiveObject *co = getobject(ref);
2580 if(co == NULL) return 0;
2582 v3f pos = checkFloatPos(L, 2);
2588 // moveto(self, pos, continuous=false)
2589 static int l_moveto(lua_State *L)
2591 ObjectRef *ref = checkobject(L, 1);
2592 //LuaEntitySAO *co = getluaobject(ref);
2593 ServerActiveObject *co = getobject(ref);
2594 if(co == NULL) return 0;
2596 v3f pos = checkFloatPos(L, 2);
2598 bool continuous = lua_toboolean(L, 3);
2600 co->moveTo(pos, continuous);
2604 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2605 static int l_punch(lua_State *L)
2607 ObjectRef *ref = checkobject(L, 1);
2608 ObjectRef *puncher_ref = checkobject(L, 2);
2609 ServerActiveObject *co = getobject(ref);
2610 ServerActiveObject *puncher = getobject(puncher_ref);
2611 if(co == NULL) return 0;
2612 if(puncher == NULL) return 0;
2614 if(lua_type(L, 5) != LUA_TTABLE)
2615 dir = co->getBasePosition() - puncher->getBasePosition();
2617 dir = read_v3f(L, 5);
2618 float time_from_last_punch = 1000000;
2619 if(lua_isnumber(L, 3))
2620 time_from_last_punch = lua_tonumber(L, 3);
2621 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2624 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2628 // right_click(self, clicker); clicker = an another ObjectRef
2629 static int l_right_click(lua_State *L)
2631 ObjectRef *ref = checkobject(L, 1);
2632 ObjectRef *ref2 = checkobject(L, 2);
2633 ServerActiveObject *co = getobject(ref);
2634 ServerActiveObject *co2 = getobject(ref2);
2635 if(co == NULL) return 0;
2636 if(co2 == NULL) return 0;
2638 co->rightClick(co2);
2643 // hp = number of hitpoints (2 * number of hearts)
2645 static int l_set_hp(lua_State *L)
2647 ObjectRef *ref = checkobject(L, 1);
2648 luaL_checknumber(L, 2);
2649 ServerActiveObject *co = getobject(ref);
2650 if(co == NULL) return 0;
2651 int hp = lua_tonumber(L, 2);
2652 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2653 <<" hp="<<hp<<std::endl;*/
2661 // returns: number of hitpoints (2 * number of hearts)
2662 // 0 if not applicable to this type of object
2663 static int l_get_hp(lua_State *L)
2665 ObjectRef *ref = checkobject(L, 1);
2666 ServerActiveObject *co = getobject(ref);
2669 lua_pushnumber(L, 1);
2672 int hp = co->getHP();
2673 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2674 <<" hp="<<hp<<std::endl;*/
2676 lua_pushnumber(L, hp);
2680 // get_inventory(self)
2681 static int l_get_inventory(lua_State *L)
2683 ObjectRef *ref = checkobject(L, 1);
2684 ServerActiveObject *co = getobject(ref);
2685 if(co == NULL) return 0;
2687 InventoryLocation loc = co->getInventoryLocation();
2688 if(get_server(L)->getInventory(loc) != NULL)
2689 InvRef::create(L, loc);
2691 lua_pushnil(L); // An object may have no inventory (nil)
2695 // get_wield_list(self)
2696 static int l_get_wield_list(lua_State *L)
2698 ObjectRef *ref = checkobject(L, 1);
2699 ServerActiveObject *co = getobject(ref);
2700 if(co == NULL) return 0;
2702 lua_pushstring(L, co->getWieldList().c_str());
2706 // get_wield_index(self)
2707 static int l_get_wield_index(lua_State *L)
2709 ObjectRef *ref = checkobject(L, 1);
2710 ServerActiveObject *co = getobject(ref);
2711 if(co == NULL) return 0;
2713 lua_pushinteger(L, co->getWieldIndex() + 1);
2717 // get_wielded_item(self)
2718 static int l_get_wielded_item(lua_State *L)
2720 ObjectRef *ref = checkobject(L, 1);
2721 ServerActiveObject *co = getobject(ref);
2724 LuaItemStack::create(L, ItemStack());
2728 LuaItemStack::create(L, co->getWieldedItem());
2732 // set_wielded_item(self, itemstack or itemstring or table or nil)
2733 static int l_set_wielded_item(lua_State *L)
2735 ObjectRef *ref = checkobject(L, 1);
2736 ServerActiveObject *co = getobject(ref);
2737 if(co == NULL) return 0;
2739 ItemStack item = read_item(L, 2);
2740 bool success = co->setWieldedItem(item);
2741 lua_pushboolean(L, success);
2745 // set_armor_groups(self, groups)
2746 static int l_set_armor_groups(lua_State *L)
2748 ObjectRef *ref = checkobject(L, 1);
2749 ServerActiveObject *co = getobject(ref);
2750 if(co == NULL) return 0;
2752 ItemGroupList groups;
2753 read_groups(L, 2, groups);
2754 co->setArmorGroups(groups);
2758 // set_animation(self, frame_range, frame_speed, frame_blend)
2759 static int l_set_animation(lua_State *L)
2761 ObjectRef *ref = checkobject(L, 1);
2762 ServerActiveObject *co = getobject(ref);
2763 if(co == NULL) return 0;
2765 v2f frames = v2f(1, 1);
2766 if(!lua_isnil(L, 2))
2767 frames = read_v2f(L, 2);
2768 float frame_speed = 15;
2769 if(!lua_isnil(L, 3))
2770 frame_speed = lua_tonumber(L, 3);
2771 float frame_blend = 0;
2772 if(!lua_isnil(L, 4))
2773 frame_blend = lua_tonumber(L, 4);
2774 co->setAnimation(frames, frame_speed, frame_blend);
2778 // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2779 static int l_set_bone_position(lua_State *L)
2781 ObjectRef *ref = checkobject(L, 1);
2782 ServerActiveObject *co = getobject(ref);
2783 if(co == NULL) return 0;
2785 std::string bone = "";
2786 if(!lua_isnil(L, 2))
2787 bone = lua_tostring(L, 2);
2788 v3f position = v3f(0, 0, 0);
2789 if(!lua_isnil(L, 3))
2790 position = read_v3f(L, 3);
2791 v3f rotation = v3f(0, 0, 0);
2792 if(!lua_isnil(L, 4))
2793 rotation = read_v3f(L, 4);
2794 co->setBonePosition(bone, position, rotation);
2798 // set_attach(self, parent, bone, position, rotation)
2799 static int l_set_attach(lua_State *L)
2801 ObjectRef *ref = checkobject(L, 1);
2802 ObjectRef *parent_ref = checkobject(L, 2);
2803 ServerActiveObject *co = getobject(ref);
2804 ServerActiveObject *parent = getobject(parent_ref);
2805 if(co == NULL) return 0;
2806 if(parent == NULL) return 0;
2808 std::string bone = "";
2809 if(!lua_isnil(L, 3))
2810 bone = lua_tostring(L, 3);
2811 v3f position = v3f(0, 0, 0);
2812 if(!lua_isnil(L, 4))
2813 position = read_v3f(L, 4);
2814 v3f rotation = v3f(0, 0, 0);
2815 if(!lua_isnil(L, 5))
2816 rotation = read_v3f(L, 5);
2817 co->setAttachment(parent->getId(), bone, position, rotation);
2822 static int l_set_detach(lua_State *L)
2824 ObjectRef *ref = checkobject(L, 1);
2825 ServerActiveObject *co = getobject(ref);
2826 if(co == NULL) return 0;
2828 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2832 // set_properties(self, properties)
2833 static int l_set_properties(lua_State *L)
2835 ObjectRef *ref = checkobject(L, 1);
2836 ServerActiveObject *co = getobject(ref);
2837 if(co == NULL) return 0;
2838 ObjectProperties *prop = co->accessObjectProperties();
2841 read_object_properties(L, 2, prop);
2842 co->notifyObjectPropertiesModified();
2846 /* LuaEntitySAO-only */
2848 // setvelocity(self, {x=num, y=num, z=num})
2849 static int l_setvelocity(lua_State *L)
2851 ObjectRef *ref = checkobject(L, 1);
2852 LuaEntitySAO *co = getluaobject(ref);
2853 if(co == NULL) return 0;
2854 v3f pos = checkFloatPos(L, 2);
2856 co->setVelocity(pos);
2860 // getvelocity(self)
2861 static int l_getvelocity(lua_State *L)
2863 ObjectRef *ref = checkobject(L, 1);
2864 LuaEntitySAO *co = getluaobject(ref);
2865 if(co == NULL) return 0;
2867 v3f v = co->getVelocity();
2872 // setacceleration(self, {x=num, y=num, z=num})
2873 static int l_setacceleration(lua_State *L)
2875 ObjectRef *ref = checkobject(L, 1);
2876 LuaEntitySAO *co = getluaobject(ref);
2877 if(co == NULL) return 0;
2879 v3f pos = checkFloatPos(L, 2);
2881 co->setAcceleration(pos);
2885 // getacceleration(self)
2886 static int l_getacceleration(lua_State *L)
2888 ObjectRef *ref = checkobject(L, 1);
2889 LuaEntitySAO *co = getluaobject(ref);
2890 if(co == NULL) return 0;
2892 v3f v = co->getAcceleration();
2897 // setyaw(self, radians)
2898 static int l_setyaw(lua_State *L)
2900 ObjectRef *ref = checkobject(L, 1);
2901 LuaEntitySAO *co = getluaobject(ref);
2902 if(co == NULL) return 0;
2903 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2910 static int l_getyaw(lua_State *L)
2912 ObjectRef *ref = checkobject(L, 1);
2913 LuaEntitySAO *co = getluaobject(ref);
2914 if(co == NULL) return 0;
2916 float yaw = co->getYaw() * core::DEGTORAD;
2917 lua_pushnumber(L, yaw);
2921 // settexturemod(self, mod)
2922 static int l_settexturemod(lua_State *L)
2924 ObjectRef *ref = checkobject(L, 1);
2925 LuaEntitySAO *co = getluaobject(ref);
2926 if(co == NULL) return 0;
2928 std::string mod = luaL_checkstring(L, 2);
2929 co->setTextureMod(mod);
2933 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2934 // select_horiz_by_yawpitch=false)
2935 static int l_setsprite(lua_State *L)
2937 ObjectRef *ref = checkobject(L, 1);
2938 LuaEntitySAO *co = getluaobject(ref);
2939 if(co == NULL) return 0;
2942 if(!lua_isnil(L, 2))
2943 p = read_v2s16(L, 2);
2945 if(!lua_isnil(L, 3))
2946 num_frames = lua_tonumber(L, 3);
2947 float framelength = 0.2;
2948 if(!lua_isnil(L, 4))
2949 framelength = lua_tonumber(L, 4);
2950 bool select_horiz_by_yawpitch = false;
2951 if(!lua_isnil(L, 5))
2952 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2953 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2958 // get_entity_name(self)
2959 static int l_get_entity_name(lua_State *L)
2961 ObjectRef *ref = checkobject(L, 1);
2962 LuaEntitySAO *co = getluaobject(ref);
2963 if(co == NULL) return 0;
2965 std::string name = co->getName();
2966 lua_pushstring(L, name.c_str());
2970 // get_luaentity(self)
2971 static int l_get_luaentity(lua_State *L)
2973 ObjectRef *ref = checkobject(L, 1);
2974 LuaEntitySAO *co = getluaobject(ref);
2975 if(co == NULL) return 0;
2977 luaentity_get(L, co->getId());
2984 static int l_is_player(lua_State *L)
2986 ObjectRef *ref = checkobject(L, 1);
2987 Player *player = getplayer(ref);
2988 lua_pushboolean(L, (player != NULL));
2992 // get_player_name(self)
2993 static int l_get_player_name(lua_State *L)
2995 ObjectRef *ref = checkobject(L, 1);
2996 Player *player = getplayer(ref);
2998 lua_pushlstring(L, "", 0);
3002 lua_pushstring(L, player->getName());
3006 // get_look_dir(self)
3007 static int l_get_look_dir(lua_State *L)
3009 ObjectRef *ref = checkobject(L, 1);
3010 Player *player = getplayer(ref);
3011 if(player == NULL) return 0;
3013 float pitch = player->getRadPitch();
3014 float yaw = player->getRadYaw();
3015 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
3020 // get_look_pitch(self)
3021 static int l_get_look_pitch(lua_State *L)
3023 ObjectRef *ref = checkobject(L, 1);
3024 Player *player = getplayer(ref);
3025 if(player == NULL) return 0;
3027 lua_pushnumber(L, player->getRadPitch());
3031 // get_look_yaw(self)
3032 static int l_get_look_yaw(lua_State *L)
3034 ObjectRef *ref = checkobject(L, 1);
3035 Player *player = getplayer(ref);
3036 if(player == NULL) return 0;
3038 lua_pushnumber(L, player->getRadYaw());
3042 // set_inventory_formspec(self, formspec)
3043 static int l_set_inventory_formspec(lua_State *L)
3045 ObjectRef *ref = checkobject(L, 1);
3046 Player *player = getplayer(ref);
3047 if(player == NULL) return 0;
3048 std::string formspec = luaL_checkstring(L, 2);
3050 player->inventory_formspec = formspec;
3051 get_server(L)->reportInventoryFormspecModified(player->getName());
3052 lua_pushboolean(L, true);
3056 // get_inventory_formspec(self) -> formspec
3057 static int l_get_inventory_formspec(lua_State *L)
3059 ObjectRef *ref = checkobject(L, 1);
3060 Player *player = getplayer(ref);
3061 if(player == NULL) return 0;
3063 std::string formspec = player->inventory_formspec;
3064 lua_pushlstring(L, formspec.c_str(), formspec.size());
3068 // get_player_control(self)
3069 static int l_get_player_control(lua_State *L)
3071 ObjectRef *ref = checkobject(L, 1);
3072 Player *player = getplayer(ref);
3074 lua_pushlstring(L, "", 0);
3078 PlayerControl control = player->getPlayerControl();
3080 lua_pushboolean(L, control.up);
3081 lua_setfield(L, -2, "up");
3082 lua_pushboolean(L, control.down);
3083 lua_setfield(L, -2, "down");
3084 lua_pushboolean(L, control.left);
3085 lua_setfield(L, -2, "left");
3086 lua_pushboolean(L, control.right);
3087 lua_setfield(L, -2, "right");
3088 lua_pushboolean(L, control.jump);
3089 lua_setfield(L, -2, "jump");
3090 lua_pushboolean(L, control.aux1);
3091 lua_setfield(L, -2, "aux1");
3092 lua_pushboolean(L, control.sneak);
3093 lua_setfield(L, -2, "sneak");
3094 lua_pushboolean(L, control.LMB);
3095 lua_setfield(L, -2, "LMB");
3096 lua_pushboolean(L, control.RMB);
3097 lua_setfield(L, -2, "RMB");
3101 // get_player_control_bits(self)
3102 static int l_get_player_control_bits(lua_State *L)
3104 ObjectRef *ref = checkobject(L, 1);
3105 Player *player = getplayer(ref);
3107 lua_pushlstring(L, "", 0);
3111 lua_pushnumber(L, player->keyPressed);
3116 ObjectRef(ServerActiveObject *object):
3119 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3125 infostream<<"ObjectRef destructing for id="
3126 <<m_object->getId()<<std::endl;
3128 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3131 // Creates an ObjectRef and leaves it on top of stack
3132 // Not callable from Lua; all references are created on the C side.
3133 static void create(lua_State *L, ServerActiveObject *object)
3135 ObjectRef *o = new ObjectRef(object);
3136 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3137 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3138 luaL_getmetatable(L, className);
3139 lua_setmetatable(L, -2);
3142 static void set_null(lua_State *L)
3144 ObjectRef *o = checkobject(L, -1);
3148 static void Register(lua_State *L)
3151 int methodtable = lua_gettop(L);
3152 luaL_newmetatable(L, className);
3153 int metatable = lua_gettop(L);
3155 lua_pushliteral(L, "__metatable");
3156 lua_pushvalue(L, methodtable);
3157 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3159 lua_pushliteral(L, "__index");
3160 lua_pushvalue(L, methodtable);
3161 lua_settable(L, metatable);
3163 lua_pushliteral(L, "__gc");
3164 lua_pushcfunction(L, gc_object);
3165 lua_settable(L, metatable);
3167 lua_pop(L, 1); // drop metatable
3169 luaL_openlib(L, 0, methods, 0); // fill methodtable
3170 lua_pop(L, 1); // drop methodtable
3172 // Cannot be created from Lua
3173 //lua_register(L, className, create_object);
3176 const char ObjectRef::className[] = "ObjectRef";
3177 const luaL_reg ObjectRef::methods[] = {
3178 // ServerActiveObject
3179 method(ObjectRef, remove),
3180 method(ObjectRef, getpos),
3181 method(ObjectRef, setpos),
3182 method(ObjectRef, moveto),
3183 method(ObjectRef, punch),
3184 method(ObjectRef, right_click),
3185 method(ObjectRef, set_hp),
3186 method(ObjectRef, get_hp),
3187 method(ObjectRef, get_inventory),
3188 method(ObjectRef, get_wield_list),
3189 method(ObjectRef, get_wield_index),
3190 method(ObjectRef, get_wielded_item),
3191 method(ObjectRef, set_wielded_item),
3192 method(ObjectRef, set_armor_groups),
3193 method(ObjectRef, set_animation),
3194 method(ObjectRef, set_bone_position),
3195 method(ObjectRef, set_attach),
3196 method(ObjectRef, set_detach),
3197 method(ObjectRef, set_properties),
3198 // LuaEntitySAO-only
3199 method(ObjectRef, setvelocity),
3200 method(ObjectRef, getvelocity),
3201 method(ObjectRef, setacceleration),
3202 method(ObjectRef, getacceleration),
3203 method(ObjectRef, setyaw),
3204 method(ObjectRef, getyaw),
3205 method(ObjectRef, settexturemod),
3206 method(ObjectRef, setsprite),
3207 method(ObjectRef, get_entity_name),
3208 method(ObjectRef, get_luaentity),
3210 method(ObjectRef, is_player),
3211 method(ObjectRef, get_player_name),
3212 method(ObjectRef, get_look_dir),
3213 method(ObjectRef, get_look_pitch),
3214 method(ObjectRef, get_look_yaw),
3215 method(ObjectRef, set_inventory_formspec),
3216 method(ObjectRef, get_inventory_formspec),
3217 method(ObjectRef, get_player_control),
3218 method(ObjectRef, get_player_control_bits),
3222 // Creates a new anonymous reference if cobj=NULL or id=0
3223 static void objectref_get_or_create(lua_State *L,
3224 ServerActiveObject *cobj)
3226 if(cobj == NULL || cobj->getId() == 0){
3227 ObjectRef::create(L, cobj);
3229 objectref_get(L, cobj->getId());
3238 class LuaPerlinNoise
3245 static const char className[];
3246 static const luaL_reg methods[];
3248 // Exported functions
3250 // garbage collector
3251 static int gc_object(lua_State *L)
3253 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3258 static int l_get2d(lua_State *L)
3260 LuaPerlinNoise *o = checkobject(L, 1);
3261 v2f pos2d = read_v2f(L,2);
3262 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3263 lua_pushnumber(L, val);
3266 static int l_get3d(lua_State *L)
3268 LuaPerlinNoise *o = checkobject(L, 1);
3269 v3f pos3d = read_v3f(L,2);
3270 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3271 lua_pushnumber(L, val);
3276 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3280 persistence(a_persistence),
3289 // LuaPerlinNoise(seed, octaves, persistence, scale)
3290 // Creates an LuaPerlinNoise and leaves it on top of stack
3291 static int create_object(lua_State *L)
3293 int seed = luaL_checkint(L, 1);
3294 int octaves = luaL_checkint(L, 2);
3295 double persistence = luaL_checknumber(L, 3);
3296 double scale = luaL_checknumber(L, 4);
3297 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3298 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3299 luaL_getmetatable(L, className);
3300 lua_setmetatable(L, -2);
3304 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3306 luaL_checktype(L, narg, LUA_TUSERDATA);
3307 void *ud = luaL_checkudata(L, narg, className);
3308 if(!ud) luaL_typerror(L, narg, className);
3309 return *(LuaPerlinNoise**)ud; // unbox pointer
3312 static void Register(lua_State *L)
3315 int methodtable = lua_gettop(L);
3316 luaL_newmetatable(L, className);
3317 int metatable = lua_gettop(L);
3319 lua_pushliteral(L, "__metatable");
3320 lua_pushvalue(L, methodtable);
3321 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3323 lua_pushliteral(L, "__index");
3324 lua_pushvalue(L, methodtable);
3325 lua_settable(L, metatable);
3327 lua_pushliteral(L, "__gc");
3328 lua_pushcfunction(L, gc_object);
3329 lua_settable(L, metatable);
3331 lua_pop(L, 1); // drop metatable
3333 luaL_openlib(L, 0, methods, 0); // fill methodtable
3334 lua_pop(L, 1); // drop methodtable
3336 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3337 lua_register(L, className, create_object);
3340 const char LuaPerlinNoise::className[] = "PerlinNoise";
3341 const luaL_reg LuaPerlinNoise::methods[] = {
3342 method(LuaPerlinNoise, get2d),
3343 method(LuaPerlinNoise, get3d),
3355 ServerEnvironment *m_env;
3357 static const char className[];
3358 static const luaL_reg methods[];
3360 static int gc_object(lua_State *L) {
3361 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3366 static NodeTimerRef *checkobject(lua_State *L, int narg)
3368 luaL_checktype(L, narg, LUA_TUSERDATA);
3369 void *ud = luaL_checkudata(L, narg, className);
3370 if(!ud) luaL_typerror(L, narg, className);
3371 return *(NodeTimerRef**)ud; // unbox pointer
3374 static int l_set(lua_State *L)
3376 NodeTimerRef *o = checkobject(L, 1);
3377 ServerEnvironment *env = o->m_env;
3378 if(env == NULL) return 0;
3379 f32 t = luaL_checknumber(L,2);
3380 f32 e = luaL_checknumber(L,3);
3381 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3385 static int l_start(lua_State *L)
3387 NodeTimerRef *o = checkobject(L, 1);
3388 ServerEnvironment *env = o->m_env;
3389 if(env == NULL) return 0;
3390 f32 t = luaL_checknumber(L,2);
3391 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3395 static int l_stop(lua_State *L)
3397 NodeTimerRef *o = checkobject(L, 1);
3398 ServerEnvironment *env = o->m_env;
3399 if(env == NULL) return 0;
3400 env->getMap().removeNodeTimer(o->m_p);
3404 static int l_is_started(lua_State *L)
3406 NodeTimerRef *o = checkobject(L, 1);
3407 ServerEnvironment *env = o->m_env;
3408 if(env == NULL) return 0;
3410 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3411 lua_pushboolean(L,(t.timeout != 0));
3415 static int l_get_timeout(lua_State *L)
3417 NodeTimerRef *o = checkobject(L, 1);
3418 ServerEnvironment *env = o->m_env;
3419 if(env == NULL) return 0;
3421 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3422 lua_pushnumber(L,t.timeout);
3426 static int l_get_elapsed(lua_State *L)
3428 NodeTimerRef *o = checkobject(L, 1);
3429 ServerEnvironment *env = o->m_env;
3430 if(env == NULL) return 0;
3432 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3433 lua_pushnumber(L,t.elapsed);
3438 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3448 // Creates an NodeTimerRef and leaves it on top of stack
3449 // Not callable from Lua; all references are created on the C side.
3450 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3452 NodeTimerRef *o = new NodeTimerRef(p, env);
3453 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3454 luaL_getmetatable(L, className);
3455 lua_setmetatable(L, -2);
3458 static void set_null(lua_State *L)
3460 NodeTimerRef *o = checkobject(L, -1);
3464 static void Register(lua_State *L)
3467 int methodtable = lua_gettop(L);
3468 luaL_newmetatable(L, className);
3469 int metatable = lua_gettop(L);
3471 lua_pushliteral(L, "__metatable");
3472 lua_pushvalue(L, methodtable);
3473 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3475 lua_pushliteral(L, "__index");
3476 lua_pushvalue(L, methodtable);
3477 lua_settable(L, metatable);
3479 lua_pushliteral(L, "__gc");
3480 lua_pushcfunction(L, gc_object);
3481 lua_settable(L, metatable);
3483 lua_pop(L, 1); // drop metatable
3485 luaL_openlib(L, 0, methods, 0); // fill methodtable
3486 lua_pop(L, 1); // drop methodtable
3488 // Cannot be created from Lua
3489 //lua_register(L, className, create_object);
3492 const char NodeTimerRef::className[] = "NodeTimerRef";
3493 const luaL_reg NodeTimerRef::methods[] = {
3494 method(NodeTimerRef, start),
3495 method(NodeTimerRef, set),
3496 method(NodeTimerRef, stop),
3497 method(NodeTimerRef, is_started),
3498 method(NodeTimerRef, get_timeout),
3499 method(NodeTimerRef, get_elapsed),
3510 ServerEnvironment *m_env;
3512 static const char className[];
3513 static const luaL_reg methods[];
3515 static int gc_object(lua_State *L) {
3516 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3521 static EnvRef *checkobject(lua_State *L, int narg)
3523 luaL_checktype(L, narg, LUA_TUSERDATA);
3524 void *ud = luaL_checkudata(L, narg, className);
3525 if(!ud) luaL_typerror(L, narg, className);
3526 return *(EnvRef**)ud; // unbox pointer
3529 // Exported functions
3531 // EnvRef:set_node(pos, node)
3532 // pos = {x=num, y=num, z=num}
3533 static int l_set_node(lua_State *L)
3535 EnvRef *o = checkobject(L, 1);
3536 ServerEnvironment *env = o->m_env;
3537 if(env == NULL) return 0;
3538 INodeDefManager *ndef = env->getGameDef()->ndef();
3540 v3s16 pos = read_v3s16(L, 2);
3541 MapNode n = readnode(L, 3, ndef);
3543 bool succeeded = env->setNode(pos, n);
3544 lua_pushboolean(L, succeeded);
3548 static int l_add_node(lua_State *L)
3550 return l_set_node(L);
3553 // EnvRef:remove_node(pos)
3554 // pos = {x=num, y=num, z=num}
3555 static int l_remove_node(lua_State *L)
3557 EnvRef *o = checkobject(L, 1);
3558 ServerEnvironment *env = o->m_env;
3559 if(env == NULL) return 0;
3560 INodeDefManager *ndef = env->getGameDef()->ndef();
3562 v3s16 pos = read_v3s16(L, 2);
3564 bool succeeded = env->removeNode(pos);
3565 lua_pushboolean(L, succeeded);
3569 // EnvRef:get_node(pos)
3570 // pos = {x=num, y=num, z=num}
3571 static int l_get_node(lua_State *L)
3573 EnvRef *o = checkobject(L, 1);
3574 ServerEnvironment *env = o->m_env;
3575 if(env == NULL) return 0;
3577 v3s16 pos = read_v3s16(L, 2);
3579 MapNode n = env->getMap().getNodeNoEx(pos);
3581 pushnode(L, n, env->getGameDef()->ndef());
3585 // EnvRef:get_node_or_nil(pos)
3586 // pos = {x=num, y=num, z=num}
3587 static int l_get_node_or_nil(lua_State *L)
3589 EnvRef *o = checkobject(L, 1);
3590 ServerEnvironment *env = o->m_env;
3591 if(env == NULL) return 0;
3593 v3s16 pos = read_v3s16(L, 2);
3596 MapNode n = env->getMap().getNode(pos);
3598 pushnode(L, n, env->getGameDef()->ndef());
3600 } catch(InvalidPositionException &e)
3607 // EnvRef:get_node_light(pos, timeofday)
3608 // pos = {x=num, y=num, z=num}
3609 // timeofday: nil = current time, 0 = night, 0.5 = day
3610 static int l_get_node_light(lua_State *L)
3612 EnvRef *o = checkobject(L, 1);
3613 ServerEnvironment *env = o->m_env;
3614 if(env == NULL) return 0;
3616 v3s16 pos = read_v3s16(L, 2);
3617 u32 time_of_day = env->getTimeOfDay();
3618 if(lua_isnumber(L, 3))
3619 time_of_day = 24000.0 * lua_tonumber(L, 3);
3620 time_of_day %= 24000;
3621 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3622 MapNode n = env->getMap().getNodeNoEx(pos);
3624 MapNode n = env->getMap().getNode(pos);
3625 INodeDefManager *ndef = env->getGameDef()->ndef();
3626 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3628 } catch(InvalidPositionException &e)
3635 // EnvRef:place_node(pos, node)
3636 // pos = {x=num, y=num, z=num}
3637 static int l_place_node(lua_State *L)
3639 EnvRef *o = checkobject(L, 1);
3640 ServerEnvironment *env = o->m_env;
3641 if(env == NULL) return 0;
3642 v3s16 pos = read_v3s16(L, 2);
3643 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3645 // Don't attempt to load non-loaded area as of now
3646 MapNode n_old = env->getMap().getNodeNoEx(pos);
3647 if(n_old.getContent() == CONTENT_IGNORE){
3648 lua_pushboolean(L, false);
3651 // Create item to place
3652 INodeDefManager *ndef = get_server(L)->ndef();
3653 IItemDefManager *idef = get_server(L)->idef();
3654 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3655 // Make pointed position
3656 PointedThing pointed;
3657 pointed.type = POINTEDTHING_NODE;
3658 pointed.node_abovesurface = pos;
3659 pointed.node_undersurface = pos + v3s16(0,-1,0);
3660 // Place it with a NULL placer (appears in Lua as a non-functional
3662 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3663 lua_pushboolean(L, success);
3667 // EnvRef:dig_node(pos)
3668 // pos = {x=num, y=num, z=num}
3669 static int l_dig_node(lua_State *L)
3671 EnvRef *o = checkobject(L, 1);
3672 ServerEnvironment *env = o->m_env;
3673 if(env == NULL) return 0;
3674 v3s16 pos = read_v3s16(L, 2);
3676 // Don't attempt to load non-loaded area as of now
3677 MapNode n = env->getMap().getNodeNoEx(pos);
3678 if(n.getContent() == CONTENT_IGNORE){
3679 lua_pushboolean(L, false);
3682 // Dig it out with a NULL digger (appears in Lua as a
3683 // non-functional ObjectRef)
3684 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3685 lua_pushboolean(L, success);
3689 // EnvRef:punch_node(pos)
3690 // pos = {x=num, y=num, z=num}
3691 static int l_punch_node(lua_State *L)
3693 EnvRef *o = checkobject(L, 1);
3694 ServerEnvironment *env = o->m_env;
3695 if(env == NULL) return 0;
3696 v3s16 pos = read_v3s16(L, 2);
3698 // Don't attempt to load non-loaded area as of now
3699 MapNode n = env->getMap().getNodeNoEx(pos);
3700 if(n.getContent() == CONTENT_IGNORE){
3701 lua_pushboolean(L, false);
3704 // Punch it with a NULL puncher (appears in Lua as a non-functional
3706 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3707 lua_pushboolean(L, success);
3711 // EnvRef:get_meta(pos)
3712 static int l_get_meta(lua_State *L)
3714 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3715 EnvRef *o = checkobject(L, 1);
3716 ServerEnvironment *env = o->m_env;
3717 if(env == NULL) return 0;
3719 v3s16 p = read_v3s16(L, 2);
3720 NodeMetaRef::create(L, p, env);
3724 // EnvRef:get_node_timer(pos)
3725 static int l_get_node_timer(lua_State *L)
3727 EnvRef *o = checkobject(L, 1);
3728 ServerEnvironment *env = o->m_env;
3729 if(env == NULL) return 0;
3731 v3s16 p = read_v3s16(L, 2);
3732 NodeTimerRef::create(L, p, env);
3736 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3737 // pos = {x=num, y=num, z=num}
3738 static int l_add_entity(lua_State *L)
3740 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3741 EnvRef *o = checkobject(L, 1);
3742 ServerEnvironment *env = o->m_env;
3743 if(env == NULL) return 0;
3745 v3f pos = checkFloatPos(L, 2);
3747 const char *name = luaL_checkstring(L, 3);
3749 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3750 int objectid = env->addActiveObject(obj);
3751 // If failed to add, return nothing (reads as nil)
3755 objectref_get_or_create(L, obj);
3759 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3760 // pos = {x=num, y=num, z=num}
3761 static int l_add_item(lua_State *L)
3763 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3764 EnvRef *o = checkobject(L, 1);
3765 ServerEnvironment *env = o->m_env;
3766 if(env == NULL) return 0;
3768 v3f pos = checkFloatPos(L, 2);
3770 ItemStack item = read_item(L, 3);
3771 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3773 // Use minetest.spawn_item to spawn a __builtin:item
3774 lua_getglobal(L, "minetest");
3775 lua_getfield(L, -1, "spawn_item");
3776 if(lua_isnil(L, -1))
3778 lua_pushvalue(L, 2);
3779 lua_pushstring(L, item.getItemString().c_str());
3780 if(lua_pcall(L, 2, 1, 0))
3781 script_error(L, "error: %s", lua_tostring(L, -1));
3783 /*lua_pushvalue(L, 1);
3784 lua_pushstring(L, "__builtin:item");
3785 lua_pushstring(L, item.getItemString().c_str());
3786 return l_add_entity(L);*/
3788 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3789 int objectid = env->addActiveObject(obj);
3790 // If failed to add, return nothing (reads as nil)
3794 objectref_get_or_create(L, obj);
3798 // EnvRef:add_rat(pos)
3799 // pos = {x=num, y=num, z=num}
3800 static int l_add_rat(lua_State *L)
3802 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3803 <<" Doing nothing."<<std::endl;
3807 // EnvRef:add_firefly(pos)
3808 // pos = {x=num, y=num, z=num}
3809 static int l_add_firefly(lua_State *L)
3811 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3812 <<" Doing nothing."<<std::endl;
3816 // EnvRef:get_player_by_name(name)
3817 static int l_get_player_by_name(lua_State *L)
3819 EnvRef *o = checkobject(L, 1);
3820 ServerEnvironment *env = o->m_env;
3821 if(env == NULL) return 0;
3823 const char *name = luaL_checkstring(L, 2);
3824 Player *player = env->getPlayer(name);
3829 PlayerSAO *sao = player->getPlayerSAO();
3834 // Put player on stack
3835 objectref_get_or_create(L, sao);
3839 // EnvRef:get_objects_inside_radius(pos, radius)
3840 static int l_get_objects_inside_radius(lua_State *L)
3842 // Get the table insert function
3843 lua_getglobal(L, "table");
3844 lua_getfield(L, -1, "insert");
3845 int table_insert = lua_gettop(L);
3847 EnvRef *o = checkobject(L, 1);
3848 ServerEnvironment *env = o->m_env;
3849 if(env == NULL) return 0;
3851 v3f pos = checkFloatPos(L, 2);
3852 float radius = luaL_checknumber(L, 3) * BS;
3853 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3855 int table = lua_gettop(L);
3856 for(std::set<u16>::const_iterator
3857 i = ids.begin(); i != ids.end(); i++){
3858 ServerActiveObject *obj = env->getActiveObject(*i);
3859 // Insert object reference into table
3860 lua_pushvalue(L, table_insert);
3861 lua_pushvalue(L, table);
3862 objectref_get_or_create(L, obj);
3863 if(lua_pcall(L, 2, 0, 0))
3864 script_error(L, "error: %s", lua_tostring(L, -1));
3869 // EnvRef:set_timeofday(val)
3871 static int l_set_timeofday(lua_State *L)
3873 EnvRef *o = checkobject(L, 1);
3874 ServerEnvironment *env = o->m_env;
3875 if(env == NULL) return 0;
3877 float timeofday_f = luaL_checknumber(L, 2);
3878 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3879 int timeofday_mh = (int)(timeofday_f * 24000.0);
3880 // This should be set directly in the environment but currently
3881 // such changes aren't immediately sent to the clients, so call
3882 // the server instead.
3883 //env->setTimeOfDay(timeofday_mh);
3884 get_server(L)->setTimeOfDay(timeofday_mh);
3888 // EnvRef:get_timeofday() -> 0...1
3889 static int l_get_timeofday(lua_State *L)
3891 EnvRef *o = checkobject(L, 1);
3892 ServerEnvironment *env = o->m_env;
3893 if(env == NULL) return 0;
3895 int timeofday_mh = env->getTimeOfDay();
3896 float timeofday_f = (float)timeofday_mh / 24000.0;
3897 lua_pushnumber(L, timeofday_f);
3902 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3903 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3904 static int l_find_node_near(lua_State *L)
3906 EnvRef *o = checkobject(L, 1);
3907 ServerEnvironment *env = o->m_env;
3908 if(env == NULL) return 0;
3909 INodeDefManager *ndef = get_server(L)->ndef();
3910 v3s16 pos = read_v3s16(L, 2);
3911 int radius = luaL_checkinteger(L, 3);
3912 std::set<content_t> filter;
3913 if(lua_istable(L, 4)){
3916 while(lua_next(L, table) != 0){
3917 // key at index -2 and value at index -1
3918 luaL_checktype(L, -1, LUA_TSTRING);
3919 ndef->getIds(lua_tostring(L, -1), filter);
3920 // removes value, keeps key for next iteration
3923 } else if(lua_isstring(L, 4)){
3924 ndef->getIds(lua_tostring(L, 4), filter);
3927 for(int d=1; d<=radius; d++){
3928 core::list<v3s16> list;
3929 getFacePositions(list, d);
3930 for(core::list<v3s16>::Iterator i = list.begin();
3931 i != list.end(); i++){
3932 v3s16 p = pos + (*i);
3933 content_t c = env->getMap().getNodeNoEx(p).getContent();
3934 if(filter.count(c) != 0){
3943 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3944 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3945 static int l_find_nodes_in_area(lua_State *L)
3947 EnvRef *o = checkobject(L, 1);
3948 ServerEnvironment *env = o->m_env;
3949 if(env == NULL) return 0;
3950 INodeDefManager *ndef = get_server(L)->ndef();
3951 v3s16 minp = read_v3s16(L, 2);
3952 v3s16 maxp = read_v3s16(L, 3);
3953 std::set<content_t> filter;
3954 if(lua_istable(L, 4)){
3957 while(lua_next(L, table) != 0){
3958 // key at index -2 and value at index -1
3959 luaL_checktype(L, -1, LUA_TSTRING);
3960 ndef->getIds(lua_tostring(L, -1), filter);
3961 // removes value, keeps key for next iteration
3964 } else if(lua_isstring(L, 4)){
3965 ndef->getIds(lua_tostring(L, 4), filter);
3968 // Get the table insert function
3969 lua_getglobal(L, "table");
3970 lua_getfield(L, -1, "insert");
3971 int table_insert = lua_gettop(L);
3974 int table = lua_gettop(L);
3975 for(s16 x=minp.X; x<=maxp.X; x++)
3976 for(s16 y=minp.Y; y<=maxp.Y; y++)
3977 for(s16 z=minp.Z; z<=maxp.Z; z++)
3980 content_t c = env->getMap().getNodeNoEx(p).getContent();
3981 if(filter.count(c) != 0){
3982 lua_pushvalue(L, table_insert);
3983 lua_pushvalue(L, table);
3985 if(lua_pcall(L, 2, 0, 0))
3986 script_error(L, "error: %s", lua_tostring(L, -1));
3992 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3993 // returns world-specific PerlinNoise
3994 static int l_get_perlin(lua_State *L)
3996 EnvRef *o = checkobject(L, 1);
3997 ServerEnvironment *env = o->m_env;
3998 if(env == NULL) return 0;
4000 int seeddiff = luaL_checkint(L, 2);
4001 int octaves = luaL_checkint(L, 3);
4002 double persistence = luaL_checknumber(L, 4);
4003 double scale = luaL_checknumber(L, 5);
4005 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
4006 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4007 luaL_getmetatable(L, "PerlinNoise");
4008 lua_setmetatable(L, -2);
4012 // EnvRef:clear_objects()
4013 // clear all objects in the environment
4014 static int l_clear_objects(lua_State *L)
4016 EnvRef *o = checkobject(L, 1);
4017 o->m_env->clearAllObjects();
4021 static int l_spawn_tree(lua_State *L)
4023 EnvRef *o = checkobject(L, 1);
4024 ServerEnvironment *env = o->m_env;
4025 if(env == NULL) return 0;
4026 v3s16 p0 = read_v3s16(L, 2);
4028 treegen::TreeDef tree_def;
4029 std::string trunk,leaves,fruit;
4030 INodeDefManager *ndef = env->getGameDef()->ndef();
4032 if(lua_istable(L, 3))
4034 getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4035 getstringfield(L, 3, "rules_a", tree_def.rules_a);
4036 getstringfield(L, 3, "rules_b", tree_def.rules_b);
4037 getstringfield(L, 3, "rules_c", tree_def.rules_c);
4038 getstringfield(L, 3, "rules_d", tree_def.rules_d);
4039 getstringfield(L, 3, "trunk", trunk);
4040 tree_def.trunknode=ndef->getId(trunk);
4041 getstringfield(L, 3, "leaves", leaves);
4042 tree_def.leavesnode=ndef->getId(leaves);
4043 tree_def.leaves2_chance=0;
4044 getstringfield(L, 3, "leaves2", leaves);
4047 tree_def.leaves2node=ndef->getId(leaves);
4048 getintfield(L, 3, "leaves2_chance", tree_def.leaves2_chance);
4050 getintfield(L, 3, "angle", tree_def.angle);
4051 getintfield(L, 3, "iterations", tree_def.iterations);
4052 getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4053 getstringfield(L, 3, "trunk_type", tree_def.trunk_type);
4054 getboolfield(L, 3, "thin_branches", tree_def.thin_branches);
4055 tree_def.fruit_chance=0;
4056 getstringfield(L, 3, "fruit", fruit);
4059 tree_def.fruitnode=ndef->getId(fruit);
4060 getintfield(L, 3, "fruit_chance",tree_def.fruit_chance);
4065 treegen::spawn_ltree (env, p0, ndef, tree_def);
4070 EnvRef(ServerEnvironment *env):
4073 //infostream<<"EnvRef created"<<std::endl;
4078 //infostream<<"EnvRef destructing"<<std::endl;
4081 // Creates an EnvRef and leaves it on top of stack
4082 // Not callable from Lua; all references are created on the C side.
4083 static void create(lua_State *L, ServerEnvironment *env)
4085 EnvRef *o = new EnvRef(env);
4086 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4087 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4088 luaL_getmetatable(L, className);
4089 lua_setmetatable(L, -2);
4092 static void set_null(lua_State *L)
4094 EnvRef *o = checkobject(L, -1);
4098 static void Register(lua_State *L)
4101 int methodtable = lua_gettop(L);
4102 luaL_newmetatable(L, className);
4103 int metatable = lua_gettop(L);
4105 lua_pushliteral(L, "__metatable");
4106 lua_pushvalue(L, methodtable);
4107 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4109 lua_pushliteral(L, "__index");
4110 lua_pushvalue(L, methodtable);
4111 lua_settable(L, metatable);
4113 lua_pushliteral(L, "__gc");
4114 lua_pushcfunction(L, gc_object);
4115 lua_settable(L, metatable);
4117 lua_pop(L, 1); // drop metatable
4119 luaL_openlib(L, 0, methods, 0); // fill methodtable
4120 lua_pop(L, 1); // drop methodtable
4122 // Cannot be created from Lua
4123 //lua_register(L, className, create_object);
4126 const char EnvRef::className[] = "EnvRef";
4127 const luaL_reg EnvRef::methods[] = {
4128 method(EnvRef, set_node),
4129 method(EnvRef, add_node),
4130 method(EnvRef, remove_node),
4131 method(EnvRef, get_node),
4132 method(EnvRef, get_node_or_nil),
4133 method(EnvRef, get_node_light),
4134 method(EnvRef, place_node),
4135 method(EnvRef, dig_node),
4136 method(EnvRef, punch_node),
4137 method(EnvRef, add_entity),
4138 method(EnvRef, add_item),
4139 method(EnvRef, add_rat),
4140 method(EnvRef, add_firefly),
4141 method(EnvRef, get_meta),
4142 method(EnvRef, get_node_timer),
4143 method(EnvRef, get_player_by_name),
4144 method(EnvRef, get_objects_inside_radius),
4145 method(EnvRef, set_timeofday),
4146 method(EnvRef, get_timeofday),
4147 method(EnvRef, find_node_near),
4148 method(EnvRef, find_nodes_in_area),
4149 method(EnvRef, get_perlin),
4150 method(EnvRef, clear_objects),
4151 method(EnvRef, spawn_tree),
4160 class LuaPseudoRandom
4163 PseudoRandom m_pseudo;
4165 static const char className[];
4166 static const luaL_reg methods[];
4168 // Exported functions
4170 // garbage collector
4171 static int gc_object(lua_State *L)
4173 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4178 // next(self, min=0, max=32767) -> get next value
4179 static int l_next(lua_State *L)
4181 LuaPseudoRandom *o = checkobject(L, 1);
4184 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4185 if(!lua_isnil(L, 2))
4186 min = luaL_checkinteger(L, 2);
4187 if(!lua_isnil(L, 3))
4188 max = luaL_checkinteger(L, 3);
4190 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4191 throw LuaError(L, "PseudoRandom.next(): max < min");
4193 if(max - min != 32767 && max - min > 32767/5)
4194 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.");
4195 PseudoRandom &pseudo = o->m_pseudo;
4196 int val = pseudo.next();
4197 val = (val % (max-min+1)) + min;
4198 lua_pushinteger(L, val);
4203 LuaPseudoRandom(int seed):
4212 const PseudoRandom& getItem() const
4216 PseudoRandom& getItem()
4221 // LuaPseudoRandom(seed)
4222 // Creates an LuaPseudoRandom and leaves it on top of stack
4223 static int create_object(lua_State *L)
4225 int seed = luaL_checknumber(L, 1);
4226 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4227 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4228 luaL_getmetatable(L, className);
4229 lua_setmetatable(L, -2);
4233 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4235 luaL_checktype(L, narg, LUA_TUSERDATA);
4236 void *ud = luaL_checkudata(L, narg, className);
4237 if(!ud) luaL_typerror(L, narg, className);
4238 return *(LuaPseudoRandom**)ud; // unbox pointer
4241 static void Register(lua_State *L)
4244 int methodtable = lua_gettop(L);
4245 luaL_newmetatable(L, className);
4246 int metatable = lua_gettop(L);
4248 lua_pushliteral(L, "__metatable");
4249 lua_pushvalue(L, methodtable);
4250 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4252 lua_pushliteral(L, "__index");
4253 lua_pushvalue(L, methodtable);
4254 lua_settable(L, metatable);
4256 lua_pushliteral(L, "__gc");
4257 lua_pushcfunction(L, gc_object);
4258 lua_settable(L, metatable);
4260 lua_pop(L, 1); // drop metatable
4262 luaL_openlib(L, 0, methods, 0); // fill methodtable
4263 lua_pop(L, 1); // drop methodtable
4265 // Can be created from Lua (LuaPseudoRandom(seed))
4266 lua_register(L, className, create_object);
4269 const char LuaPseudoRandom::className[] = "PseudoRandom";
4270 const luaL_reg LuaPseudoRandom::methods[] = {
4271 method(LuaPseudoRandom, next),
4281 class LuaABM : public ActiveBlockModifier
4287 std::set<std::string> m_trigger_contents;
4288 std::set<std::string> m_required_neighbors;
4289 float m_trigger_interval;
4290 u32 m_trigger_chance;
4292 LuaABM(lua_State *L, int id,
4293 const std::set<std::string> &trigger_contents,
4294 const std::set<std::string> &required_neighbors,
4295 float trigger_interval, u32 trigger_chance):
4298 m_trigger_contents(trigger_contents),
4299 m_required_neighbors(required_neighbors),
4300 m_trigger_interval(trigger_interval),
4301 m_trigger_chance(trigger_chance)
4304 virtual std::set<std::string> getTriggerContents()
4306 return m_trigger_contents;
4308 virtual std::set<std::string> getRequiredNeighbors()
4310 return m_required_neighbors;
4312 virtual float getTriggerInterval()
4314 return m_trigger_interval;
4316 virtual u32 getTriggerChance()
4318 return m_trigger_chance;
4320 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4321 u32 active_object_count, u32 active_object_count_wider)
4323 lua_State *L = m_lua;
4326 assert(lua_checkstack(L, 20));
4327 StackUnroller stack_unroller(L);
4329 // Get minetest.registered_abms
4330 lua_getglobal(L, "minetest");
4331 lua_getfield(L, -1, "registered_abms");
4332 luaL_checktype(L, -1, LUA_TTABLE);
4333 int registered_abms = lua_gettop(L);
4335 // Get minetest.registered_abms[m_id]
4336 lua_pushnumber(L, m_id);
4337 lua_gettable(L, registered_abms);
4338 if(lua_isnil(L, -1))
4342 luaL_checktype(L, -1, LUA_TTABLE);
4343 lua_getfield(L, -1, "action");
4344 luaL_checktype(L, -1, LUA_TFUNCTION);
4346 pushnode(L, n, env->getGameDef()->ndef());
4347 lua_pushnumber(L, active_object_count);
4348 lua_pushnumber(L, active_object_count_wider);
4349 if(lua_pcall(L, 4, 0, 0))
4350 script_error(L, "error: %s", lua_tostring(L, -1));
4358 static void read_server_sound_params(lua_State *L, int index,
4359 ServerSoundParams ¶ms)
4362 index = lua_gettop(L) + 1 + index;
4364 params = ServerSoundParams();
4365 if(lua_istable(L, index)){
4366 getfloatfield(L, index, "gain", params.gain);
4367 getstringfield(L, index, "to_player", params.to_player);
4368 lua_getfield(L, index, "pos");
4369 if(!lua_isnil(L, -1)){
4370 v3f p = read_v3f(L, -1)*BS;
4372 params.type = ServerSoundParams::SSP_POSITIONAL;
4375 lua_getfield(L, index, "object");
4376 if(!lua_isnil(L, -1)){
4377 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4378 ServerActiveObject *sao = ObjectRef::getobject(ref);
4380 params.object = sao->getId();
4381 params.type = ServerSoundParams::SSP_OBJECT;
4385 params.max_hear_distance = BS*getfloatfield_default(L, index,
4386 "max_hear_distance", params.max_hear_distance/BS);
4387 getboolfield(L, index, "loop", params.loop);
4396 // Writes a line to dstream
4397 static int l_debug(lua_State *L)
4399 std::string text = lua_tostring(L, 1);
4400 dstream << text << std::endl;
4404 // log([level,] text)
4405 // Writes a line to the logger.
4406 // The one-argument version logs to infostream.
4407 // The two-argument version accept a log level: error, action, info, or verbose.
4408 static int l_log(lua_State *L)
4411 LogMessageLevel level = LMT_INFO;
4412 if(lua_isnone(L, 2))
4414 text = lua_tostring(L, 1);
4418 std::string levelname = lua_tostring(L, 1);
4419 text = lua_tostring(L, 2);
4420 if(levelname == "error")
4422 else if(levelname == "action")
4424 else if(levelname == "verbose")
4425 level = LMT_VERBOSE;
4427 log_printline(level, text);
4431 // request_shutdown()
4432 static int l_request_shutdown(lua_State *L)
4434 get_server(L)->requestShutdown();
4438 // get_server_status()
4439 static int l_get_server_status(lua_State *L)
4441 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4445 // register_item_raw({lots of stuff})
4446 static int l_register_item_raw(lua_State *L)
4448 luaL_checktype(L, 1, LUA_TTABLE);
4451 // Get the writable item and node definition managers from the server
4452 IWritableItemDefManager *idef =
4453 get_server(L)->getWritableItemDefManager();
4454 IWritableNodeDefManager *ndef =
4455 get_server(L)->getWritableNodeDefManager();
4457 // Check if name is defined
4459 lua_getfield(L, table, "name");
4460 if(lua_isstring(L, -1)){
4461 name = lua_tostring(L, -1);
4462 verbosestream<<"register_item_raw: "<<name<<std::endl;
4464 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4467 // Check if on_use is defined
4470 // Set a distinctive default value to check if this is set
4471 def.node_placement_prediction = "__default";
4473 // Read the item definition
4474 def = read_item_definition(L, table, def);
4476 // Default to having client-side placement prediction for nodes
4477 // ("" in item definition sets it off)
4478 if(def.node_placement_prediction == "__default"){
4479 if(def.type == ITEM_NODE)
4480 def.node_placement_prediction = name;
4482 def.node_placement_prediction = "";
4485 // Register item definition
4486 idef->registerItem(def);
4488 // Read the node definition (content features) and register it
4489 if(def.type == ITEM_NODE)
4491 ContentFeatures f = read_content_features(L, table);
4492 ndef->set(f.name, f);
4495 return 0; /* number of results */
4498 // register_alias_raw(name, convert_to_name)
4499 static int l_register_alias_raw(lua_State *L)
4501 std::string name = luaL_checkstring(L, 1);
4502 std::string convert_to = luaL_checkstring(L, 2);
4504 // Get the writable item definition manager from the server
4505 IWritableItemDefManager *idef =
4506 get_server(L)->getWritableItemDefManager();
4508 idef->registerAlias(name, convert_to);
4510 return 0; /* number of results */
4513 // helper for register_craft
4514 static bool read_craft_recipe_shaped(lua_State *L, int index,
4515 int &width, std::vector<std::string> &recipe)
4518 index = lua_gettop(L) + 1 + index;
4520 if(!lua_istable(L, index))
4525 while(lua_next(L, index) != 0){
4527 // key at index -2 and value at index -1
4528 if(!lua_istable(L, -1))
4530 int table2 = lua_gettop(L);
4532 while(lua_next(L, table2) != 0){
4533 // key at index -2 and value at index -1
4534 if(!lua_isstring(L, -1))
4536 recipe.push_back(lua_tostring(L, -1));
4537 // removes value, keeps key for next iteration
4544 if(colcount != width)
4547 // removes value, keeps key for next iteration
4554 // helper for register_craft
4555 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4556 std::vector<std::string> &recipe)
4559 index = lua_gettop(L) + 1 + index;
4561 if(!lua_istable(L, index))
4565 while(lua_next(L, index) != 0){
4566 // key at index -2 and value at index -1
4567 if(!lua_isstring(L, -1))
4569 recipe.push_back(lua_tostring(L, -1));
4570 // removes value, keeps key for next iteration
4576 // helper for register_craft
4577 static bool read_craft_replacements(lua_State *L, int index,
4578 CraftReplacements &replacements)
4581 index = lua_gettop(L) + 1 + index;
4583 if(!lua_istable(L, index))
4587 while(lua_next(L, index) != 0){
4588 // key at index -2 and value at index -1
4589 if(!lua_istable(L, -1))
4591 lua_rawgeti(L, -1, 1);
4592 if(!lua_isstring(L, -1))
4594 std::string replace_from = lua_tostring(L, -1);
4596 lua_rawgeti(L, -1, 2);
4597 if(!lua_isstring(L, -1))
4599 std::string replace_to = lua_tostring(L, -1);
4601 replacements.pairs.push_back(
4602 std::make_pair(replace_from, replace_to));
4603 // removes value, keeps key for next iteration
4608 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4609 static int l_register_craft(lua_State *L)
4611 //infostream<<"register_craft"<<std::endl;
4612 luaL_checktype(L, 1, LUA_TTABLE);
4615 // Get the writable craft definition manager from the server
4616 IWritableCraftDefManager *craftdef =
4617 get_server(L)->getWritableCraftDefManager();
4619 std::string type = getstringfield_default(L, table, "type", "shaped");
4622 CraftDefinitionShaped
4624 if(type == "shaped"){
4625 std::string output = getstringfield_default(L, table, "output", "");
4627 throw LuaError(L, "Crafting definition is missing an output");
4630 std::vector<std::string> recipe;
4631 lua_getfield(L, table, "recipe");
4632 if(lua_isnil(L, -1))
4633 throw LuaError(L, "Crafting definition is missing a recipe"
4634 " (output=\"" + output + "\")");
4635 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4636 throw LuaError(L, "Invalid crafting recipe"
4637 " (output=\"" + output + "\")");
4639 CraftReplacements replacements;
4640 lua_getfield(L, table, "replacements");
4641 if(!lua_isnil(L, -1))
4643 if(!read_craft_replacements(L, -1, replacements))
4644 throw LuaError(L, "Invalid replacements"
4645 " (output=\"" + output + "\")");
4648 CraftDefinition *def = new CraftDefinitionShaped(
4649 output, width, recipe, replacements);
4650 craftdef->registerCraft(def);
4653 CraftDefinitionShapeless
4655 else if(type == "shapeless"){
4656 std::string output = getstringfield_default(L, table, "output", "");
4658 throw LuaError(L, "Crafting definition (shapeless)"
4659 " is missing an output");
4661 std::vector<std::string> recipe;
4662 lua_getfield(L, table, "recipe");
4663 if(lua_isnil(L, -1))
4664 throw LuaError(L, "Crafting definition (shapeless)"
4665 " is missing a recipe"
4666 " (output=\"" + output + "\")");
4667 if(!read_craft_recipe_shapeless(L, -1, recipe))
4668 throw LuaError(L, "Invalid crafting recipe"
4669 " (output=\"" + output + "\")");
4671 CraftReplacements replacements;
4672 lua_getfield(L, table, "replacements");
4673 if(!lua_isnil(L, -1))
4675 if(!read_craft_replacements(L, -1, replacements))
4676 throw LuaError(L, "Invalid replacements"
4677 " (output=\"" + output + "\")");
4680 CraftDefinition *def = new CraftDefinitionShapeless(
4681 output, recipe, replacements);
4682 craftdef->registerCraft(def);
4685 CraftDefinitionToolRepair
4687 else if(type == "toolrepair"){
4688 float additional_wear = getfloatfield_default(L, table,
4689 "additional_wear", 0.0);
4691 CraftDefinition *def = new CraftDefinitionToolRepair(
4693 craftdef->registerCraft(def);
4696 CraftDefinitionCooking
4698 else if(type == "cooking"){
4699 std::string output = getstringfield_default(L, table, "output", "");
4701 throw LuaError(L, "Crafting definition (cooking)"
4702 " is missing an output");
4704 std::string recipe = getstringfield_default(L, table, "recipe", "");
4706 throw LuaError(L, "Crafting definition (cooking)"
4707 " is missing a recipe"
4708 " (output=\"" + output + "\")");
4710 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4712 CraftReplacements replacements;
4713 lua_getfield(L, table, "replacements");
4714 if(!lua_isnil(L, -1))
4716 if(!read_craft_replacements(L, -1, replacements))
4717 throw LuaError(L, "Invalid replacements"
4718 " (cooking output=\"" + output + "\")");
4721 CraftDefinition *def = new CraftDefinitionCooking(
4722 output, recipe, cooktime, replacements);
4723 craftdef->registerCraft(def);
4728 else if(type == "fuel"){
4729 std::string recipe = getstringfield_default(L, table, "recipe", "");
4731 throw LuaError(L, "Crafting definition (fuel)"
4732 " is missing a recipe");
4734 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4736 CraftReplacements replacements;
4737 lua_getfield(L, table, "replacements");
4738 if(!lua_isnil(L, -1))
4740 if(!read_craft_replacements(L, -1, replacements))
4741 throw LuaError(L, "Invalid replacements"
4742 " (fuel recipe=\"" + recipe + "\")");
4745 CraftDefinition *def = new CraftDefinitionFuel(
4746 recipe, burntime, replacements);
4747 craftdef->registerCraft(def);
4751 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4755 return 0; /* number of results */
4758 // setting_set(name, value)
4759 static int l_setting_set(lua_State *L)
4761 const char *name = luaL_checkstring(L, 1);
4762 const char *value = luaL_checkstring(L, 2);
4763 g_settings->set(name, value);
4767 // setting_get(name)
4768 static int l_setting_get(lua_State *L)
4770 const char *name = luaL_checkstring(L, 1);
4772 std::string value = g_settings->get(name);
4773 lua_pushstring(L, value.c_str());
4774 } catch(SettingNotFoundException &e){
4780 // setting_getbool(name)
4781 static int l_setting_getbool(lua_State *L)
4783 const char *name = luaL_checkstring(L, 1);
4785 bool value = g_settings->getBool(name);
4786 lua_pushboolean(L, value);
4787 } catch(SettingNotFoundException &e){
4793 // chat_send_all(text)
4794 static int l_chat_send_all(lua_State *L)
4796 const char *text = luaL_checkstring(L, 1);
4797 // Get server from registry
4798 Server *server = get_server(L);
4800 server->notifyPlayers(narrow_to_wide(text));
4804 // chat_send_player(name, text)
4805 static int l_chat_send_player(lua_State *L)
4807 const char *name = luaL_checkstring(L, 1);
4808 const char *text = luaL_checkstring(L, 2);
4809 // Get server from registry
4810 Server *server = get_server(L);
4812 server->notifyPlayer(name, narrow_to_wide(text));
4816 // get_player_privs(name, text)
4817 static int l_get_player_privs(lua_State *L)
4819 const char *name = luaL_checkstring(L, 1);
4820 // Get server from registry
4821 Server *server = get_server(L);
4824 int table = lua_gettop(L);
4825 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4826 for(std::set<std::string>::const_iterator
4827 i = privs_s.begin(); i != privs_s.end(); i++){
4828 lua_pushboolean(L, true);
4829 lua_setfield(L, table, i->c_str());
4831 lua_pushvalue(L, table);
4836 static int l_get_ban_list(lua_State *L)
4838 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4842 // get_ban_description()
4843 static int l_get_ban_description(lua_State *L)
4845 const char * ip_or_name = luaL_checkstring(L, 1);
4846 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4851 static int l_ban_player(lua_State *L)
4853 const char * name = luaL_checkstring(L, 1);
4854 Player *player = get_env(L)->getPlayer(name);
4857 lua_pushboolean(L, false); // no such player
4862 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4863 std::string ip_str = addr.serializeString();
4864 get_server(L)->setIpBanned(ip_str, name);
4866 catch(con::PeerNotFoundException) // unlikely
4868 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4869 lua_pushboolean(L, false); // error
4872 lua_pushboolean(L, true);
4876 // unban_player_or_ip()
4877 static int l_unban_player_of_ip(lua_State *L)
4879 const char * ip_or_name = luaL_checkstring(L, 1);
4880 get_server(L)->unsetIpBanned(ip_or_name);
4881 lua_pushboolean(L, true);
4885 // get_inventory(location)
4886 static int l_get_inventory(lua_State *L)
4888 InventoryLocation loc;
4890 std::string type = checkstringfield(L, 1, "type");
4891 if(type == "player"){
4892 std::string name = checkstringfield(L, 1, "name");
4893 loc.setPlayer(name);
4894 } else if(type == "node"){
4895 lua_getfield(L, 1, "pos");
4896 v3s16 pos = check_v3s16(L, -1);
4897 loc.setNodeMeta(pos);
4898 } else if(type == "detached"){
4899 std::string name = checkstringfield(L, 1, "name");
4900 loc.setDetached(name);
4903 if(get_server(L)->getInventory(loc) != NULL)
4904 InvRef::create(L, loc);
4910 // create_detached_inventory_raw(name)
4911 static int l_create_detached_inventory_raw(lua_State *L)
4913 const char *name = luaL_checkstring(L, 1);
4914 if(get_server(L)->createDetachedInventory(name) != NULL){
4915 InventoryLocation loc;
4916 loc.setDetached(name);
4917 InvRef::create(L, loc);
4924 // show_formspec(playername,formname,formspec)
4925 static int l_show_formspec(lua_State *L)
4927 const char *playername = luaL_checkstring(L, 1);
4928 const char *formname = luaL_checkstring(L, 2);
4929 const char *formspec = luaL_checkstring(L, 3);
4931 if(get_server(L)->showFormspec(playername,formspec,formname))
4933 lua_pushboolean(L, true);
4935 lua_pushboolean(L, false);
4940 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4941 static int l_get_dig_params(lua_State *L)
4943 std::map<std::string, int> groups;
4944 read_groups(L, 1, groups);
4945 ToolCapabilities tp = read_tool_capabilities(L, 2);
4946 if(lua_isnoneornil(L, 3))
4947 push_dig_params(L, getDigParams(groups, &tp));
4949 push_dig_params(L, getDigParams(groups, &tp,
4950 luaL_checknumber(L, 3)));
4954 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4955 static int l_get_hit_params(lua_State *L)
4957 std::map<std::string, int> groups;
4958 read_groups(L, 1, groups);
4959 ToolCapabilities tp = read_tool_capabilities(L, 2);
4960 if(lua_isnoneornil(L, 3))
4961 push_hit_params(L, getHitParams(groups, &tp));
4963 push_hit_params(L, getHitParams(groups, &tp,
4964 luaL_checknumber(L, 3)));
4968 // get_current_modname()
4969 static int l_get_current_modname(lua_State *L)
4971 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4975 // get_modpath(modname)
4976 static int l_get_modpath(lua_State *L)
4978 std::string modname = luaL_checkstring(L, 1);
4980 if(modname == "__builtin"){
4981 std::string path = get_server(L)->getBuiltinLuaPath();
4982 lua_pushstring(L, path.c_str());
4985 const ModSpec *mod = get_server(L)->getModSpec(modname);
4990 lua_pushstring(L, mod->path.c_str());
4995 // the returned list is sorted alphabetically for you
4996 static int l_get_modnames(lua_State *L)
4998 // Get a list of mods
4999 core::list<std::string> mods_unsorted, mods_sorted;
5000 get_server(L)->getModNames(mods_unsorted);
5002 // Take unsorted items from mods_unsorted and sort them into
5003 // mods_sorted; not great performance but the number of mods on a
5004 // server will likely be small.
5005 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5006 i != mods_unsorted.end(); i++)
5009 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5010 x != mods_unsorted.end(); x++)
5012 // I doubt anybody using Minetest will be using
5013 // anything not ASCII based :)
5014 if((*i).compare(*x) <= 0)
5016 mods_sorted.insert_before(x, *i);
5022 mods_sorted.push_back(*i);
5025 // Get the table insertion function from Lua.
5026 lua_getglobal(L, "table");
5027 lua_getfield(L, -1, "insert");
5028 int insertion_func = lua_gettop(L);
5030 // Package them up for Lua
5032 int new_table = lua_gettop(L);
5033 core::list<std::string>::Iterator i = mods_sorted.begin();
5034 while(i != mods_sorted.end())
5036 lua_pushvalue(L, insertion_func);
5037 lua_pushvalue(L, new_table);
5038 lua_pushstring(L, (*i).c_str());
5039 if(lua_pcall(L, 2, 0, 0) != 0)
5041 script_error(L, "error: %s", lua_tostring(L, -1));
5049 static int l_get_worldpath(lua_State *L)
5051 std::string worldpath = get_server(L)->getWorldPath();
5052 lua_pushstring(L, worldpath.c_str());
5056 // sound_play(spec, parameters)
5057 static int l_sound_play(lua_State *L)
5059 SimpleSoundSpec spec;
5060 read_soundspec(L, 1, spec);
5061 ServerSoundParams params;
5062 read_server_sound_params(L, 2, params);
5063 s32 handle = get_server(L)->playSound(spec, params);
5064 lua_pushinteger(L, handle);
5068 // sound_stop(handle)
5069 static int l_sound_stop(lua_State *L)
5071 int handle = luaL_checkinteger(L, 1);
5072 get_server(L)->stopSound(handle);
5076 // is_singleplayer()
5077 static int l_is_singleplayer(lua_State *L)
5079 lua_pushboolean(L, get_server(L)->isSingleplayer());
5083 // get_password_hash(name, raw_password)
5084 static int l_get_password_hash(lua_State *L)
5086 std::string name = luaL_checkstring(L, 1);
5087 std::string raw_password = luaL_checkstring(L, 2);
5088 std::string hash = translatePassword(name,
5089 narrow_to_wide(raw_password));
5090 lua_pushstring(L, hash.c_str());
5094 // notify_authentication_modified(name)
5095 static int l_notify_authentication_modified(lua_State *L)
5097 std::string name = "";
5098 if(lua_isstring(L, 1))
5099 name = lua_tostring(L, 1);
5100 get_server(L)->reportPrivsModified(name);
5104 // get_craft_result(input)
5105 static int l_get_craft_result(lua_State *L)
5108 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5109 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5110 es_CraftMethod, CRAFT_METHOD_NORMAL);
5112 lua_getfield(L, input_i, "width");
5113 if(lua_isnumber(L, -1))
5114 width = luaL_checkinteger(L, -1);
5116 lua_getfield(L, input_i, "items");
5117 std::vector<ItemStack> items = read_items(L, -1);
5118 lua_pop(L, 1); // items
5120 IGameDef *gdef = get_server(L);
5121 ICraftDefManager *cdef = gdef->cdef();
5122 CraftInput input(method, width, items);
5124 bool got = cdef->getCraftResult(input, output, true, gdef);
5125 lua_newtable(L); // output table
5128 item.deSerialize(output.item, gdef->idef());
5129 LuaItemStack::create(L, item);
5130 lua_setfield(L, -2, "item");
5131 setintfield(L, -1, "time", output.time);
5133 LuaItemStack::create(L, ItemStack());
5134 lua_setfield(L, -2, "item");
5135 setintfield(L, -1, "time", 0);
5137 lua_newtable(L); // decremented input table
5138 lua_pushstring(L, method_s.c_str());
5139 lua_setfield(L, -2, "method");
5140 lua_pushinteger(L, width);
5141 lua_setfield(L, -2, "width");
5142 push_items(L, input.items);
5143 lua_setfield(L, -2, "items");
5147 // get_craft_recipe(result item)
5148 static int l_get_craft_recipe(lua_State *L)
5153 std::string o_item = luaL_checkstring(L,input_i);
5155 IGameDef *gdef = get_server(L);
5156 ICraftDefManager *cdef = gdef->cdef();
5158 CraftOutput output(o_item,0);
5159 bool got = cdef->getCraftRecipe(input, output, gdef);
5160 lua_newtable(L); // output table
5163 for(std::vector<ItemStack>::const_iterator
5164 i = input.items.begin();
5165 i != input.items.end(); i++, k++)
5171 sprintf(tmp,"%d",k);
5172 lua_pushstring(L,tmp);
5173 lua_pushstring(L,i->name.c_str());
5174 lua_settable(L, -3);
5176 lua_setfield(L, -2, "items");
5177 setintfield(L, -1, "width", input.width);
5178 switch (input.method) {
5179 case CRAFT_METHOD_NORMAL:
5180 lua_pushstring(L,"normal");
5182 case CRAFT_METHOD_COOKING:
5183 lua_pushstring(L,"cooking");
5185 case CRAFT_METHOD_FUEL:
5186 lua_pushstring(L,"fuel");
5189 lua_pushstring(L,"unknown");
5191 lua_setfield(L, -2, "type");
5194 lua_setfield(L, -2, "items");
5195 setintfield(L, -1, "width", 0);
5200 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5201 static int l_rollback_get_last_node_actor(lua_State *L)
5203 v3s16 p = read_v3s16(L, 1);
5204 int range = luaL_checknumber(L, 2);
5205 int seconds = luaL_checknumber(L, 3);
5206 Server *server = get_server(L);
5207 IRollbackManager *rollback = server->getRollbackManager();
5209 int act_seconds = 0;
5210 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5211 lua_pushstring(L, actor.c_str());
5212 push_v3s16(L, act_p);
5213 lua_pushnumber(L, act_seconds);
5217 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5218 static int l_rollback_revert_actions_by(lua_State *L)
5220 std::string actor = luaL_checkstring(L, 1);
5221 int seconds = luaL_checknumber(L, 2);
5222 Server *server = get_server(L);
5223 IRollbackManager *rollback = server->getRollbackManager();
5224 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5225 std::list<std::string> log;
5226 bool success = server->rollbackRevertActions(actions, &log);
5227 // Push boolean result
5228 lua_pushboolean(L, success);
5229 // Get the table insert function and push the log table
5230 lua_getglobal(L, "table");
5231 lua_getfield(L, -1, "insert");
5232 int table_insert = lua_gettop(L);
5234 int table = lua_gettop(L);
5235 for(std::list<std::string>::const_iterator i = log.begin();
5236 i != log.end(); i++)
5238 lua_pushvalue(L, table_insert);
5239 lua_pushvalue(L, table);
5240 lua_pushstring(L, i->c_str());
5241 if(lua_pcall(L, 2, 0, 0))
5242 script_error(L, "error: %s", lua_tostring(L, -1));
5244 lua_remove(L, -2); // Remove table
5245 lua_remove(L, -2); // Remove insert
5249 static const struct luaL_Reg minetest_f [] = {
5252 {"request_shutdown", l_request_shutdown},
5253 {"get_server_status", l_get_server_status},
5254 {"register_item_raw", l_register_item_raw},
5255 {"register_alias_raw", l_register_alias_raw},
5256 {"register_craft", l_register_craft},
5257 {"setting_set", l_setting_set},
5258 {"setting_get", l_setting_get},
5259 {"setting_getbool", l_setting_getbool},
5260 {"chat_send_all", l_chat_send_all},
5261 {"chat_send_player", l_chat_send_player},
5262 {"get_player_privs", l_get_player_privs},
5263 {"get_ban_list", l_get_ban_list},
5264 {"get_ban_description", l_get_ban_description},
5265 {"ban_player", l_ban_player},
5266 {"unban_player_or_ip", l_unban_player_of_ip},
5267 {"get_inventory", l_get_inventory},
5268 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5269 {"show_formspec", l_show_formspec},
5270 {"get_dig_params", l_get_dig_params},
5271 {"get_hit_params", l_get_hit_params},
5272 {"get_current_modname", l_get_current_modname},
5273 {"get_modpath", l_get_modpath},
5274 {"get_modnames", l_get_modnames},
5275 {"get_worldpath", l_get_worldpath},
5276 {"sound_play", l_sound_play},
5277 {"sound_stop", l_sound_stop},
5278 {"is_singleplayer", l_is_singleplayer},
5279 {"get_password_hash", l_get_password_hash},
5280 {"notify_authentication_modified", l_notify_authentication_modified},
5281 {"get_craft_result", l_get_craft_result},
5282 {"get_craft_recipe", l_get_craft_recipe},
5283 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5284 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5289 Main export function
5292 void scriptapi_export(lua_State *L, Server *server)
5295 assert(lua_checkstack(L, 20));
5296 verbosestream<<"scriptapi_export()"<<std::endl;
5297 StackUnroller stack_unroller(L);
5299 // Store server as light userdata in registry
5300 lua_pushlightuserdata(L, server);
5301 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5303 // Register global functions in table minetest
5305 luaL_register(L, NULL, minetest_f);
5306 lua_setglobal(L, "minetest");
5308 // Get the main minetest table
5309 lua_getglobal(L, "minetest");
5311 // Add tables to minetest
5313 lua_setfield(L, -2, "object_refs");
5315 lua_setfield(L, -2, "luaentities");
5317 // Register wrappers
5318 LuaItemStack::Register(L);
5319 InvRef::Register(L);
5320 NodeMetaRef::Register(L);
5321 NodeTimerRef::Register(L);
5322 ObjectRef::Register(L);
5323 EnvRef::Register(L);
5324 LuaPseudoRandom::Register(L);
5325 LuaPerlinNoise::Register(L);
5328 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5329 const std::string &modname)
5331 ModNameStorer modnamestorer(L, modname);
5333 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5335 errorstream<<"Error loading mod \""<<modname
5336 <<"\": modname does not follow naming conventions: "
5337 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5341 bool success = false;
5344 success = script_load(L, scriptpath.c_str());
5347 errorstream<<"Error loading mod \""<<modname
5348 <<"\": "<<e.what()<<std::endl;
5354 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5357 assert(lua_checkstack(L, 20));
5358 verbosestream<<"scriptapi_add_environment"<<std::endl;
5359 StackUnroller stack_unroller(L);
5361 // Create EnvRef on stack
5362 EnvRef::create(L, env);
5363 int envref = lua_gettop(L);
5365 // minetest.env = envref
5366 lua_getglobal(L, "minetest");
5367 luaL_checktype(L, -1, LUA_TTABLE);
5368 lua_pushvalue(L, envref);
5369 lua_setfield(L, -2, "env");
5371 // Store environment as light userdata in registry
5372 lua_pushlightuserdata(L, env);
5373 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5376 Add ActiveBlockModifiers to environment
5379 // Get minetest.registered_abms
5380 lua_getglobal(L, "minetest");
5381 lua_getfield(L, -1, "registered_abms");
5382 luaL_checktype(L, -1, LUA_TTABLE);
5383 int registered_abms = lua_gettop(L);
5385 if(lua_istable(L, registered_abms)){
5386 int table = lua_gettop(L);
5388 while(lua_next(L, table) != 0){
5389 // key at index -2 and value at index -1
5390 int id = lua_tonumber(L, -2);
5391 int current_abm = lua_gettop(L);
5393 std::set<std::string> trigger_contents;
5394 lua_getfield(L, current_abm, "nodenames");
5395 if(lua_istable(L, -1)){
5396 int table = lua_gettop(L);
5398 while(lua_next(L, table) != 0){
5399 // key at index -2 and value at index -1
5400 luaL_checktype(L, -1, LUA_TSTRING);
5401 trigger_contents.insert(lua_tostring(L, -1));
5402 // removes value, keeps key for next iteration
5405 } else if(lua_isstring(L, -1)){
5406 trigger_contents.insert(lua_tostring(L, -1));
5410 std::set<std::string> required_neighbors;
5411 lua_getfield(L, current_abm, "neighbors");
5412 if(lua_istable(L, -1)){
5413 int table = lua_gettop(L);
5415 while(lua_next(L, table) != 0){
5416 // key at index -2 and value at index -1
5417 luaL_checktype(L, -1, LUA_TSTRING);
5418 required_neighbors.insert(lua_tostring(L, -1));
5419 // removes value, keeps key for next iteration
5422 } else if(lua_isstring(L, -1)){
5423 required_neighbors.insert(lua_tostring(L, -1));
5427 float trigger_interval = 10.0;
5428 getfloatfield(L, current_abm, "interval", trigger_interval);
5430 int trigger_chance = 50;
5431 getintfield(L, current_abm, "chance", trigger_chance);
5433 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5434 required_neighbors, trigger_interval, trigger_chance);
5436 env->addActiveBlockModifier(abm);
5438 // removes value, keeps key for next iteration
5446 // Dump stack top with the dump2 function
5447 static void dump2(lua_State *L, const char *name)
5449 // Dump object (debug)
5450 lua_getglobal(L, "dump2");
5451 luaL_checktype(L, -1, LUA_TFUNCTION);
5452 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5453 lua_pushstring(L, name);
5454 if(lua_pcall(L, 2, 0, 0))
5455 script_error(L, "error: %s", lua_tostring(L, -1));
5463 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5466 assert(lua_checkstack(L, 20));
5467 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5468 StackUnroller stack_unroller(L);
5470 // Create object on stack
5471 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5472 int object = lua_gettop(L);
5474 // Get minetest.object_refs table
5475 lua_getglobal(L, "minetest");
5476 lua_getfield(L, -1, "object_refs");
5477 luaL_checktype(L, -1, LUA_TTABLE);
5478 int objectstable = lua_gettop(L);
5480 // object_refs[id] = object
5481 lua_pushnumber(L, cobj->getId()); // Push id
5482 lua_pushvalue(L, object); // Copy object to top of stack
5483 lua_settable(L, objectstable);
5486 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5489 assert(lua_checkstack(L, 20));
5490 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5491 StackUnroller stack_unroller(L);
5493 // Get minetest.object_refs table
5494 lua_getglobal(L, "minetest");
5495 lua_getfield(L, -1, "object_refs");
5496 luaL_checktype(L, -1, LUA_TTABLE);
5497 int objectstable = lua_gettop(L);
5499 // Get object_refs[id]
5500 lua_pushnumber(L, cobj->getId()); // Push id
5501 lua_gettable(L, objectstable);
5502 // Set object reference to NULL
5503 ObjectRef::set_null(L);
5504 lua_pop(L, 1); // pop object
5506 // Set object_refs[id] = nil
5507 lua_pushnumber(L, cobj->getId()); // Push id
5509 lua_settable(L, objectstable);
5516 // What scriptapi_run_callbacks does with the return values of callbacks.
5517 // Regardless of the mode, if only one callback is defined,
5518 // its return value is the total return value.
5519 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5520 enum RunCallbacksMode
5522 // Returns the return value of the first callback
5523 // Returns nil if list of callbacks is empty
5524 RUN_CALLBACKS_MODE_FIRST,
5525 // Returns the return value of the last callback
5526 // Returns nil if list of callbacks is empty
5527 RUN_CALLBACKS_MODE_LAST,
5528 // If any callback returns a false value, the first such is returned
5529 // Otherwise, the first callback's return value (trueish) is returned
5530 // Returns true if list of callbacks is empty
5531 RUN_CALLBACKS_MODE_AND,
5532 // Like above, but stops calling callbacks (short circuit)
5533 // after seeing the first false value
5534 RUN_CALLBACKS_MODE_AND_SC,
5535 // If any callback returns a true value, the first such is returned
5536 // Otherwise, the first callback's return value (falseish) is returned
5537 // Returns false if list of callbacks is empty
5538 RUN_CALLBACKS_MODE_OR,
5539 // Like above, but stops calling callbacks (short circuit)
5540 // after seeing the first true value
5541 RUN_CALLBACKS_MODE_OR_SC,
5542 // Note: "a true value" and "a false value" refer to values that
5543 // are converted by lua_toboolean to true or false, respectively.
5546 // Push the list of callbacks (a lua table).
5547 // Then push nargs arguments.
5548 // Then call this function, which
5549 // - runs the callbacks
5550 // - removes the table and arguments from the lua stack
5551 // - pushes the return value, computed depending on mode
5552 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5553 RunCallbacksMode mode)
5555 // Insert the return value into the lua stack, below the table
5556 assert(lua_gettop(L) >= nargs + 1);
5558 lua_insert(L, -(nargs + 1) - 1);
5559 // Stack now looks like this:
5560 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5562 int rv = lua_gettop(L) - nargs - 1;
5564 int arg = table + 1;
5566 luaL_checktype(L, table, LUA_TTABLE);
5570 bool first_loop = true;
5571 while(lua_next(L, table) != 0){
5572 // key at index -2 and value at index -1
5573 luaL_checktype(L, -1, LUA_TFUNCTION);
5575 for(int i = 0; i < nargs; i++)
5576 lua_pushvalue(L, arg+i);
5577 if(lua_pcall(L, nargs, 1, 0))
5578 script_error(L, "error: %s", lua_tostring(L, -1));
5580 // Move return value to designated space in stack
5583 // Result of first callback is always moved
5587 // Otherwise, what happens depends on the mode
5588 if(mode == RUN_CALLBACKS_MODE_FIRST)
5590 else if(mode == RUN_CALLBACKS_MODE_LAST)
5592 else if(mode == RUN_CALLBACKS_MODE_AND ||
5593 mode == RUN_CALLBACKS_MODE_AND_SC){
5594 if((bool)lua_toboolean(L, rv) == true &&
5595 (bool)lua_toboolean(L, -1) == false)
5600 else if(mode == RUN_CALLBACKS_MODE_OR ||
5601 mode == RUN_CALLBACKS_MODE_OR_SC){
5602 if((bool)lua_toboolean(L, rv) == false &&
5603 (bool)lua_toboolean(L, -1) == true)
5612 // Handle short circuit modes
5613 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5614 (bool)lua_toboolean(L, rv) == false)
5616 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5617 (bool)lua_toboolean(L, rv) == true)
5620 // value removed, keep key for next iteration
5623 // Remove stuff from stack, leaving only the return value
5626 // Fix return value in case no callbacks were called
5628 if(mode == RUN_CALLBACKS_MODE_AND ||
5629 mode == RUN_CALLBACKS_MODE_AND_SC){
5631 lua_pushboolean(L, true);
5633 else if(mode == RUN_CALLBACKS_MODE_OR ||
5634 mode == RUN_CALLBACKS_MODE_OR_SC){
5636 lua_pushboolean(L, false);
5641 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5642 const std::string &message)
5645 assert(lua_checkstack(L, 20));
5646 StackUnroller stack_unroller(L);
5648 // Get minetest.registered_on_chat_messages
5649 lua_getglobal(L, "minetest");
5650 lua_getfield(L, -1, "registered_on_chat_messages");
5652 lua_pushstring(L, name.c_str());
5653 lua_pushstring(L, message.c_str());
5654 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5655 bool ate = lua_toboolean(L, -1);
5659 void scriptapi_on_shutdown(lua_State *L)
5662 assert(lua_checkstack(L, 20));
5663 StackUnroller stack_unroller(L);
5665 // Get registered shutdown hooks
5666 lua_getglobal(L, "minetest");
5667 lua_getfield(L, -1, "registered_on_shutdown");
5669 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5672 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5675 assert(lua_checkstack(L, 20));
5676 StackUnroller stack_unroller(L);
5678 // Get minetest.registered_on_newplayers
5679 lua_getglobal(L, "minetest");
5680 lua_getfield(L, -1, "registered_on_newplayers");
5682 objectref_get_or_create(L, player);
5683 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5686 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5689 assert(lua_checkstack(L, 20));
5690 StackUnroller stack_unroller(L);
5692 // Get minetest.registered_on_dieplayers
5693 lua_getglobal(L, "minetest");
5694 lua_getfield(L, -1, "registered_on_dieplayers");
5696 objectref_get_or_create(L, player);
5697 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5700 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5703 assert(lua_checkstack(L, 20));
5704 StackUnroller stack_unroller(L);
5706 // Get minetest.registered_on_respawnplayers
5707 lua_getglobal(L, "minetest");
5708 lua_getfield(L, -1, "registered_on_respawnplayers");
5710 objectref_get_or_create(L, player);
5711 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5712 bool positioning_handled_by_some = lua_toboolean(L, -1);
5713 return positioning_handled_by_some;
5716 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5719 assert(lua_checkstack(L, 20));
5720 StackUnroller stack_unroller(L);
5722 // Get minetest.registered_on_joinplayers
5723 lua_getglobal(L, "minetest");
5724 lua_getfield(L, -1, "registered_on_joinplayers");
5726 objectref_get_or_create(L, player);
5727 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5730 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5733 assert(lua_checkstack(L, 20));
5734 StackUnroller stack_unroller(L);
5736 // Get minetest.registered_on_leaveplayers
5737 lua_getglobal(L, "minetest");
5738 lua_getfield(L, -1, "registered_on_leaveplayers");
5740 objectref_get_or_create(L, player);
5741 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5744 static void get_auth_handler(lua_State *L)
5746 lua_getglobal(L, "minetest");
5747 lua_getfield(L, -1, "registered_auth_handler");
5748 if(lua_isnil(L, -1)){
5750 lua_getfield(L, -1, "builtin_auth_handler");
5752 if(lua_type(L, -1) != LUA_TTABLE)
5753 throw LuaError(L, "Authentication handler table not valid");
5756 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5757 std::string *dst_password, std::set<std::string> *dst_privs)
5760 assert(lua_checkstack(L, 20));
5761 StackUnroller stack_unroller(L);
5763 get_auth_handler(L);
5764 lua_getfield(L, -1, "get_auth");
5765 if(lua_type(L, -1) != LUA_TFUNCTION)
5766 throw LuaError(L, "Authentication handler missing get_auth");
5767 lua_pushstring(L, playername.c_str());
5768 if(lua_pcall(L, 1, 1, 0))
5769 script_error(L, "error: %s", lua_tostring(L, -1));
5771 // nil = login not allowed
5772 if(lua_isnil(L, -1))
5774 luaL_checktype(L, -1, LUA_TTABLE);
5776 std::string password;
5777 bool found = getstringfield(L, -1, "password", password);
5779 throw LuaError(L, "Authentication handler didn't return password");
5781 *dst_password = password;
5783 lua_getfield(L, -1, "privileges");
5784 if(!lua_istable(L, -1))
5786 "Authentication handler didn't return privilege table");
5788 read_privileges(L, -1, *dst_privs);
5794 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5795 const std::string &password)
5798 assert(lua_checkstack(L, 20));
5799 StackUnroller stack_unroller(L);
5801 get_auth_handler(L);
5802 lua_getfield(L, -1, "create_auth");
5803 if(lua_type(L, -1) != LUA_TFUNCTION)
5804 throw LuaError(L, "Authentication handler missing create_auth");
5805 lua_pushstring(L, playername.c_str());
5806 lua_pushstring(L, password.c_str());
5807 if(lua_pcall(L, 2, 0, 0))
5808 script_error(L, "error: %s", lua_tostring(L, -1));
5811 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5812 const std::string &password)
5815 assert(lua_checkstack(L, 20));
5816 StackUnroller stack_unroller(L);
5818 get_auth_handler(L);
5819 lua_getfield(L, -1, "set_password");
5820 if(lua_type(L, -1) != LUA_TFUNCTION)
5821 throw LuaError(L, "Authentication handler missing set_password");
5822 lua_pushstring(L, playername.c_str());
5823 lua_pushstring(L, password.c_str());
5824 if(lua_pcall(L, 2, 1, 0))
5825 script_error(L, "error: %s", lua_tostring(L, -1));
5826 return lua_toboolean(L, -1);
5833 void scriptapi_on_player_receive_fields(lua_State *L,
5834 ServerActiveObject *player,
5835 const std::string &formname,
5836 const std::map<std::string, std::string> &fields)
5839 assert(lua_checkstack(L, 20));
5840 StackUnroller stack_unroller(L);
5842 // Get minetest.registered_on_chat_messages
5843 lua_getglobal(L, "minetest");
5844 lua_getfield(L, -1, "registered_on_player_receive_fields");
5847 objectref_get_or_create(L, player);
5849 lua_pushstring(L, formname.c_str());
5852 for(std::map<std::string, std::string>::const_iterator
5853 i = fields.begin(); i != fields.end(); i++){
5854 const std::string &name = i->first;
5855 const std::string &value = i->second;
5856 lua_pushstring(L, name.c_str());
5857 lua_pushlstring(L, value.c_str(), value.size());
5858 lua_settable(L, -3);
5860 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5864 item callbacks and node callbacks
5867 // Retrieves minetest.registered_items[name][callbackname]
5868 // If that is nil or on error, return false and stack is unchanged
5869 // If that is a function, returns true and pushes the
5870 // function onto the stack
5871 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5872 // is tried instead so unknown items can still be manipulated to some degree
5873 static bool get_item_callback(lua_State *L,
5874 const char *name, const char *callbackname)
5876 lua_getglobal(L, "minetest");
5877 lua_getfield(L, -1, "registered_items");
5879 luaL_checktype(L, -1, LUA_TTABLE);
5880 lua_getfield(L, -1, name);
5882 // Should be a table
5883 if(lua_type(L, -1) != LUA_TTABLE)
5885 // Report error and clean up
5886 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5889 // Try minetest.nodedef_default instead
5890 lua_getglobal(L, "minetest");
5891 lua_getfield(L, -1, "nodedef_default");
5893 luaL_checktype(L, -1, LUA_TTABLE);
5895 lua_getfield(L, -1, callbackname);
5897 // Should be a function or nil
5898 if(lua_type(L, -1) == LUA_TFUNCTION)
5902 else if(lua_isnil(L, -1))
5909 errorstream<<"Item \""<<name<<"\" callback \""
5910 <<callbackname<<" is not a function"<<std::endl;
5916 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5917 ServerActiveObject *dropper, v3f pos)
5920 assert(lua_checkstack(L, 20));
5921 StackUnroller stack_unroller(L);
5923 // Push callback function on stack
5924 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5928 LuaItemStack::create(L, item);
5929 objectref_get_or_create(L, dropper);
5930 pushFloatPos(L, pos);
5931 if(lua_pcall(L, 3, 1, 0))
5932 script_error(L, "error: %s", lua_tostring(L, -1));
5933 if(!lua_isnil(L, -1))
5934 item = read_item(L, -1);
5938 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5939 ServerActiveObject *placer, const PointedThing &pointed)
5942 assert(lua_checkstack(L, 20));
5943 StackUnroller stack_unroller(L);
5945 // Push callback function on stack
5946 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5950 LuaItemStack::create(L, item);
5951 objectref_get_or_create(L, placer);
5952 push_pointed_thing(L, pointed);
5953 if(lua_pcall(L, 3, 1, 0))
5954 script_error(L, "error: %s", lua_tostring(L, -1));
5955 if(!lua_isnil(L, -1))
5956 item = read_item(L, -1);
5960 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5961 ServerActiveObject *user, const PointedThing &pointed)
5964 assert(lua_checkstack(L, 20));
5965 StackUnroller stack_unroller(L);
5967 // Push callback function on stack
5968 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5972 LuaItemStack::create(L, item);
5973 objectref_get_or_create(L, user);
5974 push_pointed_thing(L, pointed);
5975 if(lua_pcall(L, 3, 1, 0))
5976 script_error(L, "error: %s", lua_tostring(L, -1));
5977 if(!lua_isnil(L, -1))
5978 item = read_item(L, -1);
5982 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5983 ServerActiveObject *puncher)
5986 assert(lua_checkstack(L, 20));
5987 StackUnroller stack_unroller(L);
5989 INodeDefManager *ndef = get_server(L)->ndef();
5991 // Push callback function on stack
5992 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5997 pushnode(L, node, ndef);
5998 objectref_get_or_create(L, puncher);
5999 if(lua_pcall(L, 3, 0, 0))
6000 script_error(L, "error: %s", lua_tostring(L, -1));
6004 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6005 ServerActiveObject *digger)
6008 assert(lua_checkstack(L, 20));
6009 StackUnroller stack_unroller(L);
6011 INodeDefManager *ndef = get_server(L)->ndef();
6013 // Push callback function on stack
6014 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6019 pushnode(L, node, ndef);
6020 objectref_get_or_create(L, digger);
6021 if(lua_pcall(L, 3, 0, 0))
6022 script_error(L, "error: %s", lua_tostring(L, -1));
6026 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6029 assert(lua_checkstack(L, 20));
6030 StackUnroller stack_unroller(L);
6032 INodeDefManager *ndef = get_server(L)->ndef();
6034 // Push callback function on stack
6035 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6040 if(lua_pcall(L, 1, 0, 0))
6041 script_error(L, "error: %s", lua_tostring(L, -1));
6044 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6047 assert(lua_checkstack(L, 20));
6048 StackUnroller stack_unroller(L);
6050 INodeDefManager *ndef = get_server(L)->ndef();
6052 // Push callback function on stack
6053 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6058 if(lua_pcall(L, 1, 0, 0))
6059 script_error(L, "error: %s", lua_tostring(L, -1));
6062 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6065 assert(lua_checkstack(L, 20));
6066 StackUnroller stack_unroller(L);
6068 INodeDefManager *ndef = get_server(L)->ndef();
6070 // Push callback function on stack
6071 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6076 pushnode(L, node, ndef);
6077 if(lua_pcall(L, 2, 0, 0))
6078 script_error(L, "error: %s", lua_tostring(L, -1));
6081 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6084 assert(lua_checkstack(L, 20));
6085 StackUnroller stack_unroller(L);
6087 INodeDefManager *ndef = get_server(L)->ndef();
6089 // Push callback function on stack
6090 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6095 lua_pushnumber(L,dtime);
6096 if(lua_pcall(L, 2, 1, 0))
6097 script_error(L, "error: %s", lua_tostring(L, -1));
6098 if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6104 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6105 const std::string &formname,
6106 const std::map<std::string, std::string> &fields,
6107 ServerActiveObject *sender)
6110 assert(lua_checkstack(L, 20));
6111 StackUnroller stack_unroller(L);
6113 INodeDefManager *ndef = get_server(L)->ndef();
6115 // If node doesn't exist, we don't know what callback to call
6116 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6117 if(node.getContent() == CONTENT_IGNORE)
6120 // Push callback function on stack
6121 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6128 lua_pushstring(L, formname.c_str());
6131 for(std::map<std::string, std::string>::const_iterator
6132 i = fields.begin(); i != fields.end(); i++){
6133 const std::string &name = i->first;
6134 const std::string &value = i->second;
6135 lua_pushstring(L, name.c_str());
6136 lua_pushlstring(L, value.c_str(), value.size());
6137 lua_settable(L, -3);
6140 objectref_get_or_create(L, sender);
6141 if(lua_pcall(L, 4, 0, 0))
6142 script_error(L, "error: %s", lua_tostring(L, -1));
6146 Node metadata inventory callbacks
6149 // Return number of accepted items to be moved
6150 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6151 const std::string &from_list, int from_index,
6152 const std::string &to_list, int to_index,
6153 int count, ServerActiveObject *player)
6156 assert(lua_checkstack(L, 20));
6157 StackUnroller stack_unroller(L);
6159 INodeDefManager *ndef = get_server(L)->ndef();
6161 // If node doesn't exist, we don't know what callback to call
6162 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6163 if(node.getContent() == CONTENT_IGNORE)
6166 // Push callback function on stack
6167 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6168 "allow_metadata_inventory_move"))
6171 // function(pos, from_list, from_index, to_list, to_index, count, player)
6175 lua_pushstring(L, from_list.c_str());
6177 lua_pushinteger(L, from_index + 1);
6179 lua_pushstring(L, to_list.c_str());
6181 lua_pushinteger(L, to_index + 1);
6183 lua_pushinteger(L, count);
6185 objectref_get_or_create(L, player);
6186 if(lua_pcall(L, 7, 1, 0))
6187 script_error(L, "error: %s", lua_tostring(L, -1));
6188 if(!lua_isnumber(L, -1))
6189 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6190 return luaL_checkinteger(L, -1);
6193 // Return number of accepted items to be put
6194 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6195 const std::string &listname, int index, ItemStack &stack,
6196 ServerActiveObject *player)
6199 assert(lua_checkstack(L, 20));
6200 StackUnroller stack_unroller(L);
6202 INodeDefManager *ndef = get_server(L)->ndef();
6204 // If node doesn't exist, we don't know what callback to call
6205 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6206 if(node.getContent() == CONTENT_IGNORE)
6209 // Push callback function on stack
6210 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6211 "allow_metadata_inventory_put"))
6214 // Call function(pos, listname, index, stack, player)
6218 lua_pushstring(L, listname.c_str());
6220 lua_pushinteger(L, index + 1);
6222 LuaItemStack::create(L, stack);
6224 objectref_get_or_create(L, player);
6225 if(lua_pcall(L, 5, 1, 0))
6226 script_error(L, "error: %s", lua_tostring(L, -1));
6227 if(!lua_isnumber(L, -1))
6228 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6229 return luaL_checkinteger(L, -1);
6232 // Return number of accepted items to be taken
6233 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6234 const std::string &listname, int index, ItemStack &stack,
6235 ServerActiveObject *player)
6238 assert(lua_checkstack(L, 20));
6239 StackUnroller stack_unroller(L);
6241 INodeDefManager *ndef = get_server(L)->ndef();
6243 // If node doesn't exist, we don't know what callback to call
6244 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6245 if(node.getContent() == CONTENT_IGNORE)
6248 // Push callback function on stack
6249 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6250 "allow_metadata_inventory_take"))
6253 // Call function(pos, listname, index, count, player)
6257 lua_pushstring(L, listname.c_str());
6259 lua_pushinteger(L, index + 1);
6261 LuaItemStack::create(L, stack);
6263 objectref_get_or_create(L, player);
6264 if(lua_pcall(L, 5, 1, 0))
6265 script_error(L, "error: %s", lua_tostring(L, -1));
6266 if(!lua_isnumber(L, -1))
6267 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6268 return luaL_checkinteger(L, -1);
6271 // Report moved items
6272 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6273 const std::string &from_list, int from_index,
6274 const std::string &to_list, int to_index,
6275 int count, ServerActiveObject *player)
6278 assert(lua_checkstack(L, 20));
6279 StackUnroller stack_unroller(L);
6281 INodeDefManager *ndef = get_server(L)->ndef();
6283 // If node doesn't exist, we don't know what callback to call
6284 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6285 if(node.getContent() == CONTENT_IGNORE)
6288 // Push callback function on stack
6289 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6290 "on_metadata_inventory_move"))
6293 // function(pos, from_list, from_index, to_list, to_index, count, player)
6297 lua_pushstring(L, from_list.c_str());
6299 lua_pushinteger(L, from_index + 1);
6301 lua_pushstring(L, to_list.c_str());
6303 lua_pushinteger(L, to_index + 1);
6305 lua_pushinteger(L, count);
6307 objectref_get_or_create(L, player);
6308 if(lua_pcall(L, 7, 0, 0))
6309 script_error(L, "error: %s", lua_tostring(L, -1));
6313 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6314 const std::string &listname, int index, ItemStack &stack,
6315 ServerActiveObject *player)
6318 assert(lua_checkstack(L, 20));
6319 StackUnroller stack_unroller(L);
6321 INodeDefManager *ndef = get_server(L)->ndef();
6323 // If node doesn't exist, we don't know what callback to call
6324 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6325 if(node.getContent() == CONTENT_IGNORE)
6328 // Push callback function on stack
6329 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6330 "on_metadata_inventory_put"))
6333 // Call function(pos, listname, index, stack, player)
6337 lua_pushstring(L, listname.c_str());
6339 lua_pushinteger(L, index + 1);
6341 LuaItemStack::create(L, stack);
6343 objectref_get_or_create(L, player);
6344 if(lua_pcall(L, 5, 0, 0))
6345 script_error(L, "error: %s", lua_tostring(L, -1));
6348 // Report taken items
6349 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6350 const std::string &listname, int index, ItemStack &stack,
6351 ServerActiveObject *player)
6354 assert(lua_checkstack(L, 20));
6355 StackUnroller stack_unroller(L);
6357 INodeDefManager *ndef = get_server(L)->ndef();
6359 // If node doesn't exist, we don't know what callback to call
6360 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6361 if(node.getContent() == CONTENT_IGNORE)
6364 // Push callback function on stack
6365 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6366 "on_metadata_inventory_take"))
6369 // Call function(pos, listname, index, stack, player)
6373 lua_pushstring(L, listname.c_str());
6375 lua_pushinteger(L, index + 1);
6377 LuaItemStack::create(L, stack);
6379 objectref_get_or_create(L, player);
6380 if(lua_pcall(L, 5, 0, 0))
6381 script_error(L, "error: %s", lua_tostring(L, -1));
6385 Detached inventory callbacks
6388 // Retrieves minetest.detached_inventories[name][callbackname]
6389 // If that is nil or on error, return false and stack is unchanged
6390 // If that is a function, returns true and pushes the
6391 // function onto the stack
6392 static bool get_detached_inventory_callback(lua_State *L,
6393 const std::string &name, const char *callbackname)
6395 lua_getglobal(L, "minetest");
6396 lua_getfield(L, -1, "detached_inventories");
6398 luaL_checktype(L, -1, LUA_TTABLE);
6399 lua_getfield(L, -1, name.c_str());
6401 // Should be a table
6402 if(lua_type(L, -1) != LUA_TTABLE)
6404 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6408 lua_getfield(L, -1, callbackname);
6410 // Should be a function or nil
6411 if(lua_type(L, -1) == LUA_TFUNCTION)
6415 else if(lua_isnil(L, -1))
6422 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6423 <<callbackname<<"\" is not a function"<<std::endl;
6429 // Return number of accepted items to be moved
6430 int scriptapi_detached_inventory_allow_move(lua_State *L,
6431 const std::string &name,
6432 const std::string &from_list, int from_index,
6433 const std::string &to_list, int to_index,
6434 int count, ServerActiveObject *player)
6437 assert(lua_checkstack(L, 20));
6438 StackUnroller stack_unroller(L);
6440 // Push callback function on stack
6441 if(!get_detached_inventory_callback(L, name, "allow_move"))
6444 // function(inv, from_list, from_index, to_list, to_index, count, player)
6446 InventoryLocation loc;
6447 loc.setDetached(name);
6448 InvRef::create(L, loc);
6450 lua_pushstring(L, from_list.c_str());
6452 lua_pushinteger(L, from_index + 1);
6454 lua_pushstring(L, to_list.c_str());
6456 lua_pushinteger(L, to_index + 1);
6458 lua_pushinteger(L, count);
6460 objectref_get_or_create(L, player);
6461 if(lua_pcall(L, 7, 1, 0))
6462 script_error(L, "error: %s", lua_tostring(L, -1));
6463 if(!lua_isnumber(L, -1))
6464 throw LuaError(L, "allow_move should return a number");
6465 return luaL_checkinteger(L, -1);
6468 // Return number of accepted items to be put
6469 int scriptapi_detached_inventory_allow_put(lua_State *L,
6470 const std::string &name,
6471 const std::string &listname, int index, ItemStack &stack,
6472 ServerActiveObject *player)
6475 assert(lua_checkstack(L, 20));
6476 StackUnroller stack_unroller(L);
6478 // Push callback function on stack
6479 if(!get_detached_inventory_callback(L, name, "allow_put"))
6480 return stack.count; // All will be accepted
6482 // Call function(inv, listname, index, stack, player)
6484 InventoryLocation loc;
6485 loc.setDetached(name);
6486 InvRef::create(L, loc);
6488 lua_pushstring(L, listname.c_str());
6490 lua_pushinteger(L, index + 1);
6492 LuaItemStack::create(L, stack);
6494 objectref_get_or_create(L, player);
6495 if(lua_pcall(L, 5, 1, 0))
6496 script_error(L, "error: %s", lua_tostring(L, -1));
6497 if(!lua_isnumber(L, -1))
6498 throw LuaError(L, "allow_put should return a number");
6499 return luaL_checkinteger(L, -1);
6502 // Return number of accepted items to be taken
6503 int scriptapi_detached_inventory_allow_take(lua_State *L,
6504 const std::string &name,
6505 const std::string &listname, int index, ItemStack &stack,
6506 ServerActiveObject *player)
6509 assert(lua_checkstack(L, 20));
6510 StackUnroller stack_unroller(L);
6512 // Push callback function on stack
6513 if(!get_detached_inventory_callback(L, name, "allow_take"))
6514 return stack.count; // All will be accepted
6516 // Call function(inv, listname, index, stack, player)
6518 InventoryLocation loc;
6519 loc.setDetached(name);
6520 InvRef::create(L, loc);
6522 lua_pushstring(L, listname.c_str());
6524 lua_pushinteger(L, index + 1);
6526 LuaItemStack::create(L, stack);
6528 objectref_get_or_create(L, player);
6529 if(lua_pcall(L, 5, 1, 0))
6530 script_error(L, "error: %s", lua_tostring(L, -1));
6531 if(!lua_isnumber(L, -1))
6532 throw LuaError(L, "allow_take should return a number");
6533 return luaL_checkinteger(L, -1);
6536 // Report moved items
6537 void scriptapi_detached_inventory_on_move(lua_State *L,
6538 const std::string &name,
6539 const std::string &from_list, int from_index,
6540 const std::string &to_list, int to_index,
6541 int count, ServerActiveObject *player)
6544 assert(lua_checkstack(L, 20));
6545 StackUnroller stack_unroller(L);
6547 // Push callback function on stack
6548 if(!get_detached_inventory_callback(L, name, "on_move"))
6551 // function(inv, from_list, from_index, to_list, to_index, count, player)
6553 InventoryLocation loc;
6554 loc.setDetached(name);
6555 InvRef::create(L, loc);
6557 lua_pushstring(L, from_list.c_str());
6559 lua_pushinteger(L, from_index + 1);
6561 lua_pushstring(L, to_list.c_str());
6563 lua_pushinteger(L, to_index + 1);
6565 lua_pushinteger(L, count);
6567 objectref_get_or_create(L, player);
6568 if(lua_pcall(L, 7, 0, 0))
6569 script_error(L, "error: %s", lua_tostring(L, -1));
6573 void scriptapi_detached_inventory_on_put(lua_State *L,
6574 const std::string &name,
6575 const std::string &listname, int index, ItemStack &stack,
6576 ServerActiveObject *player)
6579 assert(lua_checkstack(L, 20));
6580 StackUnroller stack_unroller(L);
6582 // Push callback function on stack
6583 if(!get_detached_inventory_callback(L, name, "on_put"))
6586 // Call function(inv, listname, index, stack, player)
6588 InventoryLocation loc;
6589 loc.setDetached(name);
6590 InvRef::create(L, loc);
6592 lua_pushstring(L, listname.c_str());
6594 lua_pushinteger(L, index + 1);
6596 LuaItemStack::create(L, stack);
6598 objectref_get_or_create(L, player);
6599 if(lua_pcall(L, 5, 0, 0))
6600 script_error(L, "error: %s", lua_tostring(L, -1));
6603 // Report taken items
6604 void scriptapi_detached_inventory_on_take(lua_State *L,
6605 const std::string &name,
6606 const std::string &listname, int index, ItemStack &stack,
6607 ServerActiveObject *player)
6610 assert(lua_checkstack(L, 20));
6611 StackUnroller stack_unroller(L);
6613 // Push callback function on stack
6614 if(!get_detached_inventory_callback(L, name, "on_take"))
6617 // Call function(inv, listname, index, stack, player)
6619 InventoryLocation loc;
6620 loc.setDetached(name);
6621 InvRef::create(L, loc);
6623 lua_pushstring(L, listname.c_str());
6625 lua_pushinteger(L, index + 1);
6627 LuaItemStack::create(L, stack);
6629 objectref_get_or_create(L, player);
6630 if(lua_pcall(L, 5, 0, 0))
6631 script_error(L, "error: %s", lua_tostring(L, -1));
6638 void scriptapi_environment_step(lua_State *L, float dtime)
6641 assert(lua_checkstack(L, 20));
6642 //infostream<<"scriptapi_environment_step"<<std::endl;
6643 StackUnroller stack_unroller(L);
6645 // Get minetest.registered_globalsteps
6646 lua_getglobal(L, "minetest");
6647 lua_getfield(L, -1, "registered_globalsteps");
6649 lua_pushnumber(L, dtime);
6650 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6653 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6657 assert(lua_checkstack(L, 20));
6658 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6659 StackUnroller stack_unroller(L);
6661 // Get minetest.registered_on_generateds
6662 lua_getglobal(L, "minetest");
6663 lua_getfield(L, -1, "registered_on_generateds");
6665 push_v3s16(L, minp);
6666 push_v3s16(L, maxp);
6667 lua_pushnumber(L, blockseed);
6668 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6675 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6678 assert(lua_checkstack(L, 20));
6679 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6680 <<name<<"\""<<std::endl;
6681 StackUnroller stack_unroller(L);
6683 // Get minetest.registered_entities[name]
6684 lua_getglobal(L, "minetest");
6685 lua_getfield(L, -1, "registered_entities");
6686 luaL_checktype(L, -1, LUA_TTABLE);
6687 lua_pushstring(L, name);
6688 lua_gettable(L, -2);
6689 // Should be a table, which we will use as a prototype
6690 //luaL_checktype(L, -1, LUA_TTABLE);
6691 if(lua_type(L, -1) != LUA_TTABLE){
6692 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6695 int prototype_table = lua_gettop(L);
6696 //dump2(L, "prototype_table");
6698 // Create entity object
6700 int object = lua_gettop(L);
6702 // Set object metatable
6703 lua_pushvalue(L, prototype_table);
6704 lua_setmetatable(L, -2);
6706 // Add object reference
6707 // This should be userdata with metatable ObjectRef
6708 objectref_get(L, id);
6709 luaL_checktype(L, -1, LUA_TUSERDATA);
6710 if(!luaL_checkudata(L, -1, "ObjectRef"))
6711 luaL_typerror(L, -1, "ObjectRef");
6712 lua_setfield(L, -2, "object");
6714 // minetest.luaentities[id] = object
6715 lua_getglobal(L, "minetest");
6716 lua_getfield(L, -1, "luaentities");
6717 luaL_checktype(L, -1, LUA_TTABLE);
6718 lua_pushnumber(L, id); // Push id
6719 lua_pushvalue(L, object); // Copy object to top of stack
6720 lua_settable(L, -3);
6725 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6726 const std::string &staticdata, u32 dtime_s)
6729 assert(lua_checkstack(L, 20));
6730 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6731 StackUnroller stack_unroller(L);
6733 // Get minetest.luaentities[id]
6734 luaentity_get(L, id);
6735 int object = lua_gettop(L);
6737 // Get on_activate function
6738 lua_pushvalue(L, object);
6739 lua_getfield(L, -1, "on_activate");
6740 if(!lua_isnil(L, -1)){
6741 luaL_checktype(L, -1, LUA_TFUNCTION);
6742 lua_pushvalue(L, object); // self
6743 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6744 lua_pushinteger(L, dtime_s);
6745 // Call with 3 arguments, 0 results
6746 if(lua_pcall(L, 3, 0, 0))
6747 script_error(L, "error running function on_activate: %s\n",
6748 lua_tostring(L, -1));
6752 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6755 assert(lua_checkstack(L, 20));
6756 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6758 // Get minetest.luaentities table
6759 lua_getglobal(L, "minetest");
6760 lua_getfield(L, -1, "luaentities");
6761 luaL_checktype(L, -1, LUA_TTABLE);
6762 int objectstable = lua_gettop(L);
6764 // Set luaentities[id] = nil
6765 lua_pushnumber(L, id); // Push id
6767 lua_settable(L, objectstable);
6769 lua_pop(L, 2); // pop luaentities, minetest
6772 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6775 assert(lua_checkstack(L, 20));
6776 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6777 StackUnroller stack_unroller(L);
6779 // Get minetest.luaentities[id]
6780 luaentity_get(L, id);
6781 int object = lua_gettop(L);
6783 // Get get_staticdata function
6784 lua_pushvalue(L, object);
6785 lua_getfield(L, -1, "get_staticdata");
6786 if(lua_isnil(L, -1))
6789 luaL_checktype(L, -1, LUA_TFUNCTION);
6790 lua_pushvalue(L, object); // self
6791 // Call with 1 arguments, 1 results
6792 if(lua_pcall(L, 1, 1, 0))
6793 script_error(L, "error running function get_staticdata: %s\n",
6794 lua_tostring(L, -1));
6797 const char *s = lua_tolstring(L, -1, &len);
6798 return std::string(s, len);
6801 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6802 ObjectProperties *prop)
6805 assert(lua_checkstack(L, 20));
6806 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6807 StackUnroller stack_unroller(L);
6809 // Get minetest.luaentities[id]
6810 luaentity_get(L, id);
6811 //int object = lua_gettop(L);
6813 // Set default values that differ from ObjectProperties defaults
6818 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6820 getboolfield(L, -1, "physical", prop->physical);
6822 getfloatfield(L, -1, "weight", prop->weight);
6824 lua_getfield(L, -1, "collisionbox");
6825 if(lua_istable(L, -1))
6826 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6829 getstringfield(L, -1, "visual", prop->visual);
6831 getstringfield(L, -1, "mesh", prop->mesh);
6833 // Deprecated: read object properties directly
6834 read_object_properties(L, -1, prop);
6836 // Read initial_properties
6837 lua_getfield(L, -1, "initial_properties");
6838 read_object_properties(L, -1, prop);
6842 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6845 assert(lua_checkstack(L, 20));
6846 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6847 StackUnroller stack_unroller(L);
6849 // Get minetest.luaentities[id]
6850 luaentity_get(L, id);
6851 int object = lua_gettop(L);
6852 // State: object is at top of stack
6853 // Get step function
6854 lua_getfield(L, -1, "on_step");
6855 if(lua_isnil(L, -1))
6857 luaL_checktype(L, -1, LUA_TFUNCTION);
6858 lua_pushvalue(L, object); // self
6859 lua_pushnumber(L, dtime); // dtime
6860 // Call with 2 arguments, 0 results
6861 if(lua_pcall(L, 2, 0, 0))
6862 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6865 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6866 // tool_capabilities, direction)
6867 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6868 ServerActiveObject *puncher, float time_from_last_punch,
6869 const ToolCapabilities *toolcap, v3f dir)
6872 assert(lua_checkstack(L, 20));
6873 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6874 StackUnroller stack_unroller(L);
6876 // Get minetest.luaentities[id]
6877 luaentity_get(L, id);
6878 int object = lua_gettop(L);
6879 // State: object is at top of stack
6881 lua_getfield(L, -1, "on_punch");
6882 if(lua_isnil(L, -1))
6884 luaL_checktype(L, -1, LUA_TFUNCTION);
6885 lua_pushvalue(L, object); // self
6886 objectref_get_or_create(L, puncher); // Clicker reference
6887 lua_pushnumber(L, time_from_last_punch);
6888 push_tool_capabilities(L, *toolcap);
6890 // Call with 5 arguments, 0 results
6891 if(lua_pcall(L, 5, 0, 0))
6892 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6895 // Calls entity:on_rightclick(ObjectRef clicker)
6896 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6897 ServerActiveObject *clicker)
6900 assert(lua_checkstack(L, 20));
6901 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6902 StackUnroller stack_unroller(L);
6904 // Get minetest.luaentities[id]
6905 luaentity_get(L, id);
6906 int object = lua_gettop(L);
6907 // State: object is at top of stack
6909 lua_getfield(L, -1, "on_rightclick");
6910 if(lua_isnil(L, -1))
6912 luaL_checktype(L, -1, LUA_TFUNCTION);
6913 lua_pushvalue(L, object); // self
6914 objectref_get_or_create(L, clicker); // Clicker reference
6915 // Call with 2 arguments, 0 results
6916 if(lua_pcall(L, 2, 0, 0))
6917 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));