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());
2053 InvRef(const InventoryLocation &loc):
2062 // Creates an InvRef and leaves it on top of stack
2063 // Not callable from Lua; all references are created on the C side.
2064 static void create(lua_State *L, const InventoryLocation &loc)
2066 InvRef *o = new InvRef(loc);
2067 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2068 luaL_getmetatable(L, className);
2069 lua_setmetatable(L, -2);
2071 static void createPlayer(lua_State *L, Player *player)
2073 InventoryLocation loc;
2074 loc.setPlayer(player->getName());
2077 static void createNodeMeta(lua_State *L, v3s16 p)
2079 InventoryLocation loc;
2084 static void Register(lua_State *L)
2087 int methodtable = lua_gettop(L);
2088 luaL_newmetatable(L, className);
2089 int metatable = lua_gettop(L);
2091 lua_pushliteral(L, "__metatable");
2092 lua_pushvalue(L, methodtable);
2093 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2095 lua_pushliteral(L, "__index");
2096 lua_pushvalue(L, methodtable);
2097 lua_settable(L, metatable);
2099 lua_pushliteral(L, "__gc");
2100 lua_pushcfunction(L, gc_object);
2101 lua_settable(L, metatable);
2103 lua_pop(L, 1); // drop metatable
2105 luaL_openlib(L, 0, methods, 0); // fill methodtable
2106 lua_pop(L, 1); // drop methodtable
2108 // Cannot be created from Lua
2109 //lua_register(L, className, create_object);
2112 const char InvRef::className[] = "InvRef";
2113 const luaL_reg InvRef::methods[] = {
2114 method(InvRef, is_empty),
2115 method(InvRef, get_size),
2116 method(InvRef, set_size),
2117 method(InvRef, get_width),
2118 method(InvRef, set_width),
2119 method(InvRef, get_stack),
2120 method(InvRef, set_stack),
2121 method(InvRef, get_list),
2122 method(InvRef, set_list),
2123 method(InvRef, add_item),
2124 method(InvRef, room_for_item),
2125 method(InvRef, contains_item),
2126 method(InvRef, remove_item),
2138 ServerEnvironment *m_env;
2140 static const char className[];
2141 static const luaL_reg methods[];
2143 static NodeMetaRef *checkobject(lua_State *L, int narg)
2145 luaL_checktype(L, narg, LUA_TUSERDATA);
2146 void *ud = luaL_checkudata(L, narg, className);
2147 if(!ud) luaL_typerror(L, narg, className);
2148 return *(NodeMetaRef**)ud; // unbox pointer
2151 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2153 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2154 if(meta == NULL && auto_create)
2156 meta = new NodeMetadata(ref->m_env->getGameDef());
2157 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2162 static void reportMetadataChange(NodeMetaRef *ref)
2164 // NOTE: This same code is in rollback_interface.cpp
2165 // Inform other things that the metadata has changed
2166 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2168 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2170 ref->m_env->getMap().dispatchEvent(&event);
2171 // Set the block to be saved
2172 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2174 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2175 "NodeMetaRef::reportMetadataChange");
2178 // Exported functions
2180 // garbage collector
2181 static int gc_object(lua_State *L) {
2182 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2187 // get_string(self, name)
2188 static int l_get_string(lua_State *L)
2190 NodeMetaRef *ref = checkobject(L, 1);
2191 std::string name = luaL_checkstring(L, 2);
2193 NodeMetadata *meta = getmeta(ref, false);
2195 lua_pushlstring(L, "", 0);
2198 std::string str = meta->getString(name);
2199 lua_pushlstring(L, str.c_str(), str.size());
2203 // set_string(self, name, var)
2204 static int l_set_string(lua_State *L)
2206 NodeMetaRef *ref = checkobject(L, 1);
2207 std::string name = luaL_checkstring(L, 2);
2209 const char *s = lua_tolstring(L, 3, &len);
2210 std::string str(s, len);
2212 NodeMetadata *meta = getmeta(ref, !str.empty());
2213 if(meta == NULL || str == meta->getString(name))
2215 meta->setString(name, str);
2216 reportMetadataChange(ref);
2220 // get_int(self, name)
2221 static int l_get_int(lua_State *L)
2223 NodeMetaRef *ref = checkobject(L, 1);
2224 std::string name = lua_tostring(L, 2);
2226 NodeMetadata *meta = getmeta(ref, false);
2228 lua_pushnumber(L, 0);
2231 std::string str = meta->getString(name);
2232 lua_pushnumber(L, stoi(str));
2236 // set_int(self, name, var)
2237 static int l_set_int(lua_State *L)
2239 NodeMetaRef *ref = checkobject(L, 1);
2240 std::string name = lua_tostring(L, 2);
2241 int a = lua_tointeger(L, 3);
2242 std::string str = itos(a);
2244 NodeMetadata *meta = getmeta(ref, true);
2245 if(meta == NULL || str == meta->getString(name))
2247 meta->setString(name, str);
2248 reportMetadataChange(ref);
2252 // get_float(self, name)
2253 static int l_get_float(lua_State *L)
2255 NodeMetaRef *ref = checkobject(L, 1);
2256 std::string name = lua_tostring(L, 2);
2258 NodeMetadata *meta = getmeta(ref, false);
2260 lua_pushnumber(L, 0);
2263 std::string str = meta->getString(name);
2264 lua_pushnumber(L, stof(str));
2268 // set_float(self, name, var)
2269 static int l_set_float(lua_State *L)
2271 NodeMetaRef *ref = checkobject(L, 1);
2272 std::string name = lua_tostring(L, 2);
2273 float a = lua_tonumber(L, 3);
2274 std::string str = ftos(a);
2276 NodeMetadata *meta = getmeta(ref, true);
2277 if(meta == NULL || str == meta->getString(name))
2279 meta->setString(name, str);
2280 reportMetadataChange(ref);
2284 // get_inventory(self)
2285 static int l_get_inventory(lua_State *L)
2287 NodeMetaRef *ref = checkobject(L, 1);
2288 getmeta(ref, true); // try to ensure the metadata exists
2289 InvRef::createNodeMeta(L, ref->m_p);
2294 static int l_to_table(lua_State *L)
2296 NodeMetaRef *ref = checkobject(L, 1);
2298 NodeMetadata *meta = getmeta(ref, true);
2307 std::map<std::string, std::string> fields = meta->getStrings();
2308 for(std::map<std::string, std::string>::const_iterator
2309 i = fields.begin(); i != fields.end(); i++){
2310 const std::string &name = i->first;
2311 const std::string &value = i->second;
2312 lua_pushlstring(L, name.c_str(), name.size());
2313 lua_pushlstring(L, value.c_str(), value.size());
2314 lua_settable(L, -3);
2317 lua_setfield(L, -2, "fields");
2320 Inventory *inv = meta->getInventory();
2322 std::vector<const InventoryList*> lists = inv->getLists();
2323 for(std::vector<const InventoryList*>::const_iterator
2324 i = lists.begin(); i != lists.end(); i++){
2325 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2326 lua_setfield(L, -2, (*i)->getName().c_str());
2329 lua_setfield(L, -2, "inventory");
2333 // from_table(self, table)
2334 static int l_from_table(lua_State *L)
2336 NodeMetaRef *ref = checkobject(L, 1);
2339 if(lua_isnil(L, base)){
2341 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2342 lua_pushboolean(L, true);
2346 // Has metadata; clear old one first
2347 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2348 // Create new metadata
2349 NodeMetadata *meta = getmeta(ref, true);
2351 lua_getfield(L, base, "fields");
2352 int fieldstable = lua_gettop(L);
2354 while(lua_next(L, fieldstable) != 0){
2355 // key at index -2 and value at index -1
2356 std::string name = lua_tostring(L, -2);
2358 const char *cs = lua_tolstring(L, -1, &cl);
2359 std::string value(cs, cl);
2360 meta->setString(name, value);
2361 lua_pop(L, 1); // removes value, keeps key for next iteration
2364 Inventory *inv = meta->getInventory();
2365 lua_getfield(L, base, "inventory");
2366 int inventorytable = lua_gettop(L);
2368 while(lua_next(L, inventorytable) != 0){
2369 // key at index -2 and value at index -1
2370 std::string name = lua_tostring(L, -2);
2371 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2372 lua_pop(L, 1); // removes value, keeps key for next iteration
2374 reportMetadataChange(ref);
2375 lua_pushboolean(L, true);
2380 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2390 // Creates an NodeMetaRef and leaves it on top of stack
2391 // Not callable from Lua; all references are created on the C side.
2392 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2394 NodeMetaRef *o = new NodeMetaRef(p, env);
2395 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2396 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2397 luaL_getmetatable(L, className);
2398 lua_setmetatable(L, -2);
2401 static void Register(lua_State *L)
2404 int methodtable = lua_gettop(L);
2405 luaL_newmetatable(L, className);
2406 int metatable = lua_gettop(L);
2408 lua_pushliteral(L, "__metatable");
2409 lua_pushvalue(L, methodtable);
2410 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2412 lua_pushliteral(L, "__index");
2413 lua_pushvalue(L, methodtable);
2414 lua_settable(L, metatable);
2416 lua_pushliteral(L, "__gc");
2417 lua_pushcfunction(L, gc_object);
2418 lua_settable(L, metatable);
2420 lua_pop(L, 1); // drop metatable
2422 luaL_openlib(L, 0, methods, 0); // fill methodtable
2423 lua_pop(L, 1); // drop methodtable
2425 // Cannot be created from Lua
2426 //lua_register(L, className, create_object);
2429 const char NodeMetaRef::className[] = "NodeMetaRef";
2430 const luaL_reg NodeMetaRef::methods[] = {
2431 method(NodeMetaRef, get_string),
2432 method(NodeMetaRef, set_string),
2433 method(NodeMetaRef, get_int),
2434 method(NodeMetaRef, set_int),
2435 method(NodeMetaRef, get_float),
2436 method(NodeMetaRef, set_float),
2437 method(NodeMetaRef, get_inventory),
2438 method(NodeMetaRef, to_table),
2439 method(NodeMetaRef, from_table),
2450 ServerActiveObject *m_object;
2452 static const char className[];
2453 static const luaL_reg methods[];
2455 static ObjectRef *checkobject(lua_State *L, int narg)
2457 luaL_checktype(L, narg, LUA_TUSERDATA);
2458 void *ud = luaL_checkudata(L, narg, className);
2459 if(!ud) luaL_typerror(L, narg, className);
2460 return *(ObjectRef**)ud; // unbox pointer
2463 static ServerActiveObject* getobject(ObjectRef *ref)
2465 ServerActiveObject *co = ref->m_object;
2469 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2471 ServerActiveObject *obj = getobject(ref);
2474 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2476 return (LuaEntitySAO*)obj;
2479 static PlayerSAO* getplayersao(ObjectRef *ref)
2481 ServerActiveObject *obj = getobject(ref);
2484 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2486 return (PlayerSAO*)obj;
2489 static Player* getplayer(ObjectRef *ref)
2491 PlayerSAO *playersao = getplayersao(ref);
2492 if(playersao == NULL)
2494 return playersao->getPlayer();
2497 // Exported functions
2499 // garbage collector
2500 static int gc_object(lua_State *L) {
2501 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2502 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2508 static int l_remove(lua_State *L)
2510 ObjectRef *ref = checkobject(L, 1);
2511 ServerActiveObject *co = getobject(ref);
2512 if(co == NULL) return 0;
2513 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2514 co->m_removed = true;
2519 // returns: {x=num, y=num, z=num}
2520 static int l_getpos(lua_State *L)
2522 ObjectRef *ref = checkobject(L, 1);
2523 ServerActiveObject *co = getobject(ref);
2524 if(co == NULL) return 0;
2525 v3f pos = co->getBasePosition() / BS;
2527 lua_pushnumber(L, pos.X);
2528 lua_setfield(L, -2, "x");
2529 lua_pushnumber(L, pos.Y);
2530 lua_setfield(L, -2, "y");
2531 lua_pushnumber(L, pos.Z);
2532 lua_setfield(L, -2, "z");
2536 // setpos(self, pos)
2537 static int l_setpos(lua_State *L)
2539 ObjectRef *ref = checkobject(L, 1);
2540 //LuaEntitySAO *co = getluaobject(ref);
2541 ServerActiveObject *co = getobject(ref);
2542 if(co == NULL) return 0;
2544 v3f pos = checkFloatPos(L, 2);
2550 // moveto(self, pos, continuous=false)
2551 static int l_moveto(lua_State *L)
2553 ObjectRef *ref = checkobject(L, 1);
2554 //LuaEntitySAO *co = getluaobject(ref);
2555 ServerActiveObject *co = getobject(ref);
2556 if(co == NULL) return 0;
2558 v3f pos = checkFloatPos(L, 2);
2560 bool continuous = lua_toboolean(L, 3);
2562 co->moveTo(pos, continuous);
2566 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2567 static int l_punch(lua_State *L)
2569 ObjectRef *ref = checkobject(L, 1);
2570 ObjectRef *puncher_ref = checkobject(L, 2);
2571 ServerActiveObject *co = getobject(ref);
2572 ServerActiveObject *puncher = getobject(puncher_ref);
2573 if(co == NULL) return 0;
2574 if(puncher == NULL) return 0;
2576 if(lua_type(L, 5) != LUA_TTABLE)
2577 dir = co->getBasePosition() - puncher->getBasePosition();
2579 dir = read_v3f(L, 5);
2580 float time_from_last_punch = 1000000;
2581 if(lua_isnumber(L, 3))
2582 time_from_last_punch = lua_tonumber(L, 3);
2583 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2586 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2590 // right_click(self, clicker); clicker = an another ObjectRef
2591 static int l_right_click(lua_State *L)
2593 ObjectRef *ref = checkobject(L, 1);
2594 ObjectRef *ref2 = checkobject(L, 2);
2595 ServerActiveObject *co = getobject(ref);
2596 ServerActiveObject *co2 = getobject(ref2);
2597 if(co == NULL) return 0;
2598 if(co2 == NULL) return 0;
2600 co->rightClick(co2);
2605 // hp = number of hitpoints (2 * number of hearts)
2607 static int l_set_hp(lua_State *L)
2609 ObjectRef *ref = checkobject(L, 1);
2610 luaL_checknumber(L, 2);
2611 ServerActiveObject *co = getobject(ref);
2612 if(co == NULL) return 0;
2613 int hp = lua_tonumber(L, 2);
2614 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2615 <<" hp="<<hp<<std::endl;*/
2623 // returns: number of hitpoints (2 * number of hearts)
2624 // 0 if not applicable to this type of object
2625 static int l_get_hp(lua_State *L)
2627 ObjectRef *ref = checkobject(L, 1);
2628 ServerActiveObject *co = getobject(ref);
2631 lua_pushnumber(L, 1);
2634 int hp = co->getHP();
2635 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2636 <<" hp="<<hp<<std::endl;*/
2638 lua_pushnumber(L, hp);
2642 // get_inventory(self)
2643 static int l_get_inventory(lua_State *L)
2645 ObjectRef *ref = checkobject(L, 1);
2646 ServerActiveObject *co = getobject(ref);
2647 if(co == NULL) return 0;
2649 InventoryLocation loc = co->getInventoryLocation();
2650 if(get_server(L)->getInventory(loc) != NULL)
2651 InvRef::create(L, loc);
2653 lua_pushnil(L); // An object may have no inventory (nil)
2657 // get_wield_list(self)
2658 static int l_get_wield_list(lua_State *L)
2660 ObjectRef *ref = checkobject(L, 1);
2661 ServerActiveObject *co = getobject(ref);
2662 if(co == NULL) return 0;
2664 lua_pushstring(L, co->getWieldList().c_str());
2668 // get_wield_index(self)
2669 static int l_get_wield_index(lua_State *L)
2671 ObjectRef *ref = checkobject(L, 1);
2672 ServerActiveObject *co = getobject(ref);
2673 if(co == NULL) return 0;
2675 lua_pushinteger(L, co->getWieldIndex() + 1);
2679 // get_wielded_item(self)
2680 static int l_get_wielded_item(lua_State *L)
2682 ObjectRef *ref = checkobject(L, 1);
2683 ServerActiveObject *co = getobject(ref);
2686 LuaItemStack::create(L, ItemStack());
2690 LuaItemStack::create(L, co->getWieldedItem());
2694 // set_wielded_item(self, itemstack or itemstring or table or nil)
2695 static int l_set_wielded_item(lua_State *L)
2697 ObjectRef *ref = checkobject(L, 1);
2698 ServerActiveObject *co = getobject(ref);
2699 if(co == NULL) return 0;
2701 ItemStack item = read_item(L, 2);
2702 bool success = co->setWieldedItem(item);
2703 lua_pushboolean(L, success);
2707 // set_armor_groups(self, groups)
2708 static int l_set_armor_groups(lua_State *L)
2710 ObjectRef *ref = checkobject(L, 1);
2711 ServerActiveObject *co = getobject(ref);
2712 if(co == NULL) return 0;
2714 ItemGroupList groups;
2715 read_groups(L, 2, groups);
2716 co->setArmorGroups(groups);
2720 // set_animation(self, frame_range, frame_speed, frame_blend)
2721 static int l_set_animation(lua_State *L)
2723 ObjectRef *ref = checkobject(L, 1);
2724 ServerActiveObject *co = getobject(ref);
2725 if(co == NULL) return 0;
2727 v2f frames = v2f(1, 1);
2728 if(!lua_isnil(L, 2))
2729 frames = read_v2f(L, 2);
2730 float frame_speed = 15;
2731 if(!lua_isnil(L, 3))
2732 frame_speed = lua_tonumber(L, 3);
2733 float frame_blend = 0;
2734 if(!lua_isnil(L, 4))
2735 frame_blend = lua_tonumber(L, 4);
2736 co->setAnimation(frames, frame_speed, frame_blend);
2740 // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2741 static int l_set_bone_position(lua_State *L)
2743 ObjectRef *ref = checkobject(L, 1);
2744 ServerActiveObject *co = getobject(ref);
2745 if(co == NULL) return 0;
2747 std::string bone = "";
2748 if(!lua_isnil(L, 2))
2749 bone = lua_tostring(L, 2);
2750 v3f position = v3f(0, 0, 0);
2751 if(!lua_isnil(L, 3))
2752 position = read_v3f(L, 3);
2753 v3f rotation = v3f(0, 0, 0);
2754 if(!lua_isnil(L, 4))
2755 rotation = read_v3f(L, 4);
2756 co->setBonePosition(bone, position, rotation);
2760 // set_attach(self, parent, bone, position, rotation)
2761 static int l_set_attach(lua_State *L)
2763 ObjectRef *ref = checkobject(L, 1);
2764 ObjectRef *parent_ref = checkobject(L, 2);
2765 ServerActiveObject *co = getobject(ref);
2766 ServerActiveObject *parent = getobject(parent_ref);
2767 if(co == NULL) return 0;
2768 if(parent == NULL) return 0;
2770 std::string bone = "";
2771 if(!lua_isnil(L, 3))
2772 bone = lua_tostring(L, 3);
2773 v3f position = v3f(0, 0, 0);
2774 if(!lua_isnil(L, 4))
2775 position = read_v3f(L, 4);
2776 v3f rotation = v3f(0, 0, 0);
2777 if(!lua_isnil(L, 5))
2778 rotation = read_v3f(L, 5);
2779 co->setAttachment(parent->getId(), bone, position, rotation);
2784 static int l_set_detach(lua_State *L)
2786 ObjectRef *ref = checkobject(L, 1);
2787 ServerActiveObject *co = getobject(ref);
2788 if(co == NULL) return 0;
2790 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2794 // set_properties(self, properties)
2795 static int l_set_properties(lua_State *L)
2797 ObjectRef *ref = checkobject(L, 1);
2798 ServerActiveObject *co = getobject(ref);
2799 if(co == NULL) return 0;
2800 ObjectProperties *prop = co->accessObjectProperties();
2803 read_object_properties(L, 2, prop);
2804 co->notifyObjectPropertiesModified();
2808 /* LuaEntitySAO-only */
2810 // setvelocity(self, {x=num, y=num, z=num})
2811 static int l_setvelocity(lua_State *L)
2813 ObjectRef *ref = checkobject(L, 1);
2814 LuaEntitySAO *co = getluaobject(ref);
2815 if(co == NULL) return 0;
2816 v3f pos = checkFloatPos(L, 2);
2818 co->setVelocity(pos);
2822 // getvelocity(self)
2823 static int l_getvelocity(lua_State *L)
2825 ObjectRef *ref = checkobject(L, 1);
2826 LuaEntitySAO *co = getluaobject(ref);
2827 if(co == NULL) return 0;
2829 v3f v = co->getVelocity();
2834 // setacceleration(self, {x=num, y=num, z=num})
2835 static int l_setacceleration(lua_State *L)
2837 ObjectRef *ref = checkobject(L, 1);
2838 LuaEntitySAO *co = getluaobject(ref);
2839 if(co == NULL) return 0;
2841 v3f pos = checkFloatPos(L, 2);
2843 co->setAcceleration(pos);
2847 // getacceleration(self)
2848 static int l_getacceleration(lua_State *L)
2850 ObjectRef *ref = checkobject(L, 1);
2851 LuaEntitySAO *co = getluaobject(ref);
2852 if(co == NULL) return 0;
2854 v3f v = co->getAcceleration();
2859 // setyaw(self, radians)
2860 static int l_setyaw(lua_State *L)
2862 ObjectRef *ref = checkobject(L, 1);
2863 LuaEntitySAO *co = getluaobject(ref);
2864 if(co == NULL) return 0;
2865 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2872 static int l_getyaw(lua_State *L)
2874 ObjectRef *ref = checkobject(L, 1);
2875 LuaEntitySAO *co = getluaobject(ref);
2876 if(co == NULL) return 0;
2878 float yaw = co->getYaw() * core::DEGTORAD;
2879 lua_pushnumber(L, yaw);
2883 // settexturemod(self, mod)
2884 static int l_settexturemod(lua_State *L)
2886 ObjectRef *ref = checkobject(L, 1);
2887 LuaEntitySAO *co = getluaobject(ref);
2888 if(co == NULL) return 0;
2890 std::string mod = luaL_checkstring(L, 2);
2891 co->setTextureMod(mod);
2895 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2896 // select_horiz_by_yawpitch=false)
2897 static int l_setsprite(lua_State *L)
2899 ObjectRef *ref = checkobject(L, 1);
2900 LuaEntitySAO *co = getluaobject(ref);
2901 if(co == NULL) return 0;
2904 if(!lua_isnil(L, 2))
2905 p = read_v2s16(L, 2);
2907 if(!lua_isnil(L, 3))
2908 num_frames = lua_tonumber(L, 3);
2909 float framelength = 0.2;
2910 if(!lua_isnil(L, 4))
2911 framelength = lua_tonumber(L, 4);
2912 bool select_horiz_by_yawpitch = false;
2913 if(!lua_isnil(L, 5))
2914 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2915 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2920 // get_entity_name(self)
2921 static int l_get_entity_name(lua_State *L)
2923 ObjectRef *ref = checkobject(L, 1);
2924 LuaEntitySAO *co = getluaobject(ref);
2925 if(co == NULL) return 0;
2927 std::string name = co->getName();
2928 lua_pushstring(L, name.c_str());
2932 // get_luaentity(self)
2933 static int l_get_luaentity(lua_State *L)
2935 ObjectRef *ref = checkobject(L, 1);
2936 LuaEntitySAO *co = getluaobject(ref);
2937 if(co == NULL) return 0;
2939 luaentity_get(L, co->getId());
2946 static int l_is_player(lua_State *L)
2948 ObjectRef *ref = checkobject(L, 1);
2949 Player *player = getplayer(ref);
2950 lua_pushboolean(L, (player != NULL));
2954 // get_player_name(self)
2955 static int l_get_player_name(lua_State *L)
2957 ObjectRef *ref = checkobject(L, 1);
2958 Player *player = getplayer(ref);
2960 lua_pushlstring(L, "", 0);
2964 lua_pushstring(L, player->getName());
2968 // get_look_dir(self)
2969 static int l_get_look_dir(lua_State *L)
2971 ObjectRef *ref = checkobject(L, 1);
2972 Player *player = getplayer(ref);
2973 if(player == NULL) return 0;
2975 float pitch = player->getRadPitch();
2976 float yaw = player->getRadYaw();
2977 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2982 // get_look_pitch(self)
2983 static int l_get_look_pitch(lua_State *L)
2985 ObjectRef *ref = checkobject(L, 1);
2986 Player *player = getplayer(ref);
2987 if(player == NULL) return 0;
2989 lua_pushnumber(L, player->getRadPitch());
2993 // get_look_yaw(self)
2994 static int l_get_look_yaw(lua_State *L)
2996 ObjectRef *ref = checkobject(L, 1);
2997 Player *player = getplayer(ref);
2998 if(player == NULL) return 0;
3000 lua_pushnumber(L, player->getRadYaw());
3004 // set_inventory_formspec(self, formspec)
3005 static int l_set_inventory_formspec(lua_State *L)
3007 ObjectRef *ref = checkobject(L, 1);
3008 Player *player = getplayer(ref);
3009 if(player == NULL) return 0;
3010 std::string formspec = luaL_checkstring(L, 2);
3012 player->inventory_formspec = formspec;
3013 get_server(L)->reportInventoryFormspecModified(player->getName());
3014 lua_pushboolean(L, true);
3018 // get_inventory_formspec(self) -> formspec
3019 static int l_get_inventory_formspec(lua_State *L)
3021 ObjectRef *ref = checkobject(L, 1);
3022 Player *player = getplayer(ref);
3023 if(player == NULL) return 0;
3025 std::string formspec = player->inventory_formspec;
3026 lua_pushlstring(L, formspec.c_str(), formspec.size());
3030 // get_player_control(self)
3031 static int l_get_player_control(lua_State *L)
3033 ObjectRef *ref = checkobject(L, 1);
3034 Player *player = getplayer(ref);
3036 lua_pushlstring(L, "", 0);
3040 PlayerControl control = player->getPlayerControl();
3042 lua_pushboolean(L, control.up);
3043 lua_setfield(L, -2, "up");
3044 lua_pushboolean(L, control.down);
3045 lua_setfield(L, -2, "down");
3046 lua_pushboolean(L, control.left);
3047 lua_setfield(L, -2, "left");
3048 lua_pushboolean(L, control.right);
3049 lua_setfield(L, -2, "right");
3050 lua_pushboolean(L, control.jump);
3051 lua_setfield(L, -2, "jump");
3052 lua_pushboolean(L, control.aux1);
3053 lua_setfield(L, -2, "aux1");
3054 lua_pushboolean(L, control.sneak);
3055 lua_setfield(L, -2, "sneak");
3056 lua_pushboolean(L, control.LMB);
3057 lua_setfield(L, -2, "LMB");
3058 lua_pushboolean(L, control.RMB);
3059 lua_setfield(L, -2, "RMB");
3063 // get_player_control_bits(self)
3064 static int l_get_player_control_bits(lua_State *L)
3066 ObjectRef *ref = checkobject(L, 1);
3067 Player *player = getplayer(ref);
3069 lua_pushlstring(L, "", 0);
3073 lua_pushnumber(L, player->keyPressed);
3078 ObjectRef(ServerActiveObject *object):
3081 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3087 infostream<<"ObjectRef destructing for id="
3088 <<m_object->getId()<<std::endl;
3090 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3093 // Creates an ObjectRef and leaves it on top of stack
3094 // Not callable from Lua; all references are created on the C side.
3095 static void create(lua_State *L, ServerActiveObject *object)
3097 ObjectRef *o = new ObjectRef(object);
3098 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3099 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3100 luaL_getmetatable(L, className);
3101 lua_setmetatable(L, -2);
3104 static void set_null(lua_State *L)
3106 ObjectRef *o = checkobject(L, -1);
3110 static void Register(lua_State *L)
3113 int methodtable = lua_gettop(L);
3114 luaL_newmetatable(L, className);
3115 int metatable = lua_gettop(L);
3117 lua_pushliteral(L, "__metatable");
3118 lua_pushvalue(L, methodtable);
3119 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3121 lua_pushliteral(L, "__index");
3122 lua_pushvalue(L, methodtable);
3123 lua_settable(L, metatable);
3125 lua_pushliteral(L, "__gc");
3126 lua_pushcfunction(L, gc_object);
3127 lua_settable(L, metatable);
3129 lua_pop(L, 1); // drop metatable
3131 luaL_openlib(L, 0, methods, 0); // fill methodtable
3132 lua_pop(L, 1); // drop methodtable
3134 // Cannot be created from Lua
3135 //lua_register(L, className, create_object);
3138 const char ObjectRef::className[] = "ObjectRef";
3139 const luaL_reg ObjectRef::methods[] = {
3140 // ServerActiveObject
3141 method(ObjectRef, remove),
3142 method(ObjectRef, getpos),
3143 method(ObjectRef, setpos),
3144 method(ObjectRef, moveto),
3145 method(ObjectRef, punch),
3146 method(ObjectRef, right_click),
3147 method(ObjectRef, set_hp),
3148 method(ObjectRef, get_hp),
3149 method(ObjectRef, get_inventory),
3150 method(ObjectRef, get_wield_list),
3151 method(ObjectRef, get_wield_index),
3152 method(ObjectRef, get_wielded_item),
3153 method(ObjectRef, set_wielded_item),
3154 method(ObjectRef, set_armor_groups),
3155 method(ObjectRef, set_animation),
3156 method(ObjectRef, set_bone_position),
3157 method(ObjectRef, set_attach),
3158 method(ObjectRef, set_detach),
3159 method(ObjectRef, set_properties),
3160 // LuaEntitySAO-only
3161 method(ObjectRef, setvelocity),
3162 method(ObjectRef, getvelocity),
3163 method(ObjectRef, setacceleration),
3164 method(ObjectRef, getacceleration),
3165 method(ObjectRef, setyaw),
3166 method(ObjectRef, getyaw),
3167 method(ObjectRef, settexturemod),
3168 method(ObjectRef, setsprite),
3169 method(ObjectRef, get_entity_name),
3170 method(ObjectRef, get_luaentity),
3172 method(ObjectRef, is_player),
3173 method(ObjectRef, get_player_name),
3174 method(ObjectRef, get_look_dir),
3175 method(ObjectRef, get_look_pitch),
3176 method(ObjectRef, get_look_yaw),
3177 method(ObjectRef, set_inventory_formspec),
3178 method(ObjectRef, get_inventory_formspec),
3179 method(ObjectRef, get_player_control),
3180 method(ObjectRef, get_player_control_bits),
3184 // Creates a new anonymous reference if cobj=NULL or id=0
3185 static void objectref_get_or_create(lua_State *L,
3186 ServerActiveObject *cobj)
3188 if(cobj == NULL || cobj->getId() == 0){
3189 ObjectRef::create(L, cobj);
3191 objectref_get(L, cobj->getId());
3200 class LuaPerlinNoise
3207 static const char className[];
3208 static const luaL_reg methods[];
3210 // Exported functions
3212 // garbage collector
3213 static int gc_object(lua_State *L)
3215 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3220 static int l_get2d(lua_State *L)
3222 LuaPerlinNoise *o = checkobject(L, 1);
3223 v2f pos2d = read_v2f(L,2);
3224 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3225 lua_pushnumber(L, val);
3228 static int l_get3d(lua_State *L)
3230 LuaPerlinNoise *o = checkobject(L, 1);
3231 v3f pos3d = read_v3f(L,2);
3232 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3233 lua_pushnumber(L, val);
3238 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3242 persistence(a_persistence),
3251 // LuaPerlinNoise(seed, octaves, persistence, scale)
3252 // Creates an LuaPerlinNoise and leaves it on top of stack
3253 static int create_object(lua_State *L)
3255 int seed = luaL_checkint(L, 1);
3256 int octaves = luaL_checkint(L, 2);
3257 double persistence = luaL_checknumber(L, 3);
3258 double scale = luaL_checknumber(L, 4);
3259 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3260 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3261 luaL_getmetatable(L, className);
3262 lua_setmetatable(L, -2);
3266 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3268 luaL_checktype(L, narg, LUA_TUSERDATA);
3269 void *ud = luaL_checkudata(L, narg, className);
3270 if(!ud) luaL_typerror(L, narg, className);
3271 return *(LuaPerlinNoise**)ud; // unbox pointer
3274 static void Register(lua_State *L)
3277 int methodtable = lua_gettop(L);
3278 luaL_newmetatable(L, className);
3279 int metatable = lua_gettop(L);
3281 lua_pushliteral(L, "__metatable");
3282 lua_pushvalue(L, methodtable);
3283 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3285 lua_pushliteral(L, "__index");
3286 lua_pushvalue(L, methodtable);
3287 lua_settable(L, metatable);
3289 lua_pushliteral(L, "__gc");
3290 lua_pushcfunction(L, gc_object);
3291 lua_settable(L, metatable);
3293 lua_pop(L, 1); // drop metatable
3295 luaL_openlib(L, 0, methods, 0); // fill methodtable
3296 lua_pop(L, 1); // drop methodtable
3298 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3299 lua_register(L, className, create_object);
3302 const char LuaPerlinNoise::className[] = "PerlinNoise";
3303 const luaL_reg LuaPerlinNoise::methods[] = {
3304 method(LuaPerlinNoise, get2d),
3305 method(LuaPerlinNoise, get3d),
3317 ServerEnvironment *m_env;
3319 static const char className[];
3320 static const luaL_reg methods[];
3322 static int gc_object(lua_State *L) {
3323 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3328 static NodeTimerRef *checkobject(lua_State *L, int narg)
3330 luaL_checktype(L, narg, LUA_TUSERDATA);
3331 void *ud = luaL_checkudata(L, narg, className);
3332 if(!ud) luaL_typerror(L, narg, className);
3333 return *(NodeTimerRef**)ud; // unbox pointer
3336 static int l_set(lua_State *L)
3338 NodeTimerRef *o = checkobject(L, 1);
3339 ServerEnvironment *env = o->m_env;
3340 if(env == NULL) return 0;
3341 f32 t = luaL_checknumber(L,2);
3342 f32 e = luaL_checknumber(L,3);
3343 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3347 static int l_start(lua_State *L)
3349 NodeTimerRef *o = checkobject(L, 1);
3350 ServerEnvironment *env = o->m_env;
3351 if(env == NULL) return 0;
3352 f32 t = luaL_checknumber(L,2);
3353 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3357 static int l_stop(lua_State *L)
3359 NodeTimerRef *o = checkobject(L, 1);
3360 ServerEnvironment *env = o->m_env;
3361 if(env == NULL) return 0;
3362 env->getMap().removeNodeTimer(o->m_p);
3366 static int l_is_started(lua_State *L)
3368 NodeTimerRef *o = checkobject(L, 1);
3369 ServerEnvironment *env = o->m_env;
3370 if(env == NULL) return 0;
3372 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3373 lua_pushboolean(L,(t.timeout != 0));
3377 static int l_get_timeout(lua_State *L)
3379 NodeTimerRef *o = checkobject(L, 1);
3380 ServerEnvironment *env = o->m_env;
3381 if(env == NULL) return 0;
3383 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3384 lua_pushnumber(L,t.timeout);
3388 static int l_get_elapsed(lua_State *L)
3390 NodeTimerRef *o = checkobject(L, 1);
3391 ServerEnvironment *env = o->m_env;
3392 if(env == NULL) return 0;
3394 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3395 lua_pushnumber(L,t.elapsed);
3400 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3410 // Creates an NodeTimerRef and leaves it on top of stack
3411 // Not callable from Lua; all references are created on the C side.
3412 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3414 NodeTimerRef *o = new NodeTimerRef(p, env);
3415 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3416 luaL_getmetatable(L, className);
3417 lua_setmetatable(L, -2);
3420 static void set_null(lua_State *L)
3422 NodeTimerRef *o = checkobject(L, -1);
3426 static void Register(lua_State *L)
3429 int methodtable = lua_gettop(L);
3430 luaL_newmetatable(L, className);
3431 int metatable = lua_gettop(L);
3433 lua_pushliteral(L, "__metatable");
3434 lua_pushvalue(L, methodtable);
3435 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3437 lua_pushliteral(L, "__index");
3438 lua_pushvalue(L, methodtable);
3439 lua_settable(L, metatable);
3441 lua_pushliteral(L, "__gc");
3442 lua_pushcfunction(L, gc_object);
3443 lua_settable(L, metatable);
3445 lua_pop(L, 1); // drop metatable
3447 luaL_openlib(L, 0, methods, 0); // fill methodtable
3448 lua_pop(L, 1); // drop methodtable
3450 // Cannot be created from Lua
3451 //lua_register(L, className, create_object);
3454 const char NodeTimerRef::className[] = "NodeTimerRef";
3455 const luaL_reg NodeTimerRef::methods[] = {
3456 method(NodeTimerRef, start),
3457 method(NodeTimerRef, set),
3458 method(NodeTimerRef, stop),
3459 method(NodeTimerRef, is_started),
3460 method(NodeTimerRef, get_timeout),
3461 method(NodeTimerRef, get_elapsed),
3472 ServerEnvironment *m_env;
3474 static const char className[];
3475 static const luaL_reg methods[];
3477 static int gc_object(lua_State *L) {
3478 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3483 static EnvRef *checkobject(lua_State *L, int narg)
3485 luaL_checktype(L, narg, LUA_TUSERDATA);
3486 void *ud = luaL_checkudata(L, narg, className);
3487 if(!ud) luaL_typerror(L, narg, className);
3488 return *(EnvRef**)ud; // unbox pointer
3491 // Exported functions
3493 // EnvRef:set_node(pos, node)
3494 // pos = {x=num, y=num, z=num}
3495 static int l_set_node(lua_State *L)
3497 EnvRef *o = checkobject(L, 1);
3498 ServerEnvironment *env = o->m_env;
3499 if(env == NULL) return 0;
3500 INodeDefManager *ndef = env->getGameDef()->ndef();
3502 v3s16 pos = read_v3s16(L, 2);
3503 MapNode n = readnode(L, 3, ndef);
3505 MapNode n_old = env->getMap().getNodeNoEx(pos);
3507 if(ndef->get(n_old).has_on_destruct)
3508 scriptapi_node_on_destruct(L, pos, n_old);
3510 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3512 // Call post-destructor
3513 if(ndef->get(n_old).has_after_destruct)
3514 scriptapi_node_after_destruct(L, pos, n_old);
3516 if(ndef->get(n).has_on_construct)
3517 scriptapi_node_on_construct(L, pos, n);
3519 lua_pushboolean(L, succeeded);
3523 static int l_add_node(lua_State *L)
3525 return l_set_node(L);
3528 // EnvRef:remove_node(pos)
3529 // pos = {x=num, y=num, z=num}
3530 static int l_remove_node(lua_State *L)
3532 EnvRef *o = checkobject(L, 1);
3533 ServerEnvironment *env = o->m_env;
3534 if(env == NULL) return 0;
3535 INodeDefManager *ndef = env->getGameDef()->ndef();
3537 v3s16 pos = read_v3s16(L, 2);
3539 MapNode n_old = env->getMap().getNodeNoEx(pos);
3541 if(ndef->get(n_old).has_on_destruct)
3542 scriptapi_node_on_destruct(L, pos, n_old);
3544 // This is slightly optimized compared to addNodeWithEvent(air)
3545 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3547 // Call post-destructor
3548 if(ndef->get(n_old).has_after_destruct)
3549 scriptapi_node_after_destruct(L, pos, n_old);
3551 lua_pushboolean(L, succeeded);
3552 // Air doesn't require constructor
3556 // EnvRef:get_node(pos)
3557 // pos = {x=num, y=num, z=num}
3558 static int l_get_node(lua_State *L)
3560 EnvRef *o = checkobject(L, 1);
3561 ServerEnvironment *env = o->m_env;
3562 if(env == NULL) return 0;
3564 v3s16 pos = read_v3s16(L, 2);
3566 MapNode n = env->getMap().getNodeNoEx(pos);
3568 pushnode(L, n, env->getGameDef()->ndef());
3572 // EnvRef:get_node_or_nil(pos)
3573 // pos = {x=num, y=num, z=num}
3574 static int l_get_node_or_nil(lua_State *L)
3576 EnvRef *o = checkobject(L, 1);
3577 ServerEnvironment *env = o->m_env;
3578 if(env == NULL) return 0;
3580 v3s16 pos = read_v3s16(L, 2);
3583 MapNode n = env->getMap().getNode(pos);
3585 pushnode(L, n, env->getGameDef()->ndef());
3587 } catch(InvalidPositionException &e)
3594 // EnvRef:get_node_light(pos, timeofday)
3595 // pos = {x=num, y=num, z=num}
3596 // timeofday: nil = current time, 0 = night, 0.5 = day
3597 static int l_get_node_light(lua_State *L)
3599 EnvRef *o = checkobject(L, 1);
3600 ServerEnvironment *env = o->m_env;
3601 if(env == NULL) return 0;
3603 v3s16 pos = read_v3s16(L, 2);
3604 u32 time_of_day = env->getTimeOfDay();
3605 if(lua_isnumber(L, 3))
3606 time_of_day = 24000.0 * lua_tonumber(L, 3);
3607 time_of_day %= 24000;
3608 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3609 MapNode n = env->getMap().getNodeNoEx(pos);
3611 MapNode n = env->getMap().getNode(pos);
3612 INodeDefManager *ndef = env->getGameDef()->ndef();
3613 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3615 } catch(InvalidPositionException &e)
3622 // EnvRef:place_node(pos, node)
3623 // pos = {x=num, y=num, z=num}
3624 static int l_place_node(lua_State *L)
3626 EnvRef *o = checkobject(L, 1);
3627 ServerEnvironment *env = o->m_env;
3628 if(env == NULL) return 0;
3629 v3s16 pos = read_v3s16(L, 2);
3630 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3632 // Don't attempt to load non-loaded area as of now
3633 MapNode n_old = env->getMap().getNodeNoEx(pos);
3634 if(n_old.getContent() == CONTENT_IGNORE){
3635 lua_pushboolean(L, false);
3638 // Create item to place
3639 INodeDefManager *ndef = get_server(L)->ndef();
3640 IItemDefManager *idef = get_server(L)->idef();
3641 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3642 // Make pointed position
3643 PointedThing pointed;
3644 pointed.type = POINTEDTHING_NODE;
3645 pointed.node_abovesurface = pos;
3646 pointed.node_undersurface = pos + v3s16(0,-1,0);
3647 // Place it with a NULL placer (appears in Lua as a non-functional
3649 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3650 lua_pushboolean(L, success);
3654 // EnvRef:dig_node(pos)
3655 // pos = {x=num, y=num, z=num}
3656 static int l_dig_node(lua_State *L)
3658 EnvRef *o = checkobject(L, 1);
3659 ServerEnvironment *env = o->m_env;
3660 if(env == NULL) return 0;
3661 v3s16 pos = read_v3s16(L, 2);
3663 // Don't attempt to load non-loaded area as of now
3664 MapNode n = env->getMap().getNodeNoEx(pos);
3665 if(n.getContent() == CONTENT_IGNORE){
3666 lua_pushboolean(L, false);
3669 // Dig it out with a NULL digger (appears in Lua as a
3670 // non-functional ObjectRef)
3671 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3672 lua_pushboolean(L, success);
3676 // EnvRef:punch_node(pos)
3677 // pos = {x=num, y=num, z=num}
3678 static int l_punch_node(lua_State *L)
3680 EnvRef *o = checkobject(L, 1);
3681 ServerEnvironment *env = o->m_env;
3682 if(env == NULL) return 0;
3683 v3s16 pos = read_v3s16(L, 2);
3685 // Don't attempt to load non-loaded area as of now
3686 MapNode n = env->getMap().getNodeNoEx(pos);
3687 if(n.getContent() == CONTENT_IGNORE){
3688 lua_pushboolean(L, false);
3691 // Punch it with a NULL puncher (appears in Lua as a non-functional
3693 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3694 lua_pushboolean(L, success);
3698 // EnvRef:get_meta(pos)
3699 static int l_get_meta(lua_State *L)
3701 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3702 EnvRef *o = checkobject(L, 1);
3703 ServerEnvironment *env = o->m_env;
3704 if(env == NULL) return 0;
3706 v3s16 p = read_v3s16(L, 2);
3707 NodeMetaRef::create(L, p, env);
3711 // EnvRef:get_node_timer(pos)
3712 static int l_get_node_timer(lua_State *L)
3714 EnvRef *o = checkobject(L, 1);
3715 ServerEnvironment *env = o->m_env;
3716 if(env == NULL) return 0;
3718 v3s16 p = read_v3s16(L, 2);
3719 NodeTimerRef::create(L, p, env);
3723 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3724 // pos = {x=num, y=num, z=num}
3725 static int l_add_entity(lua_State *L)
3727 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3728 EnvRef *o = checkobject(L, 1);
3729 ServerEnvironment *env = o->m_env;
3730 if(env == NULL) return 0;
3732 v3f pos = checkFloatPos(L, 2);
3734 const char *name = luaL_checkstring(L, 3);
3736 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3737 int objectid = env->addActiveObject(obj);
3738 // If failed to add, return nothing (reads as nil)
3742 objectref_get_or_create(L, obj);
3746 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3747 // pos = {x=num, y=num, z=num}
3748 static int l_add_item(lua_State *L)
3750 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3751 EnvRef *o = checkobject(L, 1);
3752 ServerEnvironment *env = o->m_env;
3753 if(env == NULL) return 0;
3755 v3f pos = checkFloatPos(L, 2);
3757 ItemStack item = read_item(L, 3);
3758 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3760 // Use minetest.spawn_item to spawn a __builtin:item
3761 lua_getglobal(L, "minetest");
3762 lua_getfield(L, -1, "spawn_item");
3763 if(lua_isnil(L, -1))
3765 lua_pushvalue(L, 2);
3766 lua_pushstring(L, item.getItemString().c_str());
3767 if(lua_pcall(L, 2, 1, 0))
3768 script_error(L, "error: %s", lua_tostring(L, -1));
3770 /*lua_pushvalue(L, 1);
3771 lua_pushstring(L, "__builtin:item");
3772 lua_pushstring(L, item.getItemString().c_str());
3773 return l_add_entity(L);*/
3775 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3776 int objectid = env->addActiveObject(obj);
3777 // If failed to add, return nothing (reads as nil)
3781 objectref_get_or_create(L, obj);
3785 // EnvRef:add_rat(pos)
3786 // pos = {x=num, y=num, z=num}
3787 static int l_add_rat(lua_State *L)
3789 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3790 <<" Doing nothing."<<std::endl;
3794 // EnvRef:add_firefly(pos)
3795 // pos = {x=num, y=num, z=num}
3796 static int l_add_firefly(lua_State *L)
3798 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3799 <<" Doing nothing."<<std::endl;
3803 // EnvRef:get_player_by_name(name)
3804 static int l_get_player_by_name(lua_State *L)
3806 EnvRef *o = checkobject(L, 1);
3807 ServerEnvironment *env = o->m_env;
3808 if(env == NULL) return 0;
3810 const char *name = luaL_checkstring(L, 2);
3811 Player *player = env->getPlayer(name);
3816 PlayerSAO *sao = player->getPlayerSAO();
3821 // Put player on stack
3822 objectref_get_or_create(L, sao);
3826 // EnvRef:get_objects_inside_radius(pos, radius)
3827 static int l_get_objects_inside_radius(lua_State *L)
3829 // Get the table insert function
3830 lua_getglobal(L, "table");
3831 lua_getfield(L, -1, "insert");
3832 int table_insert = lua_gettop(L);
3834 EnvRef *o = checkobject(L, 1);
3835 ServerEnvironment *env = o->m_env;
3836 if(env == NULL) return 0;
3838 v3f pos = checkFloatPos(L, 2);
3839 float radius = luaL_checknumber(L, 3) * BS;
3840 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3842 int table = lua_gettop(L);
3843 for(std::set<u16>::const_iterator
3844 i = ids.begin(); i != ids.end(); i++){
3845 ServerActiveObject *obj = env->getActiveObject(*i);
3846 // Insert object reference into table
3847 lua_pushvalue(L, table_insert);
3848 lua_pushvalue(L, table);
3849 objectref_get_or_create(L, obj);
3850 if(lua_pcall(L, 2, 0, 0))
3851 script_error(L, "error: %s", lua_tostring(L, -1));
3856 // EnvRef:set_timeofday(val)
3858 static int l_set_timeofday(lua_State *L)
3860 EnvRef *o = checkobject(L, 1);
3861 ServerEnvironment *env = o->m_env;
3862 if(env == NULL) return 0;
3864 float timeofday_f = luaL_checknumber(L, 2);
3865 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3866 int timeofday_mh = (int)(timeofday_f * 24000.0);
3867 // This should be set directly in the environment but currently
3868 // such changes aren't immediately sent to the clients, so call
3869 // the server instead.
3870 //env->setTimeOfDay(timeofday_mh);
3871 get_server(L)->setTimeOfDay(timeofday_mh);
3875 // EnvRef:get_timeofday() -> 0...1
3876 static int l_get_timeofday(lua_State *L)
3878 EnvRef *o = checkobject(L, 1);
3879 ServerEnvironment *env = o->m_env;
3880 if(env == NULL) return 0;
3882 int timeofday_mh = env->getTimeOfDay();
3883 float timeofday_f = (float)timeofday_mh / 24000.0;
3884 lua_pushnumber(L, timeofday_f);
3889 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3890 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3891 static int l_find_node_near(lua_State *L)
3893 EnvRef *o = checkobject(L, 1);
3894 ServerEnvironment *env = o->m_env;
3895 if(env == NULL) return 0;
3896 INodeDefManager *ndef = get_server(L)->ndef();
3897 v3s16 pos = read_v3s16(L, 2);
3898 int radius = luaL_checkinteger(L, 3);
3899 std::set<content_t> filter;
3900 if(lua_istable(L, 4)){
3903 while(lua_next(L, table) != 0){
3904 // key at index -2 and value at index -1
3905 luaL_checktype(L, -1, LUA_TSTRING);
3906 ndef->getIds(lua_tostring(L, -1), filter);
3907 // removes value, keeps key for next iteration
3910 } else if(lua_isstring(L, 4)){
3911 ndef->getIds(lua_tostring(L, 4), filter);
3914 for(int d=1; d<=radius; d++){
3915 core::list<v3s16> list;
3916 getFacePositions(list, d);
3917 for(core::list<v3s16>::Iterator i = list.begin();
3918 i != list.end(); i++){
3919 v3s16 p = pos + (*i);
3920 content_t c = env->getMap().getNodeNoEx(p).getContent();
3921 if(filter.count(c) != 0){
3930 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3931 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3932 static int l_find_nodes_in_area(lua_State *L)
3934 EnvRef *o = checkobject(L, 1);
3935 ServerEnvironment *env = o->m_env;
3936 if(env == NULL) return 0;
3937 INodeDefManager *ndef = get_server(L)->ndef();
3938 v3s16 minp = read_v3s16(L, 2);
3939 v3s16 maxp = read_v3s16(L, 3);
3940 std::set<content_t> filter;
3941 if(lua_istable(L, 4)){
3944 while(lua_next(L, table) != 0){
3945 // key at index -2 and value at index -1
3946 luaL_checktype(L, -1, LUA_TSTRING);
3947 ndef->getIds(lua_tostring(L, -1), filter);
3948 // removes value, keeps key for next iteration
3951 } else if(lua_isstring(L, 4)){
3952 ndef->getIds(lua_tostring(L, 4), filter);
3955 // Get the table insert function
3956 lua_getglobal(L, "table");
3957 lua_getfield(L, -1, "insert");
3958 int table_insert = lua_gettop(L);
3961 int table = lua_gettop(L);
3962 for(s16 x=minp.X; x<=maxp.X; x++)
3963 for(s16 y=minp.Y; y<=maxp.Y; y++)
3964 for(s16 z=minp.Z; z<=maxp.Z; z++)
3967 content_t c = env->getMap().getNodeNoEx(p).getContent();
3968 if(filter.count(c) != 0){
3969 lua_pushvalue(L, table_insert);
3970 lua_pushvalue(L, table);
3972 if(lua_pcall(L, 2, 0, 0))
3973 script_error(L, "error: %s", lua_tostring(L, -1));
3979 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3980 // returns world-specific PerlinNoise
3981 static int l_get_perlin(lua_State *L)
3983 EnvRef *o = checkobject(L, 1);
3984 ServerEnvironment *env = o->m_env;
3985 if(env == NULL) return 0;
3987 int seeddiff = luaL_checkint(L, 2);
3988 int octaves = luaL_checkint(L, 3);
3989 double persistence = luaL_checknumber(L, 4);
3990 double scale = luaL_checknumber(L, 5);
3992 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3993 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3994 luaL_getmetatable(L, "PerlinNoise");
3995 lua_setmetatable(L, -2);
3999 // EnvRef:clear_objects()
4000 // clear all objects in the environment
4001 static int l_clear_objects(lua_State *L)
4003 EnvRef *o = checkobject(L, 1);
4004 o->m_env->clearAllObjects();
4008 static int l_spawn_tree(lua_State *L)
4010 EnvRef *o = checkobject(L, 1);
4011 ServerEnvironment *env = o->m_env;
4012 if(env == NULL) return 0;
4013 v3s16 p0 = read_v3s16(L, 2);
4015 treegen::TreeDef tree_def;
4016 std::string trunk,leaves,fruit;
4017 INodeDefManager *ndef = env->getGameDef()->ndef();
4019 if(lua_istable(L, 3))
4021 getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4022 getstringfield(L, 3, "rules_a", tree_def.rules_a);
4023 getstringfield(L, 3, "rules_b", tree_def.rules_b);
4024 getstringfield(L, 3, "rules_c", tree_def.rules_a);
4025 getstringfield(L, 3, "rules_d", tree_def.rules_b);
4026 getstringfield(L, 3, "trunk", trunk);
4027 tree_def.trunknode=ndef->getId(trunk);
4028 getstringfield(L, 3, "leaves", leaves);
4029 tree_def.leavesnode=ndef->getId(leaves);
4030 getintfield(L, 3, "angle", tree_def.angle);
4031 getintfield(L, 3, "iterations", tree_def.iterations);
4032 getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4033 getboolfield(L, 3, "thin_trunks", tree_def.thin_trunks);
4034 getboolfield(L, 3, "fruit_tree", tree_def.fruit_tree);
4035 if (tree_def.fruit_tree)
4037 getstringfield(L, 3, "fruit", fruit);
4038 tree_def.fruitnode=ndef->getId(fruit);
4043 treegen::spawn_ltree (env, p0, ndef, tree_def);
4048 EnvRef(ServerEnvironment *env):
4051 //infostream<<"EnvRef created"<<std::endl;
4056 //infostream<<"EnvRef destructing"<<std::endl;
4059 // Creates an EnvRef and leaves it on top of stack
4060 // Not callable from Lua; all references are created on the C side.
4061 static void create(lua_State *L, ServerEnvironment *env)
4063 EnvRef *o = new EnvRef(env);
4064 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4065 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4066 luaL_getmetatable(L, className);
4067 lua_setmetatable(L, -2);
4070 static void set_null(lua_State *L)
4072 EnvRef *o = checkobject(L, -1);
4076 static void Register(lua_State *L)
4079 int methodtable = lua_gettop(L);
4080 luaL_newmetatable(L, className);
4081 int metatable = lua_gettop(L);
4083 lua_pushliteral(L, "__metatable");
4084 lua_pushvalue(L, methodtable);
4085 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4087 lua_pushliteral(L, "__index");
4088 lua_pushvalue(L, methodtable);
4089 lua_settable(L, metatable);
4091 lua_pushliteral(L, "__gc");
4092 lua_pushcfunction(L, gc_object);
4093 lua_settable(L, metatable);
4095 lua_pop(L, 1); // drop metatable
4097 luaL_openlib(L, 0, methods, 0); // fill methodtable
4098 lua_pop(L, 1); // drop methodtable
4100 // Cannot be created from Lua
4101 //lua_register(L, className, create_object);
4104 const char EnvRef::className[] = "EnvRef";
4105 const luaL_reg EnvRef::methods[] = {
4106 method(EnvRef, set_node),
4107 method(EnvRef, add_node),
4108 method(EnvRef, remove_node),
4109 method(EnvRef, get_node),
4110 method(EnvRef, get_node_or_nil),
4111 method(EnvRef, get_node_light),
4112 method(EnvRef, place_node),
4113 method(EnvRef, dig_node),
4114 method(EnvRef, punch_node),
4115 method(EnvRef, add_entity),
4116 method(EnvRef, add_item),
4117 method(EnvRef, add_rat),
4118 method(EnvRef, add_firefly),
4119 method(EnvRef, get_meta),
4120 method(EnvRef, get_node_timer),
4121 method(EnvRef, get_player_by_name),
4122 method(EnvRef, get_objects_inside_radius),
4123 method(EnvRef, set_timeofday),
4124 method(EnvRef, get_timeofday),
4125 method(EnvRef, find_node_near),
4126 method(EnvRef, find_nodes_in_area),
4127 method(EnvRef, get_perlin),
4128 method(EnvRef, clear_objects),
4129 method(EnvRef, spawn_tree),
4138 class LuaPseudoRandom
4141 PseudoRandom m_pseudo;
4143 static const char className[];
4144 static const luaL_reg methods[];
4146 // Exported functions
4148 // garbage collector
4149 static int gc_object(lua_State *L)
4151 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4156 // next(self, min=0, max=32767) -> get next value
4157 static int l_next(lua_State *L)
4159 LuaPseudoRandom *o = checkobject(L, 1);
4162 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4163 if(!lua_isnil(L, 2))
4164 min = luaL_checkinteger(L, 2);
4165 if(!lua_isnil(L, 3))
4166 max = luaL_checkinteger(L, 3);
4168 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4169 throw LuaError(L, "PseudoRandom.next(): max < min");
4171 if(max - min != 32767 && max - min > 32767/5)
4172 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.");
4173 PseudoRandom &pseudo = o->m_pseudo;
4174 int val = pseudo.next();
4175 val = (val % (max-min+1)) + min;
4176 lua_pushinteger(L, val);
4181 LuaPseudoRandom(int seed):
4190 const PseudoRandom& getItem() const
4194 PseudoRandom& getItem()
4199 // LuaPseudoRandom(seed)
4200 // Creates an LuaPseudoRandom and leaves it on top of stack
4201 static int create_object(lua_State *L)
4203 int seed = luaL_checknumber(L, 1);
4204 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4205 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4206 luaL_getmetatable(L, className);
4207 lua_setmetatable(L, -2);
4211 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4213 luaL_checktype(L, narg, LUA_TUSERDATA);
4214 void *ud = luaL_checkudata(L, narg, className);
4215 if(!ud) luaL_typerror(L, narg, className);
4216 return *(LuaPseudoRandom**)ud; // unbox pointer
4219 static void Register(lua_State *L)
4222 int methodtable = lua_gettop(L);
4223 luaL_newmetatable(L, className);
4224 int metatable = lua_gettop(L);
4226 lua_pushliteral(L, "__metatable");
4227 lua_pushvalue(L, methodtable);
4228 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4230 lua_pushliteral(L, "__index");
4231 lua_pushvalue(L, methodtable);
4232 lua_settable(L, metatable);
4234 lua_pushliteral(L, "__gc");
4235 lua_pushcfunction(L, gc_object);
4236 lua_settable(L, metatable);
4238 lua_pop(L, 1); // drop metatable
4240 luaL_openlib(L, 0, methods, 0); // fill methodtable
4241 lua_pop(L, 1); // drop methodtable
4243 // Can be created from Lua (LuaPseudoRandom(seed))
4244 lua_register(L, className, create_object);
4247 const char LuaPseudoRandom::className[] = "PseudoRandom";
4248 const luaL_reg LuaPseudoRandom::methods[] = {
4249 method(LuaPseudoRandom, next),
4259 class LuaABM : public ActiveBlockModifier
4265 std::set<std::string> m_trigger_contents;
4266 std::set<std::string> m_required_neighbors;
4267 float m_trigger_interval;
4268 u32 m_trigger_chance;
4270 LuaABM(lua_State *L, int id,
4271 const std::set<std::string> &trigger_contents,
4272 const std::set<std::string> &required_neighbors,
4273 float trigger_interval, u32 trigger_chance):
4276 m_trigger_contents(trigger_contents),
4277 m_required_neighbors(required_neighbors),
4278 m_trigger_interval(trigger_interval),
4279 m_trigger_chance(trigger_chance)
4282 virtual std::set<std::string> getTriggerContents()
4284 return m_trigger_contents;
4286 virtual std::set<std::string> getRequiredNeighbors()
4288 return m_required_neighbors;
4290 virtual float getTriggerInterval()
4292 return m_trigger_interval;
4294 virtual u32 getTriggerChance()
4296 return m_trigger_chance;
4298 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4299 u32 active_object_count, u32 active_object_count_wider)
4301 lua_State *L = m_lua;
4304 assert(lua_checkstack(L, 20));
4305 StackUnroller stack_unroller(L);
4307 // Get minetest.registered_abms
4308 lua_getglobal(L, "minetest");
4309 lua_getfield(L, -1, "registered_abms");
4310 luaL_checktype(L, -1, LUA_TTABLE);
4311 int registered_abms = lua_gettop(L);
4313 // Get minetest.registered_abms[m_id]
4314 lua_pushnumber(L, m_id);
4315 lua_gettable(L, registered_abms);
4316 if(lua_isnil(L, -1))
4320 luaL_checktype(L, -1, LUA_TTABLE);
4321 lua_getfield(L, -1, "action");
4322 luaL_checktype(L, -1, LUA_TFUNCTION);
4324 pushnode(L, n, env->getGameDef()->ndef());
4325 lua_pushnumber(L, active_object_count);
4326 lua_pushnumber(L, active_object_count_wider);
4327 if(lua_pcall(L, 4, 0, 0))
4328 script_error(L, "error: %s", lua_tostring(L, -1));
4336 static void read_server_sound_params(lua_State *L, int index,
4337 ServerSoundParams ¶ms)
4340 index = lua_gettop(L) + 1 + index;
4342 params = ServerSoundParams();
4343 if(lua_istable(L, index)){
4344 getfloatfield(L, index, "gain", params.gain);
4345 getstringfield(L, index, "to_player", params.to_player);
4346 lua_getfield(L, index, "pos");
4347 if(!lua_isnil(L, -1)){
4348 v3f p = read_v3f(L, -1)*BS;
4350 params.type = ServerSoundParams::SSP_POSITIONAL;
4353 lua_getfield(L, index, "object");
4354 if(!lua_isnil(L, -1)){
4355 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4356 ServerActiveObject *sao = ObjectRef::getobject(ref);
4358 params.object = sao->getId();
4359 params.type = ServerSoundParams::SSP_OBJECT;
4363 params.max_hear_distance = BS*getfloatfield_default(L, index,
4364 "max_hear_distance", params.max_hear_distance/BS);
4365 getboolfield(L, index, "loop", params.loop);
4374 // Writes a line to dstream
4375 static int l_debug(lua_State *L)
4377 std::string text = lua_tostring(L, 1);
4378 dstream << text << std::endl;
4382 // log([level,] text)
4383 // Writes a line to the logger.
4384 // The one-argument version logs to infostream.
4385 // The two-argument version accept a log level: error, action, info, or verbose.
4386 static int l_log(lua_State *L)
4389 LogMessageLevel level = LMT_INFO;
4390 if(lua_isnone(L, 2))
4392 text = lua_tostring(L, 1);
4396 std::string levelname = lua_tostring(L, 1);
4397 text = lua_tostring(L, 2);
4398 if(levelname == "error")
4400 else if(levelname == "action")
4402 else if(levelname == "verbose")
4403 level = LMT_VERBOSE;
4405 log_printline(level, text);
4409 // request_shutdown()
4410 static int l_request_shutdown(lua_State *L)
4412 get_server(L)->requestShutdown();
4416 // get_server_status()
4417 static int l_get_server_status(lua_State *L)
4419 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4423 // register_item_raw({lots of stuff})
4424 static int l_register_item_raw(lua_State *L)
4426 luaL_checktype(L, 1, LUA_TTABLE);
4429 // Get the writable item and node definition managers from the server
4430 IWritableItemDefManager *idef =
4431 get_server(L)->getWritableItemDefManager();
4432 IWritableNodeDefManager *ndef =
4433 get_server(L)->getWritableNodeDefManager();
4435 // Check if name is defined
4437 lua_getfield(L, table, "name");
4438 if(lua_isstring(L, -1)){
4439 name = lua_tostring(L, -1);
4440 verbosestream<<"register_item_raw: "<<name<<std::endl;
4442 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4445 // Check if on_use is defined
4448 // Set a distinctive default value to check if this is set
4449 def.node_placement_prediction = "__default";
4451 // Read the item definition
4452 def = read_item_definition(L, table, def);
4454 // Default to having client-side placement prediction for nodes
4455 // ("" in item definition sets it off)
4456 if(def.node_placement_prediction == "__default"){
4457 if(def.type == ITEM_NODE)
4458 def.node_placement_prediction = name;
4460 def.node_placement_prediction = "";
4463 // Register item definition
4464 idef->registerItem(def);
4466 // Read the node definition (content features) and register it
4467 if(def.type == ITEM_NODE)
4469 ContentFeatures f = read_content_features(L, table);
4470 ndef->set(f.name, f);
4473 return 0; /* number of results */
4476 // register_alias_raw(name, convert_to_name)
4477 static int l_register_alias_raw(lua_State *L)
4479 std::string name = luaL_checkstring(L, 1);
4480 std::string convert_to = luaL_checkstring(L, 2);
4482 // Get the writable item definition manager from the server
4483 IWritableItemDefManager *idef =
4484 get_server(L)->getWritableItemDefManager();
4486 idef->registerAlias(name, convert_to);
4488 return 0; /* number of results */
4491 // helper for register_craft
4492 static bool read_craft_recipe_shaped(lua_State *L, int index,
4493 int &width, std::vector<std::string> &recipe)
4496 index = lua_gettop(L) + 1 + index;
4498 if(!lua_istable(L, index))
4503 while(lua_next(L, index) != 0){
4505 // key at index -2 and value at index -1
4506 if(!lua_istable(L, -1))
4508 int table2 = lua_gettop(L);
4510 while(lua_next(L, table2) != 0){
4511 // key at index -2 and value at index -1
4512 if(!lua_isstring(L, -1))
4514 recipe.push_back(lua_tostring(L, -1));
4515 // removes value, keeps key for next iteration
4522 if(colcount != width)
4525 // removes value, keeps key for next iteration
4532 // helper for register_craft
4533 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4534 std::vector<std::string> &recipe)
4537 index = lua_gettop(L) + 1 + index;
4539 if(!lua_istable(L, index))
4543 while(lua_next(L, index) != 0){
4544 // key at index -2 and value at index -1
4545 if(!lua_isstring(L, -1))
4547 recipe.push_back(lua_tostring(L, -1));
4548 // removes value, keeps key for next iteration
4554 // helper for register_craft
4555 static bool read_craft_replacements(lua_State *L, int index,
4556 CraftReplacements &replacements)
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_istable(L, -1))
4569 lua_rawgeti(L, -1, 1);
4570 if(!lua_isstring(L, -1))
4572 std::string replace_from = lua_tostring(L, -1);
4574 lua_rawgeti(L, -1, 2);
4575 if(!lua_isstring(L, -1))
4577 std::string replace_to = lua_tostring(L, -1);
4579 replacements.pairs.push_back(
4580 std::make_pair(replace_from, replace_to));
4581 // removes value, keeps key for next iteration
4586 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4587 static int l_register_craft(lua_State *L)
4589 //infostream<<"register_craft"<<std::endl;
4590 luaL_checktype(L, 1, LUA_TTABLE);
4593 // Get the writable craft definition manager from the server
4594 IWritableCraftDefManager *craftdef =
4595 get_server(L)->getWritableCraftDefManager();
4597 std::string type = getstringfield_default(L, table, "type", "shaped");
4600 CraftDefinitionShaped
4602 if(type == "shaped"){
4603 std::string output = getstringfield_default(L, table, "output", "");
4605 throw LuaError(L, "Crafting definition is missing an output");
4608 std::vector<std::string> recipe;
4609 lua_getfield(L, table, "recipe");
4610 if(lua_isnil(L, -1))
4611 throw LuaError(L, "Crafting definition is missing a recipe"
4612 " (output=\"" + output + "\")");
4613 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4614 throw LuaError(L, "Invalid crafting recipe"
4615 " (output=\"" + output + "\")");
4617 CraftReplacements replacements;
4618 lua_getfield(L, table, "replacements");
4619 if(!lua_isnil(L, -1))
4621 if(!read_craft_replacements(L, -1, replacements))
4622 throw LuaError(L, "Invalid replacements"
4623 " (output=\"" + output + "\")");
4626 CraftDefinition *def = new CraftDefinitionShaped(
4627 output, width, recipe, replacements);
4628 craftdef->registerCraft(def);
4631 CraftDefinitionShapeless
4633 else if(type == "shapeless"){
4634 std::string output = getstringfield_default(L, table, "output", "");
4636 throw LuaError(L, "Crafting definition (shapeless)"
4637 " is missing an output");
4639 std::vector<std::string> recipe;
4640 lua_getfield(L, table, "recipe");
4641 if(lua_isnil(L, -1))
4642 throw LuaError(L, "Crafting definition (shapeless)"
4643 " is missing a recipe"
4644 " (output=\"" + output + "\")");
4645 if(!read_craft_recipe_shapeless(L, -1, recipe))
4646 throw LuaError(L, "Invalid crafting recipe"
4647 " (output=\"" + output + "\")");
4649 CraftReplacements replacements;
4650 lua_getfield(L, table, "replacements");
4651 if(!lua_isnil(L, -1))
4653 if(!read_craft_replacements(L, -1, replacements))
4654 throw LuaError(L, "Invalid replacements"
4655 " (output=\"" + output + "\")");
4658 CraftDefinition *def = new CraftDefinitionShapeless(
4659 output, recipe, replacements);
4660 craftdef->registerCraft(def);
4663 CraftDefinitionToolRepair
4665 else if(type == "toolrepair"){
4666 float additional_wear = getfloatfield_default(L, table,
4667 "additional_wear", 0.0);
4669 CraftDefinition *def = new CraftDefinitionToolRepair(
4671 craftdef->registerCraft(def);
4674 CraftDefinitionCooking
4676 else if(type == "cooking"){
4677 std::string output = getstringfield_default(L, table, "output", "");
4679 throw LuaError(L, "Crafting definition (cooking)"
4680 " is missing an output");
4682 std::string recipe = getstringfield_default(L, table, "recipe", "");
4684 throw LuaError(L, "Crafting definition (cooking)"
4685 " is missing a recipe"
4686 " (output=\"" + output + "\")");
4688 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4690 CraftReplacements replacements;
4691 lua_getfield(L, table, "replacements");
4692 if(!lua_isnil(L, -1))
4694 if(!read_craft_replacements(L, -1, replacements))
4695 throw LuaError(L, "Invalid replacements"
4696 " (cooking output=\"" + output + "\")");
4699 CraftDefinition *def = new CraftDefinitionCooking(
4700 output, recipe, cooktime, replacements);
4701 craftdef->registerCraft(def);
4706 else if(type == "fuel"){
4707 std::string recipe = getstringfield_default(L, table, "recipe", "");
4709 throw LuaError(L, "Crafting definition (fuel)"
4710 " is missing a recipe");
4712 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4714 CraftReplacements replacements;
4715 lua_getfield(L, table, "replacements");
4716 if(!lua_isnil(L, -1))
4718 if(!read_craft_replacements(L, -1, replacements))
4719 throw LuaError(L, "Invalid replacements"
4720 " (fuel recipe=\"" + recipe + "\")");
4723 CraftDefinition *def = new CraftDefinitionFuel(
4724 recipe, burntime, replacements);
4725 craftdef->registerCraft(def);
4729 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4733 return 0; /* number of results */
4736 // setting_set(name, value)
4737 static int l_setting_set(lua_State *L)
4739 const char *name = luaL_checkstring(L, 1);
4740 const char *value = luaL_checkstring(L, 2);
4741 g_settings->set(name, value);
4745 // setting_get(name)
4746 static int l_setting_get(lua_State *L)
4748 const char *name = luaL_checkstring(L, 1);
4750 std::string value = g_settings->get(name);
4751 lua_pushstring(L, value.c_str());
4752 } catch(SettingNotFoundException &e){
4758 // setting_getbool(name)
4759 static int l_setting_getbool(lua_State *L)
4761 const char *name = luaL_checkstring(L, 1);
4763 bool value = g_settings->getBool(name);
4764 lua_pushboolean(L, value);
4765 } catch(SettingNotFoundException &e){
4771 // chat_send_all(text)
4772 static int l_chat_send_all(lua_State *L)
4774 const char *text = luaL_checkstring(L, 1);
4775 // Get server from registry
4776 Server *server = get_server(L);
4778 server->notifyPlayers(narrow_to_wide(text));
4782 // chat_send_player(name, text)
4783 static int l_chat_send_player(lua_State *L)
4785 const char *name = luaL_checkstring(L, 1);
4786 const char *text = luaL_checkstring(L, 2);
4787 // Get server from registry
4788 Server *server = get_server(L);
4790 server->notifyPlayer(name, narrow_to_wide(text));
4794 // get_player_privs(name, text)
4795 static int l_get_player_privs(lua_State *L)
4797 const char *name = luaL_checkstring(L, 1);
4798 // Get server from registry
4799 Server *server = get_server(L);
4802 int table = lua_gettop(L);
4803 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4804 for(std::set<std::string>::const_iterator
4805 i = privs_s.begin(); i != privs_s.end(); i++){
4806 lua_pushboolean(L, true);
4807 lua_setfield(L, table, i->c_str());
4809 lua_pushvalue(L, table);
4814 static int l_get_ban_list(lua_State *L)
4816 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4820 // get_ban_description()
4821 static int l_get_ban_description(lua_State *L)
4823 const char * ip_or_name = luaL_checkstring(L, 1);
4824 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4829 static int l_ban_player(lua_State *L)
4831 const char * name = luaL_checkstring(L, 1);
4832 Player *player = get_env(L)->getPlayer(name);
4835 lua_pushboolean(L, false); // no such player
4840 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4841 std::string ip_str = addr.serializeString();
4842 get_server(L)->setIpBanned(ip_str, name);
4844 catch(con::PeerNotFoundException) // unlikely
4846 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4847 lua_pushboolean(L, false); // error
4850 lua_pushboolean(L, true);
4854 // unban_player_or_ip()
4855 static int l_unban_player_of_ip(lua_State *L)
4857 const char * ip_or_name = luaL_checkstring(L, 1);
4858 get_server(L)->unsetIpBanned(ip_or_name);
4859 lua_pushboolean(L, true);
4863 // get_inventory(location)
4864 static int l_get_inventory(lua_State *L)
4866 InventoryLocation loc;
4868 std::string type = checkstringfield(L, 1, "type");
4869 if(type == "player"){
4870 std::string name = checkstringfield(L, 1, "name");
4871 loc.setPlayer(name);
4872 } else if(type == "node"){
4873 lua_getfield(L, 1, "pos");
4874 v3s16 pos = check_v3s16(L, -1);
4875 loc.setNodeMeta(pos);
4876 } else if(type == "detached"){
4877 std::string name = checkstringfield(L, 1, "name");
4878 loc.setDetached(name);
4881 if(get_server(L)->getInventory(loc) != NULL)
4882 InvRef::create(L, loc);
4888 // create_detached_inventory_raw(name)
4889 static int l_create_detached_inventory_raw(lua_State *L)
4891 const char *name = luaL_checkstring(L, 1);
4892 if(get_server(L)->createDetachedInventory(name) != NULL){
4893 InventoryLocation loc;
4894 loc.setDetached(name);
4895 InvRef::create(L, loc);
4902 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4903 static int l_get_dig_params(lua_State *L)
4905 std::map<std::string, int> groups;
4906 read_groups(L, 1, groups);
4907 ToolCapabilities tp = read_tool_capabilities(L, 2);
4908 if(lua_isnoneornil(L, 3))
4909 push_dig_params(L, getDigParams(groups, &tp));
4911 push_dig_params(L, getDigParams(groups, &tp,
4912 luaL_checknumber(L, 3)));
4916 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4917 static int l_get_hit_params(lua_State *L)
4919 std::map<std::string, int> groups;
4920 read_groups(L, 1, groups);
4921 ToolCapabilities tp = read_tool_capabilities(L, 2);
4922 if(lua_isnoneornil(L, 3))
4923 push_hit_params(L, getHitParams(groups, &tp));
4925 push_hit_params(L, getHitParams(groups, &tp,
4926 luaL_checknumber(L, 3)));
4930 // get_current_modname()
4931 static int l_get_current_modname(lua_State *L)
4933 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4937 // get_modpath(modname)
4938 static int l_get_modpath(lua_State *L)
4940 std::string modname = luaL_checkstring(L, 1);
4942 if(modname == "__builtin"){
4943 std::string path = get_server(L)->getBuiltinLuaPath();
4944 lua_pushstring(L, path.c_str());
4947 const ModSpec *mod = get_server(L)->getModSpec(modname);
4952 lua_pushstring(L, mod->path.c_str());
4957 // the returned list is sorted alphabetically for you
4958 static int l_get_modnames(lua_State *L)
4960 // Get a list of mods
4961 core::list<std::string> mods_unsorted, mods_sorted;
4962 get_server(L)->getModNames(mods_unsorted);
4964 // Take unsorted items from mods_unsorted and sort them into
4965 // mods_sorted; not great performance but the number of mods on a
4966 // server will likely be small.
4967 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4968 i != mods_unsorted.end(); i++)
4971 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4972 x != mods_unsorted.end(); x++)
4974 // I doubt anybody using Minetest will be using
4975 // anything not ASCII based :)
4976 if((*i).compare(*x) <= 0)
4978 mods_sorted.insert_before(x, *i);
4984 mods_sorted.push_back(*i);
4987 // Get the table insertion function from Lua.
4988 lua_getglobal(L, "table");
4989 lua_getfield(L, -1, "insert");
4990 int insertion_func = lua_gettop(L);
4992 // Package them up for Lua
4994 int new_table = lua_gettop(L);
4995 core::list<std::string>::Iterator i = mods_sorted.begin();
4996 while(i != mods_sorted.end())
4998 lua_pushvalue(L, insertion_func);
4999 lua_pushvalue(L, new_table);
5000 lua_pushstring(L, (*i).c_str());
5001 if(lua_pcall(L, 2, 0, 0) != 0)
5003 script_error(L, "error: %s", lua_tostring(L, -1));
5011 static int l_get_worldpath(lua_State *L)
5013 std::string worldpath = get_server(L)->getWorldPath();
5014 lua_pushstring(L, worldpath.c_str());
5018 // sound_play(spec, parameters)
5019 static int l_sound_play(lua_State *L)
5021 SimpleSoundSpec spec;
5022 read_soundspec(L, 1, spec);
5023 ServerSoundParams params;
5024 read_server_sound_params(L, 2, params);
5025 s32 handle = get_server(L)->playSound(spec, params);
5026 lua_pushinteger(L, handle);
5030 // sound_stop(handle)
5031 static int l_sound_stop(lua_State *L)
5033 int handle = luaL_checkinteger(L, 1);
5034 get_server(L)->stopSound(handle);
5038 // is_singleplayer()
5039 static int l_is_singleplayer(lua_State *L)
5041 lua_pushboolean(L, get_server(L)->isSingleplayer());
5045 // get_password_hash(name, raw_password)
5046 static int l_get_password_hash(lua_State *L)
5048 std::string name = luaL_checkstring(L, 1);
5049 std::string raw_password = luaL_checkstring(L, 2);
5050 std::string hash = translatePassword(name,
5051 narrow_to_wide(raw_password));
5052 lua_pushstring(L, hash.c_str());
5056 // notify_authentication_modified(name)
5057 static int l_notify_authentication_modified(lua_State *L)
5059 std::string name = "";
5060 if(lua_isstring(L, 1))
5061 name = lua_tostring(L, 1);
5062 get_server(L)->reportPrivsModified(name);
5066 // get_craft_result(input)
5067 static int l_get_craft_result(lua_State *L)
5070 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5071 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5072 es_CraftMethod, CRAFT_METHOD_NORMAL);
5074 lua_getfield(L, input_i, "width");
5075 if(lua_isnumber(L, -1))
5076 width = luaL_checkinteger(L, -1);
5078 lua_getfield(L, input_i, "items");
5079 std::vector<ItemStack> items = read_items(L, -1);
5080 lua_pop(L, 1); // items
5082 IGameDef *gdef = get_server(L);
5083 ICraftDefManager *cdef = gdef->cdef();
5084 CraftInput input(method, width, items);
5086 bool got = cdef->getCraftResult(input, output, true, gdef);
5087 lua_newtable(L); // output table
5090 item.deSerialize(output.item, gdef->idef());
5091 LuaItemStack::create(L, item);
5092 lua_setfield(L, -2, "item");
5093 setintfield(L, -1, "time", output.time);
5095 LuaItemStack::create(L, ItemStack());
5096 lua_setfield(L, -2, "item");
5097 setintfield(L, -1, "time", 0);
5099 lua_newtable(L); // decremented input table
5100 lua_pushstring(L, method_s.c_str());
5101 lua_setfield(L, -2, "method");
5102 lua_pushinteger(L, width);
5103 lua_setfield(L, -2, "width");
5104 push_items(L, input.items);
5105 lua_setfield(L, -2, "items");
5109 // get_craft_recipe(result item)
5110 static int l_get_craft_recipe(lua_State *L)
5115 std::string o_item = luaL_checkstring(L,input_i);
5117 IGameDef *gdef = get_server(L);
5118 ICraftDefManager *cdef = gdef->cdef();
5120 CraftOutput output(o_item,0);
5121 bool got = cdef->getCraftRecipe(input, output, gdef);
5122 lua_newtable(L); // output table
5125 for(std::vector<ItemStack>::const_iterator
5126 i = input.items.begin();
5127 i != input.items.end(); i++, k++)
5133 sprintf(tmp,"%d",k);
5134 lua_pushstring(L,tmp);
5135 lua_pushstring(L,i->name.c_str());
5136 lua_settable(L, -3);
5138 lua_setfield(L, -2, "items");
5139 setintfield(L, -1, "width", input.width);
5140 switch (input.method) {
5141 case CRAFT_METHOD_NORMAL:
5142 lua_pushstring(L,"normal");
5144 case CRAFT_METHOD_COOKING:
5145 lua_pushstring(L,"cooking");
5147 case CRAFT_METHOD_FUEL:
5148 lua_pushstring(L,"fuel");
5151 lua_pushstring(L,"unknown");
5153 lua_setfield(L, -2, "type");
5156 lua_setfield(L, -2, "items");
5157 setintfield(L, -1, "width", 0);
5162 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5163 static int l_rollback_get_last_node_actor(lua_State *L)
5165 v3s16 p = read_v3s16(L, 1);
5166 int range = luaL_checknumber(L, 2);
5167 int seconds = luaL_checknumber(L, 3);
5168 Server *server = get_server(L);
5169 IRollbackManager *rollback = server->getRollbackManager();
5171 int act_seconds = 0;
5172 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5173 lua_pushstring(L, actor.c_str());
5174 push_v3s16(L, act_p);
5175 lua_pushnumber(L, act_seconds);
5179 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5180 static int l_rollback_revert_actions_by(lua_State *L)
5182 std::string actor = luaL_checkstring(L, 1);
5183 int seconds = luaL_checknumber(L, 2);
5184 Server *server = get_server(L);
5185 IRollbackManager *rollback = server->getRollbackManager();
5186 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5187 std::list<std::string> log;
5188 bool success = server->rollbackRevertActions(actions, &log);
5189 // Push boolean result
5190 lua_pushboolean(L, success);
5191 // Get the table insert function and push the log table
5192 lua_getglobal(L, "table");
5193 lua_getfield(L, -1, "insert");
5194 int table_insert = lua_gettop(L);
5196 int table = lua_gettop(L);
5197 for(std::list<std::string>::const_iterator i = log.begin();
5198 i != log.end(); i++)
5200 lua_pushvalue(L, table_insert);
5201 lua_pushvalue(L, table);
5202 lua_pushstring(L, i->c_str());
5203 if(lua_pcall(L, 2, 0, 0))
5204 script_error(L, "error: %s", lua_tostring(L, -1));
5206 lua_remove(L, -2); // Remove table
5207 lua_remove(L, -2); // Remove insert
5211 static const struct luaL_Reg minetest_f [] = {
5214 {"request_shutdown", l_request_shutdown},
5215 {"get_server_status", l_get_server_status},
5216 {"register_item_raw", l_register_item_raw},
5217 {"register_alias_raw", l_register_alias_raw},
5218 {"register_craft", l_register_craft},
5219 {"setting_set", l_setting_set},
5220 {"setting_get", l_setting_get},
5221 {"setting_getbool", l_setting_getbool},
5222 {"chat_send_all", l_chat_send_all},
5223 {"chat_send_player", l_chat_send_player},
5224 {"get_player_privs", l_get_player_privs},
5225 {"get_ban_list", l_get_ban_list},
5226 {"get_ban_description", l_get_ban_description},
5227 {"ban_player", l_ban_player},
5228 {"unban_player_or_ip", l_unban_player_of_ip},
5229 {"get_inventory", l_get_inventory},
5230 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5231 {"get_dig_params", l_get_dig_params},
5232 {"get_hit_params", l_get_hit_params},
5233 {"get_current_modname", l_get_current_modname},
5234 {"get_modpath", l_get_modpath},
5235 {"get_modnames", l_get_modnames},
5236 {"get_worldpath", l_get_worldpath},
5237 {"sound_play", l_sound_play},
5238 {"sound_stop", l_sound_stop},
5239 {"is_singleplayer", l_is_singleplayer},
5240 {"get_password_hash", l_get_password_hash},
5241 {"notify_authentication_modified", l_notify_authentication_modified},
5242 {"get_craft_result", l_get_craft_result},
5243 {"get_craft_recipe", l_get_craft_recipe},
5244 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5245 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5250 Main export function
5253 void scriptapi_export(lua_State *L, Server *server)
5256 assert(lua_checkstack(L, 20));
5257 verbosestream<<"scriptapi_export()"<<std::endl;
5258 StackUnroller stack_unroller(L);
5260 // Store server as light userdata in registry
5261 lua_pushlightuserdata(L, server);
5262 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5264 // Register global functions in table minetest
5266 luaL_register(L, NULL, minetest_f);
5267 lua_setglobal(L, "minetest");
5269 // Get the main minetest table
5270 lua_getglobal(L, "minetest");
5272 // Add tables to minetest
5274 lua_setfield(L, -2, "object_refs");
5276 lua_setfield(L, -2, "luaentities");
5278 // Register wrappers
5279 LuaItemStack::Register(L);
5280 InvRef::Register(L);
5281 NodeMetaRef::Register(L);
5282 NodeTimerRef::Register(L);
5283 ObjectRef::Register(L);
5284 EnvRef::Register(L);
5285 LuaPseudoRandom::Register(L);
5286 LuaPerlinNoise::Register(L);
5289 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5290 const std::string &modname)
5292 ModNameStorer modnamestorer(L, modname);
5294 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5296 errorstream<<"Error loading mod \""<<modname
5297 <<"\": modname does not follow naming conventions: "
5298 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5302 bool success = false;
5305 success = script_load(L, scriptpath.c_str());
5308 errorstream<<"Error loading mod \""<<modname
5309 <<"\": "<<e.what()<<std::endl;
5315 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5318 assert(lua_checkstack(L, 20));
5319 verbosestream<<"scriptapi_add_environment"<<std::endl;
5320 StackUnroller stack_unroller(L);
5322 // Create EnvRef on stack
5323 EnvRef::create(L, env);
5324 int envref = lua_gettop(L);
5326 // minetest.env = envref
5327 lua_getglobal(L, "minetest");
5328 luaL_checktype(L, -1, LUA_TTABLE);
5329 lua_pushvalue(L, envref);
5330 lua_setfield(L, -2, "env");
5332 // Store environment as light userdata in registry
5333 lua_pushlightuserdata(L, env);
5334 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5337 Add ActiveBlockModifiers to environment
5340 // Get minetest.registered_abms
5341 lua_getglobal(L, "minetest");
5342 lua_getfield(L, -1, "registered_abms");
5343 luaL_checktype(L, -1, LUA_TTABLE);
5344 int registered_abms = lua_gettop(L);
5346 if(lua_istable(L, registered_abms)){
5347 int table = lua_gettop(L);
5349 while(lua_next(L, table) != 0){
5350 // key at index -2 and value at index -1
5351 int id = lua_tonumber(L, -2);
5352 int current_abm = lua_gettop(L);
5354 std::set<std::string> trigger_contents;
5355 lua_getfield(L, current_abm, "nodenames");
5356 if(lua_istable(L, -1)){
5357 int table = lua_gettop(L);
5359 while(lua_next(L, table) != 0){
5360 // key at index -2 and value at index -1
5361 luaL_checktype(L, -1, LUA_TSTRING);
5362 trigger_contents.insert(lua_tostring(L, -1));
5363 // removes value, keeps key for next iteration
5366 } else if(lua_isstring(L, -1)){
5367 trigger_contents.insert(lua_tostring(L, -1));
5371 std::set<std::string> required_neighbors;
5372 lua_getfield(L, current_abm, "neighbors");
5373 if(lua_istable(L, -1)){
5374 int table = lua_gettop(L);
5376 while(lua_next(L, table) != 0){
5377 // key at index -2 and value at index -1
5378 luaL_checktype(L, -1, LUA_TSTRING);
5379 required_neighbors.insert(lua_tostring(L, -1));
5380 // removes value, keeps key for next iteration
5383 } else if(lua_isstring(L, -1)){
5384 required_neighbors.insert(lua_tostring(L, -1));
5388 float trigger_interval = 10.0;
5389 getfloatfield(L, current_abm, "interval", trigger_interval);
5391 int trigger_chance = 50;
5392 getintfield(L, current_abm, "chance", trigger_chance);
5394 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5395 required_neighbors, trigger_interval, trigger_chance);
5397 env->addActiveBlockModifier(abm);
5399 // removes value, keeps key for next iteration
5407 // Dump stack top with the dump2 function
5408 static void dump2(lua_State *L, const char *name)
5410 // Dump object (debug)
5411 lua_getglobal(L, "dump2");
5412 luaL_checktype(L, -1, LUA_TFUNCTION);
5413 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5414 lua_pushstring(L, name);
5415 if(lua_pcall(L, 2, 0, 0))
5416 script_error(L, "error: %s", lua_tostring(L, -1));
5424 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5427 assert(lua_checkstack(L, 20));
5428 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5429 StackUnroller stack_unroller(L);
5431 // Create object on stack
5432 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5433 int object = lua_gettop(L);
5435 // Get minetest.object_refs table
5436 lua_getglobal(L, "minetest");
5437 lua_getfield(L, -1, "object_refs");
5438 luaL_checktype(L, -1, LUA_TTABLE);
5439 int objectstable = lua_gettop(L);
5441 // object_refs[id] = object
5442 lua_pushnumber(L, cobj->getId()); // Push id
5443 lua_pushvalue(L, object); // Copy object to top of stack
5444 lua_settable(L, objectstable);
5447 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5450 assert(lua_checkstack(L, 20));
5451 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5452 StackUnroller stack_unroller(L);
5454 // Get minetest.object_refs table
5455 lua_getglobal(L, "minetest");
5456 lua_getfield(L, -1, "object_refs");
5457 luaL_checktype(L, -1, LUA_TTABLE);
5458 int objectstable = lua_gettop(L);
5460 // Get object_refs[id]
5461 lua_pushnumber(L, cobj->getId()); // Push id
5462 lua_gettable(L, objectstable);
5463 // Set object reference to NULL
5464 ObjectRef::set_null(L);
5465 lua_pop(L, 1); // pop object
5467 // Set object_refs[id] = nil
5468 lua_pushnumber(L, cobj->getId()); // Push id
5470 lua_settable(L, objectstable);
5477 // What scriptapi_run_callbacks does with the return values of callbacks.
5478 // Regardless of the mode, if only one callback is defined,
5479 // its return value is the total return value.
5480 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5481 enum RunCallbacksMode
5483 // Returns the return value of the first callback
5484 // Returns nil if list of callbacks is empty
5485 RUN_CALLBACKS_MODE_FIRST,
5486 // Returns the return value of the last callback
5487 // Returns nil if list of callbacks is empty
5488 RUN_CALLBACKS_MODE_LAST,
5489 // If any callback returns a false value, the first such is returned
5490 // Otherwise, the first callback's return value (trueish) is returned
5491 // Returns true if list of callbacks is empty
5492 RUN_CALLBACKS_MODE_AND,
5493 // Like above, but stops calling callbacks (short circuit)
5494 // after seeing the first false value
5495 RUN_CALLBACKS_MODE_AND_SC,
5496 // If any callback returns a true value, the first such is returned
5497 // Otherwise, the first callback's return value (falseish) is returned
5498 // Returns false if list of callbacks is empty
5499 RUN_CALLBACKS_MODE_OR,
5500 // Like above, but stops calling callbacks (short circuit)
5501 // after seeing the first true value
5502 RUN_CALLBACKS_MODE_OR_SC,
5503 // Note: "a true value" and "a false value" refer to values that
5504 // are converted by lua_toboolean to true or false, respectively.
5507 // Push the list of callbacks (a lua table).
5508 // Then push nargs arguments.
5509 // Then call this function, which
5510 // - runs the callbacks
5511 // - removes the table and arguments from the lua stack
5512 // - pushes the return value, computed depending on mode
5513 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5514 RunCallbacksMode mode)
5516 // Insert the return value into the lua stack, below the table
5517 assert(lua_gettop(L) >= nargs + 1);
5519 lua_insert(L, -(nargs + 1) - 1);
5520 // Stack now looks like this:
5521 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5523 int rv = lua_gettop(L) - nargs - 1;
5525 int arg = table + 1;
5527 luaL_checktype(L, table, LUA_TTABLE);
5531 bool first_loop = true;
5532 while(lua_next(L, table) != 0){
5533 // key at index -2 and value at index -1
5534 luaL_checktype(L, -1, LUA_TFUNCTION);
5536 for(int i = 0; i < nargs; i++)
5537 lua_pushvalue(L, arg+i);
5538 if(lua_pcall(L, nargs, 1, 0))
5539 script_error(L, "error: %s", lua_tostring(L, -1));
5541 // Move return value to designated space in stack
5544 // Result of first callback is always moved
5548 // Otherwise, what happens depends on the mode
5549 if(mode == RUN_CALLBACKS_MODE_FIRST)
5551 else if(mode == RUN_CALLBACKS_MODE_LAST)
5553 else if(mode == RUN_CALLBACKS_MODE_AND ||
5554 mode == RUN_CALLBACKS_MODE_AND_SC){
5555 if(lua_toboolean(L, rv) == true &&
5556 lua_toboolean(L, -1) == false)
5561 else if(mode == RUN_CALLBACKS_MODE_OR ||
5562 mode == RUN_CALLBACKS_MODE_OR_SC){
5563 if(lua_toboolean(L, rv) == false &&
5564 lua_toboolean(L, -1) == true)
5573 // Handle short circuit modes
5574 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5575 lua_toboolean(L, rv) == false)
5577 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5578 lua_toboolean(L, rv) == true)
5581 // value removed, keep key for next iteration
5584 // Remove stuff from stack, leaving only the return value
5587 // Fix return value in case no callbacks were called
5589 if(mode == RUN_CALLBACKS_MODE_AND ||
5590 mode == RUN_CALLBACKS_MODE_AND_SC){
5592 lua_pushboolean(L, true);
5594 else if(mode == RUN_CALLBACKS_MODE_OR ||
5595 mode == RUN_CALLBACKS_MODE_OR_SC){
5597 lua_pushboolean(L, false);
5602 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5603 const std::string &message)
5606 assert(lua_checkstack(L, 20));
5607 StackUnroller stack_unroller(L);
5609 // Get minetest.registered_on_chat_messages
5610 lua_getglobal(L, "minetest");
5611 lua_getfield(L, -1, "registered_on_chat_messages");
5613 lua_pushstring(L, name.c_str());
5614 lua_pushstring(L, message.c_str());
5615 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5616 bool ate = lua_toboolean(L, -1);
5620 void scriptapi_on_shutdown(lua_State *L)
5623 assert(lua_checkstack(L, 20));
5624 StackUnroller stack_unroller(L);
5626 // Get registered shutdown hooks
5627 lua_getglobal(L, "minetest");
5628 lua_getfield(L, -1, "registered_on_shutdown");
5630 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5633 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5636 assert(lua_checkstack(L, 20));
5637 StackUnroller stack_unroller(L);
5639 // Get minetest.registered_on_newplayers
5640 lua_getglobal(L, "minetest");
5641 lua_getfield(L, -1, "registered_on_newplayers");
5643 objectref_get_or_create(L, player);
5644 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5647 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5650 assert(lua_checkstack(L, 20));
5651 StackUnroller stack_unroller(L);
5653 // Get minetest.registered_on_dieplayers
5654 lua_getglobal(L, "minetest");
5655 lua_getfield(L, -1, "registered_on_dieplayers");
5657 objectref_get_or_create(L, player);
5658 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5661 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5664 assert(lua_checkstack(L, 20));
5665 StackUnroller stack_unroller(L);
5667 // Get minetest.registered_on_respawnplayers
5668 lua_getglobal(L, "minetest");
5669 lua_getfield(L, -1, "registered_on_respawnplayers");
5671 objectref_get_or_create(L, player);
5672 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5673 bool positioning_handled_by_some = lua_toboolean(L, -1);
5674 return positioning_handled_by_some;
5677 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5680 assert(lua_checkstack(L, 20));
5681 StackUnroller stack_unroller(L);
5683 // Get minetest.registered_on_joinplayers
5684 lua_getglobal(L, "minetest");
5685 lua_getfield(L, -1, "registered_on_joinplayers");
5687 objectref_get_or_create(L, player);
5688 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5691 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5694 assert(lua_checkstack(L, 20));
5695 StackUnroller stack_unroller(L);
5697 // Get minetest.registered_on_leaveplayers
5698 lua_getglobal(L, "minetest");
5699 lua_getfield(L, -1, "registered_on_leaveplayers");
5701 objectref_get_or_create(L, player);
5702 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5705 static void get_auth_handler(lua_State *L)
5707 lua_getglobal(L, "minetest");
5708 lua_getfield(L, -1, "registered_auth_handler");
5709 if(lua_isnil(L, -1)){
5711 lua_getfield(L, -1, "builtin_auth_handler");
5713 if(lua_type(L, -1) != LUA_TTABLE)
5714 throw LuaError(L, "Authentication handler table not valid");
5717 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5718 std::string *dst_password, std::set<std::string> *dst_privs)
5721 assert(lua_checkstack(L, 20));
5722 StackUnroller stack_unroller(L);
5724 get_auth_handler(L);
5725 lua_getfield(L, -1, "get_auth");
5726 if(lua_type(L, -1) != LUA_TFUNCTION)
5727 throw LuaError(L, "Authentication handler missing get_auth");
5728 lua_pushstring(L, playername.c_str());
5729 if(lua_pcall(L, 1, 1, 0))
5730 script_error(L, "error: %s", lua_tostring(L, -1));
5732 // nil = login not allowed
5733 if(lua_isnil(L, -1))
5735 luaL_checktype(L, -1, LUA_TTABLE);
5737 std::string password;
5738 bool found = getstringfield(L, -1, "password", password);
5740 throw LuaError(L, "Authentication handler didn't return password");
5742 *dst_password = password;
5744 lua_getfield(L, -1, "privileges");
5745 if(!lua_istable(L, -1))
5747 "Authentication handler didn't return privilege table");
5749 read_privileges(L, -1, *dst_privs);
5755 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5756 const std::string &password)
5759 assert(lua_checkstack(L, 20));
5760 StackUnroller stack_unroller(L);
5762 get_auth_handler(L);
5763 lua_getfield(L, -1, "create_auth");
5764 if(lua_type(L, -1) != LUA_TFUNCTION)
5765 throw LuaError(L, "Authentication handler missing create_auth");
5766 lua_pushstring(L, playername.c_str());
5767 lua_pushstring(L, password.c_str());
5768 if(lua_pcall(L, 2, 0, 0))
5769 script_error(L, "error: %s", lua_tostring(L, -1));
5772 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5773 const std::string &password)
5776 assert(lua_checkstack(L, 20));
5777 StackUnroller stack_unroller(L);
5779 get_auth_handler(L);
5780 lua_getfield(L, -1, "set_password");
5781 if(lua_type(L, -1) != LUA_TFUNCTION)
5782 throw LuaError(L, "Authentication handler missing set_password");
5783 lua_pushstring(L, playername.c_str());
5784 lua_pushstring(L, password.c_str());
5785 if(lua_pcall(L, 2, 1, 0))
5786 script_error(L, "error: %s", lua_tostring(L, -1));
5787 return lua_toboolean(L, -1);
5794 void scriptapi_on_player_receive_fields(lua_State *L,
5795 ServerActiveObject *player,
5796 const std::string &formname,
5797 const std::map<std::string, std::string> &fields)
5800 assert(lua_checkstack(L, 20));
5801 StackUnroller stack_unroller(L);
5803 // Get minetest.registered_on_chat_messages
5804 lua_getglobal(L, "minetest");
5805 lua_getfield(L, -1, "registered_on_player_receive_fields");
5808 objectref_get_or_create(L, player);
5810 lua_pushstring(L, formname.c_str());
5813 for(std::map<std::string, std::string>::const_iterator
5814 i = fields.begin(); i != fields.end(); i++){
5815 const std::string &name = i->first;
5816 const std::string &value = i->second;
5817 lua_pushstring(L, name.c_str());
5818 lua_pushlstring(L, value.c_str(), value.size());
5819 lua_settable(L, -3);
5821 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5825 item callbacks and node callbacks
5828 // Retrieves minetest.registered_items[name][callbackname]
5829 // If that is nil or on error, return false and stack is unchanged
5830 // If that is a function, returns true and pushes the
5831 // function onto the stack
5832 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5833 // is tried instead so unknown items can still be manipulated to some degree
5834 static bool get_item_callback(lua_State *L,
5835 const char *name, const char *callbackname)
5837 lua_getglobal(L, "minetest");
5838 lua_getfield(L, -1, "registered_items");
5840 luaL_checktype(L, -1, LUA_TTABLE);
5841 lua_getfield(L, -1, name);
5843 // Should be a table
5844 if(lua_type(L, -1) != LUA_TTABLE)
5846 // Report error and clean up
5847 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5850 // Try minetest.nodedef_default instead
5851 lua_getglobal(L, "minetest");
5852 lua_getfield(L, -1, "nodedef_default");
5854 luaL_checktype(L, -1, LUA_TTABLE);
5856 lua_getfield(L, -1, callbackname);
5858 // Should be a function or nil
5859 if(lua_type(L, -1) == LUA_TFUNCTION)
5863 else if(lua_isnil(L, -1))
5870 errorstream<<"Item \""<<name<<"\" callback \""
5871 <<callbackname<<" is not a function"<<std::endl;
5877 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5878 ServerActiveObject *dropper, v3f pos)
5881 assert(lua_checkstack(L, 20));
5882 StackUnroller stack_unroller(L);
5884 // Push callback function on stack
5885 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5889 LuaItemStack::create(L, item);
5890 objectref_get_or_create(L, dropper);
5891 pushFloatPos(L, pos);
5892 if(lua_pcall(L, 3, 1, 0))
5893 script_error(L, "error: %s", lua_tostring(L, -1));
5894 if(!lua_isnil(L, -1))
5895 item = read_item(L, -1);
5899 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5900 ServerActiveObject *placer, const PointedThing &pointed)
5903 assert(lua_checkstack(L, 20));
5904 StackUnroller stack_unroller(L);
5906 // Push callback function on stack
5907 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5911 LuaItemStack::create(L, item);
5912 objectref_get_or_create(L, placer);
5913 push_pointed_thing(L, pointed);
5914 if(lua_pcall(L, 3, 1, 0))
5915 script_error(L, "error: %s", lua_tostring(L, -1));
5916 if(!lua_isnil(L, -1))
5917 item = read_item(L, -1);
5921 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5922 ServerActiveObject *user, const PointedThing &pointed)
5925 assert(lua_checkstack(L, 20));
5926 StackUnroller stack_unroller(L);
5928 // Push callback function on stack
5929 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5933 LuaItemStack::create(L, item);
5934 objectref_get_or_create(L, user);
5935 push_pointed_thing(L, pointed);
5936 if(lua_pcall(L, 3, 1, 0))
5937 script_error(L, "error: %s", lua_tostring(L, -1));
5938 if(!lua_isnil(L, -1))
5939 item = read_item(L, -1);
5943 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5944 ServerActiveObject *puncher)
5947 assert(lua_checkstack(L, 20));
5948 StackUnroller stack_unroller(L);
5950 INodeDefManager *ndef = get_server(L)->ndef();
5952 // Push callback function on stack
5953 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5958 pushnode(L, node, ndef);
5959 objectref_get_or_create(L, puncher);
5960 if(lua_pcall(L, 3, 0, 0))
5961 script_error(L, "error: %s", lua_tostring(L, -1));
5965 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5966 ServerActiveObject *digger)
5969 assert(lua_checkstack(L, 20));
5970 StackUnroller stack_unroller(L);
5972 INodeDefManager *ndef = get_server(L)->ndef();
5974 // Push callback function on stack
5975 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5980 pushnode(L, node, ndef);
5981 objectref_get_or_create(L, digger);
5982 if(lua_pcall(L, 3, 0, 0))
5983 script_error(L, "error: %s", lua_tostring(L, -1));
5987 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5990 assert(lua_checkstack(L, 20));
5991 StackUnroller stack_unroller(L);
5993 INodeDefManager *ndef = get_server(L)->ndef();
5995 // Push callback function on stack
5996 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6001 if(lua_pcall(L, 1, 0, 0))
6002 script_error(L, "error: %s", lua_tostring(L, -1));
6005 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
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_destruct"))
6019 if(lua_pcall(L, 1, 0, 0))
6020 script_error(L, "error: %s", lua_tostring(L, -1));
6023 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6026 assert(lua_checkstack(L, 20));
6027 StackUnroller stack_unroller(L);
6029 INodeDefManager *ndef = get_server(L)->ndef();
6031 // Push callback function on stack
6032 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6037 pushnode(L, node, ndef);
6038 if(lua_pcall(L, 2, 0, 0))
6039 script_error(L, "error: %s", lua_tostring(L, -1));
6042 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6045 assert(lua_checkstack(L, 20));
6046 StackUnroller stack_unroller(L);
6048 INodeDefManager *ndef = get_server(L)->ndef();
6050 // Push callback function on stack
6051 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6056 lua_pushnumber(L,dtime);
6057 if(lua_pcall(L, 2, 1, 0))
6058 script_error(L, "error: %s", lua_tostring(L, -1));
6059 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
6065 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6066 const std::string &formname,
6067 const std::map<std::string, std::string> &fields,
6068 ServerActiveObject *sender)
6071 assert(lua_checkstack(L, 20));
6072 StackUnroller stack_unroller(L);
6074 INodeDefManager *ndef = get_server(L)->ndef();
6076 // If node doesn't exist, we don't know what callback to call
6077 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6078 if(node.getContent() == CONTENT_IGNORE)
6081 // Push callback function on stack
6082 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6089 lua_pushstring(L, formname.c_str());
6092 for(std::map<std::string, std::string>::const_iterator
6093 i = fields.begin(); i != fields.end(); i++){
6094 const std::string &name = i->first;
6095 const std::string &value = i->second;
6096 lua_pushstring(L, name.c_str());
6097 lua_pushlstring(L, value.c_str(), value.size());
6098 lua_settable(L, -3);
6101 objectref_get_or_create(L, sender);
6102 if(lua_pcall(L, 4, 0, 0))
6103 script_error(L, "error: %s", lua_tostring(L, -1));
6107 Node metadata inventory callbacks
6110 // Return number of accepted items to be moved
6111 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6112 const std::string &from_list, int from_index,
6113 const std::string &to_list, int to_index,
6114 int count, ServerActiveObject *player)
6117 assert(lua_checkstack(L, 20));
6118 StackUnroller stack_unroller(L);
6120 INodeDefManager *ndef = get_server(L)->ndef();
6122 // If node doesn't exist, we don't know what callback to call
6123 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6124 if(node.getContent() == CONTENT_IGNORE)
6127 // Push callback function on stack
6128 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6129 "allow_metadata_inventory_move"))
6132 // function(pos, from_list, from_index, to_list, to_index, count, player)
6136 lua_pushstring(L, from_list.c_str());
6138 lua_pushinteger(L, from_index + 1);
6140 lua_pushstring(L, to_list.c_str());
6142 lua_pushinteger(L, to_index + 1);
6144 lua_pushinteger(L, count);
6146 objectref_get_or_create(L, player);
6147 if(lua_pcall(L, 7, 1, 0))
6148 script_error(L, "error: %s", lua_tostring(L, -1));
6149 if(!lua_isnumber(L, -1))
6150 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6151 return luaL_checkinteger(L, -1);
6154 // Return number of accepted items to be put
6155 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6156 const std::string &listname, int index, ItemStack &stack,
6157 ServerActiveObject *player)
6160 assert(lua_checkstack(L, 20));
6161 StackUnroller stack_unroller(L);
6163 INodeDefManager *ndef = get_server(L)->ndef();
6165 // If node doesn't exist, we don't know what callback to call
6166 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6167 if(node.getContent() == CONTENT_IGNORE)
6170 // Push callback function on stack
6171 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6172 "allow_metadata_inventory_put"))
6175 // Call function(pos, listname, index, stack, player)
6179 lua_pushstring(L, listname.c_str());
6181 lua_pushinteger(L, index + 1);
6183 LuaItemStack::create(L, stack);
6185 objectref_get_or_create(L, player);
6186 if(lua_pcall(L, 5, 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_put should return a number");
6190 return luaL_checkinteger(L, -1);
6193 // Return number of accepted items to be taken
6194 int scriptapi_nodemeta_inventory_allow_take(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_take"))
6214 // Call function(pos, listname, index, count, 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_take should return a number");
6229 return luaL_checkinteger(L, -1);
6232 // Report moved items
6233 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6234 const std::string &from_list, int from_index,
6235 const std::string &to_list, int to_index,
6236 int count, ServerActiveObject *player)
6239 assert(lua_checkstack(L, 20));
6240 StackUnroller stack_unroller(L);
6242 INodeDefManager *ndef = get_server(L)->ndef();
6244 // If node doesn't exist, we don't know what callback to call
6245 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6246 if(node.getContent() == CONTENT_IGNORE)
6249 // Push callback function on stack
6250 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6251 "on_metadata_inventory_move"))
6254 // function(pos, from_list, from_index, to_list, to_index, count, player)
6258 lua_pushstring(L, from_list.c_str());
6260 lua_pushinteger(L, from_index + 1);
6262 lua_pushstring(L, to_list.c_str());
6264 lua_pushinteger(L, to_index + 1);
6266 lua_pushinteger(L, count);
6268 objectref_get_or_create(L, player);
6269 if(lua_pcall(L, 7, 0, 0))
6270 script_error(L, "error: %s", lua_tostring(L, -1));
6274 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6275 const std::string &listname, int index, ItemStack &stack,
6276 ServerActiveObject *player)
6279 assert(lua_checkstack(L, 20));
6280 StackUnroller stack_unroller(L);
6282 INodeDefManager *ndef = get_server(L)->ndef();
6284 // If node doesn't exist, we don't know what callback to call
6285 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6286 if(node.getContent() == CONTENT_IGNORE)
6289 // Push callback function on stack
6290 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6291 "on_metadata_inventory_put"))
6294 // Call function(pos, listname, index, stack, player)
6298 lua_pushstring(L, listname.c_str());
6300 lua_pushinteger(L, index + 1);
6302 LuaItemStack::create(L, stack);
6304 objectref_get_or_create(L, player);
6305 if(lua_pcall(L, 5, 0, 0))
6306 script_error(L, "error: %s", lua_tostring(L, -1));
6309 // Report taken items
6310 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6311 const std::string &listname, int index, ItemStack &stack,
6312 ServerActiveObject *player)
6315 assert(lua_checkstack(L, 20));
6316 StackUnroller stack_unroller(L);
6318 INodeDefManager *ndef = get_server(L)->ndef();
6320 // If node doesn't exist, we don't know what callback to call
6321 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6322 if(node.getContent() == CONTENT_IGNORE)
6325 // Push callback function on stack
6326 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6327 "on_metadata_inventory_take"))
6330 // Call function(pos, listname, index, stack, player)
6334 lua_pushstring(L, listname.c_str());
6336 lua_pushinteger(L, index + 1);
6338 LuaItemStack::create(L, stack);
6340 objectref_get_or_create(L, player);
6341 if(lua_pcall(L, 5, 0, 0))
6342 script_error(L, "error: %s", lua_tostring(L, -1));
6346 Detached inventory callbacks
6349 // Retrieves minetest.detached_inventories[name][callbackname]
6350 // If that is nil or on error, return false and stack is unchanged
6351 // If that is a function, returns true and pushes the
6352 // function onto the stack
6353 static bool get_detached_inventory_callback(lua_State *L,
6354 const std::string &name, const char *callbackname)
6356 lua_getglobal(L, "minetest");
6357 lua_getfield(L, -1, "detached_inventories");
6359 luaL_checktype(L, -1, LUA_TTABLE);
6360 lua_getfield(L, -1, name.c_str());
6362 // Should be a table
6363 if(lua_type(L, -1) != LUA_TTABLE)
6365 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6369 lua_getfield(L, -1, callbackname);
6371 // Should be a function or nil
6372 if(lua_type(L, -1) == LUA_TFUNCTION)
6376 else if(lua_isnil(L, -1))
6383 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6384 <<callbackname<<"\" is not a function"<<std::endl;
6390 // Return number of accepted items to be moved
6391 int scriptapi_detached_inventory_allow_move(lua_State *L,
6392 const std::string &name,
6393 const std::string &from_list, int from_index,
6394 const std::string &to_list, int to_index,
6395 int count, ServerActiveObject *player)
6398 assert(lua_checkstack(L, 20));
6399 StackUnroller stack_unroller(L);
6401 // Push callback function on stack
6402 if(!get_detached_inventory_callback(L, name, "allow_move"))
6405 // function(inv, from_list, from_index, to_list, to_index, count, player)
6407 InventoryLocation loc;
6408 loc.setDetached(name);
6409 InvRef::create(L, loc);
6411 lua_pushstring(L, from_list.c_str());
6413 lua_pushinteger(L, from_index + 1);
6415 lua_pushstring(L, to_list.c_str());
6417 lua_pushinteger(L, to_index + 1);
6419 lua_pushinteger(L, count);
6421 objectref_get_or_create(L, player);
6422 if(lua_pcall(L, 7, 1, 0))
6423 script_error(L, "error: %s", lua_tostring(L, -1));
6424 if(!lua_isnumber(L, -1))
6425 throw LuaError(L, "allow_move should return a number");
6426 return luaL_checkinteger(L, -1);
6429 // Return number of accepted items to be put
6430 int scriptapi_detached_inventory_allow_put(lua_State *L,
6431 const std::string &name,
6432 const std::string &listname, int index, ItemStack &stack,
6433 ServerActiveObject *player)
6436 assert(lua_checkstack(L, 20));
6437 StackUnroller stack_unroller(L);
6439 // Push callback function on stack
6440 if(!get_detached_inventory_callback(L, name, "allow_put"))
6441 return stack.count; // All will be accepted
6443 // Call function(inv, listname, index, stack, player)
6445 InventoryLocation loc;
6446 loc.setDetached(name);
6447 InvRef::create(L, loc);
6449 lua_pushstring(L, listname.c_str());
6451 lua_pushinteger(L, index + 1);
6453 LuaItemStack::create(L, stack);
6455 objectref_get_or_create(L, player);
6456 if(lua_pcall(L, 5, 1, 0))
6457 script_error(L, "error: %s", lua_tostring(L, -1));
6458 if(!lua_isnumber(L, -1))
6459 throw LuaError(L, "allow_put should return a number");
6460 return luaL_checkinteger(L, -1);
6463 // Return number of accepted items to be taken
6464 int scriptapi_detached_inventory_allow_take(lua_State *L,
6465 const std::string &name,
6466 const std::string &listname, int index, ItemStack &stack,
6467 ServerActiveObject *player)
6470 assert(lua_checkstack(L, 20));
6471 StackUnroller stack_unroller(L);
6473 // Push callback function on stack
6474 if(!get_detached_inventory_callback(L, name, "allow_take"))
6475 return stack.count; // All will be accepted
6477 // Call function(inv, listname, index, stack, player)
6479 InventoryLocation loc;
6480 loc.setDetached(name);
6481 InvRef::create(L, loc);
6483 lua_pushstring(L, listname.c_str());
6485 lua_pushinteger(L, index + 1);
6487 LuaItemStack::create(L, stack);
6489 objectref_get_or_create(L, player);
6490 if(lua_pcall(L, 5, 1, 0))
6491 script_error(L, "error: %s", lua_tostring(L, -1));
6492 if(!lua_isnumber(L, -1))
6493 throw LuaError(L, "allow_take should return a number");
6494 return luaL_checkinteger(L, -1);
6497 // Report moved items
6498 void scriptapi_detached_inventory_on_move(lua_State *L,
6499 const std::string &name,
6500 const std::string &from_list, int from_index,
6501 const std::string &to_list, int to_index,
6502 int count, ServerActiveObject *player)
6505 assert(lua_checkstack(L, 20));
6506 StackUnroller stack_unroller(L);
6508 // Push callback function on stack
6509 if(!get_detached_inventory_callback(L, name, "on_move"))
6512 // function(inv, from_list, from_index, to_list, to_index, count, player)
6514 InventoryLocation loc;
6515 loc.setDetached(name);
6516 InvRef::create(L, loc);
6518 lua_pushstring(L, from_list.c_str());
6520 lua_pushinteger(L, from_index + 1);
6522 lua_pushstring(L, to_list.c_str());
6524 lua_pushinteger(L, to_index + 1);
6526 lua_pushinteger(L, count);
6528 objectref_get_or_create(L, player);
6529 if(lua_pcall(L, 7, 0, 0))
6530 script_error(L, "error: %s", lua_tostring(L, -1));
6534 void scriptapi_detached_inventory_on_put(lua_State *L,
6535 const std::string &name,
6536 const std::string &listname, int index, ItemStack &stack,
6537 ServerActiveObject *player)
6540 assert(lua_checkstack(L, 20));
6541 StackUnroller stack_unroller(L);
6543 // Push callback function on stack
6544 if(!get_detached_inventory_callback(L, name, "on_put"))
6547 // Call function(inv, listname, index, stack, player)
6549 InventoryLocation loc;
6550 loc.setDetached(name);
6551 InvRef::create(L, loc);
6553 lua_pushstring(L, listname.c_str());
6555 lua_pushinteger(L, index + 1);
6557 LuaItemStack::create(L, stack);
6559 objectref_get_or_create(L, player);
6560 if(lua_pcall(L, 5, 0, 0))
6561 script_error(L, "error: %s", lua_tostring(L, -1));
6564 // Report taken items
6565 void scriptapi_detached_inventory_on_take(lua_State *L,
6566 const std::string &name,
6567 const std::string &listname, int index, ItemStack &stack,
6568 ServerActiveObject *player)
6571 assert(lua_checkstack(L, 20));
6572 StackUnroller stack_unroller(L);
6574 // Push callback function on stack
6575 if(!get_detached_inventory_callback(L, name, "on_take"))
6578 // Call function(inv, listname, index, stack, player)
6580 InventoryLocation loc;
6581 loc.setDetached(name);
6582 InvRef::create(L, loc);
6584 lua_pushstring(L, listname.c_str());
6586 lua_pushinteger(L, index + 1);
6588 LuaItemStack::create(L, stack);
6590 objectref_get_or_create(L, player);
6591 if(lua_pcall(L, 5, 0, 0))
6592 script_error(L, "error: %s", lua_tostring(L, -1));
6599 void scriptapi_environment_step(lua_State *L, float dtime)
6602 assert(lua_checkstack(L, 20));
6603 //infostream<<"scriptapi_environment_step"<<std::endl;
6604 StackUnroller stack_unroller(L);
6606 // Get minetest.registered_globalsteps
6607 lua_getglobal(L, "minetest");
6608 lua_getfield(L, -1, "registered_globalsteps");
6610 lua_pushnumber(L, dtime);
6611 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6614 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6618 assert(lua_checkstack(L, 20));
6619 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6620 StackUnroller stack_unroller(L);
6622 // Get minetest.registered_on_generateds
6623 lua_getglobal(L, "minetest");
6624 lua_getfield(L, -1, "registered_on_generateds");
6626 push_v3s16(L, minp);
6627 push_v3s16(L, maxp);
6628 lua_pushnumber(L, blockseed);
6629 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6636 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6639 assert(lua_checkstack(L, 20));
6640 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6641 <<name<<"\""<<std::endl;
6642 StackUnroller stack_unroller(L);
6644 // Get minetest.registered_entities[name]
6645 lua_getglobal(L, "minetest");
6646 lua_getfield(L, -1, "registered_entities");
6647 luaL_checktype(L, -1, LUA_TTABLE);
6648 lua_pushstring(L, name);
6649 lua_gettable(L, -2);
6650 // Should be a table, which we will use as a prototype
6651 //luaL_checktype(L, -1, LUA_TTABLE);
6652 if(lua_type(L, -1) != LUA_TTABLE){
6653 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6656 int prototype_table = lua_gettop(L);
6657 //dump2(L, "prototype_table");
6659 // Create entity object
6661 int object = lua_gettop(L);
6663 // Set object metatable
6664 lua_pushvalue(L, prototype_table);
6665 lua_setmetatable(L, -2);
6667 // Add object reference
6668 // This should be userdata with metatable ObjectRef
6669 objectref_get(L, id);
6670 luaL_checktype(L, -1, LUA_TUSERDATA);
6671 if(!luaL_checkudata(L, -1, "ObjectRef"))
6672 luaL_typerror(L, -1, "ObjectRef");
6673 lua_setfield(L, -2, "object");
6675 // minetest.luaentities[id] = object
6676 lua_getglobal(L, "minetest");
6677 lua_getfield(L, -1, "luaentities");
6678 luaL_checktype(L, -1, LUA_TTABLE);
6679 lua_pushnumber(L, id); // Push id
6680 lua_pushvalue(L, object); // Copy object to top of stack
6681 lua_settable(L, -3);
6686 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6687 const std::string &staticdata, u32 dtime_s)
6690 assert(lua_checkstack(L, 20));
6691 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6692 StackUnroller stack_unroller(L);
6694 // Get minetest.luaentities[id]
6695 luaentity_get(L, id);
6696 int object = lua_gettop(L);
6698 // Get on_activate function
6699 lua_pushvalue(L, object);
6700 lua_getfield(L, -1, "on_activate");
6701 if(!lua_isnil(L, -1)){
6702 luaL_checktype(L, -1, LUA_TFUNCTION);
6703 lua_pushvalue(L, object); // self
6704 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6705 lua_pushinteger(L, dtime_s);
6706 // Call with 3 arguments, 0 results
6707 if(lua_pcall(L, 3, 0, 0))
6708 script_error(L, "error running function on_activate: %s\n",
6709 lua_tostring(L, -1));
6713 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6716 assert(lua_checkstack(L, 20));
6717 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6719 // Get minetest.luaentities table
6720 lua_getglobal(L, "minetest");
6721 lua_getfield(L, -1, "luaentities");
6722 luaL_checktype(L, -1, LUA_TTABLE);
6723 int objectstable = lua_gettop(L);
6725 // Set luaentities[id] = nil
6726 lua_pushnumber(L, id); // Push id
6728 lua_settable(L, objectstable);
6730 lua_pop(L, 2); // pop luaentities, minetest
6733 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6736 assert(lua_checkstack(L, 20));
6737 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6738 StackUnroller stack_unroller(L);
6740 // Get minetest.luaentities[id]
6741 luaentity_get(L, id);
6742 int object = lua_gettop(L);
6744 // Get get_staticdata function
6745 lua_pushvalue(L, object);
6746 lua_getfield(L, -1, "get_staticdata");
6747 if(lua_isnil(L, -1))
6750 luaL_checktype(L, -1, LUA_TFUNCTION);
6751 lua_pushvalue(L, object); // self
6752 // Call with 1 arguments, 1 results
6753 if(lua_pcall(L, 1, 1, 0))
6754 script_error(L, "error running function get_staticdata: %s\n",
6755 lua_tostring(L, -1));
6758 const char *s = lua_tolstring(L, -1, &len);
6759 return std::string(s, len);
6762 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6763 ObjectProperties *prop)
6766 assert(lua_checkstack(L, 20));
6767 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6768 StackUnroller stack_unroller(L);
6770 // Get minetest.luaentities[id]
6771 luaentity_get(L, id);
6772 //int object = lua_gettop(L);
6774 // Set default values that differ from ObjectProperties defaults
6779 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6781 getboolfield(L, -1, "physical", prop->physical);
6783 getfloatfield(L, -1, "weight", prop->weight);
6785 lua_getfield(L, -1, "collisionbox");
6786 if(lua_istable(L, -1))
6787 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6790 getstringfield(L, -1, "visual", prop->visual);
6792 getstringfield(L, -1, "mesh", prop->mesh);
6794 // Deprecated: read object properties directly
6795 read_object_properties(L, -1, prop);
6797 // Read initial_properties
6798 lua_getfield(L, -1, "initial_properties");
6799 read_object_properties(L, -1, prop);
6803 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6806 assert(lua_checkstack(L, 20));
6807 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6808 StackUnroller stack_unroller(L);
6810 // Get minetest.luaentities[id]
6811 luaentity_get(L, id);
6812 int object = lua_gettop(L);
6813 // State: object is at top of stack
6814 // Get step function
6815 lua_getfield(L, -1, "on_step");
6816 if(lua_isnil(L, -1))
6818 luaL_checktype(L, -1, LUA_TFUNCTION);
6819 lua_pushvalue(L, object); // self
6820 lua_pushnumber(L, dtime); // dtime
6821 // Call with 2 arguments, 0 results
6822 if(lua_pcall(L, 2, 0, 0))
6823 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6826 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6827 // tool_capabilities, direction)
6828 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6829 ServerActiveObject *puncher, float time_from_last_punch,
6830 const ToolCapabilities *toolcap, v3f dir)
6833 assert(lua_checkstack(L, 20));
6834 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6835 StackUnroller stack_unroller(L);
6837 // Get minetest.luaentities[id]
6838 luaentity_get(L, id);
6839 int object = lua_gettop(L);
6840 // State: object is at top of stack
6842 lua_getfield(L, -1, "on_punch");
6843 if(lua_isnil(L, -1))
6845 luaL_checktype(L, -1, LUA_TFUNCTION);
6846 lua_pushvalue(L, object); // self
6847 objectref_get_or_create(L, puncher); // Clicker reference
6848 lua_pushnumber(L, time_from_last_punch);
6849 push_tool_capabilities(L, *toolcap);
6851 // Call with 5 arguments, 0 results
6852 if(lua_pcall(L, 5, 0, 0))
6853 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6856 // Calls entity:on_rightclick(ObjectRef clicker)
6857 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6858 ServerActiveObject *clicker)
6861 assert(lua_checkstack(L, 20));
6862 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6863 StackUnroller stack_unroller(L);
6865 // Get minetest.luaentities[id]
6866 luaentity_get(L, id);
6867 int object = lua_gettop(L);
6868 // State: object is at top of stack
6870 lua_getfield(L, -1, "on_rightclick");
6871 if(lua_isnil(L, -1))
6873 luaL_checktype(L, -1, LUA_TFUNCTION);
6874 lua_pushvalue(L, object); // self
6875 objectref_get_or_create(L, clicker); // Clicker reference
6876 // Call with 2 arguments, 0 results
6877 if(lua_pcall(L, 2, 0, 0))
6878 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));