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);
4260 treegen::spawn_ltree (env, p0, ndef, tree_def);
4265 EnvRef(ServerEnvironment *env):
4268 //infostream<<"EnvRef created"<<std::endl;
4273 //infostream<<"EnvRef destructing"<<std::endl;
4276 // Creates an EnvRef and leaves it on top of stack
4277 // Not callable from Lua; all references are created on the C side.
4278 static void create(lua_State *L, ServerEnvironment *env)
4280 EnvRef *o = new EnvRef(env);
4281 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4282 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4283 luaL_getmetatable(L, className);
4284 lua_setmetatable(L, -2);
4287 static void set_null(lua_State *L)
4289 EnvRef *o = checkobject(L, -1);
4293 static void Register(lua_State *L)
4296 int methodtable = lua_gettop(L);
4297 luaL_newmetatable(L, className);
4298 int metatable = lua_gettop(L);
4300 lua_pushliteral(L, "__metatable");
4301 lua_pushvalue(L, methodtable);
4302 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4304 lua_pushliteral(L, "__index");
4305 lua_pushvalue(L, methodtable);
4306 lua_settable(L, metatable);
4308 lua_pushliteral(L, "__gc");
4309 lua_pushcfunction(L, gc_object);
4310 lua_settable(L, metatable);
4312 lua_pop(L, 1); // drop metatable
4314 luaL_openlib(L, 0, methods, 0); // fill methodtable
4315 lua_pop(L, 1); // drop methodtable
4317 // Cannot be created from Lua
4318 //lua_register(L, className, create_object);
4321 const char EnvRef::className[] = "EnvRef";
4322 const luaL_reg EnvRef::methods[] = {
4323 method(EnvRef, set_node),
4324 method(EnvRef, add_node),
4325 method(EnvRef, remove_node),
4326 method(EnvRef, get_node),
4327 method(EnvRef, get_node_or_nil),
4328 method(EnvRef, get_node_light),
4329 method(EnvRef, place_node),
4330 method(EnvRef, dig_node),
4331 method(EnvRef, punch_node),
4332 method(EnvRef, add_entity),
4333 method(EnvRef, add_item),
4334 method(EnvRef, add_rat),
4335 method(EnvRef, add_firefly),
4336 method(EnvRef, get_meta),
4337 method(EnvRef, get_node_timer),
4338 method(EnvRef, get_player_by_name),
4339 method(EnvRef, get_objects_inside_radius),
4340 method(EnvRef, set_timeofday),
4341 method(EnvRef, get_timeofday),
4342 method(EnvRef, find_node_near),
4343 method(EnvRef, find_nodes_in_area),
4344 method(EnvRef, get_perlin),
4345 method(EnvRef, get_perlin_map),
4346 method(EnvRef, clear_objects),
4347 method(EnvRef, spawn_tree),
4356 class LuaPseudoRandom
4359 PseudoRandom m_pseudo;
4361 static const char className[];
4362 static const luaL_reg methods[];
4364 // Exported functions
4366 // garbage collector
4367 static int gc_object(lua_State *L)
4369 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4374 // next(self, min=0, max=32767) -> get next value
4375 static int l_next(lua_State *L)
4377 LuaPseudoRandom *o = checkobject(L, 1);
4380 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4381 if(!lua_isnil(L, 2))
4382 min = luaL_checkinteger(L, 2);
4383 if(!lua_isnil(L, 3))
4384 max = luaL_checkinteger(L, 3);
4386 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4387 throw LuaError(L, "PseudoRandom.next(): max < min");
4389 if(max - min != 32767 && max - min > 32767/5)
4390 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.");
4391 PseudoRandom &pseudo = o->m_pseudo;
4392 int val = pseudo.next();
4393 val = (val % (max-min+1)) + min;
4394 lua_pushinteger(L, val);
4399 LuaPseudoRandom(int seed):
4408 const PseudoRandom& getItem() const
4412 PseudoRandom& getItem()
4417 // LuaPseudoRandom(seed)
4418 // Creates an LuaPseudoRandom and leaves it on top of stack
4419 static int create_object(lua_State *L)
4421 int seed = luaL_checknumber(L, 1);
4422 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4423 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4424 luaL_getmetatable(L, className);
4425 lua_setmetatable(L, -2);
4429 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4431 luaL_checktype(L, narg, LUA_TUSERDATA);
4432 void *ud = luaL_checkudata(L, narg, className);
4433 if(!ud) luaL_typerror(L, narg, className);
4434 return *(LuaPseudoRandom**)ud; // unbox pointer
4437 static void Register(lua_State *L)
4440 int methodtable = lua_gettop(L);
4441 luaL_newmetatable(L, className);
4442 int metatable = lua_gettop(L);
4444 lua_pushliteral(L, "__metatable");
4445 lua_pushvalue(L, methodtable);
4446 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4448 lua_pushliteral(L, "__index");
4449 lua_pushvalue(L, methodtable);
4450 lua_settable(L, metatable);
4452 lua_pushliteral(L, "__gc");
4453 lua_pushcfunction(L, gc_object);
4454 lua_settable(L, metatable);
4456 lua_pop(L, 1); // drop metatable
4458 luaL_openlib(L, 0, methods, 0); // fill methodtable
4459 lua_pop(L, 1); // drop methodtable
4461 // Can be created from Lua (LuaPseudoRandom(seed))
4462 lua_register(L, className, create_object);
4465 const char LuaPseudoRandom::className[] = "PseudoRandom";
4466 const luaL_reg LuaPseudoRandom::methods[] = {
4467 method(LuaPseudoRandom, next),
4477 class LuaABM : public ActiveBlockModifier
4483 std::set<std::string> m_trigger_contents;
4484 std::set<std::string> m_required_neighbors;
4485 float m_trigger_interval;
4486 u32 m_trigger_chance;
4488 LuaABM(lua_State *L, int id,
4489 const std::set<std::string> &trigger_contents,
4490 const std::set<std::string> &required_neighbors,
4491 float trigger_interval, u32 trigger_chance):
4494 m_trigger_contents(trigger_contents),
4495 m_required_neighbors(required_neighbors),
4496 m_trigger_interval(trigger_interval),
4497 m_trigger_chance(trigger_chance)
4500 virtual std::set<std::string> getTriggerContents()
4502 return m_trigger_contents;
4504 virtual std::set<std::string> getRequiredNeighbors()
4506 return m_required_neighbors;
4508 virtual float getTriggerInterval()
4510 return m_trigger_interval;
4512 virtual u32 getTriggerChance()
4514 return m_trigger_chance;
4516 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4517 u32 active_object_count, u32 active_object_count_wider)
4519 lua_State *L = m_lua;
4522 assert(lua_checkstack(L, 20));
4523 StackUnroller stack_unroller(L);
4525 // Get minetest.registered_abms
4526 lua_getglobal(L, "minetest");
4527 lua_getfield(L, -1, "registered_abms");
4528 luaL_checktype(L, -1, LUA_TTABLE);
4529 int registered_abms = lua_gettop(L);
4531 // Get minetest.registered_abms[m_id]
4532 lua_pushnumber(L, m_id);
4533 lua_gettable(L, registered_abms);
4534 if(lua_isnil(L, -1))
4538 luaL_checktype(L, -1, LUA_TTABLE);
4539 lua_getfield(L, -1, "action");
4540 luaL_checktype(L, -1, LUA_TFUNCTION);
4542 pushnode(L, n, env->getGameDef()->ndef());
4543 lua_pushnumber(L, active_object_count);
4544 lua_pushnumber(L, active_object_count_wider);
4545 if(lua_pcall(L, 4, 0, 0))
4546 script_error(L, "error: %s", lua_tostring(L, -1));
4554 static void read_server_sound_params(lua_State *L, int index,
4555 ServerSoundParams ¶ms)
4558 index = lua_gettop(L) + 1 + index;
4560 params = ServerSoundParams();
4561 if(lua_istable(L, index)){
4562 getfloatfield(L, index, "gain", params.gain);
4563 getstringfield(L, index, "to_player", params.to_player);
4564 lua_getfield(L, index, "pos");
4565 if(!lua_isnil(L, -1)){
4566 v3f p = read_v3f(L, -1)*BS;
4568 params.type = ServerSoundParams::SSP_POSITIONAL;
4571 lua_getfield(L, index, "object");
4572 if(!lua_isnil(L, -1)){
4573 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4574 ServerActiveObject *sao = ObjectRef::getobject(ref);
4576 params.object = sao->getId();
4577 params.type = ServerSoundParams::SSP_OBJECT;
4581 params.max_hear_distance = BS*getfloatfield_default(L, index,
4582 "max_hear_distance", params.max_hear_distance/BS);
4583 getboolfield(L, index, "loop", params.loop);
4592 // Writes a line to dstream
4593 static int l_debug(lua_State *L)
4595 std::string text = lua_tostring(L, 1);
4596 dstream << text << std::endl;
4600 // log([level,] text)
4601 // Writes a line to the logger.
4602 // The one-argument version logs to infostream.
4603 // The two-argument version accept a log level: error, action, info, or verbose.
4604 static int l_log(lua_State *L)
4607 LogMessageLevel level = LMT_INFO;
4608 if(lua_isnone(L, 2))
4610 text = lua_tostring(L, 1);
4614 std::string levelname = luaL_checkstring(L, 1);
4615 text = luaL_checkstring(L, 2);
4616 if(levelname == "error")
4618 else if(levelname == "action")
4620 else if(levelname == "verbose")
4621 level = LMT_VERBOSE;
4623 log_printline(level, text);
4627 // request_shutdown()
4628 static int l_request_shutdown(lua_State *L)
4630 get_server(L)->requestShutdown();
4634 // get_server_status()
4635 static int l_get_server_status(lua_State *L)
4637 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4641 // register_biome_groups({frequencies})
4642 static int l_register_biome_groups(lua_State *L)
4644 luaL_checktype(L, 1, LUA_TTABLE);
4646 if (!lua_istable(L, index))
4647 throw LuaError(L, "register_biome_groups: parameter is not a table");
4649 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4651 verbosestream << "register_biome_groups: BiomeDefManager not active" << std::endl;
4656 for (int i = 1; lua_next(L, index) != 0; i++) {
4657 bmgr->addBiomeGroup(lua_tonumber(L, -1));
4665 // register_biome({lots of stuff})
4666 static int l_register_biome(lua_State *L)
4668 luaL_checktype(L, 1, LUA_TTABLE);
4669 int index = 1, groupid;
4670 std::string nodename;
4672 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
4673 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4675 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
4679 groupid = getintfield_default(L, index, "group_id", 0);
4681 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
4682 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
4683 Biome *b = bmgr->createBiome(terrain);
4685 b->name = getstringfield_default(L, index, "name", "");
4687 if (getstringfield(L, index, "node_top", nodename))
4688 b->n_top = MapNode(ndef->getId(nodename));
4690 b->n_top = MapNode(CONTENT_IGNORE);
4692 if (getstringfield(L, index, "node_filler", nodename))
4693 b->n_filler = MapNode(ndef->getId(nodename));
4695 b->n_filler = b->n_top;
4697 b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
4699 b->height_min = getintfield_default(L, index, "height_min", 0);
4700 b->height_max = getintfield_default(L, index, "height_max", 0);
4701 b->heat_min = getfloatfield_default(L, index, "heat_min", 0.);
4702 b->heat_max = getfloatfield_default(L, index, "heat_max", 0.);
4703 b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
4704 b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
4706 b->np = new NoiseParams; // should read an entire NoiseParams later on...
4707 getfloatfield(L, index, "scale", b->np->scale);
4708 getfloatfield(L, index, "offset", b->np->offset);
4710 b->groupid = (s8)groupid;
4711 b->flags = 0; //reserved
4715 verbosestream << "register_biome: " << b->name << std::endl;
4719 // register_item_raw({lots of stuff})
4720 static int l_register_item_raw(lua_State *L)
4722 luaL_checktype(L, 1, LUA_TTABLE);
4725 // Get the writable item and node definition managers from the server
4726 IWritableItemDefManager *idef =
4727 get_server(L)->getWritableItemDefManager();
4728 IWritableNodeDefManager *ndef =
4729 get_server(L)->getWritableNodeDefManager();
4731 // Check if name is defined
4733 lua_getfield(L, table, "name");
4734 if(lua_isstring(L, -1)){
4735 name = lua_tostring(L, -1);
4736 verbosestream<<"register_item_raw: "<<name<<std::endl;
4738 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4741 // Check if on_use is defined
4744 // Set a distinctive default value to check if this is set
4745 def.node_placement_prediction = "__default";
4747 // Read the item definition
4748 def = read_item_definition(L, table, def);
4750 // Default to having client-side placement prediction for nodes
4751 // ("" in item definition sets it off)
4752 if(def.node_placement_prediction == "__default"){
4753 if(def.type == ITEM_NODE && !def.rightclickable)
4754 def.node_placement_prediction = name;
4756 def.node_placement_prediction = "";
4759 // Register item definition
4760 idef->registerItem(def);
4762 // Read the node definition (content features) and register it
4763 if(def.type == ITEM_NODE)
4765 ContentFeatures f = read_content_features(L, table);
4766 ndef->set(f.name, f);
4769 return 0; /* number of results */
4772 // register_alias_raw(name, convert_to_name)
4773 static int l_register_alias_raw(lua_State *L)
4775 std::string name = luaL_checkstring(L, 1);
4776 std::string convert_to = luaL_checkstring(L, 2);
4778 // Get the writable item definition manager from the server
4779 IWritableItemDefManager *idef =
4780 get_server(L)->getWritableItemDefManager();
4782 idef->registerAlias(name, convert_to);
4784 return 0; /* number of results */
4787 // helper for register_craft
4788 static bool read_craft_recipe_shaped(lua_State *L, int index,
4789 int &width, std::vector<std::string> &recipe)
4792 index = lua_gettop(L) + 1 + index;
4794 if(!lua_istable(L, index))
4799 while(lua_next(L, index) != 0){
4801 // key at index -2 and value at index -1
4802 if(!lua_istable(L, -1))
4804 int table2 = lua_gettop(L);
4806 while(lua_next(L, table2) != 0){
4807 // key at index -2 and value at index -1
4808 if(!lua_isstring(L, -1))
4810 recipe.push_back(lua_tostring(L, -1));
4811 // removes value, keeps key for next iteration
4818 if(colcount != width)
4821 // removes value, keeps key for next iteration
4828 // helper for register_craft
4829 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4830 std::vector<std::string> &recipe)
4833 index = lua_gettop(L) + 1 + index;
4835 if(!lua_istable(L, index))
4839 while(lua_next(L, index) != 0){
4840 // key at index -2 and value at index -1
4841 if(!lua_isstring(L, -1))
4843 recipe.push_back(lua_tostring(L, -1));
4844 // removes value, keeps key for next iteration
4850 // helper for register_craft
4851 static bool read_craft_replacements(lua_State *L, int index,
4852 CraftReplacements &replacements)
4855 index = lua_gettop(L) + 1 + index;
4857 if(!lua_istable(L, index))
4861 while(lua_next(L, index) != 0){
4862 // key at index -2 and value at index -1
4863 if(!lua_istable(L, -1))
4865 lua_rawgeti(L, -1, 1);
4866 if(!lua_isstring(L, -1))
4868 std::string replace_from = lua_tostring(L, -1);
4870 lua_rawgeti(L, -1, 2);
4871 if(!lua_isstring(L, -1))
4873 std::string replace_to = lua_tostring(L, -1);
4875 replacements.pairs.push_back(
4876 std::make_pair(replace_from, replace_to));
4877 // removes value, keeps key for next iteration
4882 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4883 static int l_register_craft(lua_State *L)
4885 //infostream<<"register_craft"<<std::endl;
4886 luaL_checktype(L, 1, LUA_TTABLE);
4889 // Get the writable craft definition manager from the server
4890 IWritableCraftDefManager *craftdef =
4891 get_server(L)->getWritableCraftDefManager();
4893 std::string type = getstringfield_default(L, table, "type", "shaped");
4896 CraftDefinitionShaped
4898 if(type == "shaped"){
4899 std::string output = getstringfield_default(L, table, "output", "");
4901 throw LuaError(L, "Crafting definition is missing an output");
4904 std::vector<std::string> recipe;
4905 lua_getfield(L, table, "recipe");
4906 if(lua_isnil(L, -1))
4907 throw LuaError(L, "Crafting definition is missing a recipe"
4908 " (output=\"" + output + "\")");
4909 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4910 throw LuaError(L, "Invalid crafting recipe"
4911 " (output=\"" + output + "\")");
4913 CraftReplacements replacements;
4914 lua_getfield(L, table, "replacements");
4915 if(!lua_isnil(L, -1))
4917 if(!read_craft_replacements(L, -1, replacements))
4918 throw LuaError(L, "Invalid replacements"
4919 " (output=\"" + output + "\")");
4922 CraftDefinition *def = new CraftDefinitionShaped(
4923 output, width, recipe, replacements);
4924 craftdef->registerCraft(def);
4927 CraftDefinitionShapeless
4929 else if(type == "shapeless"){
4930 std::string output = getstringfield_default(L, table, "output", "");
4932 throw LuaError(L, "Crafting definition (shapeless)"
4933 " is missing an output");
4935 std::vector<std::string> recipe;
4936 lua_getfield(L, table, "recipe");
4937 if(lua_isnil(L, -1))
4938 throw LuaError(L, "Crafting definition (shapeless)"
4939 " is missing a recipe"
4940 " (output=\"" + output + "\")");
4941 if(!read_craft_recipe_shapeless(L, -1, recipe))
4942 throw LuaError(L, "Invalid crafting recipe"
4943 " (output=\"" + output + "\")");
4945 CraftReplacements replacements;
4946 lua_getfield(L, table, "replacements");
4947 if(!lua_isnil(L, -1))
4949 if(!read_craft_replacements(L, -1, replacements))
4950 throw LuaError(L, "Invalid replacements"
4951 " (output=\"" + output + "\")");
4954 CraftDefinition *def = new CraftDefinitionShapeless(
4955 output, recipe, replacements);
4956 craftdef->registerCraft(def);
4959 CraftDefinitionToolRepair
4961 else if(type == "toolrepair"){
4962 float additional_wear = getfloatfield_default(L, table,
4963 "additional_wear", 0.0);
4965 CraftDefinition *def = new CraftDefinitionToolRepair(
4967 craftdef->registerCraft(def);
4970 CraftDefinitionCooking
4972 else if(type == "cooking"){
4973 std::string output = getstringfield_default(L, table, "output", "");
4975 throw LuaError(L, "Crafting definition (cooking)"
4976 " is missing an output");
4978 std::string recipe = getstringfield_default(L, table, "recipe", "");
4980 throw LuaError(L, "Crafting definition (cooking)"
4981 " is missing a recipe"
4982 " (output=\"" + output + "\")");
4984 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4986 CraftReplacements replacements;
4987 lua_getfield(L, table, "replacements");
4988 if(!lua_isnil(L, -1))
4990 if(!read_craft_replacements(L, -1, replacements))
4991 throw LuaError(L, "Invalid replacements"
4992 " (cooking output=\"" + output + "\")");
4995 CraftDefinition *def = new CraftDefinitionCooking(
4996 output, recipe, cooktime, replacements);
4997 craftdef->registerCraft(def);
5002 else if(type == "fuel"){
5003 std::string recipe = getstringfield_default(L, table, "recipe", "");
5005 throw LuaError(L, "Crafting definition (fuel)"
5006 " is missing a recipe");
5008 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
5010 CraftReplacements replacements;
5011 lua_getfield(L, table, "replacements");
5012 if(!lua_isnil(L, -1))
5014 if(!read_craft_replacements(L, -1, replacements))
5015 throw LuaError(L, "Invalid replacements"
5016 " (fuel recipe=\"" + recipe + "\")");
5019 CraftDefinition *def = new CraftDefinitionFuel(
5020 recipe, burntime, replacements);
5021 craftdef->registerCraft(def);
5025 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
5029 return 0; /* number of results */
5032 // setting_set(name, value)
5033 static int l_setting_set(lua_State *L)
5035 const char *name = luaL_checkstring(L, 1);
5036 const char *value = luaL_checkstring(L, 2);
5037 g_settings->set(name, value);
5041 // setting_get(name)
5042 static int l_setting_get(lua_State *L)
5044 const char *name = luaL_checkstring(L, 1);
5046 std::string value = g_settings->get(name);
5047 lua_pushstring(L, value.c_str());
5048 } catch(SettingNotFoundException &e){
5054 // setting_getbool(name)
5055 static int l_setting_getbool(lua_State *L)
5057 const char *name = luaL_checkstring(L, 1);
5059 bool value = g_settings->getBool(name);
5060 lua_pushboolean(L, value);
5061 } catch(SettingNotFoundException &e){
5068 static int l_setting_save(lua_State *L)
5070 get_server(L)->saveConfig();
5074 // chat_send_all(text)
5075 static int l_chat_send_all(lua_State *L)
5077 const char *text = luaL_checkstring(L, 1);
5078 // Get server from registry
5079 Server *server = get_server(L);
5081 server->notifyPlayers(narrow_to_wide(text));
5085 // chat_send_player(name, text)
5086 static int l_chat_send_player(lua_State *L)
5088 const char *name = luaL_checkstring(L, 1);
5089 const char *text = luaL_checkstring(L, 2);
5090 // Get server from registry
5091 Server *server = get_server(L);
5093 server->notifyPlayer(name, narrow_to_wide(text));
5097 // get_player_privs(name, text)
5098 static int l_get_player_privs(lua_State *L)
5100 const char *name = luaL_checkstring(L, 1);
5101 // Get server from registry
5102 Server *server = get_server(L);
5105 int table = lua_gettop(L);
5106 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
5107 for(std::set<std::string>::const_iterator
5108 i = privs_s.begin(); i != privs_s.end(); i++){
5109 lua_pushboolean(L, true);
5110 lua_setfield(L, table, i->c_str());
5112 lua_pushvalue(L, table);
5117 static int l_get_ban_list(lua_State *L)
5119 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
5123 // get_ban_description()
5124 static int l_get_ban_description(lua_State *L)
5126 const char * ip_or_name = luaL_checkstring(L, 1);
5127 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
5132 static int l_ban_player(lua_State *L)
5134 const char * name = luaL_checkstring(L, 1);
5135 Player *player = get_env(L)->getPlayer(name);
5138 lua_pushboolean(L, false); // no such player
5143 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
5144 std::string ip_str = addr.serializeString();
5145 get_server(L)->setIpBanned(ip_str, name);
5147 catch(con::PeerNotFoundException) // unlikely
5149 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
5150 lua_pushboolean(L, false); // error
5153 lua_pushboolean(L, true);
5157 // unban_player_or_ip()
5158 static int l_unban_player_of_ip(lua_State *L)
5160 const char * ip_or_name = luaL_checkstring(L, 1);
5161 get_server(L)->unsetIpBanned(ip_or_name);
5162 lua_pushboolean(L, true);
5166 // get_inventory(location)
5167 static int l_get_inventory(lua_State *L)
5169 InventoryLocation loc;
5171 std::string type = checkstringfield(L, 1, "type");
5172 if(type == "player"){
5173 std::string name = checkstringfield(L, 1, "name");
5174 loc.setPlayer(name);
5175 } else if(type == "node"){
5176 lua_getfield(L, 1, "pos");
5177 v3s16 pos = check_v3s16(L, -1);
5178 loc.setNodeMeta(pos);
5179 } else if(type == "detached"){
5180 std::string name = checkstringfield(L, 1, "name");
5181 loc.setDetached(name);
5184 if(get_server(L)->getInventory(loc) != NULL)
5185 InvRef::create(L, loc);
5191 // create_detached_inventory_raw(name)
5192 static int l_create_detached_inventory_raw(lua_State *L)
5194 const char *name = luaL_checkstring(L, 1);
5195 if(get_server(L)->createDetachedInventory(name) != NULL){
5196 InventoryLocation loc;
5197 loc.setDetached(name);
5198 InvRef::create(L, loc);
5205 // show_formspec(playername,formname,formspec)
5206 static int l_show_formspec(lua_State *L)
5208 const char *playername = luaL_checkstring(L, 1);
5209 const char *formname = luaL_checkstring(L, 2);
5210 const char *formspec = luaL_checkstring(L, 3);
5212 if(get_server(L)->showFormspec(playername,formspec,formname))
5214 lua_pushboolean(L, true);
5216 lua_pushboolean(L, false);
5221 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5222 static int l_get_dig_params(lua_State *L)
5224 std::map<std::string, int> groups;
5225 read_groups(L, 1, groups);
5226 ToolCapabilities tp = read_tool_capabilities(L, 2);
5227 if(lua_isnoneornil(L, 3))
5228 push_dig_params(L, getDigParams(groups, &tp));
5230 push_dig_params(L, getDigParams(groups, &tp,
5231 luaL_checknumber(L, 3)));
5235 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5236 static int l_get_hit_params(lua_State *L)
5238 std::map<std::string, int> groups;
5239 read_groups(L, 1, groups);
5240 ToolCapabilities tp = read_tool_capabilities(L, 2);
5241 if(lua_isnoneornil(L, 3))
5242 push_hit_params(L, getHitParams(groups, &tp));
5244 push_hit_params(L, getHitParams(groups, &tp,
5245 luaL_checknumber(L, 3)));
5249 // get_current_modname()
5250 static int l_get_current_modname(lua_State *L)
5252 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5256 // get_modpath(modname)
5257 static int l_get_modpath(lua_State *L)
5259 std::string modname = luaL_checkstring(L, 1);
5261 if(modname == "__builtin"){
5262 std::string path = get_server(L)->getBuiltinLuaPath();
5263 lua_pushstring(L, path.c_str());
5266 const ModSpec *mod = get_server(L)->getModSpec(modname);
5271 lua_pushstring(L, mod->path.c_str());
5276 // the returned list is sorted alphabetically for you
5277 static int l_get_modnames(lua_State *L)
5279 // Get a list of mods
5280 core::list<std::string> mods_unsorted, mods_sorted;
5281 get_server(L)->getModNames(mods_unsorted);
5283 // Take unsorted items from mods_unsorted and sort them into
5284 // mods_sorted; not great performance but the number of mods on a
5285 // server will likely be small.
5286 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5287 i != mods_unsorted.end(); i++)
5290 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5291 x != mods_unsorted.end(); x++)
5293 // I doubt anybody using Minetest will be using
5294 // anything not ASCII based :)
5295 if((*i).compare(*x) <= 0)
5297 mods_sorted.insert_before(x, *i);
5303 mods_sorted.push_back(*i);
5306 // Get the table insertion function from Lua.
5307 lua_getglobal(L, "table");
5308 lua_getfield(L, -1, "insert");
5309 int insertion_func = lua_gettop(L);
5311 // Package them up for Lua
5313 int new_table = lua_gettop(L);
5314 core::list<std::string>::Iterator i = mods_sorted.begin();
5315 while(i != mods_sorted.end())
5317 lua_pushvalue(L, insertion_func);
5318 lua_pushvalue(L, new_table);
5319 lua_pushstring(L, (*i).c_str());
5320 if(lua_pcall(L, 2, 0, 0) != 0)
5322 script_error(L, "error: %s", lua_tostring(L, -1));
5330 static int l_get_worldpath(lua_State *L)
5332 std::string worldpath = get_server(L)->getWorldPath();
5333 lua_pushstring(L, worldpath.c_str());
5337 // sound_play(spec, parameters)
5338 static int l_sound_play(lua_State *L)
5340 SimpleSoundSpec spec;
5341 read_soundspec(L, 1, spec);
5342 ServerSoundParams params;
5343 read_server_sound_params(L, 2, params);
5344 s32 handle = get_server(L)->playSound(spec, params);
5345 lua_pushinteger(L, handle);
5349 // sound_stop(handle)
5350 static int l_sound_stop(lua_State *L)
5352 int handle = luaL_checkinteger(L, 1);
5353 get_server(L)->stopSound(handle);
5357 // is_singleplayer()
5358 static int l_is_singleplayer(lua_State *L)
5360 lua_pushboolean(L, get_server(L)->isSingleplayer());
5364 // get_password_hash(name, raw_password)
5365 static int l_get_password_hash(lua_State *L)
5367 std::string name = luaL_checkstring(L, 1);
5368 std::string raw_password = luaL_checkstring(L, 2);
5369 std::string hash = translatePassword(name,
5370 narrow_to_wide(raw_password));
5371 lua_pushstring(L, hash.c_str());
5375 // notify_authentication_modified(name)
5376 static int l_notify_authentication_modified(lua_State *L)
5378 std::string name = "";
5379 if(lua_isstring(L, 1))
5380 name = lua_tostring(L, 1);
5381 get_server(L)->reportPrivsModified(name);
5385 // get_craft_result(input)
5386 static int l_get_craft_result(lua_State *L)
5389 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5390 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5391 es_CraftMethod, CRAFT_METHOD_NORMAL);
5393 lua_getfield(L, input_i, "width");
5394 if(lua_isnumber(L, -1))
5395 width = luaL_checkinteger(L, -1);
5397 lua_getfield(L, input_i, "items");
5398 std::vector<ItemStack> items = read_items(L, -1);
5399 lua_pop(L, 1); // items
5401 IGameDef *gdef = get_server(L);
5402 ICraftDefManager *cdef = gdef->cdef();
5403 CraftInput input(method, width, items);
5405 bool got = cdef->getCraftResult(input, output, true, gdef);
5406 lua_newtable(L); // output table
5409 item.deSerialize(output.item, gdef->idef());
5410 LuaItemStack::create(L, item);
5411 lua_setfield(L, -2, "item");
5412 setintfield(L, -1, "time", output.time);
5414 LuaItemStack::create(L, ItemStack());
5415 lua_setfield(L, -2, "item");
5416 setintfield(L, -1, "time", 0);
5418 lua_newtable(L); // decremented input table
5419 lua_pushstring(L, method_s.c_str());
5420 lua_setfield(L, -2, "method");
5421 lua_pushinteger(L, width);
5422 lua_setfield(L, -2, "width");
5423 push_items(L, input.items);
5424 lua_setfield(L, -2, "items");
5428 // get_craft_recipe(result item)
5429 static int l_get_craft_recipe(lua_State *L)
5434 std::string o_item = luaL_checkstring(L,input_i);
5436 IGameDef *gdef = get_server(L);
5437 ICraftDefManager *cdef = gdef->cdef();
5439 CraftOutput output(o_item,0);
5440 bool got = cdef->getCraftRecipe(input, output, gdef);
5441 lua_newtable(L); // output table
5444 for(std::vector<ItemStack>::const_iterator
5445 i = input.items.begin();
5446 i != input.items.end(); i++, k++)
5452 sprintf(tmp,"%d",k);
5453 lua_pushstring(L,tmp);
5454 lua_pushstring(L,i->name.c_str());
5455 lua_settable(L, -3);
5457 lua_setfield(L, -2, "items");
5458 setintfield(L, -1, "width", input.width);
5459 switch (input.method) {
5460 case CRAFT_METHOD_NORMAL:
5461 lua_pushstring(L,"normal");
5463 case CRAFT_METHOD_COOKING:
5464 lua_pushstring(L,"cooking");
5466 case CRAFT_METHOD_FUEL:
5467 lua_pushstring(L,"fuel");
5470 lua_pushstring(L,"unknown");
5472 lua_setfield(L, -2, "type");
5475 lua_setfield(L, -2, "items");
5476 setintfield(L, -1, "width", 0);
5481 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5482 static int l_rollback_get_last_node_actor(lua_State *L)
5484 v3s16 p = read_v3s16(L, 1);
5485 int range = luaL_checknumber(L, 2);
5486 int seconds = luaL_checknumber(L, 3);
5487 Server *server = get_server(L);
5488 IRollbackManager *rollback = server->getRollbackManager();
5490 int act_seconds = 0;
5491 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5492 lua_pushstring(L, actor.c_str());
5493 push_v3s16(L, act_p);
5494 lua_pushnumber(L, act_seconds);
5498 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5499 static int l_rollback_revert_actions_by(lua_State *L)
5501 std::string actor = luaL_checkstring(L, 1);
5502 int seconds = luaL_checknumber(L, 2);
5503 Server *server = get_server(L);
5504 IRollbackManager *rollback = server->getRollbackManager();
5505 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5506 std::list<std::string> log;
5507 bool success = server->rollbackRevertActions(actions, &log);
5508 // Push boolean result
5509 lua_pushboolean(L, success);
5510 // Get the table insert function and push the log table
5511 lua_getglobal(L, "table");
5512 lua_getfield(L, -1, "insert");
5513 int table_insert = lua_gettop(L);
5515 int table = lua_gettop(L);
5516 for(std::list<std::string>::const_iterator i = log.begin();
5517 i != log.end(); i++)
5519 lua_pushvalue(L, table_insert);
5520 lua_pushvalue(L, table);
5521 lua_pushstring(L, i->c_str());
5522 if(lua_pcall(L, 2, 0, 0))
5523 script_error(L, "error: %s", lua_tostring(L, -1));
5525 lua_remove(L, -2); // Remove table
5526 lua_remove(L, -2); // Remove insert
5530 static const struct luaL_Reg minetest_f [] = {
5533 {"request_shutdown", l_request_shutdown},
5534 {"get_server_status", l_get_server_status},
5535 {"register_item_raw", l_register_item_raw},
5536 {"register_alias_raw", l_register_alias_raw},
5537 {"register_craft", l_register_craft},
5538 {"register_biome", l_register_biome},
5539 {"register_biome_groups", l_register_biome_groups},
5540 {"setting_set", l_setting_set},
5541 {"setting_get", l_setting_get},
5542 {"setting_getbool", l_setting_getbool},
5543 {"setting_save",l_setting_save},
5544 {"chat_send_all", l_chat_send_all},
5545 {"chat_send_player", l_chat_send_player},
5546 {"get_player_privs", l_get_player_privs},
5547 {"get_ban_list", l_get_ban_list},
5548 {"get_ban_description", l_get_ban_description},
5549 {"ban_player", l_ban_player},
5550 {"unban_player_or_ip", l_unban_player_of_ip},
5551 {"get_inventory", l_get_inventory},
5552 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5553 {"show_formspec", l_show_formspec},
5554 {"get_dig_params", l_get_dig_params},
5555 {"get_hit_params", l_get_hit_params},
5556 {"get_current_modname", l_get_current_modname},
5557 {"get_modpath", l_get_modpath},
5558 {"get_modnames", l_get_modnames},
5559 {"get_worldpath", l_get_worldpath},
5560 {"sound_play", l_sound_play},
5561 {"sound_stop", l_sound_stop},
5562 {"is_singleplayer", l_is_singleplayer},
5563 {"get_password_hash", l_get_password_hash},
5564 {"notify_authentication_modified", l_notify_authentication_modified},
5565 {"get_craft_result", l_get_craft_result},
5566 {"get_craft_recipe", l_get_craft_recipe},
5567 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5568 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5573 Main export function
5576 void scriptapi_export(lua_State *L, Server *server)
5579 assert(lua_checkstack(L, 20));
5580 verbosestream<<"scriptapi_export()"<<std::endl;
5581 StackUnroller stack_unroller(L);
5583 // Store server as light userdata in registry
5584 lua_pushlightuserdata(L, server);
5585 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5587 // Register global functions in table minetest
5589 luaL_register(L, NULL, minetest_f);
5590 lua_setglobal(L, "minetest");
5592 // Get the main minetest table
5593 lua_getglobal(L, "minetest");
5595 // Add tables to minetest
5597 lua_setfield(L, -2, "object_refs");
5599 lua_setfield(L, -2, "luaentities");
5601 // Register wrappers
5602 LuaItemStack::Register(L);
5603 InvRef::Register(L);
5604 NodeMetaRef::Register(L);
5605 NodeTimerRef::Register(L);
5606 ObjectRef::Register(L);
5607 EnvRef::Register(L);
5608 LuaPseudoRandom::Register(L);
5609 LuaPerlinNoise::Register(L);
5610 LuaPerlinNoiseMap::Register(L);
5613 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5614 const std::string &modname)
5616 ModNameStorer modnamestorer(L, modname);
5618 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5620 errorstream<<"Error loading mod \""<<modname
5621 <<"\": modname does not follow naming conventions: "
5622 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5626 bool success = false;
5629 success = script_load(L, scriptpath.c_str());
5632 errorstream<<"Error loading mod \""<<modname
5633 <<"\": "<<e.what()<<std::endl;
5639 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5642 assert(lua_checkstack(L, 20));
5643 verbosestream<<"scriptapi_add_environment"<<std::endl;
5644 StackUnroller stack_unroller(L);
5646 // Create EnvRef on stack
5647 EnvRef::create(L, env);
5648 int envref = lua_gettop(L);
5650 // minetest.env = envref
5651 lua_getglobal(L, "minetest");
5652 luaL_checktype(L, -1, LUA_TTABLE);
5653 lua_pushvalue(L, envref);
5654 lua_setfield(L, -2, "env");
5656 // Store environment as light userdata in registry
5657 lua_pushlightuserdata(L, env);
5658 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5661 Add ActiveBlockModifiers to environment
5664 // Get minetest.registered_abms
5665 lua_getglobal(L, "minetest");
5666 lua_getfield(L, -1, "registered_abms");
5667 luaL_checktype(L, -1, LUA_TTABLE);
5668 int registered_abms = lua_gettop(L);
5670 if(lua_istable(L, registered_abms)){
5671 int table = lua_gettop(L);
5673 while(lua_next(L, table) != 0){
5674 // key at index -2 and value at index -1
5675 int id = lua_tonumber(L, -2);
5676 int current_abm = lua_gettop(L);
5678 std::set<std::string> trigger_contents;
5679 lua_getfield(L, current_abm, "nodenames");
5680 if(lua_istable(L, -1)){
5681 int table = lua_gettop(L);
5683 while(lua_next(L, table) != 0){
5684 // key at index -2 and value at index -1
5685 luaL_checktype(L, -1, LUA_TSTRING);
5686 trigger_contents.insert(lua_tostring(L, -1));
5687 // removes value, keeps key for next iteration
5690 } else if(lua_isstring(L, -1)){
5691 trigger_contents.insert(lua_tostring(L, -1));
5695 std::set<std::string> required_neighbors;
5696 lua_getfield(L, current_abm, "neighbors");
5697 if(lua_istable(L, -1)){
5698 int table = lua_gettop(L);
5700 while(lua_next(L, table) != 0){
5701 // key at index -2 and value at index -1
5702 luaL_checktype(L, -1, LUA_TSTRING);
5703 required_neighbors.insert(lua_tostring(L, -1));
5704 // removes value, keeps key for next iteration
5707 } else if(lua_isstring(L, -1)){
5708 required_neighbors.insert(lua_tostring(L, -1));
5712 float trigger_interval = 10.0;
5713 getfloatfield(L, current_abm, "interval", trigger_interval);
5715 int trigger_chance = 50;
5716 getintfield(L, current_abm, "chance", trigger_chance);
5718 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5719 required_neighbors, trigger_interval, trigger_chance);
5721 env->addActiveBlockModifier(abm);
5723 // removes value, keeps key for next iteration
5731 // Dump stack top with the dump2 function
5732 static void dump2(lua_State *L, const char *name)
5734 // Dump object (debug)
5735 lua_getglobal(L, "dump2");
5736 luaL_checktype(L, -1, LUA_TFUNCTION);
5737 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5738 lua_pushstring(L, name);
5739 if(lua_pcall(L, 2, 0, 0))
5740 script_error(L, "error: %s", lua_tostring(L, -1));
5748 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5751 assert(lua_checkstack(L, 20));
5752 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5753 StackUnroller stack_unroller(L);
5755 // Create object on stack
5756 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5757 int object = lua_gettop(L);
5759 // Get minetest.object_refs table
5760 lua_getglobal(L, "minetest");
5761 lua_getfield(L, -1, "object_refs");
5762 luaL_checktype(L, -1, LUA_TTABLE);
5763 int objectstable = lua_gettop(L);
5765 // object_refs[id] = object
5766 lua_pushnumber(L, cobj->getId()); // Push id
5767 lua_pushvalue(L, object); // Copy object to top of stack
5768 lua_settable(L, objectstable);
5771 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5774 assert(lua_checkstack(L, 20));
5775 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5776 StackUnroller stack_unroller(L);
5778 // Get minetest.object_refs table
5779 lua_getglobal(L, "minetest");
5780 lua_getfield(L, -1, "object_refs");
5781 luaL_checktype(L, -1, LUA_TTABLE);
5782 int objectstable = lua_gettop(L);
5784 // Get object_refs[id]
5785 lua_pushnumber(L, cobj->getId()); // Push id
5786 lua_gettable(L, objectstable);
5787 // Set object reference to NULL
5788 ObjectRef::set_null(L);
5789 lua_pop(L, 1); // pop object
5791 // Set object_refs[id] = nil
5792 lua_pushnumber(L, cobj->getId()); // Push id
5794 lua_settable(L, objectstable);
5801 // What scriptapi_run_callbacks does with the return values of callbacks.
5802 // Regardless of the mode, if only one callback is defined,
5803 // its return value is the total return value.
5804 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5805 enum RunCallbacksMode
5807 // Returns the return value of the first callback
5808 // Returns nil if list of callbacks is empty
5809 RUN_CALLBACKS_MODE_FIRST,
5810 // Returns the return value of the last callback
5811 // Returns nil if list of callbacks is empty
5812 RUN_CALLBACKS_MODE_LAST,
5813 // If any callback returns a false value, the first such is returned
5814 // Otherwise, the first callback's return value (trueish) is returned
5815 // Returns true if list of callbacks is empty
5816 RUN_CALLBACKS_MODE_AND,
5817 // Like above, but stops calling callbacks (short circuit)
5818 // after seeing the first false value
5819 RUN_CALLBACKS_MODE_AND_SC,
5820 // If any callback returns a true value, the first such is returned
5821 // Otherwise, the first callback's return value (falseish) is returned
5822 // Returns false if list of callbacks is empty
5823 RUN_CALLBACKS_MODE_OR,
5824 // Like above, but stops calling callbacks (short circuit)
5825 // after seeing the first true value
5826 RUN_CALLBACKS_MODE_OR_SC,
5827 // Note: "a true value" and "a false value" refer to values that
5828 // are converted by lua_toboolean to true or false, respectively.
5831 // Push the list of callbacks (a lua table).
5832 // Then push nargs arguments.
5833 // Then call this function, which
5834 // - runs the callbacks
5835 // - removes the table and arguments from the lua stack
5836 // - pushes the return value, computed depending on mode
5837 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5838 RunCallbacksMode mode)
5840 // Insert the return value into the lua stack, below the table
5841 assert(lua_gettop(L) >= nargs + 1);
5843 lua_insert(L, -(nargs + 1) - 1);
5844 // Stack now looks like this:
5845 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5847 int rv = lua_gettop(L) - nargs - 1;
5849 int arg = table + 1;
5851 luaL_checktype(L, table, LUA_TTABLE);
5855 bool first_loop = true;
5856 while(lua_next(L, table) != 0){
5857 // key at index -2 and value at index -1
5858 luaL_checktype(L, -1, LUA_TFUNCTION);
5860 for(int i = 0; i < nargs; i++)
5861 lua_pushvalue(L, arg+i);
5862 if(lua_pcall(L, nargs, 1, 0))
5863 script_error(L, "error: %s", lua_tostring(L, -1));
5865 // Move return value to designated space in stack
5868 // Result of first callback is always moved
5872 // Otherwise, what happens depends on the mode
5873 if(mode == RUN_CALLBACKS_MODE_FIRST)
5875 else if(mode == RUN_CALLBACKS_MODE_LAST)
5877 else if(mode == RUN_CALLBACKS_MODE_AND ||
5878 mode == RUN_CALLBACKS_MODE_AND_SC){
5879 if((bool)lua_toboolean(L, rv) == true &&
5880 (bool)lua_toboolean(L, -1) == false)
5885 else if(mode == RUN_CALLBACKS_MODE_OR ||
5886 mode == RUN_CALLBACKS_MODE_OR_SC){
5887 if((bool)lua_toboolean(L, rv) == false &&
5888 (bool)lua_toboolean(L, -1) == true)
5897 // Handle short circuit modes
5898 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5899 (bool)lua_toboolean(L, rv) == false)
5901 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5902 (bool)lua_toboolean(L, rv) == true)
5905 // value removed, keep key for next iteration
5908 // Remove stuff from stack, leaving only the return value
5911 // Fix return value in case no callbacks were called
5913 if(mode == RUN_CALLBACKS_MODE_AND ||
5914 mode == RUN_CALLBACKS_MODE_AND_SC){
5916 lua_pushboolean(L, true);
5918 else if(mode == RUN_CALLBACKS_MODE_OR ||
5919 mode == RUN_CALLBACKS_MODE_OR_SC){
5921 lua_pushboolean(L, false);
5926 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5927 const std::string &message)
5930 assert(lua_checkstack(L, 20));
5931 StackUnroller stack_unroller(L);
5933 // Get minetest.registered_on_chat_messages
5934 lua_getglobal(L, "minetest");
5935 lua_getfield(L, -1, "registered_on_chat_messages");
5937 lua_pushstring(L, name.c_str());
5938 lua_pushstring(L, message.c_str());
5939 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5940 bool ate = lua_toboolean(L, -1);
5944 void scriptapi_on_shutdown(lua_State *L)
5947 assert(lua_checkstack(L, 20));
5948 StackUnroller stack_unroller(L);
5950 // Get registered shutdown hooks
5951 lua_getglobal(L, "minetest");
5952 lua_getfield(L, -1, "registered_on_shutdown");
5954 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5957 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5960 assert(lua_checkstack(L, 20));
5961 StackUnroller stack_unroller(L);
5963 // Get minetest.registered_on_newplayers
5964 lua_getglobal(L, "minetest");
5965 lua_getfield(L, -1, "registered_on_newplayers");
5967 objectref_get_or_create(L, player);
5968 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5971 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5974 assert(lua_checkstack(L, 20));
5975 StackUnroller stack_unroller(L);
5977 // Get minetest.registered_on_dieplayers
5978 lua_getglobal(L, "minetest");
5979 lua_getfield(L, -1, "registered_on_dieplayers");
5981 objectref_get_or_create(L, player);
5982 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5985 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5988 assert(lua_checkstack(L, 20));
5989 StackUnroller stack_unroller(L);
5991 // Get minetest.registered_on_respawnplayers
5992 lua_getglobal(L, "minetest");
5993 lua_getfield(L, -1, "registered_on_respawnplayers");
5995 objectref_get_or_create(L, player);
5996 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5997 bool positioning_handled_by_some = lua_toboolean(L, -1);
5998 return positioning_handled_by_some;
6001 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
6004 assert(lua_checkstack(L, 20));
6005 StackUnroller stack_unroller(L);
6007 // Get minetest.registered_on_joinplayers
6008 lua_getglobal(L, "minetest");
6009 lua_getfield(L, -1, "registered_on_joinplayers");
6011 objectref_get_or_create(L, player);
6012 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6015 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
6018 assert(lua_checkstack(L, 20));
6019 StackUnroller stack_unroller(L);
6021 // Get minetest.registered_on_leaveplayers
6022 lua_getglobal(L, "minetest");
6023 lua_getfield(L, -1, "registered_on_leaveplayers");
6025 objectref_get_or_create(L, player);
6026 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6029 static void get_auth_handler(lua_State *L)
6031 lua_getglobal(L, "minetest");
6032 lua_getfield(L, -1, "registered_auth_handler");
6033 if(lua_isnil(L, -1)){
6035 lua_getfield(L, -1, "builtin_auth_handler");
6037 if(lua_type(L, -1) != LUA_TTABLE)
6038 throw LuaError(L, "Authentication handler table not valid");
6041 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
6042 std::string *dst_password, std::set<std::string> *dst_privs)
6045 assert(lua_checkstack(L, 20));
6046 StackUnroller stack_unroller(L);
6048 get_auth_handler(L);
6049 lua_getfield(L, -1, "get_auth");
6050 if(lua_type(L, -1) != LUA_TFUNCTION)
6051 throw LuaError(L, "Authentication handler missing get_auth");
6052 lua_pushstring(L, playername.c_str());
6053 if(lua_pcall(L, 1, 1, 0))
6054 script_error(L, "error: %s", lua_tostring(L, -1));
6056 // nil = login not allowed
6057 if(lua_isnil(L, -1))
6059 luaL_checktype(L, -1, LUA_TTABLE);
6061 std::string password;
6062 bool found = getstringfield(L, -1, "password", password);
6064 throw LuaError(L, "Authentication handler didn't return password");
6066 *dst_password = password;
6068 lua_getfield(L, -1, "privileges");
6069 if(!lua_istable(L, -1))
6071 "Authentication handler didn't return privilege table");
6073 read_privileges(L, -1, *dst_privs);
6079 void scriptapi_create_auth(lua_State *L, const std::string &playername,
6080 const std::string &password)
6083 assert(lua_checkstack(L, 20));
6084 StackUnroller stack_unroller(L);
6086 get_auth_handler(L);
6087 lua_getfield(L, -1, "create_auth");
6088 if(lua_type(L, -1) != LUA_TFUNCTION)
6089 throw LuaError(L, "Authentication handler missing create_auth");
6090 lua_pushstring(L, playername.c_str());
6091 lua_pushstring(L, password.c_str());
6092 if(lua_pcall(L, 2, 0, 0))
6093 script_error(L, "error: %s", lua_tostring(L, -1));
6096 bool scriptapi_set_password(lua_State *L, const std::string &playername,
6097 const std::string &password)
6100 assert(lua_checkstack(L, 20));
6101 StackUnroller stack_unroller(L);
6103 get_auth_handler(L);
6104 lua_getfield(L, -1, "set_password");
6105 if(lua_type(L, -1) != LUA_TFUNCTION)
6106 throw LuaError(L, "Authentication handler missing set_password");
6107 lua_pushstring(L, playername.c_str());
6108 lua_pushstring(L, password.c_str());
6109 if(lua_pcall(L, 2, 1, 0))
6110 script_error(L, "error: %s", lua_tostring(L, -1));
6111 return lua_toboolean(L, -1);
6118 void scriptapi_on_player_receive_fields(lua_State *L,
6119 ServerActiveObject *player,
6120 const std::string &formname,
6121 const std::map<std::string, std::string> &fields)
6124 assert(lua_checkstack(L, 20));
6125 StackUnroller stack_unroller(L);
6127 // Get minetest.registered_on_chat_messages
6128 lua_getglobal(L, "minetest");
6129 lua_getfield(L, -1, "registered_on_player_receive_fields");
6132 objectref_get_or_create(L, player);
6134 lua_pushstring(L, formname.c_str());
6137 for(std::map<std::string, std::string>::const_iterator
6138 i = fields.begin(); i != fields.end(); i++){
6139 const std::string &name = i->first;
6140 const std::string &value = i->second;
6141 lua_pushstring(L, name.c_str());
6142 lua_pushlstring(L, value.c_str(), value.size());
6143 lua_settable(L, -3);
6145 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
6149 item callbacks and node callbacks
6152 // Retrieves minetest.registered_items[name][callbackname]
6153 // If that is nil or on error, return false and stack is unchanged
6154 // If that is a function, returns true and pushes the
6155 // function onto the stack
6156 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
6157 // is tried instead so unknown items can still be manipulated to some degree
6158 static bool get_item_callback(lua_State *L,
6159 const char *name, const char *callbackname)
6161 lua_getglobal(L, "minetest");
6162 lua_getfield(L, -1, "registered_items");
6164 luaL_checktype(L, -1, LUA_TTABLE);
6165 lua_getfield(L, -1, name);
6167 // Should be a table
6168 if(lua_type(L, -1) != LUA_TTABLE)
6170 // Report error and clean up
6171 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6174 // Try minetest.nodedef_default instead
6175 lua_getglobal(L, "minetest");
6176 lua_getfield(L, -1, "nodedef_default");
6178 luaL_checktype(L, -1, LUA_TTABLE);
6180 lua_getfield(L, -1, callbackname);
6182 // Should be a function or nil
6183 if(lua_type(L, -1) == LUA_TFUNCTION)
6187 else if(lua_isnil(L, -1))
6194 errorstream<<"Item \""<<name<<"\" callback \""
6195 <<callbackname<<" is not a function"<<std::endl;
6201 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6202 ServerActiveObject *dropper, v3f pos)
6205 assert(lua_checkstack(L, 20));
6206 StackUnroller stack_unroller(L);
6208 // Push callback function on stack
6209 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6213 LuaItemStack::create(L, item);
6214 objectref_get_or_create(L, dropper);
6215 pushFloatPos(L, pos);
6216 if(lua_pcall(L, 3, 1, 0))
6217 script_error(L, "error: %s", lua_tostring(L, -1));
6218 if(!lua_isnil(L, -1))
6219 item = read_item(L, -1);
6223 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6224 ServerActiveObject *placer, const PointedThing &pointed)
6227 assert(lua_checkstack(L, 20));
6228 StackUnroller stack_unroller(L);
6230 // Push callback function on stack
6231 if(!get_item_callback(L, item.name.c_str(), "on_place"))
6235 LuaItemStack::create(L, item);
6236 objectref_get_or_create(L, placer);
6237 push_pointed_thing(L, pointed);
6238 if(lua_pcall(L, 3, 1, 0))
6239 script_error(L, "error: %s", lua_tostring(L, -1));
6240 if(!lua_isnil(L, -1))
6241 item = read_item(L, -1);
6245 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6246 ServerActiveObject *user, const PointedThing &pointed)
6249 assert(lua_checkstack(L, 20));
6250 StackUnroller stack_unroller(L);
6252 // Push callback function on stack
6253 if(!get_item_callback(L, item.name.c_str(), "on_use"))
6257 LuaItemStack::create(L, item);
6258 objectref_get_or_create(L, user);
6259 push_pointed_thing(L, pointed);
6260 if(lua_pcall(L, 3, 1, 0))
6261 script_error(L, "error: %s", lua_tostring(L, -1));
6262 if(!lua_isnil(L, -1))
6263 item = read_item(L, -1);
6267 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6268 ServerActiveObject *puncher)
6271 assert(lua_checkstack(L, 20));
6272 StackUnroller stack_unroller(L);
6274 INodeDefManager *ndef = get_server(L)->ndef();
6276 // Push callback function on stack
6277 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6282 pushnode(L, node, ndef);
6283 objectref_get_or_create(L, puncher);
6284 if(lua_pcall(L, 3, 0, 0))
6285 script_error(L, "error: %s", lua_tostring(L, -1));
6289 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6290 ServerActiveObject *digger)
6293 assert(lua_checkstack(L, 20));
6294 StackUnroller stack_unroller(L);
6296 INodeDefManager *ndef = get_server(L)->ndef();
6298 // Push callback function on stack
6299 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6304 pushnode(L, node, ndef);
6305 objectref_get_or_create(L, digger);
6306 if(lua_pcall(L, 3, 0, 0))
6307 script_error(L, "error: %s", lua_tostring(L, -1));
6311 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6314 assert(lua_checkstack(L, 20));
6315 StackUnroller stack_unroller(L);
6317 INodeDefManager *ndef = get_server(L)->ndef();
6319 // Push callback function on stack
6320 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6325 if(lua_pcall(L, 1, 0, 0))
6326 script_error(L, "error: %s", lua_tostring(L, -1));
6329 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6332 assert(lua_checkstack(L, 20));
6333 StackUnroller stack_unroller(L);
6335 INodeDefManager *ndef = get_server(L)->ndef();
6337 // Push callback function on stack
6338 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6343 if(lua_pcall(L, 1, 0, 0))
6344 script_error(L, "error: %s", lua_tostring(L, -1));
6347 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6350 assert(lua_checkstack(L, 20));
6351 StackUnroller stack_unroller(L);
6353 INodeDefManager *ndef = get_server(L)->ndef();
6355 // Push callback function on stack
6356 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6361 pushnode(L, node, ndef);
6362 if(lua_pcall(L, 2, 0, 0))
6363 script_error(L, "error: %s", lua_tostring(L, -1));
6366 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6369 assert(lua_checkstack(L, 20));
6370 StackUnroller stack_unroller(L);
6372 INodeDefManager *ndef = get_server(L)->ndef();
6374 // Push callback function on stack
6375 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6380 lua_pushnumber(L,dtime);
6381 if(lua_pcall(L, 2, 1, 0))
6382 script_error(L, "error: %s", lua_tostring(L, -1));
6383 if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6389 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6390 const std::string &formname,
6391 const std::map<std::string, std::string> &fields,
6392 ServerActiveObject *sender)
6395 assert(lua_checkstack(L, 20));
6396 StackUnroller stack_unroller(L);
6398 INodeDefManager *ndef = get_server(L)->ndef();
6400 // If node doesn't exist, we don't know what callback to call
6401 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6402 if(node.getContent() == CONTENT_IGNORE)
6405 // Push callback function on stack
6406 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6413 lua_pushstring(L, formname.c_str());
6416 for(std::map<std::string, std::string>::const_iterator
6417 i = fields.begin(); i != fields.end(); i++){
6418 const std::string &name = i->first;
6419 const std::string &value = i->second;
6420 lua_pushstring(L, name.c_str());
6421 lua_pushlstring(L, value.c_str(), value.size());
6422 lua_settable(L, -3);
6425 objectref_get_or_create(L, sender);
6426 if(lua_pcall(L, 4, 0, 0))
6427 script_error(L, "error: %s", lua_tostring(L, -1));
6431 Node metadata inventory callbacks
6434 // Return number of accepted items to be moved
6435 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6436 const std::string &from_list, int from_index,
6437 const std::string &to_list, int to_index,
6438 int count, ServerActiveObject *player)
6441 assert(lua_checkstack(L, 20));
6442 StackUnroller stack_unroller(L);
6444 INodeDefManager *ndef = get_server(L)->ndef();
6446 // If node doesn't exist, we don't know what callback to call
6447 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6448 if(node.getContent() == CONTENT_IGNORE)
6451 // Push callback function on stack
6452 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6453 "allow_metadata_inventory_move"))
6456 // function(pos, from_list, from_index, to_list, to_index, count, player)
6460 lua_pushstring(L, from_list.c_str());
6462 lua_pushinteger(L, from_index + 1);
6464 lua_pushstring(L, to_list.c_str());
6466 lua_pushinteger(L, to_index + 1);
6468 lua_pushinteger(L, count);
6470 objectref_get_or_create(L, player);
6471 if(lua_pcall(L, 7, 1, 0))
6472 script_error(L, "error: %s", lua_tostring(L, -1));
6473 if(!lua_isnumber(L, -1))
6474 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6475 return luaL_checkinteger(L, -1);
6478 // Return number of accepted items to be put
6479 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6480 const std::string &listname, int index, ItemStack &stack,
6481 ServerActiveObject *player)
6484 assert(lua_checkstack(L, 20));
6485 StackUnroller stack_unroller(L);
6487 INodeDefManager *ndef = get_server(L)->ndef();
6489 // If node doesn't exist, we don't know what callback to call
6490 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6491 if(node.getContent() == CONTENT_IGNORE)
6494 // Push callback function on stack
6495 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6496 "allow_metadata_inventory_put"))
6499 // Call function(pos, listname, index, stack, player)
6503 lua_pushstring(L, listname.c_str());
6505 lua_pushinteger(L, index + 1);
6507 LuaItemStack::create(L, stack);
6509 objectref_get_or_create(L, player);
6510 if(lua_pcall(L, 5, 1, 0))
6511 script_error(L, "error: %s", lua_tostring(L, -1));
6512 if(!lua_isnumber(L, -1))
6513 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6514 return luaL_checkinteger(L, -1);
6517 // Return number of accepted items to be taken
6518 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6519 const std::string &listname, int index, ItemStack &stack,
6520 ServerActiveObject *player)
6523 assert(lua_checkstack(L, 20));
6524 StackUnroller stack_unroller(L);
6526 INodeDefManager *ndef = get_server(L)->ndef();
6528 // If node doesn't exist, we don't know what callback to call
6529 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6530 if(node.getContent() == CONTENT_IGNORE)
6533 // Push callback function on stack
6534 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6535 "allow_metadata_inventory_take"))
6538 // Call function(pos, listname, index, count, player)
6542 lua_pushstring(L, listname.c_str());
6544 lua_pushinteger(L, index + 1);
6546 LuaItemStack::create(L, stack);
6548 objectref_get_or_create(L, player);
6549 if(lua_pcall(L, 5, 1, 0))
6550 script_error(L, "error: %s", lua_tostring(L, -1));
6551 if(!lua_isnumber(L, -1))
6552 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6553 return luaL_checkinteger(L, -1);
6556 // Report moved items
6557 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6558 const std::string &from_list, int from_index,
6559 const std::string &to_list, int to_index,
6560 int count, ServerActiveObject *player)
6563 assert(lua_checkstack(L, 20));
6564 StackUnroller stack_unroller(L);
6566 INodeDefManager *ndef = get_server(L)->ndef();
6568 // If node doesn't exist, we don't know what callback to call
6569 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6570 if(node.getContent() == CONTENT_IGNORE)
6573 // Push callback function on stack
6574 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6575 "on_metadata_inventory_move"))
6578 // function(pos, from_list, from_index, to_list, to_index, count, player)
6582 lua_pushstring(L, from_list.c_str());
6584 lua_pushinteger(L, from_index + 1);
6586 lua_pushstring(L, to_list.c_str());
6588 lua_pushinteger(L, to_index + 1);
6590 lua_pushinteger(L, count);
6592 objectref_get_or_create(L, player);
6593 if(lua_pcall(L, 7, 0, 0))
6594 script_error(L, "error: %s", lua_tostring(L, -1));
6598 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6599 const std::string &listname, int index, ItemStack &stack,
6600 ServerActiveObject *player)
6603 assert(lua_checkstack(L, 20));
6604 StackUnroller stack_unroller(L);
6606 INodeDefManager *ndef = get_server(L)->ndef();
6608 // If node doesn't exist, we don't know what callback to call
6609 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6610 if(node.getContent() == CONTENT_IGNORE)
6613 // Push callback function on stack
6614 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6615 "on_metadata_inventory_put"))
6618 // Call function(pos, listname, index, stack, player)
6622 lua_pushstring(L, listname.c_str());
6624 lua_pushinteger(L, index + 1);
6626 LuaItemStack::create(L, stack);
6628 objectref_get_or_create(L, player);
6629 if(lua_pcall(L, 5, 0, 0))
6630 script_error(L, "error: %s", lua_tostring(L, -1));
6633 // Report taken items
6634 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6635 const std::string &listname, int index, ItemStack &stack,
6636 ServerActiveObject *player)
6639 assert(lua_checkstack(L, 20));
6640 StackUnroller stack_unroller(L);
6642 INodeDefManager *ndef = get_server(L)->ndef();
6644 // If node doesn't exist, we don't know what callback to call
6645 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6646 if(node.getContent() == CONTENT_IGNORE)
6649 // Push callback function on stack
6650 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6651 "on_metadata_inventory_take"))
6654 // Call function(pos, listname, index, stack, player)
6658 lua_pushstring(L, listname.c_str());
6660 lua_pushinteger(L, index + 1);
6662 LuaItemStack::create(L, stack);
6664 objectref_get_or_create(L, player);
6665 if(lua_pcall(L, 5, 0, 0))
6666 script_error(L, "error: %s", lua_tostring(L, -1));
6670 Detached inventory callbacks
6673 // Retrieves minetest.detached_inventories[name][callbackname]
6674 // If that is nil or on error, return false and stack is unchanged
6675 // If that is a function, returns true and pushes the
6676 // function onto the stack
6677 static bool get_detached_inventory_callback(lua_State *L,
6678 const std::string &name, const char *callbackname)
6680 lua_getglobal(L, "minetest");
6681 lua_getfield(L, -1, "detached_inventories");
6683 luaL_checktype(L, -1, LUA_TTABLE);
6684 lua_getfield(L, -1, name.c_str());
6686 // Should be a table
6687 if(lua_type(L, -1) != LUA_TTABLE)
6689 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6693 lua_getfield(L, -1, callbackname);
6695 // Should be a function or nil
6696 if(lua_type(L, -1) == LUA_TFUNCTION)
6700 else if(lua_isnil(L, -1))
6707 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6708 <<callbackname<<"\" is not a function"<<std::endl;
6714 // Return number of accepted items to be moved
6715 int scriptapi_detached_inventory_allow_move(lua_State *L,
6716 const std::string &name,
6717 const std::string &from_list, int from_index,
6718 const std::string &to_list, int to_index,
6719 int count, ServerActiveObject *player)
6722 assert(lua_checkstack(L, 20));
6723 StackUnroller stack_unroller(L);
6725 // Push callback function on stack
6726 if(!get_detached_inventory_callback(L, name, "allow_move"))
6729 // function(inv, from_list, from_index, to_list, to_index, count, player)
6731 InventoryLocation loc;
6732 loc.setDetached(name);
6733 InvRef::create(L, loc);
6735 lua_pushstring(L, from_list.c_str());
6737 lua_pushinteger(L, from_index + 1);
6739 lua_pushstring(L, to_list.c_str());
6741 lua_pushinteger(L, to_index + 1);
6743 lua_pushinteger(L, count);
6745 objectref_get_or_create(L, player);
6746 if(lua_pcall(L, 7, 1, 0))
6747 script_error(L, "error: %s", lua_tostring(L, -1));
6748 if(!lua_isnumber(L, -1))
6749 throw LuaError(L, "allow_move should return a number");
6750 return luaL_checkinteger(L, -1);
6753 // Return number of accepted items to be put
6754 int scriptapi_detached_inventory_allow_put(lua_State *L,
6755 const std::string &name,
6756 const std::string &listname, int index, ItemStack &stack,
6757 ServerActiveObject *player)
6760 assert(lua_checkstack(L, 20));
6761 StackUnroller stack_unroller(L);
6763 // Push callback function on stack
6764 if(!get_detached_inventory_callback(L, name, "allow_put"))
6765 return stack.count; // All will be accepted
6767 // Call function(inv, listname, index, stack, player)
6769 InventoryLocation loc;
6770 loc.setDetached(name);
6771 InvRef::create(L, loc);
6773 lua_pushstring(L, listname.c_str());
6775 lua_pushinteger(L, index + 1);
6777 LuaItemStack::create(L, stack);
6779 objectref_get_or_create(L, player);
6780 if(lua_pcall(L, 5, 1, 0))
6781 script_error(L, "error: %s", lua_tostring(L, -1));
6782 if(!lua_isnumber(L, -1))
6783 throw LuaError(L, "allow_put should return a number");
6784 return luaL_checkinteger(L, -1);
6787 // Return number of accepted items to be taken
6788 int scriptapi_detached_inventory_allow_take(lua_State *L,
6789 const std::string &name,
6790 const std::string &listname, int index, ItemStack &stack,
6791 ServerActiveObject *player)
6794 assert(lua_checkstack(L, 20));
6795 StackUnroller stack_unroller(L);
6797 // Push callback function on stack
6798 if(!get_detached_inventory_callback(L, name, "allow_take"))
6799 return stack.count; // All will be accepted
6801 // Call function(inv, listname, index, stack, player)
6803 InventoryLocation loc;
6804 loc.setDetached(name);
6805 InvRef::create(L, loc);
6807 lua_pushstring(L, listname.c_str());
6809 lua_pushinteger(L, index + 1);
6811 LuaItemStack::create(L, stack);
6813 objectref_get_or_create(L, player);
6814 if(lua_pcall(L, 5, 1, 0))
6815 script_error(L, "error: %s", lua_tostring(L, -1));
6816 if(!lua_isnumber(L, -1))
6817 throw LuaError(L, "allow_take should return a number");
6818 return luaL_checkinteger(L, -1);
6821 // Report moved items
6822 void scriptapi_detached_inventory_on_move(lua_State *L,
6823 const std::string &name,
6824 const std::string &from_list, int from_index,
6825 const std::string &to_list, int to_index,
6826 int count, ServerActiveObject *player)
6829 assert(lua_checkstack(L, 20));
6830 StackUnroller stack_unroller(L);
6832 // Push callback function on stack
6833 if(!get_detached_inventory_callback(L, name, "on_move"))
6836 // function(inv, from_list, from_index, to_list, to_index, count, player)
6838 InventoryLocation loc;
6839 loc.setDetached(name);
6840 InvRef::create(L, loc);
6842 lua_pushstring(L, from_list.c_str());
6844 lua_pushinteger(L, from_index + 1);
6846 lua_pushstring(L, to_list.c_str());
6848 lua_pushinteger(L, to_index + 1);
6850 lua_pushinteger(L, count);
6852 objectref_get_or_create(L, player);
6853 if(lua_pcall(L, 7, 0, 0))
6854 script_error(L, "error: %s", lua_tostring(L, -1));
6858 void scriptapi_detached_inventory_on_put(lua_State *L,
6859 const std::string &name,
6860 const std::string &listname, int index, ItemStack &stack,
6861 ServerActiveObject *player)
6864 assert(lua_checkstack(L, 20));
6865 StackUnroller stack_unroller(L);
6867 // Push callback function on stack
6868 if(!get_detached_inventory_callback(L, name, "on_put"))
6871 // Call function(inv, listname, index, stack, player)
6873 InventoryLocation loc;
6874 loc.setDetached(name);
6875 InvRef::create(L, loc);
6877 lua_pushstring(L, listname.c_str());
6879 lua_pushinteger(L, index + 1);
6881 LuaItemStack::create(L, stack);
6883 objectref_get_or_create(L, player);
6884 if(lua_pcall(L, 5, 0, 0))
6885 script_error(L, "error: %s", lua_tostring(L, -1));
6888 // Report taken items
6889 void scriptapi_detached_inventory_on_take(lua_State *L,
6890 const std::string &name,
6891 const std::string &listname, int index, ItemStack &stack,
6892 ServerActiveObject *player)
6895 assert(lua_checkstack(L, 20));
6896 StackUnroller stack_unroller(L);
6898 // Push callback function on stack
6899 if(!get_detached_inventory_callback(L, name, "on_take"))
6902 // Call function(inv, listname, index, stack, player)
6904 InventoryLocation loc;
6905 loc.setDetached(name);
6906 InvRef::create(L, loc);
6908 lua_pushstring(L, listname.c_str());
6910 lua_pushinteger(L, index + 1);
6912 LuaItemStack::create(L, stack);
6914 objectref_get_or_create(L, player);
6915 if(lua_pcall(L, 5, 0, 0))
6916 script_error(L, "error: %s", lua_tostring(L, -1));
6923 void scriptapi_environment_step(lua_State *L, float dtime)
6926 assert(lua_checkstack(L, 20));
6927 //infostream<<"scriptapi_environment_step"<<std::endl;
6928 StackUnroller stack_unroller(L);
6930 // Get minetest.registered_globalsteps
6931 lua_getglobal(L, "minetest");
6932 lua_getfield(L, -1, "registered_globalsteps");
6934 lua_pushnumber(L, dtime);
6935 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6938 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6942 assert(lua_checkstack(L, 20));
6943 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6944 StackUnroller stack_unroller(L);
6946 // Get minetest.registered_on_generateds
6947 lua_getglobal(L, "minetest");
6948 lua_getfield(L, -1, "registered_on_generateds");
6950 push_v3s16(L, minp);
6951 push_v3s16(L, maxp);
6952 lua_pushnumber(L, blockseed);
6953 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6960 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6963 assert(lua_checkstack(L, 20));
6964 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6965 <<name<<"\""<<std::endl;
6966 StackUnroller stack_unroller(L);
6968 // Get minetest.registered_entities[name]
6969 lua_getglobal(L, "minetest");
6970 lua_getfield(L, -1, "registered_entities");
6971 luaL_checktype(L, -1, LUA_TTABLE);
6972 lua_pushstring(L, name);
6973 lua_gettable(L, -2);
6974 // Should be a table, which we will use as a prototype
6975 //luaL_checktype(L, -1, LUA_TTABLE);
6976 if(lua_type(L, -1) != LUA_TTABLE){
6977 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6980 int prototype_table = lua_gettop(L);
6981 //dump2(L, "prototype_table");
6983 // Create entity object
6985 int object = lua_gettop(L);
6987 // Set object metatable
6988 lua_pushvalue(L, prototype_table);
6989 lua_setmetatable(L, -2);
6991 // Add object reference
6992 // This should be userdata with metatable ObjectRef
6993 objectref_get(L, id);
6994 luaL_checktype(L, -1, LUA_TUSERDATA);
6995 if(!luaL_checkudata(L, -1, "ObjectRef"))
6996 luaL_typerror(L, -1, "ObjectRef");
6997 lua_setfield(L, -2, "object");
6999 // minetest.luaentities[id] = object
7000 lua_getglobal(L, "minetest");
7001 lua_getfield(L, -1, "luaentities");
7002 luaL_checktype(L, -1, LUA_TTABLE);
7003 lua_pushnumber(L, id); // Push id
7004 lua_pushvalue(L, object); // Copy object to top of stack
7005 lua_settable(L, -3);
7010 void scriptapi_luaentity_activate(lua_State *L, u16 id,
7011 const std::string &staticdata, u32 dtime_s)
7014 assert(lua_checkstack(L, 20));
7015 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
7016 StackUnroller stack_unroller(L);
7018 // Get minetest.luaentities[id]
7019 luaentity_get(L, id);
7020 int object = lua_gettop(L);
7022 // Get on_activate function
7023 lua_pushvalue(L, object);
7024 lua_getfield(L, -1, "on_activate");
7025 if(!lua_isnil(L, -1)){
7026 luaL_checktype(L, -1, LUA_TFUNCTION);
7027 lua_pushvalue(L, object); // self
7028 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
7029 lua_pushinteger(L, dtime_s);
7030 // Call with 3 arguments, 0 results
7031 if(lua_pcall(L, 3, 0, 0))
7032 script_error(L, "error running function on_activate: %s\n",
7033 lua_tostring(L, -1));
7037 void scriptapi_luaentity_rm(lua_State *L, u16 id)
7040 assert(lua_checkstack(L, 20));
7041 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
7043 // Get minetest.luaentities table
7044 lua_getglobal(L, "minetest");
7045 lua_getfield(L, -1, "luaentities");
7046 luaL_checktype(L, -1, LUA_TTABLE);
7047 int objectstable = lua_gettop(L);
7049 // Set luaentities[id] = nil
7050 lua_pushnumber(L, id); // Push id
7052 lua_settable(L, objectstable);
7054 lua_pop(L, 2); // pop luaentities, minetest
7057 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
7060 assert(lua_checkstack(L, 20));
7061 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
7062 StackUnroller stack_unroller(L);
7064 // Get minetest.luaentities[id]
7065 luaentity_get(L, id);
7066 int object = lua_gettop(L);
7068 // Get get_staticdata function
7069 lua_pushvalue(L, object);
7070 lua_getfield(L, -1, "get_staticdata");
7071 if(lua_isnil(L, -1))
7074 luaL_checktype(L, -1, LUA_TFUNCTION);
7075 lua_pushvalue(L, object); // self
7076 // Call with 1 arguments, 1 results
7077 if(lua_pcall(L, 1, 1, 0))
7078 script_error(L, "error running function get_staticdata: %s\n",
7079 lua_tostring(L, -1));
7082 const char *s = lua_tolstring(L, -1, &len);
7083 return std::string(s, len);
7086 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
7087 ObjectProperties *prop)
7090 assert(lua_checkstack(L, 20));
7091 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
7092 StackUnroller stack_unroller(L);
7094 // Get minetest.luaentities[id]
7095 luaentity_get(L, id);
7096 //int object = lua_gettop(L);
7098 // Set default values that differ from ObjectProperties defaults
7103 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
7105 getboolfield(L, -1, "physical", prop->physical);
7107 getfloatfield(L, -1, "weight", prop->weight);
7109 lua_getfield(L, -1, "collisionbox");
7110 if(lua_istable(L, -1))
7111 prop->collisionbox = read_aabb3f(L, -1, 1.0);
7114 getstringfield(L, -1, "visual", prop->visual);
7116 getstringfield(L, -1, "mesh", prop->mesh);
7118 // Deprecated: read object properties directly
7119 read_object_properties(L, -1, prop);
7121 // Read initial_properties
7122 lua_getfield(L, -1, "initial_properties");
7123 read_object_properties(L, -1, prop);
7127 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
7130 assert(lua_checkstack(L, 20));
7131 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7132 StackUnroller stack_unroller(L);
7134 // Get minetest.luaentities[id]
7135 luaentity_get(L, id);
7136 int object = lua_gettop(L);
7137 // State: object is at top of stack
7138 // Get step function
7139 lua_getfield(L, -1, "on_step");
7140 if(lua_isnil(L, -1))
7142 luaL_checktype(L, -1, LUA_TFUNCTION);
7143 lua_pushvalue(L, object); // self
7144 lua_pushnumber(L, dtime); // dtime
7145 // Call with 2 arguments, 0 results
7146 if(lua_pcall(L, 2, 0, 0))
7147 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
7150 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
7151 // tool_capabilities, direction)
7152 void scriptapi_luaentity_punch(lua_State *L, u16 id,
7153 ServerActiveObject *puncher, float time_from_last_punch,
7154 const ToolCapabilities *toolcap, v3f dir)
7157 assert(lua_checkstack(L, 20));
7158 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7159 StackUnroller stack_unroller(L);
7161 // Get minetest.luaentities[id]
7162 luaentity_get(L, id);
7163 int object = lua_gettop(L);
7164 // State: object is at top of stack
7166 lua_getfield(L, -1, "on_punch");
7167 if(lua_isnil(L, -1))
7169 luaL_checktype(L, -1, LUA_TFUNCTION);
7170 lua_pushvalue(L, object); // self
7171 objectref_get_or_create(L, puncher); // Clicker reference
7172 lua_pushnumber(L, time_from_last_punch);
7173 push_tool_capabilities(L, *toolcap);
7175 // Call with 5 arguments, 0 results
7176 if(lua_pcall(L, 5, 0, 0))
7177 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
7180 // Calls entity:on_rightclick(ObjectRef clicker)
7181 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
7182 ServerActiveObject *clicker)
7185 assert(lua_checkstack(L, 20));
7186 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7187 StackUnroller stack_unroller(L);
7189 // Get minetest.luaentities[id]
7190 luaentity_get(L, id);
7191 int object = lua_gettop(L);
7192 // State: object is at top of stack
7194 lua_getfield(L, -1, "on_rightclick");
7195 if(lua_isnil(L, -1))
7197 luaL_checktype(L, -1, LUA_TFUNCTION);
7198 lua_pushvalue(L, object); // self
7199 objectref_get_or_create(L, clicker); // Clicker reference
7200 // Call with 2 arguments, 0 results
7201 if(lua_pcall(L, 2, 0, 0))
7202 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));