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 NoiseParams *read_noiseparams(lua_State *L, int index)
702 index = lua_gettop(L) + 1 + index;
704 if (!lua_istable(L, index))
707 NoiseParams *np = new NoiseParams;
709 np->offset = getfloatfield_default(L, index, "offset", 0.0);
710 np->scale = getfloatfield_default(L, index, "scale", 0.0);
711 lua_getfield(L, index, "spread");
712 np->spread = read_v3f(L, -1);
713 np->seed = getintfield_default(L, index, "seed", 0);
714 np->octaves = getintfield_default(L, index, "octaves", 0);
715 np->persist = getfloatfield_default(L, index, "persist", 0.0);
723 static void read_groups(lua_State *L, int index,
724 std::map<std::string, int> &result)
726 if (!lua_istable(L,index))
732 while(lua_next(L, index) != 0){
733 // key at index -2 and value at index -1
734 std::string name = luaL_checkstring(L, -2);
735 int rating = luaL_checkinteger(L, -1);
736 result[name] = rating;
737 // removes value, keeps key for next iteration
745 static void read_privileges(lua_State *L, int index,
746 std::set<std::string> &result)
752 while(lua_next(L, index) != 0){
753 // key at index -2 and value at index -1
754 std::string key = luaL_checkstring(L, -2);
755 bool value = lua_toboolean(L, -1);
758 // removes value, keeps key for next iteration
767 static ToolCapabilities read_tool_capabilities(
768 lua_State *L, int table)
770 ToolCapabilities toolcap;
771 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
772 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
773 lua_getfield(L, table, "groupcaps");
774 if(lua_istable(L, -1)){
775 int table_groupcaps = lua_gettop(L);
777 while(lua_next(L, table_groupcaps) != 0){
778 // key at index -2 and value at index -1
779 std::string groupname = luaL_checkstring(L, -2);
780 if(lua_istable(L, -1)){
781 int table_groupcap = lua_gettop(L);
782 // This will be created
783 ToolGroupCap groupcap;
784 // Read simple parameters
785 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
786 getintfield(L, table_groupcap, "uses", groupcap.uses);
787 // DEPRECATED: maxwear
789 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
791 groupcap.uses = 1.0/maxwear;
794 infostream<<script_get_backtrace(L)<<std::endl;
795 infostream<<"WARNING: field \"maxwear\" is deprecated; "
796 <<"should replace with uses=1/maxwear"<<std::endl;
798 // Read "times" table
799 lua_getfield(L, table_groupcap, "times");
800 if(lua_istable(L, -1)){
801 int table_times = lua_gettop(L);
803 while(lua_next(L, table_times) != 0){
804 // key at index -2 and value at index -1
805 int rating = luaL_checkinteger(L, -2);
806 float time = luaL_checknumber(L, -1);
807 groupcap.times[rating] = time;
808 // removes value, keeps key for next iteration
813 // Insert groupcap into toolcap
814 toolcap.groupcaps[groupname] = groupcap;
816 // removes value, keeps key for next iteration
824 static void set_tool_capabilities(lua_State *L, int table,
825 const ToolCapabilities &toolcap)
827 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
828 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
829 // Create groupcaps table
832 for(std::map<std::string, ToolGroupCap>::const_iterator
833 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
834 // Create groupcap table
836 const std::string &name = i->first;
837 const ToolGroupCap &groupcap = i->second;
838 // Create subtable "times"
840 for(std::map<int, float>::const_iterator
841 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
842 int rating = i->first;
843 float time = i->second;
844 lua_pushinteger(L, rating);
845 lua_pushnumber(L, time);
848 // Set subtable "times"
849 lua_setfield(L, -2, "times");
850 // Set simple parameters
851 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
852 setintfield(L, -1, "uses", groupcap.uses);
853 // Insert groupcap table into groupcaps table
854 lua_setfield(L, -2, name.c_str());
856 // Set groupcaps table
857 lua_setfield(L, -2, "groupcaps");
860 static void push_tool_capabilities(lua_State *L,
861 const ToolCapabilities &prop)
864 set_tool_capabilities(L, -1, prop);
871 static void set_dig_params(lua_State *L, int table,
872 const DigParams ¶ms)
874 setboolfield(L, table, "diggable", params.diggable);
875 setfloatfield(L, table, "time", params.time);
876 setintfield(L, table, "wear", params.wear);
879 static void push_dig_params(lua_State *L,
880 const DigParams ¶ms)
883 set_dig_params(L, -1, params);
890 static void set_hit_params(lua_State *L, int table,
891 const HitParams ¶ms)
893 setintfield(L, table, "hp", params.hp);
894 setintfield(L, table, "wear", params.wear);
897 static void push_hit_params(lua_State *L,
898 const HitParams ¶ms)
901 set_hit_params(L, -1, params);
908 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
911 if(pointed.type == POINTEDTHING_NODE)
913 lua_pushstring(L, "node");
914 lua_setfield(L, -2, "type");
915 push_v3s16(L, pointed.node_undersurface);
916 lua_setfield(L, -2, "under");
917 push_v3s16(L, pointed.node_abovesurface);
918 lua_setfield(L, -2, "above");
920 else if(pointed.type == POINTEDTHING_OBJECT)
922 lua_pushstring(L, "object");
923 lua_setfield(L, -2, "type");
924 objectref_get(L, pointed.object_id);
925 lua_setfield(L, -2, "ref");
929 lua_pushstring(L, "nothing");
930 lua_setfield(L, -2, "type");
938 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
941 index = lua_gettop(L) + 1 + index;
942 if(lua_isnil(L, index)){
943 } else if(lua_istable(L, index)){
944 getstringfield(L, index, "name", spec.name);
945 getfloatfield(L, index, "gain", spec.gain);
946 } else if(lua_isstring(L, index)){
947 spec.name = lua_tostring(L, index);
955 static void read_object_properties(lua_State *L, int index,
956 ObjectProperties *prop)
959 index = lua_gettop(L) + 1 + index;
960 if(!lua_istable(L, index))
963 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
965 getboolfield(L, -1, "physical", prop->physical);
967 getfloatfield(L, -1, "weight", prop->weight);
969 lua_getfield(L, -1, "collisionbox");
970 if(lua_istable(L, -1))
971 prop->collisionbox = read_aabb3f(L, -1, 1.0);
974 getstringfield(L, -1, "visual", prop->visual);
976 getstringfield(L, -1, "mesh", prop->mesh);
978 lua_getfield(L, -1, "visual_size");
979 if(lua_istable(L, -1))
980 prop->visual_size = read_v2f(L, -1);
983 lua_getfield(L, -1, "textures");
984 if(lua_istable(L, -1)){
985 prop->textures.clear();
986 int table = lua_gettop(L);
988 while(lua_next(L, table) != 0){
989 // key at index -2 and value at index -1
990 if(lua_isstring(L, -1))
991 prop->textures.push_back(lua_tostring(L, -1));
993 prop->textures.push_back("");
994 // removes value, keeps key for next iteration
1000 lua_getfield(L, -1, "colors");
1001 if(lua_istable(L, -1)){
1002 prop->colors.clear();
1003 int table = lua_gettop(L);
1005 while(lua_next(L, table) != 0){
1006 // key at index -2 and value at index -1
1007 if(lua_isstring(L, -1))
1008 prop->colors.push_back(readARGB8(L, -1));
1010 prop->colors.push_back(video::SColor(255, 255, 255, 255));
1011 // removes value, keeps key for next iteration
1017 lua_getfield(L, -1, "spritediv");
1018 if(lua_istable(L, -1))
1019 prop->spritediv = read_v2s16(L, -1);
1022 lua_getfield(L, -1, "initial_sprite_basepos");
1023 if(lua_istable(L, -1))
1024 prop->initial_sprite_basepos = read_v2s16(L, -1);
1027 getboolfield(L, -1, "is_visible", prop->is_visible);
1028 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
1029 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
1036 static ItemDefinition read_item_definition(lua_State *L, int index,
1037 ItemDefinition default_def = ItemDefinition())
1040 index = lua_gettop(L) + 1 + index;
1042 // Read the item definition
1043 ItemDefinition def = default_def;
1045 def.type = (ItemType)getenumfield(L, index, "type",
1046 es_ItemType, ITEM_NONE);
1047 getstringfield(L, index, "name", def.name);
1048 getstringfield(L, index, "description", def.description);
1049 getstringfield(L, index, "inventory_image", def.inventory_image);
1050 getstringfield(L, index, "wield_image", def.wield_image);
1052 lua_getfield(L, index, "wield_scale");
1053 if(lua_istable(L, -1)){
1054 def.wield_scale = check_v3f(L, -1);
1058 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1059 if(def.stack_max == 0)
1062 lua_getfield(L, index, "on_use");
1063 def.usable = lua_isfunction(L, -1);
1066 lua_getfield(L, index, "on_rightclick");
1067 def.rightclickable = lua_isfunction(L, -1);
1070 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1072 warn_if_field_exists(L, index, "tool_digging_properties",
1073 "deprecated: use tool_capabilities");
1075 lua_getfield(L, index, "tool_capabilities");
1076 if(lua_istable(L, -1)){
1077 def.tool_capabilities = new ToolCapabilities(
1078 read_tool_capabilities(L, -1));
1081 // If name is "" (hand), ensure there are ToolCapabilities
1082 // because it will be looked up there whenever any other item has
1083 // no ToolCapabilities
1084 if(def.name == "" && def.tool_capabilities == NULL){
1085 def.tool_capabilities = new ToolCapabilities();
1088 lua_getfield(L, index, "groups");
1089 read_groups(L, -1, def.groups);
1092 // Client shall immediately place this node when player places the item.
1093 // Server will update the precise end result a moment later.
1094 // "" = no prediction
1095 getstringfield(L, index, "node_placement_prediction",
1096 def.node_placement_prediction);
1105 static TileDef read_tiledef(lua_State *L, int index)
1108 index = lua_gettop(L) + 1 + index;
1112 // key at index -2 and value at index
1113 if(lua_isstring(L, index)){
1114 // "default_lava.png"
1115 tiledef.name = lua_tostring(L, index);
1117 else if(lua_istable(L, index))
1119 // {name="default_lava.png", animation={}}
1121 getstringfield(L, index, "name", tiledef.name);
1122 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1123 tiledef.backface_culling = getboolfield_default(
1124 L, index, "backface_culling", true);
1126 lua_getfield(L, index, "animation");
1127 if(lua_istable(L, -1)){
1128 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1129 tiledef.animation.type = (TileAnimationType)
1130 getenumfield(L, -1, "type", es_TileAnimationType,
1132 tiledef.animation.aspect_w =
1133 getintfield_default(L, -1, "aspect_w", 16);
1134 tiledef.animation.aspect_h =
1135 getintfield_default(L, -1, "aspect_h", 16);
1136 tiledef.animation.length =
1137 getfloatfield_default(L, -1, "length", 1.0);
1149 static ContentFeatures read_content_features(lua_State *L, int index)
1152 index = lua_gettop(L) + 1 + index;
1156 /* Cache existence of some callbacks */
1157 lua_getfield(L, index, "on_construct");
1158 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1160 lua_getfield(L, index, "on_destruct");
1161 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1163 lua_getfield(L, index, "after_destruct");
1164 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1168 getstringfield(L, index, "name", f.name);
1171 lua_getfield(L, index, "groups");
1172 read_groups(L, -1, f.groups);
1175 /* Visual definition */
1177 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1179 getfloatfield(L, index, "visual_scale", f.visual_scale);
1182 lua_getfield(L, index, "tiles");
1183 // If nil, try the deprecated name "tile_images" instead
1184 if(lua_isnil(L, -1)){
1186 warn_if_field_exists(L, index, "tile_images",
1187 "Deprecated; new name is \"tiles\".");
1188 lua_getfield(L, index, "tile_images");
1190 if(lua_istable(L, -1)){
1191 int table = lua_gettop(L);
1194 while(lua_next(L, table) != 0){
1195 // Read tiledef from value
1196 f.tiledef[i] = read_tiledef(L, -1);
1197 // removes value, keeps key for next iteration
1205 // Copy last value to all remaining textures
1207 TileDef lasttile = f.tiledef[i-1];
1209 f.tiledef[i] = lasttile;
1216 // special_tiles = {}
1217 lua_getfield(L, index, "special_tiles");
1218 // If nil, try the deprecated name "special_materials" instead
1219 if(lua_isnil(L, -1)){
1221 warn_if_field_exists(L, index, "special_materials",
1222 "Deprecated; new name is \"special_tiles\".");
1223 lua_getfield(L, index, "special_materials");
1225 if(lua_istable(L, -1)){
1226 int table = lua_gettop(L);
1229 while(lua_next(L, table) != 0){
1230 // Read tiledef from value
1231 f.tiledef_special[i] = read_tiledef(L, -1);
1232 // removes value, keeps key for next iteration
1243 f.alpha = getintfield_default(L, index, "alpha", 255);
1247 lua_getfield(L, index, "post_effect_color");
1248 if(!lua_isnil(L, -1))
1249 f.post_effect_color = readARGB8(L, -1);
1252 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1253 es_ContentParamType, CPT_NONE);
1254 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1255 es_ContentParamType2, CPT2_NONE);
1257 // Warn about some deprecated fields
1258 warn_if_field_exists(L, index, "wall_mounted",
1259 "deprecated: use paramtype2 = 'wallmounted'");
1260 warn_if_field_exists(L, index, "light_propagates",
1261 "deprecated: determined from paramtype");
1262 warn_if_field_exists(L, index, "dug_item",
1263 "deprecated: use 'drop' field");
1264 warn_if_field_exists(L, index, "extra_dug_item",
1265 "deprecated: use 'drop' field");
1266 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1267 "deprecated: use 'drop' field");
1268 warn_if_field_exists(L, index, "metadata_name",
1269 "deprecated: use on_add and metadata callbacks");
1271 // True for all ground-like things like stone and mud, false for eg. trees
1272 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1273 f.light_propagates = (f.param_type == CPT_LIGHT);
1274 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1275 // This is used for collision detection.
1276 // Also for general solidness queries.
1277 getboolfield(L, index, "walkable", f.walkable);
1278 // Player can point to these
1279 getboolfield(L, index, "pointable", f.pointable);
1280 // Player can dig these
1281 getboolfield(L, index, "diggable", f.diggable);
1282 // Player can climb these
1283 getboolfield(L, index, "climbable", f.climbable);
1284 // Player can build on these
1285 getboolfield(L, index, "buildable_to", f.buildable_to);
1286 // Whether the node is non-liquid, source liquid or flowing liquid
1287 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1288 es_LiquidType, LIQUID_NONE);
1289 // If the content is liquid, this is the flowing version of the liquid.
1290 getstringfield(L, index, "liquid_alternative_flowing",
1291 f.liquid_alternative_flowing);
1292 // If the content is liquid, this is the source version of the liquid.
1293 getstringfield(L, index, "liquid_alternative_source",
1294 f.liquid_alternative_source);
1295 // Viscosity for fluid flow, ranging from 1 to 7, with
1296 // 1 giving almost instantaneous propagation and 7 being
1297 // the slowest possible
1298 f.liquid_viscosity = getintfield_default(L, index,
1299 "liquid_viscosity", f.liquid_viscosity);
1300 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1301 // Amount of light the node emits
1302 f.light_source = getintfield_default(L, index,
1303 "light_source", f.light_source);
1304 f.damage_per_second = getintfield_default(L, index,
1305 "damage_per_second", f.damage_per_second);
1307 lua_getfield(L, index, "node_box");
1308 if(lua_istable(L, -1))
1309 f.node_box = read_nodebox(L, -1);
1312 lua_getfield(L, index, "selection_box");
1313 if(lua_istable(L, -1))
1314 f.selection_box = read_nodebox(L, -1);
1317 // Set to true if paramtype used to be 'facedir_simple'
1318 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1319 // Set to true if wall_mounted used to be set to true
1320 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1323 lua_getfield(L, index, "sounds");
1324 if(lua_istable(L, -1)){
1325 lua_getfield(L, -1, "footstep");
1326 read_soundspec(L, -1, f.sound_footstep);
1328 lua_getfield(L, -1, "dig");
1329 read_soundspec(L, -1, f.sound_dig);
1331 lua_getfield(L, -1, "dug");
1332 read_soundspec(L, -1, f.sound_dug);
1344 static ItemStack read_item(lua_State *L, int index);
1345 static std::vector<ItemStack> read_items(lua_State *L, int index);
1346 // creates a table of ItemStacks
1347 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1349 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1350 lua_State *L, int tableindex, int forcesize=-1)
1353 tableindex = lua_gettop(L) + 1 + tableindex;
1354 // If nil, delete list
1355 if(lua_isnil(L, tableindex)){
1356 inv->deleteList(name);
1359 // Otherwise set list
1360 std::vector<ItemStack> items = read_items(L, tableindex);
1361 int listsize = (forcesize != -1) ? forcesize : items.size();
1362 InventoryList *invlist = inv->addList(name, listsize);
1364 for(std::vector<ItemStack>::const_iterator
1365 i = items.begin(); i != items.end(); i++){
1366 if(forcesize != -1 && index == forcesize)
1368 invlist->changeItem(index, *i);
1371 while(forcesize != -1 && index < forcesize){
1372 invlist->deleteItem(index);
1377 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1380 InventoryList *invlist = inv->getList(name);
1381 if(invlist == NULL){
1385 std::vector<ItemStack> items;
1386 for(u32 i=0; i<invlist->getSize(); i++)
1387 items.push_back(invlist->getItem(i));
1388 push_items(L, items);
1392 Helpful macros for userdata classes
1395 #define method(class, name) {#name, class::l_##name}
1406 static const char className[];
1407 static const luaL_reg methods[];
1409 // Exported functions
1411 // garbage collector
1412 static int gc_object(lua_State *L)
1414 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1419 // is_empty(self) -> true/false
1420 static int l_is_empty(lua_State *L)
1422 LuaItemStack *o = checkobject(L, 1);
1423 ItemStack &item = o->m_stack;
1424 lua_pushboolean(L, item.empty());
1428 // get_name(self) -> string
1429 static int l_get_name(lua_State *L)
1431 LuaItemStack *o = checkobject(L, 1);
1432 ItemStack &item = o->m_stack;
1433 lua_pushstring(L, item.name.c_str());
1437 // get_count(self) -> number
1438 static int l_get_count(lua_State *L)
1440 LuaItemStack *o = checkobject(L, 1);
1441 ItemStack &item = o->m_stack;
1442 lua_pushinteger(L, item.count);
1446 // get_wear(self) -> number
1447 static int l_get_wear(lua_State *L)
1449 LuaItemStack *o = checkobject(L, 1);
1450 ItemStack &item = o->m_stack;
1451 lua_pushinteger(L, item.wear);
1455 // get_metadata(self) -> string
1456 static int l_get_metadata(lua_State *L)
1458 LuaItemStack *o = checkobject(L, 1);
1459 ItemStack &item = o->m_stack;
1460 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1464 // clear(self) -> true
1465 static int l_clear(lua_State *L)
1467 LuaItemStack *o = checkobject(L, 1);
1469 lua_pushboolean(L, true);
1473 // replace(self, itemstack or itemstring or table or nil) -> true
1474 static int l_replace(lua_State *L)
1476 LuaItemStack *o = checkobject(L, 1);
1477 o->m_stack = read_item(L, 2);
1478 lua_pushboolean(L, true);
1482 // to_string(self) -> string
1483 static int l_to_string(lua_State *L)
1485 LuaItemStack *o = checkobject(L, 1);
1486 std::string itemstring = o->m_stack.getItemString();
1487 lua_pushstring(L, itemstring.c_str());
1491 // to_table(self) -> table or nil
1492 static int l_to_table(lua_State *L)
1494 LuaItemStack *o = checkobject(L, 1);
1495 const ItemStack &item = o->m_stack;
1503 lua_pushstring(L, item.name.c_str());
1504 lua_setfield(L, -2, "name");
1505 lua_pushinteger(L, item.count);
1506 lua_setfield(L, -2, "count");
1507 lua_pushinteger(L, item.wear);
1508 lua_setfield(L, -2, "wear");
1509 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1510 lua_setfield(L, -2, "metadata");
1515 // get_stack_max(self) -> number
1516 static int l_get_stack_max(lua_State *L)
1518 LuaItemStack *o = checkobject(L, 1);
1519 ItemStack &item = o->m_stack;
1520 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1524 // get_free_space(self) -> number
1525 static int l_get_free_space(lua_State *L)
1527 LuaItemStack *o = checkobject(L, 1);
1528 ItemStack &item = o->m_stack;
1529 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1533 // is_known(self) -> true/false
1534 // Checks if the item is defined.
1535 static int l_is_known(lua_State *L)
1537 LuaItemStack *o = checkobject(L, 1);
1538 ItemStack &item = o->m_stack;
1539 bool is_known = item.isKnown(get_server(L)->idef());
1540 lua_pushboolean(L, is_known);
1544 // get_definition(self) -> table
1545 // Returns the item definition table from minetest.registered_items,
1546 // or a fallback one (name="unknown")
1547 static int l_get_definition(lua_State *L)
1549 LuaItemStack *o = checkobject(L, 1);
1550 ItemStack &item = o->m_stack;
1552 // Get minetest.registered_items[name]
1553 lua_getglobal(L, "minetest");
1554 lua_getfield(L, -1, "registered_items");
1555 luaL_checktype(L, -1, LUA_TTABLE);
1556 lua_getfield(L, -1, item.name.c_str());
1557 if(lua_isnil(L, -1))
1560 lua_getfield(L, -1, "unknown");
1565 // get_tool_capabilities(self) -> table
1566 // Returns the effective tool digging properties.
1567 // Returns those of the hand ("") if this item has none associated.
1568 static int l_get_tool_capabilities(lua_State *L)
1570 LuaItemStack *o = checkobject(L, 1);
1571 ItemStack &item = o->m_stack;
1572 const ToolCapabilities &prop =
1573 item.getToolCapabilities(get_server(L)->idef());
1574 push_tool_capabilities(L, prop);
1578 // add_wear(self, amount) -> true/false
1579 // The range for "amount" is [0,65535]. Wear is only added if the item
1580 // is a tool. Adding wear might destroy the item.
1581 // Returns true if the item is (or was) a tool.
1582 static int l_add_wear(lua_State *L)
1584 LuaItemStack *o = checkobject(L, 1);
1585 ItemStack &item = o->m_stack;
1586 int amount = lua_tointeger(L, 2);
1587 bool result = item.addWear(amount, get_server(L)->idef());
1588 lua_pushboolean(L, result);
1592 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1593 // Returns leftover item stack
1594 static int l_add_item(lua_State *L)
1596 LuaItemStack *o = checkobject(L, 1);
1597 ItemStack &item = o->m_stack;
1598 ItemStack newitem = read_item(L, 2);
1599 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1600 create(L, leftover);
1604 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1605 // First return value is true iff the new item fits fully into the stack
1606 // Second return value is the would-be-left-over item stack
1607 static int l_item_fits(lua_State *L)
1609 LuaItemStack *o = checkobject(L, 1);
1610 ItemStack &item = o->m_stack;
1611 ItemStack newitem = read_item(L, 2);
1613 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1614 lua_pushboolean(L, fits); // first return value
1615 create(L, restitem); // second return value
1619 // take_item(self, takecount=1) -> itemstack
1620 static int l_take_item(lua_State *L)
1622 LuaItemStack *o = checkobject(L, 1);
1623 ItemStack &item = o->m_stack;
1625 if(!lua_isnone(L, 2))
1626 takecount = luaL_checkinteger(L, 2);
1627 ItemStack taken = item.takeItem(takecount);
1632 // peek_item(self, peekcount=1) -> itemstack
1633 static int l_peek_item(lua_State *L)
1635 LuaItemStack *o = checkobject(L, 1);
1636 ItemStack &item = o->m_stack;
1638 if(!lua_isnone(L, 2))
1639 peekcount = lua_tointeger(L, 2);
1640 ItemStack peekaboo = item.peekItem(peekcount);
1641 create(L, peekaboo);
1646 LuaItemStack(const ItemStack &item):
1655 const ItemStack& getItem() const
1659 ItemStack& getItem()
1664 // LuaItemStack(itemstack or itemstring or table or nil)
1665 // Creates an LuaItemStack and leaves it on top of stack
1666 static int create_object(lua_State *L)
1668 ItemStack item = read_item(L, 1);
1669 LuaItemStack *o = new LuaItemStack(item);
1670 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1671 luaL_getmetatable(L, className);
1672 lua_setmetatable(L, -2);
1675 // Not callable from Lua
1676 static int create(lua_State *L, const ItemStack &item)
1678 LuaItemStack *o = new LuaItemStack(item);
1679 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1680 luaL_getmetatable(L, className);
1681 lua_setmetatable(L, -2);
1685 static LuaItemStack* checkobject(lua_State *L, int narg)
1687 luaL_checktype(L, narg, LUA_TUSERDATA);
1688 void *ud = luaL_checkudata(L, narg, className);
1689 if(!ud) luaL_typerror(L, narg, className);
1690 return *(LuaItemStack**)ud; // unbox pointer
1693 static void Register(lua_State *L)
1696 int methodtable = lua_gettop(L);
1697 luaL_newmetatable(L, className);
1698 int metatable = lua_gettop(L);
1700 lua_pushliteral(L, "__metatable");
1701 lua_pushvalue(L, methodtable);
1702 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1704 lua_pushliteral(L, "__index");
1705 lua_pushvalue(L, methodtable);
1706 lua_settable(L, metatable);
1708 lua_pushliteral(L, "__gc");
1709 lua_pushcfunction(L, gc_object);
1710 lua_settable(L, metatable);
1712 lua_pop(L, 1); // drop metatable
1714 luaL_openlib(L, 0, methods, 0); // fill methodtable
1715 lua_pop(L, 1); // drop methodtable
1717 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1718 lua_register(L, className, create_object);
1721 const char LuaItemStack::className[] = "ItemStack";
1722 const luaL_reg LuaItemStack::methods[] = {
1723 method(LuaItemStack, is_empty),
1724 method(LuaItemStack, get_name),
1725 method(LuaItemStack, get_count),
1726 method(LuaItemStack, get_wear),
1727 method(LuaItemStack, get_metadata),
1728 method(LuaItemStack, clear),
1729 method(LuaItemStack, replace),
1730 method(LuaItemStack, to_string),
1731 method(LuaItemStack, to_table),
1732 method(LuaItemStack, get_stack_max),
1733 method(LuaItemStack, get_free_space),
1734 method(LuaItemStack, is_known),
1735 method(LuaItemStack, get_definition),
1736 method(LuaItemStack, get_tool_capabilities),
1737 method(LuaItemStack, add_wear),
1738 method(LuaItemStack, add_item),
1739 method(LuaItemStack, item_fits),
1740 method(LuaItemStack, take_item),
1741 method(LuaItemStack, peek_item),
1745 static ItemStack read_item(lua_State *L, int index)
1748 index = lua_gettop(L) + 1 + index;
1750 if(lua_isnil(L, index))
1754 else if(lua_isuserdata(L, index))
1756 // Convert from LuaItemStack
1757 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1758 return o->getItem();
1760 else if(lua_isstring(L, index))
1762 // Convert from itemstring
1763 std::string itemstring = lua_tostring(L, index);
1764 IItemDefManager *idef = get_server(L)->idef();
1768 item.deSerialize(itemstring, idef);
1771 catch(SerializationError &e)
1773 infostream<<"WARNING: unable to create item from itemstring"
1774 <<": "<<itemstring<<std::endl;
1778 else if(lua_istable(L, index))
1780 // Convert from table
1781 IItemDefManager *idef = get_server(L)->idef();
1782 std::string name = getstringfield_default(L, index, "name", "");
1783 int count = getintfield_default(L, index, "count", 1);
1784 int wear = getintfield_default(L, index, "wear", 0);
1785 std::string metadata = getstringfield_default(L, index, "metadata", "");
1786 return ItemStack(name, count, wear, metadata, idef);
1790 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1794 static std::vector<ItemStack> read_items(lua_State *L, int index)
1797 index = lua_gettop(L) + 1 + index;
1799 std::vector<ItemStack> items;
1800 luaL_checktype(L, index, LUA_TTABLE);
1802 while(lua_next(L, index) != 0){
1803 // key at index -2 and value at index -1
1804 items.push_back(read_item(L, -1));
1805 // removes value, keeps key for next iteration
1811 // creates a table of ItemStacks
1812 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1814 // Get the table insert function
1815 lua_getglobal(L, "table");
1816 lua_getfield(L, -1, "insert");
1817 int table_insert = lua_gettop(L);
1818 // Create and fill table
1820 int table = lua_gettop(L);
1821 for(u32 i=0; i<items.size(); i++){
1822 ItemStack item = items[i];
1823 lua_pushvalue(L, table_insert);
1824 lua_pushvalue(L, table);
1825 LuaItemStack::create(L, item);
1826 if(lua_pcall(L, 2, 0, 0))
1827 script_error(L, "error: %s", lua_tostring(L, -1));
1829 lua_remove(L, -2); // Remove table
1830 lua_remove(L, -2); // Remove insert
1840 InventoryLocation m_loc;
1842 static const char className[];
1843 static const luaL_reg methods[];
1845 static InvRef *checkobject(lua_State *L, int narg)
1847 luaL_checktype(L, narg, LUA_TUSERDATA);
1848 void *ud = luaL_checkudata(L, narg, className);
1849 if(!ud) luaL_typerror(L, narg, className);
1850 return *(InvRef**)ud; // unbox pointer
1853 static Inventory* getinv(lua_State *L, InvRef *ref)
1855 return get_server(L)->getInventory(ref->m_loc);
1858 static InventoryList* getlist(lua_State *L, InvRef *ref,
1859 const char *listname)
1861 Inventory *inv = getinv(L, ref);
1864 return inv->getList(listname);
1867 static void reportInventoryChange(lua_State *L, InvRef *ref)
1869 // Inform other things that the inventory has changed
1870 get_server(L)->setInventoryModified(ref->m_loc);
1873 // Exported functions
1875 // garbage collector
1876 static int gc_object(lua_State *L) {
1877 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1882 // is_empty(self, listname) -> true/false
1883 static int l_is_empty(lua_State *L)
1885 InvRef *ref = checkobject(L, 1);
1886 const char *listname = luaL_checkstring(L, 2);
1887 InventoryList *list = getlist(L, ref, listname);
1888 if(list && list->getUsedSlots() > 0){
1889 lua_pushboolean(L, false);
1891 lua_pushboolean(L, true);
1896 // get_size(self, listname)
1897 static int l_get_size(lua_State *L)
1899 InvRef *ref = checkobject(L, 1);
1900 const char *listname = luaL_checkstring(L, 2);
1901 InventoryList *list = getlist(L, ref, listname);
1903 lua_pushinteger(L, list->getSize());
1905 lua_pushinteger(L, 0);
1910 // get_width(self, listname)
1911 static int l_get_width(lua_State *L)
1913 InvRef *ref = checkobject(L, 1);
1914 const char *listname = luaL_checkstring(L, 2);
1915 InventoryList *list = getlist(L, ref, listname);
1917 lua_pushinteger(L, list->getWidth());
1919 lua_pushinteger(L, 0);
1924 // set_size(self, listname, size)
1925 static int l_set_size(lua_State *L)
1927 InvRef *ref = checkobject(L, 1);
1928 const char *listname = luaL_checkstring(L, 2);
1929 int newsize = luaL_checknumber(L, 3);
1930 Inventory *inv = getinv(L, ref);
1932 inv->deleteList(listname);
1933 reportInventoryChange(L, ref);
1936 InventoryList *list = inv->getList(listname);
1938 list->setSize(newsize);
1940 list = inv->addList(listname, newsize);
1942 reportInventoryChange(L, ref);
1946 // set_width(self, listname, size)
1947 static int l_set_width(lua_State *L)
1949 InvRef *ref = checkobject(L, 1);
1950 const char *listname = luaL_checkstring(L, 2);
1951 int newwidth = luaL_checknumber(L, 3);
1952 Inventory *inv = getinv(L, ref);
1953 InventoryList *list = inv->getList(listname);
1955 list->setWidth(newwidth);
1959 reportInventoryChange(L, ref);
1963 // get_stack(self, listname, i) -> itemstack
1964 static int l_get_stack(lua_State *L)
1966 InvRef *ref = checkobject(L, 1);
1967 const char *listname = luaL_checkstring(L, 2);
1968 int i = luaL_checknumber(L, 3) - 1;
1969 InventoryList *list = getlist(L, ref, listname);
1971 if(list != NULL && i >= 0 && i < (int) list->getSize())
1972 item = list->getItem(i);
1973 LuaItemStack::create(L, item);
1977 // set_stack(self, listname, i, stack) -> true/false
1978 static int l_set_stack(lua_State *L)
1980 InvRef *ref = checkobject(L, 1);
1981 const char *listname = luaL_checkstring(L, 2);
1982 int i = luaL_checknumber(L, 3) - 1;
1983 ItemStack newitem = read_item(L, 4);
1984 InventoryList *list = getlist(L, ref, listname);
1985 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1986 list->changeItem(i, newitem);
1987 reportInventoryChange(L, ref);
1988 lua_pushboolean(L, true);
1990 lua_pushboolean(L, false);
1995 // get_list(self, listname) -> list or nil
1996 static int l_get_list(lua_State *L)
1998 InvRef *ref = checkobject(L, 1);
1999 const char *listname = luaL_checkstring(L, 2);
2000 Inventory *inv = getinv(L, ref);
2001 inventory_get_list_to_lua(inv, listname, L);
2005 // set_list(self, listname, list)
2006 static int l_set_list(lua_State *L)
2008 InvRef *ref = checkobject(L, 1);
2009 const char *listname = luaL_checkstring(L, 2);
2010 Inventory *inv = getinv(L, ref);
2011 InventoryList *list = inv->getList(listname);
2013 inventory_set_list_from_lua(inv, listname, L, 3,
2016 inventory_set_list_from_lua(inv, listname, L, 3);
2017 reportInventoryChange(L, ref);
2021 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2022 // Returns the leftover stack
2023 static int l_add_item(lua_State *L)
2025 InvRef *ref = checkobject(L, 1);
2026 const char *listname = luaL_checkstring(L, 2);
2027 ItemStack item = read_item(L, 3);
2028 InventoryList *list = getlist(L, ref, listname);
2030 ItemStack leftover = list->addItem(item);
2031 if(leftover.count != item.count)
2032 reportInventoryChange(L, ref);
2033 LuaItemStack::create(L, leftover);
2035 LuaItemStack::create(L, item);
2040 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2041 // Returns true if the item completely fits into the list
2042 static int l_room_for_item(lua_State *L)
2044 InvRef *ref = checkobject(L, 1);
2045 const char *listname = luaL_checkstring(L, 2);
2046 ItemStack item = read_item(L, 3);
2047 InventoryList *list = getlist(L, ref, listname);
2049 lua_pushboolean(L, list->roomForItem(item));
2051 lua_pushboolean(L, false);
2056 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2057 // Returns true if the list contains the given count of the given item name
2058 static int l_contains_item(lua_State *L)
2060 InvRef *ref = checkobject(L, 1);
2061 const char *listname = luaL_checkstring(L, 2);
2062 ItemStack item = read_item(L, 3);
2063 InventoryList *list = getlist(L, ref, listname);
2065 lua_pushboolean(L, list->containsItem(item));
2067 lua_pushboolean(L, false);
2072 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2073 // Returns the items that were actually removed
2074 static int l_remove_item(lua_State *L)
2076 InvRef *ref = checkobject(L, 1);
2077 const char *listname = luaL_checkstring(L, 2);
2078 ItemStack item = read_item(L, 3);
2079 InventoryList *list = getlist(L, ref, listname);
2081 ItemStack removed = list->removeItem(item);
2082 if(!removed.empty())
2083 reportInventoryChange(L, ref);
2084 LuaItemStack::create(L, removed);
2086 LuaItemStack::create(L, ItemStack());
2091 // get_location() -> location (like minetest.get_inventory(location))
2092 static int l_get_location(lua_State *L)
2094 InvRef *ref = checkobject(L, 1);
2095 const InventoryLocation &loc = ref->m_loc;
2097 case InventoryLocation::PLAYER:
2099 lua_pushstring(L, "player");
2100 lua_setfield(L, -2, "type");
2101 lua_pushstring(L, loc.name.c_str());
2102 lua_setfield(L, -2, "name");
2104 case InventoryLocation::NODEMETA:
2106 lua_pushstring(L, "nodemeta");
2107 lua_setfield(L, -2, "type");
2108 push_v3s16(L, loc.p);
2109 lua_setfield(L, -2, "name");
2111 case InventoryLocation::DETACHED:
2113 lua_pushstring(L, "detached");
2114 lua_setfield(L, -2, "type");
2115 lua_pushstring(L, loc.name.c_str());
2116 lua_setfield(L, -2, "name");
2118 case InventoryLocation::UNDEFINED:
2119 case InventoryLocation::CURRENT_PLAYER:
2123 lua_pushstring(L, "undefined");
2124 lua_setfield(L, -2, "type");
2129 InvRef(const InventoryLocation &loc):
2138 // Creates an InvRef and leaves it on top of stack
2139 // Not callable from Lua; all references are created on the C side.
2140 static void create(lua_State *L, const InventoryLocation &loc)
2142 InvRef *o = new InvRef(loc);
2143 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2144 luaL_getmetatable(L, className);
2145 lua_setmetatable(L, -2);
2147 static void createPlayer(lua_State *L, Player *player)
2149 InventoryLocation loc;
2150 loc.setPlayer(player->getName());
2153 static void createNodeMeta(lua_State *L, v3s16 p)
2155 InventoryLocation loc;
2160 static void Register(lua_State *L)
2163 int methodtable = lua_gettop(L);
2164 luaL_newmetatable(L, className);
2165 int metatable = lua_gettop(L);
2167 lua_pushliteral(L, "__metatable");
2168 lua_pushvalue(L, methodtable);
2169 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2171 lua_pushliteral(L, "__index");
2172 lua_pushvalue(L, methodtable);
2173 lua_settable(L, metatable);
2175 lua_pushliteral(L, "__gc");
2176 lua_pushcfunction(L, gc_object);
2177 lua_settable(L, metatable);
2179 lua_pop(L, 1); // drop metatable
2181 luaL_openlib(L, 0, methods, 0); // fill methodtable
2182 lua_pop(L, 1); // drop methodtable
2184 // Cannot be created from Lua
2185 //lua_register(L, className, create_object);
2188 const char InvRef::className[] = "InvRef";
2189 const luaL_reg InvRef::methods[] = {
2190 method(InvRef, is_empty),
2191 method(InvRef, get_size),
2192 method(InvRef, set_size),
2193 method(InvRef, get_width),
2194 method(InvRef, set_width),
2195 method(InvRef, get_stack),
2196 method(InvRef, set_stack),
2197 method(InvRef, get_list),
2198 method(InvRef, set_list),
2199 method(InvRef, add_item),
2200 method(InvRef, room_for_item),
2201 method(InvRef, contains_item),
2202 method(InvRef, remove_item),
2203 method(InvRef, get_location),
2215 ServerEnvironment *m_env;
2217 static const char className[];
2218 static const luaL_reg methods[];
2220 static NodeMetaRef *checkobject(lua_State *L, int narg)
2222 luaL_checktype(L, narg, LUA_TUSERDATA);
2223 void *ud = luaL_checkudata(L, narg, className);
2224 if(!ud) luaL_typerror(L, narg, className);
2225 return *(NodeMetaRef**)ud; // unbox pointer
2228 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2230 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2231 if(meta == NULL && auto_create)
2233 meta = new NodeMetadata(ref->m_env->getGameDef());
2234 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2239 static void reportMetadataChange(NodeMetaRef *ref)
2241 // NOTE: This same code is in rollback_interface.cpp
2242 // Inform other things that the metadata has changed
2243 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2245 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2247 ref->m_env->getMap().dispatchEvent(&event);
2248 // Set the block to be saved
2249 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2251 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2252 "NodeMetaRef::reportMetadataChange");
2255 // Exported functions
2257 // garbage collector
2258 static int gc_object(lua_State *L) {
2259 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2264 // get_string(self, name)
2265 static int l_get_string(lua_State *L)
2267 NodeMetaRef *ref = checkobject(L, 1);
2268 std::string name = luaL_checkstring(L, 2);
2270 NodeMetadata *meta = getmeta(ref, false);
2272 lua_pushlstring(L, "", 0);
2275 std::string str = meta->getString(name);
2276 lua_pushlstring(L, str.c_str(), str.size());
2280 // set_string(self, name, var)
2281 static int l_set_string(lua_State *L)
2283 NodeMetaRef *ref = checkobject(L, 1);
2284 std::string name = luaL_checkstring(L, 2);
2286 const char *s = lua_tolstring(L, 3, &len);
2287 std::string str(s, len);
2289 NodeMetadata *meta = getmeta(ref, !str.empty());
2290 if(meta == NULL || str == meta->getString(name))
2292 meta->setString(name, str);
2293 reportMetadataChange(ref);
2297 // get_int(self, name)
2298 static int l_get_int(lua_State *L)
2300 NodeMetaRef *ref = checkobject(L, 1);
2301 std::string name = lua_tostring(L, 2);
2303 NodeMetadata *meta = getmeta(ref, false);
2305 lua_pushnumber(L, 0);
2308 std::string str = meta->getString(name);
2309 lua_pushnumber(L, stoi(str));
2313 // set_int(self, name, var)
2314 static int l_set_int(lua_State *L)
2316 NodeMetaRef *ref = checkobject(L, 1);
2317 std::string name = lua_tostring(L, 2);
2318 int a = lua_tointeger(L, 3);
2319 std::string str = itos(a);
2321 NodeMetadata *meta = getmeta(ref, true);
2322 if(meta == NULL || str == meta->getString(name))
2324 meta->setString(name, str);
2325 reportMetadataChange(ref);
2329 // get_float(self, name)
2330 static int l_get_float(lua_State *L)
2332 NodeMetaRef *ref = checkobject(L, 1);
2333 std::string name = lua_tostring(L, 2);
2335 NodeMetadata *meta = getmeta(ref, false);
2337 lua_pushnumber(L, 0);
2340 std::string str = meta->getString(name);
2341 lua_pushnumber(L, stof(str));
2345 // set_float(self, name, var)
2346 static int l_set_float(lua_State *L)
2348 NodeMetaRef *ref = checkobject(L, 1);
2349 std::string name = lua_tostring(L, 2);
2350 float a = lua_tonumber(L, 3);
2351 std::string str = ftos(a);
2353 NodeMetadata *meta = getmeta(ref, true);
2354 if(meta == NULL || str == meta->getString(name))
2356 meta->setString(name, str);
2357 reportMetadataChange(ref);
2361 // get_inventory(self)
2362 static int l_get_inventory(lua_State *L)
2364 NodeMetaRef *ref = checkobject(L, 1);
2365 getmeta(ref, true); // try to ensure the metadata exists
2366 InvRef::createNodeMeta(L, ref->m_p);
2371 static int l_to_table(lua_State *L)
2373 NodeMetaRef *ref = checkobject(L, 1);
2375 NodeMetadata *meta = getmeta(ref, true);
2384 std::map<std::string, std::string> fields = meta->getStrings();
2385 for(std::map<std::string, std::string>::const_iterator
2386 i = fields.begin(); i != fields.end(); i++){
2387 const std::string &name = i->first;
2388 const std::string &value = i->second;
2389 lua_pushlstring(L, name.c_str(), name.size());
2390 lua_pushlstring(L, value.c_str(), value.size());
2391 lua_settable(L, -3);
2394 lua_setfield(L, -2, "fields");
2397 Inventory *inv = meta->getInventory();
2399 std::vector<const InventoryList*> lists = inv->getLists();
2400 for(std::vector<const InventoryList*>::const_iterator
2401 i = lists.begin(); i != lists.end(); i++){
2402 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2403 lua_setfield(L, -2, (*i)->getName().c_str());
2406 lua_setfield(L, -2, "inventory");
2410 // from_table(self, table)
2411 static int l_from_table(lua_State *L)
2413 NodeMetaRef *ref = checkobject(L, 1);
2416 if(lua_isnil(L, base)){
2418 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2419 lua_pushboolean(L, true);
2423 // Has metadata; clear old one first
2424 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2425 // Create new metadata
2426 NodeMetadata *meta = getmeta(ref, true);
2428 lua_getfield(L, base, "fields");
2429 int fieldstable = lua_gettop(L);
2431 while(lua_next(L, fieldstable) != 0){
2432 // key at index -2 and value at index -1
2433 std::string name = lua_tostring(L, -2);
2435 const char *cs = lua_tolstring(L, -1, &cl);
2436 std::string value(cs, cl);
2437 meta->setString(name, value);
2438 lua_pop(L, 1); // removes value, keeps key for next iteration
2441 Inventory *inv = meta->getInventory();
2442 lua_getfield(L, base, "inventory");
2443 int inventorytable = lua_gettop(L);
2445 while(lua_next(L, inventorytable) != 0){
2446 // key at index -2 and value at index -1
2447 std::string name = lua_tostring(L, -2);
2448 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2449 lua_pop(L, 1); // removes value, keeps key for next iteration
2451 reportMetadataChange(ref);
2452 lua_pushboolean(L, true);
2457 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2467 // Creates an NodeMetaRef and leaves it on top of stack
2468 // Not callable from Lua; all references are created on the C side.
2469 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2471 NodeMetaRef *o = new NodeMetaRef(p, env);
2472 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2473 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2474 luaL_getmetatable(L, className);
2475 lua_setmetatable(L, -2);
2478 static void Register(lua_State *L)
2481 int methodtable = lua_gettop(L);
2482 luaL_newmetatable(L, className);
2483 int metatable = lua_gettop(L);
2485 lua_pushliteral(L, "__metatable");
2486 lua_pushvalue(L, methodtable);
2487 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2489 lua_pushliteral(L, "__index");
2490 lua_pushvalue(L, methodtable);
2491 lua_settable(L, metatable);
2493 lua_pushliteral(L, "__gc");
2494 lua_pushcfunction(L, gc_object);
2495 lua_settable(L, metatable);
2497 lua_pop(L, 1); // drop metatable
2499 luaL_openlib(L, 0, methods, 0); // fill methodtable
2500 lua_pop(L, 1); // drop methodtable
2502 // Cannot be created from Lua
2503 //lua_register(L, className, create_object);
2506 const char NodeMetaRef::className[] = "NodeMetaRef";
2507 const luaL_reg NodeMetaRef::methods[] = {
2508 method(NodeMetaRef, get_string),
2509 method(NodeMetaRef, set_string),
2510 method(NodeMetaRef, get_int),
2511 method(NodeMetaRef, set_int),
2512 method(NodeMetaRef, get_float),
2513 method(NodeMetaRef, set_float),
2514 method(NodeMetaRef, get_inventory),
2515 method(NodeMetaRef, to_table),
2516 method(NodeMetaRef, from_table),
2527 ServerActiveObject *m_object;
2529 static const char className[];
2530 static const luaL_reg methods[];
2532 static ObjectRef *checkobject(lua_State *L, int narg)
2534 luaL_checktype(L, narg, LUA_TUSERDATA);
2535 void *ud = luaL_checkudata(L, narg, className);
2536 if(!ud) luaL_typerror(L, narg, className);
2537 return *(ObjectRef**)ud; // unbox pointer
2540 static ServerActiveObject* getobject(ObjectRef *ref)
2542 ServerActiveObject *co = ref->m_object;
2546 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2548 ServerActiveObject *obj = getobject(ref);
2551 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2553 return (LuaEntitySAO*)obj;
2556 static PlayerSAO* getplayersao(ObjectRef *ref)
2558 ServerActiveObject *obj = getobject(ref);
2561 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2563 return (PlayerSAO*)obj;
2566 static Player* getplayer(ObjectRef *ref)
2568 PlayerSAO *playersao = getplayersao(ref);
2569 if(playersao == NULL)
2571 return playersao->getPlayer();
2574 // Exported functions
2576 // garbage collector
2577 static int gc_object(lua_State *L) {
2578 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2579 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2585 static int l_remove(lua_State *L)
2587 ObjectRef *ref = checkobject(L, 1);
2588 ServerActiveObject *co = getobject(ref);
2589 if(co == NULL) return 0;
2590 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2591 co->m_removed = true;
2596 // returns: {x=num, y=num, z=num}
2597 static int l_getpos(lua_State *L)
2599 ObjectRef *ref = checkobject(L, 1);
2600 ServerActiveObject *co = getobject(ref);
2601 if(co == NULL) return 0;
2602 v3f pos = co->getBasePosition() / BS;
2604 lua_pushnumber(L, pos.X);
2605 lua_setfield(L, -2, "x");
2606 lua_pushnumber(L, pos.Y);
2607 lua_setfield(L, -2, "y");
2608 lua_pushnumber(L, pos.Z);
2609 lua_setfield(L, -2, "z");
2613 // setpos(self, pos)
2614 static int l_setpos(lua_State *L)
2616 ObjectRef *ref = checkobject(L, 1);
2617 //LuaEntitySAO *co = getluaobject(ref);
2618 ServerActiveObject *co = getobject(ref);
2619 if(co == NULL) return 0;
2621 v3f pos = checkFloatPos(L, 2);
2627 // moveto(self, pos, continuous=false)
2628 static int l_moveto(lua_State *L)
2630 ObjectRef *ref = checkobject(L, 1);
2631 //LuaEntitySAO *co = getluaobject(ref);
2632 ServerActiveObject *co = getobject(ref);
2633 if(co == NULL) return 0;
2635 v3f pos = checkFloatPos(L, 2);
2637 bool continuous = lua_toboolean(L, 3);
2639 co->moveTo(pos, continuous);
2643 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2644 static int l_punch(lua_State *L)
2646 ObjectRef *ref = checkobject(L, 1);
2647 ObjectRef *puncher_ref = checkobject(L, 2);
2648 ServerActiveObject *co = getobject(ref);
2649 ServerActiveObject *puncher = getobject(puncher_ref);
2650 if(co == NULL) return 0;
2651 if(puncher == NULL) return 0;
2653 if(lua_type(L, 5) != LUA_TTABLE)
2654 dir = co->getBasePosition() - puncher->getBasePosition();
2656 dir = read_v3f(L, 5);
2657 float time_from_last_punch = 1000000;
2658 if(lua_isnumber(L, 3))
2659 time_from_last_punch = lua_tonumber(L, 3);
2660 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2663 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2667 // right_click(self, clicker); clicker = an another ObjectRef
2668 static int l_right_click(lua_State *L)
2670 ObjectRef *ref = checkobject(L, 1);
2671 ObjectRef *ref2 = checkobject(L, 2);
2672 ServerActiveObject *co = getobject(ref);
2673 ServerActiveObject *co2 = getobject(ref2);
2674 if(co == NULL) return 0;
2675 if(co2 == NULL) return 0;
2677 co->rightClick(co2);
2682 // hp = number of hitpoints (2 * number of hearts)
2684 static int l_set_hp(lua_State *L)
2686 ObjectRef *ref = checkobject(L, 1);
2687 luaL_checknumber(L, 2);
2688 ServerActiveObject *co = getobject(ref);
2689 if(co == NULL) return 0;
2690 int hp = lua_tonumber(L, 2);
2691 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2692 <<" hp="<<hp<<std::endl;*/
2700 // returns: number of hitpoints (2 * number of hearts)
2701 // 0 if not applicable to this type of object
2702 static int l_get_hp(lua_State *L)
2704 ObjectRef *ref = checkobject(L, 1);
2705 ServerActiveObject *co = getobject(ref);
2708 lua_pushnumber(L, 1);
2711 int hp = co->getHP();
2712 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2713 <<" hp="<<hp<<std::endl;*/
2715 lua_pushnumber(L, hp);
2719 // get_inventory(self)
2720 static int l_get_inventory(lua_State *L)
2722 ObjectRef *ref = checkobject(L, 1);
2723 ServerActiveObject *co = getobject(ref);
2724 if(co == NULL) return 0;
2726 InventoryLocation loc = co->getInventoryLocation();
2727 if(get_server(L)->getInventory(loc) != NULL)
2728 InvRef::create(L, loc);
2730 lua_pushnil(L); // An object may have no inventory (nil)
2734 // get_wield_list(self)
2735 static int l_get_wield_list(lua_State *L)
2737 ObjectRef *ref = checkobject(L, 1);
2738 ServerActiveObject *co = getobject(ref);
2739 if(co == NULL) return 0;
2741 lua_pushstring(L, co->getWieldList().c_str());
2745 // get_wield_index(self)
2746 static int l_get_wield_index(lua_State *L)
2748 ObjectRef *ref = checkobject(L, 1);
2749 ServerActiveObject *co = getobject(ref);
2750 if(co == NULL) return 0;
2752 lua_pushinteger(L, co->getWieldIndex() + 1);
2756 // get_wielded_item(self)
2757 static int l_get_wielded_item(lua_State *L)
2759 ObjectRef *ref = checkobject(L, 1);
2760 ServerActiveObject *co = getobject(ref);
2763 LuaItemStack::create(L, ItemStack());
2767 LuaItemStack::create(L, co->getWieldedItem());
2771 // set_wielded_item(self, itemstack or itemstring or table or nil)
2772 static int l_set_wielded_item(lua_State *L)
2774 ObjectRef *ref = checkobject(L, 1);
2775 ServerActiveObject *co = getobject(ref);
2776 if(co == NULL) return 0;
2778 ItemStack item = read_item(L, 2);
2779 bool success = co->setWieldedItem(item);
2780 lua_pushboolean(L, success);
2784 // set_armor_groups(self, groups)
2785 static int l_set_armor_groups(lua_State *L)
2787 ObjectRef *ref = checkobject(L, 1);
2788 ServerActiveObject *co = getobject(ref);
2789 if(co == NULL) return 0;
2791 ItemGroupList groups;
2792 read_groups(L, 2, groups);
2793 co->setArmorGroups(groups);
2797 // set_animation(self, frame_range, frame_speed, frame_blend)
2798 static int l_set_animation(lua_State *L)
2800 ObjectRef *ref = checkobject(L, 1);
2801 ServerActiveObject *co = getobject(ref);
2802 if(co == NULL) return 0;
2804 v2f frames = v2f(1, 1);
2805 if(!lua_isnil(L, 2))
2806 frames = read_v2f(L, 2);
2807 float frame_speed = 15;
2808 if(!lua_isnil(L, 3))
2809 frame_speed = lua_tonumber(L, 3);
2810 float frame_blend = 0;
2811 if(!lua_isnil(L, 4))
2812 frame_blend = lua_tonumber(L, 4);
2813 co->setAnimation(frames, frame_speed, frame_blend);
2817 // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2818 static int l_set_bone_position(lua_State *L)
2820 ObjectRef *ref = checkobject(L, 1);
2821 ServerActiveObject *co = getobject(ref);
2822 if(co == NULL) return 0;
2824 std::string bone = "";
2825 if(!lua_isnil(L, 2))
2826 bone = lua_tostring(L, 2);
2827 v3f position = v3f(0, 0, 0);
2828 if(!lua_isnil(L, 3))
2829 position = read_v3f(L, 3);
2830 v3f rotation = v3f(0, 0, 0);
2831 if(!lua_isnil(L, 4))
2832 rotation = read_v3f(L, 4);
2833 co->setBonePosition(bone, position, rotation);
2837 // set_attach(self, parent, bone, position, rotation)
2838 static int l_set_attach(lua_State *L)
2840 ObjectRef *ref = checkobject(L, 1);
2841 ObjectRef *parent_ref = checkobject(L, 2);
2842 ServerActiveObject *co = getobject(ref);
2843 ServerActiveObject *parent = getobject(parent_ref);
2844 if(co == NULL) return 0;
2845 if(parent == NULL) return 0;
2847 std::string bone = "";
2848 if(!lua_isnil(L, 3))
2849 bone = lua_tostring(L, 3);
2850 v3f position = v3f(0, 0, 0);
2851 if(!lua_isnil(L, 4))
2852 position = read_v3f(L, 4);
2853 v3f rotation = v3f(0, 0, 0);
2854 if(!lua_isnil(L, 5))
2855 rotation = read_v3f(L, 5);
2856 co->setAttachment(parent->getId(), bone, position, rotation);
2861 static int l_set_detach(lua_State *L)
2863 ObjectRef *ref = checkobject(L, 1);
2864 ServerActiveObject *co = getobject(ref);
2865 if(co == NULL) return 0;
2867 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2871 // set_properties(self, properties)
2872 static int l_set_properties(lua_State *L)
2874 ObjectRef *ref = checkobject(L, 1);
2875 ServerActiveObject *co = getobject(ref);
2876 if(co == NULL) return 0;
2877 ObjectProperties *prop = co->accessObjectProperties();
2880 read_object_properties(L, 2, prop);
2881 co->notifyObjectPropertiesModified();
2885 /* LuaEntitySAO-only */
2887 // setvelocity(self, {x=num, y=num, z=num})
2888 static int l_setvelocity(lua_State *L)
2890 ObjectRef *ref = checkobject(L, 1);
2891 LuaEntitySAO *co = getluaobject(ref);
2892 if(co == NULL) return 0;
2893 v3f pos = checkFloatPos(L, 2);
2895 co->setVelocity(pos);
2899 // getvelocity(self)
2900 static int l_getvelocity(lua_State *L)
2902 ObjectRef *ref = checkobject(L, 1);
2903 LuaEntitySAO *co = getluaobject(ref);
2904 if(co == NULL) return 0;
2906 v3f v = co->getVelocity();
2911 // setacceleration(self, {x=num, y=num, z=num})
2912 static int l_setacceleration(lua_State *L)
2914 ObjectRef *ref = checkobject(L, 1);
2915 LuaEntitySAO *co = getluaobject(ref);
2916 if(co == NULL) return 0;
2918 v3f pos = checkFloatPos(L, 2);
2920 co->setAcceleration(pos);
2924 // getacceleration(self)
2925 static int l_getacceleration(lua_State *L)
2927 ObjectRef *ref = checkobject(L, 1);
2928 LuaEntitySAO *co = getluaobject(ref);
2929 if(co == NULL) return 0;
2931 v3f v = co->getAcceleration();
2936 // setyaw(self, radians)
2937 static int l_setyaw(lua_State *L)
2939 ObjectRef *ref = checkobject(L, 1);
2940 LuaEntitySAO *co = getluaobject(ref);
2941 if(co == NULL) return 0;
2942 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2949 static int l_getyaw(lua_State *L)
2951 ObjectRef *ref = checkobject(L, 1);
2952 LuaEntitySAO *co = getluaobject(ref);
2953 if(co == NULL) return 0;
2955 float yaw = co->getYaw() * core::DEGTORAD;
2956 lua_pushnumber(L, yaw);
2960 // settexturemod(self, mod)
2961 static int l_settexturemod(lua_State *L)
2963 ObjectRef *ref = checkobject(L, 1);
2964 LuaEntitySAO *co = getluaobject(ref);
2965 if(co == NULL) return 0;
2967 std::string mod = luaL_checkstring(L, 2);
2968 co->setTextureMod(mod);
2972 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2973 // select_horiz_by_yawpitch=false)
2974 static int l_setsprite(lua_State *L)
2976 ObjectRef *ref = checkobject(L, 1);
2977 LuaEntitySAO *co = getluaobject(ref);
2978 if(co == NULL) return 0;
2981 if(!lua_isnil(L, 2))
2982 p = read_v2s16(L, 2);
2984 if(!lua_isnil(L, 3))
2985 num_frames = lua_tonumber(L, 3);
2986 float framelength = 0.2;
2987 if(!lua_isnil(L, 4))
2988 framelength = lua_tonumber(L, 4);
2989 bool select_horiz_by_yawpitch = false;
2990 if(!lua_isnil(L, 5))
2991 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2992 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2997 // get_entity_name(self)
2998 static int l_get_entity_name(lua_State *L)
3000 ObjectRef *ref = checkobject(L, 1);
3001 LuaEntitySAO *co = getluaobject(ref);
3002 if(co == NULL) return 0;
3004 std::string name = co->getName();
3005 lua_pushstring(L, name.c_str());
3009 // get_luaentity(self)
3010 static int l_get_luaentity(lua_State *L)
3012 ObjectRef *ref = checkobject(L, 1);
3013 LuaEntitySAO *co = getluaobject(ref);
3014 if(co == NULL) return 0;
3016 luaentity_get(L, co->getId());
3023 static int l_is_player(lua_State *L)
3025 ObjectRef *ref = checkobject(L, 1);
3026 Player *player = getplayer(ref);
3027 lua_pushboolean(L, (player != NULL));
3031 // get_player_name(self)
3032 static int l_get_player_name(lua_State *L)
3034 ObjectRef *ref = checkobject(L, 1);
3035 Player *player = getplayer(ref);
3037 lua_pushlstring(L, "", 0);
3041 lua_pushstring(L, player->getName());
3045 // get_look_dir(self)
3046 static int l_get_look_dir(lua_State *L)
3048 ObjectRef *ref = checkobject(L, 1);
3049 Player *player = getplayer(ref);
3050 if(player == NULL) return 0;
3052 float pitch = player->getRadPitch();
3053 float yaw = player->getRadYaw();
3054 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
3059 // get_look_pitch(self)
3060 static int l_get_look_pitch(lua_State *L)
3062 ObjectRef *ref = checkobject(L, 1);
3063 Player *player = getplayer(ref);
3064 if(player == NULL) return 0;
3066 lua_pushnumber(L, player->getRadPitch());
3070 // get_look_yaw(self)
3071 static int l_get_look_yaw(lua_State *L)
3073 ObjectRef *ref = checkobject(L, 1);
3074 Player *player = getplayer(ref);
3075 if(player == NULL) return 0;
3077 lua_pushnumber(L, player->getRadYaw());
3081 // set_inventory_formspec(self, formspec)
3082 static int l_set_inventory_formspec(lua_State *L)
3084 ObjectRef *ref = checkobject(L, 1);
3085 Player *player = getplayer(ref);
3086 if(player == NULL) return 0;
3087 std::string formspec = luaL_checkstring(L, 2);
3089 player->inventory_formspec = formspec;
3090 get_server(L)->reportInventoryFormspecModified(player->getName());
3091 lua_pushboolean(L, true);
3095 // get_inventory_formspec(self) -> formspec
3096 static int l_get_inventory_formspec(lua_State *L)
3098 ObjectRef *ref = checkobject(L, 1);
3099 Player *player = getplayer(ref);
3100 if(player == NULL) return 0;
3102 std::string formspec = player->inventory_formspec;
3103 lua_pushlstring(L, formspec.c_str(), formspec.size());
3107 // get_player_control(self)
3108 static int l_get_player_control(lua_State *L)
3110 ObjectRef *ref = checkobject(L, 1);
3111 Player *player = getplayer(ref);
3113 lua_pushlstring(L, "", 0);
3117 PlayerControl control = player->getPlayerControl();
3119 lua_pushboolean(L, control.up);
3120 lua_setfield(L, -2, "up");
3121 lua_pushboolean(L, control.down);
3122 lua_setfield(L, -2, "down");
3123 lua_pushboolean(L, control.left);
3124 lua_setfield(L, -2, "left");
3125 lua_pushboolean(L, control.right);
3126 lua_setfield(L, -2, "right");
3127 lua_pushboolean(L, control.jump);
3128 lua_setfield(L, -2, "jump");
3129 lua_pushboolean(L, control.aux1);
3130 lua_setfield(L, -2, "aux1");
3131 lua_pushboolean(L, control.sneak);
3132 lua_setfield(L, -2, "sneak");
3133 lua_pushboolean(L, control.LMB);
3134 lua_setfield(L, -2, "LMB");
3135 lua_pushboolean(L, control.RMB);
3136 lua_setfield(L, -2, "RMB");
3140 // get_player_control_bits(self)
3141 static int l_get_player_control_bits(lua_State *L)
3143 ObjectRef *ref = checkobject(L, 1);
3144 Player *player = getplayer(ref);
3146 lua_pushlstring(L, "", 0);
3150 lua_pushnumber(L, player->keyPressed);
3155 ObjectRef(ServerActiveObject *object):
3158 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3164 infostream<<"ObjectRef destructing for id="
3165 <<m_object->getId()<<std::endl;
3167 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3170 // Creates an ObjectRef and leaves it on top of stack
3171 // Not callable from Lua; all references are created on the C side.
3172 static void create(lua_State *L, ServerActiveObject *object)
3174 ObjectRef *o = new ObjectRef(object);
3175 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3176 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3177 luaL_getmetatable(L, className);
3178 lua_setmetatable(L, -2);
3181 static void set_null(lua_State *L)
3183 ObjectRef *o = checkobject(L, -1);
3187 static void Register(lua_State *L)
3190 int methodtable = lua_gettop(L);
3191 luaL_newmetatable(L, className);
3192 int metatable = lua_gettop(L);
3194 lua_pushliteral(L, "__metatable");
3195 lua_pushvalue(L, methodtable);
3196 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3198 lua_pushliteral(L, "__index");
3199 lua_pushvalue(L, methodtable);
3200 lua_settable(L, metatable);
3202 lua_pushliteral(L, "__gc");
3203 lua_pushcfunction(L, gc_object);
3204 lua_settable(L, metatable);
3206 lua_pop(L, 1); // drop metatable
3208 luaL_openlib(L, 0, methods, 0); // fill methodtable
3209 lua_pop(L, 1); // drop methodtable
3211 // Cannot be created from Lua
3212 //lua_register(L, className, create_object);
3215 const char ObjectRef::className[] = "ObjectRef";
3216 const luaL_reg ObjectRef::methods[] = {
3217 // ServerActiveObject
3218 method(ObjectRef, remove),
3219 method(ObjectRef, getpos),
3220 method(ObjectRef, setpos),
3221 method(ObjectRef, moveto),
3222 method(ObjectRef, punch),
3223 method(ObjectRef, right_click),
3224 method(ObjectRef, set_hp),
3225 method(ObjectRef, get_hp),
3226 method(ObjectRef, get_inventory),
3227 method(ObjectRef, get_wield_list),
3228 method(ObjectRef, get_wield_index),
3229 method(ObjectRef, get_wielded_item),
3230 method(ObjectRef, set_wielded_item),
3231 method(ObjectRef, set_armor_groups),
3232 method(ObjectRef, set_animation),
3233 method(ObjectRef, set_bone_position),
3234 method(ObjectRef, set_attach),
3235 method(ObjectRef, set_detach),
3236 method(ObjectRef, set_properties),
3237 // LuaEntitySAO-only
3238 method(ObjectRef, setvelocity),
3239 method(ObjectRef, getvelocity),
3240 method(ObjectRef, setacceleration),
3241 method(ObjectRef, getacceleration),
3242 method(ObjectRef, setyaw),
3243 method(ObjectRef, getyaw),
3244 method(ObjectRef, settexturemod),
3245 method(ObjectRef, setsprite),
3246 method(ObjectRef, get_entity_name),
3247 method(ObjectRef, get_luaentity),
3249 method(ObjectRef, is_player),
3250 method(ObjectRef, get_player_name),
3251 method(ObjectRef, get_look_dir),
3252 method(ObjectRef, get_look_pitch),
3253 method(ObjectRef, get_look_yaw),
3254 method(ObjectRef, set_inventory_formspec),
3255 method(ObjectRef, get_inventory_formspec),
3256 method(ObjectRef, get_player_control),
3257 method(ObjectRef, get_player_control_bits),
3261 // Creates a new anonymous reference if cobj=NULL or id=0
3262 static void objectref_get_or_create(lua_State *L,
3263 ServerActiveObject *cobj)
3265 if(cobj == NULL || cobj->getId() == 0){
3266 ObjectRef::create(L, cobj);
3268 objectref_get(L, cobj->getId());
3272 class LuaPerlinNoise
3279 static const char className[];
3280 static const luaL_reg methods[];
3282 // Exported functions
3284 // garbage collector
3285 static int gc_object(lua_State *L)
3287 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3292 static int l_get2d(lua_State *L)
3294 LuaPerlinNoise *o = checkobject(L, 1);
3295 v2f pos2d = read_v2f(L,2);
3296 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3297 lua_pushnumber(L, val);
3300 static int l_get3d(lua_State *L)
3302 LuaPerlinNoise *o = checkobject(L, 1);
3303 v3f pos3d = read_v3f(L,2);
3304 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3305 lua_pushnumber(L, val);
3310 LuaPerlinNoise(int a_seed, int a_octaves, float a_persistence,
3314 persistence(a_persistence),
3323 // LuaPerlinNoise(seed, octaves, persistence, scale)
3324 // Creates an LuaPerlinNoise and leaves it on top of stack
3325 static int create_object(lua_State *L)
3327 int seed = luaL_checkint(L, 1);
3328 int octaves = luaL_checkint(L, 2);
3329 float persistence = luaL_checknumber(L, 3);
3330 float scale = luaL_checknumber(L, 4);
3331 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3332 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3333 luaL_getmetatable(L, className);
3334 lua_setmetatable(L, -2);
3338 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3340 luaL_checktype(L, narg, LUA_TUSERDATA);
3341 void *ud = luaL_checkudata(L, narg, className);
3342 if(!ud) luaL_typerror(L, narg, className);
3343 return *(LuaPerlinNoise**)ud; // unbox pointer
3346 static void Register(lua_State *L)
3349 int methodtable = lua_gettop(L);
3350 luaL_newmetatable(L, className);
3351 int metatable = lua_gettop(L);
3353 lua_pushliteral(L, "__metatable");
3354 lua_pushvalue(L, methodtable);
3355 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3357 lua_pushliteral(L, "__index");
3358 lua_pushvalue(L, methodtable);
3359 lua_settable(L, metatable);
3361 lua_pushliteral(L, "__gc");
3362 lua_pushcfunction(L, gc_object);
3363 lua_settable(L, metatable);
3365 lua_pop(L, 1); // drop metatable
3367 luaL_openlib(L, 0, methods, 0); // fill methodtable
3368 lua_pop(L, 1); // drop methodtable
3370 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3371 lua_register(L, className, create_object);
3374 const char LuaPerlinNoise::className[] = "PerlinNoise";
3375 const luaL_reg LuaPerlinNoise::methods[] = {
3376 method(LuaPerlinNoise, get2d),
3377 method(LuaPerlinNoise, get3d),
3384 class LuaPerlinNoiseMap
3388 static const char className[];
3389 static const luaL_reg methods[];
3391 static int gc_object(lua_State *L)
3393 LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1));
3398 static int l_get2dMap(lua_State *L)
3402 LuaPerlinNoiseMap *o = checkobject(L, 1);
3403 v2f p = read_v2f(L, 2);
3405 Noise *n = o->noise;
3406 n->perlinMap2D(p.X, p.Y);
3409 for (int y = 0; y != n->sy; y++) {
3411 for (int x = 0; x != n->sx; x++) {
3412 float noiseval = n->np->offset + n->np->scale * n->result[i++];
3413 lua_pushnumber(L, noiseval);
3414 lua_rawseti(L, -2, x + 1);
3416 lua_rawseti(L, -2, y + 1);
3421 static int l_get3dMap(lua_State *L)
3425 LuaPerlinNoiseMap *o = checkobject(L, 1);
3426 v3f p = read_v3f(L, 2);
3428 Noise *n = o->noise;
3429 n->perlinMap3D(p.X, p.Y, p.Z);
3432 for (int z = 0; z != n->sz; z++) {
3434 for (int y = 0; y != n->sy; y++) {
3436 for (int x = 0; x != n->sx; x++) {
3437 lua_pushnumber(L, n->np->offset + n->np->scale * n->result[i++]);
3438 lua_rawseti(L, -2, x + 1);
3440 lua_rawseti(L, -2, y + 1);
3442 lua_rawseti(L, -2, z + 1);
3448 LuaPerlinNoiseMap(NoiseParams *np, int seed, v3s16 size) {
3449 noise = new Noise(np, seed, size.X, size.Y, size.Z);
3452 ~LuaPerlinNoiseMap()
3458 // LuaPerlinNoiseMap(np, size)
3459 // Creates an LuaPerlinNoiseMap and leaves it on top of stack
3460 static int create_object(lua_State *L)
3462 NoiseParams *np = read_noiseparams(L, 1);
3465 v3s16 size = read_v3s16(L, 2);
3467 LuaPerlinNoiseMap *o = new LuaPerlinNoiseMap(np, 0, size);
3468 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3469 luaL_getmetatable(L, className);
3470 lua_setmetatable(L, -2);
3474 static LuaPerlinNoiseMap *checkobject(lua_State *L, int narg)
3476 luaL_checktype(L, narg, LUA_TUSERDATA);
3478 void *ud = luaL_checkudata(L, narg, className);
3480 luaL_typerror(L, narg, className);
3482 return *(LuaPerlinNoiseMap **)ud; // unbox pointer
3485 static void Register(lua_State *L)
3488 int methodtable = lua_gettop(L);
3489 luaL_newmetatable(L, className);
3490 int metatable = lua_gettop(L);
3492 lua_pushliteral(L, "__metatable");
3493 lua_pushvalue(L, methodtable);
3494 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3496 lua_pushliteral(L, "__index");
3497 lua_pushvalue(L, methodtable);
3498 lua_settable(L, metatable);
3500 lua_pushliteral(L, "__gc");
3501 lua_pushcfunction(L, gc_object);
3502 lua_settable(L, metatable);
3504 lua_pop(L, 1); // drop metatable
3506 luaL_openlib(L, 0, methods, 0); // fill methodtable
3507 lua_pop(L, 1); // drop methodtable
3509 // Can be created from Lua (PerlinNoiseMap(np, size)
3510 lua_register(L, className, create_object);
3513 const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap";
3514 const luaL_reg LuaPerlinNoiseMap::methods[] = {
3515 method(LuaPerlinNoiseMap, get2dMap),
3516 method(LuaPerlinNoiseMap, get3dMap),
3528 ServerEnvironment *m_env;
3530 static const char className[];
3531 static const luaL_reg methods[];
3533 static int gc_object(lua_State *L) {
3534 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3539 static NodeTimerRef *checkobject(lua_State *L, int narg)
3541 luaL_checktype(L, narg, LUA_TUSERDATA);
3542 void *ud = luaL_checkudata(L, narg, className);
3543 if(!ud) luaL_typerror(L, narg, className);
3544 return *(NodeTimerRef**)ud; // unbox pointer
3547 static int l_set(lua_State *L)
3549 NodeTimerRef *o = checkobject(L, 1);
3550 ServerEnvironment *env = o->m_env;
3551 if(env == NULL) return 0;
3552 f32 t = luaL_checknumber(L,2);
3553 f32 e = luaL_checknumber(L,3);
3554 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3558 static int l_start(lua_State *L)
3560 NodeTimerRef *o = checkobject(L, 1);
3561 ServerEnvironment *env = o->m_env;
3562 if(env == NULL) return 0;
3563 f32 t = luaL_checknumber(L,2);
3564 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3568 static int l_stop(lua_State *L)
3570 NodeTimerRef *o = checkobject(L, 1);
3571 ServerEnvironment *env = o->m_env;
3572 if(env == NULL) return 0;
3573 env->getMap().removeNodeTimer(o->m_p);
3577 static int l_is_started(lua_State *L)
3579 NodeTimerRef *o = checkobject(L, 1);
3580 ServerEnvironment *env = o->m_env;
3581 if(env == NULL) return 0;
3583 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3584 lua_pushboolean(L,(t.timeout != 0));
3588 static int l_get_timeout(lua_State *L)
3590 NodeTimerRef *o = checkobject(L, 1);
3591 ServerEnvironment *env = o->m_env;
3592 if(env == NULL) return 0;
3594 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3595 lua_pushnumber(L,t.timeout);
3599 static int l_get_elapsed(lua_State *L)
3601 NodeTimerRef *o = checkobject(L, 1);
3602 ServerEnvironment *env = o->m_env;
3603 if(env == NULL) return 0;
3605 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3606 lua_pushnumber(L,t.elapsed);
3611 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3621 // Creates an NodeTimerRef and leaves it on top of stack
3622 // Not callable from Lua; all references are created on the C side.
3623 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3625 NodeTimerRef *o = new NodeTimerRef(p, env);
3626 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3627 luaL_getmetatable(L, className);
3628 lua_setmetatable(L, -2);
3631 static void set_null(lua_State *L)
3633 NodeTimerRef *o = checkobject(L, -1);
3637 static void Register(lua_State *L)
3640 int methodtable = lua_gettop(L);
3641 luaL_newmetatable(L, className);
3642 int metatable = lua_gettop(L);
3644 lua_pushliteral(L, "__metatable");
3645 lua_pushvalue(L, methodtable);
3646 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3648 lua_pushliteral(L, "__index");
3649 lua_pushvalue(L, methodtable);
3650 lua_settable(L, metatable);
3652 lua_pushliteral(L, "__gc");
3653 lua_pushcfunction(L, gc_object);
3654 lua_settable(L, metatable);
3656 lua_pop(L, 1); // drop metatable
3658 luaL_openlib(L, 0, methods, 0); // fill methodtable
3659 lua_pop(L, 1); // drop methodtable
3661 // Cannot be created from Lua
3662 //lua_register(L, className, create_object);
3665 const char NodeTimerRef::className[] = "NodeTimerRef";
3666 const luaL_reg NodeTimerRef::methods[] = {
3667 method(NodeTimerRef, start),
3668 method(NodeTimerRef, set),
3669 method(NodeTimerRef, stop),
3670 method(NodeTimerRef, is_started),
3671 method(NodeTimerRef, get_timeout),
3672 method(NodeTimerRef, get_elapsed),
3683 ServerEnvironment *m_env;
3685 static const char className[];
3686 static const luaL_reg methods[];
3688 static int gc_object(lua_State *L) {
3689 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3694 static EnvRef *checkobject(lua_State *L, int narg)
3696 luaL_checktype(L, narg, LUA_TUSERDATA);
3697 void *ud = luaL_checkudata(L, narg, className);
3698 if(!ud) luaL_typerror(L, narg, className);
3699 return *(EnvRef**)ud; // unbox pointer
3702 // Exported functions
3704 // EnvRef:set_node(pos, node)
3705 // pos = {x=num, y=num, z=num}
3706 static int l_set_node(lua_State *L)
3708 EnvRef *o = checkobject(L, 1);
3709 ServerEnvironment *env = o->m_env;
3710 if(env == NULL) return 0;
3711 INodeDefManager *ndef = env->getGameDef()->ndef();
3713 v3s16 pos = read_v3s16(L, 2);
3714 MapNode n = readnode(L, 3, ndef);
3716 bool succeeded = env->setNode(pos, n);
3717 lua_pushboolean(L, succeeded);
3721 static int l_add_node(lua_State *L)
3723 return l_set_node(L);
3726 // EnvRef:remove_node(pos)
3727 // pos = {x=num, y=num, z=num}
3728 static int l_remove_node(lua_State *L)
3730 EnvRef *o = checkobject(L, 1);
3731 ServerEnvironment *env = o->m_env;
3732 if(env == NULL) return 0;
3733 INodeDefManager *ndef = env->getGameDef()->ndef();
3735 v3s16 pos = read_v3s16(L, 2);
3737 bool succeeded = env->removeNode(pos);
3738 lua_pushboolean(L, succeeded);
3742 // EnvRef:get_node(pos)
3743 // pos = {x=num, y=num, z=num}
3744 static int l_get_node(lua_State *L)
3746 EnvRef *o = checkobject(L, 1);
3747 ServerEnvironment *env = o->m_env;
3748 if(env == NULL) return 0;
3750 v3s16 pos = read_v3s16(L, 2);
3752 MapNode n = env->getMap().getNodeNoEx(pos);
3754 pushnode(L, n, env->getGameDef()->ndef());
3758 // EnvRef:get_node_or_nil(pos)
3759 // pos = {x=num, y=num, z=num}
3760 static int l_get_node_or_nil(lua_State *L)
3762 EnvRef *o = checkobject(L, 1);
3763 ServerEnvironment *env = o->m_env;
3764 if(env == NULL) return 0;
3766 v3s16 pos = read_v3s16(L, 2);
3769 MapNode n = env->getMap().getNode(pos);
3771 pushnode(L, n, env->getGameDef()->ndef());
3773 } catch(InvalidPositionException &e)
3780 // EnvRef:get_node_light(pos, timeofday)
3781 // pos = {x=num, y=num, z=num}
3782 // timeofday: nil = current time, 0 = night, 0.5 = day
3783 static int l_get_node_light(lua_State *L)
3785 EnvRef *o = checkobject(L, 1);
3786 ServerEnvironment *env = o->m_env;
3787 if(env == NULL) return 0;
3789 v3s16 pos = read_v3s16(L, 2);
3790 u32 time_of_day = env->getTimeOfDay();
3791 if(lua_isnumber(L, 3))
3792 time_of_day = 24000.0 * lua_tonumber(L, 3);
3793 time_of_day %= 24000;
3794 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3795 MapNode n = env->getMap().getNodeNoEx(pos);
3797 MapNode n = env->getMap().getNode(pos);
3798 INodeDefManager *ndef = env->getGameDef()->ndef();
3799 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3801 } catch(InvalidPositionException &e)
3808 // EnvRef:place_node(pos, node)
3809 // pos = {x=num, y=num, z=num}
3810 static int l_place_node(lua_State *L)
3812 EnvRef *o = checkobject(L, 1);
3813 ServerEnvironment *env = o->m_env;
3814 if(env == NULL) return 0;
3815 v3s16 pos = read_v3s16(L, 2);
3816 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3818 // Don't attempt to load non-loaded area as of now
3819 MapNode n_old = env->getMap().getNodeNoEx(pos);
3820 if(n_old.getContent() == CONTENT_IGNORE){
3821 lua_pushboolean(L, false);
3824 // Create item to place
3825 INodeDefManager *ndef = get_server(L)->ndef();
3826 IItemDefManager *idef = get_server(L)->idef();
3827 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3828 // Make pointed position
3829 PointedThing pointed;
3830 pointed.type = POINTEDTHING_NODE;
3831 pointed.node_abovesurface = pos;
3832 pointed.node_undersurface = pos + v3s16(0,-1,0);
3833 // Place it with a NULL placer (appears in Lua as a non-functional
3835 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3836 lua_pushboolean(L, success);
3840 // EnvRef:dig_node(pos)
3841 // pos = {x=num, y=num, z=num}
3842 static int l_dig_node(lua_State *L)
3844 EnvRef *o = checkobject(L, 1);
3845 ServerEnvironment *env = o->m_env;
3846 if(env == NULL) return 0;
3847 v3s16 pos = read_v3s16(L, 2);
3849 // Don't attempt to load non-loaded area as of now
3850 MapNode n = env->getMap().getNodeNoEx(pos);
3851 if(n.getContent() == CONTENT_IGNORE){
3852 lua_pushboolean(L, false);
3855 // Dig it out with a NULL digger (appears in Lua as a
3856 // non-functional ObjectRef)
3857 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3858 lua_pushboolean(L, success);
3862 // EnvRef:punch_node(pos)
3863 // pos = {x=num, y=num, z=num}
3864 static int l_punch_node(lua_State *L)
3866 EnvRef *o = checkobject(L, 1);
3867 ServerEnvironment *env = o->m_env;
3868 if(env == NULL) return 0;
3869 v3s16 pos = read_v3s16(L, 2);
3871 // Don't attempt to load non-loaded area as of now
3872 MapNode n = env->getMap().getNodeNoEx(pos);
3873 if(n.getContent() == CONTENT_IGNORE){
3874 lua_pushboolean(L, false);
3877 // Punch it with a NULL puncher (appears in Lua as a non-functional
3879 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3880 lua_pushboolean(L, success);
3884 // EnvRef:get_meta(pos)
3885 static int l_get_meta(lua_State *L)
3887 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3888 EnvRef *o = checkobject(L, 1);
3889 ServerEnvironment *env = o->m_env;
3890 if(env == NULL) return 0;
3892 v3s16 p = read_v3s16(L, 2);
3893 NodeMetaRef::create(L, p, env);
3897 // EnvRef:get_node_timer(pos)
3898 static int l_get_node_timer(lua_State *L)
3900 EnvRef *o = checkobject(L, 1);
3901 ServerEnvironment *env = o->m_env;
3902 if(env == NULL) return 0;
3904 v3s16 p = read_v3s16(L, 2);
3905 NodeTimerRef::create(L, p, env);
3909 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3910 // pos = {x=num, y=num, z=num}
3911 static int l_add_entity(lua_State *L)
3913 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3914 EnvRef *o = checkobject(L, 1);
3915 ServerEnvironment *env = o->m_env;
3916 if(env == NULL) return 0;
3918 v3f pos = checkFloatPos(L, 2);
3920 const char *name = luaL_checkstring(L, 3);
3922 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3923 int objectid = env->addActiveObject(obj);
3924 // If failed to add, return nothing (reads as nil)
3928 objectref_get_or_create(L, obj);
3932 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3933 // pos = {x=num, y=num, z=num}
3934 static int l_add_item(lua_State *L)
3936 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3937 EnvRef *o = checkobject(L, 1);
3938 ServerEnvironment *env = o->m_env;
3939 if(env == NULL) return 0;
3941 v3f pos = checkFloatPos(L, 2);
3943 ItemStack item = read_item(L, 3);
3944 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3946 // Use minetest.spawn_item to spawn a __builtin:item
3947 lua_getglobal(L, "minetest");
3948 lua_getfield(L, -1, "spawn_item");
3949 if(lua_isnil(L, -1))
3951 lua_pushvalue(L, 2);
3952 lua_pushstring(L, item.getItemString().c_str());
3953 if(lua_pcall(L, 2, 1, 0))
3954 script_error(L, "error: %s", lua_tostring(L, -1));
3956 /*lua_pushvalue(L, 1);
3957 lua_pushstring(L, "__builtin:item");
3958 lua_pushstring(L, item.getItemString().c_str());
3959 return l_add_entity(L);*/
3961 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3962 int objectid = env->addActiveObject(obj);
3963 // If failed to add, return nothing (reads as nil)
3967 objectref_get_or_create(L, obj);
3971 // EnvRef:add_rat(pos)
3972 // pos = {x=num, y=num, z=num}
3973 static int l_add_rat(lua_State *L)
3975 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3976 <<" Doing nothing."<<std::endl;
3980 // EnvRef:add_firefly(pos)
3981 // pos = {x=num, y=num, z=num}
3982 static int l_add_firefly(lua_State *L)
3984 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3985 <<" Doing nothing."<<std::endl;
3989 // EnvRef:get_player_by_name(name)
3990 static int l_get_player_by_name(lua_State *L)
3992 EnvRef *o = checkobject(L, 1);
3993 ServerEnvironment *env = o->m_env;
3994 if(env == NULL) return 0;
3996 const char *name = luaL_checkstring(L, 2);
3997 Player *player = env->getPlayer(name);
4002 PlayerSAO *sao = player->getPlayerSAO();
4007 // Put player on stack
4008 objectref_get_or_create(L, sao);
4012 // EnvRef:get_objects_inside_radius(pos, radius)
4013 static int l_get_objects_inside_radius(lua_State *L)
4015 // Get the table insert function
4016 lua_getglobal(L, "table");
4017 lua_getfield(L, -1, "insert");
4018 int table_insert = lua_gettop(L);
4020 EnvRef *o = checkobject(L, 1);
4021 ServerEnvironment *env = o->m_env;
4022 if(env == NULL) return 0;
4024 v3f pos = checkFloatPos(L, 2);
4025 float radius = luaL_checknumber(L, 3) * BS;
4026 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
4028 int table = lua_gettop(L);
4029 for(std::set<u16>::const_iterator
4030 i = ids.begin(); i != ids.end(); i++){
4031 ServerActiveObject *obj = env->getActiveObject(*i);
4032 // Insert object reference into table
4033 lua_pushvalue(L, table_insert);
4034 lua_pushvalue(L, table);
4035 objectref_get_or_create(L, obj);
4036 if(lua_pcall(L, 2, 0, 0))
4037 script_error(L, "error: %s", lua_tostring(L, -1));
4042 // EnvRef:set_timeofday(val)
4044 static int l_set_timeofday(lua_State *L)
4046 EnvRef *o = checkobject(L, 1);
4047 ServerEnvironment *env = o->m_env;
4048 if(env == NULL) return 0;
4050 float timeofday_f = luaL_checknumber(L, 2);
4051 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
4052 int timeofday_mh = (int)(timeofday_f * 24000.0);
4053 // This should be set directly in the environment but currently
4054 // such changes aren't immediately sent to the clients, so call
4055 // the server instead.
4056 //env->setTimeOfDay(timeofday_mh);
4057 get_server(L)->setTimeOfDay(timeofday_mh);
4061 // EnvRef:get_timeofday() -> 0...1
4062 static int l_get_timeofday(lua_State *L)
4064 EnvRef *o = checkobject(L, 1);
4065 ServerEnvironment *env = o->m_env;
4066 if(env == NULL) return 0;
4068 int timeofday_mh = env->getTimeOfDay();
4069 float timeofday_f = (float)timeofday_mh / 24000.0;
4070 lua_pushnumber(L, timeofday_f);
4075 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
4076 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
4077 static int l_find_node_near(lua_State *L)
4079 EnvRef *o = checkobject(L, 1);
4080 ServerEnvironment *env = o->m_env;
4081 if(env == NULL) return 0;
4082 INodeDefManager *ndef = get_server(L)->ndef();
4083 v3s16 pos = read_v3s16(L, 2);
4084 int radius = luaL_checkinteger(L, 3);
4085 std::set<content_t> filter;
4086 if(lua_istable(L, 4)){
4089 while(lua_next(L, table) != 0){
4090 // key at index -2 and value at index -1
4091 luaL_checktype(L, -1, LUA_TSTRING);
4092 ndef->getIds(lua_tostring(L, -1), filter);
4093 // removes value, keeps key for next iteration
4096 } else if(lua_isstring(L, 4)){
4097 ndef->getIds(lua_tostring(L, 4), filter);
4100 for(int d=1; d<=radius; d++){
4101 core::list<v3s16> list;
4102 getFacePositions(list, d);
4103 for(core::list<v3s16>::Iterator i = list.begin();
4104 i != list.end(); i++){
4105 v3s16 p = pos + (*i);
4106 content_t c = env->getMap().getNodeNoEx(p).getContent();
4107 if(filter.count(c) != 0){
4116 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
4117 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
4118 static int l_find_nodes_in_area(lua_State *L)
4120 EnvRef *o = checkobject(L, 1);
4121 ServerEnvironment *env = o->m_env;
4122 if(env == NULL) return 0;
4123 INodeDefManager *ndef = get_server(L)->ndef();
4124 v3s16 minp = read_v3s16(L, 2);
4125 v3s16 maxp = read_v3s16(L, 3);
4126 std::set<content_t> filter;
4127 if(lua_istable(L, 4)){
4130 while(lua_next(L, table) != 0){
4131 // key at index -2 and value at index -1
4132 luaL_checktype(L, -1, LUA_TSTRING);
4133 ndef->getIds(lua_tostring(L, -1), filter);
4134 // removes value, keeps key for next iteration
4137 } else if(lua_isstring(L, 4)){
4138 ndef->getIds(lua_tostring(L, 4), filter);
4141 // Get the table insert function
4142 lua_getglobal(L, "table");
4143 lua_getfield(L, -1, "insert");
4144 int table_insert = lua_gettop(L);
4147 int table = lua_gettop(L);
4148 for(s16 x=minp.X; x<=maxp.X; x++)
4149 for(s16 y=minp.Y; y<=maxp.Y; y++)
4150 for(s16 z=minp.Z; z<=maxp.Z; z++)
4153 content_t c = env->getMap().getNodeNoEx(p).getContent();
4154 if(filter.count(c) != 0){
4155 lua_pushvalue(L, table_insert);
4156 lua_pushvalue(L, table);
4158 if(lua_pcall(L, 2, 0, 0))
4159 script_error(L, "error: %s", lua_tostring(L, -1));
4165 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
4166 // returns world-specific PerlinNoise
4167 static int l_get_perlin(lua_State *L)
4169 EnvRef *o = checkobject(L, 1);
4170 ServerEnvironment *env = o->m_env;
4171 if(env == NULL) return 0;
4173 int seeddiff = luaL_checkint(L, 2);
4174 int octaves = luaL_checkint(L, 3);
4175 float persistence = luaL_checknumber(L, 4);
4176 float scale = luaL_checknumber(L, 5);
4178 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
4179 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4180 luaL_getmetatable(L, "PerlinNoise");
4181 lua_setmetatable(L, -2);
4185 // EnvRef:get_perlin_map(noiseparams, size)
4186 // returns world-specific PerlinNoiseMap
4187 static int l_get_perlin_map(lua_State *L)
4189 EnvRef *o = checkobject(L, 1);
4190 ServerEnvironment *env = o->m_env;
4194 NoiseParams *np = read_noiseparams(L, 2);
4197 v3s16 size = read_v3s16(L, 3);
4199 int seed = (int)(env->getServerMap().getSeed());
4200 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(np, seed, size);
4201 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4202 luaL_getmetatable(L, "PerlinNoiseMap");
4203 lua_setmetatable(L, -2);
4207 // EnvRef:clear_objects()
4208 // clear all objects in the environment
4209 static int l_clear_objects(lua_State *L)
4211 EnvRef *o = checkobject(L, 1);
4212 o->m_env->clearAllObjects();
4216 static int l_spawn_tree(lua_State *L)
4218 EnvRef *o = checkobject(L, 1);
4219 ServerEnvironment *env = o->m_env;
4220 if(env == NULL) return 0;
4221 v3s16 p0 = read_v3s16(L, 2);
4223 treegen::TreeDef tree_def;
4224 std::string trunk,leaves,fruit;
4225 INodeDefManager *ndef = env->getGameDef()->ndef();
4227 if(lua_istable(L, 3))
4229 getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4230 getstringfield(L, 3, "rules_a", tree_def.rules_a);
4231 getstringfield(L, 3, "rules_b", tree_def.rules_b);
4232 getstringfield(L, 3, "rules_c", tree_def.rules_c);
4233 getstringfield(L, 3, "rules_d", tree_def.rules_d);
4234 getstringfield(L, 3, "trunk", trunk);
4235 tree_def.trunknode=ndef->getId(trunk);
4236 getstringfield(L, 3, "leaves", leaves);
4237 tree_def.leavesnode=ndef->getId(leaves);
4238 tree_def.leaves2_chance=0;
4239 getstringfield(L, 3, "leaves2", leaves);
4242 tree_def.leaves2node=ndef->getId(leaves);
4243 getintfield(L, 3, "leaves2_chance", tree_def.leaves2_chance);
4245 getintfield(L, 3, "angle", tree_def.angle);
4246 getintfield(L, 3, "iterations", tree_def.iterations);
4247 getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4248 getstringfield(L, 3, "trunk_type", tree_def.trunk_type);
4249 getboolfield(L, 3, "thin_branches", tree_def.thin_branches);
4250 tree_def.fruit_chance=0;
4251 getstringfield(L, 3, "fruit", fruit);
4254 tree_def.fruitnode=ndef->getId(fruit);
4255 getintfield(L, 3, "fruit_chance",tree_def.fruit_chance);
4257 getintfield(L, 3, "seed", tree_def.seed);
4261 treegen::spawn_ltree (env, p0, ndef, tree_def);
4266 EnvRef(ServerEnvironment *env):
4269 //infostream<<"EnvRef created"<<std::endl;
4274 //infostream<<"EnvRef destructing"<<std::endl;
4277 // Creates an EnvRef and leaves it on top of stack
4278 // Not callable from Lua; all references are created on the C side.
4279 static void create(lua_State *L, ServerEnvironment *env)
4281 EnvRef *o = new EnvRef(env);
4282 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4283 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4284 luaL_getmetatable(L, className);
4285 lua_setmetatable(L, -2);
4288 static void set_null(lua_State *L)
4290 EnvRef *o = checkobject(L, -1);
4294 static void Register(lua_State *L)
4297 int methodtable = lua_gettop(L);
4298 luaL_newmetatable(L, className);
4299 int metatable = lua_gettop(L);
4301 lua_pushliteral(L, "__metatable");
4302 lua_pushvalue(L, methodtable);
4303 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4305 lua_pushliteral(L, "__index");
4306 lua_pushvalue(L, methodtable);
4307 lua_settable(L, metatable);
4309 lua_pushliteral(L, "__gc");
4310 lua_pushcfunction(L, gc_object);
4311 lua_settable(L, metatable);
4313 lua_pop(L, 1); // drop metatable
4315 luaL_openlib(L, 0, methods, 0); // fill methodtable
4316 lua_pop(L, 1); // drop methodtable
4318 // Cannot be created from Lua
4319 //lua_register(L, className, create_object);
4322 const char EnvRef::className[] = "EnvRef";
4323 const luaL_reg EnvRef::methods[] = {
4324 method(EnvRef, set_node),
4325 method(EnvRef, add_node),
4326 method(EnvRef, remove_node),
4327 method(EnvRef, get_node),
4328 method(EnvRef, get_node_or_nil),
4329 method(EnvRef, get_node_light),
4330 method(EnvRef, place_node),
4331 method(EnvRef, dig_node),
4332 method(EnvRef, punch_node),
4333 method(EnvRef, add_entity),
4334 method(EnvRef, add_item),
4335 method(EnvRef, add_rat),
4336 method(EnvRef, add_firefly),
4337 method(EnvRef, get_meta),
4338 method(EnvRef, get_node_timer),
4339 method(EnvRef, get_player_by_name),
4340 method(EnvRef, get_objects_inside_radius),
4341 method(EnvRef, set_timeofday),
4342 method(EnvRef, get_timeofday),
4343 method(EnvRef, find_node_near),
4344 method(EnvRef, find_nodes_in_area),
4345 method(EnvRef, get_perlin),
4346 method(EnvRef, get_perlin_map),
4347 method(EnvRef, clear_objects),
4348 method(EnvRef, spawn_tree),
4357 class LuaPseudoRandom
4360 PseudoRandom m_pseudo;
4362 static const char className[];
4363 static const luaL_reg methods[];
4365 // Exported functions
4367 // garbage collector
4368 static int gc_object(lua_State *L)
4370 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4375 // next(self, min=0, max=32767) -> get next value
4376 static int l_next(lua_State *L)
4378 LuaPseudoRandom *o = checkobject(L, 1);
4381 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4382 if(!lua_isnil(L, 2))
4383 min = luaL_checkinteger(L, 2);
4384 if(!lua_isnil(L, 3))
4385 max = luaL_checkinteger(L, 3);
4387 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4388 throw LuaError(L, "PseudoRandom.next(): max < min");
4390 if(max - min != 32767 && max - min > 32767/5)
4391 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.");
4392 PseudoRandom &pseudo = o->m_pseudo;
4393 int val = pseudo.next();
4394 val = (val % (max-min+1)) + min;
4395 lua_pushinteger(L, val);
4400 LuaPseudoRandom(int seed):
4409 const PseudoRandom& getItem() const
4413 PseudoRandom& getItem()
4418 // LuaPseudoRandom(seed)
4419 // Creates an LuaPseudoRandom and leaves it on top of stack
4420 static int create_object(lua_State *L)
4422 int seed = luaL_checknumber(L, 1);
4423 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4424 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4425 luaL_getmetatable(L, className);
4426 lua_setmetatable(L, -2);
4430 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4432 luaL_checktype(L, narg, LUA_TUSERDATA);
4433 void *ud = luaL_checkudata(L, narg, className);
4434 if(!ud) luaL_typerror(L, narg, className);
4435 return *(LuaPseudoRandom**)ud; // unbox pointer
4438 static void Register(lua_State *L)
4441 int methodtable = lua_gettop(L);
4442 luaL_newmetatable(L, className);
4443 int metatable = lua_gettop(L);
4445 lua_pushliteral(L, "__metatable");
4446 lua_pushvalue(L, methodtable);
4447 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4449 lua_pushliteral(L, "__index");
4450 lua_pushvalue(L, methodtable);
4451 lua_settable(L, metatable);
4453 lua_pushliteral(L, "__gc");
4454 lua_pushcfunction(L, gc_object);
4455 lua_settable(L, metatable);
4457 lua_pop(L, 1); // drop metatable
4459 luaL_openlib(L, 0, methods, 0); // fill methodtable
4460 lua_pop(L, 1); // drop methodtable
4462 // Can be created from Lua (LuaPseudoRandom(seed))
4463 lua_register(L, className, create_object);
4466 const char LuaPseudoRandom::className[] = "PseudoRandom";
4467 const luaL_reg LuaPseudoRandom::methods[] = {
4468 method(LuaPseudoRandom, next),
4478 class LuaABM : public ActiveBlockModifier
4484 std::set<std::string> m_trigger_contents;
4485 std::set<std::string> m_required_neighbors;
4486 float m_trigger_interval;
4487 u32 m_trigger_chance;
4489 LuaABM(lua_State *L, int id,
4490 const std::set<std::string> &trigger_contents,
4491 const std::set<std::string> &required_neighbors,
4492 float trigger_interval, u32 trigger_chance):
4495 m_trigger_contents(trigger_contents),
4496 m_required_neighbors(required_neighbors),
4497 m_trigger_interval(trigger_interval),
4498 m_trigger_chance(trigger_chance)
4501 virtual std::set<std::string> getTriggerContents()
4503 return m_trigger_contents;
4505 virtual std::set<std::string> getRequiredNeighbors()
4507 return m_required_neighbors;
4509 virtual float getTriggerInterval()
4511 return m_trigger_interval;
4513 virtual u32 getTriggerChance()
4515 return m_trigger_chance;
4517 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4518 u32 active_object_count, u32 active_object_count_wider)
4520 lua_State *L = m_lua;
4523 assert(lua_checkstack(L, 20));
4524 StackUnroller stack_unroller(L);
4526 // Get minetest.registered_abms
4527 lua_getglobal(L, "minetest");
4528 lua_getfield(L, -1, "registered_abms");
4529 luaL_checktype(L, -1, LUA_TTABLE);
4530 int registered_abms = lua_gettop(L);
4532 // Get minetest.registered_abms[m_id]
4533 lua_pushnumber(L, m_id);
4534 lua_gettable(L, registered_abms);
4535 if(lua_isnil(L, -1))
4539 luaL_checktype(L, -1, LUA_TTABLE);
4540 lua_getfield(L, -1, "action");
4541 luaL_checktype(L, -1, LUA_TFUNCTION);
4543 pushnode(L, n, env->getGameDef()->ndef());
4544 lua_pushnumber(L, active_object_count);
4545 lua_pushnumber(L, active_object_count_wider);
4546 if(lua_pcall(L, 4, 0, 0))
4547 script_error(L, "error: %s", lua_tostring(L, -1));
4555 static void read_server_sound_params(lua_State *L, int index,
4556 ServerSoundParams ¶ms)
4559 index = lua_gettop(L) + 1 + index;
4561 params = ServerSoundParams();
4562 if(lua_istable(L, index)){
4563 getfloatfield(L, index, "gain", params.gain);
4564 getstringfield(L, index, "to_player", params.to_player);
4565 lua_getfield(L, index, "pos");
4566 if(!lua_isnil(L, -1)){
4567 v3f p = read_v3f(L, -1)*BS;
4569 params.type = ServerSoundParams::SSP_POSITIONAL;
4572 lua_getfield(L, index, "object");
4573 if(!lua_isnil(L, -1)){
4574 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4575 ServerActiveObject *sao = ObjectRef::getobject(ref);
4577 params.object = sao->getId();
4578 params.type = ServerSoundParams::SSP_OBJECT;
4582 params.max_hear_distance = BS*getfloatfield_default(L, index,
4583 "max_hear_distance", params.max_hear_distance/BS);
4584 getboolfield(L, index, "loop", params.loop);
4593 // Writes a line to dstream
4594 static int l_debug(lua_State *L)
4596 std::string text = lua_tostring(L, 1);
4597 dstream << text << std::endl;
4601 // log([level,] text)
4602 // Writes a line to the logger.
4603 // The one-argument version logs to infostream.
4604 // The two-argument version accept a log level: error, action, info, or verbose.
4605 static int l_log(lua_State *L)
4608 LogMessageLevel level = LMT_INFO;
4609 if(lua_isnone(L, 2))
4611 text = lua_tostring(L, 1);
4615 std::string levelname = luaL_checkstring(L, 1);
4616 text = luaL_checkstring(L, 2);
4617 if(levelname == "error")
4619 else if(levelname == "action")
4621 else if(levelname == "verbose")
4622 level = LMT_VERBOSE;
4624 log_printline(level, text);
4628 // request_shutdown()
4629 static int l_request_shutdown(lua_State *L)
4631 get_server(L)->requestShutdown();
4635 // get_server_status()
4636 static int l_get_server_status(lua_State *L)
4638 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4642 // register_biome_groups({frequencies})
4643 static int l_register_biome_groups(lua_State *L)
4645 luaL_checktype(L, 1, LUA_TTABLE);
4647 if (!lua_istable(L, index))
4648 throw LuaError(L, "register_biome_groups: parameter is not a table");
4650 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4652 verbosestream << "register_biome_groups: BiomeDefManager not active" << std::endl;
4657 for (int i = 1; lua_next(L, index) != 0; i++) {
4658 bmgr->addBiomeGroup(lua_tonumber(L, -1));
4666 // register_biome({lots of stuff})
4667 static int l_register_biome(lua_State *L)
4669 luaL_checktype(L, 1, LUA_TTABLE);
4670 int index = 1, groupid;
4671 std::string nodename;
4673 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
4674 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4676 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
4680 groupid = getintfield_default(L, index, "group_id", 0);
4682 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
4683 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
4684 Biome *b = bmgr->createBiome(terrain);
4686 b->name = getstringfield_default(L, index, "name", "");
4688 if (getstringfield(L, index, "node_top", nodename))
4689 b->n_top = MapNode(ndef->getId(nodename));
4691 b->n_top = MapNode(CONTENT_IGNORE);
4693 if (getstringfield(L, index, "node_filler", nodename))
4694 b->n_filler = MapNode(ndef->getId(nodename));
4696 b->n_filler = b->n_top;
4698 b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
4700 b->height_min = getintfield_default(L, index, "height_min", 0);
4701 b->height_max = getintfield_default(L, index, "height_max", 0);
4702 b->heat_min = getfloatfield_default(L, index, "heat_min", 0.);
4703 b->heat_max = getfloatfield_default(L, index, "heat_max", 0.);
4704 b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
4705 b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
4707 b->np = new NoiseParams; // should read an entire NoiseParams later on...
4708 getfloatfield(L, index, "scale", b->np->scale);
4709 getfloatfield(L, index, "offset", b->np->offset);
4711 b->groupid = (s8)groupid;
4712 b->flags = 0; //reserved
4716 verbosestream << "register_biome: " << b->name << std::endl;
4720 // register_item_raw({lots of stuff})
4721 static int l_register_item_raw(lua_State *L)
4723 luaL_checktype(L, 1, LUA_TTABLE);
4726 // Get the writable item and node definition managers from the server
4727 IWritableItemDefManager *idef =
4728 get_server(L)->getWritableItemDefManager();
4729 IWritableNodeDefManager *ndef =
4730 get_server(L)->getWritableNodeDefManager();
4732 // Check if name is defined
4734 lua_getfield(L, table, "name");
4735 if(lua_isstring(L, -1)){
4736 name = lua_tostring(L, -1);
4737 verbosestream<<"register_item_raw: "<<name<<std::endl;
4739 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4742 // Check if on_use is defined
4745 // Set a distinctive default value to check if this is set
4746 def.node_placement_prediction = "__default";
4748 // Read the item definition
4749 def = read_item_definition(L, table, def);
4751 // Default to having client-side placement prediction for nodes
4752 // ("" in item definition sets it off)
4753 if(def.node_placement_prediction == "__default"){
4754 if(def.type == ITEM_NODE && !def.rightclickable)
4755 def.node_placement_prediction = name;
4757 def.node_placement_prediction = "";
4760 // Register item definition
4761 idef->registerItem(def);
4763 // Read the node definition (content features) and register it
4764 if(def.type == ITEM_NODE)
4766 ContentFeatures f = read_content_features(L, table);
4767 ndef->set(f.name, f);
4770 return 0; /* number of results */
4773 // register_alias_raw(name, convert_to_name)
4774 static int l_register_alias_raw(lua_State *L)
4776 std::string name = luaL_checkstring(L, 1);
4777 std::string convert_to = luaL_checkstring(L, 2);
4779 // Get the writable item definition manager from the server
4780 IWritableItemDefManager *idef =
4781 get_server(L)->getWritableItemDefManager();
4783 idef->registerAlias(name, convert_to);
4785 return 0; /* number of results */
4788 // helper for register_craft
4789 static bool read_craft_recipe_shaped(lua_State *L, int index,
4790 int &width, std::vector<std::string> &recipe)
4793 index = lua_gettop(L) + 1 + index;
4795 if(!lua_istable(L, index))
4800 while(lua_next(L, index) != 0){
4802 // key at index -2 and value at index -1
4803 if(!lua_istable(L, -1))
4805 int table2 = lua_gettop(L);
4807 while(lua_next(L, table2) != 0){
4808 // key at index -2 and value at index -1
4809 if(!lua_isstring(L, -1))
4811 recipe.push_back(lua_tostring(L, -1));
4812 // removes value, keeps key for next iteration
4819 if(colcount != width)
4822 // removes value, keeps key for next iteration
4829 // helper for register_craft
4830 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4831 std::vector<std::string> &recipe)
4834 index = lua_gettop(L) + 1 + index;
4836 if(!lua_istable(L, index))
4840 while(lua_next(L, index) != 0){
4841 // key at index -2 and value at index -1
4842 if(!lua_isstring(L, -1))
4844 recipe.push_back(lua_tostring(L, -1));
4845 // removes value, keeps key for next iteration
4851 // helper for register_craft
4852 static bool read_craft_replacements(lua_State *L, int index,
4853 CraftReplacements &replacements)
4856 index = lua_gettop(L) + 1 + index;
4858 if(!lua_istable(L, index))
4862 while(lua_next(L, index) != 0){
4863 // key at index -2 and value at index -1
4864 if(!lua_istable(L, -1))
4866 lua_rawgeti(L, -1, 1);
4867 if(!lua_isstring(L, -1))
4869 std::string replace_from = lua_tostring(L, -1);
4871 lua_rawgeti(L, -1, 2);
4872 if(!lua_isstring(L, -1))
4874 std::string replace_to = lua_tostring(L, -1);
4876 replacements.pairs.push_back(
4877 std::make_pair(replace_from, replace_to));
4878 // removes value, keeps key for next iteration
4883 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4884 static int l_register_craft(lua_State *L)
4886 //infostream<<"register_craft"<<std::endl;
4887 luaL_checktype(L, 1, LUA_TTABLE);
4890 // Get the writable craft definition manager from the server
4891 IWritableCraftDefManager *craftdef =
4892 get_server(L)->getWritableCraftDefManager();
4894 std::string type = getstringfield_default(L, table, "type", "shaped");
4897 CraftDefinitionShaped
4899 if(type == "shaped"){
4900 std::string output = getstringfield_default(L, table, "output", "");
4902 throw LuaError(L, "Crafting definition is missing an output");
4905 std::vector<std::string> recipe;
4906 lua_getfield(L, table, "recipe");
4907 if(lua_isnil(L, -1))
4908 throw LuaError(L, "Crafting definition is missing a recipe"
4909 " (output=\"" + output + "\")");
4910 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4911 throw LuaError(L, "Invalid crafting recipe"
4912 " (output=\"" + output + "\")");
4914 CraftReplacements replacements;
4915 lua_getfield(L, table, "replacements");
4916 if(!lua_isnil(L, -1))
4918 if(!read_craft_replacements(L, -1, replacements))
4919 throw LuaError(L, "Invalid replacements"
4920 " (output=\"" + output + "\")");
4923 CraftDefinition *def = new CraftDefinitionShaped(
4924 output, width, recipe, replacements);
4925 craftdef->registerCraft(def);
4928 CraftDefinitionShapeless
4930 else if(type == "shapeless"){
4931 std::string output = getstringfield_default(L, table, "output", "");
4933 throw LuaError(L, "Crafting definition (shapeless)"
4934 " is missing an output");
4936 std::vector<std::string> recipe;
4937 lua_getfield(L, table, "recipe");
4938 if(lua_isnil(L, -1))
4939 throw LuaError(L, "Crafting definition (shapeless)"
4940 " is missing a recipe"
4941 " (output=\"" + output + "\")");
4942 if(!read_craft_recipe_shapeless(L, -1, recipe))
4943 throw LuaError(L, "Invalid crafting recipe"
4944 " (output=\"" + output + "\")");
4946 CraftReplacements replacements;
4947 lua_getfield(L, table, "replacements");
4948 if(!lua_isnil(L, -1))
4950 if(!read_craft_replacements(L, -1, replacements))
4951 throw LuaError(L, "Invalid replacements"
4952 " (output=\"" + output + "\")");
4955 CraftDefinition *def = new CraftDefinitionShapeless(
4956 output, recipe, replacements);
4957 craftdef->registerCraft(def);
4960 CraftDefinitionToolRepair
4962 else if(type == "toolrepair"){
4963 float additional_wear = getfloatfield_default(L, table,
4964 "additional_wear", 0.0);
4966 CraftDefinition *def = new CraftDefinitionToolRepair(
4968 craftdef->registerCraft(def);
4971 CraftDefinitionCooking
4973 else if(type == "cooking"){
4974 std::string output = getstringfield_default(L, table, "output", "");
4976 throw LuaError(L, "Crafting definition (cooking)"
4977 " is missing an output");
4979 std::string recipe = getstringfield_default(L, table, "recipe", "");
4981 throw LuaError(L, "Crafting definition (cooking)"
4982 " is missing a recipe"
4983 " (output=\"" + output + "\")");
4985 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4987 CraftReplacements replacements;
4988 lua_getfield(L, table, "replacements");
4989 if(!lua_isnil(L, -1))
4991 if(!read_craft_replacements(L, -1, replacements))
4992 throw LuaError(L, "Invalid replacements"
4993 " (cooking output=\"" + output + "\")");
4996 CraftDefinition *def = new CraftDefinitionCooking(
4997 output, recipe, cooktime, replacements);
4998 craftdef->registerCraft(def);
5003 else if(type == "fuel"){
5004 std::string recipe = getstringfield_default(L, table, "recipe", "");
5006 throw LuaError(L, "Crafting definition (fuel)"
5007 " is missing a recipe");
5009 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
5011 CraftReplacements replacements;
5012 lua_getfield(L, table, "replacements");
5013 if(!lua_isnil(L, -1))
5015 if(!read_craft_replacements(L, -1, replacements))
5016 throw LuaError(L, "Invalid replacements"
5017 " (fuel recipe=\"" + recipe + "\")");
5020 CraftDefinition *def = new CraftDefinitionFuel(
5021 recipe, burntime, replacements);
5022 craftdef->registerCraft(def);
5026 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
5030 return 0; /* number of results */
5033 // setting_set(name, value)
5034 static int l_setting_set(lua_State *L)
5036 const char *name = luaL_checkstring(L, 1);
5037 const char *value = luaL_checkstring(L, 2);
5038 g_settings->set(name, value);
5042 // setting_get(name)
5043 static int l_setting_get(lua_State *L)
5045 const char *name = luaL_checkstring(L, 1);
5047 std::string value = g_settings->get(name);
5048 lua_pushstring(L, value.c_str());
5049 } catch(SettingNotFoundException &e){
5055 // setting_getbool(name)
5056 static int l_setting_getbool(lua_State *L)
5058 const char *name = luaL_checkstring(L, 1);
5060 bool value = g_settings->getBool(name);
5061 lua_pushboolean(L, value);
5062 } catch(SettingNotFoundException &e){
5069 static int l_setting_save(lua_State *L)
5071 get_server(L)->saveConfig();
5075 // chat_send_all(text)
5076 static int l_chat_send_all(lua_State *L)
5078 const char *text = luaL_checkstring(L, 1);
5079 // Get server from registry
5080 Server *server = get_server(L);
5082 server->notifyPlayers(narrow_to_wide(text));
5086 // chat_send_player(name, text)
5087 static int l_chat_send_player(lua_State *L)
5089 const char *name = luaL_checkstring(L, 1);
5090 const char *text = luaL_checkstring(L, 2);
5091 // Get server from registry
5092 Server *server = get_server(L);
5094 server->notifyPlayer(name, narrow_to_wide(text));
5098 // get_player_privs(name, text)
5099 static int l_get_player_privs(lua_State *L)
5101 const char *name = luaL_checkstring(L, 1);
5102 // Get server from registry
5103 Server *server = get_server(L);
5106 int table = lua_gettop(L);
5107 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
5108 for(std::set<std::string>::const_iterator
5109 i = privs_s.begin(); i != privs_s.end(); i++){
5110 lua_pushboolean(L, true);
5111 lua_setfield(L, table, i->c_str());
5113 lua_pushvalue(L, table);
5118 static int l_get_ban_list(lua_State *L)
5120 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
5124 // get_ban_description()
5125 static int l_get_ban_description(lua_State *L)
5127 const char * ip_or_name = luaL_checkstring(L, 1);
5128 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
5133 static int l_ban_player(lua_State *L)
5135 const char * name = luaL_checkstring(L, 1);
5136 Player *player = get_env(L)->getPlayer(name);
5139 lua_pushboolean(L, false); // no such player
5144 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
5145 std::string ip_str = addr.serializeString();
5146 get_server(L)->setIpBanned(ip_str, name);
5148 catch(con::PeerNotFoundException) // unlikely
5150 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
5151 lua_pushboolean(L, false); // error
5154 lua_pushboolean(L, true);
5158 // unban_player_or_ip()
5159 static int l_unban_player_of_ip(lua_State *L)
5161 const char * ip_or_name = luaL_checkstring(L, 1);
5162 get_server(L)->unsetIpBanned(ip_or_name);
5163 lua_pushboolean(L, true);
5167 // get_inventory(location)
5168 static int l_get_inventory(lua_State *L)
5170 InventoryLocation loc;
5172 std::string type = checkstringfield(L, 1, "type");
5173 if(type == "player"){
5174 std::string name = checkstringfield(L, 1, "name");
5175 loc.setPlayer(name);
5176 } else if(type == "node"){
5177 lua_getfield(L, 1, "pos");
5178 v3s16 pos = check_v3s16(L, -1);
5179 loc.setNodeMeta(pos);
5180 } else if(type == "detached"){
5181 std::string name = checkstringfield(L, 1, "name");
5182 loc.setDetached(name);
5185 if(get_server(L)->getInventory(loc) != NULL)
5186 InvRef::create(L, loc);
5192 // create_detached_inventory_raw(name)
5193 static int l_create_detached_inventory_raw(lua_State *L)
5195 const char *name = luaL_checkstring(L, 1);
5196 if(get_server(L)->createDetachedInventory(name) != NULL){
5197 InventoryLocation loc;
5198 loc.setDetached(name);
5199 InvRef::create(L, loc);
5206 // show_formspec(playername,formname,formspec)
5207 static int l_show_formspec(lua_State *L)
5209 const char *playername = luaL_checkstring(L, 1);
5210 const char *formname = luaL_checkstring(L, 2);
5211 const char *formspec = luaL_checkstring(L, 3);
5213 if(get_server(L)->showFormspec(playername,formspec,formname))
5215 lua_pushboolean(L, true);
5217 lua_pushboolean(L, false);
5222 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5223 static int l_get_dig_params(lua_State *L)
5225 std::map<std::string, int> groups;
5226 read_groups(L, 1, groups);
5227 ToolCapabilities tp = read_tool_capabilities(L, 2);
5228 if(lua_isnoneornil(L, 3))
5229 push_dig_params(L, getDigParams(groups, &tp));
5231 push_dig_params(L, getDigParams(groups, &tp,
5232 luaL_checknumber(L, 3)));
5236 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5237 static int l_get_hit_params(lua_State *L)
5239 std::map<std::string, int> groups;
5240 read_groups(L, 1, groups);
5241 ToolCapabilities tp = read_tool_capabilities(L, 2);
5242 if(lua_isnoneornil(L, 3))
5243 push_hit_params(L, getHitParams(groups, &tp));
5245 push_hit_params(L, getHitParams(groups, &tp,
5246 luaL_checknumber(L, 3)));
5250 // get_current_modname()
5251 static int l_get_current_modname(lua_State *L)
5253 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5257 // get_modpath(modname)
5258 static int l_get_modpath(lua_State *L)
5260 std::string modname = luaL_checkstring(L, 1);
5262 if(modname == "__builtin"){
5263 std::string path = get_server(L)->getBuiltinLuaPath();
5264 lua_pushstring(L, path.c_str());
5267 const ModSpec *mod = get_server(L)->getModSpec(modname);
5272 lua_pushstring(L, mod->path.c_str());
5277 // the returned list is sorted alphabetically for you
5278 static int l_get_modnames(lua_State *L)
5280 // Get a list of mods
5281 core::list<std::string> mods_unsorted, mods_sorted;
5282 get_server(L)->getModNames(mods_unsorted);
5284 // Take unsorted items from mods_unsorted and sort them into
5285 // mods_sorted; not great performance but the number of mods on a
5286 // server will likely be small.
5287 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5288 i != mods_unsorted.end(); i++)
5291 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5292 x != mods_unsorted.end(); x++)
5294 // I doubt anybody using Minetest will be using
5295 // anything not ASCII based :)
5296 if((*i).compare(*x) <= 0)
5298 mods_sorted.insert_before(x, *i);
5304 mods_sorted.push_back(*i);
5307 // Get the table insertion function from Lua.
5308 lua_getglobal(L, "table");
5309 lua_getfield(L, -1, "insert");
5310 int insertion_func = lua_gettop(L);
5312 // Package them up for Lua
5314 int new_table = lua_gettop(L);
5315 core::list<std::string>::Iterator i = mods_sorted.begin();
5316 while(i != mods_sorted.end())
5318 lua_pushvalue(L, insertion_func);
5319 lua_pushvalue(L, new_table);
5320 lua_pushstring(L, (*i).c_str());
5321 if(lua_pcall(L, 2, 0, 0) != 0)
5323 script_error(L, "error: %s", lua_tostring(L, -1));
5331 static int l_get_worldpath(lua_State *L)
5333 std::string worldpath = get_server(L)->getWorldPath();
5334 lua_pushstring(L, worldpath.c_str());
5338 // sound_play(spec, parameters)
5339 static int l_sound_play(lua_State *L)
5341 SimpleSoundSpec spec;
5342 read_soundspec(L, 1, spec);
5343 ServerSoundParams params;
5344 read_server_sound_params(L, 2, params);
5345 s32 handle = get_server(L)->playSound(spec, params);
5346 lua_pushinteger(L, handle);
5350 // sound_stop(handle)
5351 static int l_sound_stop(lua_State *L)
5353 int handle = luaL_checkinteger(L, 1);
5354 get_server(L)->stopSound(handle);
5358 // is_singleplayer()
5359 static int l_is_singleplayer(lua_State *L)
5361 lua_pushboolean(L, get_server(L)->isSingleplayer());
5365 // get_password_hash(name, raw_password)
5366 static int l_get_password_hash(lua_State *L)
5368 std::string name = luaL_checkstring(L, 1);
5369 std::string raw_password = luaL_checkstring(L, 2);
5370 std::string hash = translatePassword(name,
5371 narrow_to_wide(raw_password));
5372 lua_pushstring(L, hash.c_str());
5376 // notify_authentication_modified(name)
5377 static int l_notify_authentication_modified(lua_State *L)
5379 std::string name = "";
5380 if(lua_isstring(L, 1))
5381 name = lua_tostring(L, 1);
5382 get_server(L)->reportPrivsModified(name);
5386 // get_craft_result(input)
5387 static int l_get_craft_result(lua_State *L)
5390 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5391 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5392 es_CraftMethod, CRAFT_METHOD_NORMAL);
5394 lua_getfield(L, input_i, "width");
5395 if(lua_isnumber(L, -1))
5396 width = luaL_checkinteger(L, -1);
5398 lua_getfield(L, input_i, "items");
5399 std::vector<ItemStack> items = read_items(L, -1);
5400 lua_pop(L, 1); // items
5402 IGameDef *gdef = get_server(L);
5403 ICraftDefManager *cdef = gdef->cdef();
5404 CraftInput input(method, width, items);
5406 bool got = cdef->getCraftResult(input, output, true, gdef);
5407 lua_newtable(L); // output table
5410 item.deSerialize(output.item, gdef->idef());
5411 LuaItemStack::create(L, item);
5412 lua_setfield(L, -2, "item");
5413 setintfield(L, -1, "time", output.time);
5415 LuaItemStack::create(L, ItemStack());
5416 lua_setfield(L, -2, "item");
5417 setintfield(L, -1, "time", 0);
5419 lua_newtable(L); // decremented input table
5420 lua_pushstring(L, method_s.c_str());
5421 lua_setfield(L, -2, "method");
5422 lua_pushinteger(L, width);
5423 lua_setfield(L, -2, "width");
5424 push_items(L, input.items);
5425 lua_setfield(L, -2, "items");
5429 // get_craft_recipe(result item)
5430 static int l_get_craft_recipe(lua_State *L)
5435 std::string o_item = luaL_checkstring(L,input_i);
5437 IGameDef *gdef = get_server(L);
5438 ICraftDefManager *cdef = gdef->cdef();
5440 CraftOutput output(o_item,0);
5441 bool got = cdef->getCraftRecipe(input, output, gdef);
5442 lua_newtable(L); // output table
5445 for(std::vector<ItemStack>::const_iterator
5446 i = input.items.begin();
5447 i != input.items.end(); i++, k++)
5453 sprintf(tmp,"%d",k);
5454 lua_pushstring(L,tmp);
5455 lua_pushstring(L,i->name.c_str());
5456 lua_settable(L, -3);
5458 lua_setfield(L, -2, "items");
5459 setintfield(L, -1, "width", input.width);
5460 switch (input.method) {
5461 case CRAFT_METHOD_NORMAL:
5462 lua_pushstring(L,"normal");
5464 case CRAFT_METHOD_COOKING:
5465 lua_pushstring(L,"cooking");
5467 case CRAFT_METHOD_FUEL:
5468 lua_pushstring(L,"fuel");
5471 lua_pushstring(L,"unknown");
5473 lua_setfield(L, -2, "type");
5476 lua_setfield(L, -2, "items");
5477 setintfield(L, -1, "width", 0);
5482 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5483 static int l_rollback_get_last_node_actor(lua_State *L)
5485 v3s16 p = read_v3s16(L, 1);
5486 int range = luaL_checknumber(L, 2);
5487 int seconds = luaL_checknumber(L, 3);
5488 Server *server = get_server(L);
5489 IRollbackManager *rollback = server->getRollbackManager();
5491 int act_seconds = 0;
5492 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5493 lua_pushstring(L, actor.c_str());
5494 push_v3s16(L, act_p);
5495 lua_pushnumber(L, act_seconds);
5499 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5500 static int l_rollback_revert_actions_by(lua_State *L)
5502 std::string actor = luaL_checkstring(L, 1);
5503 int seconds = luaL_checknumber(L, 2);
5504 Server *server = get_server(L);
5505 IRollbackManager *rollback = server->getRollbackManager();
5506 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5507 std::list<std::string> log;
5508 bool success = server->rollbackRevertActions(actions, &log);
5509 // Push boolean result
5510 lua_pushboolean(L, success);
5511 // Get the table insert function and push the log table
5512 lua_getglobal(L, "table");
5513 lua_getfield(L, -1, "insert");
5514 int table_insert = lua_gettop(L);
5516 int table = lua_gettop(L);
5517 for(std::list<std::string>::const_iterator i = log.begin();
5518 i != log.end(); i++)
5520 lua_pushvalue(L, table_insert);
5521 lua_pushvalue(L, table);
5522 lua_pushstring(L, i->c_str());
5523 if(lua_pcall(L, 2, 0, 0))
5524 script_error(L, "error: %s", lua_tostring(L, -1));
5526 lua_remove(L, -2); // Remove table
5527 lua_remove(L, -2); // Remove insert
5531 static const struct luaL_Reg minetest_f [] = {
5534 {"request_shutdown", l_request_shutdown},
5535 {"get_server_status", l_get_server_status},
5536 {"register_item_raw", l_register_item_raw},
5537 {"register_alias_raw", l_register_alias_raw},
5538 {"register_craft", l_register_craft},
5539 {"register_biome", l_register_biome},
5540 {"register_biome_groups", l_register_biome_groups},
5541 {"setting_set", l_setting_set},
5542 {"setting_get", l_setting_get},
5543 {"setting_getbool", l_setting_getbool},
5544 {"setting_save",l_setting_save},
5545 {"chat_send_all", l_chat_send_all},
5546 {"chat_send_player", l_chat_send_player},
5547 {"get_player_privs", l_get_player_privs},
5548 {"get_ban_list", l_get_ban_list},
5549 {"get_ban_description", l_get_ban_description},
5550 {"ban_player", l_ban_player},
5551 {"unban_player_or_ip", l_unban_player_of_ip},
5552 {"get_inventory", l_get_inventory},
5553 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5554 {"show_formspec", l_show_formspec},
5555 {"get_dig_params", l_get_dig_params},
5556 {"get_hit_params", l_get_hit_params},
5557 {"get_current_modname", l_get_current_modname},
5558 {"get_modpath", l_get_modpath},
5559 {"get_modnames", l_get_modnames},
5560 {"get_worldpath", l_get_worldpath},
5561 {"sound_play", l_sound_play},
5562 {"sound_stop", l_sound_stop},
5563 {"is_singleplayer", l_is_singleplayer},
5564 {"get_password_hash", l_get_password_hash},
5565 {"notify_authentication_modified", l_notify_authentication_modified},
5566 {"get_craft_result", l_get_craft_result},
5567 {"get_craft_recipe", l_get_craft_recipe},
5568 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5569 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5574 Main export function
5577 void scriptapi_export(lua_State *L, Server *server)
5580 assert(lua_checkstack(L, 20));
5581 verbosestream<<"scriptapi_export()"<<std::endl;
5582 StackUnroller stack_unroller(L);
5584 // Store server as light userdata in registry
5585 lua_pushlightuserdata(L, server);
5586 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5588 // Register global functions in table minetest
5590 luaL_register(L, NULL, minetest_f);
5591 lua_setglobal(L, "minetest");
5593 // Get the main minetest table
5594 lua_getglobal(L, "minetest");
5596 // Add tables to minetest
5598 lua_setfield(L, -2, "object_refs");
5600 lua_setfield(L, -2, "luaentities");
5602 // Register wrappers
5603 LuaItemStack::Register(L);
5604 InvRef::Register(L);
5605 NodeMetaRef::Register(L);
5606 NodeTimerRef::Register(L);
5607 ObjectRef::Register(L);
5608 EnvRef::Register(L);
5609 LuaPseudoRandom::Register(L);
5610 LuaPerlinNoise::Register(L);
5611 LuaPerlinNoiseMap::Register(L);
5614 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5615 const std::string &modname)
5617 ModNameStorer modnamestorer(L, modname);
5619 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5621 errorstream<<"Error loading mod \""<<modname
5622 <<"\": modname does not follow naming conventions: "
5623 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5627 bool success = false;
5630 success = script_load(L, scriptpath.c_str());
5633 errorstream<<"Error loading mod \""<<modname
5634 <<"\": "<<e.what()<<std::endl;
5640 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5643 assert(lua_checkstack(L, 20));
5644 verbosestream<<"scriptapi_add_environment"<<std::endl;
5645 StackUnroller stack_unroller(L);
5647 // Create EnvRef on stack
5648 EnvRef::create(L, env);
5649 int envref = lua_gettop(L);
5651 // minetest.env = envref
5652 lua_getglobal(L, "minetest");
5653 luaL_checktype(L, -1, LUA_TTABLE);
5654 lua_pushvalue(L, envref);
5655 lua_setfield(L, -2, "env");
5657 // Store environment as light userdata in registry
5658 lua_pushlightuserdata(L, env);
5659 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5662 Add ActiveBlockModifiers to environment
5665 // Get minetest.registered_abms
5666 lua_getglobal(L, "minetest");
5667 lua_getfield(L, -1, "registered_abms");
5668 luaL_checktype(L, -1, LUA_TTABLE);
5669 int registered_abms = lua_gettop(L);
5671 if(lua_istable(L, registered_abms)){
5672 int table = lua_gettop(L);
5674 while(lua_next(L, table) != 0){
5675 // key at index -2 and value at index -1
5676 int id = lua_tonumber(L, -2);
5677 int current_abm = lua_gettop(L);
5679 std::set<std::string> trigger_contents;
5680 lua_getfield(L, current_abm, "nodenames");
5681 if(lua_istable(L, -1)){
5682 int table = lua_gettop(L);
5684 while(lua_next(L, table) != 0){
5685 // key at index -2 and value at index -1
5686 luaL_checktype(L, -1, LUA_TSTRING);
5687 trigger_contents.insert(lua_tostring(L, -1));
5688 // removes value, keeps key for next iteration
5691 } else if(lua_isstring(L, -1)){
5692 trigger_contents.insert(lua_tostring(L, -1));
5696 std::set<std::string> required_neighbors;
5697 lua_getfield(L, current_abm, "neighbors");
5698 if(lua_istable(L, -1)){
5699 int table = lua_gettop(L);
5701 while(lua_next(L, table) != 0){
5702 // key at index -2 and value at index -1
5703 luaL_checktype(L, -1, LUA_TSTRING);
5704 required_neighbors.insert(lua_tostring(L, -1));
5705 // removes value, keeps key for next iteration
5708 } else if(lua_isstring(L, -1)){
5709 required_neighbors.insert(lua_tostring(L, -1));
5713 float trigger_interval = 10.0;
5714 getfloatfield(L, current_abm, "interval", trigger_interval);
5716 int trigger_chance = 50;
5717 getintfield(L, current_abm, "chance", trigger_chance);
5719 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5720 required_neighbors, trigger_interval, trigger_chance);
5722 env->addActiveBlockModifier(abm);
5724 // removes value, keeps key for next iteration
5732 // Dump stack top with the dump2 function
5733 static void dump2(lua_State *L, const char *name)
5735 // Dump object (debug)
5736 lua_getglobal(L, "dump2");
5737 luaL_checktype(L, -1, LUA_TFUNCTION);
5738 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5739 lua_pushstring(L, name);
5740 if(lua_pcall(L, 2, 0, 0))
5741 script_error(L, "error: %s", lua_tostring(L, -1));
5749 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5752 assert(lua_checkstack(L, 20));
5753 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5754 StackUnroller stack_unroller(L);
5756 // Create object on stack
5757 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5758 int object = lua_gettop(L);
5760 // Get minetest.object_refs table
5761 lua_getglobal(L, "minetest");
5762 lua_getfield(L, -1, "object_refs");
5763 luaL_checktype(L, -1, LUA_TTABLE);
5764 int objectstable = lua_gettop(L);
5766 // object_refs[id] = object
5767 lua_pushnumber(L, cobj->getId()); // Push id
5768 lua_pushvalue(L, object); // Copy object to top of stack
5769 lua_settable(L, objectstable);
5772 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5775 assert(lua_checkstack(L, 20));
5776 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5777 StackUnroller stack_unroller(L);
5779 // Get minetest.object_refs table
5780 lua_getglobal(L, "minetest");
5781 lua_getfield(L, -1, "object_refs");
5782 luaL_checktype(L, -1, LUA_TTABLE);
5783 int objectstable = lua_gettop(L);
5785 // Get object_refs[id]
5786 lua_pushnumber(L, cobj->getId()); // Push id
5787 lua_gettable(L, objectstable);
5788 // Set object reference to NULL
5789 ObjectRef::set_null(L);
5790 lua_pop(L, 1); // pop object
5792 // Set object_refs[id] = nil
5793 lua_pushnumber(L, cobj->getId()); // Push id
5795 lua_settable(L, objectstable);
5802 // What scriptapi_run_callbacks does with the return values of callbacks.
5803 // Regardless of the mode, if only one callback is defined,
5804 // its return value is the total return value.
5805 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5806 enum RunCallbacksMode
5808 // Returns the return value of the first callback
5809 // Returns nil if list of callbacks is empty
5810 RUN_CALLBACKS_MODE_FIRST,
5811 // Returns the return value of the last callback
5812 // Returns nil if list of callbacks is empty
5813 RUN_CALLBACKS_MODE_LAST,
5814 // If any callback returns a false value, the first such is returned
5815 // Otherwise, the first callback's return value (trueish) is returned
5816 // Returns true if list of callbacks is empty
5817 RUN_CALLBACKS_MODE_AND,
5818 // Like above, but stops calling callbacks (short circuit)
5819 // after seeing the first false value
5820 RUN_CALLBACKS_MODE_AND_SC,
5821 // If any callback returns a true value, the first such is returned
5822 // Otherwise, the first callback's return value (falseish) is returned
5823 // Returns false if list of callbacks is empty
5824 RUN_CALLBACKS_MODE_OR,
5825 // Like above, but stops calling callbacks (short circuit)
5826 // after seeing the first true value
5827 RUN_CALLBACKS_MODE_OR_SC,
5828 // Note: "a true value" and "a false value" refer to values that
5829 // are converted by lua_toboolean to true or false, respectively.
5832 // Push the list of callbacks (a lua table).
5833 // Then push nargs arguments.
5834 // Then call this function, which
5835 // - runs the callbacks
5836 // - removes the table and arguments from the lua stack
5837 // - pushes the return value, computed depending on mode
5838 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5839 RunCallbacksMode mode)
5841 // Insert the return value into the lua stack, below the table
5842 assert(lua_gettop(L) >= nargs + 1);
5844 lua_insert(L, -(nargs + 1) - 1);
5845 // Stack now looks like this:
5846 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5848 int rv = lua_gettop(L) - nargs - 1;
5850 int arg = table + 1;
5852 luaL_checktype(L, table, LUA_TTABLE);
5856 bool first_loop = true;
5857 while(lua_next(L, table) != 0){
5858 // key at index -2 and value at index -1
5859 luaL_checktype(L, -1, LUA_TFUNCTION);
5861 for(int i = 0; i < nargs; i++)
5862 lua_pushvalue(L, arg+i);
5863 if(lua_pcall(L, nargs, 1, 0))
5864 script_error(L, "error: %s", lua_tostring(L, -1));
5866 // Move return value to designated space in stack
5869 // Result of first callback is always moved
5873 // Otherwise, what happens depends on the mode
5874 if(mode == RUN_CALLBACKS_MODE_FIRST)
5876 else if(mode == RUN_CALLBACKS_MODE_LAST)
5878 else if(mode == RUN_CALLBACKS_MODE_AND ||
5879 mode == RUN_CALLBACKS_MODE_AND_SC){
5880 if((bool)lua_toboolean(L, rv) == true &&
5881 (bool)lua_toboolean(L, -1) == false)
5886 else if(mode == RUN_CALLBACKS_MODE_OR ||
5887 mode == RUN_CALLBACKS_MODE_OR_SC){
5888 if((bool)lua_toboolean(L, rv) == false &&
5889 (bool)lua_toboolean(L, -1) == true)
5898 // Handle short circuit modes
5899 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5900 (bool)lua_toboolean(L, rv) == false)
5902 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5903 (bool)lua_toboolean(L, rv) == true)
5906 // value removed, keep key for next iteration
5909 // Remove stuff from stack, leaving only the return value
5912 // Fix return value in case no callbacks were called
5914 if(mode == RUN_CALLBACKS_MODE_AND ||
5915 mode == RUN_CALLBACKS_MODE_AND_SC){
5917 lua_pushboolean(L, true);
5919 else if(mode == RUN_CALLBACKS_MODE_OR ||
5920 mode == RUN_CALLBACKS_MODE_OR_SC){
5922 lua_pushboolean(L, false);
5927 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5928 const std::string &message)
5931 assert(lua_checkstack(L, 20));
5932 StackUnroller stack_unroller(L);
5934 // Get minetest.registered_on_chat_messages
5935 lua_getglobal(L, "minetest");
5936 lua_getfield(L, -1, "registered_on_chat_messages");
5938 lua_pushstring(L, name.c_str());
5939 lua_pushstring(L, message.c_str());
5940 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5941 bool ate = lua_toboolean(L, -1);
5945 void scriptapi_on_shutdown(lua_State *L)
5948 assert(lua_checkstack(L, 20));
5949 StackUnroller stack_unroller(L);
5951 // Get registered shutdown hooks
5952 lua_getglobal(L, "minetest");
5953 lua_getfield(L, -1, "registered_on_shutdown");
5955 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5958 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5961 assert(lua_checkstack(L, 20));
5962 StackUnroller stack_unroller(L);
5964 // Get minetest.registered_on_newplayers
5965 lua_getglobal(L, "minetest");
5966 lua_getfield(L, -1, "registered_on_newplayers");
5968 objectref_get_or_create(L, player);
5969 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5972 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5975 assert(lua_checkstack(L, 20));
5976 StackUnroller stack_unroller(L);
5978 // Get minetest.registered_on_dieplayers
5979 lua_getglobal(L, "minetest");
5980 lua_getfield(L, -1, "registered_on_dieplayers");
5982 objectref_get_or_create(L, player);
5983 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5986 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5989 assert(lua_checkstack(L, 20));
5990 StackUnroller stack_unroller(L);
5992 // Get minetest.registered_on_respawnplayers
5993 lua_getglobal(L, "minetest");
5994 lua_getfield(L, -1, "registered_on_respawnplayers");
5996 objectref_get_or_create(L, player);
5997 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5998 bool positioning_handled_by_some = lua_toboolean(L, -1);
5999 return positioning_handled_by_some;
6002 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
6005 assert(lua_checkstack(L, 20));
6006 StackUnroller stack_unroller(L);
6008 // Get minetest.registered_on_joinplayers
6009 lua_getglobal(L, "minetest");
6010 lua_getfield(L, -1, "registered_on_joinplayers");
6012 objectref_get_or_create(L, player);
6013 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6016 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
6019 assert(lua_checkstack(L, 20));
6020 StackUnroller stack_unroller(L);
6022 // Get minetest.registered_on_leaveplayers
6023 lua_getglobal(L, "minetest");
6024 lua_getfield(L, -1, "registered_on_leaveplayers");
6026 objectref_get_or_create(L, player);
6027 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6030 static void get_auth_handler(lua_State *L)
6032 lua_getglobal(L, "minetest");
6033 lua_getfield(L, -1, "registered_auth_handler");
6034 if(lua_isnil(L, -1)){
6036 lua_getfield(L, -1, "builtin_auth_handler");
6038 if(lua_type(L, -1) != LUA_TTABLE)
6039 throw LuaError(L, "Authentication handler table not valid");
6042 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
6043 std::string *dst_password, std::set<std::string> *dst_privs)
6046 assert(lua_checkstack(L, 20));
6047 StackUnroller stack_unroller(L);
6049 get_auth_handler(L);
6050 lua_getfield(L, -1, "get_auth");
6051 if(lua_type(L, -1) != LUA_TFUNCTION)
6052 throw LuaError(L, "Authentication handler missing get_auth");
6053 lua_pushstring(L, playername.c_str());
6054 if(lua_pcall(L, 1, 1, 0))
6055 script_error(L, "error: %s", lua_tostring(L, -1));
6057 // nil = login not allowed
6058 if(lua_isnil(L, -1))
6060 luaL_checktype(L, -1, LUA_TTABLE);
6062 std::string password;
6063 bool found = getstringfield(L, -1, "password", password);
6065 throw LuaError(L, "Authentication handler didn't return password");
6067 *dst_password = password;
6069 lua_getfield(L, -1, "privileges");
6070 if(!lua_istable(L, -1))
6072 "Authentication handler didn't return privilege table");
6074 read_privileges(L, -1, *dst_privs);
6080 void scriptapi_create_auth(lua_State *L, const std::string &playername,
6081 const std::string &password)
6084 assert(lua_checkstack(L, 20));
6085 StackUnroller stack_unroller(L);
6087 get_auth_handler(L);
6088 lua_getfield(L, -1, "create_auth");
6089 if(lua_type(L, -1) != LUA_TFUNCTION)
6090 throw LuaError(L, "Authentication handler missing create_auth");
6091 lua_pushstring(L, playername.c_str());
6092 lua_pushstring(L, password.c_str());
6093 if(lua_pcall(L, 2, 0, 0))
6094 script_error(L, "error: %s", lua_tostring(L, -1));
6097 bool scriptapi_set_password(lua_State *L, const std::string &playername,
6098 const std::string &password)
6101 assert(lua_checkstack(L, 20));
6102 StackUnroller stack_unroller(L);
6104 get_auth_handler(L);
6105 lua_getfield(L, -1, "set_password");
6106 if(lua_type(L, -1) != LUA_TFUNCTION)
6107 throw LuaError(L, "Authentication handler missing set_password");
6108 lua_pushstring(L, playername.c_str());
6109 lua_pushstring(L, password.c_str());
6110 if(lua_pcall(L, 2, 1, 0))
6111 script_error(L, "error: %s", lua_tostring(L, -1));
6112 return lua_toboolean(L, -1);
6119 void scriptapi_on_player_receive_fields(lua_State *L,
6120 ServerActiveObject *player,
6121 const std::string &formname,
6122 const std::map<std::string, std::string> &fields)
6125 assert(lua_checkstack(L, 20));
6126 StackUnroller stack_unroller(L);
6128 // Get minetest.registered_on_chat_messages
6129 lua_getglobal(L, "minetest");
6130 lua_getfield(L, -1, "registered_on_player_receive_fields");
6133 objectref_get_or_create(L, player);
6135 lua_pushstring(L, formname.c_str());
6138 for(std::map<std::string, std::string>::const_iterator
6139 i = fields.begin(); i != fields.end(); i++){
6140 const std::string &name = i->first;
6141 const std::string &value = i->second;
6142 lua_pushstring(L, name.c_str());
6143 lua_pushlstring(L, value.c_str(), value.size());
6144 lua_settable(L, -3);
6146 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
6150 item callbacks and node callbacks
6153 // Retrieves minetest.registered_items[name][callbackname]
6154 // If that is nil or on error, return false and stack is unchanged
6155 // If that is a function, returns true and pushes the
6156 // function onto the stack
6157 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
6158 // is tried instead so unknown items can still be manipulated to some degree
6159 static bool get_item_callback(lua_State *L,
6160 const char *name, const char *callbackname)
6162 lua_getglobal(L, "minetest");
6163 lua_getfield(L, -1, "registered_items");
6165 luaL_checktype(L, -1, LUA_TTABLE);
6166 lua_getfield(L, -1, name);
6168 // Should be a table
6169 if(lua_type(L, -1) != LUA_TTABLE)
6171 // Report error and clean up
6172 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6175 // Try minetest.nodedef_default instead
6176 lua_getglobal(L, "minetest");
6177 lua_getfield(L, -1, "nodedef_default");
6179 luaL_checktype(L, -1, LUA_TTABLE);
6181 lua_getfield(L, -1, callbackname);
6183 // Should be a function or nil
6184 if(lua_type(L, -1) == LUA_TFUNCTION)
6188 else if(lua_isnil(L, -1))
6195 errorstream<<"Item \""<<name<<"\" callback \""
6196 <<callbackname<<" is not a function"<<std::endl;
6202 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6203 ServerActiveObject *dropper, v3f pos)
6206 assert(lua_checkstack(L, 20));
6207 StackUnroller stack_unroller(L);
6209 // Push callback function on stack
6210 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6214 LuaItemStack::create(L, item);
6215 objectref_get_or_create(L, dropper);
6216 pushFloatPos(L, pos);
6217 if(lua_pcall(L, 3, 1, 0))
6218 script_error(L, "error: %s", lua_tostring(L, -1));
6219 if(!lua_isnil(L, -1))
6220 item = read_item(L, -1);
6224 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6225 ServerActiveObject *placer, const PointedThing &pointed)
6228 assert(lua_checkstack(L, 20));
6229 StackUnroller stack_unroller(L);
6231 // Push callback function on stack
6232 if(!get_item_callback(L, item.name.c_str(), "on_place"))
6236 LuaItemStack::create(L, item);
6237 objectref_get_or_create(L, placer);
6238 push_pointed_thing(L, pointed);
6239 if(lua_pcall(L, 3, 1, 0))
6240 script_error(L, "error: %s", lua_tostring(L, -1));
6241 if(!lua_isnil(L, -1))
6242 item = read_item(L, -1);
6246 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6247 ServerActiveObject *user, const PointedThing &pointed)
6250 assert(lua_checkstack(L, 20));
6251 StackUnroller stack_unroller(L);
6253 // Push callback function on stack
6254 if(!get_item_callback(L, item.name.c_str(), "on_use"))
6258 LuaItemStack::create(L, item);
6259 objectref_get_or_create(L, user);
6260 push_pointed_thing(L, pointed);
6261 if(lua_pcall(L, 3, 1, 0))
6262 script_error(L, "error: %s", lua_tostring(L, -1));
6263 if(!lua_isnil(L, -1))
6264 item = read_item(L, -1);
6268 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6269 ServerActiveObject *puncher)
6272 assert(lua_checkstack(L, 20));
6273 StackUnroller stack_unroller(L);
6275 INodeDefManager *ndef = get_server(L)->ndef();
6277 // Push callback function on stack
6278 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6283 pushnode(L, node, ndef);
6284 objectref_get_or_create(L, puncher);
6285 if(lua_pcall(L, 3, 0, 0))
6286 script_error(L, "error: %s", lua_tostring(L, -1));
6290 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6291 ServerActiveObject *digger)
6294 assert(lua_checkstack(L, 20));
6295 StackUnroller stack_unroller(L);
6297 INodeDefManager *ndef = get_server(L)->ndef();
6299 // Push callback function on stack
6300 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6305 pushnode(L, node, ndef);
6306 objectref_get_or_create(L, digger);
6307 if(lua_pcall(L, 3, 0, 0))
6308 script_error(L, "error: %s", lua_tostring(L, -1));
6312 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6315 assert(lua_checkstack(L, 20));
6316 StackUnroller stack_unroller(L);
6318 INodeDefManager *ndef = get_server(L)->ndef();
6320 // Push callback function on stack
6321 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6326 if(lua_pcall(L, 1, 0, 0))
6327 script_error(L, "error: %s", lua_tostring(L, -1));
6330 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6333 assert(lua_checkstack(L, 20));
6334 StackUnroller stack_unroller(L);
6336 INodeDefManager *ndef = get_server(L)->ndef();
6338 // Push callback function on stack
6339 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6344 if(lua_pcall(L, 1, 0, 0))
6345 script_error(L, "error: %s", lua_tostring(L, -1));
6348 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6351 assert(lua_checkstack(L, 20));
6352 StackUnroller stack_unroller(L);
6354 INodeDefManager *ndef = get_server(L)->ndef();
6356 // Push callback function on stack
6357 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6362 pushnode(L, node, ndef);
6363 if(lua_pcall(L, 2, 0, 0))
6364 script_error(L, "error: %s", lua_tostring(L, -1));
6367 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6370 assert(lua_checkstack(L, 20));
6371 StackUnroller stack_unroller(L);
6373 INodeDefManager *ndef = get_server(L)->ndef();
6375 // Push callback function on stack
6376 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6381 lua_pushnumber(L,dtime);
6382 if(lua_pcall(L, 2, 1, 0))
6383 script_error(L, "error: %s", lua_tostring(L, -1));
6384 if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6390 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6391 const std::string &formname,
6392 const std::map<std::string, std::string> &fields,
6393 ServerActiveObject *sender)
6396 assert(lua_checkstack(L, 20));
6397 StackUnroller stack_unroller(L);
6399 INodeDefManager *ndef = get_server(L)->ndef();
6401 // If node doesn't exist, we don't know what callback to call
6402 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6403 if(node.getContent() == CONTENT_IGNORE)
6406 // Push callback function on stack
6407 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6414 lua_pushstring(L, formname.c_str());
6417 for(std::map<std::string, std::string>::const_iterator
6418 i = fields.begin(); i != fields.end(); i++){
6419 const std::string &name = i->first;
6420 const std::string &value = i->second;
6421 lua_pushstring(L, name.c_str());
6422 lua_pushlstring(L, value.c_str(), value.size());
6423 lua_settable(L, -3);
6426 objectref_get_or_create(L, sender);
6427 if(lua_pcall(L, 4, 0, 0))
6428 script_error(L, "error: %s", lua_tostring(L, -1));
6432 Node metadata inventory callbacks
6435 // Return number of accepted items to be moved
6436 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6437 const std::string &from_list, int from_index,
6438 const std::string &to_list, int to_index,
6439 int count, ServerActiveObject *player)
6442 assert(lua_checkstack(L, 20));
6443 StackUnroller stack_unroller(L);
6445 INodeDefManager *ndef = get_server(L)->ndef();
6447 // If node doesn't exist, we don't know what callback to call
6448 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6449 if(node.getContent() == CONTENT_IGNORE)
6452 // Push callback function on stack
6453 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6454 "allow_metadata_inventory_move"))
6457 // function(pos, from_list, from_index, to_list, to_index, count, player)
6461 lua_pushstring(L, from_list.c_str());
6463 lua_pushinteger(L, from_index + 1);
6465 lua_pushstring(L, to_list.c_str());
6467 lua_pushinteger(L, to_index + 1);
6469 lua_pushinteger(L, count);
6471 objectref_get_or_create(L, player);
6472 if(lua_pcall(L, 7, 1, 0))
6473 script_error(L, "error: %s", lua_tostring(L, -1));
6474 if(!lua_isnumber(L, -1))
6475 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6476 return luaL_checkinteger(L, -1);
6479 // Return number of accepted items to be put
6480 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6481 const std::string &listname, int index, ItemStack &stack,
6482 ServerActiveObject *player)
6485 assert(lua_checkstack(L, 20));
6486 StackUnroller stack_unroller(L);
6488 INodeDefManager *ndef = get_server(L)->ndef();
6490 // If node doesn't exist, we don't know what callback to call
6491 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6492 if(node.getContent() == CONTENT_IGNORE)
6495 // Push callback function on stack
6496 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6497 "allow_metadata_inventory_put"))
6500 // Call function(pos, listname, index, stack, player)
6504 lua_pushstring(L, listname.c_str());
6506 lua_pushinteger(L, index + 1);
6508 LuaItemStack::create(L, stack);
6510 objectref_get_or_create(L, player);
6511 if(lua_pcall(L, 5, 1, 0))
6512 script_error(L, "error: %s", lua_tostring(L, -1));
6513 if(!lua_isnumber(L, -1))
6514 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6515 return luaL_checkinteger(L, -1);
6518 // Return number of accepted items to be taken
6519 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6520 const std::string &listname, int index, ItemStack &stack,
6521 ServerActiveObject *player)
6524 assert(lua_checkstack(L, 20));
6525 StackUnroller stack_unroller(L);
6527 INodeDefManager *ndef = get_server(L)->ndef();
6529 // If node doesn't exist, we don't know what callback to call
6530 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6531 if(node.getContent() == CONTENT_IGNORE)
6534 // Push callback function on stack
6535 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6536 "allow_metadata_inventory_take"))
6539 // Call function(pos, listname, index, count, player)
6543 lua_pushstring(L, listname.c_str());
6545 lua_pushinteger(L, index + 1);
6547 LuaItemStack::create(L, stack);
6549 objectref_get_or_create(L, player);
6550 if(lua_pcall(L, 5, 1, 0))
6551 script_error(L, "error: %s", lua_tostring(L, -1));
6552 if(!lua_isnumber(L, -1))
6553 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6554 return luaL_checkinteger(L, -1);
6557 // Report moved items
6558 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6559 const std::string &from_list, int from_index,
6560 const std::string &to_list, int to_index,
6561 int count, ServerActiveObject *player)
6564 assert(lua_checkstack(L, 20));
6565 StackUnroller stack_unroller(L);
6567 INodeDefManager *ndef = get_server(L)->ndef();
6569 // If node doesn't exist, we don't know what callback to call
6570 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6571 if(node.getContent() == CONTENT_IGNORE)
6574 // Push callback function on stack
6575 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6576 "on_metadata_inventory_move"))
6579 // function(pos, from_list, from_index, to_list, to_index, count, player)
6583 lua_pushstring(L, from_list.c_str());
6585 lua_pushinteger(L, from_index + 1);
6587 lua_pushstring(L, to_list.c_str());
6589 lua_pushinteger(L, to_index + 1);
6591 lua_pushinteger(L, count);
6593 objectref_get_or_create(L, player);
6594 if(lua_pcall(L, 7, 0, 0))
6595 script_error(L, "error: %s", lua_tostring(L, -1));
6599 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6600 const std::string &listname, int index, ItemStack &stack,
6601 ServerActiveObject *player)
6604 assert(lua_checkstack(L, 20));
6605 StackUnroller stack_unroller(L);
6607 INodeDefManager *ndef = get_server(L)->ndef();
6609 // If node doesn't exist, we don't know what callback to call
6610 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6611 if(node.getContent() == CONTENT_IGNORE)
6614 // Push callback function on stack
6615 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6616 "on_metadata_inventory_put"))
6619 // Call function(pos, listname, index, stack, player)
6623 lua_pushstring(L, listname.c_str());
6625 lua_pushinteger(L, index + 1);
6627 LuaItemStack::create(L, stack);
6629 objectref_get_or_create(L, player);
6630 if(lua_pcall(L, 5, 0, 0))
6631 script_error(L, "error: %s", lua_tostring(L, -1));
6634 // Report taken items
6635 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6636 const std::string &listname, int index, ItemStack &stack,
6637 ServerActiveObject *player)
6640 assert(lua_checkstack(L, 20));
6641 StackUnroller stack_unroller(L);
6643 INodeDefManager *ndef = get_server(L)->ndef();
6645 // If node doesn't exist, we don't know what callback to call
6646 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6647 if(node.getContent() == CONTENT_IGNORE)
6650 // Push callback function on stack
6651 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6652 "on_metadata_inventory_take"))
6655 // Call function(pos, listname, index, stack, player)
6659 lua_pushstring(L, listname.c_str());
6661 lua_pushinteger(L, index + 1);
6663 LuaItemStack::create(L, stack);
6665 objectref_get_or_create(L, player);
6666 if(lua_pcall(L, 5, 0, 0))
6667 script_error(L, "error: %s", lua_tostring(L, -1));
6671 Detached inventory callbacks
6674 // Retrieves minetest.detached_inventories[name][callbackname]
6675 // If that is nil or on error, return false and stack is unchanged
6676 // If that is a function, returns true and pushes the
6677 // function onto the stack
6678 static bool get_detached_inventory_callback(lua_State *L,
6679 const std::string &name, const char *callbackname)
6681 lua_getglobal(L, "minetest");
6682 lua_getfield(L, -1, "detached_inventories");
6684 luaL_checktype(L, -1, LUA_TTABLE);
6685 lua_getfield(L, -1, name.c_str());
6687 // Should be a table
6688 if(lua_type(L, -1) != LUA_TTABLE)
6690 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6694 lua_getfield(L, -1, callbackname);
6696 // Should be a function or nil
6697 if(lua_type(L, -1) == LUA_TFUNCTION)
6701 else if(lua_isnil(L, -1))
6708 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6709 <<callbackname<<"\" is not a function"<<std::endl;
6715 // Return number of accepted items to be moved
6716 int scriptapi_detached_inventory_allow_move(lua_State *L,
6717 const std::string &name,
6718 const std::string &from_list, int from_index,
6719 const std::string &to_list, int to_index,
6720 int count, ServerActiveObject *player)
6723 assert(lua_checkstack(L, 20));
6724 StackUnroller stack_unroller(L);
6726 // Push callback function on stack
6727 if(!get_detached_inventory_callback(L, name, "allow_move"))
6730 // function(inv, from_list, from_index, to_list, to_index, count, player)
6732 InventoryLocation loc;
6733 loc.setDetached(name);
6734 InvRef::create(L, loc);
6736 lua_pushstring(L, from_list.c_str());
6738 lua_pushinteger(L, from_index + 1);
6740 lua_pushstring(L, to_list.c_str());
6742 lua_pushinteger(L, to_index + 1);
6744 lua_pushinteger(L, count);
6746 objectref_get_or_create(L, player);
6747 if(lua_pcall(L, 7, 1, 0))
6748 script_error(L, "error: %s", lua_tostring(L, -1));
6749 if(!lua_isnumber(L, -1))
6750 throw LuaError(L, "allow_move should return a number");
6751 return luaL_checkinteger(L, -1);
6754 // Return number of accepted items to be put
6755 int scriptapi_detached_inventory_allow_put(lua_State *L,
6756 const std::string &name,
6757 const std::string &listname, int index, ItemStack &stack,
6758 ServerActiveObject *player)
6761 assert(lua_checkstack(L, 20));
6762 StackUnroller stack_unroller(L);
6764 // Push callback function on stack
6765 if(!get_detached_inventory_callback(L, name, "allow_put"))
6766 return stack.count; // All will be accepted
6768 // Call function(inv, listname, index, stack, player)
6770 InventoryLocation loc;
6771 loc.setDetached(name);
6772 InvRef::create(L, loc);
6774 lua_pushstring(L, listname.c_str());
6776 lua_pushinteger(L, index + 1);
6778 LuaItemStack::create(L, stack);
6780 objectref_get_or_create(L, player);
6781 if(lua_pcall(L, 5, 1, 0))
6782 script_error(L, "error: %s", lua_tostring(L, -1));
6783 if(!lua_isnumber(L, -1))
6784 throw LuaError(L, "allow_put should return a number");
6785 return luaL_checkinteger(L, -1);
6788 // Return number of accepted items to be taken
6789 int scriptapi_detached_inventory_allow_take(lua_State *L,
6790 const std::string &name,
6791 const std::string &listname, int index, ItemStack &stack,
6792 ServerActiveObject *player)
6795 assert(lua_checkstack(L, 20));
6796 StackUnroller stack_unroller(L);
6798 // Push callback function on stack
6799 if(!get_detached_inventory_callback(L, name, "allow_take"))
6800 return stack.count; // All will be accepted
6802 // Call function(inv, listname, index, stack, player)
6804 InventoryLocation loc;
6805 loc.setDetached(name);
6806 InvRef::create(L, loc);
6808 lua_pushstring(L, listname.c_str());
6810 lua_pushinteger(L, index + 1);
6812 LuaItemStack::create(L, stack);
6814 objectref_get_or_create(L, player);
6815 if(lua_pcall(L, 5, 1, 0))
6816 script_error(L, "error: %s", lua_tostring(L, -1));
6817 if(!lua_isnumber(L, -1))
6818 throw LuaError(L, "allow_take should return a number");
6819 return luaL_checkinteger(L, -1);
6822 // Report moved items
6823 void scriptapi_detached_inventory_on_move(lua_State *L,
6824 const std::string &name,
6825 const std::string &from_list, int from_index,
6826 const std::string &to_list, int to_index,
6827 int count, ServerActiveObject *player)
6830 assert(lua_checkstack(L, 20));
6831 StackUnroller stack_unroller(L);
6833 // Push callback function on stack
6834 if(!get_detached_inventory_callback(L, name, "on_move"))
6837 // function(inv, from_list, from_index, to_list, to_index, count, player)
6839 InventoryLocation loc;
6840 loc.setDetached(name);
6841 InvRef::create(L, loc);
6843 lua_pushstring(L, from_list.c_str());
6845 lua_pushinteger(L, from_index + 1);
6847 lua_pushstring(L, to_list.c_str());
6849 lua_pushinteger(L, to_index + 1);
6851 lua_pushinteger(L, count);
6853 objectref_get_or_create(L, player);
6854 if(lua_pcall(L, 7, 0, 0))
6855 script_error(L, "error: %s", lua_tostring(L, -1));
6859 void scriptapi_detached_inventory_on_put(lua_State *L,
6860 const std::string &name,
6861 const std::string &listname, int index, ItemStack &stack,
6862 ServerActiveObject *player)
6865 assert(lua_checkstack(L, 20));
6866 StackUnroller stack_unroller(L);
6868 // Push callback function on stack
6869 if(!get_detached_inventory_callback(L, name, "on_put"))
6872 // Call function(inv, listname, index, stack, player)
6874 InventoryLocation loc;
6875 loc.setDetached(name);
6876 InvRef::create(L, loc);
6878 lua_pushstring(L, listname.c_str());
6880 lua_pushinteger(L, index + 1);
6882 LuaItemStack::create(L, stack);
6884 objectref_get_or_create(L, player);
6885 if(lua_pcall(L, 5, 0, 0))
6886 script_error(L, "error: %s", lua_tostring(L, -1));
6889 // Report taken items
6890 void scriptapi_detached_inventory_on_take(lua_State *L,
6891 const std::string &name,
6892 const std::string &listname, int index, ItemStack &stack,
6893 ServerActiveObject *player)
6896 assert(lua_checkstack(L, 20));
6897 StackUnroller stack_unroller(L);
6899 // Push callback function on stack
6900 if(!get_detached_inventory_callback(L, name, "on_take"))
6903 // Call function(inv, listname, index, stack, player)
6905 InventoryLocation loc;
6906 loc.setDetached(name);
6907 InvRef::create(L, loc);
6909 lua_pushstring(L, listname.c_str());
6911 lua_pushinteger(L, index + 1);
6913 LuaItemStack::create(L, stack);
6915 objectref_get_or_create(L, player);
6916 if(lua_pcall(L, 5, 0, 0))
6917 script_error(L, "error: %s", lua_tostring(L, -1));
6924 void scriptapi_environment_step(lua_State *L, float dtime)
6927 assert(lua_checkstack(L, 20));
6928 //infostream<<"scriptapi_environment_step"<<std::endl;
6929 StackUnroller stack_unroller(L);
6931 // Get minetest.registered_globalsteps
6932 lua_getglobal(L, "minetest");
6933 lua_getfield(L, -1, "registered_globalsteps");
6935 lua_pushnumber(L, dtime);
6936 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6939 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6943 assert(lua_checkstack(L, 20));
6944 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6945 StackUnroller stack_unroller(L);
6947 // Get minetest.registered_on_generateds
6948 lua_getglobal(L, "minetest");
6949 lua_getfield(L, -1, "registered_on_generateds");
6951 push_v3s16(L, minp);
6952 push_v3s16(L, maxp);
6953 lua_pushnumber(L, blockseed);
6954 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6961 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6964 assert(lua_checkstack(L, 20));
6965 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6966 <<name<<"\""<<std::endl;
6967 StackUnroller stack_unroller(L);
6969 // Get minetest.registered_entities[name]
6970 lua_getglobal(L, "minetest");
6971 lua_getfield(L, -1, "registered_entities");
6972 luaL_checktype(L, -1, LUA_TTABLE);
6973 lua_pushstring(L, name);
6974 lua_gettable(L, -2);
6975 // Should be a table, which we will use as a prototype
6976 //luaL_checktype(L, -1, LUA_TTABLE);
6977 if(lua_type(L, -1) != LUA_TTABLE){
6978 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6981 int prototype_table = lua_gettop(L);
6982 //dump2(L, "prototype_table");
6984 // Create entity object
6986 int object = lua_gettop(L);
6988 // Set object metatable
6989 lua_pushvalue(L, prototype_table);
6990 lua_setmetatable(L, -2);
6992 // Add object reference
6993 // This should be userdata with metatable ObjectRef
6994 objectref_get(L, id);
6995 luaL_checktype(L, -1, LUA_TUSERDATA);
6996 if(!luaL_checkudata(L, -1, "ObjectRef"))
6997 luaL_typerror(L, -1, "ObjectRef");
6998 lua_setfield(L, -2, "object");
7000 // minetest.luaentities[id] = object
7001 lua_getglobal(L, "minetest");
7002 lua_getfield(L, -1, "luaentities");
7003 luaL_checktype(L, -1, LUA_TTABLE);
7004 lua_pushnumber(L, id); // Push id
7005 lua_pushvalue(L, object); // Copy object to top of stack
7006 lua_settable(L, -3);
7011 void scriptapi_luaentity_activate(lua_State *L, u16 id,
7012 const std::string &staticdata, u32 dtime_s)
7015 assert(lua_checkstack(L, 20));
7016 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
7017 StackUnroller stack_unroller(L);
7019 // Get minetest.luaentities[id]
7020 luaentity_get(L, id);
7021 int object = lua_gettop(L);
7023 // Get on_activate function
7024 lua_pushvalue(L, object);
7025 lua_getfield(L, -1, "on_activate");
7026 if(!lua_isnil(L, -1)){
7027 luaL_checktype(L, -1, LUA_TFUNCTION);
7028 lua_pushvalue(L, object); // self
7029 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
7030 lua_pushinteger(L, dtime_s);
7031 // Call with 3 arguments, 0 results
7032 if(lua_pcall(L, 3, 0, 0))
7033 script_error(L, "error running function on_activate: %s\n",
7034 lua_tostring(L, -1));
7038 void scriptapi_luaentity_rm(lua_State *L, u16 id)
7041 assert(lua_checkstack(L, 20));
7042 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
7044 // Get minetest.luaentities table
7045 lua_getglobal(L, "minetest");
7046 lua_getfield(L, -1, "luaentities");
7047 luaL_checktype(L, -1, LUA_TTABLE);
7048 int objectstable = lua_gettop(L);
7050 // Set luaentities[id] = nil
7051 lua_pushnumber(L, id); // Push id
7053 lua_settable(L, objectstable);
7055 lua_pop(L, 2); // pop luaentities, minetest
7058 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
7061 assert(lua_checkstack(L, 20));
7062 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
7063 StackUnroller stack_unroller(L);
7065 // Get minetest.luaentities[id]
7066 luaentity_get(L, id);
7067 int object = lua_gettop(L);
7069 // Get get_staticdata function
7070 lua_pushvalue(L, object);
7071 lua_getfield(L, -1, "get_staticdata");
7072 if(lua_isnil(L, -1))
7075 luaL_checktype(L, -1, LUA_TFUNCTION);
7076 lua_pushvalue(L, object); // self
7077 // Call with 1 arguments, 1 results
7078 if(lua_pcall(L, 1, 1, 0))
7079 script_error(L, "error running function get_staticdata: %s\n",
7080 lua_tostring(L, -1));
7083 const char *s = lua_tolstring(L, -1, &len);
7084 return std::string(s, len);
7087 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
7088 ObjectProperties *prop)
7091 assert(lua_checkstack(L, 20));
7092 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
7093 StackUnroller stack_unroller(L);
7095 // Get minetest.luaentities[id]
7096 luaentity_get(L, id);
7097 //int object = lua_gettop(L);
7099 // Set default values that differ from ObjectProperties defaults
7104 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
7106 getboolfield(L, -1, "physical", prop->physical);
7108 getfloatfield(L, -1, "weight", prop->weight);
7110 lua_getfield(L, -1, "collisionbox");
7111 if(lua_istable(L, -1))
7112 prop->collisionbox = read_aabb3f(L, -1, 1.0);
7115 getstringfield(L, -1, "visual", prop->visual);
7117 getstringfield(L, -1, "mesh", prop->mesh);
7119 // Deprecated: read object properties directly
7120 read_object_properties(L, -1, prop);
7122 // Read initial_properties
7123 lua_getfield(L, -1, "initial_properties");
7124 read_object_properties(L, -1, prop);
7128 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
7131 assert(lua_checkstack(L, 20));
7132 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7133 StackUnroller stack_unroller(L);
7135 // Get minetest.luaentities[id]
7136 luaentity_get(L, id);
7137 int object = lua_gettop(L);
7138 // State: object is at top of stack
7139 // Get step function
7140 lua_getfield(L, -1, "on_step");
7141 if(lua_isnil(L, -1))
7143 luaL_checktype(L, -1, LUA_TFUNCTION);
7144 lua_pushvalue(L, object); // self
7145 lua_pushnumber(L, dtime); // dtime
7146 // Call with 2 arguments, 0 results
7147 if(lua_pcall(L, 2, 0, 0))
7148 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
7151 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
7152 // tool_capabilities, direction)
7153 void scriptapi_luaentity_punch(lua_State *L, u16 id,
7154 ServerActiveObject *puncher, float time_from_last_punch,
7155 const ToolCapabilities *toolcap, v3f dir)
7158 assert(lua_checkstack(L, 20));
7159 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7160 StackUnroller stack_unroller(L);
7162 // Get minetest.luaentities[id]
7163 luaentity_get(L, id);
7164 int object = lua_gettop(L);
7165 // State: object is at top of stack
7167 lua_getfield(L, -1, "on_punch");
7168 if(lua_isnil(L, -1))
7170 luaL_checktype(L, -1, LUA_TFUNCTION);
7171 lua_pushvalue(L, object); // self
7172 objectref_get_or_create(L, puncher); // Clicker reference
7173 lua_pushnumber(L, time_from_last_punch);
7174 push_tool_capabilities(L, *toolcap);
7176 // Call with 5 arguments, 0 results
7177 if(lua_pcall(L, 5, 0, 0))
7178 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
7181 // Calls entity:on_rightclick(ObjectRef clicker)
7182 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
7183 ServerActiveObject *clicker)
7186 assert(lua_checkstack(L, 20));
7187 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7188 StackUnroller stack_unroller(L);
7190 // Get minetest.luaentities[id]
7191 luaentity_get(L, id);
7192 int object = lua_gettop(L);
7193 // State: object is at top of stack
7195 lua_getfield(L, -1, "on_rightclick");
7196 if(lua_isnil(L, -1))
7198 luaL_checktype(L, -1, LUA_TFUNCTION);
7199 lua_pushvalue(L, object); // self
7200 objectref_get_or_create(L, clicker); // Clicker reference
7201 // Call with 2 arguments, 0 results
7202 if(lua_pcall(L, 2, 0, 0))
7203 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));