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)->getBiomeDef();
4468 verbosestream << "register_biome_groups: BiomeDefManager not active" << std::endl;
4473 for (int i = 1; lua_next(L, index) != 0; i++) {
4474 bmgr->addBiomeGroup(lua_tonumber(L, -1));
4482 // register_biome({lots of stuff})
4483 static int l_register_biome(lua_State *L)
4485 luaL_checktype(L, 1, LUA_TTABLE);
4486 int index = 1, groupid;
4487 std::string nodename;
4489 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
4490 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4492 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
4496 groupid = getintfield_default(L, index, "group_id", 0);
4498 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
4499 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
4500 Biome *b = bmgr->createBiome(terrain);
4502 b->name = getstringfield_default(L, index, "name", "");
4504 if (getstringfield(L, index, "node_top", nodename))
4505 b->n_top = MapNode(ndef->getId(nodename));
4507 b->n_top = MapNode(CONTENT_IGNORE);
4509 if (getstringfield(L, index, "node_filler", nodename))
4510 b->n_filler = MapNode(ndef->getId(nodename));
4512 b->n_filler = b->n_top;
4514 b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
4516 b->height_min = getintfield_default(L, index, "height_min", 0);
4517 b->height_max = getintfield_default(L, index, "height_max", 0);
4518 b->heat_min = getfloatfield_default(L, index, "heat_min", 0.);
4519 b->heat_max = getfloatfield_default(L, index, "heat_max", 0.);
4520 b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
4521 b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
4523 b->np = new NoiseParams; // should read an entire NoiseParams later on...
4524 getfloatfield(L, index, "scale", b->np->scale);
4525 getfloatfield(L, index, "offset", b->np->offset);
4527 b->groupid = (s8)groupid;
4528 b->flags = 0; //reserved
4532 verbosestream << "register_biome: " << b->name << std::endl;
4536 // register_item_raw({lots of stuff})
4537 static int l_register_item_raw(lua_State *L)
4539 luaL_checktype(L, 1, LUA_TTABLE);
4542 // Get the writable item and node definition managers from the server
4543 IWritableItemDefManager *idef =
4544 get_server(L)->getWritableItemDefManager();
4545 IWritableNodeDefManager *ndef =
4546 get_server(L)->getWritableNodeDefManager();
4548 // Check if name is defined
4550 lua_getfield(L, table, "name");
4551 if(lua_isstring(L, -1)){
4552 name = lua_tostring(L, -1);
4553 verbosestream<<"register_item_raw: "<<name<<std::endl;
4555 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4558 // Check if on_use is defined
4561 // Set a distinctive default value to check if this is set
4562 def.node_placement_prediction = "__default";
4564 // Read the item definition
4565 def = read_item_definition(L, table, def);
4567 // Default to having client-side placement prediction for nodes
4568 // ("" in item definition sets it off)
4569 if(def.node_placement_prediction == "__default"){
4570 if(def.type == ITEM_NODE)
4571 def.node_placement_prediction = name;
4573 def.node_placement_prediction = "";
4576 // Register item definition
4577 idef->registerItem(def);
4579 // Read the node definition (content features) and register it
4580 if(def.type == ITEM_NODE)
4582 ContentFeatures f = read_content_features(L, table);
4583 ndef->set(f.name, f);
4586 return 0; /* number of results */
4589 // register_alias_raw(name, convert_to_name)
4590 static int l_register_alias_raw(lua_State *L)
4592 std::string name = luaL_checkstring(L, 1);
4593 std::string convert_to = luaL_checkstring(L, 2);
4595 // Get the writable item definition manager from the server
4596 IWritableItemDefManager *idef =
4597 get_server(L)->getWritableItemDefManager();
4599 idef->registerAlias(name, convert_to);
4601 return 0; /* number of results */
4604 // helper for register_craft
4605 static bool read_craft_recipe_shaped(lua_State *L, int index,
4606 int &width, std::vector<std::string> &recipe)
4609 index = lua_gettop(L) + 1 + index;
4611 if(!lua_istable(L, index))
4616 while(lua_next(L, index) != 0){
4618 // key at index -2 and value at index -1
4619 if(!lua_istable(L, -1))
4621 int table2 = lua_gettop(L);
4623 while(lua_next(L, table2) != 0){
4624 // key at index -2 and value at index -1
4625 if(!lua_isstring(L, -1))
4627 recipe.push_back(lua_tostring(L, -1));
4628 // removes value, keeps key for next iteration
4635 if(colcount != width)
4638 // removes value, keeps key for next iteration
4645 // helper for register_craft
4646 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4647 std::vector<std::string> &recipe)
4650 index = lua_gettop(L) + 1 + index;
4652 if(!lua_istable(L, index))
4656 while(lua_next(L, index) != 0){
4657 // key at index -2 and value at index -1
4658 if(!lua_isstring(L, -1))
4660 recipe.push_back(lua_tostring(L, -1));
4661 // removes value, keeps key for next iteration
4667 // helper for register_craft
4668 static bool read_craft_replacements(lua_State *L, int index,
4669 CraftReplacements &replacements)
4672 index = lua_gettop(L) + 1 + index;
4674 if(!lua_istable(L, index))
4678 while(lua_next(L, index) != 0){
4679 // key at index -2 and value at index -1
4680 if(!lua_istable(L, -1))
4682 lua_rawgeti(L, -1, 1);
4683 if(!lua_isstring(L, -1))
4685 std::string replace_from = lua_tostring(L, -1);
4687 lua_rawgeti(L, -1, 2);
4688 if(!lua_isstring(L, -1))
4690 std::string replace_to = lua_tostring(L, -1);
4692 replacements.pairs.push_back(
4693 std::make_pair(replace_from, replace_to));
4694 // removes value, keeps key for next iteration
4699 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4700 static int l_register_craft(lua_State *L)
4702 //infostream<<"register_craft"<<std::endl;
4703 luaL_checktype(L, 1, LUA_TTABLE);
4706 // Get the writable craft definition manager from the server
4707 IWritableCraftDefManager *craftdef =
4708 get_server(L)->getWritableCraftDefManager();
4710 std::string type = getstringfield_default(L, table, "type", "shaped");
4713 CraftDefinitionShaped
4715 if(type == "shaped"){
4716 std::string output = getstringfield_default(L, table, "output", "");
4718 throw LuaError(L, "Crafting definition is missing an output");
4721 std::vector<std::string> recipe;
4722 lua_getfield(L, table, "recipe");
4723 if(lua_isnil(L, -1))
4724 throw LuaError(L, "Crafting definition is missing a recipe"
4725 " (output=\"" + output + "\")");
4726 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4727 throw LuaError(L, "Invalid crafting recipe"
4728 " (output=\"" + output + "\")");
4730 CraftReplacements replacements;
4731 lua_getfield(L, table, "replacements");
4732 if(!lua_isnil(L, -1))
4734 if(!read_craft_replacements(L, -1, replacements))
4735 throw LuaError(L, "Invalid replacements"
4736 " (output=\"" + output + "\")");
4739 CraftDefinition *def = new CraftDefinitionShaped(
4740 output, width, recipe, replacements);
4741 craftdef->registerCraft(def);
4744 CraftDefinitionShapeless
4746 else if(type == "shapeless"){
4747 std::string output = getstringfield_default(L, table, "output", "");
4749 throw LuaError(L, "Crafting definition (shapeless)"
4750 " is missing an output");
4752 std::vector<std::string> recipe;
4753 lua_getfield(L, table, "recipe");
4754 if(lua_isnil(L, -1))
4755 throw LuaError(L, "Crafting definition (shapeless)"
4756 " is missing a recipe"
4757 " (output=\"" + output + "\")");
4758 if(!read_craft_recipe_shapeless(L, -1, recipe))
4759 throw LuaError(L, "Invalid crafting recipe"
4760 " (output=\"" + output + "\")");
4762 CraftReplacements replacements;
4763 lua_getfield(L, table, "replacements");
4764 if(!lua_isnil(L, -1))
4766 if(!read_craft_replacements(L, -1, replacements))
4767 throw LuaError(L, "Invalid replacements"
4768 " (output=\"" + output + "\")");
4771 CraftDefinition *def = new CraftDefinitionShapeless(
4772 output, recipe, replacements);
4773 craftdef->registerCraft(def);
4776 CraftDefinitionToolRepair
4778 else if(type == "toolrepair"){
4779 float additional_wear = getfloatfield_default(L, table,
4780 "additional_wear", 0.0);
4782 CraftDefinition *def = new CraftDefinitionToolRepair(
4784 craftdef->registerCraft(def);
4787 CraftDefinitionCooking
4789 else if(type == "cooking"){
4790 std::string output = getstringfield_default(L, table, "output", "");
4792 throw LuaError(L, "Crafting definition (cooking)"
4793 " is missing an output");
4795 std::string recipe = getstringfield_default(L, table, "recipe", "");
4797 throw LuaError(L, "Crafting definition (cooking)"
4798 " is missing a recipe"
4799 " (output=\"" + output + "\")");
4801 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4803 CraftReplacements replacements;
4804 lua_getfield(L, table, "replacements");
4805 if(!lua_isnil(L, -1))
4807 if(!read_craft_replacements(L, -1, replacements))
4808 throw LuaError(L, "Invalid replacements"
4809 " (cooking output=\"" + output + "\")");
4812 CraftDefinition *def = new CraftDefinitionCooking(
4813 output, recipe, cooktime, replacements);
4814 craftdef->registerCraft(def);
4819 else if(type == "fuel"){
4820 std::string recipe = getstringfield_default(L, table, "recipe", "");
4822 throw LuaError(L, "Crafting definition (fuel)"
4823 " is missing a recipe");
4825 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4827 CraftReplacements replacements;
4828 lua_getfield(L, table, "replacements");
4829 if(!lua_isnil(L, -1))
4831 if(!read_craft_replacements(L, -1, replacements))
4832 throw LuaError(L, "Invalid replacements"
4833 " (fuel recipe=\"" + recipe + "\")");
4836 CraftDefinition *def = new CraftDefinitionFuel(
4837 recipe, burntime, replacements);
4838 craftdef->registerCraft(def);
4842 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4846 return 0; /* number of results */
4849 // setting_set(name, value)
4850 static int l_setting_set(lua_State *L)
4852 const char *name = luaL_checkstring(L, 1);
4853 const char *value = luaL_checkstring(L, 2);
4854 g_settings->set(name, value);
4858 // setting_get(name)
4859 static int l_setting_get(lua_State *L)
4861 const char *name = luaL_checkstring(L, 1);
4863 std::string value = g_settings->get(name);
4864 lua_pushstring(L, value.c_str());
4865 } catch(SettingNotFoundException &e){
4871 // setting_getbool(name)
4872 static int l_setting_getbool(lua_State *L)
4874 const char *name = luaL_checkstring(L, 1);
4876 bool value = g_settings->getBool(name);
4877 lua_pushboolean(L, value);
4878 } catch(SettingNotFoundException &e){
4884 // chat_send_all(text)
4885 static int l_chat_send_all(lua_State *L)
4887 const char *text = luaL_checkstring(L, 1);
4888 // Get server from registry
4889 Server *server = get_server(L);
4891 server->notifyPlayers(narrow_to_wide(text));
4895 // chat_send_player(name, text)
4896 static int l_chat_send_player(lua_State *L)
4898 const char *name = luaL_checkstring(L, 1);
4899 const char *text = luaL_checkstring(L, 2);
4900 // Get server from registry
4901 Server *server = get_server(L);
4903 server->notifyPlayer(name, narrow_to_wide(text));
4907 // get_player_privs(name, text)
4908 static int l_get_player_privs(lua_State *L)
4910 const char *name = luaL_checkstring(L, 1);
4911 // Get server from registry
4912 Server *server = get_server(L);
4915 int table = lua_gettop(L);
4916 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4917 for(std::set<std::string>::const_iterator
4918 i = privs_s.begin(); i != privs_s.end(); i++){
4919 lua_pushboolean(L, true);
4920 lua_setfield(L, table, i->c_str());
4922 lua_pushvalue(L, table);
4927 static int l_get_ban_list(lua_State *L)
4929 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
4933 // get_ban_description()
4934 static int l_get_ban_description(lua_State *L)
4936 const char * ip_or_name = luaL_checkstring(L, 1);
4937 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
4942 static int l_ban_player(lua_State *L)
4944 const char * name = luaL_checkstring(L, 1);
4945 Player *player = get_env(L)->getPlayer(name);
4948 lua_pushboolean(L, false); // no such player
4953 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
4954 std::string ip_str = addr.serializeString();
4955 get_server(L)->setIpBanned(ip_str, name);
4957 catch(con::PeerNotFoundException) // unlikely
4959 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
4960 lua_pushboolean(L, false); // error
4963 lua_pushboolean(L, true);
4967 // unban_player_or_ip()
4968 static int l_unban_player_of_ip(lua_State *L)
4970 const char * ip_or_name = luaL_checkstring(L, 1);
4971 get_server(L)->unsetIpBanned(ip_or_name);
4972 lua_pushboolean(L, true);
4976 // get_inventory(location)
4977 static int l_get_inventory(lua_State *L)
4979 InventoryLocation loc;
4981 std::string type = checkstringfield(L, 1, "type");
4982 if(type == "player"){
4983 std::string name = checkstringfield(L, 1, "name");
4984 loc.setPlayer(name);
4985 } else if(type == "node"){
4986 lua_getfield(L, 1, "pos");
4987 v3s16 pos = check_v3s16(L, -1);
4988 loc.setNodeMeta(pos);
4989 } else if(type == "detached"){
4990 std::string name = checkstringfield(L, 1, "name");
4991 loc.setDetached(name);
4994 if(get_server(L)->getInventory(loc) != NULL)
4995 InvRef::create(L, loc);
5001 // create_detached_inventory_raw(name)
5002 static int l_create_detached_inventory_raw(lua_State *L)
5004 const char *name = luaL_checkstring(L, 1);
5005 if(get_server(L)->createDetachedInventory(name) != NULL){
5006 InventoryLocation loc;
5007 loc.setDetached(name);
5008 InvRef::create(L, loc);
5015 // show_formspec(playername,formname,formspec)
5016 static int l_show_formspec(lua_State *L)
5018 const char *playername = luaL_checkstring(L, 1);
5019 const char *formname = luaL_checkstring(L, 2);
5020 const char *formspec = luaL_checkstring(L, 3);
5022 if(get_server(L)->showFormspec(playername,formspec,formname))
5024 lua_pushboolean(L, true);
5026 lua_pushboolean(L, false);
5031 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5032 static int l_get_dig_params(lua_State *L)
5034 std::map<std::string, int> groups;
5035 read_groups(L, 1, groups);
5036 ToolCapabilities tp = read_tool_capabilities(L, 2);
5037 if(lua_isnoneornil(L, 3))
5038 push_dig_params(L, getDigParams(groups, &tp));
5040 push_dig_params(L, getDigParams(groups, &tp,
5041 luaL_checknumber(L, 3)));
5045 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5046 static int l_get_hit_params(lua_State *L)
5048 std::map<std::string, int> groups;
5049 read_groups(L, 1, groups);
5050 ToolCapabilities tp = read_tool_capabilities(L, 2);
5051 if(lua_isnoneornil(L, 3))
5052 push_hit_params(L, getHitParams(groups, &tp));
5054 push_hit_params(L, getHitParams(groups, &tp,
5055 luaL_checknumber(L, 3)));
5059 // get_current_modname()
5060 static int l_get_current_modname(lua_State *L)
5062 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5066 // get_modpath(modname)
5067 static int l_get_modpath(lua_State *L)
5069 std::string modname = luaL_checkstring(L, 1);
5071 if(modname == "__builtin"){
5072 std::string path = get_server(L)->getBuiltinLuaPath();
5073 lua_pushstring(L, path.c_str());
5076 const ModSpec *mod = get_server(L)->getModSpec(modname);
5081 lua_pushstring(L, mod->path.c_str());
5086 // the returned list is sorted alphabetically for you
5087 static int l_get_modnames(lua_State *L)
5089 // Get a list of mods
5090 core::list<std::string> mods_unsorted, mods_sorted;
5091 get_server(L)->getModNames(mods_unsorted);
5093 // Take unsorted items from mods_unsorted and sort them into
5094 // mods_sorted; not great performance but the number of mods on a
5095 // server will likely be small.
5096 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5097 i != mods_unsorted.end(); i++)
5100 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5101 x != mods_unsorted.end(); x++)
5103 // I doubt anybody using Minetest will be using
5104 // anything not ASCII based :)
5105 if((*i).compare(*x) <= 0)
5107 mods_sorted.insert_before(x, *i);
5113 mods_sorted.push_back(*i);
5116 // Get the table insertion function from Lua.
5117 lua_getglobal(L, "table");
5118 lua_getfield(L, -1, "insert");
5119 int insertion_func = lua_gettop(L);
5121 // Package them up for Lua
5123 int new_table = lua_gettop(L);
5124 core::list<std::string>::Iterator i = mods_sorted.begin();
5125 while(i != mods_sorted.end())
5127 lua_pushvalue(L, insertion_func);
5128 lua_pushvalue(L, new_table);
5129 lua_pushstring(L, (*i).c_str());
5130 if(lua_pcall(L, 2, 0, 0) != 0)
5132 script_error(L, "error: %s", lua_tostring(L, -1));
5140 static int l_get_worldpath(lua_State *L)
5142 std::string worldpath = get_server(L)->getWorldPath();
5143 lua_pushstring(L, worldpath.c_str());
5147 // sound_play(spec, parameters)
5148 static int l_sound_play(lua_State *L)
5150 SimpleSoundSpec spec;
5151 read_soundspec(L, 1, spec);
5152 ServerSoundParams params;
5153 read_server_sound_params(L, 2, params);
5154 s32 handle = get_server(L)->playSound(spec, params);
5155 lua_pushinteger(L, handle);
5159 // sound_stop(handle)
5160 static int l_sound_stop(lua_State *L)
5162 int handle = luaL_checkinteger(L, 1);
5163 get_server(L)->stopSound(handle);
5167 // is_singleplayer()
5168 static int l_is_singleplayer(lua_State *L)
5170 lua_pushboolean(L, get_server(L)->isSingleplayer());
5174 // get_password_hash(name, raw_password)
5175 static int l_get_password_hash(lua_State *L)
5177 std::string name = luaL_checkstring(L, 1);
5178 std::string raw_password = luaL_checkstring(L, 2);
5179 std::string hash = translatePassword(name,
5180 narrow_to_wide(raw_password));
5181 lua_pushstring(L, hash.c_str());
5185 // notify_authentication_modified(name)
5186 static int l_notify_authentication_modified(lua_State *L)
5188 std::string name = "";
5189 if(lua_isstring(L, 1))
5190 name = lua_tostring(L, 1);
5191 get_server(L)->reportPrivsModified(name);
5195 // get_craft_result(input)
5196 static int l_get_craft_result(lua_State *L)
5199 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5200 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5201 es_CraftMethod, CRAFT_METHOD_NORMAL);
5203 lua_getfield(L, input_i, "width");
5204 if(lua_isnumber(L, -1))
5205 width = luaL_checkinteger(L, -1);
5207 lua_getfield(L, input_i, "items");
5208 std::vector<ItemStack> items = read_items(L, -1);
5209 lua_pop(L, 1); // items
5211 IGameDef *gdef = get_server(L);
5212 ICraftDefManager *cdef = gdef->cdef();
5213 CraftInput input(method, width, items);
5215 bool got = cdef->getCraftResult(input, output, true, gdef);
5216 lua_newtable(L); // output table
5219 item.deSerialize(output.item, gdef->idef());
5220 LuaItemStack::create(L, item);
5221 lua_setfield(L, -2, "item");
5222 setintfield(L, -1, "time", output.time);
5224 LuaItemStack::create(L, ItemStack());
5225 lua_setfield(L, -2, "item");
5226 setintfield(L, -1, "time", 0);
5228 lua_newtable(L); // decremented input table
5229 lua_pushstring(L, method_s.c_str());
5230 lua_setfield(L, -2, "method");
5231 lua_pushinteger(L, width);
5232 lua_setfield(L, -2, "width");
5233 push_items(L, input.items);
5234 lua_setfield(L, -2, "items");
5238 // get_craft_recipe(result item)
5239 static int l_get_craft_recipe(lua_State *L)
5244 std::string o_item = luaL_checkstring(L,input_i);
5246 IGameDef *gdef = get_server(L);
5247 ICraftDefManager *cdef = gdef->cdef();
5249 CraftOutput output(o_item,0);
5250 bool got = cdef->getCraftRecipe(input, output, gdef);
5251 lua_newtable(L); // output table
5254 for(std::vector<ItemStack>::const_iterator
5255 i = input.items.begin();
5256 i != input.items.end(); i++, k++)
5262 sprintf(tmp,"%d",k);
5263 lua_pushstring(L,tmp);
5264 lua_pushstring(L,i->name.c_str());
5265 lua_settable(L, -3);
5267 lua_setfield(L, -2, "items");
5268 setintfield(L, -1, "width", input.width);
5269 switch (input.method) {
5270 case CRAFT_METHOD_NORMAL:
5271 lua_pushstring(L,"normal");
5273 case CRAFT_METHOD_COOKING:
5274 lua_pushstring(L,"cooking");
5276 case CRAFT_METHOD_FUEL:
5277 lua_pushstring(L,"fuel");
5280 lua_pushstring(L,"unknown");
5282 lua_setfield(L, -2, "type");
5285 lua_setfield(L, -2, "items");
5286 setintfield(L, -1, "width", 0);
5291 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5292 static int l_rollback_get_last_node_actor(lua_State *L)
5294 v3s16 p = read_v3s16(L, 1);
5295 int range = luaL_checknumber(L, 2);
5296 int seconds = luaL_checknumber(L, 3);
5297 Server *server = get_server(L);
5298 IRollbackManager *rollback = server->getRollbackManager();
5300 int act_seconds = 0;
5301 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5302 lua_pushstring(L, actor.c_str());
5303 push_v3s16(L, act_p);
5304 lua_pushnumber(L, act_seconds);
5308 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5309 static int l_rollback_revert_actions_by(lua_State *L)
5311 std::string actor = luaL_checkstring(L, 1);
5312 int seconds = luaL_checknumber(L, 2);
5313 Server *server = get_server(L);
5314 IRollbackManager *rollback = server->getRollbackManager();
5315 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5316 std::list<std::string> log;
5317 bool success = server->rollbackRevertActions(actions, &log);
5318 // Push boolean result
5319 lua_pushboolean(L, success);
5320 // Get the table insert function and push the log table
5321 lua_getglobal(L, "table");
5322 lua_getfield(L, -1, "insert");
5323 int table_insert = lua_gettop(L);
5325 int table = lua_gettop(L);
5326 for(std::list<std::string>::const_iterator i = log.begin();
5327 i != log.end(); i++)
5329 lua_pushvalue(L, table_insert);
5330 lua_pushvalue(L, table);
5331 lua_pushstring(L, i->c_str());
5332 if(lua_pcall(L, 2, 0, 0))
5333 script_error(L, "error: %s", lua_tostring(L, -1));
5335 lua_remove(L, -2); // Remove table
5336 lua_remove(L, -2); // Remove insert
5340 static const struct luaL_Reg minetest_f [] = {
5343 {"request_shutdown", l_request_shutdown},
5344 {"get_server_status", l_get_server_status},
5345 {"register_item_raw", l_register_item_raw},
5346 {"register_alias_raw", l_register_alias_raw},
5347 {"register_craft", l_register_craft},
5348 {"register_biome", l_register_biome},
5349 {"register_biome_groups", l_register_biome_groups},
5350 {"setting_set", l_setting_set},
5351 {"setting_get", l_setting_get},
5352 {"setting_getbool", l_setting_getbool},
5353 {"chat_send_all", l_chat_send_all},
5354 {"chat_send_player", l_chat_send_player},
5355 {"get_player_privs", l_get_player_privs},
5356 {"get_ban_list", l_get_ban_list},
5357 {"get_ban_description", l_get_ban_description},
5358 {"ban_player", l_ban_player},
5359 {"unban_player_or_ip", l_unban_player_of_ip},
5360 {"get_inventory", l_get_inventory},
5361 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5362 {"show_formspec", l_show_formspec},
5363 {"get_dig_params", l_get_dig_params},
5364 {"get_hit_params", l_get_hit_params},
5365 {"get_current_modname", l_get_current_modname},
5366 {"get_modpath", l_get_modpath},
5367 {"get_modnames", l_get_modnames},
5368 {"get_worldpath", l_get_worldpath},
5369 {"sound_play", l_sound_play},
5370 {"sound_stop", l_sound_stop},
5371 {"is_singleplayer", l_is_singleplayer},
5372 {"get_password_hash", l_get_password_hash},
5373 {"notify_authentication_modified", l_notify_authentication_modified},
5374 {"get_craft_result", l_get_craft_result},
5375 {"get_craft_recipe", l_get_craft_recipe},
5376 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5377 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5382 Main export function
5385 void scriptapi_export(lua_State *L, Server *server)
5388 assert(lua_checkstack(L, 20));
5389 verbosestream<<"scriptapi_export()"<<std::endl;
5390 StackUnroller stack_unroller(L);
5392 // Store server as light userdata in registry
5393 lua_pushlightuserdata(L, server);
5394 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5396 // Register global functions in table minetest
5398 luaL_register(L, NULL, minetest_f);
5399 lua_setglobal(L, "minetest");
5401 // Get the main minetest table
5402 lua_getglobal(L, "minetest");
5404 // Add tables to minetest
5406 lua_setfield(L, -2, "object_refs");
5408 lua_setfield(L, -2, "luaentities");
5410 // Register wrappers
5411 LuaItemStack::Register(L);
5412 InvRef::Register(L);
5413 NodeMetaRef::Register(L);
5414 NodeTimerRef::Register(L);
5415 ObjectRef::Register(L);
5416 EnvRef::Register(L);
5417 LuaPseudoRandom::Register(L);
5418 LuaPerlinNoise::Register(L);
5421 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5422 const std::string &modname)
5424 ModNameStorer modnamestorer(L, modname);
5426 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5428 errorstream<<"Error loading mod \""<<modname
5429 <<"\": modname does not follow naming conventions: "
5430 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5434 bool success = false;
5437 success = script_load(L, scriptpath.c_str());
5440 errorstream<<"Error loading mod \""<<modname
5441 <<"\": "<<e.what()<<std::endl;
5447 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5450 assert(lua_checkstack(L, 20));
5451 verbosestream<<"scriptapi_add_environment"<<std::endl;
5452 StackUnroller stack_unroller(L);
5454 // Create EnvRef on stack
5455 EnvRef::create(L, env);
5456 int envref = lua_gettop(L);
5458 // minetest.env = envref
5459 lua_getglobal(L, "minetest");
5460 luaL_checktype(L, -1, LUA_TTABLE);
5461 lua_pushvalue(L, envref);
5462 lua_setfield(L, -2, "env");
5464 // Store environment as light userdata in registry
5465 lua_pushlightuserdata(L, env);
5466 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5469 Add ActiveBlockModifiers to environment
5472 // Get minetest.registered_abms
5473 lua_getglobal(L, "minetest");
5474 lua_getfield(L, -1, "registered_abms");
5475 luaL_checktype(L, -1, LUA_TTABLE);
5476 int registered_abms = lua_gettop(L);
5478 if(lua_istable(L, registered_abms)){
5479 int table = lua_gettop(L);
5481 while(lua_next(L, table) != 0){
5482 // key at index -2 and value at index -1
5483 int id = lua_tonumber(L, -2);
5484 int current_abm = lua_gettop(L);
5486 std::set<std::string> trigger_contents;
5487 lua_getfield(L, current_abm, "nodenames");
5488 if(lua_istable(L, -1)){
5489 int table = lua_gettop(L);
5491 while(lua_next(L, table) != 0){
5492 // key at index -2 and value at index -1
5493 luaL_checktype(L, -1, LUA_TSTRING);
5494 trigger_contents.insert(lua_tostring(L, -1));
5495 // removes value, keeps key for next iteration
5498 } else if(lua_isstring(L, -1)){
5499 trigger_contents.insert(lua_tostring(L, -1));
5503 std::set<std::string> required_neighbors;
5504 lua_getfield(L, current_abm, "neighbors");
5505 if(lua_istable(L, -1)){
5506 int table = lua_gettop(L);
5508 while(lua_next(L, table) != 0){
5509 // key at index -2 and value at index -1
5510 luaL_checktype(L, -1, LUA_TSTRING);
5511 required_neighbors.insert(lua_tostring(L, -1));
5512 // removes value, keeps key for next iteration
5515 } else if(lua_isstring(L, -1)){
5516 required_neighbors.insert(lua_tostring(L, -1));
5520 float trigger_interval = 10.0;
5521 getfloatfield(L, current_abm, "interval", trigger_interval);
5523 int trigger_chance = 50;
5524 getintfield(L, current_abm, "chance", trigger_chance);
5526 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5527 required_neighbors, trigger_interval, trigger_chance);
5529 env->addActiveBlockModifier(abm);
5531 // removes value, keeps key for next iteration
5539 // Dump stack top with the dump2 function
5540 static void dump2(lua_State *L, const char *name)
5542 // Dump object (debug)
5543 lua_getglobal(L, "dump2");
5544 luaL_checktype(L, -1, LUA_TFUNCTION);
5545 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5546 lua_pushstring(L, name);
5547 if(lua_pcall(L, 2, 0, 0))
5548 script_error(L, "error: %s", lua_tostring(L, -1));
5556 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5559 assert(lua_checkstack(L, 20));
5560 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5561 StackUnroller stack_unroller(L);
5563 // Create object on stack
5564 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5565 int object = lua_gettop(L);
5567 // Get minetest.object_refs table
5568 lua_getglobal(L, "minetest");
5569 lua_getfield(L, -1, "object_refs");
5570 luaL_checktype(L, -1, LUA_TTABLE);
5571 int objectstable = lua_gettop(L);
5573 // object_refs[id] = object
5574 lua_pushnumber(L, cobj->getId()); // Push id
5575 lua_pushvalue(L, object); // Copy object to top of stack
5576 lua_settable(L, objectstable);
5579 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5582 assert(lua_checkstack(L, 20));
5583 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5584 StackUnroller stack_unroller(L);
5586 // Get minetest.object_refs table
5587 lua_getglobal(L, "minetest");
5588 lua_getfield(L, -1, "object_refs");
5589 luaL_checktype(L, -1, LUA_TTABLE);
5590 int objectstable = lua_gettop(L);
5592 // Get object_refs[id]
5593 lua_pushnumber(L, cobj->getId()); // Push id
5594 lua_gettable(L, objectstable);
5595 // Set object reference to NULL
5596 ObjectRef::set_null(L);
5597 lua_pop(L, 1); // pop object
5599 // Set object_refs[id] = nil
5600 lua_pushnumber(L, cobj->getId()); // Push id
5602 lua_settable(L, objectstable);
5609 // What scriptapi_run_callbacks does with the return values of callbacks.
5610 // Regardless of the mode, if only one callback is defined,
5611 // its return value is the total return value.
5612 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5613 enum RunCallbacksMode
5615 // Returns the return value of the first callback
5616 // Returns nil if list of callbacks is empty
5617 RUN_CALLBACKS_MODE_FIRST,
5618 // Returns the return value of the last callback
5619 // Returns nil if list of callbacks is empty
5620 RUN_CALLBACKS_MODE_LAST,
5621 // If any callback returns a false value, the first such is returned
5622 // Otherwise, the first callback's return value (trueish) is returned
5623 // Returns true if list of callbacks is empty
5624 RUN_CALLBACKS_MODE_AND,
5625 // Like above, but stops calling callbacks (short circuit)
5626 // after seeing the first false value
5627 RUN_CALLBACKS_MODE_AND_SC,
5628 // If any callback returns a true value, the first such is returned
5629 // Otherwise, the first callback's return value (falseish) is returned
5630 // Returns false if list of callbacks is empty
5631 RUN_CALLBACKS_MODE_OR,
5632 // Like above, but stops calling callbacks (short circuit)
5633 // after seeing the first true value
5634 RUN_CALLBACKS_MODE_OR_SC,
5635 // Note: "a true value" and "a false value" refer to values that
5636 // are converted by lua_toboolean to true or false, respectively.
5639 // Push the list of callbacks (a lua table).
5640 // Then push nargs arguments.
5641 // Then call this function, which
5642 // - runs the callbacks
5643 // - removes the table and arguments from the lua stack
5644 // - pushes the return value, computed depending on mode
5645 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5646 RunCallbacksMode mode)
5648 // Insert the return value into the lua stack, below the table
5649 assert(lua_gettop(L) >= nargs + 1);
5651 lua_insert(L, -(nargs + 1) - 1);
5652 // Stack now looks like this:
5653 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5655 int rv = lua_gettop(L) - nargs - 1;
5657 int arg = table + 1;
5659 luaL_checktype(L, table, LUA_TTABLE);
5663 bool first_loop = true;
5664 while(lua_next(L, table) != 0){
5665 // key at index -2 and value at index -1
5666 luaL_checktype(L, -1, LUA_TFUNCTION);
5668 for(int i = 0; i < nargs; i++)
5669 lua_pushvalue(L, arg+i);
5670 if(lua_pcall(L, nargs, 1, 0))
5671 script_error(L, "error: %s", lua_tostring(L, -1));
5673 // Move return value to designated space in stack
5676 // Result of first callback is always moved
5680 // Otherwise, what happens depends on the mode
5681 if(mode == RUN_CALLBACKS_MODE_FIRST)
5683 else if(mode == RUN_CALLBACKS_MODE_LAST)
5685 else if(mode == RUN_CALLBACKS_MODE_AND ||
5686 mode == RUN_CALLBACKS_MODE_AND_SC){
5687 if((bool)lua_toboolean(L, rv) == true &&
5688 (bool)lua_toboolean(L, -1) == false)
5693 else if(mode == RUN_CALLBACKS_MODE_OR ||
5694 mode == RUN_CALLBACKS_MODE_OR_SC){
5695 if((bool)lua_toboolean(L, rv) == false &&
5696 (bool)lua_toboolean(L, -1) == true)
5705 // Handle short circuit modes
5706 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5707 (bool)lua_toboolean(L, rv) == false)
5709 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5710 (bool)lua_toboolean(L, rv) == true)
5713 // value removed, keep key for next iteration
5716 // Remove stuff from stack, leaving only the return value
5719 // Fix return value in case no callbacks were called
5721 if(mode == RUN_CALLBACKS_MODE_AND ||
5722 mode == RUN_CALLBACKS_MODE_AND_SC){
5724 lua_pushboolean(L, true);
5726 else if(mode == RUN_CALLBACKS_MODE_OR ||
5727 mode == RUN_CALLBACKS_MODE_OR_SC){
5729 lua_pushboolean(L, false);
5734 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5735 const std::string &message)
5738 assert(lua_checkstack(L, 20));
5739 StackUnroller stack_unroller(L);
5741 // Get minetest.registered_on_chat_messages
5742 lua_getglobal(L, "minetest");
5743 lua_getfield(L, -1, "registered_on_chat_messages");
5745 lua_pushstring(L, name.c_str());
5746 lua_pushstring(L, message.c_str());
5747 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5748 bool ate = lua_toboolean(L, -1);
5752 void scriptapi_on_shutdown(lua_State *L)
5755 assert(lua_checkstack(L, 20));
5756 StackUnroller stack_unroller(L);
5758 // Get registered shutdown hooks
5759 lua_getglobal(L, "minetest");
5760 lua_getfield(L, -1, "registered_on_shutdown");
5762 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5765 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5768 assert(lua_checkstack(L, 20));
5769 StackUnroller stack_unroller(L);
5771 // Get minetest.registered_on_newplayers
5772 lua_getglobal(L, "minetest");
5773 lua_getfield(L, -1, "registered_on_newplayers");
5775 objectref_get_or_create(L, player);
5776 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5779 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5782 assert(lua_checkstack(L, 20));
5783 StackUnroller stack_unroller(L);
5785 // Get minetest.registered_on_dieplayers
5786 lua_getglobal(L, "minetest");
5787 lua_getfield(L, -1, "registered_on_dieplayers");
5789 objectref_get_or_create(L, player);
5790 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5793 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5796 assert(lua_checkstack(L, 20));
5797 StackUnroller stack_unroller(L);
5799 // Get minetest.registered_on_respawnplayers
5800 lua_getglobal(L, "minetest");
5801 lua_getfield(L, -1, "registered_on_respawnplayers");
5803 objectref_get_or_create(L, player);
5804 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5805 bool positioning_handled_by_some = lua_toboolean(L, -1);
5806 return positioning_handled_by_some;
5809 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5812 assert(lua_checkstack(L, 20));
5813 StackUnroller stack_unroller(L);
5815 // Get minetest.registered_on_joinplayers
5816 lua_getglobal(L, "minetest");
5817 lua_getfield(L, -1, "registered_on_joinplayers");
5819 objectref_get_or_create(L, player);
5820 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5823 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5826 assert(lua_checkstack(L, 20));
5827 StackUnroller stack_unroller(L);
5829 // Get minetest.registered_on_leaveplayers
5830 lua_getglobal(L, "minetest");
5831 lua_getfield(L, -1, "registered_on_leaveplayers");
5833 objectref_get_or_create(L, player);
5834 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5837 static void get_auth_handler(lua_State *L)
5839 lua_getglobal(L, "minetest");
5840 lua_getfield(L, -1, "registered_auth_handler");
5841 if(lua_isnil(L, -1)){
5843 lua_getfield(L, -1, "builtin_auth_handler");
5845 if(lua_type(L, -1) != LUA_TTABLE)
5846 throw LuaError(L, "Authentication handler table not valid");
5849 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5850 std::string *dst_password, std::set<std::string> *dst_privs)
5853 assert(lua_checkstack(L, 20));
5854 StackUnroller stack_unroller(L);
5856 get_auth_handler(L);
5857 lua_getfield(L, -1, "get_auth");
5858 if(lua_type(L, -1) != LUA_TFUNCTION)
5859 throw LuaError(L, "Authentication handler missing get_auth");
5860 lua_pushstring(L, playername.c_str());
5861 if(lua_pcall(L, 1, 1, 0))
5862 script_error(L, "error: %s", lua_tostring(L, -1));
5864 // nil = login not allowed
5865 if(lua_isnil(L, -1))
5867 luaL_checktype(L, -1, LUA_TTABLE);
5869 std::string password;
5870 bool found = getstringfield(L, -1, "password", password);
5872 throw LuaError(L, "Authentication handler didn't return password");
5874 *dst_password = password;
5876 lua_getfield(L, -1, "privileges");
5877 if(!lua_istable(L, -1))
5879 "Authentication handler didn't return privilege table");
5881 read_privileges(L, -1, *dst_privs);
5887 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5888 const std::string &password)
5891 assert(lua_checkstack(L, 20));
5892 StackUnroller stack_unroller(L);
5894 get_auth_handler(L);
5895 lua_getfield(L, -1, "create_auth");
5896 if(lua_type(L, -1) != LUA_TFUNCTION)
5897 throw LuaError(L, "Authentication handler missing create_auth");
5898 lua_pushstring(L, playername.c_str());
5899 lua_pushstring(L, password.c_str());
5900 if(lua_pcall(L, 2, 0, 0))
5901 script_error(L, "error: %s", lua_tostring(L, -1));
5904 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5905 const std::string &password)
5908 assert(lua_checkstack(L, 20));
5909 StackUnroller stack_unroller(L);
5911 get_auth_handler(L);
5912 lua_getfield(L, -1, "set_password");
5913 if(lua_type(L, -1) != LUA_TFUNCTION)
5914 throw LuaError(L, "Authentication handler missing set_password");
5915 lua_pushstring(L, playername.c_str());
5916 lua_pushstring(L, password.c_str());
5917 if(lua_pcall(L, 2, 1, 0))
5918 script_error(L, "error: %s", lua_tostring(L, -1));
5919 return lua_toboolean(L, -1);
5926 void scriptapi_on_player_receive_fields(lua_State *L,
5927 ServerActiveObject *player,
5928 const std::string &formname,
5929 const std::map<std::string, std::string> &fields)
5932 assert(lua_checkstack(L, 20));
5933 StackUnroller stack_unroller(L);
5935 // Get minetest.registered_on_chat_messages
5936 lua_getglobal(L, "minetest");
5937 lua_getfield(L, -1, "registered_on_player_receive_fields");
5940 objectref_get_or_create(L, player);
5942 lua_pushstring(L, formname.c_str());
5945 for(std::map<std::string, std::string>::const_iterator
5946 i = fields.begin(); i != fields.end(); i++){
5947 const std::string &name = i->first;
5948 const std::string &value = i->second;
5949 lua_pushstring(L, name.c_str());
5950 lua_pushlstring(L, value.c_str(), value.size());
5951 lua_settable(L, -3);
5953 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
5957 item callbacks and node callbacks
5960 // Retrieves minetest.registered_items[name][callbackname]
5961 // If that is nil or on error, return false and stack is unchanged
5962 // If that is a function, returns true and pushes the
5963 // function onto the stack
5964 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
5965 // is tried instead so unknown items can still be manipulated to some degree
5966 static bool get_item_callback(lua_State *L,
5967 const char *name, const char *callbackname)
5969 lua_getglobal(L, "minetest");
5970 lua_getfield(L, -1, "registered_items");
5972 luaL_checktype(L, -1, LUA_TTABLE);
5973 lua_getfield(L, -1, name);
5975 // Should be a table
5976 if(lua_type(L, -1) != LUA_TTABLE)
5978 // Report error and clean up
5979 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5982 // Try minetest.nodedef_default instead
5983 lua_getglobal(L, "minetest");
5984 lua_getfield(L, -1, "nodedef_default");
5986 luaL_checktype(L, -1, LUA_TTABLE);
5988 lua_getfield(L, -1, callbackname);
5990 // Should be a function or nil
5991 if(lua_type(L, -1) == LUA_TFUNCTION)
5995 else if(lua_isnil(L, -1))
6002 errorstream<<"Item \""<<name<<"\" callback \""
6003 <<callbackname<<" is not a function"<<std::endl;
6009 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6010 ServerActiveObject *dropper, v3f pos)
6013 assert(lua_checkstack(L, 20));
6014 StackUnroller stack_unroller(L);
6016 // Push callback function on stack
6017 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6021 LuaItemStack::create(L, item);
6022 objectref_get_or_create(L, dropper);
6023 pushFloatPos(L, pos);
6024 if(lua_pcall(L, 3, 1, 0))
6025 script_error(L, "error: %s", lua_tostring(L, -1));
6026 if(!lua_isnil(L, -1))
6027 item = read_item(L, -1);
6031 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6032 ServerActiveObject *placer, const PointedThing &pointed)
6035 assert(lua_checkstack(L, 20));
6036 StackUnroller stack_unroller(L);
6038 // Push callback function on stack
6039 if(!get_item_callback(L, item.name.c_str(), "on_place"))
6043 LuaItemStack::create(L, item);
6044 objectref_get_or_create(L, placer);
6045 push_pointed_thing(L, pointed);
6046 if(lua_pcall(L, 3, 1, 0))
6047 script_error(L, "error: %s", lua_tostring(L, -1));
6048 if(!lua_isnil(L, -1))
6049 item = read_item(L, -1);
6053 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6054 ServerActiveObject *user, const PointedThing &pointed)
6057 assert(lua_checkstack(L, 20));
6058 StackUnroller stack_unroller(L);
6060 // Push callback function on stack
6061 if(!get_item_callback(L, item.name.c_str(), "on_use"))
6065 LuaItemStack::create(L, item);
6066 objectref_get_or_create(L, user);
6067 push_pointed_thing(L, pointed);
6068 if(lua_pcall(L, 3, 1, 0))
6069 script_error(L, "error: %s", lua_tostring(L, -1));
6070 if(!lua_isnil(L, -1))
6071 item = read_item(L, -1);
6075 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6076 ServerActiveObject *puncher)
6079 assert(lua_checkstack(L, 20));
6080 StackUnroller stack_unroller(L);
6082 INodeDefManager *ndef = get_server(L)->ndef();
6084 // Push callback function on stack
6085 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6090 pushnode(L, node, ndef);
6091 objectref_get_or_create(L, puncher);
6092 if(lua_pcall(L, 3, 0, 0))
6093 script_error(L, "error: %s", lua_tostring(L, -1));
6097 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6098 ServerActiveObject *digger)
6101 assert(lua_checkstack(L, 20));
6102 StackUnroller stack_unroller(L);
6104 INodeDefManager *ndef = get_server(L)->ndef();
6106 // Push callback function on stack
6107 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6112 pushnode(L, node, ndef);
6113 objectref_get_or_create(L, digger);
6114 if(lua_pcall(L, 3, 0, 0))
6115 script_error(L, "error: %s", lua_tostring(L, -1));
6119 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6122 assert(lua_checkstack(L, 20));
6123 StackUnroller stack_unroller(L);
6125 INodeDefManager *ndef = get_server(L)->ndef();
6127 // Push callback function on stack
6128 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6133 if(lua_pcall(L, 1, 0, 0))
6134 script_error(L, "error: %s", lua_tostring(L, -1));
6137 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6140 assert(lua_checkstack(L, 20));
6141 StackUnroller stack_unroller(L);
6143 INodeDefManager *ndef = get_server(L)->ndef();
6145 // Push callback function on stack
6146 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6151 if(lua_pcall(L, 1, 0, 0))
6152 script_error(L, "error: %s", lua_tostring(L, -1));
6155 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6158 assert(lua_checkstack(L, 20));
6159 StackUnroller stack_unroller(L);
6161 INodeDefManager *ndef = get_server(L)->ndef();
6163 // Push callback function on stack
6164 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6169 pushnode(L, node, ndef);
6170 if(lua_pcall(L, 2, 0, 0))
6171 script_error(L, "error: %s", lua_tostring(L, -1));
6174 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6177 assert(lua_checkstack(L, 20));
6178 StackUnroller stack_unroller(L);
6180 INodeDefManager *ndef = get_server(L)->ndef();
6182 // Push callback function on stack
6183 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6188 lua_pushnumber(L,dtime);
6189 if(lua_pcall(L, 2, 1, 0))
6190 script_error(L, "error: %s", lua_tostring(L, -1));
6191 if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6197 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6198 const std::string &formname,
6199 const std::map<std::string, std::string> &fields,
6200 ServerActiveObject *sender)
6203 assert(lua_checkstack(L, 20));
6204 StackUnroller stack_unroller(L);
6206 INodeDefManager *ndef = get_server(L)->ndef();
6208 // If node doesn't exist, we don't know what callback to call
6209 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6210 if(node.getContent() == CONTENT_IGNORE)
6213 // Push callback function on stack
6214 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6221 lua_pushstring(L, formname.c_str());
6224 for(std::map<std::string, std::string>::const_iterator
6225 i = fields.begin(); i != fields.end(); i++){
6226 const std::string &name = i->first;
6227 const std::string &value = i->second;
6228 lua_pushstring(L, name.c_str());
6229 lua_pushlstring(L, value.c_str(), value.size());
6230 lua_settable(L, -3);
6233 objectref_get_or_create(L, sender);
6234 if(lua_pcall(L, 4, 0, 0))
6235 script_error(L, "error: %s", lua_tostring(L, -1));
6239 Node metadata inventory callbacks
6242 // Return number of accepted items to be moved
6243 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6244 const std::string &from_list, int from_index,
6245 const std::string &to_list, int to_index,
6246 int count, ServerActiveObject *player)
6249 assert(lua_checkstack(L, 20));
6250 StackUnroller stack_unroller(L);
6252 INodeDefManager *ndef = get_server(L)->ndef();
6254 // If node doesn't exist, we don't know what callback to call
6255 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6256 if(node.getContent() == CONTENT_IGNORE)
6259 // Push callback function on stack
6260 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6261 "allow_metadata_inventory_move"))
6264 // function(pos, from_list, from_index, to_list, to_index, count, player)
6268 lua_pushstring(L, from_list.c_str());
6270 lua_pushinteger(L, from_index + 1);
6272 lua_pushstring(L, to_list.c_str());
6274 lua_pushinteger(L, to_index + 1);
6276 lua_pushinteger(L, count);
6278 objectref_get_or_create(L, player);
6279 if(lua_pcall(L, 7, 1, 0))
6280 script_error(L, "error: %s", lua_tostring(L, -1));
6281 if(!lua_isnumber(L, -1))
6282 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6283 return luaL_checkinteger(L, -1);
6286 // Return number of accepted items to be put
6287 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6288 const std::string &listname, int index, ItemStack &stack,
6289 ServerActiveObject *player)
6292 assert(lua_checkstack(L, 20));
6293 StackUnroller stack_unroller(L);
6295 INodeDefManager *ndef = get_server(L)->ndef();
6297 // If node doesn't exist, we don't know what callback to call
6298 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6299 if(node.getContent() == CONTENT_IGNORE)
6302 // Push callback function on stack
6303 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6304 "allow_metadata_inventory_put"))
6307 // Call function(pos, listname, index, stack, player)
6311 lua_pushstring(L, listname.c_str());
6313 lua_pushinteger(L, index + 1);
6315 LuaItemStack::create(L, stack);
6317 objectref_get_or_create(L, player);
6318 if(lua_pcall(L, 5, 1, 0))
6319 script_error(L, "error: %s", lua_tostring(L, -1));
6320 if(!lua_isnumber(L, -1))
6321 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6322 return luaL_checkinteger(L, -1);
6325 // Return number of accepted items to be taken
6326 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6327 const std::string &listname, int index, ItemStack &stack,
6328 ServerActiveObject *player)
6331 assert(lua_checkstack(L, 20));
6332 StackUnroller stack_unroller(L);
6334 INodeDefManager *ndef = get_server(L)->ndef();
6336 // If node doesn't exist, we don't know what callback to call
6337 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6338 if(node.getContent() == CONTENT_IGNORE)
6341 // Push callback function on stack
6342 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6343 "allow_metadata_inventory_take"))
6346 // Call function(pos, listname, index, count, player)
6350 lua_pushstring(L, listname.c_str());
6352 lua_pushinteger(L, index + 1);
6354 LuaItemStack::create(L, stack);
6356 objectref_get_or_create(L, player);
6357 if(lua_pcall(L, 5, 1, 0))
6358 script_error(L, "error: %s", lua_tostring(L, -1));
6359 if(!lua_isnumber(L, -1))
6360 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6361 return luaL_checkinteger(L, -1);
6364 // Report moved items
6365 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6366 const std::string &from_list, int from_index,
6367 const std::string &to_list, int to_index,
6368 int count, ServerActiveObject *player)
6371 assert(lua_checkstack(L, 20));
6372 StackUnroller stack_unroller(L);
6374 INodeDefManager *ndef = get_server(L)->ndef();
6376 // If node doesn't exist, we don't know what callback to call
6377 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6378 if(node.getContent() == CONTENT_IGNORE)
6381 // Push callback function on stack
6382 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6383 "on_metadata_inventory_move"))
6386 // function(pos, from_list, from_index, to_list, to_index, count, player)
6390 lua_pushstring(L, from_list.c_str());
6392 lua_pushinteger(L, from_index + 1);
6394 lua_pushstring(L, to_list.c_str());
6396 lua_pushinteger(L, to_index + 1);
6398 lua_pushinteger(L, count);
6400 objectref_get_or_create(L, player);
6401 if(lua_pcall(L, 7, 0, 0))
6402 script_error(L, "error: %s", lua_tostring(L, -1));
6406 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6407 const std::string &listname, int index, ItemStack &stack,
6408 ServerActiveObject *player)
6411 assert(lua_checkstack(L, 20));
6412 StackUnroller stack_unroller(L);
6414 INodeDefManager *ndef = get_server(L)->ndef();
6416 // If node doesn't exist, we don't know what callback to call
6417 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6418 if(node.getContent() == CONTENT_IGNORE)
6421 // Push callback function on stack
6422 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6423 "on_metadata_inventory_put"))
6426 // Call function(pos, listname, index, stack, player)
6430 lua_pushstring(L, listname.c_str());
6432 lua_pushinteger(L, index + 1);
6434 LuaItemStack::create(L, stack);
6436 objectref_get_or_create(L, player);
6437 if(lua_pcall(L, 5, 0, 0))
6438 script_error(L, "error: %s", lua_tostring(L, -1));
6441 // Report taken items
6442 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6443 const std::string &listname, int index, ItemStack &stack,
6444 ServerActiveObject *player)
6447 assert(lua_checkstack(L, 20));
6448 StackUnroller stack_unroller(L);
6450 INodeDefManager *ndef = get_server(L)->ndef();
6452 // If node doesn't exist, we don't know what callback to call
6453 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6454 if(node.getContent() == CONTENT_IGNORE)
6457 // Push callback function on stack
6458 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6459 "on_metadata_inventory_take"))
6462 // Call function(pos, listname, index, stack, player)
6466 lua_pushstring(L, listname.c_str());
6468 lua_pushinteger(L, index + 1);
6470 LuaItemStack::create(L, stack);
6472 objectref_get_or_create(L, player);
6473 if(lua_pcall(L, 5, 0, 0))
6474 script_error(L, "error: %s", lua_tostring(L, -1));
6478 Detached inventory callbacks
6481 // Retrieves minetest.detached_inventories[name][callbackname]
6482 // If that is nil or on error, return false and stack is unchanged
6483 // If that is a function, returns true and pushes the
6484 // function onto the stack
6485 static bool get_detached_inventory_callback(lua_State *L,
6486 const std::string &name, const char *callbackname)
6488 lua_getglobal(L, "minetest");
6489 lua_getfield(L, -1, "detached_inventories");
6491 luaL_checktype(L, -1, LUA_TTABLE);
6492 lua_getfield(L, -1, name.c_str());
6494 // Should be a table
6495 if(lua_type(L, -1) != LUA_TTABLE)
6497 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6501 lua_getfield(L, -1, callbackname);
6503 // Should be a function or nil
6504 if(lua_type(L, -1) == LUA_TFUNCTION)
6508 else if(lua_isnil(L, -1))
6515 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6516 <<callbackname<<"\" is not a function"<<std::endl;
6522 // Return number of accepted items to be moved
6523 int scriptapi_detached_inventory_allow_move(lua_State *L,
6524 const std::string &name,
6525 const std::string &from_list, int from_index,
6526 const std::string &to_list, int to_index,
6527 int count, ServerActiveObject *player)
6530 assert(lua_checkstack(L, 20));
6531 StackUnroller stack_unroller(L);
6533 // Push callback function on stack
6534 if(!get_detached_inventory_callback(L, name, "allow_move"))
6537 // function(inv, from_list, from_index, to_list, to_index, count, player)
6539 InventoryLocation loc;
6540 loc.setDetached(name);
6541 InvRef::create(L, loc);
6543 lua_pushstring(L, from_list.c_str());
6545 lua_pushinteger(L, from_index + 1);
6547 lua_pushstring(L, to_list.c_str());
6549 lua_pushinteger(L, to_index + 1);
6551 lua_pushinteger(L, count);
6553 objectref_get_or_create(L, player);
6554 if(lua_pcall(L, 7, 1, 0))
6555 script_error(L, "error: %s", lua_tostring(L, -1));
6556 if(!lua_isnumber(L, -1))
6557 throw LuaError(L, "allow_move should return a number");
6558 return luaL_checkinteger(L, -1);
6561 // Return number of accepted items to be put
6562 int scriptapi_detached_inventory_allow_put(lua_State *L,
6563 const std::string &name,
6564 const std::string &listname, int index, ItemStack &stack,
6565 ServerActiveObject *player)
6568 assert(lua_checkstack(L, 20));
6569 StackUnroller stack_unroller(L);
6571 // Push callback function on stack
6572 if(!get_detached_inventory_callback(L, name, "allow_put"))
6573 return stack.count; // All will be accepted
6575 // Call function(inv, listname, index, stack, player)
6577 InventoryLocation loc;
6578 loc.setDetached(name);
6579 InvRef::create(L, loc);
6581 lua_pushstring(L, listname.c_str());
6583 lua_pushinteger(L, index + 1);
6585 LuaItemStack::create(L, stack);
6587 objectref_get_or_create(L, player);
6588 if(lua_pcall(L, 5, 1, 0))
6589 script_error(L, "error: %s", lua_tostring(L, -1));
6590 if(!lua_isnumber(L, -1))
6591 throw LuaError(L, "allow_put should return a number");
6592 return luaL_checkinteger(L, -1);
6595 // Return number of accepted items to be taken
6596 int scriptapi_detached_inventory_allow_take(lua_State *L,
6597 const std::string &name,
6598 const std::string &listname, int index, ItemStack &stack,
6599 ServerActiveObject *player)
6602 assert(lua_checkstack(L, 20));
6603 StackUnroller stack_unroller(L);
6605 // Push callback function on stack
6606 if(!get_detached_inventory_callback(L, name, "allow_take"))
6607 return stack.count; // All will be accepted
6609 // Call function(inv, listname, index, stack, player)
6611 InventoryLocation loc;
6612 loc.setDetached(name);
6613 InvRef::create(L, loc);
6615 lua_pushstring(L, listname.c_str());
6617 lua_pushinteger(L, index + 1);
6619 LuaItemStack::create(L, stack);
6621 objectref_get_or_create(L, player);
6622 if(lua_pcall(L, 5, 1, 0))
6623 script_error(L, "error: %s", lua_tostring(L, -1));
6624 if(!lua_isnumber(L, -1))
6625 throw LuaError(L, "allow_take should return a number");
6626 return luaL_checkinteger(L, -1);
6629 // Report moved items
6630 void scriptapi_detached_inventory_on_move(lua_State *L,
6631 const std::string &name,
6632 const std::string &from_list, int from_index,
6633 const std::string &to_list, int to_index,
6634 int count, ServerActiveObject *player)
6637 assert(lua_checkstack(L, 20));
6638 StackUnroller stack_unroller(L);
6640 // Push callback function on stack
6641 if(!get_detached_inventory_callback(L, name, "on_move"))
6644 // function(inv, from_list, from_index, to_list, to_index, count, player)
6646 InventoryLocation loc;
6647 loc.setDetached(name);
6648 InvRef::create(L, loc);
6650 lua_pushstring(L, from_list.c_str());
6652 lua_pushinteger(L, from_index + 1);
6654 lua_pushstring(L, to_list.c_str());
6656 lua_pushinteger(L, to_index + 1);
6658 lua_pushinteger(L, count);
6660 objectref_get_or_create(L, player);
6661 if(lua_pcall(L, 7, 0, 0))
6662 script_error(L, "error: %s", lua_tostring(L, -1));
6666 void scriptapi_detached_inventory_on_put(lua_State *L,
6667 const std::string &name,
6668 const std::string &listname, int index, ItemStack &stack,
6669 ServerActiveObject *player)
6672 assert(lua_checkstack(L, 20));
6673 StackUnroller stack_unroller(L);
6675 // Push callback function on stack
6676 if(!get_detached_inventory_callback(L, name, "on_put"))
6679 // Call function(inv, listname, index, stack, player)
6681 InventoryLocation loc;
6682 loc.setDetached(name);
6683 InvRef::create(L, loc);
6685 lua_pushstring(L, listname.c_str());
6687 lua_pushinteger(L, index + 1);
6689 LuaItemStack::create(L, stack);
6691 objectref_get_or_create(L, player);
6692 if(lua_pcall(L, 5, 0, 0))
6693 script_error(L, "error: %s", lua_tostring(L, -1));
6696 // Report taken items
6697 void scriptapi_detached_inventory_on_take(lua_State *L,
6698 const std::string &name,
6699 const std::string &listname, int index, ItemStack &stack,
6700 ServerActiveObject *player)
6703 assert(lua_checkstack(L, 20));
6704 StackUnroller stack_unroller(L);
6706 // Push callback function on stack
6707 if(!get_detached_inventory_callback(L, name, "on_take"))
6710 // Call function(inv, listname, index, stack, player)
6712 InventoryLocation loc;
6713 loc.setDetached(name);
6714 InvRef::create(L, loc);
6716 lua_pushstring(L, listname.c_str());
6718 lua_pushinteger(L, index + 1);
6720 LuaItemStack::create(L, stack);
6722 objectref_get_or_create(L, player);
6723 if(lua_pcall(L, 5, 0, 0))
6724 script_error(L, "error: %s", lua_tostring(L, -1));
6731 void scriptapi_environment_step(lua_State *L, float dtime)
6734 assert(lua_checkstack(L, 20));
6735 //infostream<<"scriptapi_environment_step"<<std::endl;
6736 StackUnroller stack_unroller(L);
6738 // Get minetest.registered_globalsteps
6739 lua_getglobal(L, "minetest");
6740 lua_getfield(L, -1, "registered_globalsteps");
6742 lua_pushnumber(L, dtime);
6743 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6746 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6750 assert(lua_checkstack(L, 20));
6751 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6752 StackUnroller stack_unroller(L);
6754 // Get minetest.registered_on_generateds
6755 lua_getglobal(L, "minetest");
6756 lua_getfield(L, -1, "registered_on_generateds");
6758 push_v3s16(L, minp);
6759 push_v3s16(L, maxp);
6760 lua_pushnumber(L, blockseed);
6761 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6768 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6771 assert(lua_checkstack(L, 20));
6772 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6773 <<name<<"\""<<std::endl;
6774 StackUnroller stack_unroller(L);
6776 // Get minetest.registered_entities[name]
6777 lua_getglobal(L, "minetest");
6778 lua_getfield(L, -1, "registered_entities");
6779 luaL_checktype(L, -1, LUA_TTABLE);
6780 lua_pushstring(L, name);
6781 lua_gettable(L, -2);
6782 // Should be a table, which we will use as a prototype
6783 //luaL_checktype(L, -1, LUA_TTABLE);
6784 if(lua_type(L, -1) != LUA_TTABLE){
6785 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6788 int prototype_table = lua_gettop(L);
6789 //dump2(L, "prototype_table");
6791 // Create entity object
6793 int object = lua_gettop(L);
6795 // Set object metatable
6796 lua_pushvalue(L, prototype_table);
6797 lua_setmetatable(L, -2);
6799 // Add object reference
6800 // This should be userdata with metatable ObjectRef
6801 objectref_get(L, id);
6802 luaL_checktype(L, -1, LUA_TUSERDATA);
6803 if(!luaL_checkudata(L, -1, "ObjectRef"))
6804 luaL_typerror(L, -1, "ObjectRef");
6805 lua_setfield(L, -2, "object");
6807 // minetest.luaentities[id] = object
6808 lua_getglobal(L, "minetest");
6809 lua_getfield(L, -1, "luaentities");
6810 luaL_checktype(L, -1, LUA_TTABLE);
6811 lua_pushnumber(L, id); // Push id
6812 lua_pushvalue(L, object); // Copy object to top of stack
6813 lua_settable(L, -3);
6818 void scriptapi_luaentity_activate(lua_State *L, u16 id,
6819 const std::string &staticdata, u32 dtime_s)
6822 assert(lua_checkstack(L, 20));
6823 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
6824 StackUnroller stack_unroller(L);
6826 // Get minetest.luaentities[id]
6827 luaentity_get(L, id);
6828 int object = lua_gettop(L);
6830 // Get on_activate function
6831 lua_pushvalue(L, object);
6832 lua_getfield(L, -1, "on_activate");
6833 if(!lua_isnil(L, -1)){
6834 luaL_checktype(L, -1, LUA_TFUNCTION);
6835 lua_pushvalue(L, object); // self
6836 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
6837 lua_pushinteger(L, dtime_s);
6838 // Call with 3 arguments, 0 results
6839 if(lua_pcall(L, 3, 0, 0))
6840 script_error(L, "error running function on_activate: %s\n",
6841 lua_tostring(L, -1));
6845 void scriptapi_luaentity_rm(lua_State *L, u16 id)
6848 assert(lua_checkstack(L, 20));
6849 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
6851 // Get minetest.luaentities table
6852 lua_getglobal(L, "minetest");
6853 lua_getfield(L, -1, "luaentities");
6854 luaL_checktype(L, -1, LUA_TTABLE);
6855 int objectstable = lua_gettop(L);
6857 // Set luaentities[id] = nil
6858 lua_pushnumber(L, id); // Push id
6860 lua_settable(L, objectstable);
6862 lua_pop(L, 2); // pop luaentities, minetest
6865 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
6868 assert(lua_checkstack(L, 20));
6869 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
6870 StackUnroller stack_unroller(L);
6872 // Get minetest.luaentities[id]
6873 luaentity_get(L, id);
6874 int object = lua_gettop(L);
6876 // Get get_staticdata function
6877 lua_pushvalue(L, object);
6878 lua_getfield(L, -1, "get_staticdata");
6879 if(lua_isnil(L, -1))
6882 luaL_checktype(L, -1, LUA_TFUNCTION);
6883 lua_pushvalue(L, object); // self
6884 // Call with 1 arguments, 1 results
6885 if(lua_pcall(L, 1, 1, 0))
6886 script_error(L, "error running function get_staticdata: %s\n",
6887 lua_tostring(L, -1));
6890 const char *s = lua_tolstring(L, -1, &len);
6891 return std::string(s, len);
6894 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
6895 ObjectProperties *prop)
6898 assert(lua_checkstack(L, 20));
6899 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
6900 StackUnroller stack_unroller(L);
6902 // Get minetest.luaentities[id]
6903 luaentity_get(L, id);
6904 //int object = lua_gettop(L);
6906 // Set default values that differ from ObjectProperties defaults
6911 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
6913 getboolfield(L, -1, "physical", prop->physical);
6915 getfloatfield(L, -1, "weight", prop->weight);
6917 lua_getfield(L, -1, "collisionbox");
6918 if(lua_istable(L, -1))
6919 prop->collisionbox = read_aabb3f(L, -1, 1.0);
6922 getstringfield(L, -1, "visual", prop->visual);
6924 getstringfield(L, -1, "mesh", prop->mesh);
6926 // Deprecated: read object properties directly
6927 read_object_properties(L, -1, prop);
6929 // Read initial_properties
6930 lua_getfield(L, -1, "initial_properties");
6931 read_object_properties(L, -1, prop);
6935 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
6938 assert(lua_checkstack(L, 20));
6939 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6940 StackUnroller stack_unroller(L);
6942 // Get minetest.luaentities[id]
6943 luaentity_get(L, id);
6944 int object = lua_gettop(L);
6945 // State: object is at top of stack
6946 // Get step function
6947 lua_getfield(L, -1, "on_step");
6948 if(lua_isnil(L, -1))
6950 luaL_checktype(L, -1, LUA_TFUNCTION);
6951 lua_pushvalue(L, object); // self
6952 lua_pushnumber(L, dtime); // dtime
6953 // Call with 2 arguments, 0 results
6954 if(lua_pcall(L, 2, 0, 0))
6955 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
6958 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
6959 // tool_capabilities, direction)
6960 void scriptapi_luaentity_punch(lua_State *L, u16 id,
6961 ServerActiveObject *puncher, float time_from_last_punch,
6962 const ToolCapabilities *toolcap, v3f dir)
6965 assert(lua_checkstack(L, 20));
6966 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6967 StackUnroller stack_unroller(L);
6969 // Get minetest.luaentities[id]
6970 luaentity_get(L, id);
6971 int object = lua_gettop(L);
6972 // State: object is at top of stack
6974 lua_getfield(L, -1, "on_punch");
6975 if(lua_isnil(L, -1))
6977 luaL_checktype(L, -1, LUA_TFUNCTION);
6978 lua_pushvalue(L, object); // self
6979 objectref_get_or_create(L, puncher); // Clicker reference
6980 lua_pushnumber(L, time_from_last_punch);
6981 push_tool_capabilities(L, *toolcap);
6983 // Call with 5 arguments, 0 results
6984 if(lua_pcall(L, 5, 0, 0))
6985 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
6988 // Calls entity:on_rightclick(ObjectRef clicker)
6989 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
6990 ServerActiveObject *clicker)
6993 assert(lua_checkstack(L, 20));
6994 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
6995 StackUnroller stack_unroller(L);
6997 // Get minetest.luaentities[id]
6998 luaentity_get(L, id);
6999 int object = lua_gettop(L);
7000 // State: object is at top of stack
7002 lua_getfield(L, -1, "on_rightclick");
7003 if(lua_isnil(L, -1))
7005 luaL_checktype(L, -1, LUA_TFUNCTION);
7006 lua_pushvalue(L, object); // self
7007 objectref_get_or_create(L, clicker); // Clicker reference
7008 // Call with 2 arguments, 0 results
7009 if(lua_pcall(L, 2, 0, 0))
7010 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));