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"
52 static void stackDump(lua_State *L, std::ostream &o)
55 int top = lua_gettop(L);
56 for (i = 1; i <= top; i++) { /* repeat for each level */
57 int t = lua_type(L, i);
60 case LUA_TSTRING: /* strings */
61 o<<"\""<<lua_tostring(L, i)<<"\"";
64 case LUA_TBOOLEAN: /* booleans */
65 o<<(lua_toboolean(L, i) ? "true" : "false");
68 case LUA_TNUMBER: /* numbers */ {
70 snprintf(buf, 10, "%g", lua_tonumber(L, i));
74 default: /* other values */
75 o<<lua_typename(L, t);
84 static void realitycheck(lua_State *L)
86 int top = lua_gettop(L);
88 dstream<<"Stack is over 30:"<<std::endl;
89 stackDump(L, dstream);
90 script_error(L, "Stack is over 30 (reality check)");
100 StackUnroller(lua_State *L):
104 m_original_top = lua_gettop(m_lua); // store stack height
108 lua_settop(m_lua, m_original_top); // restore stack height
117 ModNameStorer(lua_State *L_, const std::string modname):
120 // Store current modname in registry
121 lua_pushstring(L, modname.c_str());
122 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
126 // Clear current modname in registry
128 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
133 Getters for stuff in main tables
136 static Server* get_server(lua_State *L)
138 // Get server from registry
139 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
140 Server *server = (Server*)lua_touserdata(L, -1);
145 static ServerEnvironment* get_env(lua_State *L)
147 // Get environment from registry
148 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
149 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
154 static void objectref_get(lua_State *L, u16 id)
156 // Get minetest.object_refs[i]
157 lua_getglobal(L, "minetest");
158 lua_getfield(L, -1, "object_refs");
159 luaL_checktype(L, -1, LUA_TTABLE);
160 lua_pushnumber(L, id);
162 lua_remove(L, -2); // object_refs
163 lua_remove(L, -2); // minetest
166 static void luaentity_get(lua_State *L, u16 id)
168 // Get minetest.luaentities[i]
169 lua_getglobal(L, "minetest");
170 lua_getfield(L, -1, "luaentities");
171 luaL_checktype(L, -1, LUA_TTABLE);
172 lua_pushnumber(L, id);
174 lua_remove(L, -2); // luaentities
175 lua_remove(L, -2); // minetest
182 static bool getstringfield(lua_State *L, int table,
183 const char *fieldname, std::string &result)
185 lua_getfield(L, table, fieldname);
187 if(lua_isstring(L, -1)){
189 const char *ptr = lua_tolstring(L, -1, &len);
190 result.assign(ptr, len);
197 static bool getintfield(lua_State *L, int table,
198 const char *fieldname, int &result)
200 lua_getfield(L, table, fieldname);
202 if(lua_isnumber(L, -1)){
203 result = lua_tonumber(L, -1);
210 static bool getfloatfield(lua_State *L, int table,
211 const char *fieldname, float &result)
213 lua_getfield(L, table, fieldname);
215 if(lua_isnumber(L, -1)){
216 result = lua_tonumber(L, -1);
223 static bool getboolfield(lua_State *L, int table,
224 const char *fieldname, bool &result)
226 lua_getfield(L, table, fieldname);
228 if(lua_isboolean(L, -1)){
229 result = lua_toboolean(L, -1);
236 static std::string checkstringfield(lua_State *L, int table,
237 const char *fieldname)
239 lua_getfield(L, table, fieldname);
240 std::string s = luaL_checkstring(L, -1);
245 static std::string getstringfield_default(lua_State *L, int table,
246 const char *fieldname, const std::string &default_)
248 std::string result = default_;
249 getstringfield(L, table, fieldname, result);
253 static int getintfield_default(lua_State *L, int table,
254 const char *fieldname, int default_)
256 int result = default_;
257 getintfield(L, table, fieldname, result);
261 static float getfloatfield_default(lua_State *L, int table,
262 const char *fieldname, float default_)
264 float result = default_;
265 getfloatfield(L, table, fieldname, result);
269 static bool getboolfield_default(lua_State *L, int table,
270 const char *fieldname, bool default_)
272 bool result = default_;
273 getboolfield(L, table, fieldname, result);
283 static bool string_to_enum(const EnumString *spec, int &result,
284 const std::string &str)
286 const EnumString *esp = spec;
288 if(str == std::string(esp->str)){
297 /*static bool enum_to_string(const EnumString *spec, std::string &result,
300 const EnumString *esp = spec;
311 static int getenumfield(lua_State *L, int table,
312 const char *fieldname, const EnumString *spec, int default_)
314 int result = default_;
315 string_to_enum(spec, result,
316 getstringfield_default(L, table, fieldname, ""));
320 static void setintfield(lua_State *L, int table,
321 const char *fieldname, int value)
323 lua_pushinteger(L, value);
326 lua_setfield(L, table, fieldname);
329 static void setfloatfield(lua_State *L, int table,
330 const char *fieldname, float value)
332 lua_pushnumber(L, value);
335 lua_setfield(L, table, fieldname);
338 static void setboolfield(lua_State *L, int table,
339 const char *fieldname, bool value)
341 lua_pushboolean(L, value);
344 lua_setfield(L, table, fieldname);
347 static void warn_if_field_exists(lua_State *L, int table,
348 const char *fieldname, const std::string &message)
350 lua_getfield(L, table, fieldname);
351 if(!lua_isnil(L, -1)){
352 infostream<<script_get_backtrace(L)<<std::endl;
353 infostream<<"WARNING: field \""<<fieldname<<"\": "
354 <<message<<std::endl;
360 EnumString definitions
363 struct EnumString es_ItemType[] =
367 {ITEM_CRAFT, "craft"},
372 struct EnumString es_DrawType[] =
374 {NDT_NORMAL, "normal"},
375 {NDT_AIRLIKE, "airlike"},
376 {NDT_LIQUID, "liquid"},
377 {NDT_FLOWINGLIQUID, "flowingliquid"},
378 {NDT_GLASSLIKE, "glasslike"},
379 {NDT_ALLFACES, "allfaces"},
380 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
381 {NDT_TORCHLIKE, "torchlike"},
382 {NDT_SIGNLIKE, "signlike"},
383 {NDT_PLANTLIKE, "plantlike"},
384 {NDT_FENCELIKE, "fencelike"},
385 {NDT_RAILLIKE, "raillike"},
386 {NDT_NODEBOX, "nodebox"},
390 struct EnumString es_ContentParamType[] =
393 {CPT_LIGHT, "light"},
397 struct EnumString es_ContentParamType2[] =
401 {CPT2_FLOWINGLIQUID, "flowingliquid"},
402 {CPT2_FACEDIR, "facedir"},
403 {CPT2_WALLMOUNTED, "wallmounted"},
407 struct EnumString es_LiquidType[] =
409 {LIQUID_NONE, "none"},
410 {LIQUID_FLOWING, "flowing"},
411 {LIQUID_SOURCE, "source"},
415 struct EnumString es_NodeBoxType[] =
417 {NODEBOX_REGULAR, "regular"},
418 {NODEBOX_FIXED, "fixed"},
419 {NODEBOX_WALLMOUNTED, "wallmounted"},
423 struct EnumString es_CraftMethod[] =
425 {CRAFT_METHOD_NORMAL, "normal"},
426 {CRAFT_METHOD_COOKING, "cooking"},
427 {CRAFT_METHOD_FUEL, "fuel"},
431 struct EnumString es_TileAnimationType[] =
434 {TAT_VERTICAL_FRAMES, "vertical_frames"},
439 C struct <-> Lua table converter functions
442 static void push_v3f(lua_State *L, v3f p)
445 lua_pushnumber(L, p.X);
446 lua_setfield(L, -2, "x");
447 lua_pushnumber(L, p.Y);
448 lua_setfield(L, -2, "y");
449 lua_pushnumber(L, p.Z);
450 lua_setfield(L, -2, "z");
453 static v2s16 read_v2s16(lua_State *L, int index)
456 luaL_checktype(L, index, LUA_TTABLE);
457 lua_getfield(L, index, "x");
458 p.X = lua_tonumber(L, -1);
460 lua_getfield(L, index, "y");
461 p.Y = lua_tonumber(L, -1);
466 static v2f read_v2f(lua_State *L, int index)
469 luaL_checktype(L, index, LUA_TTABLE);
470 lua_getfield(L, index, "x");
471 p.X = lua_tonumber(L, -1);
473 lua_getfield(L, index, "y");
474 p.Y = lua_tonumber(L, -1);
479 static v3f read_v3f(lua_State *L, int index)
482 luaL_checktype(L, index, LUA_TTABLE);
483 lua_getfield(L, index, "x");
484 pos.X = lua_tonumber(L, -1);
486 lua_getfield(L, index, "y");
487 pos.Y = lua_tonumber(L, -1);
489 lua_getfield(L, index, "z");
490 pos.Z = lua_tonumber(L, -1);
495 static v3f check_v3f(lua_State *L, int index)
498 luaL_checktype(L, index, LUA_TTABLE);
499 lua_getfield(L, index, "x");
500 pos.X = luaL_checknumber(L, -1);
502 lua_getfield(L, index, "y");
503 pos.Y = luaL_checknumber(L, -1);
505 lua_getfield(L, index, "z");
506 pos.Z = luaL_checknumber(L, -1);
511 static void pushFloatPos(lua_State *L, v3f p)
517 static v3f checkFloatPos(lua_State *L, int index)
519 return check_v3f(L, index) * BS;
522 static void push_v3s16(lua_State *L, v3s16 p)
525 lua_pushnumber(L, p.X);
526 lua_setfield(L, -2, "x");
527 lua_pushnumber(L, p.Y);
528 lua_setfield(L, -2, "y");
529 lua_pushnumber(L, p.Z);
530 lua_setfield(L, -2, "z");
533 static v3s16 read_v3s16(lua_State *L, int index)
535 // Correct rounding at <0
536 v3f pf = read_v3f(L, index);
537 return floatToInt(pf, 1.0);
540 static v3s16 check_v3s16(lua_State *L, int index)
542 // Correct rounding at <0
543 v3f pf = check_v3f(L, index);
544 return floatToInt(pf, 1.0);
547 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
550 lua_pushstring(L, ndef->get(n).name.c_str());
551 lua_setfield(L, -2, "name");
552 lua_pushnumber(L, n.getParam1());
553 lua_setfield(L, -2, "param1");
554 lua_pushnumber(L, n.getParam2());
555 lua_setfield(L, -2, "param2");
558 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
560 lua_getfield(L, index, "name");
561 const char *name = luaL_checkstring(L, -1);
564 lua_getfield(L, index, "param1");
568 param1 = lua_tonumber(L, -1);
571 lua_getfield(L, index, "param2");
575 param2 = lua_tonumber(L, -1);
577 return MapNode(ndef, name, param1, param2);
580 static video::SColor readARGB8(lua_State *L, int index)
583 luaL_checktype(L, index, LUA_TTABLE);
584 lua_getfield(L, index, "a");
585 if(lua_isnumber(L, -1))
586 color.setAlpha(lua_tonumber(L, -1));
588 lua_getfield(L, index, "r");
589 color.setRed(lua_tonumber(L, -1));
591 lua_getfield(L, index, "g");
592 color.setGreen(lua_tonumber(L, -1));
594 lua_getfield(L, index, "b");
595 color.setBlue(lua_tonumber(L, -1));
600 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
603 if(lua_istable(L, index)){
604 lua_rawgeti(L, index, 1);
605 box.MinEdge.X = lua_tonumber(L, -1) * scale;
607 lua_rawgeti(L, index, 2);
608 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
610 lua_rawgeti(L, index, 3);
611 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
613 lua_rawgeti(L, index, 4);
614 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
616 lua_rawgeti(L, index, 5);
617 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
619 lua_rawgeti(L, index, 6);
620 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
626 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
628 std::vector<aabb3f> boxes;
629 if(lua_istable(L, index)){
630 int n = lua_objlen(L, index);
631 // Check if it's a single box or a list of boxes
632 bool possibly_single_box = (n == 6);
633 for(int i = 1; i <= n && possibly_single_box; i++){
634 lua_rawgeti(L, index, i);
635 if(!lua_isnumber(L, -1))
636 possibly_single_box = false;
639 if(possibly_single_box){
641 boxes.push_back(read_aabb3f(L, index, scale));
643 // Read a list of boxes
644 for(int i = 1; i <= n; i++){
645 lua_rawgeti(L, index, i);
646 boxes.push_back(read_aabb3f(L, -1, scale));
654 static NodeBox read_nodebox(lua_State *L, int index)
657 if(lua_istable(L, -1)){
658 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
659 es_NodeBoxType, NODEBOX_REGULAR);
661 lua_getfield(L, index, "fixed");
662 if(lua_istable(L, -1))
663 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
666 lua_getfield(L, index, "wall_top");
667 if(lua_istable(L, -1))
668 nodebox.wall_top = read_aabb3f(L, -1, BS);
671 lua_getfield(L, index, "wall_bottom");
672 if(lua_istable(L, -1))
673 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
676 lua_getfield(L, index, "wall_side");
677 if(lua_istable(L, -1))
678 nodebox.wall_side = read_aabb3f(L, -1, BS);
687 static void read_groups(lua_State *L, int index,
688 std::map<std::string, int> &result)
690 if (!lua_istable(L,index))
696 while(lua_next(L, index) != 0){
697 // key at index -2 and value at index -1
698 std::string name = luaL_checkstring(L, -2);
699 int rating = luaL_checkinteger(L, -1);
700 result[name] = rating;
701 // removes value, keeps key for next iteration
709 static void read_privileges(lua_State *L, int index,
710 std::set<std::string> &result)
716 while(lua_next(L, index) != 0){
717 // key at index -2 and value at index -1
718 std::string key = luaL_checkstring(L, -2);
719 bool value = lua_toboolean(L, -1);
722 // removes value, keeps key for next iteration
731 static ToolCapabilities read_tool_capabilities(
732 lua_State *L, int table)
734 ToolCapabilities toolcap;
735 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
736 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
737 lua_getfield(L, table, "groupcaps");
738 if(lua_istable(L, -1)){
739 int table_groupcaps = lua_gettop(L);
741 while(lua_next(L, table_groupcaps) != 0){
742 // key at index -2 and value at index -1
743 std::string groupname = luaL_checkstring(L, -2);
744 if(lua_istable(L, -1)){
745 int table_groupcap = lua_gettop(L);
746 // This will be created
747 ToolGroupCap groupcap;
748 // Read simple parameters
749 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
750 getintfield(L, table_groupcap, "uses", groupcap.uses);
751 // DEPRECATED: maxwear
753 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
755 groupcap.uses = 1.0/maxwear;
758 infostream<<script_get_backtrace(L)<<std::endl;
759 infostream<<"WARNING: field \"maxwear\" is deprecated; "
760 <<"should replace with uses=1/maxwear"<<std::endl;
762 // Read "times" table
763 lua_getfield(L, table_groupcap, "times");
764 if(lua_istable(L, -1)){
765 int table_times = lua_gettop(L);
767 while(lua_next(L, table_times) != 0){
768 // key at index -2 and value at index -1
769 int rating = luaL_checkinteger(L, -2);
770 float time = luaL_checknumber(L, -1);
771 groupcap.times[rating] = time;
772 // removes value, keeps key for next iteration
777 // Insert groupcap into toolcap
778 toolcap.groupcaps[groupname] = groupcap;
780 // removes value, keeps key for next iteration
788 static void set_tool_capabilities(lua_State *L, int table,
789 const ToolCapabilities &toolcap)
791 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
792 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
793 // Create groupcaps table
796 for(std::map<std::string, ToolGroupCap>::const_iterator
797 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
798 // Create groupcap table
800 const std::string &name = i->first;
801 const ToolGroupCap &groupcap = i->second;
802 // Create subtable "times"
804 for(std::map<int, float>::const_iterator
805 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
806 int rating = i->first;
807 float time = i->second;
808 lua_pushinteger(L, rating);
809 lua_pushnumber(L, time);
812 // Set subtable "times"
813 lua_setfield(L, -2, "times");
814 // Set simple parameters
815 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
816 setintfield(L, -1, "uses", groupcap.uses);
817 // Insert groupcap table into groupcaps table
818 lua_setfield(L, -2, name.c_str());
820 // Set groupcaps table
821 lua_setfield(L, -2, "groupcaps");
824 static void push_tool_capabilities(lua_State *L,
825 const ToolCapabilities &prop)
828 set_tool_capabilities(L, -1, prop);
835 static void set_dig_params(lua_State *L, int table,
836 const DigParams ¶ms)
838 setboolfield(L, table, "diggable", params.diggable);
839 setfloatfield(L, table, "time", params.time);
840 setintfield(L, table, "wear", params.wear);
843 static void push_dig_params(lua_State *L,
844 const DigParams ¶ms)
847 set_dig_params(L, -1, params);
854 static void set_hit_params(lua_State *L, int table,
855 const HitParams ¶ms)
857 setintfield(L, table, "hp", params.hp);
858 setintfield(L, table, "wear", params.wear);
861 static void push_hit_params(lua_State *L,
862 const HitParams ¶ms)
865 set_hit_params(L, -1, params);
872 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
875 if(pointed.type == POINTEDTHING_NODE)
877 lua_pushstring(L, "node");
878 lua_setfield(L, -2, "type");
879 push_v3s16(L, pointed.node_undersurface);
880 lua_setfield(L, -2, "under");
881 push_v3s16(L, pointed.node_abovesurface);
882 lua_setfield(L, -2, "above");
884 else if(pointed.type == POINTEDTHING_OBJECT)
886 lua_pushstring(L, "object");
887 lua_setfield(L, -2, "type");
888 objectref_get(L, pointed.object_id);
889 lua_setfield(L, -2, "ref");
893 lua_pushstring(L, "nothing");
894 lua_setfield(L, -2, "type");
902 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
905 index = lua_gettop(L) + 1 + index;
906 if(lua_isnil(L, index)){
907 } else if(lua_istable(L, index)){
908 getstringfield(L, index, "name", spec.name);
909 getfloatfield(L, index, "gain", spec.gain);
910 } else if(lua_isstring(L, index)){
911 spec.name = lua_tostring(L, index);
919 static void read_object_properties(lua_State *L, int index,
920 ObjectProperties *prop)
923 index = lua_gettop(L) + 1 + index;
924 if(!lua_istable(L, index))
927 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
929 getboolfield(L, -1, "physical", prop->physical);
931 getfloatfield(L, -1, "weight", prop->weight);
933 lua_getfield(L, -1, "collisionbox");
934 if(lua_istable(L, -1))
935 prop->collisionbox = read_aabb3f(L, -1, 1.0);
938 getstringfield(L, -1, "visual", prop->visual);
940 getstringfield(L, -1, "mesh", prop->mesh);
942 lua_getfield(L, -1, "visual_size");
943 if(lua_istable(L, -1))
944 prop->visual_size = read_v2f(L, -1);
947 lua_getfield(L, -1, "textures");
948 if(lua_istable(L, -1)){
949 prop->textures.clear();
950 int table = lua_gettop(L);
952 while(lua_next(L, table) != 0){
953 // key at index -2 and value at index -1
954 if(lua_isstring(L, -1))
955 prop->textures.push_back(lua_tostring(L, -1));
957 prop->textures.push_back("");
958 // removes value, keeps key for next iteration
964 lua_getfield(L, -1, "colors");
965 if(lua_istable(L, -1)){
966 prop->colors.clear();
967 int table = lua_gettop(L);
969 while(lua_next(L, table) != 0){
970 // key at index -2 and value at index -1
971 if(lua_isstring(L, -1))
972 prop->colors.push_back(readARGB8(L, -1));
974 prop->colors.push_back(video::SColor(255, 255, 255, 255));
975 // removes value, keeps key for next iteration
981 lua_getfield(L, -1, "spritediv");
982 if(lua_istable(L, -1))
983 prop->spritediv = read_v2s16(L, -1);
986 lua_getfield(L, -1, "initial_sprite_basepos");
987 if(lua_istable(L, -1))
988 prop->initial_sprite_basepos = read_v2s16(L, -1);
991 getboolfield(L, -1, "is_visible", prop->is_visible);
992 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
993 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
1000 static ItemDefinition read_item_definition(lua_State *L, int index,
1001 ItemDefinition default_def = ItemDefinition())
1004 index = lua_gettop(L) + 1 + index;
1006 // Read the item definition
1007 ItemDefinition def = default_def;
1009 def.type = (ItemType)getenumfield(L, index, "type",
1010 es_ItemType, ITEM_NONE);
1011 getstringfield(L, index, "name", def.name);
1012 getstringfield(L, index, "description", def.description);
1013 getstringfield(L, index, "inventory_image", def.inventory_image);
1014 getstringfield(L, index, "wield_image", def.wield_image);
1016 lua_getfield(L, index, "wield_scale");
1017 if(lua_istable(L, -1)){
1018 def.wield_scale = check_v3f(L, -1);
1022 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1023 if(def.stack_max == 0)
1026 lua_getfield(L, index, "on_use");
1027 def.usable = lua_isfunction(L, -1);
1030 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1032 warn_if_field_exists(L, index, "tool_digging_properties",
1033 "deprecated: use tool_capabilities");
1035 lua_getfield(L, index, "tool_capabilities");
1036 if(lua_istable(L, -1)){
1037 def.tool_capabilities = new ToolCapabilities(
1038 read_tool_capabilities(L, -1));
1041 // If name is "" (hand), ensure there are ToolCapabilities
1042 // because it will be looked up there whenever any other item has
1043 // no ToolCapabilities
1044 if(def.name == "" && def.tool_capabilities == NULL){
1045 def.tool_capabilities = new ToolCapabilities();
1048 lua_getfield(L, index, "groups");
1049 read_groups(L, -1, def.groups);
1052 // Client shall immediately place this node when player places the item.
1053 // Server will update the precise end result a moment later.
1054 // "" = no prediction
1055 getstringfield(L, index, "node_placement_prediction",
1056 def.node_placement_prediction);
1065 static TileDef read_tiledef(lua_State *L, int index)
1068 index = lua_gettop(L) + 1 + index;
1072 // key at index -2 and value at index
1073 if(lua_isstring(L, index)){
1074 // "default_lava.png"
1075 tiledef.name = lua_tostring(L, index);
1077 else if(lua_istable(L, index))
1079 // {name="default_lava.png", animation={}}
1081 getstringfield(L, index, "name", tiledef.name);
1082 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1083 tiledef.backface_culling = getboolfield_default(
1084 L, index, "backface_culling", true);
1086 lua_getfield(L, index, "animation");
1087 if(lua_istable(L, -1)){
1088 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1089 tiledef.animation.type = (TileAnimationType)
1090 getenumfield(L, -1, "type", es_TileAnimationType,
1092 tiledef.animation.aspect_w =
1093 getintfield_default(L, -1, "aspect_w", 16);
1094 tiledef.animation.aspect_h =
1095 getintfield_default(L, -1, "aspect_h", 16);
1096 tiledef.animation.length =
1097 getfloatfield_default(L, -1, "length", 1.0);
1109 static ContentFeatures read_content_features(lua_State *L, int index)
1112 index = lua_gettop(L) + 1 + index;
1116 /* Cache existence of some callbacks */
1117 lua_getfield(L, index, "on_construct");
1118 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1120 lua_getfield(L, index, "on_destruct");
1121 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1123 lua_getfield(L, index, "after_destruct");
1124 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1128 getstringfield(L, index, "name", f.name);
1131 lua_getfield(L, index, "groups");
1132 read_groups(L, -1, f.groups);
1135 /* Visual definition */
1137 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1139 getfloatfield(L, index, "visual_scale", f.visual_scale);
1142 lua_getfield(L, index, "tiles");
1143 // If nil, try the deprecated name "tile_images" instead
1144 if(lua_isnil(L, -1)){
1146 warn_if_field_exists(L, index, "tile_images",
1147 "Deprecated; new name is \"tiles\".");
1148 lua_getfield(L, index, "tile_images");
1150 if(lua_istable(L, -1)){
1151 int table = lua_gettop(L);
1154 while(lua_next(L, table) != 0){
1155 // Read tiledef from value
1156 f.tiledef[i] = read_tiledef(L, -1);
1157 // removes value, keeps key for next iteration
1165 // Copy last value to all remaining textures
1167 TileDef lasttile = f.tiledef[i-1];
1169 f.tiledef[i] = lasttile;
1176 // special_tiles = {}
1177 lua_getfield(L, index, "special_tiles");
1178 // If nil, try the deprecated name "special_materials" instead
1179 if(lua_isnil(L, -1)){
1181 warn_if_field_exists(L, index, "special_materials",
1182 "Deprecated; new name is \"special_tiles\".");
1183 lua_getfield(L, index, "special_materials");
1185 if(lua_istable(L, -1)){
1186 int table = lua_gettop(L);
1189 while(lua_next(L, table) != 0){
1190 // Read tiledef from value
1191 f.tiledef_special[i] = read_tiledef(L, -1);
1192 // removes value, keeps key for next iteration
1203 f.alpha = getintfield_default(L, index, "alpha", 255);
1207 lua_getfield(L, index, "post_effect_color");
1208 if(!lua_isnil(L, -1))
1209 f.post_effect_color = readARGB8(L, -1);
1212 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1213 es_ContentParamType, CPT_NONE);
1214 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1215 es_ContentParamType2, CPT2_NONE);
1217 // Warn about some deprecated fields
1218 warn_if_field_exists(L, index, "wall_mounted",
1219 "deprecated: use paramtype2 = 'wallmounted'");
1220 warn_if_field_exists(L, index, "light_propagates",
1221 "deprecated: determined from paramtype");
1222 warn_if_field_exists(L, index, "dug_item",
1223 "deprecated: use 'drop' field");
1224 warn_if_field_exists(L, index, "extra_dug_item",
1225 "deprecated: use 'drop' field");
1226 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1227 "deprecated: use 'drop' field");
1228 warn_if_field_exists(L, index, "metadata_name",
1229 "deprecated: use on_add and metadata callbacks");
1231 // True for all ground-like things like stone and mud, false for eg. trees
1232 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1233 f.light_propagates = (f.param_type == CPT_LIGHT);
1234 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1235 // This is used for collision detection.
1236 // Also for general solidness queries.
1237 getboolfield(L, index, "walkable", f.walkable);
1238 // Player can point to these
1239 getboolfield(L, index, "pointable", f.pointable);
1240 // Player can dig these
1241 getboolfield(L, index, "diggable", f.diggable);
1242 // Player can climb these
1243 getboolfield(L, index, "climbable", f.climbable);
1244 // Player can build on these
1245 getboolfield(L, index, "buildable_to", f.buildable_to);
1246 // Whether the node is non-liquid, source liquid or flowing liquid
1247 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1248 es_LiquidType, LIQUID_NONE);
1249 // If the content is liquid, this is the flowing version of the liquid.
1250 getstringfield(L, index, "liquid_alternative_flowing",
1251 f.liquid_alternative_flowing);
1252 // If the content is liquid, this is the source version of the liquid.
1253 getstringfield(L, index, "liquid_alternative_source",
1254 f.liquid_alternative_source);
1255 // Viscosity for fluid flow, ranging from 1 to 7, with
1256 // 1 giving almost instantaneous propagation and 7 being
1257 // the slowest possible
1258 f.liquid_viscosity = getintfield_default(L, index,
1259 "liquid_viscosity", f.liquid_viscosity);
1260 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1261 // Amount of light the node emits
1262 f.light_source = getintfield_default(L, index,
1263 "light_source", f.light_source);
1264 f.damage_per_second = getintfield_default(L, index,
1265 "damage_per_second", f.damage_per_second);
1267 lua_getfield(L, index, "node_box");
1268 if(lua_istable(L, -1))
1269 f.node_box = read_nodebox(L, -1);
1272 lua_getfield(L, index, "selection_box");
1273 if(lua_istable(L, -1))
1274 f.selection_box = read_nodebox(L, -1);
1277 // Set to true if paramtype used to be 'facedir_simple'
1278 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1279 // Set to true if wall_mounted used to be set to true
1280 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1283 lua_getfield(L, index, "sounds");
1284 if(lua_istable(L, -1)){
1285 lua_getfield(L, -1, "footstep");
1286 read_soundspec(L, -1, f.sound_footstep);
1288 lua_getfield(L, -1, "dig");
1289 read_soundspec(L, -1, f.sound_dig);
1291 lua_getfield(L, -1, "dug");
1292 read_soundspec(L, -1, f.sound_dug);
1304 static ItemStack read_item(lua_State *L, int index);
1305 static std::vector<ItemStack> read_items(lua_State *L, int index);
1306 // creates a table of ItemStacks
1307 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1309 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1310 lua_State *L, int tableindex, int forcesize=-1)
1313 tableindex = lua_gettop(L) + 1 + tableindex;
1314 // If nil, delete list
1315 if(lua_isnil(L, tableindex)){
1316 inv->deleteList(name);
1319 // Otherwise set list
1320 std::vector<ItemStack> items = read_items(L, tableindex);
1321 int listsize = (forcesize != -1) ? forcesize : items.size();
1322 InventoryList *invlist = inv->addList(name, listsize);
1324 for(std::vector<ItemStack>::const_iterator
1325 i = items.begin(); i != items.end(); i++){
1326 if(forcesize != -1 && index == forcesize)
1328 invlist->changeItem(index, *i);
1331 while(forcesize != -1 && index < forcesize){
1332 invlist->deleteItem(index);
1337 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1340 InventoryList *invlist = inv->getList(name);
1341 if(invlist == NULL){
1345 std::vector<ItemStack> items;
1346 for(u32 i=0; i<invlist->getSize(); i++)
1347 items.push_back(invlist->getItem(i));
1348 push_items(L, items);
1352 Helpful macros for userdata classes
1355 #define method(class, name) {#name, class::l_##name}
1366 static const char className[];
1367 static const luaL_reg methods[];
1369 // Exported functions
1371 // garbage collector
1372 static int gc_object(lua_State *L)
1374 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1379 // is_empty(self) -> true/false
1380 static int l_is_empty(lua_State *L)
1382 LuaItemStack *o = checkobject(L, 1);
1383 ItemStack &item = o->m_stack;
1384 lua_pushboolean(L, item.empty());
1388 // get_name(self) -> string
1389 static int l_get_name(lua_State *L)
1391 LuaItemStack *o = checkobject(L, 1);
1392 ItemStack &item = o->m_stack;
1393 lua_pushstring(L, item.name.c_str());
1397 // get_count(self) -> number
1398 static int l_get_count(lua_State *L)
1400 LuaItemStack *o = checkobject(L, 1);
1401 ItemStack &item = o->m_stack;
1402 lua_pushinteger(L, item.count);
1406 // get_wear(self) -> number
1407 static int l_get_wear(lua_State *L)
1409 LuaItemStack *o = checkobject(L, 1);
1410 ItemStack &item = o->m_stack;
1411 lua_pushinteger(L, item.wear);
1415 // get_metadata(self) -> string
1416 static int l_get_metadata(lua_State *L)
1418 LuaItemStack *o = checkobject(L, 1);
1419 ItemStack &item = o->m_stack;
1420 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1424 // clear(self) -> true
1425 static int l_clear(lua_State *L)
1427 LuaItemStack *o = checkobject(L, 1);
1429 lua_pushboolean(L, true);
1433 // replace(self, itemstack or itemstring or table or nil) -> true
1434 static int l_replace(lua_State *L)
1436 LuaItemStack *o = checkobject(L, 1);
1437 o->m_stack = read_item(L, 2);
1438 lua_pushboolean(L, true);
1442 // to_string(self) -> string
1443 static int l_to_string(lua_State *L)
1445 LuaItemStack *o = checkobject(L, 1);
1446 std::string itemstring = o->m_stack.getItemString();
1447 lua_pushstring(L, itemstring.c_str());
1451 // to_table(self) -> table or nil
1452 static int l_to_table(lua_State *L)
1454 LuaItemStack *o = checkobject(L, 1);
1455 const ItemStack &item = o->m_stack;
1463 lua_pushstring(L, item.name.c_str());
1464 lua_setfield(L, -2, "name");
1465 lua_pushinteger(L, item.count);
1466 lua_setfield(L, -2, "count");
1467 lua_pushinteger(L, item.wear);
1468 lua_setfield(L, -2, "wear");
1469 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1470 lua_setfield(L, -2, "metadata");
1475 // get_stack_max(self) -> number
1476 static int l_get_stack_max(lua_State *L)
1478 LuaItemStack *o = checkobject(L, 1);
1479 ItemStack &item = o->m_stack;
1480 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1484 // get_free_space(self) -> number
1485 static int l_get_free_space(lua_State *L)
1487 LuaItemStack *o = checkobject(L, 1);
1488 ItemStack &item = o->m_stack;
1489 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1493 // is_known(self) -> true/false
1494 // Checks if the item is defined.
1495 static int l_is_known(lua_State *L)
1497 LuaItemStack *o = checkobject(L, 1);
1498 ItemStack &item = o->m_stack;
1499 bool is_known = item.isKnown(get_server(L)->idef());
1500 lua_pushboolean(L, is_known);
1504 // get_definition(self) -> table
1505 // Returns the item definition table from minetest.registered_items,
1506 // or a fallback one (name="unknown")
1507 static int l_get_definition(lua_State *L)
1509 LuaItemStack *o = checkobject(L, 1);
1510 ItemStack &item = o->m_stack;
1512 // Get minetest.registered_items[name]
1513 lua_getglobal(L, "minetest");
1514 lua_getfield(L, -1, "registered_items");
1515 luaL_checktype(L, -1, LUA_TTABLE);
1516 lua_getfield(L, -1, item.name.c_str());
1517 if(lua_isnil(L, -1))
1520 lua_getfield(L, -1, "unknown");
1525 // get_tool_capabilities(self) -> table
1526 // Returns the effective tool digging properties.
1527 // Returns those of the hand ("") if this item has none associated.
1528 static int l_get_tool_capabilities(lua_State *L)
1530 LuaItemStack *o = checkobject(L, 1);
1531 ItemStack &item = o->m_stack;
1532 const ToolCapabilities &prop =
1533 item.getToolCapabilities(get_server(L)->idef());
1534 push_tool_capabilities(L, prop);
1538 // add_wear(self, amount) -> true/false
1539 // The range for "amount" is [0,65535]. Wear is only added if the item
1540 // is a tool. Adding wear might destroy the item.
1541 // Returns true if the item is (or was) a tool.
1542 static int l_add_wear(lua_State *L)
1544 LuaItemStack *o = checkobject(L, 1);
1545 ItemStack &item = o->m_stack;
1546 int amount = lua_tointeger(L, 2);
1547 bool result = item.addWear(amount, get_server(L)->idef());
1548 lua_pushboolean(L, result);
1552 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1553 // Returns leftover item stack
1554 static int l_add_item(lua_State *L)
1556 LuaItemStack *o = checkobject(L, 1);
1557 ItemStack &item = o->m_stack;
1558 ItemStack newitem = read_item(L, 2);
1559 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1560 create(L, leftover);
1564 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1565 // First return value is true iff the new item fits fully into the stack
1566 // Second return value is the would-be-left-over item stack
1567 static int l_item_fits(lua_State *L)
1569 LuaItemStack *o = checkobject(L, 1);
1570 ItemStack &item = o->m_stack;
1571 ItemStack newitem = read_item(L, 2);
1573 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1574 lua_pushboolean(L, fits); // first return value
1575 create(L, restitem); // second return value
1579 // take_item(self, takecount=1) -> itemstack
1580 static int l_take_item(lua_State *L)
1582 LuaItemStack *o = checkobject(L, 1);
1583 ItemStack &item = o->m_stack;
1585 if(!lua_isnone(L, 2))
1586 takecount = luaL_checkinteger(L, 2);
1587 ItemStack taken = item.takeItem(takecount);
1592 // peek_item(self, peekcount=1) -> itemstack
1593 static int l_peek_item(lua_State *L)
1595 LuaItemStack *o = checkobject(L, 1);
1596 ItemStack &item = o->m_stack;
1598 if(!lua_isnone(L, 2))
1599 peekcount = lua_tointeger(L, 2);
1600 ItemStack peekaboo = item.peekItem(peekcount);
1601 create(L, peekaboo);
1606 LuaItemStack(const ItemStack &item):
1615 const ItemStack& getItem() const
1619 ItemStack& getItem()
1624 // LuaItemStack(itemstack or itemstring or table or nil)
1625 // Creates an LuaItemStack and leaves it on top of stack
1626 static int create_object(lua_State *L)
1628 ItemStack item = read_item(L, 1);
1629 LuaItemStack *o = new LuaItemStack(item);
1630 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1631 luaL_getmetatable(L, className);
1632 lua_setmetatable(L, -2);
1635 // Not callable from Lua
1636 static int create(lua_State *L, const ItemStack &item)
1638 LuaItemStack *o = new LuaItemStack(item);
1639 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1640 luaL_getmetatable(L, className);
1641 lua_setmetatable(L, -2);
1645 static LuaItemStack* checkobject(lua_State *L, int narg)
1647 luaL_checktype(L, narg, LUA_TUSERDATA);
1648 void *ud = luaL_checkudata(L, narg, className);
1649 if(!ud) luaL_typerror(L, narg, className);
1650 return *(LuaItemStack**)ud; // unbox pointer
1653 static void Register(lua_State *L)
1656 int methodtable = lua_gettop(L);
1657 luaL_newmetatable(L, className);
1658 int metatable = lua_gettop(L);
1660 lua_pushliteral(L, "__metatable");
1661 lua_pushvalue(L, methodtable);
1662 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1664 lua_pushliteral(L, "__index");
1665 lua_pushvalue(L, methodtable);
1666 lua_settable(L, metatable);
1668 lua_pushliteral(L, "__gc");
1669 lua_pushcfunction(L, gc_object);
1670 lua_settable(L, metatable);
1672 lua_pop(L, 1); // drop metatable
1674 luaL_openlib(L, 0, methods, 0); // fill methodtable
1675 lua_pop(L, 1); // drop methodtable
1677 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1678 lua_register(L, className, create_object);
1681 const char LuaItemStack::className[] = "ItemStack";
1682 const luaL_reg LuaItemStack::methods[] = {
1683 method(LuaItemStack, is_empty),
1684 method(LuaItemStack, get_name),
1685 method(LuaItemStack, get_count),
1686 method(LuaItemStack, get_wear),
1687 method(LuaItemStack, get_metadata),
1688 method(LuaItemStack, clear),
1689 method(LuaItemStack, replace),
1690 method(LuaItemStack, to_string),
1691 method(LuaItemStack, to_table),
1692 method(LuaItemStack, get_stack_max),
1693 method(LuaItemStack, get_free_space),
1694 method(LuaItemStack, is_known),
1695 method(LuaItemStack, get_definition),
1696 method(LuaItemStack, get_tool_capabilities),
1697 method(LuaItemStack, add_wear),
1698 method(LuaItemStack, add_item),
1699 method(LuaItemStack, item_fits),
1700 method(LuaItemStack, take_item),
1701 method(LuaItemStack, peek_item),
1705 static ItemStack read_item(lua_State *L, int index)
1708 index = lua_gettop(L) + 1 + index;
1710 if(lua_isnil(L, index))
1714 else if(lua_isuserdata(L, index))
1716 // Convert from LuaItemStack
1717 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1718 return o->getItem();
1720 else if(lua_isstring(L, index))
1722 // Convert from itemstring
1723 std::string itemstring = lua_tostring(L, index);
1724 IItemDefManager *idef = get_server(L)->idef();
1728 item.deSerialize(itemstring, idef);
1731 catch(SerializationError &e)
1733 infostream<<"WARNING: unable to create item from itemstring"
1734 <<": "<<itemstring<<std::endl;
1738 else if(lua_istable(L, index))
1740 // Convert from table
1741 IItemDefManager *idef = get_server(L)->idef();
1742 std::string name = getstringfield_default(L, index, "name", "");
1743 int count = getintfield_default(L, index, "count", 1);
1744 int wear = getintfield_default(L, index, "wear", 0);
1745 std::string metadata = getstringfield_default(L, index, "metadata", "");
1746 return ItemStack(name, count, wear, metadata, idef);
1750 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1754 static std::vector<ItemStack> read_items(lua_State *L, int index)
1757 index = lua_gettop(L) + 1 + index;
1759 std::vector<ItemStack> items;
1760 luaL_checktype(L, index, LUA_TTABLE);
1762 while(lua_next(L, index) != 0){
1763 // key at index -2 and value at index -1
1764 items.push_back(read_item(L, -1));
1765 // removes value, keeps key for next iteration
1771 // creates a table of ItemStacks
1772 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1774 // Get the table insert function
1775 lua_getglobal(L, "table");
1776 lua_getfield(L, -1, "insert");
1777 int table_insert = lua_gettop(L);
1778 // Create and fill table
1780 int table = lua_gettop(L);
1781 for(u32 i=0; i<items.size(); i++){
1782 ItemStack item = items[i];
1783 lua_pushvalue(L, table_insert);
1784 lua_pushvalue(L, table);
1785 LuaItemStack::create(L, item);
1786 if(lua_pcall(L, 2, 0, 0))
1787 script_error(L, "error: %s", lua_tostring(L, -1));
1789 lua_remove(L, -2); // Remove table
1790 lua_remove(L, -2); // Remove insert
1800 InventoryLocation m_loc;
1802 static const char className[];
1803 static const luaL_reg methods[];
1805 static InvRef *checkobject(lua_State *L, int narg)
1807 luaL_checktype(L, narg, LUA_TUSERDATA);
1808 void *ud = luaL_checkudata(L, narg, className);
1809 if(!ud) luaL_typerror(L, narg, className);
1810 return *(InvRef**)ud; // unbox pointer
1813 static Inventory* getinv(lua_State *L, InvRef *ref)
1815 return get_server(L)->getInventory(ref->m_loc);
1818 static InventoryList* getlist(lua_State *L, InvRef *ref,
1819 const char *listname)
1821 Inventory *inv = getinv(L, ref);
1824 return inv->getList(listname);
1827 static void reportInventoryChange(lua_State *L, InvRef *ref)
1829 // Inform other things that the inventory has changed
1830 get_server(L)->setInventoryModified(ref->m_loc);
1833 // Exported functions
1835 // garbage collector
1836 static int gc_object(lua_State *L) {
1837 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1842 // is_empty(self, listname) -> true/false
1843 static int l_is_empty(lua_State *L)
1845 InvRef *ref = checkobject(L, 1);
1846 const char *listname = luaL_checkstring(L, 2);
1847 InventoryList *list = getlist(L, ref, listname);
1848 if(list && list->getUsedSlots() > 0){
1849 lua_pushboolean(L, false);
1851 lua_pushboolean(L, true);
1856 // get_size(self, listname)
1857 static int l_get_size(lua_State *L)
1859 InvRef *ref = checkobject(L, 1);
1860 const char *listname = luaL_checkstring(L, 2);
1861 InventoryList *list = getlist(L, ref, listname);
1863 lua_pushinteger(L, list->getSize());
1865 lua_pushinteger(L, 0);
1870 // get_width(self, listname)
1871 static int l_get_width(lua_State *L)
1873 InvRef *ref = checkobject(L, 1);
1874 const char *listname = luaL_checkstring(L, 2);
1875 InventoryList *list = getlist(L, ref, listname);
1877 lua_pushinteger(L, list->getWidth());
1879 lua_pushinteger(L, 0);
1884 // set_size(self, listname, size)
1885 static int l_set_size(lua_State *L)
1887 InvRef *ref = checkobject(L, 1);
1888 const char *listname = luaL_checkstring(L, 2);
1889 int newsize = luaL_checknumber(L, 3);
1890 Inventory *inv = getinv(L, ref);
1892 inv->deleteList(listname);
1893 reportInventoryChange(L, ref);
1896 InventoryList *list = inv->getList(listname);
1898 list->setSize(newsize);
1900 list = inv->addList(listname, newsize);
1902 reportInventoryChange(L, ref);
1906 // set_width(self, listname, size)
1907 static int l_set_width(lua_State *L)
1909 InvRef *ref = checkobject(L, 1);
1910 const char *listname = luaL_checkstring(L, 2);
1911 int newwidth = luaL_checknumber(L, 3);
1912 Inventory *inv = getinv(L, ref);
1913 InventoryList *list = inv->getList(listname);
1915 list->setWidth(newwidth);
1919 reportInventoryChange(L, ref);
1923 // get_stack(self, listname, i) -> itemstack
1924 static int l_get_stack(lua_State *L)
1926 InvRef *ref = checkobject(L, 1);
1927 const char *listname = luaL_checkstring(L, 2);
1928 int i = luaL_checknumber(L, 3) - 1;
1929 InventoryList *list = getlist(L, ref, listname);
1931 if(list != NULL && i >= 0 && i < (int) list->getSize())
1932 item = list->getItem(i);
1933 LuaItemStack::create(L, item);
1937 // set_stack(self, listname, i, stack) -> true/false
1938 static int l_set_stack(lua_State *L)
1940 InvRef *ref = checkobject(L, 1);
1941 const char *listname = luaL_checkstring(L, 2);
1942 int i = luaL_checknumber(L, 3) - 1;
1943 ItemStack newitem = read_item(L, 4);
1944 InventoryList *list = getlist(L, ref, listname);
1945 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1946 list->changeItem(i, newitem);
1947 reportInventoryChange(L, ref);
1948 lua_pushboolean(L, true);
1950 lua_pushboolean(L, false);
1955 // get_list(self, listname) -> list or nil
1956 static int l_get_list(lua_State *L)
1958 InvRef *ref = checkobject(L, 1);
1959 const char *listname = luaL_checkstring(L, 2);
1960 Inventory *inv = getinv(L, ref);
1961 inventory_get_list_to_lua(inv, listname, L);
1965 // set_list(self, listname, list)
1966 static int l_set_list(lua_State *L)
1968 InvRef *ref = checkobject(L, 1);
1969 const char *listname = luaL_checkstring(L, 2);
1970 Inventory *inv = getinv(L, ref);
1971 InventoryList *list = inv->getList(listname);
1973 inventory_set_list_from_lua(inv, listname, L, 3,
1976 inventory_set_list_from_lua(inv, listname, L, 3);
1977 reportInventoryChange(L, ref);
1981 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1982 // Returns the leftover stack
1983 static int l_add_item(lua_State *L)
1985 InvRef *ref = checkobject(L, 1);
1986 const char *listname = luaL_checkstring(L, 2);
1987 ItemStack item = read_item(L, 3);
1988 InventoryList *list = getlist(L, ref, listname);
1990 ItemStack leftover = list->addItem(item);
1991 if(leftover.count != item.count)
1992 reportInventoryChange(L, ref);
1993 LuaItemStack::create(L, leftover);
1995 LuaItemStack::create(L, item);
2000 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2001 // Returns true if the item completely fits into the list
2002 static int l_room_for_item(lua_State *L)
2004 InvRef *ref = checkobject(L, 1);
2005 const char *listname = luaL_checkstring(L, 2);
2006 ItemStack item = read_item(L, 3);
2007 InventoryList *list = getlist(L, ref, listname);
2009 lua_pushboolean(L, list->roomForItem(item));
2011 lua_pushboolean(L, false);
2016 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2017 // Returns true if the list contains the given count of the given item name
2018 static int l_contains_item(lua_State *L)
2020 InvRef *ref = checkobject(L, 1);
2021 const char *listname = luaL_checkstring(L, 2);
2022 ItemStack item = read_item(L, 3);
2023 InventoryList *list = getlist(L, ref, listname);
2025 lua_pushboolean(L, list->containsItem(item));
2027 lua_pushboolean(L, false);
2032 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2033 // Returns the items that were actually removed
2034 static int l_remove_item(lua_State *L)
2036 InvRef *ref = checkobject(L, 1);
2037 const char *listname = luaL_checkstring(L, 2);
2038 ItemStack item = read_item(L, 3);
2039 InventoryList *list = getlist(L, ref, listname);
2041 ItemStack removed = list->removeItem(item);
2042 if(!removed.empty())
2043 reportInventoryChange(L, ref);
2044 LuaItemStack::create(L, removed);
2046 LuaItemStack::create(L, ItemStack());
2052 InvRef(const InventoryLocation &loc):
2061 // Creates an InvRef and leaves it on top of stack
2062 // Not callable from Lua; all references are created on the C side.
2063 static void create(lua_State *L, const InventoryLocation &loc)
2065 InvRef *o = new InvRef(loc);
2066 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2067 luaL_getmetatable(L, className);
2068 lua_setmetatable(L, -2);
2070 static void createPlayer(lua_State *L, Player *player)
2072 InventoryLocation loc;
2073 loc.setPlayer(player->getName());
2076 static void createNodeMeta(lua_State *L, v3s16 p)
2078 InventoryLocation loc;
2083 static void Register(lua_State *L)
2086 int methodtable = lua_gettop(L);
2087 luaL_newmetatable(L, className);
2088 int metatable = lua_gettop(L);
2090 lua_pushliteral(L, "__metatable");
2091 lua_pushvalue(L, methodtable);
2092 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2094 lua_pushliteral(L, "__index");
2095 lua_pushvalue(L, methodtable);
2096 lua_settable(L, metatable);
2098 lua_pushliteral(L, "__gc");
2099 lua_pushcfunction(L, gc_object);
2100 lua_settable(L, metatable);
2102 lua_pop(L, 1); // drop metatable
2104 luaL_openlib(L, 0, methods, 0); // fill methodtable
2105 lua_pop(L, 1); // drop methodtable
2107 // Cannot be created from Lua
2108 //lua_register(L, className, create_object);
2111 const char InvRef::className[] = "InvRef";
2112 const luaL_reg InvRef::methods[] = {
2113 method(InvRef, is_empty),
2114 method(InvRef, get_size),
2115 method(InvRef, set_size),
2116 method(InvRef, get_width),
2117 method(InvRef, set_width),
2118 method(InvRef, get_stack),
2119 method(InvRef, set_stack),
2120 method(InvRef, get_list),
2121 method(InvRef, set_list),
2122 method(InvRef, add_item),
2123 method(InvRef, room_for_item),
2124 method(InvRef, contains_item),
2125 method(InvRef, remove_item),
2137 ServerEnvironment *m_env;
2139 static const char className[];
2140 static const luaL_reg methods[];
2142 static NodeMetaRef *checkobject(lua_State *L, int narg)
2144 luaL_checktype(L, narg, LUA_TUSERDATA);
2145 void *ud = luaL_checkudata(L, narg, className);
2146 if(!ud) luaL_typerror(L, narg, className);
2147 return *(NodeMetaRef**)ud; // unbox pointer
2150 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2152 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2153 if(meta == NULL && auto_create)
2155 meta = new NodeMetadata(ref->m_env->getGameDef());
2156 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2161 static void reportMetadataChange(NodeMetaRef *ref)
2163 // NOTE: This same code is in rollback_interface.cpp
2164 // Inform other things that the metadata has changed
2165 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2167 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2169 ref->m_env->getMap().dispatchEvent(&event);
2170 // Set the block to be saved
2171 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2173 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2174 "NodeMetaRef::reportMetadataChange");
2177 // Exported functions
2179 // garbage collector
2180 static int gc_object(lua_State *L) {
2181 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2186 // get_string(self, name)
2187 static int l_get_string(lua_State *L)
2189 NodeMetaRef *ref = checkobject(L, 1);
2190 std::string name = luaL_checkstring(L, 2);
2192 NodeMetadata *meta = getmeta(ref, false);
2194 lua_pushlstring(L, "", 0);
2197 std::string str = meta->getString(name);
2198 lua_pushlstring(L, str.c_str(), str.size());
2202 // set_string(self, name, var)
2203 static int l_set_string(lua_State *L)
2205 NodeMetaRef *ref = checkobject(L, 1);
2206 std::string name = luaL_checkstring(L, 2);
2208 const char *s = lua_tolstring(L, 3, &len);
2209 std::string str(s, len);
2211 NodeMetadata *meta = getmeta(ref, !str.empty());
2212 if(meta == NULL || str == meta->getString(name))
2214 meta->setString(name, str);
2215 reportMetadataChange(ref);
2219 // get_int(self, name)
2220 static int l_get_int(lua_State *L)
2222 NodeMetaRef *ref = checkobject(L, 1);
2223 std::string name = lua_tostring(L, 2);
2225 NodeMetadata *meta = getmeta(ref, false);
2227 lua_pushnumber(L, 0);
2230 std::string str = meta->getString(name);
2231 lua_pushnumber(L, stoi(str));
2235 // set_int(self, name, var)
2236 static int l_set_int(lua_State *L)
2238 NodeMetaRef *ref = checkobject(L, 1);
2239 std::string name = lua_tostring(L, 2);
2240 int a = lua_tointeger(L, 3);
2241 std::string str = itos(a);
2243 NodeMetadata *meta = getmeta(ref, true);
2244 if(meta == NULL || str == meta->getString(name))
2246 meta->setString(name, str);
2247 reportMetadataChange(ref);
2251 // get_float(self, name)
2252 static int l_get_float(lua_State *L)
2254 NodeMetaRef *ref = checkobject(L, 1);
2255 std::string name = lua_tostring(L, 2);
2257 NodeMetadata *meta = getmeta(ref, false);
2259 lua_pushnumber(L, 0);
2262 std::string str = meta->getString(name);
2263 lua_pushnumber(L, stof(str));
2267 // set_float(self, name, var)
2268 static int l_set_float(lua_State *L)
2270 NodeMetaRef *ref = checkobject(L, 1);
2271 std::string name = lua_tostring(L, 2);
2272 float a = lua_tonumber(L, 3);
2273 std::string str = ftos(a);
2275 NodeMetadata *meta = getmeta(ref, true);
2276 if(meta == NULL || str == meta->getString(name))
2278 meta->setString(name, str);
2279 reportMetadataChange(ref);
2283 // get_inventory(self)
2284 static int l_get_inventory(lua_State *L)
2286 NodeMetaRef *ref = checkobject(L, 1);
2287 getmeta(ref, true); // try to ensure the metadata exists
2288 InvRef::createNodeMeta(L, ref->m_p);
2293 static int l_to_table(lua_State *L)
2295 NodeMetaRef *ref = checkobject(L, 1);
2297 NodeMetadata *meta = getmeta(ref, true);
2306 std::map<std::string, std::string> fields = meta->getStrings();
2307 for(std::map<std::string, std::string>::const_iterator
2308 i = fields.begin(); i != fields.end(); i++){
2309 const std::string &name = i->first;
2310 const std::string &value = i->second;
2311 lua_pushlstring(L, name.c_str(), name.size());
2312 lua_pushlstring(L, value.c_str(), value.size());
2313 lua_settable(L, -3);
2316 lua_setfield(L, -2, "fields");
2319 Inventory *inv = meta->getInventory();
2321 std::vector<const InventoryList*> lists = inv->getLists();
2322 for(std::vector<const InventoryList*>::const_iterator
2323 i = lists.begin(); i != lists.end(); i++){
2324 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2325 lua_setfield(L, -2, (*i)->getName().c_str());
2328 lua_setfield(L, -2, "inventory");
2332 // from_table(self, table)
2333 static int l_from_table(lua_State *L)
2335 NodeMetaRef *ref = checkobject(L, 1);
2338 if(lua_isnil(L, base)){
2340 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2341 lua_pushboolean(L, true);
2345 // Has metadata; clear old one first
2346 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2347 // Create new metadata
2348 NodeMetadata *meta = getmeta(ref, true);
2350 lua_getfield(L, base, "fields");
2351 int fieldstable = lua_gettop(L);
2353 while(lua_next(L, fieldstable) != 0){
2354 // key at index -2 and value at index -1
2355 std::string name = lua_tostring(L, -2);
2357 const char *cs = lua_tolstring(L, -1, &cl);
2358 std::string value(cs, cl);
2359 meta->setString(name, value);
2360 lua_pop(L, 1); // removes value, keeps key for next iteration
2363 Inventory *inv = meta->getInventory();
2364 lua_getfield(L, base, "inventory");
2365 int inventorytable = lua_gettop(L);
2367 while(lua_next(L, inventorytable) != 0){
2368 // key at index -2 and value at index -1
2369 std::string name = lua_tostring(L, -2);
2370 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2371 lua_pop(L, 1); // removes value, keeps key for next iteration
2373 reportMetadataChange(ref);
2374 lua_pushboolean(L, true);
2379 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2389 // Creates an NodeMetaRef and leaves it on top of stack
2390 // Not callable from Lua; all references are created on the C side.
2391 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2393 NodeMetaRef *o = new NodeMetaRef(p, env);
2394 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2395 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2396 luaL_getmetatable(L, className);
2397 lua_setmetatable(L, -2);
2400 static void Register(lua_State *L)
2403 int methodtable = lua_gettop(L);
2404 luaL_newmetatable(L, className);
2405 int metatable = lua_gettop(L);
2407 lua_pushliteral(L, "__metatable");
2408 lua_pushvalue(L, methodtable);
2409 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2411 lua_pushliteral(L, "__index");
2412 lua_pushvalue(L, methodtable);
2413 lua_settable(L, metatable);
2415 lua_pushliteral(L, "__gc");
2416 lua_pushcfunction(L, gc_object);
2417 lua_settable(L, metatable);
2419 lua_pop(L, 1); // drop metatable
2421 luaL_openlib(L, 0, methods, 0); // fill methodtable
2422 lua_pop(L, 1); // drop methodtable
2424 // Cannot be created from Lua
2425 //lua_register(L, className, create_object);
2428 const char NodeMetaRef::className[] = "NodeMetaRef";
2429 const luaL_reg NodeMetaRef::methods[] = {
2430 method(NodeMetaRef, get_string),
2431 method(NodeMetaRef, set_string),
2432 method(NodeMetaRef, get_int),
2433 method(NodeMetaRef, set_int),
2434 method(NodeMetaRef, get_float),
2435 method(NodeMetaRef, set_float),
2436 method(NodeMetaRef, get_inventory),
2437 method(NodeMetaRef, to_table),
2438 method(NodeMetaRef, from_table),
2449 ServerActiveObject *m_object;
2451 static const char className[];
2452 static const luaL_reg methods[];
2454 static ObjectRef *checkobject(lua_State *L, int narg)
2456 luaL_checktype(L, narg, LUA_TUSERDATA);
2457 void *ud = luaL_checkudata(L, narg, className);
2458 if(!ud) luaL_typerror(L, narg, className);
2459 return *(ObjectRef**)ud; // unbox pointer
2462 static ServerActiveObject* getobject(ObjectRef *ref)
2464 ServerActiveObject *co = ref->m_object;
2468 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2470 ServerActiveObject *obj = getobject(ref);
2473 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2475 return (LuaEntitySAO*)obj;
2478 static PlayerSAO* getplayersao(ObjectRef *ref)
2480 ServerActiveObject *obj = getobject(ref);
2483 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2485 return (PlayerSAO*)obj;
2488 static Player* getplayer(ObjectRef *ref)
2490 PlayerSAO *playersao = getplayersao(ref);
2491 if(playersao == NULL)
2493 return playersao->getPlayer();
2496 // Exported functions
2498 // garbage collector
2499 static int gc_object(lua_State *L) {
2500 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2501 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2507 static int l_remove(lua_State *L)
2509 ObjectRef *ref = checkobject(L, 1);
2510 ServerActiveObject *co = getobject(ref);
2511 if(co == NULL) return 0;
2512 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2513 co->m_removed = true;
2518 // returns: {x=num, y=num, z=num}
2519 static int l_getpos(lua_State *L)
2521 ObjectRef *ref = checkobject(L, 1);
2522 ServerActiveObject *co = getobject(ref);
2523 if(co == NULL) return 0;
2524 v3f pos = co->getBasePosition() / BS;
2526 lua_pushnumber(L, pos.X);
2527 lua_setfield(L, -2, "x");
2528 lua_pushnumber(L, pos.Y);
2529 lua_setfield(L, -2, "y");
2530 lua_pushnumber(L, pos.Z);
2531 lua_setfield(L, -2, "z");
2535 // setpos(self, pos)
2536 static int l_setpos(lua_State *L)
2538 ObjectRef *ref = checkobject(L, 1);
2539 //LuaEntitySAO *co = getluaobject(ref);
2540 ServerActiveObject *co = getobject(ref);
2541 if(co == NULL) return 0;
2543 v3f pos = checkFloatPos(L, 2);
2549 // moveto(self, pos, continuous=false)
2550 static int l_moveto(lua_State *L)
2552 ObjectRef *ref = checkobject(L, 1);
2553 //LuaEntitySAO *co = getluaobject(ref);
2554 ServerActiveObject *co = getobject(ref);
2555 if(co == NULL) return 0;
2557 v3f pos = checkFloatPos(L, 2);
2559 bool continuous = lua_toboolean(L, 3);
2561 co->moveTo(pos, continuous);
2565 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2566 static int l_punch(lua_State *L)
2568 ObjectRef *ref = checkobject(L, 1);
2569 ObjectRef *puncher_ref = checkobject(L, 2);
2570 ServerActiveObject *co = getobject(ref);
2571 ServerActiveObject *puncher = getobject(puncher_ref);
2572 if(co == NULL) return 0;
2573 if(puncher == NULL) return 0;
2575 if(lua_type(L, 5) != LUA_TTABLE)
2576 dir = co->getBasePosition() - puncher->getBasePosition();
2578 dir = read_v3f(L, 5);
2579 float time_from_last_punch = 1000000;
2580 if(lua_isnumber(L, 3))
2581 time_from_last_punch = lua_tonumber(L, 3);
2582 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2585 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2589 // right_click(self, clicker); clicker = an another ObjectRef
2590 static int l_right_click(lua_State *L)
2592 ObjectRef *ref = checkobject(L, 1);
2593 ObjectRef *ref2 = checkobject(L, 2);
2594 ServerActiveObject *co = getobject(ref);
2595 ServerActiveObject *co2 = getobject(ref2);
2596 if(co == NULL) return 0;
2597 if(co2 == NULL) return 0;
2599 co->rightClick(co2);
2604 // hp = number of hitpoints (2 * number of hearts)
2606 static int l_set_hp(lua_State *L)
2608 ObjectRef *ref = checkobject(L, 1);
2609 luaL_checknumber(L, 2);
2610 ServerActiveObject *co = getobject(ref);
2611 if(co == NULL) return 0;
2612 int hp = lua_tonumber(L, 2);
2613 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2614 <<" hp="<<hp<<std::endl;*/
2622 // returns: number of hitpoints (2 * number of hearts)
2623 // 0 if not applicable to this type of object
2624 static int l_get_hp(lua_State *L)
2626 ObjectRef *ref = checkobject(L, 1);
2627 ServerActiveObject *co = getobject(ref);
2630 lua_pushnumber(L, 1);
2633 int hp = co->getHP();
2634 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2635 <<" hp="<<hp<<std::endl;*/
2637 lua_pushnumber(L, hp);
2641 // get_inventory(self)
2642 static int l_get_inventory(lua_State *L)
2644 ObjectRef *ref = checkobject(L, 1);
2645 ServerActiveObject *co = getobject(ref);
2646 if(co == NULL) return 0;
2648 InventoryLocation loc = co->getInventoryLocation();
2649 if(get_server(L)->getInventory(loc) != NULL)
2650 InvRef::create(L, loc);
2652 lua_pushnil(L); // An object may have no inventory (nil)
2656 // get_wield_list(self)
2657 static int l_get_wield_list(lua_State *L)
2659 ObjectRef *ref = checkobject(L, 1);
2660 ServerActiveObject *co = getobject(ref);
2661 if(co == NULL) return 0;
2663 lua_pushstring(L, co->getWieldList().c_str());
2667 // get_wield_index(self)
2668 static int l_get_wield_index(lua_State *L)
2670 ObjectRef *ref = checkobject(L, 1);
2671 ServerActiveObject *co = getobject(ref);
2672 if(co == NULL) return 0;
2674 lua_pushinteger(L, co->getWieldIndex() + 1);
2678 // get_wielded_item(self)
2679 static int l_get_wielded_item(lua_State *L)
2681 ObjectRef *ref = checkobject(L, 1);
2682 ServerActiveObject *co = getobject(ref);
2685 LuaItemStack::create(L, ItemStack());
2689 LuaItemStack::create(L, co->getWieldedItem());
2693 // set_wielded_item(self, itemstack or itemstring or table or nil)
2694 static int l_set_wielded_item(lua_State *L)
2696 ObjectRef *ref = checkobject(L, 1);
2697 ServerActiveObject *co = getobject(ref);
2698 if(co == NULL) return 0;
2700 ItemStack item = read_item(L, 2);
2701 bool success = co->setWieldedItem(item);
2702 lua_pushboolean(L, success);
2706 // set_armor_groups(self, groups)
2707 static int l_set_armor_groups(lua_State *L)
2709 ObjectRef *ref = checkobject(L, 1);
2710 ServerActiveObject *co = getobject(ref);
2711 if(co == NULL) return 0;
2713 ItemGroupList groups;
2714 read_groups(L, 2, groups);
2715 co->setArmorGroups(groups);
2719 // set_animation(self, frame_range, frame_speed, frame_blend)
2720 static int l_set_animation(lua_State *L)
2722 ObjectRef *ref = checkobject(L, 1);
2723 ServerActiveObject *co = getobject(ref);
2724 if(co == NULL) return 0;
2726 v2f frames = v2f(1, 1);
2727 if(!lua_isnil(L, 2))
2728 frames = read_v2f(L, 2);
2729 float frame_speed = 15;
2730 if(!lua_isnil(L, 3))
2731 frame_speed = lua_tonumber(L, 3);
2732 float frame_blend = 0;
2733 if(!lua_isnil(L, 4))
2734 frame_blend = lua_tonumber(L, 4);
2735 co->setAnimation(frames, frame_speed, frame_blend);
2739 // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2740 static int l_set_bone_position(lua_State *L)
2742 ObjectRef *ref = checkobject(L, 1);
2743 ServerActiveObject *co = getobject(ref);
2744 if(co == NULL) return 0;
2746 std::string bone = "";
2747 if(!lua_isnil(L, 2))
2748 bone = lua_tostring(L, 2);
2749 v3f position = v3f(0, 0, 0);
2750 if(!lua_isnil(L, 3))
2751 position = read_v3f(L, 3);
2752 v3f rotation = v3f(0, 0, 0);
2753 if(!lua_isnil(L, 4))
2754 rotation = read_v3f(L, 4);
2755 co->setBonePosition(bone, position, rotation);
2759 // set_attach(self, parent, bone, position, rotation)
2760 static int l_set_attach(lua_State *L)
2762 ObjectRef *ref = checkobject(L, 1);
2763 ObjectRef *parent_ref = checkobject(L, 2);
2764 ServerActiveObject *co = getobject(ref);
2765 ServerActiveObject *parent = getobject(parent_ref);
2766 if(co == NULL) return 0;
2767 if(parent == NULL) return 0;
2769 std::string bone = "";
2770 if(!lua_isnil(L, 3))
2771 bone = lua_tostring(L, 3);
2772 v3f position = v3f(0, 0, 0);
2773 if(!lua_isnil(L, 4))
2774 position = read_v3f(L, 4);
2775 v3f rotation = v3f(0, 0, 0);
2776 if(!lua_isnil(L, 5))
2777 rotation = read_v3f(L, 5);
2778 co->setAttachment(parent->getId(), bone, position, rotation);
2783 static int l_set_detach(lua_State *L)
2785 ObjectRef *ref = checkobject(L, 1);
2786 ServerActiveObject *co = getobject(ref);
2787 if(co == NULL) return 0;
2789 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2793 // set_properties(self, properties)
2794 static int l_set_properties(lua_State *L)
2796 ObjectRef *ref = checkobject(L, 1);
2797 ServerActiveObject *co = getobject(ref);
2798 if(co == NULL) return 0;
2799 ObjectProperties *prop = co->accessObjectProperties();
2802 read_object_properties(L, 2, prop);
2803 co->notifyObjectPropertiesModified();
2807 /* LuaEntitySAO-only */
2809 // setvelocity(self, {x=num, y=num, z=num})
2810 static int l_setvelocity(lua_State *L)
2812 ObjectRef *ref = checkobject(L, 1);
2813 LuaEntitySAO *co = getluaobject(ref);
2814 if(co == NULL) return 0;
2815 v3f pos = checkFloatPos(L, 2);
2817 co->setVelocity(pos);
2821 // getvelocity(self)
2822 static int l_getvelocity(lua_State *L)
2824 ObjectRef *ref = checkobject(L, 1);
2825 LuaEntitySAO *co = getluaobject(ref);
2826 if(co == NULL) return 0;
2828 v3f v = co->getVelocity();
2833 // setacceleration(self, {x=num, y=num, z=num})
2834 static int l_setacceleration(lua_State *L)
2836 ObjectRef *ref = checkobject(L, 1);
2837 LuaEntitySAO *co = getluaobject(ref);
2838 if(co == NULL) return 0;
2840 v3f pos = checkFloatPos(L, 2);
2842 co->setAcceleration(pos);
2846 // getacceleration(self)
2847 static int l_getacceleration(lua_State *L)
2849 ObjectRef *ref = checkobject(L, 1);
2850 LuaEntitySAO *co = getluaobject(ref);
2851 if(co == NULL) return 0;
2853 v3f v = co->getAcceleration();
2858 // setyaw(self, radians)
2859 static int l_setyaw(lua_State *L)
2861 ObjectRef *ref = checkobject(L, 1);
2862 LuaEntitySAO *co = getluaobject(ref);
2863 if(co == NULL) return 0;
2864 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2871 static int l_getyaw(lua_State *L)
2873 ObjectRef *ref = checkobject(L, 1);
2874 LuaEntitySAO *co = getluaobject(ref);
2875 if(co == NULL) return 0;
2877 float yaw = co->getYaw() * core::DEGTORAD;
2878 lua_pushnumber(L, yaw);
2882 // settexturemod(self, mod)
2883 static int l_settexturemod(lua_State *L)
2885 ObjectRef *ref = checkobject(L, 1);
2886 LuaEntitySAO *co = getluaobject(ref);
2887 if(co == NULL) return 0;
2889 std::string mod = luaL_checkstring(L, 2);
2890 co->setTextureMod(mod);
2894 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2895 // select_horiz_by_yawpitch=false)
2896 static int l_setsprite(lua_State *L)
2898 ObjectRef *ref = checkobject(L, 1);
2899 LuaEntitySAO *co = getluaobject(ref);
2900 if(co == NULL) return 0;
2903 if(!lua_isnil(L, 2))
2904 p = read_v2s16(L, 2);
2906 if(!lua_isnil(L, 3))
2907 num_frames = lua_tonumber(L, 3);
2908 float framelength = 0.2;
2909 if(!lua_isnil(L, 4))
2910 framelength = lua_tonumber(L, 4);
2911 bool select_horiz_by_yawpitch = false;
2912 if(!lua_isnil(L, 5))
2913 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2914 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2919 // get_entity_name(self)
2920 static int l_get_entity_name(lua_State *L)
2922 ObjectRef *ref = checkobject(L, 1);
2923 LuaEntitySAO *co = getluaobject(ref);
2924 if(co == NULL) return 0;
2926 std::string name = co->getName();
2927 lua_pushstring(L, name.c_str());
2931 // get_luaentity(self)
2932 static int l_get_luaentity(lua_State *L)
2934 ObjectRef *ref = checkobject(L, 1);
2935 LuaEntitySAO *co = getluaobject(ref);
2936 if(co == NULL) return 0;
2938 luaentity_get(L, co->getId());
2945 static int l_is_player(lua_State *L)
2947 ObjectRef *ref = checkobject(L, 1);
2948 Player *player = getplayer(ref);
2949 lua_pushboolean(L, (player != NULL));
2953 // get_player_name(self)
2954 static int l_get_player_name(lua_State *L)
2956 ObjectRef *ref = checkobject(L, 1);
2957 Player *player = getplayer(ref);
2959 lua_pushlstring(L, "", 0);
2963 lua_pushstring(L, player->getName());
2967 // get_look_dir(self)
2968 static int l_get_look_dir(lua_State *L)
2970 ObjectRef *ref = checkobject(L, 1);
2971 Player *player = getplayer(ref);
2972 if(player == NULL) return 0;
2974 float pitch = player->getRadPitch();
2975 float yaw = player->getRadYaw();
2976 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2981 // get_look_pitch(self)
2982 static int l_get_look_pitch(lua_State *L)
2984 ObjectRef *ref = checkobject(L, 1);
2985 Player *player = getplayer(ref);
2986 if(player == NULL) return 0;
2988 lua_pushnumber(L, player->getRadPitch());
2992 // get_look_yaw(self)
2993 static int l_get_look_yaw(lua_State *L)
2995 ObjectRef *ref = checkobject(L, 1);
2996 Player *player = getplayer(ref);
2997 if(player == NULL) return 0;
2999 lua_pushnumber(L, player->getRadYaw());
3003 // set_inventory_formspec(self, formspec)
3004 static int l_set_inventory_formspec(lua_State *L)
3006 ObjectRef *ref = checkobject(L, 1);
3007 Player *player = getplayer(ref);
3008 if(player == NULL) return 0;
3009 std::string formspec = luaL_checkstring(L, 2);
3011 player->inventory_formspec = formspec;
3012 get_server(L)->reportInventoryFormspecModified(player->getName());
3013 lua_pushboolean(L, true);
3017 // get_inventory_formspec(self) -> formspec
3018 static int l_get_inventory_formspec(lua_State *L)
3020 ObjectRef *ref = checkobject(L, 1);
3021 Player *player = getplayer(ref);
3022 if(player == NULL) return 0;
3024 std::string formspec = player->inventory_formspec;
3025 lua_pushlstring(L, formspec.c_str(), formspec.size());
3030 ObjectRef(ServerActiveObject *object):
3033 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3039 infostream<<"ObjectRef destructing for id="
3040 <<m_object->getId()<<std::endl;
3042 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3045 // Creates an ObjectRef and leaves it on top of stack
3046 // Not callable from Lua; all references are created on the C side.
3047 static void create(lua_State *L, ServerActiveObject *object)
3049 ObjectRef *o = new ObjectRef(object);
3050 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3051 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3052 luaL_getmetatable(L, className);
3053 lua_setmetatable(L, -2);
3056 static void set_null(lua_State *L)
3058 ObjectRef *o = checkobject(L, -1);
3062 static void Register(lua_State *L)
3065 int methodtable = lua_gettop(L);
3066 luaL_newmetatable(L, className);
3067 int metatable = lua_gettop(L);
3069 lua_pushliteral(L, "__metatable");
3070 lua_pushvalue(L, methodtable);
3071 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3073 lua_pushliteral(L, "__index");
3074 lua_pushvalue(L, methodtable);
3075 lua_settable(L, metatable);
3077 lua_pushliteral(L, "__gc");
3078 lua_pushcfunction(L, gc_object);
3079 lua_settable(L, metatable);
3081 lua_pop(L, 1); // drop metatable
3083 luaL_openlib(L, 0, methods, 0); // fill methodtable
3084 lua_pop(L, 1); // drop methodtable
3086 // Cannot be created from Lua
3087 //lua_register(L, className, create_object);
3090 const char ObjectRef::className[] = "ObjectRef";
3091 const luaL_reg ObjectRef::methods[] = {
3092 // ServerActiveObject
3093 method(ObjectRef, remove),
3094 method(ObjectRef, getpos),
3095 method(ObjectRef, setpos),
3096 method(ObjectRef, moveto),
3097 method(ObjectRef, punch),
3098 method(ObjectRef, right_click),
3099 method(ObjectRef, set_hp),
3100 method(ObjectRef, get_hp),
3101 method(ObjectRef, get_inventory),
3102 method(ObjectRef, get_wield_list),
3103 method(ObjectRef, get_wield_index),
3104 method(ObjectRef, get_wielded_item),
3105 method(ObjectRef, set_wielded_item),
3106 method(ObjectRef, set_armor_groups),
3107 method(ObjectRef, set_animation),
3108 method(ObjectRef, set_bone_position),
3109 method(ObjectRef, set_attach),
3110 method(ObjectRef, set_detach),
3111 method(ObjectRef, set_properties),
3112 // LuaEntitySAO-only
3113 method(ObjectRef, setvelocity),
3114 method(ObjectRef, getvelocity),
3115 method(ObjectRef, setacceleration),
3116 method(ObjectRef, getacceleration),
3117 method(ObjectRef, setyaw),
3118 method(ObjectRef, getyaw),
3119 method(ObjectRef, settexturemod),
3120 method(ObjectRef, setsprite),
3121 method(ObjectRef, get_entity_name),
3122 method(ObjectRef, get_luaentity),
3124 method(ObjectRef, is_player),
3125 method(ObjectRef, get_player_name),
3126 method(ObjectRef, get_look_dir),
3127 method(ObjectRef, get_look_pitch),
3128 method(ObjectRef, get_look_yaw),
3129 method(ObjectRef, set_inventory_formspec),
3130 method(ObjectRef, get_inventory_formspec),
3134 // Creates a new anonymous reference if cobj=NULL or id=0
3135 static void objectref_get_or_create(lua_State *L,
3136 ServerActiveObject *cobj)
3138 if(cobj == NULL || cobj->getId() == 0){
3139 ObjectRef::create(L, cobj);
3141 objectref_get(L, cobj->getId());
3150 class LuaPerlinNoise
3157 static const char className[];
3158 static const luaL_reg methods[];
3160 // Exported functions
3162 // garbage collector
3163 static int gc_object(lua_State *L)
3165 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3170 static int l_get2d(lua_State *L)
3172 LuaPerlinNoise *o = checkobject(L, 1);
3173 v2f pos2d = read_v2f(L,2);
3174 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3175 lua_pushnumber(L, val);
3178 static int l_get3d(lua_State *L)
3180 LuaPerlinNoise *o = checkobject(L, 1);
3181 v3f pos3d = read_v3f(L,2);
3182 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3183 lua_pushnumber(L, val);
3188 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3192 persistence(a_persistence),
3201 // LuaPerlinNoise(seed, octaves, persistence, scale)
3202 // Creates an LuaPerlinNoise and leaves it on top of stack
3203 static int create_object(lua_State *L)
3205 int seed = luaL_checkint(L, 1);
3206 int octaves = luaL_checkint(L, 2);
3207 double persistence = luaL_checknumber(L, 3);
3208 double scale = luaL_checknumber(L, 4);
3209 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3210 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3211 luaL_getmetatable(L, className);
3212 lua_setmetatable(L, -2);
3216 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3218 luaL_checktype(L, narg, LUA_TUSERDATA);
3219 void *ud = luaL_checkudata(L, narg, className);
3220 if(!ud) luaL_typerror(L, narg, className);
3221 return *(LuaPerlinNoise**)ud; // unbox pointer
3224 static void Register(lua_State *L)
3227 int methodtable = lua_gettop(L);
3228 luaL_newmetatable(L, className);
3229 int metatable = lua_gettop(L);
3231 lua_pushliteral(L, "__metatable");
3232 lua_pushvalue(L, methodtable);
3233 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3235 lua_pushliteral(L, "__index");
3236 lua_pushvalue(L, methodtable);
3237 lua_settable(L, metatable);
3239 lua_pushliteral(L, "__gc");
3240 lua_pushcfunction(L, gc_object);
3241 lua_settable(L, metatable);
3243 lua_pop(L, 1); // drop metatable
3245 luaL_openlib(L, 0, methods, 0); // fill methodtable
3246 lua_pop(L, 1); // drop methodtable
3248 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3249 lua_register(L, className, create_object);
3252 const char LuaPerlinNoise::className[] = "PerlinNoise";
3253 const luaL_reg LuaPerlinNoise::methods[] = {
3254 method(LuaPerlinNoise, get2d),
3255 method(LuaPerlinNoise, get3d),
3267 ServerEnvironment *m_env;
3269 static const char className[];
3270 static const luaL_reg methods[];
3272 static int gc_object(lua_State *L) {
3273 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3278 static NodeTimerRef *checkobject(lua_State *L, int narg)
3280 luaL_checktype(L, narg, LUA_TUSERDATA);
3281 void *ud = luaL_checkudata(L, narg, className);
3282 if(!ud) luaL_typerror(L, narg, className);
3283 return *(NodeTimerRef**)ud; // unbox pointer
3286 static int l_set(lua_State *L)
3288 NodeTimerRef *o = checkobject(L, 1);
3289 ServerEnvironment *env = o->m_env;
3290 if(env == NULL) return 0;
3291 f32 t = luaL_checknumber(L,2);
3292 f32 e = luaL_checknumber(L,3);
3293 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3297 static int l_start(lua_State *L)
3299 NodeTimerRef *o = checkobject(L, 1);
3300 ServerEnvironment *env = o->m_env;
3301 if(env == NULL) return 0;
3302 f32 t = luaL_checknumber(L,2);
3303 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3307 static int l_stop(lua_State *L)
3309 NodeTimerRef *o = checkobject(L, 1);
3310 ServerEnvironment *env = o->m_env;
3311 if(env == NULL) return 0;
3312 env->getMap().removeNodeTimer(o->m_p);
3316 static int l_is_started(lua_State *L)
3318 NodeTimerRef *o = checkobject(L, 1);
3319 ServerEnvironment *env = o->m_env;
3320 if(env == NULL) return 0;
3322 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3323 lua_pushboolean(L,(t.timeout != 0));
3327 static int l_get_timeout(lua_State *L)
3329 NodeTimerRef *o = checkobject(L, 1);
3330 ServerEnvironment *env = o->m_env;
3331 if(env == NULL) return 0;
3333 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3334 lua_pushnumber(L,t.timeout);
3338 static int l_get_elapsed(lua_State *L)
3340 NodeTimerRef *o = checkobject(L, 1);
3341 ServerEnvironment *env = o->m_env;
3342 if(env == NULL) return 0;
3344 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3345 lua_pushnumber(L,t.elapsed);
3350 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3360 // Creates an NodeTimerRef and leaves it on top of stack
3361 // Not callable from Lua; all references are created on the C side.
3362 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3364 NodeTimerRef *o = new NodeTimerRef(p, env);
3365 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3366 luaL_getmetatable(L, className);
3367 lua_setmetatable(L, -2);
3370 static void set_null(lua_State *L)
3372 NodeTimerRef *o = checkobject(L, -1);
3376 static void Register(lua_State *L)
3379 int methodtable = lua_gettop(L);
3380 luaL_newmetatable(L, className);
3381 int metatable = lua_gettop(L);
3383 lua_pushliteral(L, "__metatable");
3384 lua_pushvalue(L, methodtable);
3385 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3387 lua_pushliteral(L, "__index");
3388 lua_pushvalue(L, methodtable);
3389 lua_settable(L, metatable);
3391 lua_pushliteral(L, "__gc");
3392 lua_pushcfunction(L, gc_object);
3393 lua_settable(L, metatable);
3395 lua_pop(L, 1); // drop metatable
3397 luaL_openlib(L, 0, methods, 0); // fill methodtable
3398 lua_pop(L, 1); // drop methodtable
3400 // Cannot be created from Lua
3401 //lua_register(L, className, create_object);
3404 const char NodeTimerRef::className[] = "NodeTimerRef";
3405 const luaL_reg NodeTimerRef::methods[] = {
3406 method(NodeTimerRef, start),
3407 method(NodeTimerRef, set),
3408 method(NodeTimerRef, stop),
3409 method(NodeTimerRef, is_started),
3410 method(NodeTimerRef, get_timeout),
3411 method(NodeTimerRef, get_elapsed),
3422 ServerEnvironment *m_env;
3424 static const char className[];
3425 static const luaL_reg methods[];
3427 static int gc_object(lua_State *L) {
3428 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3433 static EnvRef *checkobject(lua_State *L, int narg)
3435 luaL_checktype(L, narg, LUA_TUSERDATA);
3436 void *ud = luaL_checkudata(L, narg, className);
3437 if(!ud) luaL_typerror(L, narg, className);
3438 return *(EnvRef**)ud; // unbox pointer
3441 // Exported functions
3443 // EnvRef:set_node(pos, node)
3444 // pos = {x=num, y=num, z=num}
3445 static int l_set_node(lua_State *L)
3447 EnvRef *o = checkobject(L, 1);
3448 ServerEnvironment *env = o->m_env;
3449 if(env == NULL) return 0;
3450 INodeDefManager *ndef = env->getGameDef()->ndef();
3452 v3s16 pos = read_v3s16(L, 2);
3453 MapNode n = readnode(L, 3, ndef);
3455 MapNode n_old = env->getMap().getNodeNoEx(pos);
3457 if(ndef->get(n_old).has_on_destruct)
3458 scriptapi_node_on_destruct(L, pos, n_old);
3460 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3462 // Call post-destructor
3463 if(ndef->get(n_old).has_after_destruct)
3464 scriptapi_node_after_destruct(L, pos, n_old);
3466 if(ndef->get(n).has_on_construct)
3467 scriptapi_node_on_construct(L, pos, n);
3469 lua_pushboolean(L, succeeded);
3473 static int l_add_node(lua_State *L)
3475 return l_set_node(L);
3478 // EnvRef:remove_node(pos)
3479 // pos = {x=num, y=num, z=num}
3480 static int l_remove_node(lua_State *L)
3482 EnvRef *o = checkobject(L, 1);
3483 ServerEnvironment *env = o->m_env;
3484 if(env == NULL) return 0;
3485 INodeDefManager *ndef = env->getGameDef()->ndef();
3487 v3s16 pos = read_v3s16(L, 2);
3489 MapNode n_old = env->getMap().getNodeNoEx(pos);
3491 if(ndef->get(n_old).has_on_destruct)
3492 scriptapi_node_on_destruct(L, pos, n_old);
3494 // This is slightly optimized compared to addNodeWithEvent(air)
3495 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3497 // Call post-destructor
3498 if(ndef->get(n_old).has_after_destruct)
3499 scriptapi_node_after_destruct(L, pos, n_old);
3501 lua_pushboolean(L, succeeded);
3502 // Air doesn't require constructor
3506 // EnvRef:get_node(pos)
3507 // pos = {x=num, y=num, z=num}
3508 static int l_get_node(lua_State *L)
3510 EnvRef *o = checkobject(L, 1);
3511 ServerEnvironment *env = o->m_env;
3512 if(env == NULL) return 0;
3514 v3s16 pos = read_v3s16(L, 2);
3516 MapNode n = env->getMap().getNodeNoEx(pos);
3518 pushnode(L, n, env->getGameDef()->ndef());
3522 // EnvRef:get_node_or_nil(pos)
3523 // pos = {x=num, y=num, z=num}
3524 static int l_get_node_or_nil(lua_State *L)
3526 EnvRef *o = checkobject(L, 1);
3527 ServerEnvironment *env = o->m_env;
3528 if(env == NULL) return 0;
3530 v3s16 pos = read_v3s16(L, 2);
3533 MapNode n = env->getMap().getNode(pos);
3535 pushnode(L, n, env->getGameDef()->ndef());
3537 } catch(InvalidPositionException &e)
3544 // EnvRef:get_node_light(pos, timeofday)
3545 // pos = {x=num, y=num, z=num}
3546 // timeofday: nil = current time, 0 = night, 0.5 = day
3547 static int l_get_node_light(lua_State *L)
3549 EnvRef *o = checkobject(L, 1);
3550 ServerEnvironment *env = o->m_env;
3551 if(env == NULL) return 0;
3553 v3s16 pos = read_v3s16(L, 2);
3554 u32 time_of_day = env->getTimeOfDay();
3555 if(lua_isnumber(L, 3))
3556 time_of_day = 24000.0 * lua_tonumber(L, 3);
3557 time_of_day %= 24000;
3558 u32 dnr = time_to_daynight_ratio(time_of_day);
3559 MapNode n = env->getMap().getNodeNoEx(pos);
3561 MapNode n = env->getMap().getNode(pos);
3562 INodeDefManager *ndef = env->getGameDef()->ndef();
3563 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3565 } catch(InvalidPositionException &e)
3572 // EnvRef:place_node(pos, node)
3573 // pos = {x=num, y=num, z=num}
3574 static int l_place_node(lua_State *L)
3576 EnvRef *o = checkobject(L, 1);
3577 ServerEnvironment *env = o->m_env;
3578 if(env == NULL) return 0;
3579 v3s16 pos = read_v3s16(L, 2);
3580 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3582 // Don't attempt to load non-loaded area as of now
3583 MapNode n_old = env->getMap().getNodeNoEx(pos);
3584 if(n_old.getContent() == CONTENT_IGNORE){
3585 lua_pushboolean(L, false);
3588 // Create item to place
3589 INodeDefManager *ndef = get_server(L)->ndef();
3590 IItemDefManager *idef = get_server(L)->idef();
3591 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3592 // Make pointed position
3593 PointedThing pointed;
3594 pointed.type = POINTEDTHING_NODE;
3595 pointed.node_abovesurface = pos;
3596 pointed.node_undersurface = pos + v3s16(0,-1,0);
3597 // Place it with a NULL placer (appears in Lua as a non-functional
3599 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3600 lua_pushboolean(L, success);
3604 // EnvRef:dig_node(pos)
3605 // pos = {x=num, y=num, z=num}
3606 static int l_dig_node(lua_State *L)
3608 EnvRef *o = checkobject(L, 1);
3609 ServerEnvironment *env = o->m_env;
3610 if(env == NULL) return 0;
3611 v3s16 pos = read_v3s16(L, 2);
3613 // Don't attempt to load non-loaded area as of now
3614 MapNode n = env->getMap().getNodeNoEx(pos);
3615 if(n.getContent() == CONTENT_IGNORE){
3616 lua_pushboolean(L, false);
3619 // Dig it out with a NULL digger (appears in Lua as a
3620 // non-functional ObjectRef)
3621 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3622 lua_pushboolean(L, success);
3626 // EnvRef:punch_node(pos)
3627 // pos = {x=num, y=num, z=num}
3628 static int l_punch_node(lua_State *L)
3630 EnvRef *o = checkobject(L, 1);
3631 ServerEnvironment *env = o->m_env;
3632 if(env == NULL) return 0;
3633 v3s16 pos = read_v3s16(L, 2);
3635 // Don't attempt to load non-loaded area as of now
3636 MapNode n = env->getMap().getNodeNoEx(pos);
3637 if(n.getContent() == CONTENT_IGNORE){
3638 lua_pushboolean(L, false);
3641 // Punch it with a NULL puncher (appears in Lua as a non-functional
3643 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3644 lua_pushboolean(L, success);
3648 // EnvRef:get_meta(pos)
3649 static int l_get_meta(lua_State *L)
3651 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3652 EnvRef *o = checkobject(L, 1);
3653 ServerEnvironment *env = o->m_env;
3654 if(env == NULL) return 0;
3656 v3s16 p = read_v3s16(L, 2);
3657 NodeMetaRef::create(L, p, env);
3661 // EnvRef:get_node_timer(pos)
3662 static int l_get_node_timer(lua_State *L)
3664 EnvRef *o = checkobject(L, 1);
3665 ServerEnvironment *env = o->m_env;
3666 if(env == NULL) return 0;
3668 v3s16 p = read_v3s16(L, 2);
3669 NodeTimerRef::create(L, p, env);
3673 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3674 // pos = {x=num, y=num, z=num}
3675 static int l_add_entity(lua_State *L)
3677 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3678 EnvRef *o = checkobject(L, 1);
3679 ServerEnvironment *env = o->m_env;
3680 if(env == NULL) return 0;
3682 v3f pos = checkFloatPos(L, 2);
3684 const char *name = luaL_checkstring(L, 3);
3686 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3687 int objectid = env->addActiveObject(obj);
3688 // If failed to add, return nothing (reads as nil)
3692 objectref_get_or_create(L, obj);
3696 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3697 // pos = {x=num, y=num, z=num}
3698 static int l_add_item(lua_State *L)
3700 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3701 EnvRef *o = checkobject(L, 1);
3702 ServerEnvironment *env = o->m_env;
3703 if(env == NULL) return 0;
3705 v3f pos = checkFloatPos(L, 2);
3707 ItemStack item = read_item(L, 3);
3708 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3710 // Use minetest.spawn_item to spawn a __builtin:item
3711 lua_getglobal(L, "minetest");
3712 lua_getfield(L, -1, "spawn_item");
3713 if(lua_isnil(L, -1))
3715 lua_pushvalue(L, 2);
3716 lua_pushstring(L, item.getItemString().c_str());
3717 if(lua_pcall(L, 2, 1, 0))
3718 script_error(L, "error: %s", lua_tostring(L, -1));
3720 /*lua_pushvalue(L, 1);
3721 lua_pushstring(L, "__builtin:item");
3722 lua_pushstring(L, item.getItemString().c_str());
3723 return l_add_entity(L);*/
3725 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3726 int objectid = env->addActiveObject(obj);
3727 // If failed to add, return nothing (reads as nil)
3731 objectref_get_or_create(L, obj);
3735 // EnvRef:add_rat(pos)
3736 // pos = {x=num, y=num, z=num}
3737 static int l_add_rat(lua_State *L)
3739 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3740 <<" Doing nothing."<<std::endl;
3744 // EnvRef:add_firefly(pos)
3745 // pos = {x=num, y=num, z=num}
3746 static int l_add_firefly(lua_State *L)
3748 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3749 <<" Doing nothing."<<std::endl;
3753 // EnvRef:get_player_by_name(name)
3754 static int l_get_player_by_name(lua_State *L)
3756 EnvRef *o = checkobject(L, 1);
3757 ServerEnvironment *env = o->m_env;
3758 if(env == NULL) return 0;
3760 const char *name = luaL_checkstring(L, 2);
3761 Player *player = env->getPlayer(name);
3766 PlayerSAO *sao = player->getPlayerSAO();
3771 // Put player on stack
3772 objectref_get_or_create(L, sao);
3776 // EnvRef:get_objects_inside_radius(pos, radius)
3777 static int l_get_objects_inside_radius(lua_State *L)
3779 // Get the table insert function
3780 lua_getglobal(L, "table");
3781 lua_getfield(L, -1, "insert");
3782 int table_insert = lua_gettop(L);
3784 EnvRef *o = checkobject(L, 1);
3785 ServerEnvironment *env = o->m_env;
3786 if(env == NULL) return 0;
3788 v3f pos = checkFloatPos(L, 2);
3789 float radius = luaL_checknumber(L, 3) * BS;
3790 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3792 int table = lua_gettop(L);
3793 for(std::set<u16>::const_iterator
3794 i = ids.begin(); i != ids.end(); i++){
3795 ServerActiveObject *obj = env->getActiveObject(*i);
3796 // Insert object reference into table
3797 lua_pushvalue(L, table_insert);
3798 lua_pushvalue(L, table);
3799 objectref_get_or_create(L, obj);
3800 if(lua_pcall(L, 2, 0, 0))
3801 script_error(L, "error: %s", lua_tostring(L, -1));
3806 // EnvRef:set_timeofday(val)
3808 static int l_set_timeofday(lua_State *L)
3810 EnvRef *o = checkobject(L, 1);
3811 ServerEnvironment *env = o->m_env;
3812 if(env == NULL) return 0;
3814 float timeofday_f = luaL_checknumber(L, 2);
3815 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3816 int timeofday_mh = (int)(timeofday_f * 24000.0);
3817 // This should be set directly in the environment but currently
3818 // such changes aren't immediately sent to the clients, so call
3819 // the server instead.
3820 //env->setTimeOfDay(timeofday_mh);
3821 get_server(L)->setTimeOfDay(timeofday_mh);
3825 // EnvRef:get_timeofday() -> 0...1
3826 static int l_get_timeofday(lua_State *L)
3828 EnvRef *o = checkobject(L, 1);
3829 ServerEnvironment *env = o->m_env;
3830 if(env == NULL) return 0;
3832 int timeofday_mh = env->getTimeOfDay();
3833 float timeofday_f = (float)timeofday_mh / 24000.0;
3834 lua_pushnumber(L, timeofday_f);
3839 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3840 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3841 static int l_find_node_near(lua_State *L)
3843 EnvRef *o = checkobject(L, 1);
3844 ServerEnvironment *env = o->m_env;
3845 if(env == NULL) return 0;
3846 INodeDefManager *ndef = get_server(L)->ndef();
3847 v3s16 pos = read_v3s16(L, 2);
3848 int radius = luaL_checkinteger(L, 3);
3849 std::set<content_t> filter;
3850 if(lua_istable(L, 4)){
3853 while(lua_next(L, table) != 0){
3854 // key at index -2 and value at index -1
3855 luaL_checktype(L, -1, LUA_TSTRING);
3856 ndef->getIds(lua_tostring(L, -1), filter);
3857 // removes value, keeps key for next iteration
3860 } else if(lua_isstring(L, 4)){
3861 ndef->getIds(lua_tostring(L, 4), filter);
3864 for(int d=1; d<=radius; d++){
3865 core::list<v3s16> list;
3866 getFacePositions(list, d);
3867 for(core::list<v3s16>::Iterator i = list.begin();
3868 i != list.end(); i++){
3869 v3s16 p = pos + (*i);
3870 content_t c = env->getMap().getNodeNoEx(p).getContent();
3871 if(filter.count(c) != 0){
3880 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3881 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3882 static int l_find_nodes_in_area(lua_State *L)
3884 EnvRef *o = checkobject(L, 1);
3885 ServerEnvironment *env = o->m_env;
3886 if(env == NULL) return 0;
3887 INodeDefManager *ndef = get_server(L)->ndef();
3888 v3s16 minp = read_v3s16(L, 2);
3889 v3s16 maxp = read_v3s16(L, 3);
3890 std::set<content_t> filter;
3891 if(lua_istable(L, 4)){
3894 while(lua_next(L, table) != 0){
3895 // key at index -2 and value at index -1
3896 luaL_checktype(L, -1, LUA_TSTRING);
3897 ndef->getIds(lua_tostring(L, -1), filter);
3898 // removes value, keeps key for next iteration
3901 } else if(lua_isstring(L, 4)){
3902 ndef->getIds(lua_tostring(L, 4), filter);
3905 // Get the table insert function
3906 lua_getglobal(L, "table");
3907 lua_getfield(L, -1, "insert");
3908 int table_insert = lua_gettop(L);
3911 int table = lua_gettop(L);
3912 for(s16 x=minp.X; x<=maxp.X; x++)
3913 for(s16 y=minp.Y; y<=maxp.Y; y++)
3914 for(s16 z=minp.Z; z<=maxp.Z; z++)
3917 content_t c = env->getMap().getNodeNoEx(p).getContent();
3918 if(filter.count(c) != 0){
3919 lua_pushvalue(L, table_insert);
3920 lua_pushvalue(L, table);
3922 if(lua_pcall(L, 2, 0, 0))
3923 script_error(L, "error: %s", lua_tostring(L, -1));
3929 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3930 // returns world-specific PerlinNoise
3931 static int l_get_perlin(lua_State *L)
3933 EnvRef *o = checkobject(L, 1);
3934 ServerEnvironment *env = o->m_env;
3935 if(env == NULL) return 0;
3937 int seeddiff = luaL_checkint(L, 2);
3938 int octaves = luaL_checkint(L, 3);
3939 double persistence = luaL_checknumber(L, 4);
3940 double scale = luaL_checknumber(L, 5);
3942 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3943 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3944 luaL_getmetatable(L, "PerlinNoise");
3945 lua_setmetatable(L, -2);
3949 // EnvRef:clear_objects()
3950 // clear all objects in the environment
3951 static int l_clear_objects(lua_State *L)
3953 EnvRef *o = checkobject(L, 1);
3954 o->m_env->clearAllObjects();
3959 EnvRef(ServerEnvironment *env):
3962 //infostream<<"EnvRef created"<<std::endl;
3967 //infostream<<"EnvRef destructing"<<std::endl;
3970 // Creates an EnvRef and leaves it on top of stack
3971 // Not callable from Lua; all references are created on the C side.
3972 static void create(lua_State *L, ServerEnvironment *env)
3974 EnvRef *o = new EnvRef(env);
3975 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3976 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3977 luaL_getmetatable(L, className);
3978 lua_setmetatable(L, -2);
3981 static void set_null(lua_State *L)
3983 EnvRef *o = checkobject(L, -1);
3987 static void Register(lua_State *L)
3990 int methodtable = lua_gettop(L);
3991 luaL_newmetatable(L, className);
3992 int metatable = lua_gettop(L);
3994 lua_pushliteral(L, "__metatable");
3995 lua_pushvalue(L, methodtable);
3996 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3998 lua_pushliteral(L, "__index");
3999 lua_pushvalue(L, methodtable);
4000 lua_settable(L, metatable);
4002 lua_pushliteral(L, "__gc");
4003 lua_pushcfunction(L, gc_object);
4004 lua_settable(L, metatable);
4006 lua_pop(L, 1); // drop metatable
4008 luaL_openlib(L, 0, methods, 0); // fill methodtable
4009 lua_pop(L, 1); // drop methodtable
4011 // Cannot be created from Lua
4012 //lua_register(L, className, create_object);
4015 const char EnvRef::className[] = "EnvRef";
4016 const luaL_reg EnvRef::methods[] = {
4017 method(EnvRef, set_node),
4018 method(EnvRef, add_node),
4019 method(EnvRef, remove_node),
4020 method(EnvRef, get_node),
4021 method(EnvRef, get_node_or_nil),
4022 method(EnvRef, get_node_light),
4023 method(EnvRef, place_node),
4024 method(EnvRef, dig_node),
4025 method(EnvRef, punch_node),
4026 method(EnvRef, add_entity),
4027 method(EnvRef, add_item),
4028 method(EnvRef, add_rat),
4029 method(EnvRef, add_firefly),
4030 method(EnvRef, get_meta),
4031 method(EnvRef, get_node_timer),
4032 method(EnvRef, get_player_by_name),
4033 method(EnvRef, get_objects_inside_radius),
4034 method(EnvRef, set_timeofday),
4035 method(EnvRef, get_timeofday),
4036 method(EnvRef, find_node_near),
4037 method(EnvRef, find_nodes_in_area),
4038 method(EnvRef, get_perlin),
4039 method(EnvRef, clear_objects),
4048 class LuaPseudoRandom
4051 PseudoRandom m_pseudo;
4053 static const char className[];
4054 static const luaL_reg methods[];
4056 // Exported functions
4058 // garbage collector
4059 static int gc_object(lua_State *L)
4061 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4066 // next(self, min=0, max=32767) -> get next value
4067 static int l_next(lua_State *L)
4069 LuaPseudoRandom *o = checkobject(L, 1);
4072 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4073 if(!lua_isnil(L, 2))
4074 min = luaL_checkinteger(L, 2);
4075 if(!lua_isnil(L, 3))
4076 max = luaL_checkinteger(L, 3);
4078 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4079 throw LuaError(L, "PseudoRandom.next(): max < min");
4081 if(max - min != 32767 && max - min > 32767/5)
4082 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.");
4083 PseudoRandom &pseudo = o->m_pseudo;
4084 int val = pseudo.next();
4085 val = (val % (max-min+1)) + min;
4086 lua_pushinteger(L, val);
4091 LuaPseudoRandom(int seed):
4100 const PseudoRandom& getItem() const
4104 PseudoRandom& getItem()
4109 // LuaPseudoRandom(seed)
4110 // Creates an LuaPseudoRandom and leaves it on top of stack
4111 static int create_object(lua_State *L)
4113 int seed = luaL_checknumber(L, 1);
4114 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4115 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4116 luaL_getmetatable(L, className);
4117 lua_setmetatable(L, -2);
4121 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4123 luaL_checktype(L, narg, LUA_TUSERDATA);
4124 void *ud = luaL_checkudata(L, narg, className);
4125 if(!ud) luaL_typerror(L, narg, className);
4126 return *(LuaPseudoRandom**)ud; // unbox pointer
4129 static void Register(lua_State *L)
4132 int methodtable = lua_gettop(L);
4133 luaL_newmetatable(L, className);
4134 int metatable = lua_gettop(L);
4136 lua_pushliteral(L, "__metatable");
4137 lua_pushvalue(L, methodtable);
4138 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4140 lua_pushliteral(L, "__index");
4141 lua_pushvalue(L, methodtable);
4142 lua_settable(L, metatable);
4144 lua_pushliteral(L, "__gc");
4145 lua_pushcfunction(L, gc_object);
4146 lua_settable(L, metatable);
4148 lua_pop(L, 1); // drop metatable
4150 luaL_openlib(L, 0, methods, 0); // fill methodtable
4151 lua_pop(L, 1); // drop methodtable
4153 // Can be created from Lua (LuaPseudoRandom(seed))
4154 lua_register(L, className, create_object);
4157 const char LuaPseudoRandom::className[] = "PseudoRandom";
4158 const luaL_reg LuaPseudoRandom::methods[] = {
4159 method(LuaPseudoRandom, next),
4169 class LuaABM : public ActiveBlockModifier
4175 std::set<std::string> m_trigger_contents;
4176 std::set<std::string> m_required_neighbors;
4177 float m_trigger_interval;
4178 u32 m_trigger_chance;
4180 LuaABM(lua_State *L, int id,
4181 const std::set<std::string> &trigger_contents,
4182 const std::set<std::string> &required_neighbors,
4183 float trigger_interval, u32 trigger_chance):
4186 m_trigger_contents(trigger_contents),
4187 m_required_neighbors(required_neighbors),
4188 m_trigger_interval(trigger_interval),
4189 m_trigger_chance(trigger_chance)
4192 virtual std::set<std::string> getTriggerContents()
4194 return m_trigger_contents;
4196 virtual std::set<std::string> getRequiredNeighbors()
4198 return m_required_neighbors;
4200 virtual float getTriggerInterval()
4202 return m_trigger_interval;
4204 virtual u32 getTriggerChance()
4206 return m_trigger_chance;
4208 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4209 u32 active_object_count, u32 active_object_count_wider)
4211 lua_State *L = m_lua;
4214 assert(lua_checkstack(L, 20));
4215 StackUnroller stack_unroller(L);
4217 // Get minetest.registered_abms
4218 lua_getglobal(L, "minetest");
4219 lua_getfield(L, -1, "registered_abms");
4220 luaL_checktype(L, -1, LUA_TTABLE);
4221 int registered_abms = lua_gettop(L);
4223 // Get minetest.registered_abms[m_id]
4224 lua_pushnumber(L, m_id);
4225 lua_gettable(L, registered_abms);
4226 if(lua_isnil(L, -1))
4230 luaL_checktype(L, -1, LUA_TTABLE);
4231 lua_getfield(L, -1, "action");
4232 luaL_checktype(L, -1, LUA_TFUNCTION);
4234 pushnode(L, n, env->getGameDef()->ndef());
4235 lua_pushnumber(L, active_object_count);
4236 lua_pushnumber(L, active_object_count_wider);
4237 if(lua_pcall(L, 4, 0, 0))
4238 script_error(L, "error: %s", lua_tostring(L, -1));
4246 static void read_server_sound_params(lua_State *L, int index,
4247 ServerSoundParams ¶ms)
4250 index = lua_gettop(L) + 1 + index;
4252 params = ServerSoundParams();
4253 if(lua_istable(L, index)){
4254 getfloatfield(L, index, "gain", params.gain);
4255 getstringfield(L, index, "to_player", params.to_player);
4256 lua_getfield(L, index, "pos");
4257 if(!lua_isnil(L, -1)){
4258 v3f p = read_v3f(L, -1)*BS;
4260 params.type = ServerSoundParams::SSP_POSITIONAL;
4263 lua_getfield(L, index, "object");
4264 if(!lua_isnil(L, -1)){
4265 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4266 ServerActiveObject *sao = ObjectRef::getobject(ref);
4268 params.object = sao->getId();
4269 params.type = ServerSoundParams::SSP_OBJECT;
4273 params.max_hear_distance = BS*getfloatfield_default(L, index,
4274 "max_hear_distance", params.max_hear_distance/BS);
4275 getboolfield(L, index, "loop", params.loop);
4284 // Writes a line to dstream
4285 static int l_debug(lua_State *L)
4287 std::string text = lua_tostring(L, 1);
4288 dstream << text << std::endl;
4292 // log([level,] text)
4293 // Writes a line to the logger.
4294 // The one-argument version logs to infostream.
4295 // The two-argument version accept a log level: error, action, info, or verbose.
4296 static int l_log(lua_State *L)
4299 LogMessageLevel level = LMT_INFO;
4300 if(lua_isnone(L, 2))
4302 text = lua_tostring(L, 1);
4306 std::string levelname = lua_tostring(L, 1);
4307 text = lua_tostring(L, 2);
4308 if(levelname == "error")
4310 else if(levelname == "action")
4312 else if(levelname == "verbose")
4313 level = LMT_VERBOSE;
4315 log_printline(level, text);
4319 // request_shutdown()
4320 static int l_request_shutdown(lua_State *L)
4322 get_server(L)->requestShutdown();
4326 // get_server_status()
4327 static int l_get_server_status(lua_State *L)
4329 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4333 // register_item_raw({lots of stuff})
4334 static int l_register_item_raw(lua_State *L)
4336 luaL_checktype(L, 1, LUA_TTABLE);
4339 // Get the writable item and node definition managers from the server
4340 IWritableItemDefManager *idef =
4341 get_server(L)->getWritableItemDefManager();
4342 IWritableNodeDefManager *ndef =
4343 get_server(L)->getWritableNodeDefManager();
4345 // Check if name is defined
4347 lua_getfield(L, table, "name");
4348 if(lua_isstring(L, -1)){
4349 name = lua_tostring(L, -1);
4350 verbosestream<<"register_item_raw: "<<name<<std::endl;
4352 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4355 // Check if on_use is defined
4358 // Set a distinctive default value to check if this is set
4359 def.node_placement_prediction = "__default";
4361 // Read the item definition
4362 def = read_item_definition(L, table, def);
4364 // Default to having client-side placement prediction for nodes
4365 // ("" in item definition sets it off)
4366 if(def.node_placement_prediction == "__default"){
4367 if(def.type == ITEM_NODE)
4368 def.node_placement_prediction = name;
4370 def.node_placement_prediction = "";
4373 // Register item definition
4374 idef->registerItem(def);
4376 // Read the node definition (content features) and register it
4377 if(def.type == ITEM_NODE)
4379 ContentFeatures f = read_content_features(L, table);
4380 ndef->set(f.name, f);
4383 return 0; /* number of results */
4386 // register_alias_raw(name, convert_to_name)
4387 static int l_register_alias_raw(lua_State *L)
4389 std::string name = luaL_checkstring(L, 1);
4390 std::string convert_to = luaL_checkstring(L, 2);
4392 // Get the writable item definition manager from the server
4393 IWritableItemDefManager *idef =
4394 get_server(L)->getWritableItemDefManager();
4396 idef->registerAlias(name, convert_to);
4398 return 0; /* number of results */
4401 // helper for register_craft
4402 static bool read_craft_recipe_shaped(lua_State *L, int index,
4403 int &width, std::vector<std::string> &recipe)
4406 index = lua_gettop(L) + 1 + index;
4408 if(!lua_istable(L, index))
4413 while(lua_next(L, index) != 0){
4415 // key at index -2 and value at index -1
4416 if(!lua_istable(L, -1))
4418 int table2 = lua_gettop(L);
4420 while(lua_next(L, table2) != 0){
4421 // key at index -2 and value at index -1
4422 if(!lua_isstring(L, -1))
4424 recipe.push_back(lua_tostring(L, -1));
4425 // removes value, keeps key for next iteration
4432 if(colcount != width)
4435 // removes value, keeps key for next iteration
4442 // helper for register_craft
4443 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4444 std::vector<std::string> &recipe)
4447 index = lua_gettop(L) + 1 + index;
4449 if(!lua_istable(L, index))
4453 while(lua_next(L, index) != 0){
4454 // key at index -2 and value at index -1
4455 if(!lua_isstring(L, -1))
4457 recipe.push_back(lua_tostring(L, -1));
4458 // removes value, keeps key for next iteration
4464 // helper for register_craft
4465 static bool read_craft_replacements(lua_State *L, int index,
4466 CraftReplacements &replacements)
4469 index = lua_gettop(L) + 1 + index;
4471 if(!lua_istable(L, index))
4475 while(lua_next(L, index) != 0){
4476 // key at index -2 and value at index -1
4477 if(!lua_istable(L, -1))
4479 lua_rawgeti(L, -1, 1);
4480 if(!lua_isstring(L, -1))
4482 std::string replace_from = lua_tostring(L, -1);
4484 lua_rawgeti(L, -1, 2);
4485 if(!lua_isstring(L, -1))
4487 std::string replace_to = lua_tostring(L, -1);
4489 replacements.pairs.push_back(
4490 std::make_pair(replace_from, replace_to));
4491 // removes value, keeps key for next iteration
4496 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4497 static int l_register_craft(lua_State *L)
4499 //infostream<<"register_craft"<<std::endl;
4500 luaL_checktype(L, 1, LUA_TTABLE);
4503 // Get the writable craft definition manager from the server
4504 IWritableCraftDefManager *craftdef =
4505 get_server(L)->getWritableCraftDefManager();
4507 std::string type = getstringfield_default(L, table, "type", "shaped");
4510 CraftDefinitionShaped
4512 if(type == "shaped"){
4513 std::string output = getstringfield_default(L, table, "output", "");
4515 throw LuaError(L, "Crafting definition is missing an output");
4518 std::vector<std::string> recipe;
4519 lua_getfield(L, table, "recipe");
4520 if(lua_isnil(L, -1))
4521 throw LuaError(L, "Crafting definition is missing a recipe"
4522 " (output=\"" + output + "\")");
4523 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4524 throw LuaError(L, "Invalid crafting recipe"
4525 " (output=\"" + output + "\")");
4527 CraftReplacements replacements;
4528 lua_getfield(L, table, "replacements");
4529 if(!lua_isnil(L, -1))
4531 if(!read_craft_replacements(L, -1, replacements))
4532 throw LuaError(L, "Invalid replacements"
4533 " (output=\"" + output + "\")");
4536 CraftDefinition *def = new CraftDefinitionShaped(
4537 output, width, recipe, replacements);
4538 craftdef->registerCraft(def);
4541 CraftDefinitionShapeless
4543 else if(type == "shapeless"){
4544 std::string output = getstringfield_default(L, table, "output", "");
4546 throw LuaError(L, "Crafting definition (shapeless)"
4547 " is missing an output");
4549 std::vector<std::string> recipe;
4550 lua_getfield(L, table, "recipe");
4551 if(lua_isnil(L, -1))
4552 throw LuaError(L, "Crafting definition (shapeless)"
4553 " is missing a recipe"
4554 " (output=\"" + output + "\")");
4555 if(!read_craft_recipe_shapeless(L, -1, recipe))
4556 throw LuaError(L, "Invalid crafting recipe"
4557 " (output=\"" + output + "\")");
4559 CraftReplacements replacements;
4560 lua_getfield(L, table, "replacements");
4561 if(!lua_isnil(L, -1))
4563 if(!read_craft_replacements(L, -1, replacements))
4564 throw LuaError(L, "Invalid replacements"
4565 " (output=\"" + output + "\")");
4568 CraftDefinition *def = new CraftDefinitionShapeless(
4569 output, recipe, replacements);
4570 craftdef->registerCraft(def);
4573 CraftDefinitionToolRepair
4575 else if(type == "toolrepair"){
4576 float additional_wear = getfloatfield_default(L, table,
4577 "additional_wear", 0.0);
4579 CraftDefinition *def = new CraftDefinitionToolRepair(
4581 craftdef->registerCraft(def);
4584 CraftDefinitionCooking
4586 else if(type == "cooking"){
4587 std::string output = getstringfield_default(L, table, "output", "");
4589 throw LuaError(L, "Crafting definition (cooking)"
4590 " is missing an output");
4592 std::string recipe = getstringfield_default(L, table, "recipe", "");
4594 throw LuaError(L, "Crafting definition (cooking)"
4595 " is missing a recipe"
4596 " (output=\"" + output + "\")");
4598 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4600 CraftReplacements replacements;
4601 lua_getfield(L, table, "replacements");
4602 if(!lua_isnil(L, -1))
4604 if(!read_craft_replacements(L, -1, replacements))
4605 throw LuaError(L, "Invalid replacements"
4606 " (cooking output=\"" + output + "\")");
4609 CraftDefinition *def = new CraftDefinitionCooking(
4610 output, recipe, cooktime, replacements);
4611 craftdef->registerCraft(def);
4616 else if(type == "fuel"){
4617 std::string recipe = getstringfield_default(L, table, "recipe", "");
4619 throw LuaError(L, "Crafting definition (fuel)"
4620 " is missing a recipe");
4622 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4624 CraftReplacements replacements;
4625 lua_getfield(L, table, "replacements");
4626 if(!lua_isnil(L, -1))
4628 if(!read_craft_replacements(L, -1, replacements))
4629 throw LuaError(L, "Invalid replacements"
4630 " (fuel recipe=\"" + recipe + "\")");
4633 CraftDefinition *def = new CraftDefinitionFuel(
4634 recipe, burntime, replacements);
4635 craftdef->registerCraft(def);
4639 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4643 return 0; /* number of results */
4646 // setting_set(name, value)
4647 static int l_setting_set(lua_State *L)
4649 const char *name = luaL_checkstring(L, 1);
4650 const char *value = luaL_checkstring(L, 2);
4651 g_settings->set(name, value);
4655 // setting_get(name)
4656 static int l_setting_get(lua_State *L)
4658 const char *name = luaL_checkstring(L, 1);
4660 std::string value = g_settings->get(name);
4661 lua_pushstring(L, value.c_str());
4662 } catch(SettingNotFoundException &e){
4668 // setting_getbool(name)
4669 static int l_setting_getbool(lua_State *L)
4671 const char *name = luaL_checkstring(L, 1);
4673 bool value = g_settings->getBool(name);
4674 lua_pushboolean(L, value);
4675 } catch(SettingNotFoundException &e){
4681 // chat_send_all(text)
4682 static int l_chat_send_all(lua_State *L)
4684 const char *text = luaL_checkstring(L, 1);
4685 // Get server from registry
4686 Server *server = get_server(L);
4688 server->notifyPlayers(narrow_to_wide(text));
4692 // chat_send_player(name, text)
4693 static int l_chat_send_player(lua_State *L)
4695 const char *name = luaL_checkstring(L, 1);
4696 const char *text = luaL_checkstring(L, 2);
4697 // Get server from registry
4698 Server *server = get_server(L);
4700 server->notifyPlayer(name, narrow_to_wide(text));
4704 // get_player_privs(name, text)
4705 static int l_get_player_privs(lua_State *L)
4707 const char *name = luaL_checkstring(L, 1);
4708 // Get server from registry
4709 Server *server = get_server(L);
4712 int table = lua_gettop(L);
4713 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4714 for(std::set<std::string>::const_iterator
4715 i = privs_s.begin(); i != privs_s.end(); i++){
4716 lua_pushboolean(L, true);
4717 lua_setfield(L, table, i->c_str());
4719 lua_pushvalue(L, table);
4724 static int l_get_ban_list(lua_State *L)
4726 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4730 // get_ban_description()
4731 static int l_get_ban_description(lua_State *L)
4733 const char * ip_or_name = luaL_checkstring(L, 1);
4734 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4739 static int l_ban_player(lua_State *L)
4741 const char * name = luaL_checkstring(L, 1);
4742 Player *player = get_env(L)->getPlayer(name);
4745 lua_pushboolean(L, false); // no such player
4750 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4751 std::string ip_str = addr.serializeString();
4752 get_server(L)->setIpBanned(ip_str, name);
4754 catch(con::PeerNotFoundException) // unlikely
4756 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4757 lua_pushboolean(L, false); // error
4760 lua_pushboolean(L, true);
4764 // unban_player_or_ip()
4765 static int l_unban_player_of_ip(lua_State *L)
4767 const char * ip_or_name = luaL_checkstring(L, 1);
4768 get_server(L)->unsetIpBanned(ip_or_name);
4769 lua_pushboolean(L, true);
4773 // get_inventory(location)
4774 static int l_get_inventory(lua_State *L)
4776 InventoryLocation loc;
4778 std::string type = checkstringfield(L, 1, "type");
4779 if(type == "player"){
4780 std::string name = checkstringfield(L, 1, "name");
4781 loc.setPlayer(name);
4782 } else if(type == "node"){
4783 lua_getfield(L, 1, "pos");
4784 v3s16 pos = check_v3s16(L, -1);
4785 loc.setNodeMeta(pos);
4786 } else if(type == "detached"){
4787 std::string name = checkstringfield(L, 1, "name");
4788 loc.setDetached(name);
4791 if(get_server(L)->getInventory(loc) != NULL)
4792 InvRef::create(L, loc);
4798 // create_detached_inventory_raw(name)
4799 static int l_create_detached_inventory_raw(lua_State *L)
4801 const char *name = luaL_checkstring(L, 1);
4802 if(get_server(L)->createDetachedInventory(name) != NULL){
4803 InventoryLocation loc;
4804 loc.setDetached(name);
4805 InvRef::create(L, loc);
4812 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4813 static int l_get_dig_params(lua_State *L)
4815 std::map<std::string, int> groups;
4816 read_groups(L, 1, groups);
4817 ToolCapabilities tp = read_tool_capabilities(L, 2);
4818 if(lua_isnoneornil(L, 3))
4819 push_dig_params(L, getDigParams(groups, &tp));
4821 push_dig_params(L, getDigParams(groups, &tp,
4822 luaL_checknumber(L, 3)));
4826 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4827 static int l_get_hit_params(lua_State *L)
4829 std::map<std::string, int> groups;
4830 read_groups(L, 1, groups);
4831 ToolCapabilities tp = read_tool_capabilities(L, 2);
4832 if(lua_isnoneornil(L, 3))
4833 push_hit_params(L, getHitParams(groups, &tp));
4835 push_hit_params(L, getHitParams(groups, &tp,
4836 luaL_checknumber(L, 3)));
4840 // get_current_modname()
4841 static int l_get_current_modname(lua_State *L)
4843 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4847 // get_modpath(modname)
4848 static int l_get_modpath(lua_State *L)
4850 std::string modname = luaL_checkstring(L, 1);
4852 if(modname == "__builtin"){
4853 std::string path = get_server(L)->getBuiltinLuaPath();
4854 lua_pushstring(L, path.c_str());
4857 const ModSpec *mod = get_server(L)->getModSpec(modname);
4862 lua_pushstring(L, mod->path.c_str());
4867 // the returned list is sorted alphabetically for you
4868 static int l_get_modnames(lua_State *L)
4870 // Get a list of mods
4871 core::list<std::string> mods_unsorted, mods_sorted;
4872 get_server(L)->getModNames(mods_unsorted);
4874 // Take unsorted items from mods_unsorted and sort them into
4875 // mods_sorted; not great performance but the number of mods on a
4876 // server will likely be small.
4877 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
4878 i != mods_unsorted.end(); i++)
4881 for(core::list<std::string>::Iterator x = mods_sorted.begin();
4882 x != mods_unsorted.end(); x++)
4884 // I doubt anybody using Minetest will be using
4885 // anything not ASCII based :)
4886 if((*i).compare(*x) <= 0)
4888 mods_sorted.insert_before(x, *i);
4894 mods_sorted.push_back(*i);
4897 // Get the table insertion function from Lua.
4898 lua_getglobal(L, "table");
4899 lua_getfield(L, -1, "insert");
4900 int insertion_func = lua_gettop(L);
4902 // Package them up for Lua
4904 int new_table = lua_gettop(L);
4905 core::list<std::string>::Iterator i = mods_sorted.begin();
4906 while(i != mods_sorted.end())
4908 lua_pushvalue(L, insertion_func);
4909 lua_pushvalue(L, new_table);
4910 lua_pushstring(L, (*i).c_str());
4911 if(lua_pcall(L, 2, 0, 0) != 0)
4913 script_error(L, "error: %s", lua_tostring(L, -1));
4921 static int l_get_worldpath(lua_State *L)
4923 std::string worldpath = get_server(L)->getWorldPath();
4924 lua_pushstring(L, worldpath.c_str());
4928 // sound_play(spec, parameters)
4929 static int l_sound_play(lua_State *L)
4931 SimpleSoundSpec spec;
4932 read_soundspec(L, 1, spec);
4933 ServerSoundParams params;
4934 read_server_sound_params(L, 2, params);
4935 s32 handle = get_server(L)->playSound(spec, params);
4936 lua_pushinteger(L, handle);
4940 // sound_stop(handle)
4941 static int l_sound_stop(lua_State *L)
4943 int handle = luaL_checkinteger(L, 1);
4944 get_server(L)->stopSound(handle);
4948 // is_singleplayer()
4949 static int l_is_singleplayer(lua_State *L)
4951 lua_pushboolean(L, get_server(L)->isSingleplayer());
4955 // get_password_hash(name, raw_password)
4956 static int l_get_password_hash(lua_State *L)
4958 std::string name = luaL_checkstring(L, 1);
4959 std::string raw_password = luaL_checkstring(L, 2);
4960 std::string hash = translatePassword(name,
4961 narrow_to_wide(raw_password));
4962 lua_pushstring(L, hash.c_str());
4966 // notify_authentication_modified(name)
4967 static int l_notify_authentication_modified(lua_State *L)
4969 std::string name = "";
4970 if(lua_isstring(L, 1))
4971 name = lua_tostring(L, 1);
4972 get_server(L)->reportPrivsModified(name);
4976 // get_craft_result(input)
4977 static int l_get_craft_result(lua_State *L)
4980 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4981 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4982 es_CraftMethod, CRAFT_METHOD_NORMAL);
4984 lua_getfield(L, input_i, "width");
4985 if(lua_isnumber(L, -1))
4986 width = luaL_checkinteger(L, -1);
4988 lua_getfield(L, input_i, "items");
4989 std::vector<ItemStack> items = read_items(L, -1);
4990 lua_pop(L, 1); // items
4992 IGameDef *gdef = get_server(L);
4993 ICraftDefManager *cdef = gdef->cdef();
4994 CraftInput input(method, width, items);
4996 bool got = cdef->getCraftResult(input, output, true, gdef);
4997 lua_newtable(L); // output table
5000 item.deSerialize(output.item, gdef->idef());
5001 LuaItemStack::create(L, item);
5002 lua_setfield(L, -2, "item");
5003 setintfield(L, -1, "time", output.time);
5005 LuaItemStack::create(L, ItemStack());
5006 lua_setfield(L, -2, "item");
5007 setintfield(L, -1, "time", 0);
5009 lua_newtable(L); // decremented input table
5010 lua_pushstring(L, method_s.c_str());
5011 lua_setfield(L, -2, "method");
5012 lua_pushinteger(L, width);
5013 lua_setfield(L, -2, "width");
5014 push_items(L, input.items);
5015 lua_setfield(L, -2, "items");
5019 // get_craft_recipe(result item)
5020 static int l_get_craft_recipe(lua_State *L)
5025 std::string o_item = luaL_checkstring(L,input_i);
5027 IGameDef *gdef = get_server(L);
5028 ICraftDefManager *cdef = gdef->cdef();
5030 CraftOutput output(o_item,0);
5031 bool got = cdef->getCraftRecipe(input, output, gdef);
5032 lua_newtable(L); // output table
5035 for(std::vector<ItemStack>::const_iterator
5036 i = input.items.begin();
5037 i != input.items.end(); i++, k++)
5043 sprintf(tmp,"%d",k);
5044 lua_pushstring(L,tmp);
5045 lua_pushstring(L,i->name.c_str());
5046 lua_settable(L, -3);
5048 lua_setfield(L, -2, "items");
5049 setintfield(L, -1, "width", input.width);
5050 switch (input.method) {
5051 case CRAFT_METHOD_NORMAL:
5052 lua_pushstring(L,"normal");
5054 case CRAFT_METHOD_COOKING:
5055 lua_pushstring(L,"cooking");
5057 case CRAFT_METHOD_FUEL:
5058 lua_pushstring(L,"fuel");
5061 lua_pushstring(L,"unknown");
5063 lua_setfield(L, -2, "type");
5066 lua_setfield(L, -2, "items");
5067 setintfield(L, -1, "width", 0);
5072 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5073 static int l_rollback_get_last_node_actor(lua_State *L)
5075 v3s16 p = read_v3s16(L, 1);
5076 int range = luaL_checknumber(L, 2);
5077 int seconds = luaL_checknumber(L, 3);
5078 Server *server = get_server(L);
5079 IRollbackManager *rollback = server->getRollbackManager();
5081 int act_seconds = 0;
5082 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5083 lua_pushstring(L, actor.c_str());
5084 push_v3s16(L, act_p);
5085 lua_pushnumber(L, act_seconds);
5089 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5090 static int l_rollback_revert_actions_by(lua_State *L)
5092 std::string actor = luaL_checkstring(L, 1);
5093 int seconds = luaL_checknumber(L, 2);
5094 Server *server = get_server(L);
5095 IRollbackManager *rollback = server->getRollbackManager();
5096 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5097 std::list<std::string> log;
5098 bool success = server->rollbackRevertActions(actions, &log);
5099 // Push boolean result
5100 lua_pushboolean(L, success);
5101 // Get the table insert function and push the log table
5102 lua_getglobal(L, "table");
5103 lua_getfield(L, -1, "insert");
5104 int table_insert = lua_gettop(L);
5106 int table = lua_gettop(L);
5107 for(std::list<std::string>::const_iterator i = log.begin();
5108 i != log.end(); i++)
5110 lua_pushvalue(L, table_insert);
5111 lua_pushvalue(L, table);
5112 lua_pushstring(L, i->c_str());
5113 if(lua_pcall(L, 2, 0, 0))
5114 script_error(L, "error: %s", lua_tostring(L, -1));
5116 lua_remove(L, -2); // Remove table
5117 lua_remove(L, -2); // Remove insert
5121 static const struct luaL_Reg minetest_f [] = {
5124 {"request_shutdown", l_request_shutdown},
5125 {"get_server_status", l_get_server_status},
5126 {"register_item_raw", l_register_item_raw},
5127 {"register_alias_raw", l_register_alias_raw},
5128 {"register_craft", l_register_craft},
5129 {"setting_set", l_setting_set},
5130 {"setting_get", l_setting_get},
5131 {"setting_getbool", l_setting_getbool},
5132 {"chat_send_all", l_chat_send_all},
5133 {"chat_send_player", l_chat_send_player},
5134 {"get_player_privs", l_get_player_privs},
5135 {"get_ban_list", l_get_ban_list},
5136 {"get_ban_description", l_get_ban_description},
5137 {"ban_player", l_ban_player},
5138 {"unban_player_or_ip", l_unban_player_of_ip},
5139 {"get_inventory", l_get_inventory},
5140 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5141 {"get_dig_params", l_get_dig_params},
5142 {"get_hit_params", l_get_hit_params},
5143 {"get_current_modname", l_get_current_modname},
5144 {"get_modpath", l_get_modpath},
5145 {"get_modnames", l_get_modnames},
5146 {"get_worldpath", l_get_worldpath},
5147 {"sound_play", l_sound_play},
5148 {"sound_stop", l_sound_stop},
5149 {"is_singleplayer", l_is_singleplayer},
5150 {"get_password_hash", l_get_password_hash},
5151 {"notify_authentication_modified", l_notify_authentication_modified},
5152 {"get_craft_result", l_get_craft_result},
5153 {"get_craft_recipe", l_get_craft_recipe},
5154 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5155 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5160 Main export function
5163 void scriptapi_export(lua_State *L, Server *server)
5166 assert(lua_checkstack(L, 20));
5167 verbosestream<<"scriptapi_export()"<<std::endl;
5168 StackUnroller stack_unroller(L);
5170 // Store server as light userdata in registry
5171 lua_pushlightuserdata(L, server);
5172 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5174 // Register global functions in table minetest
5176 luaL_register(L, NULL, minetest_f);
5177 lua_setglobal(L, "minetest");
5179 // Get the main minetest table
5180 lua_getglobal(L, "minetest");
5182 // Add tables to minetest
5184 lua_setfield(L, -2, "object_refs");
5186 lua_setfield(L, -2, "luaentities");
5188 // Register wrappers
5189 LuaItemStack::Register(L);
5190 InvRef::Register(L);
5191 NodeMetaRef::Register(L);
5192 NodeTimerRef::Register(L);
5193 ObjectRef::Register(L);
5194 EnvRef::Register(L);
5195 LuaPseudoRandom::Register(L);
5196 LuaPerlinNoise::Register(L);
5199 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5200 const std::string &modname)
5202 ModNameStorer modnamestorer(L, modname);
5204 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5206 errorstream<<"Error loading mod \""<<modname
5207 <<"\": modname does not follow naming conventions: "
5208 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5212 bool success = false;
5215 success = script_load(L, scriptpath.c_str());
5218 errorstream<<"Error loading mod \""<<modname
5219 <<"\": "<<e.what()<<std::endl;
5225 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5228 assert(lua_checkstack(L, 20));
5229 verbosestream<<"scriptapi_add_environment"<<std::endl;
5230 StackUnroller stack_unroller(L);
5232 // Create EnvRef on stack
5233 EnvRef::create(L, env);
5234 int envref = lua_gettop(L);
5236 // minetest.env = envref
5237 lua_getglobal(L, "minetest");
5238 luaL_checktype(L, -1, LUA_TTABLE);
5239 lua_pushvalue(L, envref);
5240 lua_setfield(L, -2, "env");
5242 // Store environment as light userdata in registry
5243 lua_pushlightuserdata(L, env);
5244 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5247 Add ActiveBlockModifiers to environment
5250 // Get minetest.registered_abms
5251 lua_getglobal(L, "minetest");
5252 lua_getfield(L, -1, "registered_abms");
5253 luaL_checktype(L, -1, LUA_TTABLE);
5254 int registered_abms = lua_gettop(L);
5256 if(lua_istable(L, registered_abms)){
5257 int table = lua_gettop(L);
5259 while(lua_next(L, table) != 0){
5260 // key at index -2 and value at index -1
5261 int id = lua_tonumber(L, -2);
5262 int current_abm = lua_gettop(L);
5264 std::set<std::string> trigger_contents;
5265 lua_getfield(L, current_abm, "nodenames");
5266 if(lua_istable(L, -1)){
5267 int table = lua_gettop(L);
5269 while(lua_next(L, table) != 0){
5270 // key at index -2 and value at index -1
5271 luaL_checktype(L, -1, LUA_TSTRING);
5272 trigger_contents.insert(lua_tostring(L, -1));
5273 // removes value, keeps key for next iteration
5276 } else if(lua_isstring(L, -1)){
5277 trigger_contents.insert(lua_tostring(L, -1));
5281 std::set<std::string> required_neighbors;
5282 lua_getfield(L, current_abm, "neighbors");
5283 if(lua_istable(L, -1)){
5284 int table = lua_gettop(L);
5286 while(lua_next(L, table) != 0){
5287 // key at index -2 and value at index -1
5288 luaL_checktype(L, -1, LUA_TSTRING);
5289 required_neighbors.insert(lua_tostring(L, -1));
5290 // removes value, keeps key for next iteration
5293 } else if(lua_isstring(L, -1)){
5294 required_neighbors.insert(lua_tostring(L, -1));
5298 float trigger_interval = 10.0;
5299 getfloatfield(L, current_abm, "interval", trigger_interval);
5301 int trigger_chance = 50;
5302 getintfield(L, current_abm, "chance", trigger_chance);
5304 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5305 required_neighbors, trigger_interval, trigger_chance);
5307 env->addActiveBlockModifier(abm);
5309 // removes value, keeps key for next iteration
5317 // Dump stack top with the dump2 function
5318 static void dump2(lua_State *L, const char *name)
5320 // Dump object (debug)
5321 lua_getglobal(L, "dump2");
5322 luaL_checktype(L, -1, LUA_TFUNCTION);
5323 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5324 lua_pushstring(L, name);
5325 if(lua_pcall(L, 2, 0, 0))
5326 script_error(L, "error: %s", lua_tostring(L, -1));
5334 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5337 assert(lua_checkstack(L, 20));
5338 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5339 StackUnroller stack_unroller(L);
5341 // Create object on stack
5342 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5343 int object = lua_gettop(L);
5345 // Get minetest.object_refs table
5346 lua_getglobal(L, "minetest");
5347 lua_getfield(L, -1, "object_refs");
5348 luaL_checktype(L, -1, LUA_TTABLE);
5349 int objectstable = lua_gettop(L);
5351 // object_refs[id] = object
5352 lua_pushnumber(L, cobj->getId()); // Push id
5353 lua_pushvalue(L, object); // Copy object to top of stack
5354 lua_settable(L, objectstable);
5357 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5360 assert(lua_checkstack(L, 20));
5361 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5362 StackUnroller stack_unroller(L);
5364 // Get minetest.object_refs table
5365 lua_getglobal(L, "minetest");
5366 lua_getfield(L, -1, "object_refs");
5367 luaL_checktype(L, -1, LUA_TTABLE);
5368 int objectstable = lua_gettop(L);
5370 // Get object_refs[id]
5371 lua_pushnumber(L, cobj->getId()); // Push id
5372 lua_gettable(L, objectstable);
5373 // Set object reference to NULL
5374 ObjectRef::set_null(L);
5375 lua_pop(L, 1); // pop object
5377 // Set object_refs[id] = nil
5378 lua_pushnumber(L, cobj->getId()); // Push id
5380 lua_settable(L, objectstable);
5387 // What scriptapi_run_callbacks does with the return values of callbacks.
5388 // Regardless of the mode, if only one callback is defined,
5389 // its return value is the total return value.
5390 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5391 enum RunCallbacksMode
5393 // Returns the return value of the first callback
5394 // Returns nil if list of callbacks is empty
5395 RUN_CALLBACKS_MODE_FIRST,
5396 // Returns the return value of the last callback
5397 // Returns nil if list of callbacks is empty
5398 RUN_CALLBACKS_MODE_LAST,
5399 // If any callback returns a false value, the first such is returned
5400 // Otherwise, the first callback's return value (trueish) is returned
5401 // Returns true if list of callbacks is empty
5402 RUN_CALLBACKS_MODE_AND,
5403 // Like above, but stops calling callbacks (short circuit)
5404 // after seeing the first false value
5405 RUN_CALLBACKS_MODE_AND_SC,
5406 // If any callback returns a true value, the first such is returned
5407 // Otherwise, the first callback's return value (falseish) is returned
5408 // Returns false if list of callbacks is empty
5409 RUN_CALLBACKS_MODE_OR,
5410 // Like above, but stops calling callbacks (short circuit)
5411 // after seeing the first true value
5412 RUN_CALLBACKS_MODE_OR_SC,
5413 // Note: "a true value" and "a false value" refer to values that
5414 // are converted by lua_toboolean to true or false, respectively.
5417 // Push the list of callbacks (a lua table).
5418 // Then push nargs arguments.
5419 // Then call this function, which
5420 // - runs the callbacks
5421 // - removes the table and arguments from the lua stack
5422 // - pushes the return value, computed depending on mode
5423 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5424 RunCallbacksMode mode)
5426 // Insert the return value into the lua stack, below the table
5427 assert(lua_gettop(L) >= nargs + 1);
5429 lua_insert(L, -(nargs + 1) - 1);
5430 // Stack now looks like this:
5431 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5433 int rv = lua_gettop(L) - nargs - 1;
5435 int arg = table + 1;
5437 luaL_checktype(L, table, LUA_TTABLE);
5441 bool first_loop = true;
5442 while(lua_next(L, table) != 0){
5443 // key at index -2 and value at index -1
5444 luaL_checktype(L, -1, LUA_TFUNCTION);
5446 for(int i = 0; i < nargs; i++)
5447 lua_pushvalue(L, arg+i);
5448 if(lua_pcall(L, nargs, 1, 0))
5449 script_error(L, "error: %s", lua_tostring(L, -1));
5451 // Move return value to designated space in stack
5454 // Result of first callback is always moved
5458 // Otherwise, what happens depends on the mode
5459 if(mode == RUN_CALLBACKS_MODE_FIRST)
5461 else if(mode == RUN_CALLBACKS_MODE_LAST)
5463 else if(mode == RUN_CALLBACKS_MODE_AND ||
5464 mode == RUN_CALLBACKS_MODE_AND_SC){
5465 if(lua_toboolean(L, rv) == true &&
5466 lua_toboolean(L, -1) == false)
5471 else if(mode == RUN_CALLBACKS_MODE_OR ||
5472 mode == RUN_CALLBACKS_MODE_OR_SC){
5473 if(lua_toboolean(L, rv) == false &&
5474 lua_toboolean(L, -1) == true)
5483 // Handle short circuit modes
5484 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5485 lua_toboolean(L, rv) == false)
5487 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5488 lua_toboolean(L, rv) == true)
5491 // value removed, keep key for next iteration
5494 // Remove stuff from stack, leaving only the return value
5497 // Fix return value in case no callbacks were called
5499 if(mode == RUN_CALLBACKS_MODE_AND ||
5500 mode == RUN_CALLBACKS_MODE_AND_SC){
5502 lua_pushboolean(L, true);
5504 else if(mode == RUN_CALLBACKS_MODE_OR ||
5505 mode == RUN_CALLBACKS_MODE_OR_SC){
5507 lua_pushboolean(L, false);
5512 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5513 const std::string &message)
5516 assert(lua_checkstack(L, 20));
5517 StackUnroller stack_unroller(L);
5519 // Get minetest.registered_on_chat_messages
5520 lua_getglobal(L, "minetest");
5521 lua_getfield(L, -1, "registered_on_chat_messages");
5523 lua_pushstring(L, name.c_str());
5524 lua_pushstring(L, message.c_str());
5525 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5526 bool ate = lua_toboolean(L, -1);
5530 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5533 assert(lua_checkstack(L, 20));
5534 StackUnroller stack_unroller(L);
5536 // Get minetest.registered_on_newplayers
5537 lua_getglobal(L, "minetest");
5538 lua_getfield(L, -1, "registered_on_newplayers");
5540 objectref_get_or_create(L, player);
5541 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5544 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5547 assert(lua_checkstack(L, 20));
5548 StackUnroller stack_unroller(L);
5550 // Get minetest.registered_on_dieplayers
5551 lua_getglobal(L, "minetest");
5552 lua_getfield(L, -1, "registered_on_dieplayers");
5554 objectref_get_or_create(L, player);
5555 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5558 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5561 assert(lua_checkstack(L, 20));
5562 StackUnroller stack_unroller(L);
5564 // Get minetest.registered_on_respawnplayers
5565 lua_getglobal(L, "minetest");
5566 lua_getfield(L, -1, "registered_on_respawnplayers");
5568 objectref_get_or_create(L, player);
5569 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5570 bool positioning_handled_by_some = lua_toboolean(L, -1);
5571 return positioning_handled_by_some;
5574 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5577 assert(lua_checkstack(L, 20));
5578 StackUnroller stack_unroller(L);
5580 // Get minetest.registered_on_joinplayers
5581 lua_getglobal(L, "minetest");
5582 lua_getfield(L, -1, "registered_on_joinplayers");
5584 objectref_get_or_create(L, player);
5585 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5588 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5591 assert(lua_checkstack(L, 20));
5592 StackUnroller stack_unroller(L);
5594 // Get minetest.registered_on_leaveplayers
5595 lua_getglobal(L, "minetest");
5596 lua_getfield(L, -1, "registered_on_leaveplayers");
5598 objectref_get_or_create(L, player);
5599 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5602 static void get_auth_handler(lua_State *L)
5604 lua_getglobal(L, "minetest");
5605 lua_getfield(L, -1, "registered_auth_handler");
5606 if(lua_isnil(L, -1)){
5608 lua_getfield(L, -1, "builtin_auth_handler");
5610 if(lua_type(L, -1) != LUA_TTABLE)
5611 throw LuaError(L, "Authentication handler table not valid");
5614 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5615 std::string *dst_password, std::set<std::string> *dst_privs)
5618 assert(lua_checkstack(L, 20));
5619 StackUnroller stack_unroller(L);
5621 get_auth_handler(L);
5622 lua_getfield(L, -1, "get_auth");
5623 if(lua_type(L, -1) != LUA_TFUNCTION)
5624 throw LuaError(L, "Authentication handler missing get_auth");
5625 lua_pushstring(L, playername.c_str());
5626 if(lua_pcall(L, 1, 1, 0))
5627 script_error(L, "error: %s", lua_tostring(L, -1));
5629 // nil = login not allowed
5630 if(lua_isnil(L, -1))
5632 luaL_checktype(L, -1, LUA_TTABLE);
5634 std::string password;
5635 bool found = getstringfield(L, -1, "password", password);
5637 throw LuaError(L, "Authentication handler didn't return password");
5639 *dst_password = password;
5641 lua_getfield(L, -1, "privileges");
5642 if(!lua_istable(L, -1))
5644 "Authentication handler didn't return privilege table");
5646 read_privileges(L, -1, *dst_privs);
5652 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5653 const std::string &password)
5656 assert(lua_checkstack(L, 20));
5657 StackUnroller stack_unroller(L);
5659 get_auth_handler(L);
5660 lua_getfield(L, -1, "create_auth");
5661 if(lua_type(L, -1) != LUA_TFUNCTION)
5662 throw LuaError(L, "Authentication handler missing create_auth");
5663 lua_pushstring(L, playername.c_str());
5664 lua_pushstring(L, password.c_str());
5665 if(lua_pcall(L, 2, 0, 0))
5666 script_error(L, "error: %s", lua_tostring(L, -1));
5669 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5670 const std::string &password)
5673 assert(lua_checkstack(L, 20));
5674 StackUnroller stack_unroller(L);
5676 get_auth_handler(L);
5677 lua_getfield(L, -1, "set_password");
5678 if(lua_type(L, -1) != LUA_TFUNCTION)
5679 throw LuaError(L, "Authentication handler missing set_password");
5680 lua_pushstring(L, playername.c_str());
5681 lua_pushstring(L, password.c_str());
5682 if(lua_pcall(L, 2, 1, 0))
5683 script_error(L, "error: %s", lua_tostring(L, -1));
5684 return lua_toboolean(L, -1);
5691 void scriptapi_on_player_receive_fields(lua_State *L,
5692 ServerActiveObject *player,
5693 const std::string &formname,
5694 const std::map<std::string, std::string> &fields)
5697 assert(lua_checkstack(L, 20));
5698 StackUnroller stack_unroller(L);
5700 // Get minetest.registered_on_chat_messages
5701 lua_getglobal(L, "minetest");
5702 lua_getfield(L, -1, "registered_on_player_receive_fields");
5705 objectref_get_or_create(L, player);
5707 lua_pushstring(L, formname.c_str());
5710 for(std::map<std::string, std::string>::const_iterator
5711 i = fields.begin(); i != fields.end(); i++){
5712 const std::string &name = i->first;
5713 const std::string &value = i->second;
5714 lua_pushstring(L, name.c_str());
5715 lua_pushlstring(L, value.c_str(), value.size());
5716 lua_settable(L, -3);
5718 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5722 item callbacks and node callbacks
5725 // Retrieves minetest.registered_items[name][callbackname]
5726 // If that is nil or on error, return false and stack is unchanged
5727 // If that is a function, returns true and pushes the
5728 // function onto the stack
5729 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5730 // is tried instead so unknown items can still be manipulated to some degree
5731 static bool get_item_callback(lua_State *L,
5732 const char *name, const char *callbackname)
5734 lua_getglobal(L, "minetest");
5735 lua_getfield(L, -1, "registered_items");
5737 luaL_checktype(L, -1, LUA_TTABLE);
5738 lua_getfield(L, -1, name);
5740 // Should be a table
5741 if(lua_type(L, -1) != LUA_TTABLE)
5743 // Report error and clean up
5744 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5747 // Try minetest.nodedef_default instead
5748 lua_getglobal(L, "minetest");
5749 lua_getfield(L, -1, "nodedef_default");
5751 luaL_checktype(L, -1, LUA_TTABLE);
5753 lua_getfield(L, -1, callbackname);
5755 // Should be a function or nil
5756 if(lua_type(L, -1) == LUA_TFUNCTION)
5760 else if(lua_isnil(L, -1))
5767 errorstream<<"Item \""<<name<<"\" callback \""
5768 <<callbackname<<" is not a function"<<std::endl;
5774 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5775 ServerActiveObject *dropper, v3f pos)
5778 assert(lua_checkstack(L, 20));
5779 StackUnroller stack_unroller(L);
5781 // Push callback function on stack
5782 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5786 LuaItemStack::create(L, item);
5787 objectref_get_or_create(L, dropper);
5788 pushFloatPos(L, pos);
5789 if(lua_pcall(L, 3, 1, 0))
5790 script_error(L, "error: %s", lua_tostring(L, -1));
5791 if(!lua_isnil(L, -1))
5792 item = read_item(L, -1);
5796 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5797 ServerActiveObject *placer, const PointedThing &pointed)
5800 assert(lua_checkstack(L, 20));
5801 StackUnroller stack_unroller(L);
5803 // Push callback function on stack
5804 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5808 LuaItemStack::create(L, item);
5809 objectref_get_or_create(L, placer);
5810 push_pointed_thing(L, pointed);
5811 if(lua_pcall(L, 3, 1, 0))
5812 script_error(L, "error: %s", lua_tostring(L, -1));
5813 if(!lua_isnil(L, -1))
5814 item = read_item(L, -1);
5818 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5819 ServerActiveObject *user, const PointedThing &pointed)
5822 assert(lua_checkstack(L, 20));
5823 StackUnroller stack_unroller(L);
5825 // Push callback function on stack
5826 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5830 LuaItemStack::create(L, item);
5831 objectref_get_or_create(L, user);
5832 push_pointed_thing(L, pointed);
5833 if(lua_pcall(L, 3, 1, 0))
5834 script_error(L, "error: %s", lua_tostring(L, -1));
5835 if(!lua_isnil(L, -1))
5836 item = read_item(L, -1);
5840 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5841 ServerActiveObject *puncher)
5844 assert(lua_checkstack(L, 20));
5845 StackUnroller stack_unroller(L);
5847 INodeDefManager *ndef = get_server(L)->ndef();
5849 // Push callback function on stack
5850 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5855 pushnode(L, node, ndef);
5856 objectref_get_or_create(L, puncher);
5857 if(lua_pcall(L, 3, 0, 0))
5858 script_error(L, "error: %s", lua_tostring(L, -1));
5862 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5863 ServerActiveObject *digger)
5866 assert(lua_checkstack(L, 20));
5867 StackUnroller stack_unroller(L);
5869 INodeDefManager *ndef = get_server(L)->ndef();
5871 // Push callback function on stack
5872 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5877 pushnode(L, node, ndef);
5878 objectref_get_or_create(L, digger);
5879 if(lua_pcall(L, 3, 0, 0))
5880 script_error(L, "error: %s", lua_tostring(L, -1));
5884 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5887 assert(lua_checkstack(L, 20));
5888 StackUnroller stack_unroller(L);
5890 INodeDefManager *ndef = get_server(L)->ndef();
5892 // Push callback function on stack
5893 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5898 if(lua_pcall(L, 1, 0, 0))
5899 script_error(L, "error: %s", lua_tostring(L, -1));
5902 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5905 assert(lua_checkstack(L, 20));
5906 StackUnroller stack_unroller(L);
5908 INodeDefManager *ndef = get_server(L)->ndef();
5910 // Push callback function on stack
5911 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5916 if(lua_pcall(L, 1, 0, 0))
5917 script_error(L, "error: %s", lua_tostring(L, -1));
5920 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5923 assert(lua_checkstack(L, 20));
5924 StackUnroller stack_unroller(L);
5926 INodeDefManager *ndef = get_server(L)->ndef();
5928 // Push callback function on stack
5929 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5934 pushnode(L, node, ndef);
5935 if(lua_pcall(L, 2, 0, 0))
5936 script_error(L, "error: %s", lua_tostring(L, -1));
5939 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
5942 assert(lua_checkstack(L, 20));
5943 StackUnroller stack_unroller(L);
5945 INodeDefManager *ndef = get_server(L)->ndef();
5947 // Push callback function on stack
5948 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
5953 lua_pushnumber(L,dtime);
5954 if(lua_pcall(L, 2, 1, 0))
5955 script_error(L, "error: %s", lua_tostring(L, -1));
5956 if(lua_isboolean(L,-1) && lua_toboolean(L,-1) == true)
5962 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5963 const std::string &formname,
5964 const std::map<std::string, std::string> &fields,
5965 ServerActiveObject *sender)
5968 assert(lua_checkstack(L, 20));
5969 StackUnroller stack_unroller(L);
5971 INodeDefManager *ndef = get_server(L)->ndef();
5973 // If node doesn't exist, we don't know what callback to call
5974 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5975 if(node.getContent() == CONTENT_IGNORE)
5978 // Push callback function on stack
5979 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5986 lua_pushstring(L, formname.c_str());
5989 for(std::map<std::string, std::string>::const_iterator
5990 i = fields.begin(); i != fields.end(); i++){
5991 const std::string &name = i->first;
5992 const std::string &value = i->second;
5993 lua_pushstring(L, name.c_str());
5994 lua_pushlstring(L, value.c_str(), value.size());
5995 lua_settable(L, -3);
5998 objectref_get_or_create(L, sender);
5999 if(lua_pcall(L, 4, 0, 0))
6000 script_error(L, "error: %s", lua_tostring(L, -1));
6004 Node metadata inventory callbacks
6007 // Return number of accepted items to be moved
6008 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6009 const std::string &from_list, int from_index,
6010 const std::string &to_list, int to_index,
6011 int count, ServerActiveObject *player)
6014 assert(lua_checkstack(L, 20));
6015 StackUnroller stack_unroller(L);
6017 INodeDefManager *ndef = get_server(L)->ndef();
6019 // If node doesn't exist, we don't know what callback to call
6020 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6021 if(node.getContent() == CONTENT_IGNORE)
6024 // Push callback function on stack
6025 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6026 "allow_metadata_inventory_move"))
6029 // function(pos, from_list, from_index, to_list, to_index, count, player)
6033 lua_pushstring(L, from_list.c_str());
6035 lua_pushinteger(L, from_index + 1);
6037 lua_pushstring(L, to_list.c_str());
6039 lua_pushinteger(L, to_index + 1);
6041 lua_pushinteger(L, count);
6043 objectref_get_or_create(L, player);
6044 if(lua_pcall(L, 7, 1, 0))
6045 script_error(L, "error: %s", lua_tostring(L, -1));
6046 if(!lua_isnumber(L, -1))
6047 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6048 return luaL_checkinteger(L, -1);
6051 // Return number of accepted items to be put
6052 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6053 const std::string &listname, int index, ItemStack &stack,
6054 ServerActiveObject *player)
6057 assert(lua_checkstack(L, 20));
6058 StackUnroller stack_unroller(L);
6060 INodeDefManager *ndef = get_server(L)->ndef();
6062 // If node doesn't exist, we don't know what callback to call
6063 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6064 if(node.getContent() == CONTENT_IGNORE)
6067 // Push callback function on stack
6068 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6069 "allow_metadata_inventory_put"))
6072 // Call function(pos, listname, index, stack, player)
6076 lua_pushstring(L, listname.c_str());
6078 lua_pushinteger(L, index + 1);
6080 LuaItemStack::create(L, stack);
6082 objectref_get_or_create(L, player);
6083 if(lua_pcall(L, 5, 1, 0))
6084 script_error(L, "error: %s", lua_tostring(L, -1));
6085 if(!lua_isnumber(L, -1))
6086 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6087 return luaL_checkinteger(L, -1);
6090 // Return number of accepted items to be taken
6091 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6092 const std::string &listname, int index, ItemStack &stack,
6093 ServerActiveObject *player)
6096 assert(lua_checkstack(L, 20));
6097 StackUnroller stack_unroller(L);
6099 INodeDefManager *ndef = get_server(L)->ndef();
6101 // If node doesn't exist, we don't know what callback to call
6102 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6103 if(node.getContent() == CONTENT_IGNORE)
6106 // Push callback function on stack
6107 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6108 "allow_metadata_inventory_take"))
6111 // Call function(pos, listname, index, count, player)
6115 lua_pushstring(L, listname.c_str());
6117 lua_pushinteger(L, index + 1);
6119 LuaItemStack::create(L, stack);
6121 objectref_get_or_create(L, player);
6122 if(lua_pcall(L, 5, 1, 0))
6123 script_error(L, "error: %s", lua_tostring(L, -1));
6124 if(!lua_isnumber(L, -1))
6125 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6126 return luaL_checkinteger(L, -1);
6129 // Report moved items
6130 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6131 const std::string &from_list, int from_index,
6132 const std::string &to_list, int to_index,
6133 int count, ServerActiveObject *player)
6136 assert(lua_checkstack(L, 20));
6137 StackUnroller stack_unroller(L);
6139 INodeDefManager *ndef = get_server(L)->ndef();
6141 // If node doesn't exist, we don't know what callback to call
6142 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6143 if(node.getContent() == CONTENT_IGNORE)
6146 // Push callback function on stack
6147 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6148 "on_metadata_inventory_move"))
6151 // function(pos, from_list, from_index, to_list, to_index, count, player)
6155 lua_pushstring(L, from_list.c_str());
6157 lua_pushinteger(L, from_index + 1);
6159 lua_pushstring(L, to_list.c_str());
6161 lua_pushinteger(L, to_index + 1);
6163 lua_pushinteger(L, count);
6165 objectref_get_or_create(L, player);
6166 if(lua_pcall(L, 7, 0, 0))
6167 script_error(L, "error: %s", lua_tostring(L, -1));
6171 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6172 const std::string &listname, int index, ItemStack &stack,
6173 ServerActiveObject *player)
6176 assert(lua_checkstack(L, 20));
6177 StackUnroller stack_unroller(L);
6179 INodeDefManager *ndef = get_server(L)->ndef();
6181 // If node doesn't exist, we don't know what callback to call
6182 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6183 if(node.getContent() == CONTENT_IGNORE)
6186 // Push callback function on stack
6187 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6188 "on_metadata_inventory_put"))
6191 // Call function(pos, listname, index, stack, player)
6195 lua_pushstring(L, listname.c_str());
6197 lua_pushinteger(L, index + 1);
6199 LuaItemStack::create(L, stack);
6201 objectref_get_or_create(L, player);
6202 if(lua_pcall(L, 5, 0, 0))
6203 script_error(L, "error: %s", lua_tostring(L, -1));
6206 // Report taken items
6207 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6208 const std::string &listname, int index, ItemStack &stack,
6209 ServerActiveObject *player)
6212 assert(lua_checkstack(L, 20));
6213 StackUnroller stack_unroller(L);
6215 INodeDefManager *ndef = get_server(L)->ndef();
6217 // If node doesn't exist, we don't know what callback to call
6218 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6219 if(node.getContent() == CONTENT_IGNORE)
6222 // Push callback function on stack
6223 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6224 "on_metadata_inventory_take"))
6227 // Call function(pos, listname, index, stack, player)
6231 lua_pushstring(L, listname.c_str());
6233 lua_pushinteger(L, index + 1);
6235 LuaItemStack::create(L, stack);
6237 objectref_get_or_create(L, player);
6238 if(lua_pcall(L, 5, 0, 0))
6239 script_error(L, "error: %s", lua_tostring(L, -1));
6243 Detached inventory callbacks
6246 // Retrieves minetest.detached_inventories[name][callbackname]
6247 // If that is nil or on error, return false and stack is unchanged
6248 // If that is a function, returns true and pushes the
6249 // function onto the stack
6250 static bool get_detached_inventory_callback(lua_State *L,
6251 const std::string &name, const char *callbackname)
6253 lua_getglobal(L, "minetest");
6254 lua_getfield(L, -1, "detached_inventories");
6256 luaL_checktype(L, -1, LUA_TTABLE);
6257 lua_getfield(L, -1, name.c_str());
6259 // Should be a table
6260 if(lua_type(L, -1) != LUA_TTABLE)
6262 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6266 lua_getfield(L, -1, callbackname);
6268 // Should be a function or nil
6269 if(lua_type(L, -1) == LUA_TFUNCTION)
6273 else if(lua_isnil(L, -1))
6280 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6281 <<callbackname<<"\" is not a function"<<std::endl;
6287 // Return number of accepted items to be moved
6288 int scriptapi_detached_inventory_allow_move(lua_State *L,
6289 const std::string &name,
6290 const std::string &from_list, int from_index,
6291 const std::string &to_list, int to_index,
6292 int count, ServerActiveObject *player)
6295 assert(lua_checkstack(L, 20));
6296 StackUnroller stack_unroller(L);
6298 // Push callback function on stack
6299 if(!get_detached_inventory_callback(L, name, "allow_move"))
6302 // function(inv, from_list, from_index, to_list, to_index, count, player)
6304 InventoryLocation loc;
6305 loc.setDetached(name);
6306 InvRef::create(L, loc);
6308 lua_pushstring(L, from_list.c_str());
6310 lua_pushinteger(L, from_index + 1);
6312 lua_pushstring(L, to_list.c_str());
6314 lua_pushinteger(L, to_index + 1);
6316 lua_pushinteger(L, count);
6318 objectref_get_or_create(L, player);
6319 if(lua_pcall(L, 7, 1, 0))
6320 script_error(L, "error: %s", lua_tostring(L, -1));
6321 if(!lua_isnumber(L, -1))
6322 throw LuaError(L, "allow_move should return a number");
6323 return luaL_checkinteger(L, -1);
6326 // Return number of accepted items to be put
6327 int scriptapi_detached_inventory_allow_put(lua_State *L,
6328 const std::string &name,
6329 const std::string &listname, int index, ItemStack &stack,
6330 ServerActiveObject *player)
6333 assert(lua_checkstack(L, 20));
6334 StackUnroller stack_unroller(L);
6336 // Push callback function on stack
6337 if(!get_detached_inventory_callback(L, name, "allow_put"))
6338 return stack.count; // All will be accepted
6340 // Call function(inv, listname, index, stack, player)
6342 InventoryLocation loc;
6343 loc.setDetached(name);
6344 InvRef::create(L, loc);
6346 lua_pushstring(L, listname.c_str());
6348 lua_pushinteger(L, index + 1);
6350 LuaItemStack::create(L, stack);
6352 objectref_get_or_create(L, player);
6353 if(lua_pcall(L, 5, 1, 0))
6354 script_error(L, "error: %s", lua_tostring(L, -1));
6355 if(!lua_isnumber(L, -1))
6356 throw LuaError(L, "allow_put should return a number");
6357 return luaL_checkinteger(L, -1);
6360 // Return number of accepted items to be taken
6361 int scriptapi_detached_inventory_allow_take(lua_State *L,
6362 const std::string &name,
6363 const std::string &listname, int index, ItemStack &stack,
6364 ServerActiveObject *player)
6367 assert(lua_checkstack(L, 20));
6368 StackUnroller stack_unroller(L);
6370 // Push callback function on stack
6371 if(!get_detached_inventory_callback(L, name, "allow_take"))
6372 return stack.count; // All will be accepted
6374 // Call function(inv, listname, index, stack, player)
6376 InventoryLocation loc;
6377 loc.setDetached(name);
6378 InvRef::create(L, loc);
6380 lua_pushstring(L, listname.c_str());
6382 lua_pushinteger(L, index + 1);
6384 LuaItemStack::create(L, stack);
6386 objectref_get_or_create(L, player);
6387 if(lua_pcall(L, 5, 1, 0))
6388 script_error(L, "error: %s", lua_tostring(L, -1));
6389 if(!lua_isnumber(L, -1))
6390 throw LuaError(L, "allow_take should return a number");
6391 return luaL_checkinteger(L, -1);
6394 // Report moved items
6395 void scriptapi_detached_inventory_on_move(lua_State *L,
6396 const std::string &name,
6397 const std::string &from_list, int from_index,
6398 const std::string &to_list, int to_index,
6399 int count, ServerActiveObject *player)
6402 assert(lua_checkstack(L, 20));
6403 StackUnroller stack_unroller(L);
6405 // Push callback function on stack
6406 if(!get_detached_inventory_callback(L, name, "on_move"))
6409 // function(inv, from_list, from_index, to_list, to_index, count, player)
6411 InventoryLocation loc;
6412 loc.setDetached(name);
6413 InvRef::create(L, loc);
6415 lua_pushstring(L, from_list.c_str());
6417 lua_pushinteger(L, from_index + 1);
6419 lua_pushstring(L, to_list.c_str());
6421 lua_pushinteger(L, to_index + 1);
6423 lua_pushinteger(L, count);
6425 objectref_get_or_create(L, player);
6426 if(lua_pcall(L, 7, 0, 0))
6427 script_error(L, "error: %s", lua_tostring(L, -1));
6431 void scriptapi_detached_inventory_on_put(lua_State *L,
6432 const std::string &name,
6433 const std::string &listname, int index, ItemStack &stack,
6434 ServerActiveObject *player)
6437 assert(lua_checkstack(L, 20));
6438 StackUnroller stack_unroller(L);
6440 // Push callback function on stack
6441 if(!get_detached_inventory_callback(L, name, "on_put"))
6444 // Call function(inv, listname, index, stack, player)
6446 InventoryLocation loc;
6447 loc.setDetached(name);
6448 InvRef::create(L, loc);
6450 lua_pushstring(L, listname.c_str());
6452 lua_pushinteger(L, index + 1);
6454 LuaItemStack::create(L, stack);
6456 objectref_get_or_create(L, player);
6457 if(lua_pcall(L, 5, 0, 0))
6458 script_error(L, "error: %s", lua_tostring(L, -1));
6461 // Report taken items
6462 void scriptapi_detached_inventory_on_take(lua_State *L,
6463 const std::string &name,
6464 const std::string &listname, int index, ItemStack &stack,
6465 ServerActiveObject *player)
6468 assert(lua_checkstack(L, 20));
6469 StackUnroller stack_unroller(L);
6471 // Push callback function on stack
6472 if(!get_detached_inventory_callback(L, name, "on_take"))
6475 // Call function(inv, listname, index, stack, player)
6477 InventoryLocation loc;
6478 loc.setDetached(name);
6479 InvRef::create(L, loc);
6481 lua_pushstring(L, listname.c_str());
6483 lua_pushinteger(L, index + 1);
6485 LuaItemStack::create(L, stack);
6487 objectref_get_or_create(L, player);
6488 if(lua_pcall(L, 5, 0, 0))
6489 script_error(L, "error: %s", lua_tostring(L, -1));
6496 void scriptapi_environment_step(lua_State *L, float dtime)
6499 assert(lua_checkstack(L, 20));
6500 //infostream<<"scriptapi_environment_step"<<std::endl;
6501 StackUnroller stack_unroller(L);
6503 // Get minetest.registered_globalsteps
6504 lua_getglobal(L, "minetest");
6505 lua_getfield(L, -1, "registered_globalsteps");
6507 lua_pushnumber(L, dtime);
6508 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6511 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6515 assert(lua_checkstack(L, 20));
6516 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6517 StackUnroller stack_unroller(L);
6519 // Get minetest.registered_on_generateds
6520 lua_getglobal(L, "minetest");
6521 lua_getfield(L, -1, "registered_on_generateds");
6523 push_v3s16(L, minp);
6524 push_v3s16(L, maxp);
6525 lua_pushnumber(L, blockseed);
6526 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6533 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6536 assert(lua_checkstack(L, 20));
6537 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6538 <<name<<"\""<<std::endl;
6539 StackUnroller stack_unroller(L);
6541 // Get minetest.registered_entities[name]
6542 lua_getglobal(L, "minetest");
6543 lua_getfield(L, -1, "registered_entities");
6544 luaL_checktype(L, -1, LUA_TTABLE);
6545 lua_pushstring(L, name);
6546 lua_gettable(L, -2);
6547 // Should be a table, which we will use as a prototype
6548 //luaL_checktype(L, -1, LUA_TTABLE);
6549 if(lua_type(L, -1) != LUA_TTABLE){
6550 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6553 int prototype_table = lua_gettop(L);
6554 //dump2(L, "prototype_table");
6556 // Create entity object
6558 int object = lua_gettop(L);
6560 // Set object metatable
6561 lua_pushvalue(L, prototype_table);
6562 lua_setmetatable(L, -2);
6564 // Add object reference
6565 // This should be userdata with metatable ObjectRef
6566 objectref_get(L, id);
6567 luaL_checktype(L, -1, LUA_TUSERDATA);
6568 if(!luaL_checkudata(L, -1, "ObjectRef"))
6569 luaL_typerror(L, -1, "ObjectRef");
6570 lua_setfield(L, -2, "object");
6572 // minetest.luaentities[id] = object
6573 lua_getglobal(L, "minetest");
6574 lua_getfield(L, -1, "luaentities");
6575 luaL_checktype(L, -1, LUA_TTABLE);
6576 lua_pushnumber(L, id); // Push id
6577 lua_pushvalue(L, object); // Copy object to top of stack
6578 lua_settable(L, -3);
6583 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6584 const std::string &staticdata, u32 dtime_s)
6587 assert(lua_checkstack(L, 20));
6588 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6589 StackUnroller stack_unroller(L);
6591 // Get minetest.luaentities[id]
6592 luaentity_get(L, id);
6593 int object = lua_gettop(L);
6595 // Get on_activate function
6596 lua_pushvalue(L, object);
6597 lua_getfield(L, -1, "on_activate");
6598 if(!lua_isnil(L, -1)){
6599 luaL_checktype(L, -1, LUA_TFUNCTION);
6600 lua_pushvalue(L, object); // self
6601 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6602 lua_pushinteger(L, dtime_s);
6603 // Call with 3 arguments, 0 results
6604 if(lua_pcall(L, 3, 0, 0))
6605 script_error(L, "error running function on_activate: %s\n",
6606 lua_tostring(L, -1));
6610 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6613 assert(lua_checkstack(L, 20));
6614 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6616 // Get minetest.luaentities table
6617 lua_getglobal(L, "minetest");
6618 lua_getfield(L, -1, "luaentities");
6619 luaL_checktype(L, -1, LUA_TTABLE);
6620 int objectstable = lua_gettop(L);
6622 // Set luaentities[id] = nil
6623 lua_pushnumber(L, id); // Push id
6625 lua_settable(L, objectstable);
6627 lua_pop(L, 2); // pop luaentities, minetest
6630 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6633 assert(lua_checkstack(L, 20));
6634 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6635 StackUnroller stack_unroller(L);
6637 // Get minetest.luaentities[id]
6638 luaentity_get(L, id);
6639 int object = lua_gettop(L);
6641 // Get get_staticdata function
6642 lua_pushvalue(L, object);
6643 lua_getfield(L, -1, "get_staticdata");
6644 if(lua_isnil(L, -1))
6647 luaL_checktype(L, -1, LUA_TFUNCTION);
6648 lua_pushvalue(L, object); // self
6649 // Call with 1 arguments, 1 results
6650 if(lua_pcall(L, 1, 1, 0))
6651 script_error(L, "error running function get_staticdata: %s\n",
6652 lua_tostring(L, -1));
6655 const char *s = lua_tolstring(L, -1, &len);
6656 return std::string(s, len);
6659 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6660 ObjectProperties *prop)
6663 assert(lua_checkstack(L, 20));
6664 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6665 StackUnroller stack_unroller(L);
6667 // Get minetest.luaentities[id]
6668 luaentity_get(L, id);
6669 //int object = lua_gettop(L);
6671 // Set default values that differ from ObjectProperties defaults
6676 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6678 getboolfield(L, -1, "physical", prop->physical);
6680 getfloatfield(L, -1, "weight", prop->weight);
6682 lua_getfield(L, -1, "collisionbox");
6683 if(lua_istable(L, -1))
6684 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6687 getstringfield(L, -1, "visual", prop->visual);
6689 getstringfield(L, -1, "mesh", prop->mesh);
6691 // Deprecated: read object properties directly
6692 read_object_properties(L, -1, prop);
6694 // Read initial_properties
6695 lua_getfield(L, -1, "initial_properties");
6696 read_object_properties(L, -1, prop);
6700 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6703 assert(lua_checkstack(L, 20));
6704 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6705 StackUnroller stack_unroller(L);
6707 // Get minetest.luaentities[id]
6708 luaentity_get(L, id);
6709 int object = lua_gettop(L);
6710 // State: object is at top of stack
6711 // Get step function
6712 lua_getfield(L, -1, "on_step");
6713 if(lua_isnil(L, -1))
6715 luaL_checktype(L, -1, LUA_TFUNCTION);
6716 lua_pushvalue(L, object); // self
6717 lua_pushnumber(L, dtime); // dtime
6718 // Call with 2 arguments, 0 results
6719 if(lua_pcall(L, 2, 0, 0))
6720 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6723 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6724 // tool_capabilities, direction)
6725 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6726 ServerActiveObject *puncher, float time_from_last_punch,
6727 const ToolCapabilities *toolcap, v3f dir)
6730 assert(lua_checkstack(L, 20));
6731 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6732 StackUnroller stack_unroller(L);
6734 // Get minetest.luaentities[id]
6735 luaentity_get(L, id);
6736 int object = lua_gettop(L);
6737 // State: object is at top of stack
6739 lua_getfield(L, -1, "on_punch");
6740 if(lua_isnil(L, -1))
6742 luaL_checktype(L, -1, LUA_TFUNCTION);
6743 lua_pushvalue(L, object); // self
6744 objectref_get_or_create(L, puncher); // Clicker reference
6745 lua_pushnumber(L, time_from_last_punch);
6746 push_tool_capabilities(L, *toolcap);
6748 // Call with 5 arguments, 0 results
6749 if(lua_pcall(L, 5, 0, 0))
6750 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6753 // Calls entity:on_rightclick(ObjectRef clicker)
6754 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6755 ServerActiveObject *clicker)
6758 assert(lua_checkstack(L, 20));
6759 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6760 StackUnroller stack_unroller(L);
6762 // Get minetest.luaentities[id]
6763 luaentity_get(L, id);
6764 int object = lua_gettop(L);
6765 // State: object is at top of stack
6767 lua_getfield(L, -1, "on_rightclick");
6768 if(lua_isnil(L, -1))
6770 luaL_checktype(L, -1, LUA_TFUNCTION);
6771 lua_pushvalue(L, object); // self
6772 objectref_get_or_create(L, clicker); // Clicker reference
6773 // Call with 2 arguments, 0 results
6774 if(lua_pcall(L, 2, 0, 0))
6775 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));