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
42 #include "main.h" // For g_settings
43 #include "settings.h" // For accessing g_settings
44 #include "nodemetadata.h"
45 #include "mapblock.h" // For getNodeBlockPos
46 #include "content_nodemeta.h"
48 #include "daynightratio.h"
49 #include "noise.h" // PseudoRandom for LuaPseudoRandom
50 #include "util/pointedthing.h"
54 static void stackDump(lua_State *L, std::ostream &o)
57 int top = lua_gettop(L);
58 for (i = 1; i <= top; i++) { /* repeat for each level */
59 int t = lua_type(L, i);
62 case LUA_TSTRING: /* strings */
63 o<<"\""<<lua_tostring(L, i)<<"\"";
66 case LUA_TBOOLEAN: /* booleans */
67 o<<(lua_toboolean(L, i) ? "true" : "false");
70 case LUA_TNUMBER: /* numbers */ {
72 snprintf(buf, 10, "%g", lua_tonumber(L, i));
76 default: /* other values */
77 o<<lua_typename(L, t);
86 static void realitycheck(lua_State *L)
88 int top = lua_gettop(L);
90 dstream<<"Stack is over 30:"<<std::endl;
91 stackDump(L, dstream);
92 script_error(L, "Stack is over 30 (reality check)");
102 StackUnroller(lua_State *L):
106 m_original_top = lua_gettop(m_lua); // store stack height
110 lua_settop(m_lua, m_original_top); // restore stack height
119 ModNameStorer(lua_State *L_, const std::string modname):
122 // Store current modname in registry
123 lua_pushstring(L, modname.c_str());
124 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
128 // Clear current modname in registry
130 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
135 Getters for stuff in main tables
138 static Server* get_server(lua_State *L)
140 // Get server from registry
141 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
142 Server *server = (Server*)lua_touserdata(L, -1);
147 static ServerEnvironment* get_env(lua_State *L)
149 // Get environment from registry
150 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
151 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
156 static void objectref_get(lua_State *L, u16 id)
158 // Get minetest.object_refs[i]
159 lua_getglobal(L, "minetest");
160 lua_getfield(L, -1, "object_refs");
161 luaL_checktype(L, -1, LUA_TTABLE);
162 lua_pushnumber(L, id);
164 lua_remove(L, -2); // object_refs
165 lua_remove(L, -2); // minetest
168 static void luaentity_get(lua_State *L, u16 id)
170 // Get minetest.luaentities[i]
171 lua_getglobal(L, "minetest");
172 lua_getfield(L, -1, "luaentities");
173 luaL_checktype(L, -1, LUA_TTABLE);
174 lua_pushnumber(L, id);
176 lua_remove(L, -2); // luaentities
177 lua_remove(L, -2); // minetest
184 static bool getstringfield(lua_State *L, int table,
185 const char *fieldname, std::string &result)
187 lua_getfield(L, table, fieldname);
189 if(lua_isstring(L, -1)){
191 const char *ptr = lua_tolstring(L, -1, &len);
192 result.assign(ptr, len);
199 static bool getintfield(lua_State *L, int table,
200 const char *fieldname, int &result)
202 lua_getfield(L, table, fieldname);
204 if(lua_isnumber(L, -1)){
205 result = lua_tonumber(L, -1);
212 static bool getfloatfield(lua_State *L, int table,
213 const char *fieldname, float &result)
215 lua_getfield(L, table, fieldname);
217 if(lua_isnumber(L, -1)){
218 result = lua_tonumber(L, -1);
225 static bool getboolfield(lua_State *L, int table,
226 const char *fieldname, bool &result)
228 lua_getfield(L, table, fieldname);
230 if(lua_isboolean(L, -1)){
231 result = lua_toboolean(L, -1);
238 static std::string checkstringfield(lua_State *L, int table,
239 const char *fieldname)
241 lua_getfield(L, table, fieldname);
242 std::string s = luaL_checkstring(L, -1);
247 static std::string getstringfield_default(lua_State *L, int table,
248 const char *fieldname, const std::string &default_)
250 std::string result = default_;
251 getstringfield(L, table, fieldname, result);
255 static int getintfield_default(lua_State *L, int table,
256 const char *fieldname, int default_)
258 int result = default_;
259 getintfield(L, table, fieldname, result);
263 static float getfloatfield_default(lua_State *L, int table,
264 const char *fieldname, float default_)
266 float result = default_;
267 getfloatfield(L, table, fieldname, result);
271 static bool getboolfield_default(lua_State *L, int table,
272 const char *fieldname, bool default_)
274 bool result = default_;
275 getboolfield(L, table, fieldname, result);
285 static bool string_to_enum(const EnumString *spec, int &result,
286 const std::string &str)
288 const EnumString *esp = spec;
290 if(str == std::string(esp->str)){
299 /*static bool enum_to_string(const EnumString *spec, std::string &result,
302 const EnumString *esp = spec;
313 static int getenumfield(lua_State *L, int table,
314 const char *fieldname, const EnumString *spec, int default_)
316 int result = default_;
317 string_to_enum(spec, result,
318 getstringfield_default(L, table, fieldname, ""));
322 static void setintfield(lua_State *L, int table,
323 const char *fieldname, int value)
325 lua_pushinteger(L, value);
328 lua_setfield(L, table, fieldname);
331 static void setfloatfield(lua_State *L, int table,
332 const char *fieldname, float value)
334 lua_pushnumber(L, value);
337 lua_setfield(L, table, fieldname);
340 static void setboolfield(lua_State *L, int table,
341 const char *fieldname, bool value)
343 lua_pushboolean(L, value);
346 lua_setfield(L, table, fieldname);
349 static void warn_if_field_exists(lua_State *L, int table,
350 const char *fieldname, const std::string &message)
352 lua_getfield(L, table, fieldname);
353 if(!lua_isnil(L, -1)){
354 infostream<<script_get_backtrace(L)<<std::endl;
355 infostream<<"WARNING: field \""<<fieldname<<"\": "
356 <<message<<std::endl;
362 EnumString definitions
365 struct EnumString es_ItemType[] =
369 {ITEM_CRAFT, "craft"},
374 struct EnumString es_DrawType[] =
376 {NDT_NORMAL, "normal"},
377 {NDT_AIRLIKE, "airlike"},
378 {NDT_LIQUID, "liquid"},
379 {NDT_FLOWINGLIQUID, "flowingliquid"},
380 {NDT_GLASSLIKE, "glasslike"},
381 {NDT_ALLFACES, "allfaces"},
382 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
383 {NDT_TORCHLIKE, "torchlike"},
384 {NDT_SIGNLIKE, "signlike"},
385 {NDT_PLANTLIKE, "plantlike"},
386 {NDT_FENCELIKE, "fencelike"},
387 {NDT_RAILLIKE, "raillike"},
388 {NDT_NODEBOX, "nodebox"},
392 struct EnumString es_ContentParamType[] =
395 {CPT_LIGHT, "light"},
399 struct EnumString es_ContentParamType2[] =
403 {CPT2_FLOWINGLIQUID, "flowingliquid"},
404 {CPT2_FACEDIR, "facedir"},
405 {CPT2_WALLMOUNTED, "wallmounted"},
409 struct EnumString es_LiquidType[] =
411 {LIQUID_NONE, "none"},
412 {LIQUID_FLOWING, "flowing"},
413 {LIQUID_SOURCE, "source"},
417 struct EnumString es_NodeBoxType[] =
419 {NODEBOX_REGULAR, "regular"},
420 {NODEBOX_FIXED, "fixed"},
421 {NODEBOX_WALLMOUNTED, "wallmounted"},
425 struct EnumString es_CraftMethod[] =
427 {CRAFT_METHOD_NORMAL, "normal"},
428 {CRAFT_METHOD_COOKING, "cooking"},
429 {CRAFT_METHOD_FUEL, "fuel"},
433 struct EnumString es_TileAnimationType[] =
436 {TAT_VERTICAL_FRAMES, "vertical_frames"},
440 struct EnumString es_BiomeTerrainType[] =
442 {BIOME_TERRAIN_NORMAL, "normal"},
443 {BIOME_TERRAIN_LIQUID, "liquid"},
444 {BIOME_TERRAIN_NETHER, "nether"},
445 {BIOME_TERRAIN_AETHER, "aether"},
446 {BIOME_TERRAIN_FLAT, "flat"},
451 C struct <-> Lua table converter functions
454 static void push_v3f(lua_State *L, v3f p)
457 lua_pushnumber(L, p.X);
458 lua_setfield(L, -2, "x");
459 lua_pushnumber(L, p.Y);
460 lua_setfield(L, -2, "y");
461 lua_pushnumber(L, p.Z);
462 lua_setfield(L, -2, "z");
465 static v2s16 read_v2s16(lua_State *L, int index)
468 luaL_checktype(L, index, LUA_TTABLE);
469 lua_getfield(L, index, "x");
470 p.X = lua_tonumber(L, -1);
472 lua_getfield(L, index, "y");
473 p.Y = lua_tonumber(L, -1);
478 static v2f read_v2f(lua_State *L, int index)
481 luaL_checktype(L, index, LUA_TTABLE);
482 lua_getfield(L, index, "x");
483 p.X = lua_tonumber(L, -1);
485 lua_getfield(L, index, "y");
486 p.Y = lua_tonumber(L, -1);
491 static v3f read_v3f(lua_State *L, int index)
494 luaL_checktype(L, index, LUA_TTABLE);
495 lua_getfield(L, index, "x");
496 pos.X = lua_tonumber(L, -1);
498 lua_getfield(L, index, "y");
499 pos.Y = lua_tonumber(L, -1);
501 lua_getfield(L, index, "z");
502 pos.Z = lua_tonumber(L, -1);
507 static v3f check_v3f(lua_State *L, int index)
510 luaL_checktype(L, index, LUA_TTABLE);
511 lua_getfield(L, index, "x");
512 pos.X = luaL_checknumber(L, -1);
514 lua_getfield(L, index, "y");
515 pos.Y = luaL_checknumber(L, -1);
517 lua_getfield(L, index, "z");
518 pos.Z = luaL_checknumber(L, -1);
523 static void pushFloatPos(lua_State *L, v3f p)
529 static v3f checkFloatPos(lua_State *L, int index)
531 return check_v3f(L, index) * BS;
534 static void push_v3s16(lua_State *L, v3s16 p)
537 lua_pushnumber(L, p.X);
538 lua_setfield(L, -2, "x");
539 lua_pushnumber(L, p.Y);
540 lua_setfield(L, -2, "y");
541 lua_pushnumber(L, p.Z);
542 lua_setfield(L, -2, "z");
545 static v3s16 read_v3s16(lua_State *L, int index)
547 // Correct rounding at <0
548 v3f pf = read_v3f(L, index);
549 return floatToInt(pf, 1.0);
552 static v3s16 check_v3s16(lua_State *L, int index)
554 // Correct rounding at <0
555 v3f pf = check_v3f(L, index);
556 return floatToInt(pf, 1.0);
559 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
562 lua_pushstring(L, ndef->get(n).name.c_str());
563 lua_setfield(L, -2, "name");
564 lua_pushnumber(L, n.getParam1());
565 lua_setfield(L, -2, "param1");
566 lua_pushnumber(L, n.getParam2());
567 lua_setfield(L, -2, "param2");
570 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
572 lua_getfield(L, index, "name");
573 const char *name = luaL_checkstring(L, -1);
576 lua_getfield(L, index, "param1");
580 param1 = lua_tonumber(L, -1);
583 lua_getfield(L, index, "param2");
587 param2 = lua_tonumber(L, -1);
589 return MapNode(ndef, name, param1, param2);
592 static video::SColor readARGB8(lua_State *L, int index)
595 luaL_checktype(L, index, LUA_TTABLE);
596 lua_getfield(L, index, "a");
597 if(lua_isnumber(L, -1))
598 color.setAlpha(lua_tonumber(L, -1));
600 lua_getfield(L, index, "r");
601 color.setRed(lua_tonumber(L, -1));
603 lua_getfield(L, index, "g");
604 color.setGreen(lua_tonumber(L, -1));
606 lua_getfield(L, index, "b");
607 color.setBlue(lua_tonumber(L, -1));
612 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
615 if(lua_istable(L, index)){
616 lua_rawgeti(L, index, 1);
617 box.MinEdge.X = lua_tonumber(L, -1) * scale;
619 lua_rawgeti(L, index, 2);
620 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
622 lua_rawgeti(L, index, 3);
623 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
625 lua_rawgeti(L, index, 4);
626 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
628 lua_rawgeti(L, index, 5);
629 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
631 lua_rawgeti(L, index, 6);
632 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
638 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
640 std::vector<aabb3f> boxes;
641 if(lua_istable(L, index)){
642 int n = lua_objlen(L, index);
643 // Check if it's a single box or a list of boxes
644 bool possibly_single_box = (n == 6);
645 for(int i = 1; i <= n && possibly_single_box; i++){
646 lua_rawgeti(L, index, i);
647 if(!lua_isnumber(L, -1))
648 possibly_single_box = false;
651 if(possibly_single_box){
653 boxes.push_back(read_aabb3f(L, index, scale));
655 // Read a list of boxes
656 for(int i = 1; i <= n; i++){
657 lua_rawgeti(L, index, i);
658 boxes.push_back(read_aabb3f(L, -1, scale));
666 static NodeBox read_nodebox(lua_State *L, int index)
669 if(lua_istable(L, -1)){
670 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
671 es_NodeBoxType, NODEBOX_REGULAR);
673 lua_getfield(L, index, "fixed");
674 if(lua_istable(L, -1))
675 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
678 lua_getfield(L, index, "wall_top");
679 if(lua_istable(L, -1))
680 nodebox.wall_top = read_aabb3f(L, -1, BS);
683 lua_getfield(L, index, "wall_bottom");
684 if(lua_istable(L, -1))
685 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
688 lua_getfield(L, index, "wall_side");
689 if(lua_istable(L, -1))
690 nodebox.wall_side = read_aabb3f(L, -1, BS);
699 static void read_groups(lua_State *L, int index,
700 std::map<std::string, int> &result)
702 if (!lua_istable(L,index))
708 while(lua_next(L, index) != 0){
709 // key at index -2 and value at index -1
710 std::string name = luaL_checkstring(L, -2);
711 int rating = luaL_checkinteger(L, -1);
712 result[name] = rating;
713 // removes value, keeps key for next iteration
721 static void read_privileges(lua_State *L, int index,
722 std::set<std::string> &result)
728 while(lua_next(L, index) != 0){
729 // key at index -2 and value at index -1
730 std::string key = luaL_checkstring(L, -2);
731 bool value = lua_toboolean(L, -1);
734 // removes value, keeps key for next iteration
743 static ToolCapabilities read_tool_capabilities(
744 lua_State *L, int table)
746 ToolCapabilities toolcap;
747 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
748 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
749 lua_getfield(L, table, "groupcaps");
750 if(lua_istable(L, -1)){
751 int table_groupcaps = lua_gettop(L);
753 while(lua_next(L, table_groupcaps) != 0){
754 // key at index -2 and value at index -1
755 std::string groupname = luaL_checkstring(L, -2);
756 if(lua_istable(L, -1)){
757 int table_groupcap = lua_gettop(L);
758 // This will be created
759 ToolGroupCap groupcap;
760 // Read simple parameters
761 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
762 getintfield(L, table_groupcap, "uses", groupcap.uses);
763 // DEPRECATED: maxwear
765 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
767 groupcap.uses = 1.0/maxwear;
770 infostream<<script_get_backtrace(L)<<std::endl;
771 infostream<<"WARNING: field \"maxwear\" is deprecated; "
772 <<"should replace with uses=1/maxwear"<<std::endl;
774 // Read "times" table
775 lua_getfield(L, table_groupcap, "times");
776 if(lua_istable(L, -1)){
777 int table_times = lua_gettop(L);
779 while(lua_next(L, table_times) != 0){
780 // key at index -2 and value at index -1
781 int rating = luaL_checkinteger(L, -2);
782 float time = luaL_checknumber(L, -1);
783 groupcap.times[rating] = time;
784 // removes value, keeps key for next iteration
789 // Insert groupcap into toolcap
790 toolcap.groupcaps[groupname] = groupcap;
792 // removes value, keeps key for next iteration
800 static void set_tool_capabilities(lua_State *L, int table,
801 const ToolCapabilities &toolcap)
803 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
804 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
805 // Create groupcaps table
808 for(std::map<std::string, ToolGroupCap>::const_iterator
809 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
810 // Create groupcap table
812 const std::string &name = i->first;
813 const ToolGroupCap &groupcap = i->second;
814 // Create subtable "times"
816 for(std::map<int, float>::const_iterator
817 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
818 int rating = i->first;
819 float time = i->second;
820 lua_pushinteger(L, rating);
821 lua_pushnumber(L, time);
824 // Set subtable "times"
825 lua_setfield(L, -2, "times");
826 // Set simple parameters
827 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
828 setintfield(L, -1, "uses", groupcap.uses);
829 // Insert groupcap table into groupcaps table
830 lua_setfield(L, -2, name.c_str());
832 // Set groupcaps table
833 lua_setfield(L, -2, "groupcaps");
836 static void push_tool_capabilities(lua_State *L,
837 const ToolCapabilities &prop)
840 set_tool_capabilities(L, -1, prop);
847 static void set_dig_params(lua_State *L, int table,
848 const DigParams ¶ms)
850 setboolfield(L, table, "diggable", params.diggable);
851 setfloatfield(L, table, "time", params.time);
852 setintfield(L, table, "wear", params.wear);
855 static void push_dig_params(lua_State *L,
856 const DigParams ¶ms)
859 set_dig_params(L, -1, params);
866 static void set_hit_params(lua_State *L, int table,
867 const HitParams ¶ms)
869 setintfield(L, table, "hp", params.hp);
870 setintfield(L, table, "wear", params.wear);
873 static void push_hit_params(lua_State *L,
874 const HitParams ¶ms)
877 set_hit_params(L, -1, params);
884 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
887 if(pointed.type == POINTEDTHING_NODE)
889 lua_pushstring(L, "node");
890 lua_setfield(L, -2, "type");
891 push_v3s16(L, pointed.node_undersurface);
892 lua_setfield(L, -2, "under");
893 push_v3s16(L, pointed.node_abovesurface);
894 lua_setfield(L, -2, "above");
896 else if(pointed.type == POINTEDTHING_OBJECT)
898 lua_pushstring(L, "object");
899 lua_setfield(L, -2, "type");
900 objectref_get(L, pointed.object_id);
901 lua_setfield(L, -2, "ref");
905 lua_pushstring(L, "nothing");
906 lua_setfield(L, -2, "type");
914 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
917 index = lua_gettop(L) + 1 + index;
918 if(lua_isnil(L, index)){
919 } else if(lua_istable(L, index)){
920 getstringfield(L, index, "name", spec.name);
921 getfloatfield(L, index, "gain", spec.gain);
922 } else if(lua_isstring(L, index)){
923 spec.name = lua_tostring(L, index);
931 static void read_object_properties(lua_State *L, int index,
932 ObjectProperties *prop)
935 index = lua_gettop(L) + 1 + index;
936 if(!lua_istable(L, index))
939 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
941 getboolfield(L, -1, "physical", prop->physical);
943 getfloatfield(L, -1, "weight", prop->weight);
945 lua_getfield(L, -1, "collisionbox");
946 if(lua_istable(L, -1))
947 prop->collisionbox = read_aabb3f(L, -1, 1.0);
950 getstringfield(L, -1, "visual", prop->visual);
952 getstringfield(L, -1, "mesh", prop->mesh);
954 lua_getfield(L, -1, "visual_size");
955 if(lua_istable(L, -1))
956 prop->visual_size = read_v2f(L, -1);
959 lua_getfield(L, -1, "textures");
960 if(lua_istable(L, -1)){
961 prop->textures.clear();
962 int table = lua_gettop(L);
964 while(lua_next(L, table) != 0){
965 // key at index -2 and value at index -1
966 if(lua_isstring(L, -1))
967 prop->textures.push_back(lua_tostring(L, -1));
969 prop->textures.push_back("");
970 // removes value, keeps key for next iteration
976 lua_getfield(L, -1, "colors");
977 if(lua_istable(L, -1)){
978 prop->colors.clear();
979 int table = lua_gettop(L);
981 while(lua_next(L, table) != 0){
982 // key at index -2 and value at index -1
983 if(lua_isstring(L, -1))
984 prop->colors.push_back(readARGB8(L, -1));
986 prop->colors.push_back(video::SColor(255, 255, 255, 255));
987 // removes value, keeps key for next iteration
993 lua_getfield(L, -1, "spritediv");
994 if(lua_istable(L, -1))
995 prop->spritediv = read_v2s16(L, -1);
998 lua_getfield(L, -1, "initial_sprite_basepos");
999 if(lua_istable(L, -1))
1000 prop->initial_sprite_basepos = read_v2s16(L, -1);
1003 getboolfield(L, -1, "is_visible", prop->is_visible);
1004 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
1005 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
1012 static ItemDefinition read_item_definition(lua_State *L, int index,
1013 ItemDefinition default_def = ItemDefinition())
1016 index = lua_gettop(L) + 1 + index;
1018 // Read the item definition
1019 ItemDefinition def = default_def;
1021 def.type = (ItemType)getenumfield(L, index, "type",
1022 es_ItemType, ITEM_NONE);
1023 getstringfield(L, index, "name", def.name);
1024 getstringfield(L, index, "description", def.description);
1025 getstringfield(L, index, "inventory_image", def.inventory_image);
1026 getstringfield(L, index, "wield_image", def.wield_image);
1028 lua_getfield(L, index, "wield_scale");
1029 if(lua_istable(L, -1)){
1030 def.wield_scale = check_v3f(L, -1);
1034 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1035 if(def.stack_max == 0)
1038 lua_getfield(L, index, "on_use");
1039 def.usable = lua_isfunction(L, -1);
1042 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1044 warn_if_field_exists(L, index, "tool_digging_properties",
1045 "deprecated: use tool_capabilities");
1047 lua_getfield(L, index, "tool_capabilities");
1048 if(lua_istable(L, -1)){
1049 def.tool_capabilities = new ToolCapabilities(
1050 read_tool_capabilities(L, -1));
1053 // If name is "" (hand), ensure there are ToolCapabilities
1054 // because it will be looked up there whenever any other item has
1055 // no ToolCapabilities
1056 if(def.name == "" && def.tool_capabilities == NULL){
1057 def.tool_capabilities = new ToolCapabilities();
1060 lua_getfield(L, index, "groups");
1061 read_groups(L, -1, def.groups);
1064 // Client shall immediately place this node when player places the item.
1065 // Server will update the precise end result a moment later.
1066 // "" = no prediction
1067 getstringfield(L, index, "node_placement_prediction",
1068 def.node_placement_prediction);
1077 static TileDef read_tiledef(lua_State *L, int index)
1080 index = lua_gettop(L) + 1 + index;
1084 // key at index -2 and value at index
1085 if(lua_isstring(L, index)){
1086 // "default_lava.png"
1087 tiledef.name = lua_tostring(L, index);
1089 else if(lua_istable(L, index))
1091 // {name="default_lava.png", animation={}}
1093 getstringfield(L, index, "name", tiledef.name);
1094 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1095 tiledef.backface_culling = getboolfield_default(
1096 L, index, "backface_culling", true);
1098 lua_getfield(L, index, "animation");
1099 if(lua_istable(L, -1)){
1100 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1101 tiledef.animation.type = (TileAnimationType)
1102 getenumfield(L, -1, "type", es_TileAnimationType,
1104 tiledef.animation.aspect_w =
1105 getintfield_default(L, -1, "aspect_w", 16);
1106 tiledef.animation.aspect_h =
1107 getintfield_default(L, -1, "aspect_h", 16);
1108 tiledef.animation.length =
1109 getfloatfield_default(L, -1, "length", 1.0);
1121 static ContentFeatures read_content_features(lua_State *L, int index)
1124 index = lua_gettop(L) + 1 + index;
1128 /* Cache existence of some callbacks */
1129 lua_getfield(L, index, "on_construct");
1130 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1132 lua_getfield(L, index, "on_destruct");
1133 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1135 lua_getfield(L, index, "after_destruct");
1136 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1140 getstringfield(L, index, "name", f.name);
1143 lua_getfield(L, index, "groups");
1144 read_groups(L, -1, f.groups);
1147 /* Visual definition */
1149 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1151 getfloatfield(L, index, "visual_scale", f.visual_scale);
1154 lua_getfield(L, index, "tiles");
1155 // If nil, try the deprecated name "tile_images" instead
1156 if(lua_isnil(L, -1)){
1158 warn_if_field_exists(L, index, "tile_images",
1159 "Deprecated; new name is \"tiles\".");
1160 lua_getfield(L, index, "tile_images");
1162 if(lua_istable(L, -1)){
1163 int table = lua_gettop(L);
1166 while(lua_next(L, table) != 0){
1167 // Read tiledef from value
1168 f.tiledef[i] = read_tiledef(L, -1);
1169 // removes value, keeps key for next iteration
1177 // Copy last value to all remaining textures
1179 TileDef lasttile = f.tiledef[i-1];
1181 f.tiledef[i] = lasttile;
1188 // special_tiles = {}
1189 lua_getfield(L, index, "special_tiles");
1190 // If nil, try the deprecated name "special_materials" instead
1191 if(lua_isnil(L, -1)){
1193 warn_if_field_exists(L, index, "special_materials",
1194 "Deprecated; new name is \"special_tiles\".");
1195 lua_getfield(L, index, "special_materials");
1197 if(lua_istable(L, -1)){
1198 int table = lua_gettop(L);
1201 while(lua_next(L, table) != 0){
1202 // Read tiledef from value
1203 f.tiledef_special[i] = read_tiledef(L, -1);
1204 // removes value, keeps key for next iteration
1215 f.alpha = getintfield_default(L, index, "alpha", 255);
1219 lua_getfield(L, index, "post_effect_color");
1220 if(!lua_isnil(L, -1))
1221 f.post_effect_color = readARGB8(L, -1);
1224 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1225 es_ContentParamType, CPT_NONE);
1226 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1227 es_ContentParamType2, CPT2_NONE);
1229 // Warn about some deprecated fields
1230 warn_if_field_exists(L, index, "wall_mounted",
1231 "deprecated: use paramtype2 = 'wallmounted'");
1232 warn_if_field_exists(L, index, "light_propagates",
1233 "deprecated: determined from paramtype");
1234 warn_if_field_exists(L, index, "dug_item",
1235 "deprecated: use 'drop' field");
1236 warn_if_field_exists(L, index, "extra_dug_item",
1237 "deprecated: use 'drop' field");
1238 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1239 "deprecated: use 'drop' field");
1240 warn_if_field_exists(L, index, "metadata_name",
1241 "deprecated: use on_add and metadata callbacks");
1243 // True for all ground-like things like stone and mud, false for eg. trees
1244 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1245 f.light_propagates = (f.param_type == CPT_LIGHT);
1246 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1247 // This is used for collision detection.
1248 // Also for general solidness queries.
1249 getboolfield(L, index, "walkable", f.walkable);
1250 // Player can point to these
1251 getboolfield(L, index, "pointable", f.pointable);
1252 // Player can dig these
1253 getboolfield(L, index, "diggable", f.diggable);
1254 // Player can climb these
1255 getboolfield(L, index, "climbable", f.climbable);
1256 // Player can build on these
1257 getboolfield(L, index, "buildable_to", f.buildable_to);
1258 // Whether the node is non-liquid, source liquid or flowing liquid
1259 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1260 es_LiquidType, LIQUID_NONE);
1261 // If the content is liquid, this is the flowing version of the liquid.
1262 getstringfield(L, index, "liquid_alternative_flowing",
1263 f.liquid_alternative_flowing);
1264 // If the content is liquid, this is the source version of the liquid.
1265 getstringfield(L, index, "liquid_alternative_source",
1266 f.liquid_alternative_source);
1267 // Viscosity for fluid flow, ranging from 1 to 7, with
1268 // 1 giving almost instantaneous propagation and 7 being
1269 // the slowest possible
1270 f.liquid_viscosity = getintfield_default(L, index,
1271 "liquid_viscosity", f.liquid_viscosity);
1272 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1273 // Amount of light the node emits
1274 f.light_source = getintfield_default(L, index,
1275 "light_source", f.light_source);
1276 f.damage_per_second = getintfield_default(L, index,
1277 "damage_per_second", f.damage_per_second);
1279 lua_getfield(L, index, "node_box");
1280 if(lua_istable(L, -1))
1281 f.node_box = read_nodebox(L, -1);
1284 lua_getfield(L, index, "selection_box");
1285 if(lua_istable(L, -1))
1286 f.selection_box = read_nodebox(L, -1);
1289 // Set to true if paramtype used to be 'facedir_simple'
1290 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1291 // Set to true if wall_mounted used to be set to true
1292 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1295 lua_getfield(L, index, "sounds");
1296 if(lua_istable(L, -1)){
1297 lua_getfield(L, -1, "footstep");
1298 read_soundspec(L, -1, f.sound_footstep);
1300 lua_getfield(L, -1, "dig");
1301 read_soundspec(L, -1, f.sound_dig);
1303 lua_getfield(L, -1, "dug");
1304 read_soundspec(L, -1, f.sound_dug);
1316 static ItemStack read_item(lua_State *L, int index);
1317 static std::vector<ItemStack> read_items(lua_State *L, int index);
1318 // creates a table of ItemStacks
1319 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1321 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1322 lua_State *L, int tableindex, int forcesize=-1)
1325 tableindex = lua_gettop(L) + 1 + tableindex;
1326 // If nil, delete list
1327 if(lua_isnil(L, tableindex)){
1328 inv->deleteList(name);
1331 // Otherwise set list
1332 std::vector<ItemStack> items = read_items(L, tableindex);
1333 int listsize = (forcesize != -1) ? forcesize : items.size();
1334 InventoryList *invlist = inv->addList(name, listsize);
1336 for(std::vector<ItemStack>::const_iterator
1337 i = items.begin(); i != items.end(); i++){
1338 if(forcesize != -1 && index == forcesize)
1340 invlist->changeItem(index, *i);
1343 while(forcesize != -1 && index < forcesize){
1344 invlist->deleteItem(index);
1349 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1352 InventoryList *invlist = inv->getList(name);
1353 if(invlist == NULL){
1357 std::vector<ItemStack> items;
1358 for(u32 i=0; i<invlist->getSize(); i++)
1359 items.push_back(invlist->getItem(i));
1360 push_items(L, items);
1364 Helpful macros for userdata classes
1367 #define method(class, name) {#name, class::l_##name}
1378 static const char className[];
1379 static const luaL_reg methods[];
1381 // Exported functions
1383 // garbage collector
1384 static int gc_object(lua_State *L)
1386 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1391 // is_empty(self) -> true/false
1392 static int l_is_empty(lua_State *L)
1394 LuaItemStack *o = checkobject(L, 1);
1395 ItemStack &item = o->m_stack;
1396 lua_pushboolean(L, item.empty());
1400 // get_name(self) -> string
1401 static int l_get_name(lua_State *L)
1403 LuaItemStack *o = checkobject(L, 1);
1404 ItemStack &item = o->m_stack;
1405 lua_pushstring(L, item.name.c_str());
1409 // get_count(self) -> number
1410 static int l_get_count(lua_State *L)
1412 LuaItemStack *o = checkobject(L, 1);
1413 ItemStack &item = o->m_stack;
1414 lua_pushinteger(L, item.count);
1418 // get_wear(self) -> number
1419 static int l_get_wear(lua_State *L)
1421 LuaItemStack *o = checkobject(L, 1);
1422 ItemStack &item = o->m_stack;
1423 lua_pushinteger(L, item.wear);
1427 // get_metadata(self) -> string
1428 static int l_get_metadata(lua_State *L)
1430 LuaItemStack *o = checkobject(L, 1);
1431 ItemStack &item = o->m_stack;
1432 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1436 // clear(self) -> true
1437 static int l_clear(lua_State *L)
1439 LuaItemStack *o = checkobject(L, 1);
1441 lua_pushboolean(L, true);
1445 // replace(self, itemstack or itemstring or table or nil) -> true
1446 static int l_replace(lua_State *L)
1448 LuaItemStack *o = checkobject(L, 1);
1449 o->m_stack = read_item(L, 2);
1450 lua_pushboolean(L, true);
1454 // to_string(self) -> string
1455 static int l_to_string(lua_State *L)
1457 LuaItemStack *o = checkobject(L, 1);
1458 std::string itemstring = o->m_stack.getItemString();
1459 lua_pushstring(L, itemstring.c_str());
1463 // to_table(self) -> table or nil
1464 static int l_to_table(lua_State *L)
1466 LuaItemStack *o = checkobject(L, 1);
1467 const ItemStack &item = o->m_stack;
1475 lua_pushstring(L, item.name.c_str());
1476 lua_setfield(L, -2, "name");
1477 lua_pushinteger(L, item.count);
1478 lua_setfield(L, -2, "count");
1479 lua_pushinteger(L, item.wear);
1480 lua_setfield(L, -2, "wear");
1481 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1482 lua_setfield(L, -2, "metadata");
1487 // get_stack_max(self) -> number
1488 static int l_get_stack_max(lua_State *L)
1490 LuaItemStack *o = checkobject(L, 1);
1491 ItemStack &item = o->m_stack;
1492 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1496 // get_free_space(self) -> number
1497 static int l_get_free_space(lua_State *L)
1499 LuaItemStack *o = checkobject(L, 1);
1500 ItemStack &item = o->m_stack;
1501 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1505 // is_known(self) -> true/false
1506 // Checks if the item is defined.
1507 static int l_is_known(lua_State *L)
1509 LuaItemStack *o = checkobject(L, 1);
1510 ItemStack &item = o->m_stack;
1511 bool is_known = item.isKnown(get_server(L)->idef());
1512 lua_pushboolean(L, is_known);
1516 // get_definition(self) -> table
1517 // Returns the item definition table from minetest.registered_items,
1518 // or a fallback one (name="unknown")
1519 static int l_get_definition(lua_State *L)
1521 LuaItemStack *o = checkobject(L, 1);
1522 ItemStack &item = o->m_stack;
1524 // Get minetest.registered_items[name]
1525 lua_getglobal(L, "minetest");
1526 lua_getfield(L, -1, "registered_items");
1527 luaL_checktype(L, -1, LUA_TTABLE);
1528 lua_getfield(L, -1, item.name.c_str());
1529 if(lua_isnil(L, -1))
1532 lua_getfield(L, -1, "unknown");
1537 // get_tool_capabilities(self) -> table
1538 // Returns the effective tool digging properties.
1539 // Returns those of the hand ("") if this item has none associated.
1540 static int l_get_tool_capabilities(lua_State *L)
1542 LuaItemStack *o = checkobject(L, 1);
1543 ItemStack &item = o->m_stack;
1544 const ToolCapabilities &prop =
1545 item.getToolCapabilities(get_server(L)->idef());
1546 push_tool_capabilities(L, prop);
1550 // add_wear(self, amount) -> true/false
1551 // The range for "amount" is [0,65535]. Wear is only added if the item
1552 // is a tool. Adding wear might destroy the item.
1553 // Returns true if the item is (or was) a tool.
1554 static int l_add_wear(lua_State *L)
1556 LuaItemStack *o = checkobject(L, 1);
1557 ItemStack &item = o->m_stack;
1558 int amount = lua_tointeger(L, 2);
1559 bool result = item.addWear(amount, get_server(L)->idef());
1560 lua_pushboolean(L, result);
1564 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1565 // Returns leftover item stack
1566 static int l_add_item(lua_State *L)
1568 LuaItemStack *o = checkobject(L, 1);
1569 ItemStack &item = o->m_stack;
1570 ItemStack newitem = read_item(L, 2);
1571 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1572 create(L, leftover);
1576 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1577 // First return value is true iff the new item fits fully into the stack
1578 // Second return value is the would-be-left-over item stack
1579 static int l_item_fits(lua_State *L)
1581 LuaItemStack *o = checkobject(L, 1);
1582 ItemStack &item = o->m_stack;
1583 ItemStack newitem = read_item(L, 2);
1585 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1586 lua_pushboolean(L, fits); // first return value
1587 create(L, restitem); // second return value
1591 // take_item(self, takecount=1) -> itemstack
1592 static int l_take_item(lua_State *L)
1594 LuaItemStack *o = checkobject(L, 1);
1595 ItemStack &item = o->m_stack;
1597 if(!lua_isnone(L, 2))
1598 takecount = luaL_checkinteger(L, 2);
1599 ItemStack taken = item.takeItem(takecount);
1604 // peek_item(self, peekcount=1) -> itemstack
1605 static int l_peek_item(lua_State *L)
1607 LuaItemStack *o = checkobject(L, 1);
1608 ItemStack &item = o->m_stack;
1610 if(!lua_isnone(L, 2))
1611 peekcount = lua_tointeger(L, 2);
1612 ItemStack peekaboo = item.peekItem(peekcount);
1613 create(L, peekaboo);
1618 LuaItemStack(const ItemStack &item):
1627 const ItemStack& getItem() const
1631 ItemStack& getItem()
1636 // LuaItemStack(itemstack or itemstring or table or nil)
1637 // Creates an LuaItemStack and leaves it on top of stack
1638 static int create_object(lua_State *L)
1640 ItemStack item = read_item(L, 1);
1641 LuaItemStack *o = new LuaItemStack(item);
1642 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1643 luaL_getmetatable(L, className);
1644 lua_setmetatable(L, -2);
1647 // Not callable from Lua
1648 static int create(lua_State *L, const ItemStack &item)
1650 LuaItemStack *o = new LuaItemStack(item);
1651 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1652 luaL_getmetatable(L, className);
1653 lua_setmetatable(L, -2);
1657 static LuaItemStack* checkobject(lua_State *L, int narg)
1659 luaL_checktype(L, narg, LUA_TUSERDATA);
1660 void *ud = luaL_checkudata(L, narg, className);
1661 if(!ud) luaL_typerror(L, narg, className);
1662 return *(LuaItemStack**)ud; // unbox pointer
1665 static void Register(lua_State *L)
1668 int methodtable = lua_gettop(L);
1669 luaL_newmetatable(L, className);
1670 int metatable = lua_gettop(L);
1672 lua_pushliteral(L, "__metatable");
1673 lua_pushvalue(L, methodtable);
1674 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1676 lua_pushliteral(L, "__index");
1677 lua_pushvalue(L, methodtable);
1678 lua_settable(L, metatable);
1680 lua_pushliteral(L, "__gc");
1681 lua_pushcfunction(L, gc_object);
1682 lua_settable(L, metatable);
1684 lua_pop(L, 1); // drop metatable
1686 luaL_openlib(L, 0, methods, 0); // fill methodtable
1687 lua_pop(L, 1); // drop methodtable
1689 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1690 lua_register(L, className, create_object);
1693 const char LuaItemStack::className[] = "ItemStack";
1694 const luaL_reg LuaItemStack::methods[] = {
1695 method(LuaItemStack, is_empty),
1696 method(LuaItemStack, get_name),
1697 method(LuaItemStack, get_count),
1698 method(LuaItemStack, get_wear),
1699 method(LuaItemStack, get_metadata),
1700 method(LuaItemStack, clear),
1701 method(LuaItemStack, replace),
1702 method(LuaItemStack, to_string),
1703 method(LuaItemStack, to_table),
1704 method(LuaItemStack, get_stack_max),
1705 method(LuaItemStack, get_free_space),
1706 method(LuaItemStack, is_known),
1707 method(LuaItemStack, get_definition),
1708 method(LuaItemStack, get_tool_capabilities),
1709 method(LuaItemStack, add_wear),
1710 method(LuaItemStack, add_item),
1711 method(LuaItemStack, item_fits),
1712 method(LuaItemStack, take_item),
1713 method(LuaItemStack, peek_item),
1717 static ItemStack read_item(lua_State *L, int index)
1720 index = lua_gettop(L) + 1 + index;
1722 if(lua_isnil(L, index))
1726 else if(lua_isuserdata(L, index))
1728 // Convert from LuaItemStack
1729 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1730 return o->getItem();
1732 else if(lua_isstring(L, index))
1734 // Convert from itemstring
1735 std::string itemstring = lua_tostring(L, index);
1736 IItemDefManager *idef = get_server(L)->idef();
1740 item.deSerialize(itemstring, idef);
1743 catch(SerializationError &e)
1745 infostream<<"WARNING: unable to create item from itemstring"
1746 <<": "<<itemstring<<std::endl;
1750 else if(lua_istable(L, index))
1752 // Convert from table
1753 IItemDefManager *idef = get_server(L)->idef();
1754 std::string name = getstringfield_default(L, index, "name", "");
1755 int count = getintfield_default(L, index, "count", 1);
1756 int wear = getintfield_default(L, index, "wear", 0);
1757 std::string metadata = getstringfield_default(L, index, "metadata", "");
1758 return ItemStack(name, count, wear, metadata, idef);
1762 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1766 static std::vector<ItemStack> read_items(lua_State *L, int index)
1769 index = lua_gettop(L) + 1 + index;
1771 std::vector<ItemStack> items;
1772 luaL_checktype(L, index, LUA_TTABLE);
1774 while(lua_next(L, index) != 0){
1775 // key at index -2 and value at index -1
1776 items.push_back(read_item(L, -1));
1777 // removes value, keeps key for next iteration
1783 // creates a table of ItemStacks
1784 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1786 // Get the table insert function
1787 lua_getglobal(L, "table");
1788 lua_getfield(L, -1, "insert");
1789 int table_insert = lua_gettop(L);
1790 // Create and fill table
1792 int table = lua_gettop(L);
1793 for(u32 i=0; i<items.size(); i++){
1794 ItemStack item = items[i];
1795 lua_pushvalue(L, table_insert);
1796 lua_pushvalue(L, table);
1797 LuaItemStack::create(L, item);
1798 if(lua_pcall(L, 2, 0, 0))
1799 script_error(L, "error: %s", lua_tostring(L, -1));
1801 lua_remove(L, -2); // Remove table
1802 lua_remove(L, -2); // Remove insert
1812 InventoryLocation m_loc;
1814 static const char className[];
1815 static const luaL_reg methods[];
1817 static InvRef *checkobject(lua_State *L, int narg)
1819 luaL_checktype(L, narg, LUA_TUSERDATA);
1820 void *ud = luaL_checkudata(L, narg, className);
1821 if(!ud) luaL_typerror(L, narg, className);
1822 return *(InvRef**)ud; // unbox pointer
1825 static Inventory* getinv(lua_State *L, InvRef *ref)
1827 return get_server(L)->getInventory(ref->m_loc);
1830 static InventoryList* getlist(lua_State *L, InvRef *ref,
1831 const char *listname)
1833 Inventory *inv = getinv(L, ref);
1836 return inv->getList(listname);
1839 static void reportInventoryChange(lua_State *L, InvRef *ref)
1841 // Inform other things that the inventory has changed
1842 get_server(L)->setInventoryModified(ref->m_loc);
1845 // Exported functions
1847 // garbage collector
1848 static int gc_object(lua_State *L) {
1849 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1854 // is_empty(self, listname) -> true/false
1855 static int l_is_empty(lua_State *L)
1857 InvRef *ref = checkobject(L, 1);
1858 const char *listname = luaL_checkstring(L, 2);
1859 InventoryList *list = getlist(L, ref, listname);
1860 if(list && list->getUsedSlots() > 0){
1861 lua_pushboolean(L, false);
1863 lua_pushboolean(L, true);
1868 // get_size(self, listname)
1869 static int l_get_size(lua_State *L)
1871 InvRef *ref = checkobject(L, 1);
1872 const char *listname = luaL_checkstring(L, 2);
1873 InventoryList *list = getlist(L, ref, listname);
1875 lua_pushinteger(L, list->getSize());
1877 lua_pushinteger(L, 0);
1882 // get_width(self, listname)
1883 static int l_get_width(lua_State *L)
1885 InvRef *ref = checkobject(L, 1);
1886 const char *listname = luaL_checkstring(L, 2);
1887 InventoryList *list = getlist(L, ref, listname);
1889 lua_pushinteger(L, list->getWidth());
1891 lua_pushinteger(L, 0);
1896 // set_size(self, listname, size)
1897 static int l_set_size(lua_State *L)
1899 InvRef *ref = checkobject(L, 1);
1900 const char *listname = luaL_checkstring(L, 2);
1901 int newsize = luaL_checknumber(L, 3);
1902 Inventory *inv = getinv(L, ref);
1904 inv->deleteList(listname);
1905 reportInventoryChange(L, ref);
1908 InventoryList *list = inv->getList(listname);
1910 list->setSize(newsize);
1912 list = inv->addList(listname, newsize);
1914 reportInventoryChange(L, ref);
1918 // set_width(self, listname, size)
1919 static int l_set_width(lua_State *L)
1921 InvRef *ref = checkobject(L, 1);
1922 const char *listname = luaL_checkstring(L, 2);
1923 int newwidth = luaL_checknumber(L, 3);
1924 Inventory *inv = getinv(L, ref);
1925 InventoryList *list = inv->getList(listname);
1927 list->setWidth(newwidth);
1931 reportInventoryChange(L, ref);
1935 // get_stack(self, listname, i) -> itemstack
1936 static int l_get_stack(lua_State *L)
1938 InvRef *ref = checkobject(L, 1);
1939 const char *listname = luaL_checkstring(L, 2);
1940 int i = luaL_checknumber(L, 3) - 1;
1941 InventoryList *list = getlist(L, ref, listname);
1943 if(list != NULL && i >= 0 && i < (int) list->getSize())
1944 item = list->getItem(i);
1945 LuaItemStack::create(L, item);
1949 // set_stack(self, listname, i, stack) -> true/false
1950 static int l_set_stack(lua_State *L)
1952 InvRef *ref = checkobject(L, 1);
1953 const char *listname = luaL_checkstring(L, 2);
1954 int i = luaL_checknumber(L, 3) - 1;
1955 ItemStack newitem = read_item(L, 4);
1956 InventoryList *list = getlist(L, ref, listname);
1957 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1958 list->changeItem(i, newitem);
1959 reportInventoryChange(L, ref);
1960 lua_pushboolean(L, true);
1962 lua_pushboolean(L, false);
1967 // get_list(self, listname) -> list or nil
1968 static int l_get_list(lua_State *L)
1970 InvRef *ref = checkobject(L, 1);
1971 const char *listname = luaL_checkstring(L, 2);
1972 Inventory *inv = getinv(L, ref);
1973 inventory_get_list_to_lua(inv, listname, L);
1977 // set_list(self, listname, list)
1978 static int l_set_list(lua_State *L)
1980 InvRef *ref = checkobject(L, 1);
1981 const char *listname = luaL_checkstring(L, 2);
1982 Inventory *inv = getinv(L, ref);
1983 InventoryList *list = inv->getList(listname);
1985 inventory_set_list_from_lua(inv, listname, L, 3,
1988 inventory_set_list_from_lua(inv, listname, L, 3);
1989 reportInventoryChange(L, ref);
1993 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1994 // Returns the leftover stack
1995 static int l_add_item(lua_State *L)
1997 InvRef *ref = checkobject(L, 1);
1998 const char *listname = luaL_checkstring(L, 2);
1999 ItemStack item = read_item(L, 3);
2000 InventoryList *list = getlist(L, ref, listname);
2002 ItemStack leftover = list->addItem(item);
2003 if(leftover.count != item.count)
2004 reportInventoryChange(L, ref);
2005 LuaItemStack::create(L, leftover);
2007 LuaItemStack::create(L, item);
2012 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2013 // Returns true if the item completely fits into the list
2014 static int l_room_for_item(lua_State *L)
2016 InvRef *ref = checkobject(L, 1);
2017 const char *listname = luaL_checkstring(L, 2);
2018 ItemStack item = read_item(L, 3);
2019 InventoryList *list = getlist(L, ref, listname);
2021 lua_pushboolean(L, list->roomForItem(item));
2023 lua_pushboolean(L, false);
2028 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2029 // Returns true if the list contains the given count of the given item name
2030 static int l_contains_item(lua_State *L)
2032 InvRef *ref = checkobject(L, 1);
2033 const char *listname = luaL_checkstring(L, 2);
2034 ItemStack item = read_item(L, 3);
2035 InventoryList *list = getlist(L, ref, listname);
2037 lua_pushboolean(L, list->containsItem(item));
2039 lua_pushboolean(L, false);
2044 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2045 // Returns the items that were actually removed
2046 static int l_remove_item(lua_State *L)
2048 InvRef *ref = checkobject(L, 1);
2049 const char *listname = luaL_checkstring(L, 2);
2050 ItemStack item = read_item(L, 3);
2051 InventoryList *list = getlist(L, ref, listname);
2053 ItemStack removed = list->removeItem(item);
2054 if(!removed.empty())
2055 reportInventoryChange(L, ref);
2056 LuaItemStack::create(L, removed);
2058 LuaItemStack::create(L, ItemStack());
2063 // get_location() -> location (like minetest.get_inventory(location))
2064 static int l_get_location(lua_State *L)
2066 InvRef *ref = checkobject(L, 1);
2067 const InventoryLocation &loc = ref->m_loc;
2069 case InventoryLocation::PLAYER:
2071 lua_pushstring(L, "player");
2072 lua_setfield(L, -2, "type");
2073 lua_pushstring(L, loc.name.c_str());
2074 lua_setfield(L, -2, "name");
2076 case InventoryLocation::NODEMETA:
2078 lua_pushstring(L, "nodemeta");
2079 lua_setfield(L, -2, "type");
2080 push_v3s16(L, loc.p);
2081 lua_setfield(L, -2, "name");
2083 case InventoryLocation::DETACHED:
2085 lua_pushstring(L, "detached");
2086 lua_setfield(L, -2, "type");
2087 lua_pushstring(L, loc.name.c_str());
2088 lua_setfield(L, -2, "name");
2090 case InventoryLocation::UNDEFINED:
2091 case InventoryLocation::CURRENT_PLAYER:
2095 lua_pushstring(L, "undefined");
2096 lua_setfield(L, -2, "type");
2101 InvRef(const InventoryLocation &loc):
2110 // Creates an InvRef and leaves it on top of stack
2111 // Not callable from Lua; all references are created on the C side.
2112 static void create(lua_State *L, const InventoryLocation &loc)
2114 InvRef *o = new InvRef(loc);
2115 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2116 luaL_getmetatable(L, className);
2117 lua_setmetatable(L, -2);
2119 static void createPlayer(lua_State *L, Player *player)
2121 InventoryLocation loc;
2122 loc.setPlayer(player->getName());
2125 static void createNodeMeta(lua_State *L, v3s16 p)
2127 InventoryLocation loc;
2132 static void Register(lua_State *L)
2135 int methodtable = lua_gettop(L);
2136 luaL_newmetatable(L, className);
2137 int metatable = lua_gettop(L);
2139 lua_pushliteral(L, "__metatable");
2140 lua_pushvalue(L, methodtable);
2141 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2143 lua_pushliteral(L, "__index");
2144 lua_pushvalue(L, methodtable);
2145 lua_settable(L, metatable);
2147 lua_pushliteral(L, "__gc");
2148 lua_pushcfunction(L, gc_object);
2149 lua_settable(L, metatable);
2151 lua_pop(L, 1); // drop metatable
2153 luaL_openlib(L, 0, methods, 0); // fill methodtable
2154 lua_pop(L, 1); // drop methodtable
2156 // Cannot be created from Lua
2157 //lua_register(L, className, create_object);
2160 const char InvRef::className[] = "InvRef";
2161 const luaL_reg InvRef::methods[] = {
2162 method(InvRef, is_empty),
2163 method(InvRef, get_size),
2164 method(InvRef, set_size),
2165 method(InvRef, get_width),
2166 method(InvRef, set_width),
2167 method(InvRef, get_stack),
2168 method(InvRef, set_stack),
2169 method(InvRef, get_list),
2170 method(InvRef, set_list),
2171 method(InvRef, add_item),
2172 method(InvRef, room_for_item),
2173 method(InvRef, contains_item),
2174 method(InvRef, remove_item),
2175 method(InvRef, get_location),
2187 ServerEnvironment *m_env;
2189 static const char className[];
2190 static const luaL_reg methods[];
2192 static NodeMetaRef *checkobject(lua_State *L, int narg)
2194 luaL_checktype(L, narg, LUA_TUSERDATA);
2195 void *ud = luaL_checkudata(L, narg, className);
2196 if(!ud) luaL_typerror(L, narg, className);
2197 return *(NodeMetaRef**)ud; // unbox pointer
2200 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2202 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2203 if(meta == NULL && auto_create)
2205 meta = new NodeMetadata(ref->m_env->getGameDef());
2206 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2211 static void reportMetadataChange(NodeMetaRef *ref)
2213 // NOTE: This same code is in rollback_interface.cpp
2214 // Inform other things that the metadata has changed
2215 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2217 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2219 ref->m_env->getMap().dispatchEvent(&event);
2220 // Set the block to be saved
2221 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2223 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2224 "NodeMetaRef::reportMetadataChange");
2227 // Exported functions
2229 // garbage collector
2230 static int gc_object(lua_State *L) {
2231 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2236 // get_string(self, name)
2237 static int l_get_string(lua_State *L)
2239 NodeMetaRef *ref = checkobject(L, 1);
2240 std::string name = luaL_checkstring(L, 2);
2242 NodeMetadata *meta = getmeta(ref, false);
2244 lua_pushlstring(L, "", 0);
2247 std::string str = meta->getString(name);
2248 lua_pushlstring(L, str.c_str(), str.size());
2252 // set_string(self, name, var)
2253 static int l_set_string(lua_State *L)
2255 NodeMetaRef *ref = checkobject(L, 1);
2256 std::string name = luaL_checkstring(L, 2);
2258 const char *s = lua_tolstring(L, 3, &len);
2259 std::string str(s, len);
2261 NodeMetadata *meta = getmeta(ref, !str.empty());
2262 if(meta == NULL || str == meta->getString(name))
2264 meta->setString(name, str);
2265 reportMetadataChange(ref);
2269 // get_int(self, name)
2270 static int l_get_int(lua_State *L)
2272 NodeMetaRef *ref = checkobject(L, 1);
2273 std::string name = lua_tostring(L, 2);
2275 NodeMetadata *meta = getmeta(ref, false);
2277 lua_pushnumber(L, 0);
2280 std::string str = meta->getString(name);
2281 lua_pushnumber(L, stoi(str));
2285 // set_int(self, name, var)
2286 static int l_set_int(lua_State *L)
2288 NodeMetaRef *ref = checkobject(L, 1);
2289 std::string name = lua_tostring(L, 2);
2290 int a = lua_tointeger(L, 3);
2291 std::string str = itos(a);
2293 NodeMetadata *meta = getmeta(ref, true);
2294 if(meta == NULL || str == meta->getString(name))
2296 meta->setString(name, str);
2297 reportMetadataChange(ref);
2301 // get_float(self, name)
2302 static int l_get_float(lua_State *L)
2304 NodeMetaRef *ref = checkobject(L, 1);
2305 std::string name = lua_tostring(L, 2);
2307 NodeMetadata *meta = getmeta(ref, false);
2309 lua_pushnumber(L, 0);
2312 std::string str = meta->getString(name);
2313 lua_pushnumber(L, stof(str));
2317 // set_float(self, name, var)
2318 static int l_set_float(lua_State *L)
2320 NodeMetaRef *ref = checkobject(L, 1);
2321 std::string name = lua_tostring(L, 2);
2322 float a = lua_tonumber(L, 3);
2323 std::string str = ftos(a);
2325 NodeMetadata *meta = getmeta(ref, true);
2326 if(meta == NULL || str == meta->getString(name))
2328 meta->setString(name, str);
2329 reportMetadataChange(ref);
2333 // get_inventory(self)
2334 static int l_get_inventory(lua_State *L)
2336 NodeMetaRef *ref = checkobject(L, 1);
2337 getmeta(ref, true); // try to ensure the metadata exists
2338 InvRef::createNodeMeta(L, ref->m_p);
2343 static int l_to_table(lua_State *L)
2345 NodeMetaRef *ref = checkobject(L, 1);
2347 NodeMetadata *meta = getmeta(ref, true);
2356 std::map<std::string, std::string> fields = meta->getStrings();
2357 for(std::map<std::string, std::string>::const_iterator
2358 i = fields.begin(); i != fields.end(); i++){
2359 const std::string &name = i->first;
2360 const std::string &value = i->second;
2361 lua_pushlstring(L, name.c_str(), name.size());
2362 lua_pushlstring(L, value.c_str(), value.size());
2363 lua_settable(L, -3);
2366 lua_setfield(L, -2, "fields");
2369 Inventory *inv = meta->getInventory();
2371 std::vector<const InventoryList*> lists = inv->getLists();
2372 for(std::vector<const InventoryList*>::const_iterator
2373 i = lists.begin(); i != lists.end(); i++){
2374 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2375 lua_setfield(L, -2, (*i)->getName().c_str());
2378 lua_setfield(L, -2, "inventory");
2382 // from_table(self, table)
2383 static int l_from_table(lua_State *L)
2385 NodeMetaRef *ref = checkobject(L, 1);
2388 if(lua_isnil(L, base)){
2390 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2391 lua_pushboolean(L, true);
2395 // Has metadata; clear old one first
2396 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2397 // Create new metadata
2398 NodeMetadata *meta = getmeta(ref, true);
2400 lua_getfield(L, base, "fields");
2401 int fieldstable = lua_gettop(L);
2403 while(lua_next(L, fieldstable) != 0){
2404 // key at index -2 and value at index -1
2405 std::string name = lua_tostring(L, -2);
2407 const char *cs = lua_tolstring(L, -1, &cl);
2408 std::string value(cs, cl);
2409 meta->setString(name, value);
2410 lua_pop(L, 1); // removes value, keeps key for next iteration
2413 Inventory *inv = meta->getInventory();
2414 lua_getfield(L, base, "inventory");
2415 int inventorytable = lua_gettop(L);
2417 while(lua_next(L, inventorytable) != 0){
2418 // key at index -2 and value at index -1
2419 std::string name = lua_tostring(L, -2);
2420 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2421 lua_pop(L, 1); // removes value, keeps key for next iteration
2423 reportMetadataChange(ref);
2424 lua_pushboolean(L, true);
2429 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2439 // Creates an NodeMetaRef and leaves it on top of stack
2440 // Not callable from Lua; all references are created on the C side.
2441 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2443 NodeMetaRef *o = new NodeMetaRef(p, env);
2444 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2445 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2446 luaL_getmetatable(L, className);
2447 lua_setmetatable(L, -2);
2450 static void Register(lua_State *L)
2453 int methodtable = lua_gettop(L);
2454 luaL_newmetatable(L, className);
2455 int metatable = lua_gettop(L);
2457 lua_pushliteral(L, "__metatable");
2458 lua_pushvalue(L, methodtable);
2459 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2461 lua_pushliteral(L, "__index");
2462 lua_pushvalue(L, methodtable);
2463 lua_settable(L, metatable);
2465 lua_pushliteral(L, "__gc");
2466 lua_pushcfunction(L, gc_object);
2467 lua_settable(L, metatable);
2469 lua_pop(L, 1); // drop metatable
2471 luaL_openlib(L, 0, methods, 0); // fill methodtable
2472 lua_pop(L, 1); // drop methodtable
2474 // Cannot be created from Lua
2475 //lua_register(L, className, create_object);
2478 const char NodeMetaRef::className[] = "NodeMetaRef";
2479 const luaL_reg NodeMetaRef::methods[] = {
2480 method(NodeMetaRef, get_string),
2481 method(NodeMetaRef, set_string),
2482 method(NodeMetaRef, get_int),
2483 method(NodeMetaRef, set_int),
2484 method(NodeMetaRef, get_float),
2485 method(NodeMetaRef, set_float),
2486 method(NodeMetaRef, get_inventory),
2487 method(NodeMetaRef, to_table),
2488 method(NodeMetaRef, from_table),
2499 ServerActiveObject *m_object;
2501 static const char className[];
2502 static const luaL_reg methods[];
2504 static ObjectRef *checkobject(lua_State *L, int narg)
2506 luaL_checktype(L, narg, LUA_TUSERDATA);
2507 void *ud = luaL_checkudata(L, narg, className);
2508 if(!ud) luaL_typerror(L, narg, className);
2509 return *(ObjectRef**)ud; // unbox pointer
2512 static ServerActiveObject* getobject(ObjectRef *ref)
2514 ServerActiveObject *co = ref->m_object;
2518 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2520 ServerActiveObject *obj = getobject(ref);
2523 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2525 return (LuaEntitySAO*)obj;
2528 static PlayerSAO* getplayersao(ObjectRef *ref)
2530 ServerActiveObject *obj = getobject(ref);
2533 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2535 return (PlayerSAO*)obj;
2538 static Player* getplayer(ObjectRef *ref)
2540 PlayerSAO *playersao = getplayersao(ref);
2541 if(playersao == NULL)
2543 return playersao->getPlayer();
2546 // Exported functions
2548 // garbage collector
2549 static int gc_object(lua_State *L) {
2550 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2551 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2557 static int l_remove(lua_State *L)
2559 ObjectRef *ref = checkobject(L, 1);
2560 ServerActiveObject *co = getobject(ref);
2561 if(co == NULL) return 0;
2562 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2563 co->m_removed = true;
2568 // returns: {x=num, y=num, z=num}
2569 static int l_getpos(lua_State *L)
2571 ObjectRef *ref = checkobject(L, 1);
2572 ServerActiveObject *co = getobject(ref);
2573 if(co == NULL) return 0;
2574 v3f pos = co->getBasePosition() / BS;
2576 lua_pushnumber(L, pos.X);
2577 lua_setfield(L, -2, "x");
2578 lua_pushnumber(L, pos.Y);
2579 lua_setfield(L, -2, "y");
2580 lua_pushnumber(L, pos.Z);
2581 lua_setfield(L, -2, "z");
2585 // setpos(self, pos)
2586 static int l_setpos(lua_State *L)
2588 ObjectRef *ref = checkobject(L, 1);
2589 //LuaEntitySAO *co = getluaobject(ref);
2590 ServerActiveObject *co = getobject(ref);
2591 if(co == NULL) return 0;
2593 v3f pos = checkFloatPos(L, 2);
2599 // moveto(self, pos, continuous=false)
2600 static int l_moveto(lua_State *L)
2602 ObjectRef *ref = checkobject(L, 1);
2603 //LuaEntitySAO *co = getluaobject(ref);
2604 ServerActiveObject *co = getobject(ref);
2605 if(co == NULL) return 0;
2607 v3f pos = checkFloatPos(L, 2);
2609 bool continuous = lua_toboolean(L, 3);
2611 co->moveTo(pos, continuous);
2615 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2616 static int l_punch(lua_State *L)
2618 ObjectRef *ref = checkobject(L, 1);
2619 ObjectRef *puncher_ref = checkobject(L, 2);
2620 ServerActiveObject *co = getobject(ref);
2621 ServerActiveObject *puncher = getobject(puncher_ref);
2622 if(co == NULL) return 0;
2623 if(puncher == NULL) return 0;
2625 if(lua_type(L, 5) != LUA_TTABLE)
2626 dir = co->getBasePosition() - puncher->getBasePosition();
2628 dir = read_v3f(L, 5);
2629 float time_from_last_punch = 1000000;
2630 if(lua_isnumber(L, 3))
2631 time_from_last_punch = lua_tonumber(L, 3);
2632 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2635 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2639 // right_click(self, clicker); clicker = an another ObjectRef
2640 static int l_right_click(lua_State *L)
2642 ObjectRef *ref = checkobject(L, 1);
2643 ObjectRef *ref2 = checkobject(L, 2);
2644 ServerActiveObject *co = getobject(ref);
2645 ServerActiveObject *co2 = getobject(ref2);
2646 if(co == NULL) return 0;
2647 if(co2 == NULL) return 0;
2649 co->rightClick(co2);
2654 // hp = number of hitpoints (2 * number of hearts)
2656 static int l_set_hp(lua_State *L)
2658 ObjectRef *ref = checkobject(L, 1);
2659 luaL_checknumber(L, 2);
2660 ServerActiveObject *co = getobject(ref);
2661 if(co == NULL) return 0;
2662 int hp = lua_tonumber(L, 2);
2663 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2664 <<" hp="<<hp<<std::endl;*/
2672 // returns: number of hitpoints (2 * number of hearts)
2673 // 0 if not applicable to this type of object
2674 static int l_get_hp(lua_State *L)
2676 ObjectRef *ref = checkobject(L, 1);
2677 ServerActiveObject *co = getobject(ref);
2680 lua_pushnumber(L, 1);
2683 int hp = co->getHP();
2684 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2685 <<" hp="<<hp<<std::endl;*/
2687 lua_pushnumber(L, hp);
2691 // get_inventory(self)
2692 static int l_get_inventory(lua_State *L)
2694 ObjectRef *ref = checkobject(L, 1);
2695 ServerActiveObject *co = getobject(ref);
2696 if(co == NULL) return 0;
2698 InventoryLocation loc = co->getInventoryLocation();
2699 if(get_server(L)->getInventory(loc) != NULL)
2700 InvRef::create(L, loc);
2702 lua_pushnil(L); // An object may have no inventory (nil)
2706 // get_wield_list(self)
2707 static int l_get_wield_list(lua_State *L)
2709 ObjectRef *ref = checkobject(L, 1);
2710 ServerActiveObject *co = getobject(ref);
2711 if(co == NULL) return 0;
2713 lua_pushstring(L, co->getWieldList().c_str());
2717 // get_wield_index(self)
2718 static int l_get_wield_index(lua_State *L)
2720 ObjectRef *ref = checkobject(L, 1);
2721 ServerActiveObject *co = getobject(ref);
2722 if(co == NULL) return 0;
2724 lua_pushinteger(L, co->getWieldIndex() + 1);
2728 // get_wielded_item(self)
2729 static int l_get_wielded_item(lua_State *L)
2731 ObjectRef *ref = checkobject(L, 1);
2732 ServerActiveObject *co = getobject(ref);
2735 LuaItemStack::create(L, ItemStack());
2739 LuaItemStack::create(L, co->getWieldedItem());
2743 // set_wielded_item(self, itemstack or itemstring or table or nil)
2744 static int l_set_wielded_item(lua_State *L)
2746 ObjectRef *ref = checkobject(L, 1);
2747 ServerActiveObject *co = getobject(ref);
2748 if(co == NULL) return 0;
2750 ItemStack item = read_item(L, 2);
2751 bool success = co->setWieldedItem(item);
2752 lua_pushboolean(L, success);
2756 // set_armor_groups(self, groups)
2757 static int l_set_armor_groups(lua_State *L)
2759 ObjectRef *ref = checkobject(L, 1);
2760 ServerActiveObject *co = getobject(ref);
2761 if(co == NULL) return 0;
2763 ItemGroupList groups;
2764 read_groups(L, 2, groups);
2765 co->setArmorGroups(groups);
2769 // set_animation(self, frame_range, frame_speed, frame_blend)
2770 static int l_set_animation(lua_State *L)
2772 ObjectRef *ref = checkobject(L, 1);
2773 ServerActiveObject *co = getobject(ref);
2774 if(co == NULL) return 0;
2776 v2f frames = v2f(1, 1);
2777 if(!lua_isnil(L, 2))
2778 frames = read_v2f(L, 2);
2779 float frame_speed = 15;
2780 if(!lua_isnil(L, 3))
2781 frame_speed = lua_tonumber(L, 3);
2782 float frame_blend = 0;
2783 if(!lua_isnil(L, 4))
2784 frame_blend = lua_tonumber(L, 4);
2785 co->setAnimation(frames, frame_speed, frame_blend);
2789 // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2790 static int l_set_bone_position(lua_State *L)
2792 ObjectRef *ref = checkobject(L, 1);
2793 ServerActiveObject *co = getobject(ref);
2794 if(co == NULL) return 0;
2796 std::string bone = "";
2797 if(!lua_isnil(L, 2))
2798 bone = lua_tostring(L, 2);
2799 v3f position = v3f(0, 0, 0);
2800 if(!lua_isnil(L, 3))
2801 position = read_v3f(L, 3);
2802 v3f rotation = v3f(0, 0, 0);
2803 if(!lua_isnil(L, 4))
2804 rotation = read_v3f(L, 4);
2805 co->setBonePosition(bone, position, rotation);
2809 // set_attach(self, parent, bone, position, rotation)
2810 static int l_set_attach(lua_State *L)
2812 ObjectRef *ref = checkobject(L, 1);
2813 ObjectRef *parent_ref = checkobject(L, 2);
2814 ServerActiveObject *co = getobject(ref);
2815 ServerActiveObject *parent = getobject(parent_ref);
2816 if(co == NULL) return 0;
2817 if(parent == NULL) return 0;
2819 std::string bone = "";
2820 if(!lua_isnil(L, 3))
2821 bone = lua_tostring(L, 3);
2822 v3f position = v3f(0, 0, 0);
2823 if(!lua_isnil(L, 4))
2824 position = read_v3f(L, 4);
2825 v3f rotation = v3f(0, 0, 0);
2826 if(!lua_isnil(L, 5))
2827 rotation = read_v3f(L, 5);
2828 co->setAttachment(parent->getId(), bone, position, rotation);
2833 static int l_set_detach(lua_State *L)
2835 ObjectRef *ref = checkobject(L, 1);
2836 ServerActiveObject *co = getobject(ref);
2837 if(co == NULL) return 0;
2839 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2843 // set_properties(self, properties)
2844 static int l_set_properties(lua_State *L)
2846 ObjectRef *ref = checkobject(L, 1);
2847 ServerActiveObject *co = getobject(ref);
2848 if(co == NULL) return 0;
2849 ObjectProperties *prop = co->accessObjectProperties();
2852 read_object_properties(L, 2, prop);
2853 co->notifyObjectPropertiesModified();
2857 /* LuaEntitySAO-only */
2859 // setvelocity(self, {x=num, y=num, z=num})
2860 static int l_setvelocity(lua_State *L)
2862 ObjectRef *ref = checkobject(L, 1);
2863 LuaEntitySAO *co = getluaobject(ref);
2864 if(co == NULL) return 0;
2865 v3f pos = checkFloatPos(L, 2);
2867 co->setVelocity(pos);
2871 // getvelocity(self)
2872 static int l_getvelocity(lua_State *L)
2874 ObjectRef *ref = checkobject(L, 1);
2875 LuaEntitySAO *co = getluaobject(ref);
2876 if(co == NULL) return 0;
2878 v3f v = co->getVelocity();
2883 // setacceleration(self, {x=num, y=num, z=num})
2884 static int l_setacceleration(lua_State *L)
2886 ObjectRef *ref = checkobject(L, 1);
2887 LuaEntitySAO *co = getluaobject(ref);
2888 if(co == NULL) return 0;
2890 v3f pos = checkFloatPos(L, 2);
2892 co->setAcceleration(pos);
2896 // getacceleration(self)
2897 static int l_getacceleration(lua_State *L)
2899 ObjectRef *ref = checkobject(L, 1);
2900 LuaEntitySAO *co = getluaobject(ref);
2901 if(co == NULL) return 0;
2903 v3f v = co->getAcceleration();
2908 // setyaw(self, radians)
2909 static int l_setyaw(lua_State *L)
2911 ObjectRef *ref = checkobject(L, 1);
2912 LuaEntitySAO *co = getluaobject(ref);
2913 if(co == NULL) return 0;
2914 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2921 static int l_getyaw(lua_State *L)
2923 ObjectRef *ref = checkobject(L, 1);
2924 LuaEntitySAO *co = getluaobject(ref);
2925 if(co == NULL) return 0;
2927 float yaw = co->getYaw() * core::DEGTORAD;
2928 lua_pushnumber(L, yaw);
2932 // settexturemod(self, mod)
2933 static int l_settexturemod(lua_State *L)
2935 ObjectRef *ref = checkobject(L, 1);
2936 LuaEntitySAO *co = getluaobject(ref);
2937 if(co == NULL) return 0;
2939 std::string mod = luaL_checkstring(L, 2);
2940 co->setTextureMod(mod);
2944 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2945 // select_horiz_by_yawpitch=false)
2946 static int l_setsprite(lua_State *L)
2948 ObjectRef *ref = checkobject(L, 1);
2949 LuaEntitySAO *co = getluaobject(ref);
2950 if(co == NULL) return 0;
2953 if(!lua_isnil(L, 2))
2954 p = read_v2s16(L, 2);
2956 if(!lua_isnil(L, 3))
2957 num_frames = lua_tonumber(L, 3);
2958 float framelength = 0.2;
2959 if(!lua_isnil(L, 4))
2960 framelength = lua_tonumber(L, 4);
2961 bool select_horiz_by_yawpitch = false;
2962 if(!lua_isnil(L, 5))
2963 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2964 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2969 // get_entity_name(self)
2970 static int l_get_entity_name(lua_State *L)
2972 ObjectRef *ref = checkobject(L, 1);
2973 LuaEntitySAO *co = getluaobject(ref);
2974 if(co == NULL) return 0;
2976 std::string name = co->getName();
2977 lua_pushstring(L, name.c_str());
2981 // get_luaentity(self)
2982 static int l_get_luaentity(lua_State *L)
2984 ObjectRef *ref = checkobject(L, 1);
2985 LuaEntitySAO *co = getluaobject(ref);
2986 if(co == NULL) return 0;
2988 luaentity_get(L, co->getId());
2995 static int l_is_player(lua_State *L)
2997 ObjectRef *ref = checkobject(L, 1);
2998 Player *player = getplayer(ref);
2999 lua_pushboolean(L, (player != NULL));
3003 // get_player_name(self)
3004 static int l_get_player_name(lua_State *L)
3006 ObjectRef *ref = checkobject(L, 1);
3007 Player *player = getplayer(ref);
3009 lua_pushlstring(L, "", 0);
3013 lua_pushstring(L, player->getName());
3017 // get_look_dir(self)
3018 static int l_get_look_dir(lua_State *L)
3020 ObjectRef *ref = checkobject(L, 1);
3021 Player *player = getplayer(ref);
3022 if(player == NULL) return 0;
3024 float pitch = player->getRadPitch();
3025 float yaw = player->getRadYaw();
3026 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
3031 // get_look_pitch(self)
3032 static int l_get_look_pitch(lua_State *L)
3034 ObjectRef *ref = checkobject(L, 1);
3035 Player *player = getplayer(ref);
3036 if(player == NULL) return 0;
3038 lua_pushnumber(L, player->getRadPitch());
3042 // get_look_yaw(self)
3043 static int l_get_look_yaw(lua_State *L)
3045 ObjectRef *ref = checkobject(L, 1);
3046 Player *player = getplayer(ref);
3047 if(player == NULL) return 0;
3049 lua_pushnumber(L, player->getRadYaw());
3053 // set_inventory_formspec(self, formspec)
3054 static int l_set_inventory_formspec(lua_State *L)
3056 ObjectRef *ref = checkobject(L, 1);
3057 Player *player = getplayer(ref);
3058 if(player == NULL) return 0;
3059 std::string formspec = luaL_checkstring(L, 2);
3061 player->inventory_formspec = formspec;
3062 get_server(L)->reportInventoryFormspecModified(player->getName());
3063 lua_pushboolean(L, true);
3067 // get_inventory_formspec(self) -> formspec
3068 static int l_get_inventory_formspec(lua_State *L)
3070 ObjectRef *ref = checkobject(L, 1);
3071 Player *player = getplayer(ref);
3072 if(player == NULL) return 0;
3074 std::string formspec = player->inventory_formspec;
3075 lua_pushlstring(L, formspec.c_str(), formspec.size());
3079 // get_player_control(self)
3080 static int l_get_player_control(lua_State *L)
3082 ObjectRef *ref = checkobject(L, 1);
3083 Player *player = getplayer(ref);
3085 lua_pushlstring(L, "", 0);
3089 PlayerControl control = player->getPlayerControl();
3091 lua_pushboolean(L, control.up);
3092 lua_setfield(L, -2, "up");
3093 lua_pushboolean(L, control.down);
3094 lua_setfield(L, -2, "down");
3095 lua_pushboolean(L, control.left);
3096 lua_setfield(L, -2, "left");
3097 lua_pushboolean(L, control.right);
3098 lua_setfield(L, -2, "right");
3099 lua_pushboolean(L, control.jump);
3100 lua_setfield(L, -2, "jump");
3101 lua_pushboolean(L, control.aux1);
3102 lua_setfield(L, -2, "aux1");
3103 lua_pushboolean(L, control.sneak);
3104 lua_setfield(L, -2, "sneak");
3105 lua_pushboolean(L, control.LMB);
3106 lua_setfield(L, -2, "LMB");
3107 lua_pushboolean(L, control.RMB);
3108 lua_setfield(L, -2, "RMB");
3112 // get_player_control_bits(self)
3113 static int l_get_player_control_bits(lua_State *L)
3115 ObjectRef *ref = checkobject(L, 1);
3116 Player *player = getplayer(ref);
3118 lua_pushlstring(L, "", 0);
3122 lua_pushnumber(L, player->keyPressed);
3127 ObjectRef(ServerActiveObject *object):
3130 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3136 infostream<<"ObjectRef destructing for id="
3137 <<m_object->getId()<<std::endl;
3139 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3142 // Creates an ObjectRef and leaves it on top of stack
3143 // Not callable from Lua; all references are created on the C side.
3144 static void create(lua_State *L, ServerActiveObject *object)
3146 ObjectRef *o = new ObjectRef(object);
3147 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3148 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3149 luaL_getmetatable(L, className);
3150 lua_setmetatable(L, -2);
3153 static void set_null(lua_State *L)
3155 ObjectRef *o = checkobject(L, -1);
3159 static void Register(lua_State *L)
3162 int methodtable = lua_gettop(L);
3163 luaL_newmetatable(L, className);
3164 int metatable = lua_gettop(L);
3166 lua_pushliteral(L, "__metatable");
3167 lua_pushvalue(L, methodtable);
3168 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3170 lua_pushliteral(L, "__index");
3171 lua_pushvalue(L, methodtable);
3172 lua_settable(L, metatable);
3174 lua_pushliteral(L, "__gc");
3175 lua_pushcfunction(L, gc_object);
3176 lua_settable(L, metatable);
3178 lua_pop(L, 1); // drop metatable
3180 luaL_openlib(L, 0, methods, 0); // fill methodtable
3181 lua_pop(L, 1); // drop methodtable
3183 // Cannot be created from Lua
3184 //lua_register(L, className, create_object);
3187 const char ObjectRef::className[] = "ObjectRef";
3188 const luaL_reg ObjectRef::methods[] = {
3189 // ServerActiveObject
3190 method(ObjectRef, remove),
3191 method(ObjectRef, getpos),
3192 method(ObjectRef, setpos),
3193 method(ObjectRef, moveto),
3194 method(ObjectRef, punch),
3195 method(ObjectRef, right_click),
3196 method(ObjectRef, set_hp),
3197 method(ObjectRef, get_hp),
3198 method(ObjectRef, get_inventory),
3199 method(ObjectRef, get_wield_list),
3200 method(ObjectRef, get_wield_index),
3201 method(ObjectRef, get_wielded_item),
3202 method(ObjectRef, set_wielded_item),
3203 method(ObjectRef, set_armor_groups),
3204 method(ObjectRef, set_animation),
3205 method(ObjectRef, set_bone_position),
3206 method(ObjectRef, set_attach),
3207 method(ObjectRef, set_detach),
3208 method(ObjectRef, set_properties),
3209 // LuaEntitySAO-only
3210 method(ObjectRef, setvelocity),
3211 method(ObjectRef, getvelocity),
3212 method(ObjectRef, setacceleration),
3213 method(ObjectRef, getacceleration),
3214 method(ObjectRef, setyaw),
3215 method(ObjectRef, getyaw),
3216 method(ObjectRef, settexturemod),
3217 method(ObjectRef, setsprite),
3218 method(ObjectRef, get_entity_name),
3219 method(ObjectRef, get_luaentity),
3221 method(ObjectRef, is_player),
3222 method(ObjectRef, get_player_name),
3223 method(ObjectRef, get_look_dir),
3224 method(ObjectRef, get_look_pitch),
3225 method(ObjectRef, get_look_yaw),
3226 method(ObjectRef, set_inventory_formspec),
3227 method(ObjectRef, get_inventory_formspec),
3228 method(ObjectRef, get_player_control),
3229 method(ObjectRef, get_player_control_bits),
3233 // Creates a new anonymous reference if cobj=NULL or id=0
3234 static void objectref_get_or_create(lua_State *L,
3235 ServerActiveObject *cobj)
3237 if(cobj == NULL || cobj->getId() == 0){
3238 ObjectRef::create(L, cobj);
3240 objectref_get(L, cobj->getId());
3249 class LuaPerlinNoise
3256 static const char className[];
3257 static const luaL_reg methods[];
3259 // Exported functions
3261 // garbage collector
3262 static int gc_object(lua_State *L)
3264 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3269 static int l_get2d(lua_State *L)
3271 LuaPerlinNoise *o = checkobject(L, 1);
3272 v2f pos2d = read_v2f(L,2);
3273 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3274 lua_pushnumber(L, val);
3277 static int l_get3d(lua_State *L)
3279 LuaPerlinNoise *o = checkobject(L, 1);
3280 v3f pos3d = read_v3f(L,2);
3281 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3282 lua_pushnumber(L, val);
3287 LuaPerlinNoise(int a_seed, int a_octaves, float a_persistence,
3291 persistence(a_persistence),
3300 // LuaPerlinNoise(seed, octaves, persistence, scale)
3301 // Creates an LuaPerlinNoise and leaves it on top of stack
3302 static int create_object(lua_State *L)
3304 int seed = luaL_checkint(L, 1);
3305 int octaves = luaL_checkint(L, 2);
3306 float persistence = luaL_checknumber(L, 3);
3307 float scale = luaL_checknumber(L, 4);
3308 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3309 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3310 luaL_getmetatable(L, className);
3311 lua_setmetatable(L, -2);
3315 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3317 luaL_checktype(L, narg, LUA_TUSERDATA);
3318 void *ud = luaL_checkudata(L, narg, className);
3319 if(!ud) luaL_typerror(L, narg, className);
3320 return *(LuaPerlinNoise**)ud; // unbox pointer
3323 static void Register(lua_State *L)
3326 int methodtable = lua_gettop(L);
3327 luaL_newmetatable(L, className);
3328 int metatable = lua_gettop(L);
3330 lua_pushliteral(L, "__metatable");
3331 lua_pushvalue(L, methodtable);
3332 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3334 lua_pushliteral(L, "__index");
3335 lua_pushvalue(L, methodtable);
3336 lua_settable(L, metatable);
3338 lua_pushliteral(L, "__gc");
3339 lua_pushcfunction(L, gc_object);
3340 lua_settable(L, metatable);
3342 lua_pop(L, 1); // drop metatable
3344 luaL_openlib(L, 0, methods, 0); // fill methodtable
3345 lua_pop(L, 1); // drop methodtable
3347 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3348 lua_register(L, className, create_object);
3351 const char LuaPerlinNoise::className[] = "PerlinNoise";
3352 const luaL_reg LuaPerlinNoise::methods[] = {
3353 method(LuaPerlinNoise, get2d),
3354 method(LuaPerlinNoise, get3d),
3366 ServerEnvironment *m_env;
3368 static const char className[];
3369 static const luaL_reg methods[];
3371 static int gc_object(lua_State *L) {
3372 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3377 static NodeTimerRef *checkobject(lua_State *L, int narg)
3379 luaL_checktype(L, narg, LUA_TUSERDATA);
3380 void *ud = luaL_checkudata(L, narg, className);
3381 if(!ud) luaL_typerror(L, narg, className);
3382 return *(NodeTimerRef**)ud; // unbox pointer
3385 static int l_set(lua_State *L)
3387 NodeTimerRef *o = checkobject(L, 1);
3388 ServerEnvironment *env = o->m_env;
3389 if(env == NULL) return 0;
3390 f32 t = luaL_checknumber(L,2);
3391 f32 e = luaL_checknumber(L,3);
3392 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3396 static int l_start(lua_State *L)
3398 NodeTimerRef *o = checkobject(L, 1);
3399 ServerEnvironment *env = o->m_env;
3400 if(env == NULL) return 0;
3401 f32 t = luaL_checknumber(L,2);
3402 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3406 static int l_stop(lua_State *L)
3408 NodeTimerRef *o = checkobject(L, 1);
3409 ServerEnvironment *env = o->m_env;
3410 if(env == NULL) return 0;
3411 env->getMap().removeNodeTimer(o->m_p);
3415 static int l_is_started(lua_State *L)
3417 NodeTimerRef *o = checkobject(L, 1);
3418 ServerEnvironment *env = o->m_env;
3419 if(env == NULL) return 0;
3421 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3422 lua_pushboolean(L,(t.timeout != 0));
3426 static int l_get_timeout(lua_State *L)
3428 NodeTimerRef *o = checkobject(L, 1);
3429 ServerEnvironment *env = o->m_env;
3430 if(env == NULL) return 0;
3432 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3433 lua_pushnumber(L,t.timeout);
3437 static int l_get_elapsed(lua_State *L)
3439 NodeTimerRef *o = checkobject(L, 1);
3440 ServerEnvironment *env = o->m_env;
3441 if(env == NULL) return 0;
3443 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3444 lua_pushnumber(L,t.elapsed);
3449 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3459 // Creates an NodeTimerRef and leaves it on top of stack
3460 // Not callable from Lua; all references are created on the C side.
3461 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3463 NodeTimerRef *o = new NodeTimerRef(p, env);
3464 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3465 luaL_getmetatable(L, className);
3466 lua_setmetatable(L, -2);
3469 static void set_null(lua_State *L)
3471 NodeTimerRef *o = checkobject(L, -1);
3475 static void Register(lua_State *L)
3478 int methodtable = lua_gettop(L);
3479 luaL_newmetatable(L, className);
3480 int metatable = lua_gettop(L);
3482 lua_pushliteral(L, "__metatable");
3483 lua_pushvalue(L, methodtable);
3484 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3486 lua_pushliteral(L, "__index");
3487 lua_pushvalue(L, methodtable);
3488 lua_settable(L, metatable);
3490 lua_pushliteral(L, "__gc");
3491 lua_pushcfunction(L, gc_object);
3492 lua_settable(L, metatable);
3494 lua_pop(L, 1); // drop metatable
3496 luaL_openlib(L, 0, methods, 0); // fill methodtable
3497 lua_pop(L, 1); // drop methodtable
3499 // Cannot be created from Lua
3500 //lua_register(L, className, create_object);
3503 const char NodeTimerRef::className[] = "NodeTimerRef";
3504 const luaL_reg NodeTimerRef::methods[] = {
3505 method(NodeTimerRef, start),
3506 method(NodeTimerRef, set),
3507 method(NodeTimerRef, stop),
3508 method(NodeTimerRef, is_started),
3509 method(NodeTimerRef, get_timeout),
3510 method(NodeTimerRef, get_elapsed),
3521 ServerEnvironment *m_env;
3523 static const char className[];
3524 static const luaL_reg methods[];
3526 static int gc_object(lua_State *L) {
3527 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3532 static EnvRef *checkobject(lua_State *L, int narg)
3534 luaL_checktype(L, narg, LUA_TUSERDATA);
3535 void *ud = luaL_checkudata(L, narg, className);
3536 if(!ud) luaL_typerror(L, narg, className);
3537 return *(EnvRef**)ud; // unbox pointer
3540 // Exported functions
3542 // EnvRef:set_node(pos, node)
3543 // pos = {x=num, y=num, z=num}
3544 static int l_set_node(lua_State *L)
3546 EnvRef *o = checkobject(L, 1);
3547 ServerEnvironment *env = o->m_env;
3548 if(env == NULL) return 0;
3549 INodeDefManager *ndef = env->getGameDef()->ndef();
3551 v3s16 pos = read_v3s16(L, 2);
3552 MapNode n = readnode(L, 3, ndef);
3554 bool succeeded = env->setNode(pos, n);
3555 lua_pushboolean(L, succeeded);
3559 static int l_add_node(lua_State *L)
3561 return l_set_node(L);
3564 // EnvRef:remove_node(pos)
3565 // pos = {x=num, y=num, z=num}
3566 static int l_remove_node(lua_State *L)
3568 EnvRef *o = checkobject(L, 1);
3569 ServerEnvironment *env = o->m_env;
3570 if(env == NULL) return 0;
3571 INodeDefManager *ndef = env->getGameDef()->ndef();
3573 v3s16 pos = read_v3s16(L, 2);
3575 bool succeeded = env->removeNode(pos);
3576 lua_pushboolean(L, succeeded);
3580 // EnvRef:get_node(pos)
3581 // pos = {x=num, y=num, z=num}
3582 static int l_get_node(lua_State *L)
3584 EnvRef *o = checkobject(L, 1);
3585 ServerEnvironment *env = o->m_env;
3586 if(env == NULL) return 0;
3588 v3s16 pos = read_v3s16(L, 2);
3590 MapNode n = env->getMap().getNodeNoEx(pos);
3592 pushnode(L, n, env->getGameDef()->ndef());
3596 // EnvRef:get_node_or_nil(pos)
3597 // pos = {x=num, y=num, z=num}
3598 static int l_get_node_or_nil(lua_State *L)
3600 EnvRef *o = checkobject(L, 1);
3601 ServerEnvironment *env = o->m_env;
3602 if(env == NULL) return 0;
3604 v3s16 pos = read_v3s16(L, 2);
3607 MapNode n = env->getMap().getNode(pos);
3609 pushnode(L, n, env->getGameDef()->ndef());
3611 } catch(InvalidPositionException &e)
3618 // EnvRef:get_node_light(pos, timeofday)
3619 // pos = {x=num, y=num, z=num}
3620 // timeofday: nil = current time, 0 = night, 0.5 = day
3621 static int l_get_node_light(lua_State *L)
3623 EnvRef *o = checkobject(L, 1);
3624 ServerEnvironment *env = o->m_env;
3625 if(env == NULL) return 0;
3627 v3s16 pos = read_v3s16(L, 2);
3628 u32 time_of_day = env->getTimeOfDay();
3629 if(lua_isnumber(L, 3))
3630 time_of_day = 24000.0 * lua_tonumber(L, 3);
3631 time_of_day %= 24000;
3632 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3633 MapNode n = env->getMap().getNodeNoEx(pos);
3635 MapNode n = env->getMap().getNode(pos);
3636 INodeDefManager *ndef = env->getGameDef()->ndef();
3637 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3639 } catch(InvalidPositionException &e)
3646 // EnvRef:place_node(pos, node)
3647 // pos = {x=num, y=num, z=num}
3648 static int l_place_node(lua_State *L)
3650 EnvRef *o = checkobject(L, 1);
3651 ServerEnvironment *env = o->m_env;
3652 if(env == NULL) return 0;
3653 v3s16 pos = read_v3s16(L, 2);
3654 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3656 // Don't attempt to load non-loaded area as of now
3657 MapNode n_old = env->getMap().getNodeNoEx(pos);
3658 if(n_old.getContent() == CONTENT_IGNORE){
3659 lua_pushboolean(L, false);
3662 // Create item to place
3663 INodeDefManager *ndef = get_server(L)->ndef();
3664 IItemDefManager *idef = get_server(L)->idef();
3665 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3666 // Make pointed position
3667 PointedThing pointed;
3668 pointed.type = POINTEDTHING_NODE;
3669 pointed.node_abovesurface = pos;
3670 pointed.node_undersurface = pos + v3s16(0,-1,0);
3671 // Place it with a NULL placer (appears in Lua as a non-functional
3673 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3674 lua_pushboolean(L, success);
3678 // EnvRef:dig_node(pos)
3679 // pos = {x=num, y=num, z=num}
3680 static int l_dig_node(lua_State *L)
3682 EnvRef *o = checkobject(L, 1);
3683 ServerEnvironment *env = o->m_env;
3684 if(env == NULL) return 0;
3685 v3s16 pos = read_v3s16(L, 2);
3687 // Don't attempt to load non-loaded area as of now
3688 MapNode n = env->getMap().getNodeNoEx(pos);
3689 if(n.getContent() == CONTENT_IGNORE){
3690 lua_pushboolean(L, false);
3693 // Dig it out with a NULL digger (appears in Lua as a
3694 // non-functional ObjectRef)
3695 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3696 lua_pushboolean(L, success);
3700 // EnvRef:punch_node(pos)
3701 // pos = {x=num, y=num, z=num}
3702 static int l_punch_node(lua_State *L)
3704 EnvRef *o = checkobject(L, 1);
3705 ServerEnvironment *env = o->m_env;
3706 if(env == NULL) return 0;
3707 v3s16 pos = read_v3s16(L, 2);
3709 // Don't attempt to load non-loaded area as of now
3710 MapNode n = env->getMap().getNodeNoEx(pos);
3711 if(n.getContent() == CONTENT_IGNORE){
3712 lua_pushboolean(L, false);
3715 // Punch it with a NULL puncher (appears in Lua as a non-functional
3717 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3718 lua_pushboolean(L, success);
3722 // EnvRef:get_meta(pos)
3723 static int l_get_meta(lua_State *L)
3725 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3726 EnvRef *o = checkobject(L, 1);
3727 ServerEnvironment *env = o->m_env;
3728 if(env == NULL) return 0;
3730 v3s16 p = read_v3s16(L, 2);
3731 NodeMetaRef::create(L, p, env);
3735 // EnvRef:get_node_timer(pos)
3736 static int l_get_node_timer(lua_State *L)
3738 EnvRef *o = checkobject(L, 1);
3739 ServerEnvironment *env = o->m_env;
3740 if(env == NULL) return 0;
3742 v3s16 p = read_v3s16(L, 2);
3743 NodeTimerRef::create(L, p, env);
3747 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3748 // pos = {x=num, y=num, z=num}
3749 static int l_add_entity(lua_State *L)
3751 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3752 EnvRef *o = checkobject(L, 1);
3753 ServerEnvironment *env = o->m_env;
3754 if(env == NULL) return 0;
3756 v3f pos = checkFloatPos(L, 2);
3758 const char *name = luaL_checkstring(L, 3);
3760 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3761 int objectid = env->addActiveObject(obj);
3762 // If failed to add, return nothing (reads as nil)
3766 objectref_get_or_create(L, obj);
3770 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3771 // pos = {x=num, y=num, z=num}
3772 static int l_add_item(lua_State *L)
3774 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3775 EnvRef *o = checkobject(L, 1);
3776 ServerEnvironment *env = o->m_env;
3777 if(env == NULL) return 0;
3779 v3f pos = checkFloatPos(L, 2);
3781 ItemStack item = read_item(L, 3);
3782 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3784 // Use minetest.spawn_item to spawn a __builtin:item
3785 lua_getglobal(L, "minetest");
3786 lua_getfield(L, -1, "spawn_item");
3787 if(lua_isnil(L, -1))
3789 lua_pushvalue(L, 2);
3790 lua_pushstring(L, item.getItemString().c_str());
3791 if(lua_pcall(L, 2, 1, 0))
3792 script_error(L, "error: %s", lua_tostring(L, -1));
3794 /*lua_pushvalue(L, 1);
3795 lua_pushstring(L, "__builtin:item");
3796 lua_pushstring(L, item.getItemString().c_str());
3797 return l_add_entity(L);*/
3799 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3800 int objectid = env->addActiveObject(obj);
3801 // If failed to add, return nothing (reads as nil)
3805 objectref_get_or_create(L, obj);
3809 // EnvRef:add_rat(pos)
3810 // pos = {x=num, y=num, z=num}
3811 static int l_add_rat(lua_State *L)
3813 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3814 <<" Doing nothing."<<std::endl;
3818 // EnvRef:add_firefly(pos)
3819 // pos = {x=num, y=num, z=num}
3820 static int l_add_firefly(lua_State *L)
3822 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3823 <<" Doing nothing."<<std::endl;
3827 // EnvRef:get_player_by_name(name)
3828 static int l_get_player_by_name(lua_State *L)
3830 EnvRef *o = checkobject(L, 1);
3831 ServerEnvironment *env = o->m_env;
3832 if(env == NULL) return 0;
3834 const char *name = luaL_checkstring(L, 2);
3835 Player *player = env->getPlayer(name);
3840 PlayerSAO *sao = player->getPlayerSAO();
3845 // Put player on stack
3846 objectref_get_or_create(L, sao);
3850 // EnvRef:get_objects_inside_radius(pos, radius)
3851 static int l_get_objects_inside_radius(lua_State *L)
3853 // Get the table insert function
3854 lua_getglobal(L, "table");
3855 lua_getfield(L, -1, "insert");
3856 int table_insert = lua_gettop(L);
3858 EnvRef *o = checkobject(L, 1);
3859 ServerEnvironment *env = o->m_env;
3860 if(env == NULL) return 0;
3862 v3f pos = checkFloatPos(L, 2);
3863 float radius = luaL_checknumber(L, 3) * BS;
3864 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3866 int table = lua_gettop(L);
3867 for(std::set<u16>::const_iterator
3868 i = ids.begin(); i != ids.end(); i++){
3869 ServerActiveObject *obj = env->getActiveObject(*i);
3870 // Insert object reference into table
3871 lua_pushvalue(L, table_insert);
3872 lua_pushvalue(L, table);
3873 objectref_get_or_create(L, obj);
3874 if(lua_pcall(L, 2, 0, 0))
3875 script_error(L, "error: %s", lua_tostring(L, -1));
3880 // EnvRef:set_timeofday(val)
3882 static int l_set_timeofday(lua_State *L)
3884 EnvRef *o = checkobject(L, 1);
3885 ServerEnvironment *env = o->m_env;
3886 if(env == NULL) return 0;
3888 float timeofday_f = luaL_checknumber(L, 2);
3889 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3890 int timeofday_mh = (int)(timeofday_f * 24000.0);
3891 // This should be set directly in the environment but currently
3892 // such changes aren't immediately sent to the clients, so call
3893 // the server instead.
3894 //env->setTimeOfDay(timeofday_mh);
3895 get_server(L)->setTimeOfDay(timeofday_mh);
3899 // EnvRef:get_timeofday() -> 0...1
3900 static int l_get_timeofday(lua_State *L)
3902 EnvRef *o = checkobject(L, 1);
3903 ServerEnvironment *env = o->m_env;
3904 if(env == NULL) return 0;
3906 int timeofday_mh = env->getTimeOfDay();
3907 float timeofday_f = (float)timeofday_mh / 24000.0;
3908 lua_pushnumber(L, timeofday_f);
3913 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3914 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3915 static int l_find_node_near(lua_State *L)
3917 EnvRef *o = checkobject(L, 1);
3918 ServerEnvironment *env = o->m_env;
3919 if(env == NULL) return 0;
3920 INodeDefManager *ndef = get_server(L)->ndef();
3921 v3s16 pos = read_v3s16(L, 2);
3922 int radius = luaL_checkinteger(L, 3);
3923 std::set<content_t> filter;
3924 if(lua_istable(L, 4)){
3927 while(lua_next(L, table) != 0){
3928 // key at index -2 and value at index -1
3929 luaL_checktype(L, -1, LUA_TSTRING);
3930 ndef->getIds(lua_tostring(L, -1), filter);
3931 // removes value, keeps key for next iteration
3934 } else if(lua_isstring(L, 4)){
3935 ndef->getIds(lua_tostring(L, 4), filter);
3938 for(int d=1; d<=radius; d++){
3939 core::list<v3s16> list;
3940 getFacePositions(list, d);
3941 for(core::list<v3s16>::Iterator i = list.begin();
3942 i != list.end(); i++){
3943 v3s16 p = pos + (*i);
3944 content_t c = env->getMap().getNodeNoEx(p).getContent();
3945 if(filter.count(c) != 0){
3954 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3955 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3956 static int l_find_nodes_in_area(lua_State *L)
3958 EnvRef *o = checkobject(L, 1);
3959 ServerEnvironment *env = o->m_env;
3960 if(env == NULL) return 0;
3961 INodeDefManager *ndef = get_server(L)->ndef();
3962 v3s16 minp = read_v3s16(L, 2);
3963 v3s16 maxp = read_v3s16(L, 3);
3964 std::set<content_t> filter;
3965 if(lua_istable(L, 4)){
3968 while(lua_next(L, table) != 0){
3969 // key at index -2 and value at index -1
3970 luaL_checktype(L, -1, LUA_TSTRING);
3971 ndef->getIds(lua_tostring(L, -1), filter);
3972 // removes value, keeps key for next iteration
3975 } else if(lua_isstring(L, 4)){
3976 ndef->getIds(lua_tostring(L, 4), filter);
3979 // Get the table insert function
3980 lua_getglobal(L, "table");
3981 lua_getfield(L, -1, "insert");
3982 int table_insert = lua_gettop(L);
3985 int table = lua_gettop(L);
3986 for(s16 x=minp.X; x<=maxp.X; x++)
3987 for(s16 y=minp.Y; y<=maxp.Y; y++)
3988 for(s16 z=minp.Z; z<=maxp.Z; z++)
3991 content_t c = env->getMap().getNodeNoEx(p).getContent();
3992 if(filter.count(c) != 0){
3993 lua_pushvalue(L, table_insert);
3994 lua_pushvalue(L, table);
3996 if(lua_pcall(L, 2, 0, 0))
3997 script_error(L, "error: %s", lua_tostring(L, -1));
4003 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
4004 // returns world-specific PerlinNoise
4005 static int l_get_perlin(lua_State *L)
4007 EnvRef *o = checkobject(L, 1);
4008 ServerEnvironment *env = o->m_env;
4009 if(env == NULL) return 0;
4011 int seeddiff = luaL_checkint(L, 2);
4012 int octaves = luaL_checkint(L, 3);
4013 float persistence = luaL_checknumber(L, 4);
4014 float scale = luaL_checknumber(L, 5);
4016 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
4017 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4018 luaL_getmetatable(L, "PerlinNoise");
4019 lua_setmetatable(L, -2);
4023 // EnvRef:clear_objects()
4024 // clear all objects in the environment
4025 static int l_clear_objects(lua_State *L)
4027 EnvRef *o = checkobject(L, 1);
4028 o->m_env->clearAllObjects();
4032 static int l_spawn_tree(lua_State *L)
4034 EnvRef *o = checkobject(L, 1);
4035 ServerEnvironment *env = o->m_env;
4036 if(env == NULL) return 0;
4037 v3s16 p0 = read_v3s16(L, 2);
4039 treegen::TreeDef tree_def;
4040 std::string trunk,leaves,fruit;
4041 INodeDefManager *ndef = env->getGameDef()->ndef();
4043 if(lua_istable(L, 3))
4045 getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4046 getstringfield(L, 3, "rules_a", tree_def.rules_a);
4047 getstringfield(L, 3, "rules_b", tree_def.rules_b);
4048 getstringfield(L, 3, "rules_c", tree_def.rules_c);
4049 getstringfield(L, 3, "rules_d", tree_def.rules_d);
4050 getstringfield(L, 3, "trunk", trunk);
4051 tree_def.trunknode=ndef->getId(trunk);
4052 getstringfield(L, 3, "leaves", leaves);
4053 tree_def.leavesnode=ndef->getId(leaves);
4054 tree_def.leaves2_chance=0;
4055 getstringfield(L, 3, "leaves2", leaves);
4058 tree_def.leaves2node=ndef->getId(leaves);
4059 getintfield(L, 3, "leaves2_chance", tree_def.leaves2_chance);
4061 getintfield(L, 3, "angle", tree_def.angle);
4062 getintfield(L, 3, "iterations", tree_def.iterations);
4063 getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4064 getstringfield(L, 3, "trunk_type", tree_def.trunk_type);
4065 getboolfield(L, 3, "thin_branches", tree_def.thin_branches);
4066 tree_def.fruit_chance=0;
4067 getstringfield(L, 3, "fruit", fruit);
4070 tree_def.fruitnode=ndef->getId(fruit);
4071 getintfield(L, 3, "fruit_chance",tree_def.fruit_chance);
4076 treegen::spawn_ltree (env, p0, ndef, tree_def);
4081 EnvRef(ServerEnvironment *env):
4084 //infostream<<"EnvRef created"<<std::endl;
4089 //infostream<<"EnvRef destructing"<<std::endl;
4092 // Creates an EnvRef and leaves it on top of stack
4093 // Not callable from Lua; all references are created on the C side.
4094 static void create(lua_State *L, ServerEnvironment *env)
4096 EnvRef *o = new EnvRef(env);
4097 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4098 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4099 luaL_getmetatable(L, className);
4100 lua_setmetatable(L, -2);
4103 static void set_null(lua_State *L)
4105 EnvRef *o = checkobject(L, -1);
4109 static void Register(lua_State *L)
4112 int methodtable = lua_gettop(L);
4113 luaL_newmetatable(L, className);
4114 int metatable = lua_gettop(L);
4116 lua_pushliteral(L, "__metatable");
4117 lua_pushvalue(L, methodtable);
4118 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4120 lua_pushliteral(L, "__index");
4121 lua_pushvalue(L, methodtable);
4122 lua_settable(L, metatable);
4124 lua_pushliteral(L, "__gc");
4125 lua_pushcfunction(L, gc_object);
4126 lua_settable(L, metatable);
4128 lua_pop(L, 1); // drop metatable
4130 luaL_openlib(L, 0, methods, 0); // fill methodtable
4131 lua_pop(L, 1); // drop methodtable
4133 // Cannot be created from Lua
4134 //lua_register(L, className, create_object);
4137 const char EnvRef::className[] = "EnvRef";
4138 const luaL_reg EnvRef::methods[] = {
4139 method(EnvRef, set_node),
4140 method(EnvRef, add_node),
4141 method(EnvRef, remove_node),
4142 method(EnvRef, get_node),
4143 method(EnvRef, get_node_or_nil),
4144 method(EnvRef, get_node_light),
4145 method(EnvRef, place_node),
4146 method(EnvRef, dig_node),
4147 method(EnvRef, punch_node),
4148 method(EnvRef, add_entity),
4149 method(EnvRef, add_item),
4150 method(EnvRef, add_rat),
4151 method(EnvRef, add_firefly),
4152 method(EnvRef, get_meta),
4153 method(EnvRef, get_node_timer),
4154 method(EnvRef, get_player_by_name),
4155 method(EnvRef, get_objects_inside_radius),
4156 method(EnvRef, set_timeofday),
4157 method(EnvRef, get_timeofday),
4158 method(EnvRef, find_node_near),
4159 method(EnvRef, find_nodes_in_area),
4160 method(EnvRef, get_perlin),
4161 //method{EnvRef, get_perlin_map_2d},
4162 //method{EnvRef, get_perlin_map_3d},
4163 method(EnvRef, clear_objects),
4164 method(EnvRef, spawn_tree),
4173 class LuaPseudoRandom
4176 PseudoRandom m_pseudo;
4178 static const char className[];
4179 static const luaL_reg methods[];
4181 // Exported functions
4183 // garbage collector
4184 static int gc_object(lua_State *L)
4186 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4191 // next(self, min=0, max=32767) -> get next value
4192 static int l_next(lua_State *L)
4194 LuaPseudoRandom *o = checkobject(L, 1);
4197 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4198 if(!lua_isnil(L, 2))
4199 min = luaL_checkinteger(L, 2);
4200 if(!lua_isnil(L, 3))
4201 max = luaL_checkinteger(L, 3);
4203 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4204 throw LuaError(L, "PseudoRandom.next(): max < min");
4206 if(max - min != 32767 && max - min > 32767/5)
4207 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.");
4208 PseudoRandom &pseudo = o->m_pseudo;
4209 int val = pseudo.next();
4210 val = (val % (max-min+1)) + min;
4211 lua_pushinteger(L, val);
4216 LuaPseudoRandom(int seed):
4225 const PseudoRandom& getItem() const
4229 PseudoRandom& getItem()
4234 // LuaPseudoRandom(seed)
4235 // Creates an LuaPseudoRandom and leaves it on top of stack
4236 static int create_object(lua_State *L)
4238 int seed = luaL_checknumber(L, 1);
4239 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4240 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4241 luaL_getmetatable(L, className);
4242 lua_setmetatable(L, -2);
4246 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4248 luaL_checktype(L, narg, LUA_TUSERDATA);
4249 void *ud = luaL_checkudata(L, narg, className);
4250 if(!ud) luaL_typerror(L, narg, className);
4251 return *(LuaPseudoRandom**)ud; // unbox pointer
4254 static void Register(lua_State *L)
4257 int methodtable = lua_gettop(L);
4258 luaL_newmetatable(L, className);
4259 int metatable = lua_gettop(L);
4261 lua_pushliteral(L, "__metatable");
4262 lua_pushvalue(L, methodtable);
4263 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4265 lua_pushliteral(L, "__index");
4266 lua_pushvalue(L, methodtable);
4267 lua_settable(L, metatable);
4269 lua_pushliteral(L, "__gc");
4270 lua_pushcfunction(L, gc_object);
4271 lua_settable(L, metatable);
4273 lua_pop(L, 1); // drop metatable
4275 luaL_openlib(L, 0, methods, 0); // fill methodtable
4276 lua_pop(L, 1); // drop methodtable
4278 // Can be created from Lua (LuaPseudoRandom(seed))
4279 lua_register(L, className, create_object);
4282 const char LuaPseudoRandom::className[] = "PseudoRandom";
4283 const luaL_reg LuaPseudoRandom::methods[] = {
4284 method(LuaPseudoRandom, next),
4294 class LuaABM : public ActiveBlockModifier
4300 std::set<std::string> m_trigger_contents;
4301 std::set<std::string> m_required_neighbors;
4302 float m_trigger_interval;
4303 u32 m_trigger_chance;
4305 LuaABM(lua_State *L, int id,
4306 const std::set<std::string> &trigger_contents,
4307 const std::set<std::string> &required_neighbors,
4308 float trigger_interval, u32 trigger_chance):
4311 m_trigger_contents(trigger_contents),
4312 m_required_neighbors(required_neighbors),
4313 m_trigger_interval(trigger_interval),
4314 m_trigger_chance(trigger_chance)
4317 virtual std::set<std::string> getTriggerContents()
4319 return m_trigger_contents;
4321 virtual std::set<std::string> getRequiredNeighbors()
4323 return m_required_neighbors;
4325 virtual float getTriggerInterval()
4327 return m_trigger_interval;
4329 virtual u32 getTriggerChance()
4331 return m_trigger_chance;
4333 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4334 u32 active_object_count, u32 active_object_count_wider)
4336 lua_State *L = m_lua;
4339 assert(lua_checkstack(L, 20));
4340 StackUnroller stack_unroller(L);
4342 // Get minetest.registered_abms
4343 lua_getglobal(L, "minetest");
4344 lua_getfield(L, -1, "registered_abms");
4345 luaL_checktype(L, -1, LUA_TTABLE);
4346 int registered_abms = lua_gettop(L);
4348 // Get minetest.registered_abms[m_id]
4349 lua_pushnumber(L, m_id);
4350 lua_gettable(L, registered_abms);
4351 if(lua_isnil(L, -1))
4355 luaL_checktype(L, -1, LUA_TTABLE);
4356 lua_getfield(L, -1, "action");
4357 luaL_checktype(L, -1, LUA_TFUNCTION);
4359 pushnode(L, n, env->getGameDef()->ndef());
4360 lua_pushnumber(L, active_object_count);
4361 lua_pushnumber(L, active_object_count_wider);
4362 if(lua_pcall(L, 4, 0, 0))
4363 script_error(L, "error: %s", lua_tostring(L, -1));
4371 static void read_server_sound_params(lua_State *L, int index,
4372 ServerSoundParams ¶ms)
4375 index = lua_gettop(L) + 1 + index;
4377 params = ServerSoundParams();
4378 if(lua_istable(L, index)){
4379 getfloatfield(L, index, "gain", params.gain);
4380 getstringfield(L, index, "to_player", params.to_player);
4381 lua_getfield(L, index, "pos");
4382 if(!lua_isnil(L, -1)){
4383 v3f p = read_v3f(L, -1)*BS;
4385 params.type = ServerSoundParams::SSP_POSITIONAL;
4388 lua_getfield(L, index, "object");
4389 if(!lua_isnil(L, -1)){
4390 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4391 ServerActiveObject *sao = ObjectRef::getobject(ref);
4393 params.object = sao->getId();
4394 params.type = ServerSoundParams::SSP_OBJECT;
4398 params.max_hear_distance = BS*getfloatfield_default(L, index,
4399 "max_hear_distance", params.max_hear_distance/BS);
4400 getboolfield(L, index, "loop", params.loop);
4409 // Writes a line to dstream
4410 static int l_debug(lua_State *L)
4412 std::string text = lua_tostring(L, 1);
4413 dstream << text << std::endl;
4417 // log([level,] text)
4418 // Writes a line to the logger.
4419 // The one-argument version logs to infostream.
4420 // The two-argument version accept a log level: error, action, info, or verbose.
4421 static int l_log(lua_State *L)
4424 LogMessageLevel level = LMT_INFO;
4425 if(lua_isnone(L, 2))
4427 text = lua_tostring(L, 1);
4431 std::string levelname = lua_tostring(L, 1);
4432 text = lua_tostring(L, 2);
4433 if(levelname == "error")
4435 else if(levelname == "action")
4437 else if(levelname == "verbose")
4438 level = LMT_VERBOSE;
4440 log_printline(level, text);
4444 // request_shutdown()
4445 static int l_request_shutdown(lua_State *L)
4447 get_server(L)->requestShutdown();
4451 // get_server_status()
4452 static int l_get_server_status(lua_State *L)
4454 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4458 // register_biome_groups({frequencies})
4459 static int l_register_biome_groups(lua_State *L)
4461 luaL_checktype(L, 1, LUA_TTABLE);
4463 if (!lua_istable(L, index))
4464 throw LuaError(L, "register_biome_groups: parameter is not a table");
4466 BiomeDefManager *bmgr = get_server(L)->getEmergeManager()->biomedef;
4469 for (int i = 1; lua_next(L, index) != 0; i++) {
4470 bmgr->addBiomeGroup(lua_tonumber(L, -1));
4478 // register_biome({lots of stuff})
4479 static int l_register_biome(lua_State *L)
4481 luaL_checktype(L, 1, LUA_TTABLE);
4482 int index = 1, groupid;
4483 std::string nodename;
4485 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
4486 BiomeDefManager *bmgr = get_server(L)->getEmergeManager()->biomedef;
4488 groupid = getintfield_default(L, index, "group_id", 0);
4490 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
4491 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
4492 Biome *b = bmgr->createBiome(terrain);
4494 b->name = getstringfield_default(L, index, "name", "");
4496 if (getstringfield(L, index, "node_top", nodename))
4497 b->n_top = MapNode(ndef->getId(nodename));
4499 b->n_top = MapNode(CONTENT_IGNORE);
4501 if (getstringfield(L, index, "node_filler", nodename))
4502 b->n_filler = MapNode(ndef->getId(nodename));
4504 b->n_filler = b->n_top;
4506 b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
4508 b->height_min = getintfield_default(L, index, "height_min", 0);
4509 b->height_max = getintfield_default(L, index, "height_max", 0);
4510 b->heat_min = getfloatfield_default(L, index, "heat_min", 0.);
4511 b->heat_max = getfloatfield_default(L, index, "heat_max", 0.);
4512 b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
4513 b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
4515 b->np = new NoiseParams; // should read an entire NoiseParams later on...
4516 getfloatfield(L, index, "scale", b->np->scale);
4517 getfloatfield(L, index, "offset", b->np->offset);
4519 b->groupid = (s8)groupid;
4520 b->flags = 0; //reserved
4524 verbosestream << "register_biome: " << b->name << std::endl;
4528 // register_item_raw({lots of stuff})
4529 static int l_register_item_raw(lua_State *L)
4531 luaL_checktype(L, 1, LUA_TTABLE);
4534 // Get the writable item and node definition managers from the server
4535 IWritableItemDefManager *idef =
4536 get_server(L)->getWritableItemDefManager();
4537 IWritableNodeDefManager *ndef =
4538 get_server(L)->getWritableNodeDefManager();
4540 // Check if name is defined
4542 lua_getfield(L, table, "name");
4543 if(lua_isstring(L, -1)){
4544 name = lua_tostring(L, -1);
4545 verbosestream<<"register_item_raw: "<<name<<std::endl;
4547 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4550 // Check if on_use is defined
4553 // Set a distinctive default value to check if this is set
4554 def.node_placement_prediction = "__default";
4556 // Read the item definition
4557 def = read_item_definition(L, table, def);
4559 // Default to having client-side placement prediction for nodes
4560 // ("" in item definition sets it off)
4561 if(def.node_placement_prediction == "__default"){
4562 if(def.type == ITEM_NODE)
4563 def.node_placement_prediction = name;
4565 def.node_placement_prediction = "";
4568 // Register item definition
4569 idef->registerItem(def);
4571 // Read the node definition (content features) and register it
4572 if(def.type == ITEM_NODE)
4574 ContentFeatures f = read_content_features(L, table);
4575 ndef->set(f.name, f);
4578 return 0; /* number of results */
4581 // register_alias_raw(name, convert_to_name)
4582 static int l_register_alias_raw(lua_State *L)
4584 std::string name = luaL_checkstring(L, 1);
4585 std::string convert_to = luaL_checkstring(L, 2);
4587 // Get the writable item definition manager from the server
4588 IWritableItemDefManager *idef =
4589 get_server(L)->getWritableItemDefManager();
4591 idef->registerAlias(name, convert_to);
4593 return 0; /* number of results */
4596 // helper for register_craft
4597 static bool read_craft_recipe_shaped(lua_State *L, int index,
4598 int &width, std::vector<std::string> &recipe)
4601 index = lua_gettop(L) + 1 + index;
4603 if(!lua_istable(L, index))
4608 while(lua_next(L, index) != 0){
4610 // key at index -2 and value at index -1
4611 if(!lua_istable(L, -1))
4613 int table2 = lua_gettop(L);
4615 while(lua_next(L, table2) != 0){
4616 // key at index -2 and value at index -1
4617 if(!lua_isstring(L, -1))
4619 recipe.push_back(lua_tostring(L, -1));
4620 // removes value, keeps key for next iteration
4627 if(colcount != width)
4630 // removes value, keeps key for next iteration
4637 // helper for register_craft
4638 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4639 std::vector<std::string> &recipe)
4642 index = lua_gettop(L) + 1 + index;
4644 if(!lua_istable(L, index))
4648 while(lua_next(L, index) != 0){
4649 // key at index -2 and value at index -1
4650 if(!lua_isstring(L, -1))
4652 recipe.push_back(lua_tostring(L, -1));
4653 // removes value, keeps key for next iteration
4659 // helper for register_craft
4660 static bool read_craft_replacements(lua_State *L, int index,
4661 CraftReplacements &replacements)
4664 index = lua_gettop(L) + 1 + index;
4666 if(!lua_istable(L, index))
4670 while(lua_next(L, index) != 0){
4671 // key at index -2 and value at index -1
4672 if(!lua_istable(L, -1))
4674 lua_rawgeti(L, -1, 1);
4675 if(!lua_isstring(L, -1))
4677 std::string replace_from = lua_tostring(L, -1);
4679 lua_rawgeti(L, -1, 2);
4680 if(!lua_isstring(L, -1))
4682 std::string replace_to = lua_tostring(L, -1);
4684 replacements.pairs.push_back(
4685 std::make_pair(replace_from, replace_to));
4686 // removes value, keeps key for next iteration
4691 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4692 static int l_register_craft(lua_State *L)
4694 //infostream<<"register_craft"<<std::endl;
4695 luaL_checktype(L, 1, LUA_TTABLE);
4698 // Get the writable craft definition manager from the server
4699 IWritableCraftDefManager *craftdef =
4700 get_server(L)->getWritableCraftDefManager();
4702 std::string type = getstringfield_default(L, table, "type", "shaped");
4705 CraftDefinitionShaped
4707 if(type == "shaped"){
4708 std::string output = getstringfield_default(L, table, "output", "");
4710 throw LuaError(L, "Crafting definition is missing an output");
4713 std::vector<std::string> recipe;
4714 lua_getfield(L, table, "recipe");
4715 if(lua_isnil(L, -1))
4716 throw LuaError(L, "Crafting definition is missing a recipe"
4717 " (output=\"" + output + "\")");
4718 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4719 throw LuaError(L, "Invalid crafting recipe"
4720 " (output=\"" + output + "\")");
4722 CraftReplacements replacements;
4723 lua_getfield(L, table, "replacements");
4724 if(!lua_isnil(L, -1))
4726 if(!read_craft_replacements(L, -1, replacements))
4727 throw LuaError(L, "Invalid replacements"
4728 " (output=\"" + output + "\")");
4731 CraftDefinition *def = new CraftDefinitionShaped(
4732 output, width, recipe, replacements);
4733 craftdef->registerCraft(def);
4736 CraftDefinitionShapeless
4738 else if(type == "shapeless"){
4739 std::string output = getstringfield_default(L, table, "output", "");
4741 throw LuaError(L, "Crafting definition (shapeless)"
4742 " is missing an output");
4744 std::vector<std::string> recipe;
4745 lua_getfield(L, table, "recipe");
4746 if(lua_isnil(L, -1))
4747 throw LuaError(L, "Crafting definition (shapeless)"
4748 " is missing a recipe"
4749 " (output=\"" + output + "\")");
4750 if(!read_craft_recipe_shapeless(L, -1, recipe))
4751 throw LuaError(L, "Invalid crafting recipe"
4752 " (output=\"" + output + "\")");
4754 CraftReplacements replacements;
4755 lua_getfield(L, table, "replacements");
4756 if(!lua_isnil(L, -1))
4758 if(!read_craft_replacements(L, -1, replacements))
4759 throw LuaError(L, "Invalid replacements"
4760 " (output=\"" + output + "\")");
4763 CraftDefinition *def = new CraftDefinitionShapeless(
4764 output, recipe, replacements);
4765 craftdef->registerCraft(def);
4768 CraftDefinitionToolRepair
4770 else if(type == "toolrepair"){
4771 float additional_wear = getfloatfield_default(L, table,
4772 "additional_wear", 0.0);
4774 CraftDefinition *def = new CraftDefinitionToolRepair(
4776 craftdef->registerCraft(def);
4779 CraftDefinitionCooking
4781 else if(type == "cooking"){
4782 std::string output = getstringfield_default(L, table, "output", "");
4784 throw LuaError(L, "Crafting definition (cooking)"
4785 " is missing an output");
4787 std::string recipe = getstringfield_default(L, table, "recipe", "");
4789 throw LuaError(L, "Crafting definition (cooking)"
4790 " is missing a recipe"
4791 " (output=\"" + output + "\")");
4793 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4795 CraftReplacements replacements;
4796 lua_getfield(L, table, "replacements");
4797 if(!lua_isnil(L, -1))
4799 if(!read_craft_replacements(L, -1, replacements))
4800 throw LuaError(L, "Invalid replacements"
4801 " (cooking output=\"" + output + "\")");
4804 CraftDefinition *def = new CraftDefinitionCooking(
4805 output, recipe, cooktime, replacements);
4806 craftdef->registerCraft(def);
4811 else if(type == "fuel"){
4812 std::string recipe = getstringfield_default(L, table, "recipe", "");
4814 throw LuaError(L, "Crafting definition (fuel)"
4815 " is missing a recipe");
4817 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4819 CraftReplacements replacements;
4820 lua_getfield(L, table, "replacements");
4821 if(!lua_isnil(L, -1))
4823 if(!read_craft_replacements(L, -1, replacements))
4824 throw LuaError(L, "Invalid replacements"
4825 " (fuel recipe=\"" + recipe + "\")");
4828 CraftDefinition *def = new CraftDefinitionFuel(
4829 recipe, burntime, replacements);
4830 craftdef->registerCraft(def);
4834 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4838 return 0; /* number of results */
4841 // setting_set(name, value)
4842 static int l_setting_set(lua_State *L)
4844 const char *name = luaL_checkstring(L, 1);
4845 const char *value = luaL_checkstring(L, 2);
4846 g_settings->set(name, value);
4850 // setting_get(name)
4851 static int l_setting_get(lua_State *L)
4853 const char *name = luaL_checkstring(L, 1);
4855 std::string value = g_settings->get(name);
4856 lua_pushstring(L, value.c_str());
4857 } catch(SettingNotFoundException &e){
4863 // setting_getbool(name)
4864 static int l_setting_getbool(lua_State *L)
4866 const char *name = luaL_checkstring(L, 1);
4868 bool value = g_settings->getBool(name);
4869 lua_pushboolean(L, value);
4870 } catch(SettingNotFoundException &e){
4876 // chat_send_all(text)
4877 static int l_chat_send_all(lua_State *L)
4879 const char *text = luaL_checkstring(L, 1);
4880 // Get server from registry
4881 Server *server = get_server(L);
4883 server->notifyPlayers(narrow_to_wide(text));
4887 // chat_send_player(name, text)
4888 static int l_chat_send_player(lua_State *L)
4890 const char *name = luaL_checkstring(L, 1);
4891 const char *text = luaL_checkstring(L, 2);
4892 // Get server from registry
4893 Server *server = get_server(L);
4895 server->notifyPlayer(name, narrow_to_wide(text));
4899 // get_player_privs(name, text)
4900 static int l_get_player_privs(lua_State *L)
4902 const char *name = luaL_checkstring(L, 1);
4903 // Get server from registry
4904 Server *server = get_server(L);
4907 int table = lua_gettop(L);
4908 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4909 for(std::set<std::string>::const_iterator
4910 i = privs_s.begin(); i != privs_s.end(); i++){
4911 lua_pushboolean(L, true);
4912 lua_setfield(L, table, i->c_str());
4914 lua_pushvalue(L, table);
4919 static int l_get_ban_list(lua_State *L)
4921 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4925 // get_ban_description()
4926 static int l_get_ban_description(lua_State *L)
4928 const char * ip_or_name = luaL_checkstring(L, 1);
4929 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4934 static int l_ban_player(lua_State *L)
4936 const char * name = luaL_checkstring(L, 1);
4937 Player *player = get_env(L)->getPlayer(name);
4940 lua_pushboolean(L, false); // no such player
4945 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4946 std::string ip_str = addr.serializeString();
4947 get_server(L)->setIpBanned(ip_str, name);
4949 catch(con::PeerNotFoundException) // unlikely
4951 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4952 lua_pushboolean(L, false); // error
4955 lua_pushboolean(L, true);
4959 // unban_player_or_ip()
4960 static int l_unban_player_of_ip(lua_State *L)
4962 const char * ip_or_name = luaL_checkstring(L, 1);
4963 get_server(L)->unsetIpBanned(ip_or_name);
4964 lua_pushboolean(L, true);
4968 // get_inventory(location)
4969 static int l_get_inventory(lua_State *L)
4971 InventoryLocation loc;
4973 std::string type = checkstringfield(L, 1, "type");
4974 if(type == "player"){
4975 std::string name = checkstringfield(L, 1, "name");
4976 loc.setPlayer(name);
4977 } else if(type == "node"){
4978 lua_getfield(L, 1, "pos");
4979 v3s16 pos = check_v3s16(L, -1);
4980 loc.setNodeMeta(pos);
4981 } else if(type == "detached"){
4982 std::string name = checkstringfield(L, 1, "name");
4983 loc.setDetached(name);
4986 if(get_server(L)->getInventory(loc) != NULL)
4987 InvRef::create(L, loc);
4993 // create_detached_inventory_raw(name)
4994 static int l_create_detached_inventory_raw(lua_State *L)
4996 const char *name = luaL_checkstring(L, 1);
4997 if(get_server(L)->createDetachedInventory(name) != NULL){
4998 InventoryLocation loc;
4999 loc.setDetached(name);
5000 InvRef::create(L, loc);
5007 // show_formspec(playername,formname,formspec)
5008 static int l_show_formspec(lua_State *L)
5010 const char *playername = luaL_checkstring(L, 1);
5011 const char *formname = luaL_checkstring(L, 2);
5012 const char *formspec = luaL_checkstring(L, 3);
5014 if(get_server(L)->showFormspec(playername,formspec,formname))
5016 lua_pushboolean(L, true);
5018 lua_pushboolean(L, false);
5023 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5024 static int l_get_dig_params(lua_State *L)
5026 std::map<std::string, int> groups;
5027 read_groups(L, 1, groups);
5028 ToolCapabilities tp = read_tool_capabilities(L, 2);
5029 if(lua_isnoneornil(L, 3))
5030 push_dig_params(L, getDigParams(groups, &tp));
5032 push_dig_params(L, getDigParams(groups, &tp,
5033 luaL_checknumber(L, 3)));
5037 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5038 static int l_get_hit_params(lua_State *L)
5040 std::map<std::string, int> groups;
5041 read_groups(L, 1, groups);
5042 ToolCapabilities tp = read_tool_capabilities(L, 2);
5043 if(lua_isnoneornil(L, 3))
5044 push_hit_params(L, getHitParams(groups, &tp));
5046 push_hit_params(L, getHitParams(groups, &tp,
5047 luaL_checknumber(L, 3)));
5051 // get_current_modname()
5052 static int l_get_current_modname(lua_State *L)
5054 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5058 // get_modpath(modname)
5059 static int l_get_modpath(lua_State *L)
5061 std::string modname = luaL_checkstring(L, 1);
5063 if(modname == "__builtin"){
5064 std::string path = get_server(L)->getBuiltinLuaPath();
5065 lua_pushstring(L, path.c_str());
5068 const ModSpec *mod = get_server(L)->getModSpec(modname);
5073 lua_pushstring(L, mod->path.c_str());
5078 // the returned list is sorted alphabetically for you
5079 static int l_get_modnames(lua_State *L)
5081 // Get a list of mods
5082 core::list<std::string> mods_unsorted, mods_sorted;
5083 get_server(L)->getModNames(mods_unsorted);
5085 // Take unsorted items from mods_unsorted and sort them into
5086 // mods_sorted; not great performance but the number of mods on a
5087 // server will likely be small.
5088 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5089 i != mods_unsorted.end(); i++)
5092 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5093 x != mods_unsorted.end(); x++)
5095 // I doubt anybody using Minetest will be using
5096 // anything not ASCII based :)
5097 if((*i).compare(*x) <= 0)
5099 mods_sorted.insert_before(x, *i);
5105 mods_sorted.push_back(*i);
5108 // Get the table insertion function from Lua.
5109 lua_getglobal(L, "table");
5110 lua_getfield(L, -1, "insert");
5111 int insertion_func = lua_gettop(L);
5113 // Package them up for Lua
5115 int new_table = lua_gettop(L);
5116 core::list<std::string>::Iterator i = mods_sorted.begin();
5117 while(i != mods_sorted.end())
5119 lua_pushvalue(L, insertion_func);
5120 lua_pushvalue(L, new_table);
5121 lua_pushstring(L, (*i).c_str());
5122 if(lua_pcall(L, 2, 0, 0) != 0)
5124 script_error(L, "error: %s", lua_tostring(L, -1));
5132 static int l_get_worldpath(lua_State *L)
5134 std::string worldpath = get_server(L)->getWorldPath();
5135 lua_pushstring(L, worldpath.c_str());
5139 // sound_play(spec, parameters)
5140 static int l_sound_play(lua_State *L)
5142 SimpleSoundSpec spec;
5143 read_soundspec(L, 1, spec);
5144 ServerSoundParams params;
5145 read_server_sound_params(L, 2, params);
5146 s32 handle = get_server(L)->playSound(spec, params);
5147 lua_pushinteger(L, handle);
5151 // sound_stop(handle)
5152 static int l_sound_stop(lua_State *L)
5154 int handle = luaL_checkinteger(L, 1);
5155 get_server(L)->stopSound(handle);
5159 // is_singleplayer()
5160 static int l_is_singleplayer(lua_State *L)
5162 lua_pushboolean(L, get_server(L)->isSingleplayer());
5166 // get_password_hash(name, raw_password)
5167 static int l_get_password_hash(lua_State *L)
5169 std::string name = luaL_checkstring(L, 1);
5170 std::string raw_password = luaL_checkstring(L, 2);
5171 std::string hash = translatePassword(name,
5172 narrow_to_wide(raw_password));
5173 lua_pushstring(L, hash.c_str());
5177 // notify_authentication_modified(name)
5178 static int l_notify_authentication_modified(lua_State *L)
5180 std::string name = "";
5181 if(lua_isstring(L, 1))
5182 name = lua_tostring(L, 1);
5183 get_server(L)->reportPrivsModified(name);
5187 // get_craft_result(input)
5188 static int l_get_craft_result(lua_State *L)
5191 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5192 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5193 es_CraftMethod, CRAFT_METHOD_NORMAL);
5195 lua_getfield(L, input_i, "width");
5196 if(lua_isnumber(L, -1))
5197 width = luaL_checkinteger(L, -1);
5199 lua_getfield(L, input_i, "items");
5200 std::vector<ItemStack> items = read_items(L, -1);
5201 lua_pop(L, 1); // items
5203 IGameDef *gdef = get_server(L);
5204 ICraftDefManager *cdef = gdef->cdef();
5205 CraftInput input(method, width, items);
5207 bool got = cdef->getCraftResult(input, output, true, gdef);
5208 lua_newtable(L); // output table
5211 item.deSerialize(output.item, gdef->idef());
5212 LuaItemStack::create(L, item);
5213 lua_setfield(L, -2, "item");
5214 setintfield(L, -1, "time", output.time);
5216 LuaItemStack::create(L, ItemStack());
5217 lua_setfield(L, -2, "item");
5218 setintfield(L, -1, "time", 0);
5220 lua_newtable(L); // decremented input table
5221 lua_pushstring(L, method_s.c_str());
5222 lua_setfield(L, -2, "method");
5223 lua_pushinteger(L, width);
5224 lua_setfield(L, -2, "width");
5225 push_items(L, input.items);
5226 lua_setfield(L, -2, "items");
5230 // get_craft_recipe(result item)
5231 static int l_get_craft_recipe(lua_State *L)
5236 std::string o_item = luaL_checkstring(L,input_i);
5238 IGameDef *gdef = get_server(L);
5239 ICraftDefManager *cdef = gdef->cdef();
5241 CraftOutput output(o_item,0);
5242 bool got = cdef->getCraftRecipe(input, output, gdef);
5243 lua_newtable(L); // output table
5246 for(std::vector<ItemStack>::const_iterator
5247 i = input.items.begin();
5248 i != input.items.end(); i++, k++)
5254 sprintf(tmp,"%d",k);
5255 lua_pushstring(L,tmp);
5256 lua_pushstring(L,i->name.c_str());
5257 lua_settable(L, -3);
5259 lua_setfield(L, -2, "items");
5260 setintfield(L, -1, "width", input.width);
5261 switch (input.method) {
5262 case CRAFT_METHOD_NORMAL:
5263 lua_pushstring(L,"normal");
5265 case CRAFT_METHOD_COOKING:
5266 lua_pushstring(L,"cooking");
5268 case CRAFT_METHOD_FUEL:
5269 lua_pushstring(L,"fuel");
5272 lua_pushstring(L,"unknown");
5274 lua_setfield(L, -2, "type");
5277 lua_setfield(L, -2, "items");
5278 setintfield(L, -1, "width", 0);
5283 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5284 static int l_rollback_get_last_node_actor(lua_State *L)
5286 v3s16 p = read_v3s16(L, 1);
5287 int range = luaL_checknumber(L, 2);
5288 int seconds = luaL_checknumber(L, 3);
5289 Server *server = get_server(L);
5290 IRollbackManager *rollback = server->getRollbackManager();
5292 int act_seconds = 0;
5293 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5294 lua_pushstring(L, actor.c_str());
5295 push_v3s16(L, act_p);
5296 lua_pushnumber(L, act_seconds);
5300 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5301 static int l_rollback_revert_actions_by(lua_State *L)
5303 std::string actor = luaL_checkstring(L, 1);
5304 int seconds = luaL_checknumber(L, 2);
5305 Server *server = get_server(L);
5306 IRollbackManager *rollback = server->getRollbackManager();
5307 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5308 std::list<std::string> log;
5309 bool success = server->rollbackRevertActions(actions, &log);
5310 // Push boolean result
5311 lua_pushboolean(L, success);
5312 // Get the table insert function and push the log table
5313 lua_getglobal(L, "table");
5314 lua_getfield(L, -1, "insert");
5315 int table_insert = lua_gettop(L);
5317 int table = lua_gettop(L);
5318 for(std::list<std::string>::const_iterator i = log.begin();
5319 i != log.end(); i++)
5321 lua_pushvalue(L, table_insert);
5322 lua_pushvalue(L, table);
5323 lua_pushstring(L, i->c_str());
5324 if(lua_pcall(L, 2, 0, 0))
5325 script_error(L, "error: %s", lua_tostring(L, -1));
5327 lua_remove(L, -2); // Remove table
5328 lua_remove(L, -2); // Remove insert
5332 static const struct luaL_Reg minetest_f [] = {
5335 {"request_shutdown", l_request_shutdown},
5336 {"get_server_status", l_get_server_status},
5337 {"register_item_raw", l_register_item_raw},
5338 {"register_alias_raw", l_register_alias_raw},
5339 {"register_craft", l_register_craft},
5340 {"register_biome", l_register_biome},
5341 {"register_biome_groups", l_register_biome_groups},
5342 {"setting_set", l_setting_set},
5343 {"setting_get", l_setting_get},
5344 {"setting_getbool", l_setting_getbool},
5345 {"chat_send_all", l_chat_send_all},
5346 {"chat_send_player", l_chat_send_player},
5347 {"get_player_privs", l_get_player_privs},
5348 {"get_ban_list", l_get_ban_list},
5349 {"get_ban_description", l_get_ban_description},
5350 {"ban_player", l_ban_player},
5351 {"unban_player_or_ip", l_unban_player_of_ip},
5352 {"get_inventory", l_get_inventory},
5353 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5354 {"show_formspec", l_show_formspec},
5355 {"get_dig_params", l_get_dig_params},
5356 {"get_hit_params", l_get_hit_params},
5357 {"get_current_modname", l_get_current_modname},
5358 {"get_modpath", l_get_modpath},
5359 {"get_modnames", l_get_modnames},
5360 {"get_worldpath", l_get_worldpath},
5361 {"sound_play", l_sound_play},
5362 {"sound_stop", l_sound_stop},
5363 {"is_singleplayer", l_is_singleplayer},
5364 {"get_password_hash", l_get_password_hash},
5365 {"notify_authentication_modified", l_notify_authentication_modified},
5366 {"get_craft_result", l_get_craft_result},
5367 {"get_craft_recipe", l_get_craft_recipe},
5368 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5369 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5374 Main export function
5377 void scriptapi_export(lua_State *L, Server *server)
5380 assert(lua_checkstack(L, 20));
5381 verbosestream<<"scriptapi_export()"<<std::endl;
5382 StackUnroller stack_unroller(L);
5384 // Store server as light userdata in registry
5385 lua_pushlightuserdata(L, server);
5386 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5388 // Register global functions in table minetest
5390 luaL_register(L, NULL, minetest_f);
5391 lua_setglobal(L, "minetest");
5393 // Get the main minetest table
5394 lua_getglobal(L, "minetest");
5396 // Add tables to minetest
5398 lua_setfield(L, -2, "object_refs");
5400 lua_setfield(L, -2, "luaentities");
5402 // Register wrappers
5403 LuaItemStack::Register(L);
5404 InvRef::Register(L);
5405 NodeMetaRef::Register(L);
5406 NodeTimerRef::Register(L);
5407 ObjectRef::Register(L);
5408 EnvRef::Register(L);
5409 LuaPseudoRandom::Register(L);
5410 LuaPerlinNoise::Register(L);
5413 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5414 const std::string &modname)
5416 ModNameStorer modnamestorer(L, modname);
5418 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5420 errorstream<<"Error loading mod \""<<modname
5421 <<"\": modname does not follow naming conventions: "
5422 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5426 bool success = false;
5429 success = script_load(L, scriptpath.c_str());
5432 errorstream<<"Error loading mod \""<<modname
5433 <<"\": "<<e.what()<<std::endl;
5439 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5442 assert(lua_checkstack(L, 20));
5443 verbosestream<<"scriptapi_add_environment"<<std::endl;
5444 StackUnroller stack_unroller(L);
5446 // Create EnvRef on stack
5447 EnvRef::create(L, env);
5448 int envref = lua_gettop(L);
5450 // minetest.env = envref
5451 lua_getglobal(L, "minetest");
5452 luaL_checktype(L, -1, LUA_TTABLE);
5453 lua_pushvalue(L, envref);
5454 lua_setfield(L, -2, "env");
5456 // Store environment as light userdata in registry
5457 lua_pushlightuserdata(L, env);
5458 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5461 Add ActiveBlockModifiers to environment
5464 // Get minetest.registered_abms
5465 lua_getglobal(L, "minetest");
5466 lua_getfield(L, -1, "registered_abms");
5467 luaL_checktype(L, -1, LUA_TTABLE);
5468 int registered_abms = lua_gettop(L);
5470 if(lua_istable(L, registered_abms)){
5471 int table = lua_gettop(L);
5473 while(lua_next(L, table) != 0){
5474 // key at index -2 and value at index -1
5475 int id = lua_tonumber(L, -2);
5476 int current_abm = lua_gettop(L);
5478 std::set<std::string> trigger_contents;
5479 lua_getfield(L, current_abm, "nodenames");
5480 if(lua_istable(L, -1)){
5481 int table = lua_gettop(L);
5483 while(lua_next(L, table) != 0){
5484 // key at index -2 and value at index -1
5485 luaL_checktype(L, -1, LUA_TSTRING);
5486 trigger_contents.insert(lua_tostring(L, -1));
5487 // removes value, keeps key for next iteration
5490 } else if(lua_isstring(L, -1)){
5491 trigger_contents.insert(lua_tostring(L, -1));
5495 std::set<std::string> required_neighbors;
5496 lua_getfield(L, current_abm, "neighbors");
5497 if(lua_istable(L, -1)){
5498 int table = lua_gettop(L);
5500 while(lua_next(L, table) != 0){
5501 // key at index -2 and value at index -1
5502 luaL_checktype(L, -1, LUA_TSTRING);
5503 required_neighbors.insert(lua_tostring(L, -1));
5504 // removes value, keeps key for next iteration
5507 } else if(lua_isstring(L, -1)){
5508 required_neighbors.insert(lua_tostring(L, -1));
5512 float trigger_interval = 10.0;
5513 getfloatfield(L, current_abm, "interval", trigger_interval);
5515 int trigger_chance = 50;
5516 getintfield(L, current_abm, "chance", trigger_chance);
5518 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5519 required_neighbors, trigger_interval, trigger_chance);
5521 env->addActiveBlockModifier(abm);
5523 // removes value, keeps key for next iteration
5531 // Dump stack top with the dump2 function
5532 static void dump2(lua_State *L, const char *name)
5534 // Dump object (debug)
5535 lua_getglobal(L, "dump2");
5536 luaL_checktype(L, -1, LUA_TFUNCTION);
5537 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5538 lua_pushstring(L, name);
5539 if(lua_pcall(L, 2, 0, 0))
5540 script_error(L, "error: %s", lua_tostring(L, -1));
5548 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5551 assert(lua_checkstack(L, 20));
5552 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5553 StackUnroller stack_unroller(L);
5555 // Create object on stack
5556 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5557 int object = lua_gettop(L);
5559 // Get minetest.object_refs table
5560 lua_getglobal(L, "minetest");
5561 lua_getfield(L, -1, "object_refs");
5562 luaL_checktype(L, -1, LUA_TTABLE);
5563 int objectstable = lua_gettop(L);
5565 // object_refs[id] = object
5566 lua_pushnumber(L, cobj->getId()); // Push id
5567 lua_pushvalue(L, object); // Copy object to top of stack
5568 lua_settable(L, objectstable);
5571 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5574 assert(lua_checkstack(L, 20));
5575 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5576 StackUnroller stack_unroller(L);
5578 // Get minetest.object_refs table
5579 lua_getglobal(L, "minetest");
5580 lua_getfield(L, -1, "object_refs");
5581 luaL_checktype(L, -1, LUA_TTABLE);
5582 int objectstable = lua_gettop(L);
5584 // Get object_refs[id]
5585 lua_pushnumber(L, cobj->getId()); // Push id
5586 lua_gettable(L, objectstable);
5587 // Set object reference to NULL
5588 ObjectRef::set_null(L);
5589 lua_pop(L, 1); // pop object
5591 // Set object_refs[id] = nil
5592 lua_pushnumber(L, cobj->getId()); // Push id
5594 lua_settable(L, objectstable);
5601 // What scriptapi_run_callbacks does with the return values of callbacks.
5602 // Regardless of the mode, if only one callback is defined,
5603 // its return value is the total return value.
5604 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5605 enum RunCallbacksMode
5607 // Returns the return value of the first callback
5608 // Returns nil if list of callbacks is empty
5609 RUN_CALLBACKS_MODE_FIRST,
5610 // Returns the return value of the last callback
5611 // Returns nil if list of callbacks is empty
5612 RUN_CALLBACKS_MODE_LAST,
5613 // If any callback returns a false value, the first such is returned
5614 // Otherwise, the first callback's return value (trueish) is returned
5615 // Returns true if list of callbacks is empty
5616 RUN_CALLBACKS_MODE_AND,
5617 // Like above, but stops calling callbacks (short circuit)
5618 // after seeing the first false value
5619 RUN_CALLBACKS_MODE_AND_SC,
5620 // If any callback returns a true value, the first such is returned
5621 // Otherwise, the first callback's return value (falseish) is returned
5622 // Returns false if list of callbacks is empty
5623 RUN_CALLBACKS_MODE_OR,
5624 // Like above, but stops calling callbacks (short circuit)
5625 // after seeing the first true value
5626 RUN_CALLBACKS_MODE_OR_SC,
5627 // Note: "a true value" and "a false value" refer to values that
5628 // are converted by lua_toboolean to true or false, respectively.
5631 // Push the list of callbacks (a lua table).
5632 // Then push nargs arguments.
5633 // Then call this function, which
5634 // - runs the callbacks
5635 // - removes the table and arguments from the lua stack
5636 // - pushes the return value, computed depending on mode
5637 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5638 RunCallbacksMode mode)
5640 // Insert the return value into the lua stack, below the table
5641 assert(lua_gettop(L) >= nargs + 1);
5643 lua_insert(L, -(nargs + 1) - 1);
5644 // Stack now looks like this:
5645 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5647 int rv = lua_gettop(L) - nargs - 1;
5649 int arg = table + 1;
5651 luaL_checktype(L, table, LUA_TTABLE);
5655 bool first_loop = true;
5656 while(lua_next(L, table) != 0){
5657 // key at index -2 and value at index -1
5658 luaL_checktype(L, -1, LUA_TFUNCTION);
5660 for(int i = 0; i < nargs; i++)
5661 lua_pushvalue(L, arg+i);
5662 if(lua_pcall(L, nargs, 1, 0))
5663 script_error(L, "error: %s", lua_tostring(L, -1));
5665 // Move return value to designated space in stack
5668 // Result of first callback is always moved
5672 // Otherwise, what happens depends on the mode
5673 if(mode == RUN_CALLBACKS_MODE_FIRST)
5675 else if(mode == RUN_CALLBACKS_MODE_LAST)
5677 else if(mode == RUN_CALLBACKS_MODE_AND ||
5678 mode == RUN_CALLBACKS_MODE_AND_SC){
5679 if((bool)lua_toboolean(L, rv) == true &&
5680 (bool)lua_toboolean(L, -1) == false)
5685 else if(mode == RUN_CALLBACKS_MODE_OR ||
5686 mode == RUN_CALLBACKS_MODE_OR_SC){
5687 if((bool)lua_toboolean(L, rv) == false &&
5688 (bool)lua_toboolean(L, -1) == true)
5697 // Handle short circuit modes
5698 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5699 (bool)lua_toboolean(L, rv) == false)
5701 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5702 (bool)lua_toboolean(L, rv) == true)
5705 // value removed, keep key for next iteration
5708 // Remove stuff from stack, leaving only the return value
5711 // Fix return value in case no callbacks were called
5713 if(mode == RUN_CALLBACKS_MODE_AND ||
5714 mode == RUN_CALLBACKS_MODE_AND_SC){
5716 lua_pushboolean(L, true);
5718 else if(mode == RUN_CALLBACKS_MODE_OR ||
5719 mode == RUN_CALLBACKS_MODE_OR_SC){
5721 lua_pushboolean(L, false);
5726 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5727 const std::string &message)
5730 assert(lua_checkstack(L, 20));
5731 StackUnroller stack_unroller(L);
5733 // Get minetest.registered_on_chat_messages
5734 lua_getglobal(L, "minetest");
5735 lua_getfield(L, -1, "registered_on_chat_messages");
5737 lua_pushstring(L, name.c_str());
5738 lua_pushstring(L, message.c_str());
5739 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5740 bool ate = lua_toboolean(L, -1);
5744 void scriptapi_on_shutdown(lua_State *L)
5747 assert(lua_checkstack(L, 20));
5748 StackUnroller stack_unroller(L);
5750 // Get registered shutdown hooks
5751 lua_getglobal(L, "minetest");
5752 lua_getfield(L, -1, "registered_on_shutdown");
5754 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5757 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5760 assert(lua_checkstack(L, 20));
5761 StackUnroller stack_unroller(L);
5763 // Get minetest.registered_on_newplayers
5764 lua_getglobal(L, "minetest");
5765 lua_getfield(L, -1, "registered_on_newplayers");
5767 objectref_get_or_create(L, player);
5768 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5771 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5774 assert(lua_checkstack(L, 20));
5775 StackUnroller stack_unroller(L);
5777 // Get minetest.registered_on_dieplayers
5778 lua_getglobal(L, "minetest");
5779 lua_getfield(L, -1, "registered_on_dieplayers");
5781 objectref_get_or_create(L, player);
5782 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5785 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5788 assert(lua_checkstack(L, 20));
5789 StackUnroller stack_unroller(L);
5791 // Get minetest.registered_on_respawnplayers
5792 lua_getglobal(L, "minetest");
5793 lua_getfield(L, -1, "registered_on_respawnplayers");
5795 objectref_get_or_create(L, player);
5796 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5797 bool positioning_handled_by_some = lua_toboolean(L, -1);
5798 return positioning_handled_by_some;
5801 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5804 assert(lua_checkstack(L, 20));
5805 StackUnroller stack_unroller(L);
5807 // Get minetest.registered_on_joinplayers
5808 lua_getglobal(L, "minetest");
5809 lua_getfield(L, -1, "registered_on_joinplayers");
5811 objectref_get_or_create(L, player);
5812 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5815 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5818 assert(lua_checkstack(L, 20));
5819 StackUnroller stack_unroller(L);
5821 // Get minetest.registered_on_leaveplayers
5822 lua_getglobal(L, "minetest");
5823 lua_getfield(L, -1, "registered_on_leaveplayers");
5825 objectref_get_or_create(L, player);
5826 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5829 static void get_auth_handler(lua_State *L)
5831 lua_getglobal(L, "minetest");
5832 lua_getfield(L, -1, "registered_auth_handler");
5833 if(lua_isnil(L, -1)){
5835 lua_getfield(L, -1, "builtin_auth_handler");
5837 if(lua_type(L, -1) != LUA_TTABLE)
5838 throw LuaError(L, "Authentication handler table not valid");
5841 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5842 std::string *dst_password, std::set<std::string> *dst_privs)
5845 assert(lua_checkstack(L, 20));
5846 StackUnroller stack_unroller(L);
5848 get_auth_handler(L);
5849 lua_getfield(L, -1, "get_auth");
5850 if(lua_type(L, -1) != LUA_TFUNCTION)
5851 throw LuaError(L, "Authentication handler missing get_auth");
5852 lua_pushstring(L, playername.c_str());
5853 if(lua_pcall(L, 1, 1, 0))
5854 script_error(L, "error: %s", lua_tostring(L, -1));
5856 // nil = login not allowed
5857 if(lua_isnil(L, -1))
5859 luaL_checktype(L, -1, LUA_TTABLE);
5861 std::string password;
5862 bool found = getstringfield(L, -1, "password", password);
5864 throw LuaError(L, "Authentication handler didn't return password");
5866 *dst_password = password;
5868 lua_getfield(L, -1, "privileges");
5869 if(!lua_istable(L, -1))
5871 "Authentication handler didn't return privilege table");
5873 read_privileges(L, -1, *dst_privs);
5879 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5880 const std::string &password)
5883 assert(lua_checkstack(L, 20));
5884 StackUnroller stack_unroller(L);
5886 get_auth_handler(L);
5887 lua_getfield(L, -1, "create_auth");
5888 if(lua_type(L, -1) != LUA_TFUNCTION)
5889 throw LuaError(L, "Authentication handler missing create_auth");
5890 lua_pushstring(L, playername.c_str());
5891 lua_pushstring(L, password.c_str());
5892 if(lua_pcall(L, 2, 0, 0))
5893 script_error(L, "error: %s", lua_tostring(L, -1));
5896 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5897 const std::string &password)
5900 assert(lua_checkstack(L, 20));
5901 StackUnroller stack_unroller(L);
5903 get_auth_handler(L);
5904 lua_getfield(L, -1, "set_password");
5905 if(lua_type(L, -1) != LUA_TFUNCTION)
5906 throw LuaError(L, "Authentication handler missing set_password");
5907 lua_pushstring(L, playername.c_str());
5908 lua_pushstring(L, password.c_str());
5909 if(lua_pcall(L, 2, 1, 0))
5910 script_error(L, "error: %s", lua_tostring(L, -1));
5911 return lua_toboolean(L, -1);
5918 void scriptapi_on_player_receive_fields(lua_State *L,
5919 ServerActiveObject *player,
5920 const std::string &formname,
5921 const std::map<std::string, std::string> &fields)
5924 assert(lua_checkstack(L, 20));
5925 StackUnroller stack_unroller(L);
5927 // Get minetest.registered_on_chat_messages
5928 lua_getglobal(L, "minetest");
5929 lua_getfield(L, -1, "registered_on_player_receive_fields");
5932 objectref_get_or_create(L, player);
5934 lua_pushstring(L, formname.c_str());
5937 for(std::map<std::string, std::string>::const_iterator
5938 i = fields.begin(); i != fields.end(); i++){
5939 const std::string &name = i->first;
5940 const std::string &value = i->second;
5941 lua_pushstring(L, name.c_str());
5942 lua_pushlstring(L, value.c_str(), value.size());
5943 lua_settable(L, -3);
5945 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5949 item callbacks and node callbacks
5952 // Retrieves minetest.registered_items[name][callbackname]
5953 // If that is nil or on error, return false and stack is unchanged
5954 // If that is a function, returns true and pushes the
5955 // function onto the stack
5956 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5957 // is tried instead so unknown items can still be manipulated to some degree
5958 static bool get_item_callback(lua_State *L,
5959 const char *name, const char *callbackname)
5961 lua_getglobal(L, "minetest");
5962 lua_getfield(L, -1, "registered_items");
5964 luaL_checktype(L, -1, LUA_TTABLE);
5965 lua_getfield(L, -1, name);
5967 // Should be a table
5968 if(lua_type(L, -1) != LUA_TTABLE)
5970 // Report error and clean up
5971 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5974 // Try minetest.nodedef_default instead
5975 lua_getglobal(L, "minetest");
5976 lua_getfield(L, -1, "nodedef_default");
5978 luaL_checktype(L, -1, LUA_TTABLE);
5980 lua_getfield(L, -1, callbackname);
5982 // Should be a function or nil
5983 if(lua_type(L, -1) == LUA_TFUNCTION)
5987 else if(lua_isnil(L, -1))
5994 errorstream<<"Item \""<<name<<"\" callback \""
5995 <<callbackname<<" is not a function"<<std::endl;
6001 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6002 ServerActiveObject *dropper, v3f pos)
6005 assert(lua_checkstack(L, 20));
6006 StackUnroller stack_unroller(L);
6008 // Push callback function on stack
6009 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6013 LuaItemStack::create(L, item);
6014 objectref_get_or_create(L, dropper);
6015 pushFloatPos(L, pos);
6016 if(lua_pcall(L, 3, 1, 0))
6017 script_error(L, "error: %s", lua_tostring(L, -1));
6018 if(!lua_isnil(L, -1))
6019 item = read_item(L, -1);
6023 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6024 ServerActiveObject *placer, const PointedThing &pointed)
6027 assert(lua_checkstack(L, 20));
6028 StackUnroller stack_unroller(L);
6030 // Push callback function on stack
6031 if(!get_item_callback(L, item.name.c_str(), "on_place"))
6035 LuaItemStack::create(L, item);
6036 objectref_get_or_create(L, placer);
6037 push_pointed_thing(L, pointed);
6038 if(lua_pcall(L, 3, 1, 0))
6039 script_error(L, "error: %s", lua_tostring(L, -1));
6040 if(!lua_isnil(L, -1))
6041 item = read_item(L, -1);
6045 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6046 ServerActiveObject *user, const PointedThing &pointed)
6049 assert(lua_checkstack(L, 20));
6050 StackUnroller stack_unroller(L);
6052 // Push callback function on stack
6053 if(!get_item_callback(L, item.name.c_str(), "on_use"))
6057 LuaItemStack::create(L, item);
6058 objectref_get_or_create(L, user);
6059 push_pointed_thing(L, pointed);
6060 if(lua_pcall(L, 3, 1, 0))
6061 script_error(L, "error: %s", lua_tostring(L, -1));
6062 if(!lua_isnil(L, -1))
6063 item = read_item(L, -1);
6067 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6068 ServerActiveObject *puncher)
6071 assert(lua_checkstack(L, 20));
6072 StackUnroller stack_unroller(L);
6074 INodeDefManager *ndef = get_server(L)->ndef();
6076 // Push callback function on stack
6077 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6082 pushnode(L, node, ndef);
6083 objectref_get_or_create(L, puncher);
6084 if(lua_pcall(L, 3, 0, 0))
6085 script_error(L, "error: %s", lua_tostring(L, -1));
6089 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6090 ServerActiveObject *digger)
6093 assert(lua_checkstack(L, 20));
6094 StackUnroller stack_unroller(L);
6096 INodeDefManager *ndef = get_server(L)->ndef();
6098 // Push callback function on stack
6099 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6104 pushnode(L, node, ndef);
6105 objectref_get_or_create(L, digger);
6106 if(lua_pcall(L, 3, 0, 0))
6107 script_error(L, "error: %s", lua_tostring(L, -1));
6111 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6114 assert(lua_checkstack(L, 20));
6115 StackUnroller stack_unroller(L);
6117 INodeDefManager *ndef = get_server(L)->ndef();
6119 // Push callback function on stack
6120 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6125 if(lua_pcall(L, 1, 0, 0))
6126 script_error(L, "error: %s", lua_tostring(L, -1));
6129 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6132 assert(lua_checkstack(L, 20));
6133 StackUnroller stack_unroller(L);
6135 INodeDefManager *ndef = get_server(L)->ndef();
6137 // Push callback function on stack
6138 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6143 if(lua_pcall(L, 1, 0, 0))
6144 script_error(L, "error: %s", lua_tostring(L, -1));
6147 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6150 assert(lua_checkstack(L, 20));
6151 StackUnroller stack_unroller(L);
6153 INodeDefManager *ndef = get_server(L)->ndef();
6155 // Push callback function on stack
6156 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6161 pushnode(L, node, ndef);
6162 if(lua_pcall(L, 2, 0, 0))
6163 script_error(L, "error: %s", lua_tostring(L, -1));
6166 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6169 assert(lua_checkstack(L, 20));
6170 StackUnroller stack_unroller(L);
6172 INodeDefManager *ndef = get_server(L)->ndef();
6174 // Push callback function on stack
6175 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6180 lua_pushnumber(L,dtime);
6181 if(lua_pcall(L, 2, 1, 0))
6182 script_error(L, "error: %s", lua_tostring(L, -1));
6183 if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6189 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6190 const std::string &formname,
6191 const std::map<std::string, std::string> &fields,
6192 ServerActiveObject *sender)
6195 assert(lua_checkstack(L, 20));
6196 StackUnroller stack_unroller(L);
6198 INodeDefManager *ndef = get_server(L)->ndef();
6200 // If node doesn't exist, we don't know what callback to call
6201 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6202 if(node.getContent() == CONTENT_IGNORE)
6205 // Push callback function on stack
6206 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6213 lua_pushstring(L, formname.c_str());
6216 for(std::map<std::string, std::string>::const_iterator
6217 i = fields.begin(); i != fields.end(); i++){
6218 const std::string &name = i->first;
6219 const std::string &value = i->second;
6220 lua_pushstring(L, name.c_str());
6221 lua_pushlstring(L, value.c_str(), value.size());
6222 lua_settable(L, -3);
6225 objectref_get_or_create(L, sender);
6226 if(lua_pcall(L, 4, 0, 0))
6227 script_error(L, "error: %s", lua_tostring(L, -1));
6231 Node metadata inventory callbacks
6234 // Return number of accepted items to be moved
6235 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6236 const std::string &from_list, int from_index,
6237 const std::string &to_list, int to_index,
6238 int count, ServerActiveObject *player)
6241 assert(lua_checkstack(L, 20));
6242 StackUnroller stack_unroller(L);
6244 INodeDefManager *ndef = get_server(L)->ndef();
6246 // If node doesn't exist, we don't know what callback to call
6247 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6248 if(node.getContent() == CONTENT_IGNORE)
6251 // Push callback function on stack
6252 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6253 "allow_metadata_inventory_move"))
6256 // function(pos, from_list, from_index, to_list, to_index, count, player)
6260 lua_pushstring(L, from_list.c_str());
6262 lua_pushinteger(L, from_index + 1);
6264 lua_pushstring(L, to_list.c_str());
6266 lua_pushinteger(L, to_index + 1);
6268 lua_pushinteger(L, count);
6270 objectref_get_or_create(L, player);
6271 if(lua_pcall(L, 7, 1, 0))
6272 script_error(L, "error: %s", lua_tostring(L, -1));
6273 if(!lua_isnumber(L, -1))
6274 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6275 return luaL_checkinteger(L, -1);
6278 // Return number of accepted items to be put
6279 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6280 const std::string &listname, int index, ItemStack &stack,
6281 ServerActiveObject *player)
6284 assert(lua_checkstack(L, 20));
6285 StackUnroller stack_unroller(L);
6287 INodeDefManager *ndef = get_server(L)->ndef();
6289 // If node doesn't exist, we don't know what callback to call
6290 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6291 if(node.getContent() == CONTENT_IGNORE)
6294 // Push callback function on stack
6295 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6296 "allow_metadata_inventory_put"))
6299 // Call function(pos, listname, index, stack, player)
6303 lua_pushstring(L, listname.c_str());
6305 lua_pushinteger(L, index + 1);
6307 LuaItemStack::create(L, stack);
6309 objectref_get_or_create(L, player);
6310 if(lua_pcall(L, 5, 1, 0))
6311 script_error(L, "error: %s", lua_tostring(L, -1));
6312 if(!lua_isnumber(L, -1))
6313 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6314 return luaL_checkinteger(L, -1);
6317 // Return number of accepted items to be taken
6318 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6319 const std::string &listname, int index, ItemStack &stack,
6320 ServerActiveObject *player)
6323 assert(lua_checkstack(L, 20));
6324 StackUnroller stack_unroller(L);
6326 INodeDefManager *ndef = get_server(L)->ndef();
6328 // If node doesn't exist, we don't know what callback to call
6329 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6330 if(node.getContent() == CONTENT_IGNORE)
6333 // Push callback function on stack
6334 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6335 "allow_metadata_inventory_take"))
6338 // Call function(pos, listname, index, count, player)
6342 lua_pushstring(L, listname.c_str());
6344 lua_pushinteger(L, index + 1);
6346 LuaItemStack::create(L, stack);
6348 objectref_get_or_create(L, player);
6349 if(lua_pcall(L, 5, 1, 0))
6350 script_error(L, "error: %s", lua_tostring(L, -1));
6351 if(!lua_isnumber(L, -1))
6352 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6353 return luaL_checkinteger(L, -1);
6356 // Report moved items
6357 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6358 const std::string &from_list, int from_index,
6359 const std::string &to_list, int to_index,
6360 int count, ServerActiveObject *player)
6363 assert(lua_checkstack(L, 20));
6364 StackUnroller stack_unroller(L);
6366 INodeDefManager *ndef = get_server(L)->ndef();
6368 // If node doesn't exist, we don't know what callback to call
6369 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6370 if(node.getContent() == CONTENT_IGNORE)
6373 // Push callback function on stack
6374 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6375 "on_metadata_inventory_move"))
6378 // function(pos, from_list, from_index, to_list, to_index, count, player)
6382 lua_pushstring(L, from_list.c_str());
6384 lua_pushinteger(L, from_index + 1);
6386 lua_pushstring(L, to_list.c_str());
6388 lua_pushinteger(L, to_index + 1);
6390 lua_pushinteger(L, count);
6392 objectref_get_or_create(L, player);
6393 if(lua_pcall(L, 7, 0, 0))
6394 script_error(L, "error: %s", lua_tostring(L, -1));
6398 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6399 const std::string &listname, int index, ItemStack &stack,
6400 ServerActiveObject *player)
6403 assert(lua_checkstack(L, 20));
6404 StackUnroller stack_unroller(L);
6406 INodeDefManager *ndef = get_server(L)->ndef();
6408 // If node doesn't exist, we don't know what callback to call
6409 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6410 if(node.getContent() == CONTENT_IGNORE)
6413 // Push callback function on stack
6414 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6415 "on_metadata_inventory_put"))
6418 // Call function(pos, listname, index, stack, player)
6422 lua_pushstring(L, listname.c_str());
6424 lua_pushinteger(L, index + 1);
6426 LuaItemStack::create(L, stack);
6428 objectref_get_or_create(L, player);
6429 if(lua_pcall(L, 5, 0, 0))
6430 script_error(L, "error: %s", lua_tostring(L, -1));
6433 // Report taken items
6434 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6435 const std::string &listname, int index, ItemStack &stack,
6436 ServerActiveObject *player)
6439 assert(lua_checkstack(L, 20));
6440 StackUnroller stack_unroller(L);
6442 INodeDefManager *ndef = get_server(L)->ndef();
6444 // If node doesn't exist, we don't know what callback to call
6445 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6446 if(node.getContent() == CONTENT_IGNORE)
6449 // Push callback function on stack
6450 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6451 "on_metadata_inventory_take"))
6454 // Call function(pos, listname, index, stack, player)
6458 lua_pushstring(L, listname.c_str());
6460 lua_pushinteger(L, index + 1);
6462 LuaItemStack::create(L, stack);
6464 objectref_get_or_create(L, player);
6465 if(lua_pcall(L, 5, 0, 0))
6466 script_error(L, "error: %s", lua_tostring(L, -1));
6470 Detached inventory callbacks
6473 // Retrieves minetest.detached_inventories[name][callbackname]
6474 // If that is nil or on error, return false and stack is unchanged
6475 // If that is a function, returns true and pushes the
6476 // function onto the stack
6477 static bool get_detached_inventory_callback(lua_State *L,
6478 const std::string &name, const char *callbackname)
6480 lua_getglobal(L, "minetest");
6481 lua_getfield(L, -1, "detached_inventories");
6483 luaL_checktype(L, -1, LUA_TTABLE);
6484 lua_getfield(L, -1, name.c_str());
6486 // Should be a table
6487 if(lua_type(L, -1) != LUA_TTABLE)
6489 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6493 lua_getfield(L, -1, callbackname);
6495 // Should be a function or nil
6496 if(lua_type(L, -1) == LUA_TFUNCTION)
6500 else if(lua_isnil(L, -1))
6507 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6508 <<callbackname<<"\" is not a function"<<std::endl;
6514 // Return number of accepted items to be moved
6515 int scriptapi_detached_inventory_allow_move(lua_State *L,
6516 const std::string &name,
6517 const std::string &from_list, int from_index,
6518 const std::string &to_list, int to_index,
6519 int count, ServerActiveObject *player)
6522 assert(lua_checkstack(L, 20));
6523 StackUnroller stack_unroller(L);
6525 // Push callback function on stack
6526 if(!get_detached_inventory_callback(L, name, "allow_move"))
6529 // function(inv, from_list, from_index, to_list, to_index, count, player)
6531 InventoryLocation loc;
6532 loc.setDetached(name);
6533 InvRef::create(L, loc);
6535 lua_pushstring(L, from_list.c_str());
6537 lua_pushinteger(L, from_index + 1);
6539 lua_pushstring(L, to_list.c_str());
6541 lua_pushinteger(L, to_index + 1);
6543 lua_pushinteger(L, count);
6545 objectref_get_or_create(L, player);
6546 if(lua_pcall(L, 7, 1, 0))
6547 script_error(L, "error: %s", lua_tostring(L, -1));
6548 if(!lua_isnumber(L, -1))
6549 throw LuaError(L, "allow_move should return a number");
6550 return luaL_checkinteger(L, -1);
6553 // Return number of accepted items to be put
6554 int scriptapi_detached_inventory_allow_put(lua_State *L,
6555 const std::string &name,
6556 const std::string &listname, int index, ItemStack &stack,
6557 ServerActiveObject *player)
6560 assert(lua_checkstack(L, 20));
6561 StackUnroller stack_unroller(L);
6563 // Push callback function on stack
6564 if(!get_detached_inventory_callback(L, name, "allow_put"))
6565 return stack.count; // All will be accepted
6567 // Call function(inv, listname, index, stack, player)
6569 InventoryLocation loc;
6570 loc.setDetached(name);
6571 InvRef::create(L, loc);
6573 lua_pushstring(L, listname.c_str());
6575 lua_pushinteger(L, index + 1);
6577 LuaItemStack::create(L, stack);
6579 objectref_get_or_create(L, player);
6580 if(lua_pcall(L, 5, 1, 0))
6581 script_error(L, "error: %s", lua_tostring(L, -1));
6582 if(!lua_isnumber(L, -1))
6583 throw LuaError(L, "allow_put should return a number");
6584 return luaL_checkinteger(L, -1);
6587 // Return number of accepted items to be taken
6588 int scriptapi_detached_inventory_allow_take(lua_State *L,
6589 const std::string &name,
6590 const std::string &listname, int index, ItemStack &stack,
6591 ServerActiveObject *player)
6594 assert(lua_checkstack(L, 20));
6595 StackUnroller stack_unroller(L);
6597 // Push callback function on stack
6598 if(!get_detached_inventory_callback(L, name, "allow_take"))
6599 return stack.count; // All will be accepted
6601 // Call function(inv, listname, index, stack, player)
6603 InventoryLocation loc;
6604 loc.setDetached(name);
6605 InvRef::create(L, loc);
6607 lua_pushstring(L, listname.c_str());
6609 lua_pushinteger(L, index + 1);
6611 LuaItemStack::create(L, stack);
6613 objectref_get_or_create(L, player);
6614 if(lua_pcall(L, 5, 1, 0))
6615 script_error(L, "error: %s", lua_tostring(L, -1));
6616 if(!lua_isnumber(L, -1))
6617 throw LuaError(L, "allow_take should return a number");
6618 return luaL_checkinteger(L, -1);
6621 // Report moved items
6622 void scriptapi_detached_inventory_on_move(lua_State *L,
6623 const std::string &name,
6624 const std::string &from_list, int from_index,
6625 const std::string &to_list, int to_index,
6626 int count, ServerActiveObject *player)
6629 assert(lua_checkstack(L, 20));
6630 StackUnroller stack_unroller(L);
6632 // Push callback function on stack
6633 if(!get_detached_inventory_callback(L, name, "on_move"))
6636 // function(inv, from_list, from_index, to_list, to_index, count, player)
6638 InventoryLocation loc;
6639 loc.setDetached(name);
6640 InvRef::create(L, loc);
6642 lua_pushstring(L, from_list.c_str());
6644 lua_pushinteger(L, from_index + 1);
6646 lua_pushstring(L, to_list.c_str());
6648 lua_pushinteger(L, to_index + 1);
6650 lua_pushinteger(L, count);
6652 objectref_get_or_create(L, player);
6653 if(lua_pcall(L, 7, 0, 0))
6654 script_error(L, "error: %s", lua_tostring(L, -1));
6658 void scriptapi_detached_inventory_on_put(lua_State *L,
6659 const std::string &name,
6660 const std::string &listname, int index, ItemStack &stack,
6661 ServerActiveObject *player)
6664 assert(lua_checkstack(L, 20));
6665 StackUnroller stack_unroller(L);
6667 // Push callback function on stack
6668 if(!get_detached_inventory_callback(L, name, "on_put"))
6671 // Call function(inv, listname, index, stack, player)
6673 InventoryLocation loc;
6674 loc.setDetached(name);
6675 InvRef::create(L, loc);
6677 lua_pushstring(L, listname.c_str());
6679 lua_pushinteger(L, index + 1);
6681 LuaItemStack::create(L, stack);
6683 objectref_get_or_create(L, player);
6684 if(lua_pcall(L, 5, 0, 0))
6685 script_error(L, "error: %s", lua_tostring(L, -1));
6688 // Report taken items
6689 void scriptapi_detached_inventory_on_take(lua_State *L,
6690 const std::string &name,
6691 const std::string &listname, int index, ItemStack &stack,
6692 ServerActiveObject *player)
6695 assert(lua_checkstack(L, 20));
6696 StackUnroller stack_unroller(L);
6698 // Push callback function on stack
6699 if(!get_detached_inventory_callback(L, name, "on_take"))
6702 // Call function(inv, listname, index, stack, player)
6704 InventoryLocation loc;
6705 loc.setDetached(name);
6706 InvRef::create(L, loc);
6708 lua_pushstring(L, listname.c_str());
6710 lua_pushinteger(L, index + 1);
6712 LuaItemStack::create(L, stack);
6714 objectref_get_or_create(L, player);
6715 if(lua_pcall(L, 5, 0, 0))
6716 script_error(L, "error: %s", lua_tostring(L, -1));
6723 void scriptapi_environment_step(lua_State *L, float dtime)
6726 assert(lua_checkstack(L, 20));
6727 //infostream<<"scriptapi_environment_step"<<std::endl;
6728 StackUnroller stack_unroller(L);
6730 // Get minetest.registered_globalsteps
6731 lua_getglobal(L, "minetest");
6732 lua_getfield(L, -1, "registered_globalsteps");
6734 lua_pushnumber(L, dtime);
6735 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6738 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6742 assert(lua_checkstack(L, 20));
6743 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6744 StackUnroller stack_unroller(L);
6746 // Get minetest.registered_on_generateds
6747 lua_getglobal(L, "minetest");
6748 lua_getfield(L, -1, "registered_on_generateds");
6750 push_v3s16(L, minp);
6751 push_v3s16(L, maxp);
6752 lua_pushnumber(L, blockseed);
6753 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6760 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6763 assert(lua_checkstack(L, 20));
6764 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6765 <<name<<"\""<<std::endl;
6766 StackUnroller stack_unroller(L);
6768 // Get minetest.registered_entities[name]
6769 lua_getglobal(L, "minetest");
6770 lua_getfield(L, -1, "registered_entities");
6771 luaL_checktype(L, -1, LUA_TTABLE);
6772 lua_pushstring(L, name);
6773 lua_gettable(L, -2);
6774 // Should be a table, which we will use as a prototype
6775 //luaL_checktype(L, -1, LUA_TTABLE);
6776 if(lua_type(L, -1) != LUA_TTABLE){
6777 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6780 int prototype_table = lua_gettop(L);
6781 //dump2(L, "prototype_table");
6783 // Create entity object
6785 int object = lua_gettop(L);
6787 // Set object metatable
6788 lua_pushvalue(L, prototype_table);
6789 lua_setmetatable(L, -2);
6791 // Add object reference
6792 // This should be userdata with metatable ObjectRef
6793 objectref_get(L, id);
6794 luaL_checktype(L, -1, LUA_TUSERDATA);
6795 if(!luaL_checkudata(L, -1, "ObjectRef"))
6796 luaL_typerror(L, -1, "ObjectRef");
6797 lua_setfield(L, -2, "object");
6799 // minetest.luaentities[id] = object
6800 lua_getglobal(L, "minetest");
6801 lua_getfield(L, -1, "luaentities");
6802 luaL_checktype(L, -1, LUA_TTABLE);
6803 lua_pushnumber(L, id); // Push id
6804 lua_pushvalue(L, object); // Copy object to top of stack
6805 lua_settable(L, -3);
6810 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6811 const std::string &staticdata, u32 dtime_s)
6814 assert(lua_checkstack(L, 20));
6815 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6816 StackUnroller stack_unroller(L);
6818 // Get minetest.luaentities[id]
6819 luaentity_get(L, id);
6820 int object = lua_gettop(L);
6822 // Get on_activate function
6823 lua_pushvalue(L, object);
6824 lua_getfield(L, -1, "on_activate");
6825 if(!lua_isnil(L, -1)){
6826 luaL_checktype(L, -1, LUA_TFUNCTION);
6827 lua_pushvalue(L, object); // self
6828 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6829 lua_pushinteger(L, dtime_s);
6830 // Call with 3 arguments, 0 results
6831 if(lua_pcall(L, 3, 0, 0))
6832 script_error(L, "error running function on_activate: %s\n",
6833 lua_tostring(L, -1));
6837 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6840 assert(lua_checkstack(L, 20));
6841 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6843 // Get minetest.luaentities table
6844 lua_getglobal(L, "minetest");
6845 lua_getfield(L, -1, "luaentities");
6846 luaL_checktype(L, -1, LUA_TTABLE);
6847 int objectstable = lua_gettop(L);
6849 // Set luaentities[id] = nil
6850 lua_pushnumber(L, id); // Push id
6852 lua_settable(L, objectstable);
6854 lua_pop(L, 2); // pop luaentities, minetest
6857 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6860 assert(lua_checkstack(L, 20));
6861 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6862 StackUnroller stack_unroller(L);
6864 // Get minetest.luaentities[id]
6865 luaentity_get(L, id);
6866 int object = lua_gettop(L);
6868 // Get get_staticdata function
6869 lua_pushvalue(L, object);
6870 lua_getfield(L, -1, "get_staticdata");
6871 if(lua_isnil(L, -1))
6874 luaL_checktype(L, -1, LUA_TFUNCTION);
6875 lua_pushvalue(L, object); // self
6876 // Call with 1 arguments, 1 results
6877 if(lua_pcall(L, 1, 1, 0))
6878 script_error(L, "error running function get_staticdata: %s\n",
6879 lua_tostring(L, -1));
6882 const char *s = lua_tolstring(L, -1, &len);
6883 return std::string(s, len);
6886 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6887 ObjectProperties *prop)
6890 assert(lua_checkstack(L, 20));
6891 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6892 StackUnroller stack_unroller(L);
6894 // Get minetest.luaentities[id]
6895 luaentity_get(L, id);
6896 //int object = lua_gettop(L);
6898 // Set default values that differ from ObjectProperties defaults
6903 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6905 getboolfield(L, -1, "physical", prop->physical);
6907 getfloatfield(L, -1, "weight", prop->weight);
6909 lua_getfield(L, -1, "collisionbox");
6910 if(lua_istable(L, -1))
6911 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6914 getstringfield(L, -1, "visual", prop->visual);
6916 getstringfield(L, -1, "mesh", prop->mesh);
6918 // Deprecated: read object properties directly
6919 read_object_properties(L, -1, prop);
6921 // Read initial_properties
6922 lua_getfield(L, -1, "initial_properties");
6923 read_object_properties(L, -1, prop);
6927 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6930 assert(lua_checkstack(L, 20));
6931 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6932 StackUnroller stack_unroller(L);
6934 // Get minetest.luaentities[id]
6935 luaentity_get(L, id);
6936 int object = lua_gettop(L);
6937 // State: object is at top of stack
6938 // Get step function
6939 lua_getfield(L, -1, "on_step");
6940 if(lua_isnil(L, -1))
6942 luaL_checktype(L, -1, LUA_TFUNCTION);
6943 lua_pushvalue(L, object); // self
6944 lua_pushnumber(L, dtime); // dtime
6945 // Call with 2 arguments, 0 results
6946 if(lua_pcall(L, 2, 0, 0))
6947 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6950 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6951 // tool_capabilities, direction)
6952 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6953 ServerActiveObject *puncher, float time_from_last_punch,
6954 const ToolCapabilities *toolcap, v3f dir)
6957 assert(lua_checkstack(L, 20));
6958 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6959 StackUnroller stack_unroller(L);
6961 // Get minetest.luaentities[id]
6962 luaentity_get(L, id);
6963 int object = lua_gettop(L);
6964 // State: object is at top of stack
6966 lua_getfield(L, -1, "on_punch");
6967 if(lua_isnil(L, -1))
6969 luaL_checktype(L, -1, LUA_TFUNCTION);
6970 lua_pushvalue(L, object); // self
6971 objectref_get_or_create(L, puncher); // Clicker reference
6972 lua_pushnumber(L, time_from_last_punch);
6973 push_tool_capabilities(L, *toolcap);
6975 // Call with 5 arguments, 0 results
6976 if(lua_pcall(L, 5, 0, 0))
6977 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6980 // Calls entity:on_rightclick(ObjectRef clicker)
6981 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6982 ServerActiveObject *clicker)
6985 assert(lua_checkstack(L, 20));
6986 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6987 StackUnroller stack_unroller(L);
6989 // Get minetest.luaentities[id]
6990 luaentity_get(L, id);
6991 int object = lua_gettop(L);
6992 // State: object is at top of stack
6994 lua_getfield(L, -1, "on_rightclick");
6995 if(lua_isnil(L, -1))
6997 luaL_checktype(L, -1, LUA_TFUNCTION);
6998 lua_pushvalue(L, object); // self
6999 objectref_get_or_create(L, clicker); // Clicker reference
7000 // Call with 2 arguments, 0 results
7001 if(lua_pcall(L, 2, 0, 0))
7002 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));