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 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1068 warn_if_field_exists(L, index, "tool_digging_properties",
1069 "deprecated: use tool_capabilities");
1071 lua_getfield(L, index, "tool_capabilities");
1072 if(lua_istable(L, -1)){
1073 def.tool_capabilities = new ToolCapabilities(
1074 read_tool_capabilities(L, -1));
1077 // If name is "" (hand), ensure there are ToolCapabilities
1078 // because it will be looked up there whenever any other item has
1079 // no ToolCapabilities
1080 if(def.name == "" && def.tool_capabilities == NULL){
1081 def.tool_capabilities = new ToolCapabilities();
1084 lua_getfield(L, index, "groups");
1085 read_groups(L, -1, def.groups);
1088 // Client shall immediately place this node when player places the item.
1089 // Server will update the precise end result a moment later.
1090 // "" = no prediction
1091 getstringfield(L, index, "node_placement_prediction",
1092 def.node_placement_prediction);
1101 static TileDef read_tiledef(lua_State *L, int index)
1104 index = lua_gettop(L) + 1 + index;
1108 // key at index -2 and value at index
1109 if(lua_isstring(L, index)){
1110 // "default_lava.png"
1111 tiledef.name = lua_tostring(L, index);
1113 else if(lua_istable(L, index))
1115 // {name="default_lava.png", animation={}}
1117 getstringfield(L, index, "name", tiledef.name);
1118 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1119 tiledef.backface_culling = getboolfield_default(
1120 L, index, "backface_culling", true);
1122 lua_getfield(L, index, "animation");
1123 if(lua_istable(L, -1)){
1124 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1125 tiledef.animation.type = (TileAnimationType)
1126 getenumfield(L, -1, "type", es_TileAnimationType,
1128 tiledef.animation.aspect_w =
1129 getintfield_default(L, -1, "aspect_w", 16);
1130 tiledef.animation.aspect_h =
1131 getintfield_default(L, -1, "aspect_h", 16);
1132 tiledef.animation.length =
1133 getfloatfield_default(L, -1, "length", 1.0);
1145 static ContentFeatures read_content_features(lua_State *L, int index)
1148 index = lua_gettop(L) + 1 + index;
1152 /* Cache existence of some callbacks */
1153 lua_getfield(L, index, "on_construct");
1154 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1156 lua_getfield(L, index, "on_destruct");
1157 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1159 lua_getfield(L, index, "after_destruct");
1160 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1164 getstringfield(L, index, "name", f.name);
1167 lua_getfield(L, index, "groups");
1168 read_groups(L, -1, f.groups);
1171 /* Visual definition */
1173 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1175 getfloatfield(L, index, "visual_scale", f.visual_scale);
1178 lua_getfield(L, index, "tiles");
1179 // If nil, try the deprecated name "tile_images" instead
1180 if(lua_isnil(L, -1)){
1182 warn_if_field_exists(L, index, "tile_images",
1183 "Deprecated; new name is \"tiles\".");
1184 lua_getfield(L, index, "tile_images");
1186 if(lua_istable(L, -1)){
1187 int table = lua_gettop(L);
1190 while(lua_next(L, table) != 0){
1191 // Read tiledef from value
1192 f.tiledef[i] = read_tiledef(L, -1);
1193 // removes value, keeps key for next iteration
1201 // Copy last value to all remaining textures
1203 TileDef lasttile = f.tiledef[i-1];
1205 f.tiledef[i] = lasttile;
1212 // special_tiles = {}
1213 lua_getfield(L, index, "special_tiles");
1214 // If nil, try the deprecated name "special_materials" instead
1215 if(lua_isnil(L, -1)){
1217 warn_if_field_exists(L, index, "special_materials",
1218 "Deprecated; new name is \"special_tiles\".");
1219 lua_getfield(L, index, "special_materials");
1221 if(lua_istable(L, -1)){
1222 int table = lua_gettop(L);
1225 while(lua_next(L, table) != 0){
1226 // Read tiledef from value
1227 f.tiledef_special[i] = read_tiledef(L, -1);
1228 // removes value, keeps key for next iteration
1239 f.alpha = getintfield_default(L, index, "alpha", 255);
1243 lua_getfield(L, index, "post_effect_color");
1244 if(!lua_isnil(L, -1))
1245 f.post_effect_color = readARGB8(L, -1);
1248 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1249 es_ContentParamType, CPT_NONE);
1250 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1251 es_ContentParamType2, CPT2_NONE);
1253 // Warn about some deprecated fields
1254 warn_if_field_exists(L, index, "wall_mounted",
1255 "deprecated: use paramtype2 = 'wallmounted'");
1256 warn_if_field_exists(L, index, "light_propagates",
1257 "deprecated: determined from paramtype");
1258 warn_if_field_exists(L, index, "dug_item",
1259 "deprecated: use 'drop' field");
1260 warn_if_field_exists(L, index, "extra_dug_item",
1261 "deprecated: use 'drop' field");
1262 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1263 "deprecated: use 'drop' field");
1264 warn_if_field_exists(L, index, "metadata_name",
1265 "deprecated: use on_add and metadata callbacks");
1267 // True for all ground-like things like stone and mud, false for eg. trees
1268 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1269 f.light_propagates = (f.param_type == CPT_LIGHT);
1270 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1271 // This is used for collision detection.
1272 // Also for general solidness queries.
1273 getboolfield(L, index, "walkable", f.walkable);
1274 // Player can point to these
1275 getboolfield(L, index, "pointable", f.pointable);
1276 // Player can dig these
1277 getboolfield(L, index, "diggable", f.diggable);
1278 // Player can climb these
1279 getboolfield(L, index, "climbable", f.climbable);
1280 // Player can build on these
1281 getboolfield(L, index, "buildable_to", f.buildable_to);
1282 // Whether the node is non-liquid, source liquid or flowing liquid
1283 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1284 es_LiquidType, LIQUID_NONE);
1285 // If the content is liquid, this is the flowing version of the liquid.
1286 getstringfield(L, index, "liquid_alternative_flowing",
1287 f.liquid_alternative_flowing);
1288 // If the content is liquid, this is the source version of the liquid.
1289 getstringfield(L, index, "liquid_alternative_source",
1290 f.liquid_alternative_source);
1291 // Viscosity for fluid flow, ranging from 1 to 7, with
1292 // 1 giving almost instantaneous propagation and 7 being
1293 // the slowest possible
1294 f.liquid_viscosity = getintfield_default(L, index,
1295 "liquid_viscosity", f.liquid_viscosity);
1296 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1297 // Amount of light the node emits
1298 f.light_source = getintfield_default(L, index,
1299 "light_source", f.light_source);
1300 f.damage_per_second = getintfield_default(L, index,
1301 "damage_per_second", f.damage_per_second);
1303 lua_getfield(L, index, "node_box");
1304 if(lua_istable(L, -1))
1305 f.node_box = read_nodebox(L, -1);
1308 lua_getfield(L, index, "selection_box");
1309 if(lua_istable(L, -1))
1310 f.selection_box = read_nodebox(L, -1);
1313 // Set to true if paramtype used to be 'facedir_simple'
1314 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1315 // Set to true if wall_mounted used to be set to true
1316 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1319 lua_getfield(L, index, "sounds");
1320 if(lua_istable(L, -1)){
1321 lua_getfield(L, -1, "footstep");
1322 read_soundspec(L, -1, f.sound_footstep);
1324 lua_getfield(L, -1, "dig");
1325 read_soundspec(L, -1, f.sound_dig);
1327 lua_getfield(L, -1, "dug");
1328 read_soundspec(L, -1, f.sound_dug);
1340 static ItemStack read_item(lua_State *L, int index);
1341 static std::vector<ItemStack> read_items(lua_State *L, int index);
1342 // creates a table of ItemStacks
1343 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1345 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1346 lua_State *L, int tableindex, int forcesize=-1)
1349 tableindex = lua_gettop(L) + 1 + tableindex;
1350 // If nil, delete list
1351 if(lua_isnil(L, tableindex)){
1352 inv->deleteList(name);
1355 // Otherwise set list
1356 std::vector<ItemStack> items = read_items(L, tableindex);
1357 int listsize = (forcesize != -1) ? forcesize : items.size();
1358 InventoryList *invlist = inv->addList(name, listsize);
1360 for(std::vector<ItemStack>::const_iterator
1361 i = items.begin(); i != items.end(); i++){
1362 if(forcesize != -1 && index == forcesize)
1364 invlist->changeItem(index, *i);
1367 while(forcesize != -1 && index < forcesize){
1368 invlist->deleteItem(index);
1373 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1376 InventoryList *invlist = inv->getList(name);
1377 if(invlist == NULL){
1381 std::vector<ItemStack> items;
1382 for(u32 i=0; i<invlist->getSize(); i++)
1383 items.push_back(invlist->getItem(i));
1384 push_items(L, items);
1388 Helpful macros for userdata classes
1391 #define method(class, name) {#name, class::l_##name}
1402 static const char className[];
1403 static const luaL_reg methods[];
1405 // Exported functions
1407 // garbage collector
1408 static int gc_object(lua_State *L)
1410 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1415 // is_empty(self) -> true/false
1416 static int l_is_empty(lua_State *L)
1418 LuaItemStack *o = checkobject(L, 1);
1419 ItemStack &item = o->m_stack;
1420 lua_pushboolean(L, item.empty());
1424 // get_name(self) -> string
1425 static int l_get_name(lua_State *L)
1427 LuaItemStack *o = checkobject(L, 1);
1428 ItemStack &item = o->m_stack;
1429 lua_pushstring(L, item.name.c_str());
1433 // get_count(self) -> number
1434 static int l_get_count(lua_State *L)
1436 LuaItemStack *o = checkobject(L, 1);
1437 ItemStack &item = o->m_stack;
1438 lua_pushinteger(L, item.count);
1442 // get_wear(self) -> number
1443 static int l_get_wear(lua_State *L)
1445 LuaItemStack *o = checkobject(L, 1);
1446 ItemStack &item = o->m_stack;
1447 lua_pushinteger(L, item.wear);
1451 // get_metadata(self) -> string
1452 static int l_get_metadata(lua_State *L)
1454 LuaItemStack *o = checkobject(L, 1);
1455 ItemStack &item = o->m_stack;
1456 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1460 // clear(self) -> true
1461 static int l_clear(lua_State *L)
1463 LuaItemStack *o = checkobject(L, 1);
1465 lua_pushboolean(L, true);
1469 // replace(self, itemstack or itemstring or table or nil) -> true
1470 static int l_replace(lua_State *L)
1472 LuaItemStack *o = checkobject(L, 1);
1473 o->m_stack = read_item(L, 2);
1474 lua_pushboolean(L, true);
1478 // to_string(self) -> string
1479 static int l_to_string(lua_State *L)
1481 LuaItemStack *o = checkobject(L, 1);
1482 std::string itemstring = o->m_stack.getItemString();
1483 lua_pushstring(L, itemstring.c_str());
1487 // to_table(self) -> table or nil
1488 static int l_to_table(lua_State *L)
1490 LuaItemStack *o = checkobject(L, 1);
1491 const ItemStack &item = o->m_stack;
1499 lua_pushstring(L, item.name.c_str());
1500 lua_setfield(L, -2, "name");
1501 lua_pushinteger(L, item.count);
1502 lua_setfield(L, -2, "count");
1503 lua_pushinteger(L, item.wear);
1504 lua_setfield(L, -2, "wear");
1505 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1506 lua_setfield(L, -2, "metadata");
1511 // get_stack_max(self) -> number
1512 static int l_get_stack_max(lua_State *L)
1514 LuaItemStack *o = checkobject(L, 1);
1515 ItemStack &item = o->m_stack;
1516 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1520 // get_free_space(self) -> number
1521 static int l_get_free_space(lua_State *L)
1523 LuaItemStack *o = checkobject(L, 1);
1524 ItemStack &item = o->m_stack;
1525 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1529 // is_known(self) -> true/false
1530 // Checks if the item is defined.
1531 static int l_is_known(lua_State *L)
1533 LuaItemStack *o = checkobject(L, 1);
1534 ItemStack &item = o->m_stack;
1535 bool is_known = item.isKnown(get_server(L)->idef());
1536 lua_pushboolean(L, is_known);
1540 // get_definition(self) -> table
1541 // Returns the item definition table from minetest.registered_items,
1542 // or a fallback one (name="unknown")
1543 static int l_get_definition(lua_State *L)
1545 LuaItemStack *o = checkobject(L, 1);
1546 ItemStack &item = o->m_stack;
1548 // Get minetest.registered_items[name]
1549 lua_getglobal(L, "minetest");
1550 lua_getfield(L, -1, "registered_items");
1551 luaL_checktype(L, -1, LUA_TTABLE);
1552 lua_getfield(L, -1, item.name.c_str());
1553 if(lua_isnil(L, -1))
1556 lua_getfield(L, -1, "unknown");
1561 // get_tool_capabilities(self) -> table
1562 // Returns the effective tool digging properties.
1563 // Returns those of the hand ("") if this item has none associated.
1564 static int l_get_tool_capabilities(lua_State *L)
1566 LuaItemStack *o = checkobject(L, 1);
1567 ItemStack &item = o->m_stack;
1568 const ToolCapabilities &prop =
1569 item.getToolCapabilities(get_server(L)->idef());
1570 push_tool_capabilities(L, prop);
1574 // add_wear(self, amount) -> true/false
1575 // The range for "amount" is [0,65535]. Wear is only added if the item
1576 // is a tool. Adding wear might destroy the item.
1577 // Returns true if the item is (or was) a tool.
1578 static int l_add_wear(lua_State *L)
1580 LuaItemStack *o = checkobject(L, 1);
1581 ItemStack &item = o->m_stack;
1582 int amount = lua_tointeger(L, 2);
1583 bool result = item.addWear(amount, get_server(L)->idef());
1584 lua_pushboolean(L, result);
1588 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1589 // Returns leftover item stack
1590 static int l_add_item(lua_State *L)
1592 LuaItemStack *o = checkobject(L, 1);
1593 ItemStack &item = o->m_stack;
1594 ItemStack newitem = read_item(L, 2);
1595 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1596 create(L, leftover);
1600 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1601 // First return value is true iff the new item fits fully into the stack
1602 // Second return value is the would-be-left-over item stack
1603 static int l_item_fits(lua_State *L)
1605 LuaItemStack *o = checkobject(L, 1);
1606 ItemStack &item = o->m_stack;
1607 ItemStack newitem = read_item(L, 2);
1609 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1610 lua_pushboolean(L, fits); // first return value
1611 create(L, restitem); // second return value
1615 // take_item(self, takecount=1) -> itemstack
1616 static int l_take_item(lua_State *L)
1618 LuaItemStack *o = checkobject(L, 1);
1619 ItemStack &item = o->m_stack;
1621 if(!lua_isnone(L, 2))
1622 takecount = luaL_checkinteger(L, 2);
1623 ItemStack taken = item.takeItem(takecount);
1628 // peek_item(self, peekcount=1) -> itemstack
1629 static int l_peek_item(lua_State *L)
1631 LuaItemStack *o = checkobject(L, 1);
1632 ItemStack &item = o->m_stack;
1634 if(!lua_isnone(L, 2))
1635 peekcount = lua_tointeger(L, 2);
1636 ItemStack peekaboo = item.peekItem(peekcount);
1637 create(L, peekaboo);
1642 LuaItemStack(const ItemStack &item):
1651 const ItemStack& getItem() const
1655 ItemStack& getItem()
1660 // LuaItemStack(itemstack or itemstring or table or nil)
1661 // Creates an LuaItemStack and leaves it on top of stack
1662 static int create_object(lua_State *L)
1664 ItemStack item = read_item(L, 1);
1665 LuaItemStack *o = new LuaItemStack(item);
1666 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1667 luaL_getmetatable(L, className);
1668 lua_setmetatable(L, -2);
1671 // Not callable from Lua
1672 static int create(lua_State *L, const ItemStack &item)
1674 LuaItemStack *o = new LuaItemStack(item);
1675 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1676 luaL_getmetatable(L, className);
1677 lua_setmetatable(L, -2);
1681 static LuaItemStack* checkobject(lua_State *L, int narg)
1683 luaL_checktype(L, narg, LUA_TUSERDATA);
1684 void *ud = luaL_checkudata(L, narg, className);
1685 if(!ud) luaL_typerror(L, narg, className);
1686 return *(LuaItemStack**)ud; // unbox pointer
1689 static void Register(lua_State *L)
1692 int methodtable = lua_gettop(L);
1693 luaL_newmetatable(L, className);
1694 int metatable = lua_gettop(L);
1696 lua_pushliteral(L, "__metatable");
1697 lua_pushvalue(L, methodtable);
1698 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1700 lua_pushliteral(L, "__index");
1701 lua_pushvalue(L, methodtable);
1702 lua_settable(L, metatable);
1704 lua_pushliteral(L, "__gc");
1705 lua_pushcfunction(L, gc_object);
1706 lua_settable(L, metatable);
1708 lua_pop(L, 1); // drop metatable
1710 luaL_openlib(L, 0, methods, 0); // fill methodtable
1711 lua_pop(L, 1); // drop methodtable
1713 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1714 lua_register(L, className, create_object);
1717 const char LuaItemStack::className[] = "ItemStack";
1718 const luaL_reg LuaItemStack::methods[] = {
1719 method(LuaItemStack, is_empty),
1720 method(LuaItemStack, get_name),
1721 method(LuaItemStack, get_count),
1722 method(LuaItemStack, get_wear),
1723 method(LuaItemStack, get_metadata),
1724 method(LuaItemStack, clear),
1725 method(LuaItemStack, replace),
1726 method(LuaItemStack, to_string),
1727 method(LuaItemStack, to_table),
1728 method(LuaItemStack, get_stack_max),
1729 method(LuaItemStack, get_free_space),
1730 method(LuaItemStack, is_known),
1731 method(LuaItemStack, get_definition),
1732 method(LuaItemStack, get_tool_capabilities),
1733 method(LuaItemStack, add_wear),
1734 method(LuaItemStack, add_item),
1735 method(LuaItemStack, item_fits),
1736 method(LuaItemStack, take_item),
1737 method(LuaItemStack, peek_item),
1741 static ItemStack read_item(lua_State *L, int index)
1744 index = lua_gettop(L) + 1 + index;
1746 if(lua_isnil(L, index))
1750 else if(lua_isuserdata(L, index))
1752 // Convert from LuaItemStack
1753 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1754 return o->getItem();
1756 else if(lua_isstring(L, index))
1758 // Convert from itemstring
1759 std::string itemstring = lua_tostring(L, index);
1760 IItemDefManager *idef = get_server(L)->idef();
1764 item.deSerialize(itemstring, idef);
1767 catch(SerializationError &e)
1769 infostream<<"WARNING: unable to create item from itemstring"
1770 <<": "<<itemstring<<std::endl;
1774 else if(lua_istable(L, index))
1776 // Convert from table
1777 IItemDefManager *idef = get_server(L)->idef();
1778 std::string name = getstringfield_default(L, index, "name", "");
1779 int count = getintfield_default(L, index, "count", 1);
1780 int wear = getintfield_default(L, index, "wear", 0);
1781 std::string metadata = getstringfield_default(L, index, "metadata", "");
1782 return ItemStack(name, count, wear, metadata, idef);
1786 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1790 static std::vector<ItemStack> read_items(lua_State *L, int index)
1793 index = lua_gettop(L) + 1 + index;
1795 std::vector<ItemStack> items;
1796 luaL_checktype(L, index, LUA_TTABLE);
1798 while(lua_next(L, index) != 0){
1799 // key at index -2 and value at index -1
1800 items.push_back(read_item(L, -1));
1801 // removes value, keeps key for next iteration
1807 // creates a table of ItemStacks
1808 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1810 // Get the table insert function
1811 lua_getglobal(L, "table");
1812 lua_getfield(L, -1, "insert");
1813 int table_insert = lua_gettop(L);
1814 // Create and fill table
1816 int table = lua_gettop(L);
1817 for(u32 i=0; i<items.size(); i++){
1818 ItemStack item = items[i];
1819 lua_pushvalue(L, table_insert);
1820 lua_pushvalue(L, table);
1821 LuaItemStack::create(L, item);
1822 if(lua_pcall(L, 2, 0, 0))
1823 script_error(L, "error: %s", lua_tostring(L, -1));
1825 lua_remove(L, -2); // Remove table
1826 lua_remove(L, -2); // Remove insert
1836 InventoryLocation m_loc;
1838 static const char className[];
1839 static const luaL_reg methods[];
1841 static InvRef *checkobject(lua_State *L, int narg)
1843 luaL_checktype(L, narg, LUA_TUSERDATA);
1844 void *ud = luaL_checkudata(L, narg, className);
1845 if(!ud) luaL_typerror(L, narg, className);
1846 return *(InvRef**)ud; // unbox pointer
1849 static Inventory* getinv(lua_State *L, InvRef *ref)
1851 return get_server(L)->getInventory(ref->m_loc);
1854 static InventoryList* getlist(lua_State *L, InvRef *ref,
1855 const char *listname)
1857 Inventory *inv = getinv(L, ref);
1860 return inv->getList(listname);
1863 static void reportInventoryChange(lua_State *L, InvRef *ref)
1865 // Inform other things that the inventory has changed
1866 get_server(L)->setInventoryModified(ref->m_loc);
1869 // Exported functions
1871 // garbage collector
1872 static int gc_object(lua_State *L) {
1873 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1878 // is_empty(self, listname) -> true/false
1879 static int l_is_empty(lua_State *L)
1881 InvRef *ref = checkobject(L, 1);
1882 const char *listname = luaL_checkstring(L, 2);
1883 InventoryList *list = getlist(L, ref, listname);
1884 if(list && list->getUsedSlots() > 0){
1885 lua_pushboolean(L, false);
1887 lua_pushboolean(L, true);
1892 // get_size(self, listname)
1893 static int l_get_size(lua_State *L)
1895 InvRef *ref = checkobject(L, 1);
1896 const char *listname = luaL_checkstring(L, 2);
1897 InventoryList *list = getlist(L, ref, listname);
1899 lua_pushinteger(L, list->getSize());
1901 lua_pushinteger(L, 0);
1906 // get_width(self, listname)
1907 static int l_get_width(lua_State *L)
1909 InvRef *ref = checkobject(L, 1);
1910 const char *listname = luaL_checkstring(L, 2);
1911 InventoryList *list = getlist(L, ref, listname);
1913 lua_pushinteger(L, list->getWidth());
1915 lua_pushinteger(L, 0);
1920 // set_size(self, listname, size)
1921 static int l_set_size(lua_State *L)
1923 InvRef *ref = checkobject(L, 1);
1924 const char *listname = luaL_checkstring(L, 2);
1925 int newsize = luaL_checknumber(L, 3);
1926 Inventory *inv = getinv(L, ref);
1928 inv->deleteList(listname);
1929 reportInventoryChange(L, ref);
1932 InventoryList *list = inv->getList(listname);
1934 list->setSize(newsize);
1936 list = inv->addList(listname, newsize);
1938 reportInventoryChange(L, ref);
1942 // set_width(self, listname, size)
1943 static int l_set_width(lua_State *L)
1945 InvRef *ref = checkobject(L, 1);
1946 const char *listname = luaL_checkstring(L, 2);
1947 int newwidth = luaL_checknumber(L, 3);
1948 Inventory *inv = getinv(L, ref);
1949 InventoryList *list = inv->getList(listname);
1951 list->setWidth(newwidth);
1955 reportInventoryChange(L, ref);
1959 // get_stack(self, listname, i) -> itemstack
1960 static int l_get_stack(lua_State *L)
1962 InvRef *ref = checkobject(L, 1);
1963 const char *listname = luaL_checkstring(L, 2);
1964 int i = luaL_checknumber(L, 3) - 1;
1965 InventoryList *list = getlist(L, ref, listname);
1967 if(list != NULL && i >= 0 && i < (int) list->getSize())
1968 item = list->getItem(i);
1969 LuaItemStack::create(L, item);
1973 // set_stack(self, listname, i, stack) -> true/false
1974 static int l_set_stack(lua_State *L)
1976 InvRef *ref = checkobject(L, 1);
1977 const char *listname = luaL_checkstring(L, 2);
1978 int i = luaL_checknumber(L, 3) - 1;
1979 ItemStack newitem = read_item(L, 4);
1980 InventoryList *list = getlist(L, ref, listname);
1981 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1982 list->changeItem(i, newitem);
1983 reportInventoryChange(L, ref);
1984 lua_pushboolean(L, true);
1986 lua_pushboolean(L, false);
1991 // get_list(self, listname) -> list or nil
1992 static int l_get_list(lua_State *L)
1994 InvRef *ref = checkobject(L, 1);
1995 const char *listname = luaL_checkstring(L, 2);
1996 Inventory *inv = getinv(L, ref);
1997 inventory_get_list_to_lua(inv, listname, L);
2001 // set_list(self, listname, list)
2002 static int l_set_list(lua_State *L)
2004 InvRef *ref = checkobject(L, 1);
2005 const char *listname = luaL_checkstring(L, 2);
2006 Inventory *inv = getinv(L, ref);
2007 InventoryList *list = inv->getList(listname);
2009 inventory_set_list_from_lua(inv, listname, L, 3,
2012 inventory_set_list_from_lua(inv, listname, L, 3);
2013 reportInventoryChange(L, ref);
2017 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2018 // Returns the leftover stack
2019 static int l_add_item(lua_State *L)
2021 InvRef *ref = checkobject(L, 1);
2022 const char *listname = luaL_checkstring(L, 2);
2023 ItemStack item = read_item(L, 3);
2024 InventoryList *list = getlist(L, ref, listname);
2026 ItemStack leftover = list->addItem(item);
2027 if(leftover.count != item.count)
2028 reportInventoryChange(L, ref);
2029 LuaItemStack::create(L, leftover);
2031 LuaItemStack::create(L, item);
2036 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2037 // Returns true if the item completely fits into the list
2038 static int l_room_for_item(lua_State *L)
2040 InvRef *ref = checkobject(L, 1);
2041 const char *listname = luaL_checkstring(L, 2);
2042 ItemStack item = read_item(L, 3);
2043 InventoryList *list = getlist(L, ref, listname);
2045 lua_pushboolean(L, list->roomForItem(item));
2047 lua_pushboolean(L, false);
2052 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2053 // Returns true if the list contains the given count of the given item name
2054 static int l_contains_item(lua_State *L)
2056 InvRef *ref = checkobject(L, 1);
2057 const char *listname = luaL_checkstring(L, 2);
2058 ItemStack item = read_item(L, 3);
2059 InventoryList *list = getlist(L, ref, listname);
2061 lua_pushboolean(L, list->containsItem(item));
2063 lua_pushboolean(L, false);
2068 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2069 // Returns the items that were actually removed
2070 static int l_remove_item(lua_State *L)
2072 InvRef *ref = checkobject(L, 1);
2073 const char *listname = luaL_checkstring(L, 2);
2074 ItemStack item = read_item(L, 3);
2075 InventoryList *list = getlist(L, ref, listname);
2077 ItemStack removed = list->removeItem(item);
2078 if(!removed.empty())
2079 reportInventoryChange(L, ref);
2080 LuaItemStack::create(L, removed);
2082 LuaItemStack::create(L, ItemStack());
2087 // get_location() -> location (like minetest.get_inventory(location))
2088 static int l_get_location(lua_State *L)
2090 InvRef *ref = checkobject(L, 1);
2091 const InventoryLocation &loc = ref->m_loc;
2093 case InventoryLocation::PLAYER:
2095 lua_pushstring(L, "player");
2096 lua_setfield(L, -2, "type");
2097 lua_pushstring(L, loc.name.c_str());
2098 lua_setfield(L, -2, "name");
2100 case InventoryLocation::NODEMETA:
2102 lua_pushstring(L, "nodemeta");
2103 lua_setfield(L, -2, "type");
2104 push_v3s16(L, loc.p);
2105 lua_setfield(L, -2, "name");
2107 case InventoryLocation::DETACHED:
2109 lua_pushstring(L, "detached");
2110 lua_setfield(L, -2, "type");
2111 lua_pushstring(L, loc.name.c_str());
2112 lua_setfield(L, -2, "name");
2114 case InventoryLocation::UNDEFINED:
2115 case InventoryLocation::CURRENT_PLAYER:
2119 lua_pushstring(L, "undefined");
2120 lua_setfield(L, -2, "type");
2125 InvRef(const InventoryLocation &loc):
2134 // Creates an InvRef and leaves it on top of stack
2135 // Not callable from Lua; all references are created on the C side.
2136 static void create(lua_State *L, const InventoryLocation &loc)
2138 InvRef *o = new InvRef(loc);
2139 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2140 luaL_getmetatable(L, className);
2141 lua_setmetatable(L, -2);
2143 static void createPlayer(lua_State *L, Player *player)
2145 InventoryLocation loc;
2146 loc.setPlayer(player->getName());
2149 static void createNodeMeta(lua_State *L, v3s16 p)
2151 InventoryLocation loc;
2156 static void Register(lua_State *L)
2159 int methodtable = lua_gettop(L);
2160 luaL_newmetatable(L, className);
2161 int metatable = lua_gettop(L);
2163 lua_pushliteral(L, "__metatable");
2164 lua_pushvalue(L, methodtable);
2165 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2167 lua_pushliteral(L, "__index");
2168 lua_pushvalue(L, methodtable);
2169 lua_settable(L, metatable);
2171 lua_pushliteral(L, "__gc");
2172 lua_pushcfunction(L, gc_object);
2173 lua_settable(L, metatable);
2175 lua_pop(L, 1); // drop metatable
2177 luaL_openlib(L, 0, methods, 0); // fill methodtable
2178 lua_pop(L, 1); // drop methodtable
2180 // Cannot be created from Lua
2181 //lua_register(L, className, create_object);
2184 const char InvRef::className[] = "InvRef";
2185 const luaL_reg InvRef::methods[] = {
2186 method(InvRef, is_empty),
2187 method(InvRef, get_size),
2188 method(InvRef, set_size),
2189 method(InvRef, get_width),
2190 method(InvRef, set_width),
2191 method(InvRef, get_stack),
2192 method(InvRef, set_stack),
2193 method(InvRef, get_list),
2194 method(InvRef, set_list),
2195 method(InvRef, add_item),
2196 method(InvRef, room_for_item),
2197 method(InvRef, contains_item),
2198 method(InvRef, remove_item),
2199 method(InvRef, get_location),
2211 ServerEnvironment *m_env;
2213 static const char className[];
2214 static const luaL_reg methods[];
2216 static NodeMetaRef *checkobject(lua_State *L, int narg)
2218 luaL_checktype(L, narg, LUA_TUSERDATA);
2219 void *ud = luaL_checkudata(L, narg, className);
2220 if(!ud) luaL_typerror(L, narg, className);
2221 return *(NodeMetaRef**)ud; // unbox pointer
2224 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2226 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2227 if(meta == NULL && auto_create)
2229 meta = new NodeMetadata(ref->m_env->getGameDef());
2230 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2235 static void reportMetadataChange(NodeMetaRef *ref)
2237 // NOTE: This same code is in rollback_interface.cpp
2238 // Inform other things that the metadata has changed
2239 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2241 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2243 ref->m_env->getMap().dispatchEvent(&event);
2244 // Set the block to be saved
2245 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2247 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2248 "NodeMetaRef::reportMetadataChange");
2251 // Exported functions
2253 // garbage collector
2254 static int gc_object(lua_State *L) {
2255 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2260 // get_string(self, name)
2261 static int l_get_string(lua_State *L)
2263 NodeMetaRef *ref = checkobject(L, 1);
2264 std::string name = luaL_checkstring(L, 2);
2266 NodeMetadata *meta = getmeta(ref, false);
2268 lua_pushlstring(L, "", 0);
2271 std::string str = meta->getString(name);
2272 lua_pushlstring(L, str.c_str(), str.size());
2276 // set_string(self, name, var)
2277 static int l_set_string(lua_State *L)
2279 NodeMetaRef *ref = checkobject(L, 1);
2280 std::string name = luaL_checkstring(L, 2);
2282 const char *s = lua_tolstring(L, 3, &len);
2283 std::string str(s, len);
2285 NodeMetadata *meta = getmeta(ref, !str.empty());
2286 if(meta == NULL || str == meta->getString(name))
2288 meta->setString(name, str);
2289 reportMetadataChange(ref);
2293 // get_int(self, name)
2294 static int l_get_int(lua_State *L)
2296 NodeMetaRef *ref = checkobject(L, 1);
2297 std::string name = lua_tostring(L, 2);
2299 NodeMetadata *meta = getmeta(ref, false);
2301 lua_pushnumber(L, 0);
2304 std::string str = meta->getString(name);
2305 lua_pushnumber(L, stoi(str));
2309 // set_int(self, name, var)
2310 static int l_set_int(lua_State *L)
2312 NodeMetaRef *ref = checkobject(L, 1);
2313 std::string name = lua_tostring(L, 2);
2314 int a = lua_tointeger(L, 3);
2315 std::string str = itos(a);
2317 NodeMetadata *meta = getmeta(ref, true);
2318 if(meta == NULL || str == meta->getString(name))
2320 meta->setString(name, str);
2321 reportMetadataChange(ref);
2325 // get_float(self, name)
2326 static int l_get_float(lua_State *L)
2328 NodeMetaRef *ref = checkobject(L, 1);
2329 std::string name = lua_tostring(L, 2);
2331 NodeMetadata *meta = getmeta(ref, false);
2333 lua_pushnumber(L, 0);
2336 std::string str = meta->getString(name);
2337 lua_pushnumber(L, stof(str));
2341 // set_float(self, name, var)
2342 static int l_set_float(lua_State *L)
2344 NodeMetaRef *ref = checkobject(L, 1);
2345 std::string name = lua_tostring(L, 2);
2346 float a = lua_tonumber(L, 3);
2347 std::string str = ftos(a);
2349 NodeMetadata *meta = getmeta(ref, true);
2350 if(meta == NULL || str == meta->getString(name))
2352 meta->setString(name, str);
2353 reportMetadataChange(ref);
2357 // get_inventory(self)
2358 static int l_get_inventory(lua_State *L)
2360 NodeMetaRef *ref = checkobject(L, 1);
2361 getmeta(ref, true); // try to ensure the metadata exists
2362 InvRef::createNodeMeta(L, ref->m_p);
2367 static int l_to_table(lua_State *L)
2369 NodeMetaRef *ref = checkobject(L, 1);
2371 NodeMetadata *meta = getmeta(ref, true);
2380 std::map<std::string, std::string> fields = meta->getStrings();
2381 for(std::map<std::string, std::string>::const_iterator
2382 i = fields.begin(); i != fields.end(); i++){
2383 const std::string &name = i->first;
2384 const std::string &value = i->second;
2385 lua_pushlstring(L, name.c_str(), name.size());
2386 lua_pushlstring(L, value.c_str(), value.size());
2387 lua_settable(L, -3);
2390 lua_setfield(L, -2, "fields");
2393 Inventory *inv = meta->getInventory();
2395 std::vector<const InventoryList*> lists = inv->getLists();
2396 for(std::vector<const InventoryList*>::const_iterator
2397 i = lists.begin(); i != lists.end(); i++){
2398 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2399 lua_setfield(L, -2, (*i)->getName().c_str());
2402 lua_setfield(L, -2, "inventory");
2406 // from_table(self, table)
2407 static int l_from_table(lua_State *L)
2409 NodeMetaRef *ref = checkobject(L, 1);
2412 if(lua_isnil(L, base)){
2414 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2415 lua_pushboolean(L, true);
2419 // Has metadata; clear old one first
2420 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2421 // Create new metadata
2422 NodeMetadata *meta = getmeta(ref, true);
2424 lua_getfield(L, base, "fields");
2425 int fieldstable = lua_gettop(L);
2427 while(lua_next(L, fieldstable) != 0){
2428 // key at index -2 and value at index -1
2429 std::string name = lua_tostring(L, -2);
2431 const char *cs = lua_tolstring(L, -1, &cl);
2432 std::string value(cs, cl);
2433 meta->setString(name, value);
2434 lua_pop(L, 1); // removes value, keeps key for next iteration
2437 Inventory *inv = meta->getInventory();
2438 lua_getfield(L, base, "inventory");
2439 int inventorytable = lua_gettop(L);
2441 while(lua_next(L, inventorytable) != 0){
2442 // key at index -2 and value at index -1
2443 std::string name = lua_tostring(L, -2);
2444 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2445 lua_pop(L, 1); // removes value, keeps key for next iteration
2447 reportMetadataChange(ref);
2448 lua_pushboolean(L, true);
2453 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2463 // Creates an NodeMetaRef and leaves it on top of stack
2464 // Not callable from Lua; all references are created on the C side.
2465 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2467 NodeMetaRef *o = new NodeMetaRef(p, env);
2468 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2469 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2470 luaL_getmetatable(L, className);
2471 lua_setmetatable(L, -2);
2474 static void Register(lua_State *L)
2477 int methodtable = lua_gettop(L);
2478 luaL_newmetatable(L, className);
2479 int metatable = lua_gettop(L);
2481 lua_pushliteral(L, "__metatable");
2482 lua_pushvalue(L, methodtable);
2483 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2485 lua_pushliteral(L, "__index");
2486 lua_pushvalue(L, methodtable);
2487 lua_settable(L, metatable);
2489 lua_pushliteral(L, "__gc");
2490 lua_pushcfunction(L, gc_object);
2491 lua_settable(L, metatable);
2493 lua_pop(L, 1); // drop metatable
2495 luaL_openlib(L, 0, methods, 0); // fill methodtable
2496 lua_pop(L, 1); // drop methodtable
2498 // Cannot be created from Lua
2499 //lua_register(L, className, create_object);
2502 const char NodeMetaRef::className[] = "NodeMetaRef";
2503 const luaL_reg NodeMetaRef::methods[] = {
2504 method(NodeMetaRef, get_string),
2505 method(NodeMetaRef, set_string),
2506 method(NodeMetaRef, get_int),
2507 method(NodeMetaRef, set_int),
2508 method(NodeMetaRef, get_float),
2509 method(NodeMetaRef, set_float),
2510 method(NodeMetaRef, get_inventory),
2511 method(NodeMetaRef, to_table),
2512 method(NodeMetaRef, from_table),
2523 ServerActiveObject *m_object;
2525 static const char className[];
2526 static const luaL_reg methods[];
2528 static ObjectRef *checkobject(lua_State *L, int narg)
2530 luaL_checktype(L, narg, LUA_TUSERDATA);
2531 void *ud = luaL_checkudata(L, narg, className);
2532 if(!ud) luaL_typerror(L, narg, className);
2533 return *(ObjectRef**)ud; // unbox pointer
2536 static ServerActiveObject* getobject(ObjectRef *ref)
2538 ServerActiveObject *co = ref->m_object;
2542 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2544 ServerActiveObject *obj = getobject(ref);
2547 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2549 return (LuaEntitySAO*)obj;
2552 static PlayerSAO* getplayersao(ObjectRef *ref)
2554 ServerActiveObject *obj = getobject(ref);
2557 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2559 return (PlayerSAO*)obj;
2562 static Player* getplayer(ObjectRef *ref)
2564 PlayerSAO *playersao = getplayersao(ref);
2565 if(playersao == NULL)
2567 return playersao->getPlayer();
2570 // Exported functions
2572 // garbage collector
2573 static int gc_object(lua_State *L) {
2574 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2575 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2581 static int l_remove(lua_State *L)
2583 ObjectRef *ref = checkobject(L, 1);
2584 ServerActiveObject *co = getobject(ref);
2585 if(co == NULL) return 0;
2586 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2587 co->m_removed = true;
2592 // returns: {x=num, y=num, z=num}
2593 static int l_getpos(lua_State *L)
2595 ObjectRef *ref = checkobject(L, 1);
2596 ServerActiveObject *co = getobject(ref);
2597 if(co == NULL) return 0;
2598 v3f pos = co->getBasePosition() / BS;
2600 lua_pushnumber(L, pos.X);
2601 lua_setfield(L, -2, "x");
2602 lua_pushnumber(L, pos.Y);
2603 lua_setfield(L, -2, "y");
2604 lua_pushnumber(L, pos.Z);
2605 lua_setfield(L, -2, "z");
2609 // setpos(self, pos)
2610 static int l_setpos(lua_State *L)
2612 ObjectRef *ref = checkobject(L, 1);
2613 //LuaEntitySAO *co = getluaobject(ref);
2614 ServerActiveObject *co = getobject(ref);
2615 if(co == NULL) return 0;
2617 v3f pos = checkFloatPos(L, 2);
2623 // moveto(self, pos, continuous=false)
2624 static int l_moveto(lua_State *L)
2626 ObjectRef *ref = checkobject(L, 1);
2627 //LuaEntitySAO *co = getluaobject(ref);
2628 ServerActiveObject *co = getobject(ref);
2629 if(co == NULL) return 0;
2631 v3f pos = checkFloatPos(L, 2);
2633 bool continuous = lua_toboolean(L, 3);
2635 co->moveTo(pos, continuous);
2639 // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2640 static int l_punch(lua_State *L)
2642 ObjectRef *ref = checkobject(L, 1);
2643 ObjectRef *puncher_ref = checkobject(L, 2);
2644 ServerActiveObject *co = getobject(ref);
2645 ServerActiveObject *puncher = getobject(puncher_ref);
2646 if(co == NULL) return 0;
2647 if(puncher == NULL) return 0;
2649 if(lua_type(L, 5) != LUA_TTABLE)
2650 dir = co->getBasePosition() - puncher->getBasePosition();
2652 dir = read_v3f(L, 5);
2653 float time_from_last_punch = 1000000;
2654 if(lua_isnumber(L, 3))
2655 time_from_last_punch = lua_tonumber(L, 3);
2656 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2659 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2663 // right_click(self, clicker); clicker = an another ObjectRef
2664 static int l_right_click(lua_State *L)
2666 ObjectRef *ref = checkobject(L, 1);
2667 ObjectRef *ref2 = checkobject(L, 2);
2668 ServerActiveObject *co = getobject(ref);
2669 ServerActiveObject *co2 = getobject(ref2);
2670 if(co == NULL) return 0;
2671 if(co2 == NULL) return 0;
2673 co->rightClick(co2);
2678 // hp = number of hitpoints (2 * number of hearts)
2680 static int l_set_hp(lua_State *L)
2682 ObjectRef *ref = checkobject(L, 1);
2683 luaL_checknumber(L, 2);
2684 ServerActiveObject *co = getobject(ref);
2685 if(co == NULL) return 0;
2686 int hp = lua_tonumber(L, 2);
2687 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2688 <<" hp="<<hp<<std::endl;*/
2696 // returns: number of hitpoints (2 * number of hearts)
2697 // 0 if not applicable to this type of object
2698 static int l_get_hp(lua_State *L)
2700 ObjectRef *ref = checkobject(L, 1);
2701 ServerActiveObject *co = getobject(ref);
2704 lua_pushnumber(L, 1);
2707 int hp = co->getHP();
2708 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2709 <<" hp="<<hp<<std::endl;*/
2711 lua_pushnumber(L, hp);
2715 // get_inventory(self)
2716 static int l_get_inventory(lua_State *L)
2718 ObjectRef *ref = checkobject(L, 1);
2719 ServerActiveObject *co = getobject(ref);
2720 if(co == NULL) return 0;
2722 InventoryLocation loc = co->getInventoryLocation();
2723 if(get_server(L)->getInventory(loc) != NULL)
2724 InvRef::create(L, loc);
2726 lua_pushnil(L); // An object may have no inventory (nil)
2730 // get_wield_list(self)
2731 static int l_get_wield_list(lua_State *L)
2733 ObjectRef *ref = checkobject(L, 1);
2734 ServerActiveObject *co = getobject(ref);
2735 if(co == NULL) return 0;
2737 lua_pushstring(L, co->getWieldList().c_str());
2741 // get_wield_index(self)
2742 static int l_get_wield_index(lua_State *L)
2744 ObjectRef *ref = checkobject(L, 1);
2745 ServerActiveObject *co = getobject(ref);
2746 if(co == NULL) return 0;
2748 lua_pushinteger(L, co->getWieldIndex() + 1);
2752 // get_wielded_item(self)
2753 static int l_get_wielded_item(lua_State *L)
2755 ObjectRef *ref = checkobject(L, 1);
2756 ServerActiveObject *co = getobject(ref);
2759 LuaItemStack::create(L, ItemStack());
2763 LuaItemStack::create(L, co->getWieldedItem());
2767 // set_wielded_item(self, itemstack or itemstring or table or nil)
2768 static int l_set_wielded_item(lua_State *L)
2770 ObjectRef *ref = checkobject(L, 1);
2771 ServerActiveObject *co = getobject(ref);
2772 if(co == NULL) return 0;
2774 ItemStack item = read_item(L, 2);
2775 bool success = co->setWieldedItem(item);
2776 lua_pushboolean(L, success);
2780 // set_armor_groups(self, groups)
2781 static int l_set_armor_groups(lua_State *L)
2783 ObjectRef *ref = checkobject(L, 1);
2784 ServerActiveObject *co = getobject(ref);
2785 if(co == NULL) return 0;
2787 ItemGroupList groups;
2788 read_groups(L, 2, groups);
2789 co->setArmorGroups(groups);
2793 // set_animation(self, frame_range, frame_speed, frame_blend)
2794 static int l_set_animation(lua_State *L)
2796 ObjectRef *ref = checkobject(L, 1);
2797 ServerActiveObject *co = getobject(ref);
2798 if(co == NULL) return 0;
2800 v2f frames = v2f(1, 1);
2801 if(!lua_isnil(L, 2))
2802 frames = read_v2f(L, 2);
2803 float frame_speed = 15;
2804 if(!lua_isnil(L, 3))
2805 frame_speed = lua_tonumber(L, 3);
2806 float frame_blend = 0;
2807 if(!lua_isnil(L, 4))
2808 frame_blend = lua_tonumber(L, 4);
2809 co->setAnimation(frames, frame_speed, frame_blend);
2813 // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2814 static int l_set_bone_position(lua_State *L)
2816 ObjectRef *ref = checkobject(L, 1);
2817 ServerActiveObject *co = getobject(ref);
2818 if(co == NULL) return 0;
2820 std::string bone = "";
2821 if(!lua_isnil(L, 2))
2822 bone = lua_tostring(L, 2);
2823 v3f position = v3f(0, 0, 0);
2824 if(!lua_isnil(L, 3))
2825 position = read_v3f(L, 3);
2826 v3f rotation = v3f(0, 0, 0);
2827 if(!lua_isnil(L, 4))
2828 rotation = read_v3f(L, 4);
2829 co->setBonePosition(bone, position, rotation);
2833 // set_attach(self, parent, bone, position, rotation)
2834 static int l_set_attach(lua_State *L)
2836 ObjectRef *ref = checkobject(L, 1);
2837 ObjectRef *parent_ref = checkobject(L, 2);
2838 ServerActiveObject *co = getobject(ref);
2839 ServerActiveObject *parent = getobject(parent_ref);
2840 if(co == NULL) return 0;
2841 if(parent == NULL) return 0;
2843 std::string bone = "";
2844 if(!lua_isnil(L, 3))
2845 bone = lua_tostring(L, 3);
2846 v3f position = v3f(0, 0, 0);
2847 if(!lua_isnil(L, 4))
2848 position = read_v3f(L, 4);
2849 v3f rotation = v3f(0, 0, 0);
2850 if(!lua_isnil(L, 5))
2851 rotation = read_v3f(L, 5);
2852 co->setAttachment(parent->getId(), bone, position, rotation);
2857 static int l_set_detach(lua_State *L)
2859 ObjectRef *ref = checkobject(L, 1);
2860 ServerActiveObject *co = getobject(ref);
2861 if(co == NULL) return 0;
2863 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2867 // set_properties(self, properties)
2868 static int l_set_properties(lua_State *L)
2870 ObjectRef *ref = checkobject(L, 1);
2871 ServerActiveObject *co = getobject(ref);
2872 if(co == NULL) return 0;
2873 ObjectProperties *prop = co->accessObjectProperties();
2876 read_object_properties(L, 2, prop);
2877 co->notifyObjectPropertiesModified();
2881 /* LuaEntitySAO-only */
2883 // setvelocity(self, {x=num, y=num, z=num})
2884 static int l_setvelocity(lua_State *L)
2886 ObjectRef *ref = checkobject(L, 1);
2887 LuaEntitySAO *co = getluaobject(ref);
2888 if(co == NULL) return 0;
2889 v3f pos = checkFloatPos(L, 2);
2891 co->setVelocity(pos);
2895 // getvelocity(self)
2896 static int l_getvelocity(lua_State *L)
2898 ObjectRef *ref = checkobject(L, 1);
2899 LuaEntitySAO *co = getluaobject(ref);
2900 if(co == NULL) return 0;
2902 v3f v = co->getVelocity();
2907 // setacceleration(self, {x=num, y=num, z=num})
2908 static int l_setacceleration(lua_State *L)
2910 ObjectRef *ref = checkobject(L, 1);
2911 LuaEntitySAO *co = getluaobject(ref);
2912 if(co == NULL) return 0;
2914 v3f pos = checkFloatPos(L, 2);
2916 co->setAcceleration(pos);
2920 // getacceleration(self)
2921 static int l_getacceleration(lua_State *L)
2923 ObjectRef *ref = checkobject(L, 1);
2924 LuaEntitySAO *co = getluaobject(ref);
2925 if(co == NULL) return 0;
2927 v3f v = co->getAcceleration();
2932 // setyaw(self, radians)
2933 static int l_setyaw(lua_State *L)
2935 ObjectRef *ref = checkobject(L, 1);
2936 LuaEntitySAO *co = getluaobject(ref);
2937 if(co == NULL) return 0;
2938 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2945 static int l_getyaw(lua_State *L)
2947 ObjectRef *ref = checkobject(L, 1);
2948 LuaEntitySAO *co = getluaobject(ref);
2949 if(co == NULL) return 0;
2951 float yaw = co->getYaw() * core::DEGTORAD;
2952 lua_pushnumber(L, yaw);
2956 // settexturemod(self, mod)
2957 static int l_settexturemod(lua_State *L)
2959 ObjectRef *ref = checkobject(L, 1);
2960 LuaEntitySAO *co = getluaobject(ref);
2961 if(co == NULL) return 0;
2963 std::string mod = luaL_checkstring(L, 2);
2964 co->setTextureMod(mod);
2968 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2969 // select_horiz_by_yawpitch=false)
2970 static int l_setsprite(lua_State *L)
2972 ObjectRef *ref = checkobject(L, 1);
2973 LuaEntitySAO *co = getluaobject(ref);
2974 if(co == NULL) return 0;
2977 if(!lua_isnil(L, 2))
2978 p = read_v2s16(L, 2);
2980 if(!lua_isnil(L, 3))
2981 num_frames = lua_tonumber(L, 3);
2982 float framelength = 0.2;
2983 if(!lua_isnil(L, 4))
2984 framelength = lua_tonumber(L, 4);
2985 bool select_horiz_by_yawpitch = false;
2986 if(!lua_isnil(L, 5))
2987 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2988 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2993 // get_entity_name(self)
2994 static int l_get_entity_name(lua_State *L)
2996 ObjectRef *ref = checkobject(L, 1);
2997 LuaEntitySAO *co = getluaobject(ref);
2998 if(co == NULL) return 0;
3000 std::string name = co->getName();
3001 lua_pushstring(L, name.c_str());
3005 // get_luaentity(self)
3006 static int l_get_luaentity(lua_State *L)
3008 ObjectRef *ref = checkobject(L, 1);
3009 LuaEntitySAO *co = getluaobject(ref);
3010 if(co == NULL) return 0;
3012 luaentity_get(L, co->getId());
3019 static int l_is_player(lua_State *L)
3021 ObjectRef *ref = checkobject(L, 1);
3022 Player *player = getplayer(ref);
3023 lua_pushboolean(L, (player != NULL));
3027 // get_player_name(self)
3028 static int l_get_player_name(lua_State *L)
3030 ObjectRef *ref = checkobject(L, 1);
3031 Player *player = getplayer(ref);
3033 lua_pushlstring(L, "", 0);
3037 lua_pushstring(L, player->getName());
3041 // get_look_dir(self)
3042 static int l_get_look_dir(lua_State *L)
3044 ObjectRef *ref = checkobject(L, 1);
3045 Player *player = getplayer(ref);
3046 if(player == NULL) return 0;
3048 float pitch = player->getRadPitch();
3049 float yaw = player->getRadYaw();
3050 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
3055 // get_look_pitch(self)
3056 static int l_get_look_pitch(lua_State *L)
3058 ObjectRef *ref = checkobject(L, 1);
3059 Player *player = getplayer(ref);
3060 if(player == NULL) return 0;
3062 lua_pushnumber(L, player->getRadPitch());
3066 // get_look_yaw(self)
3067 static int l_get_look_yaw(lua_State *L)
3069 ObjectRef *ref = checkobject(L, 1);
3070 Player *player = getplayer(ref);
3071 if(player == NULL) return 0;
3073 lua_pushnumber(L, player->getRadYaw());
3077 // set_inventory_formspec(self, formspec)
3078 static int l_set_inventory_formspec(lua_State *L)
3080 ObjectRef *ref = checkobject(L, 1);
3081 Player *player = getplayer(ref);
3082 if(player == NULL) return 0;
3083 std::string formspec = luaL_checkstring(L, 2);
3085 player->inventory_formspec = formspec;
3086 get_server(L)->reportInventoryFormspecModified(player->getName());
3087 lua_pushboolean(L, true);
3091 // get_inventory_formspec(self) -> formspec
3092 static int l_get_inventory_formspec(lua_State *L)
3094 ObjectRef *ref = checkobject(L, 1);
3095 Player *player = getplayer(ref);
3096 if(player == NULL) return 0;
3098 std::string formspec = player->inventory_formspec;
3099 lua_pushlstring(L, formspec.c_str(), formspec.size());
3103 // get_player_control(self)
3104 static int l_get_player_control(lua_State *L)
3106 ObjectRef *ref = checkobject(L, 1);
3107 Player *player = getplayer(ref);
3109 lua_pushlstring(L, "", 0);
3113 PlayerControl control = player->getPlayerControl();
3115 lua_pushboolean(L, control.up);
3116 lua_setfield(L, -2, "up");
3117 lua_pushboolean(L, control.down);
3118 lua_setfield(L, -2, "down");
3119 lua_pushboolean(L, control.left);
3120 lua_setfield(L, -2, "left");
3121 lua_pushboolean(L, control.right);
3122 lua_setfield(L, -2, "right");
3123 lua_pushboolean(L, control.jump);
3124 lua_setfield(L, -2, "jump");
3125 lua_pushboolean(L, control.aux1);
3126 lua_setfield(L, -2, "aux1");
3127 lua_pushboolean(L, control.sneak);
3128 lua_setfield(L, -2, "sneak");
3129 lua_pushboolean(L, control.LMB);
3130 lua_setfield(L, -2, "LMB");
3131 lua_pushboolean(L, control.RMB);
3132 lua_setfield(L, -2, "RMB");
3136 // get_player_control_bits(self)
3137 static int l_get_player_control_bits(lua_State *L)
3139 ObjectRef *ref = checkobject(L, 1);
3140 Player *player = getplayer(ref);
3142 lua_pushlstring(L, "", 0);
3146 lua_pushnumber(L, player->keyPressed);
3151 ObjectRef(ServerActiveObject *object):
3154 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3160 infostream<<"ObjectRef destructing for id="
3161 <<m_object->getId()<<std::endl;
3163 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3166 // Creates an ObjectRef and leaves it on top of stack
3167 // Not callable from Lua; all references are created on the C side.
3168 static void create(lua_State *L, ServerActiveObject *object)
3170 ObjectRef *o = new ObjectRef(object);
3171 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3172 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3173 luaL_getmetatable(L, className);
3174 lua_setmetatable(L, -2);
3177 static void set_null(lua_State *L)
3179 ObjectRef *o = checkobject(L, -1);
3183 static void Register(lua_State *L)
3186 int methodtable = lua_gettop(L);
3187 luaL_newmetatable(L, className);
3188 int metatable = lua_gettop(L);
3190 lua_pushliteral(L, "__metatable");
3191 lua_pushvalue(L, methodtable);
3192 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3194 lua_pushliteral(L, "__index");
3195 lua_pushvalue(L, methodtable);
3196 lua_settable(L, metatable);
3198 lua_pushliteral(L, "__gc");
3199 lua_pushcfunction(L, gc_object);
3200 lua_settable(L, metatable);
3202 lua_pop(L, 1); // drop metatable
3204 luaL_openlib(L, 0, methods, 0); // fill methodtable
3205 lua_pop(L, 1); // drop methodtable
3207 // Cannot be created from Lua
3208 //lua_register(L, className, create_object);
3211 const char ObjectRef::className[] = "ObjectRef";
3212 const luaL_reg ObjectRef::methods[] = {
3213 // ServerActiveObject
3214 method(ObjectRef, remove),
3215 method(ObjectRef, getpos),
3216 method(ObjectRef, setpos),
3217 method(ObjectRef, moveto),
3218 method(ObjectRef, punch),
3219 method(ObjectRef, right_click),
3220 method(ObjectRef, set_hp),
3221 method(ObjectRef, get_hp),
3222 method(ObjectRef, get_inventory),
3223 method(ObjectRef, get_wield_list),
3224 method(ObjectRef, get_wield_index),
3225 method(ObjectRef, get_wielded_item),
3226 method(ObjectRef, set_wielded_item),
3227 method(ObjectRef, set_armor_groups),
3228 method(ObjectRef, set_animation),
3229 method(ObjectRef, set_bone_position),
3230 method(ObjectRef, set_attach),
3231 method(ObjectRef, set_detach),
3232 method(ObjectRef, set_properties),
3233 // LuaEntitySAO-only
3234 method(ObjectRef, setvelocity),
3235 method(ObjectRef, getvelocity),
3236 method(ObjectRef, setacceleration),
3237 method(ObjectRef, getacceleration),
3238 method(ObjectRef, setyaw),
3239 method(ObjectRef, getyaw),
3240 method(ObjectRef, settexturemod),
3241 method(ObjectRef, setsprite),
3242 method(ObjectRef, get_entity_name),
3243 method(ObjectRef, get_luaentity),
3245 method(ObjectRef, is_player),
3246 method(ObjectRef, get_player_name),
3247 method(ObjectRef, get_look_dir),
3248 method(ObjectRef, get_look_pitch),
3249 method(ObjectRef, get_look_yaw),
3250 method(ObjectRef, set_inventory_formspec),
3251 method(ObjectRef, get_inventory_formspec),
3252 method(ObjectRef, get_player_control),
3253 method(ObjectRef, get_player_control_bits),
3257 // Creates a new anonymous reference if cobj=NULL or id=0
3258 static void objectref_get_or_create(lua_State *L,
3259 ServerActiveObject *cobj)
3261 if(cobj == NULL || cobj->getId() == 0){
3262 ObjectRef::create(L, cobj);
3264 objectref_get(L, cobj->getId());
3268 class LuaPerlinNoise
3275 static const char className[];
3276 static const luaL_reg methods[];
3278 // Exported functions
3280 // garbage collector
3281 static int gc_object(lua_State *L)
3283 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3288 static int l_get2d(lua_State *L)
3290 LuaPerlinNoise *o = checkobject(L, 1);
3291 v2f pos2d = read_v2f(L,2);
3292 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3293 lua_pushnumber(L, val);
3296 static int l_get3d(lua_State *L)
3298 LuaPerlinNoise *o = checkobject(L, 1);
3299 v3f pos3d = read_v3f(L,2);
3300 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3301 lua_pushnumber(L, val);
3306 LuaPerlinNoise(int a_seed, int a_octaves, float a_persistence,
3310 persistence(a_persistence),
3319 // LuaPerlinNoise(seed, octaves, persistence, scale)
3320 // Creates an LuaPerlinNoise and leaves it on top of stack
3321 static int create_object(lua_State *L)
3323 int seed = luaL_checkint(L, 1);
3324 int octaves = luaL_checkint(L, 2);
3325 float persistence = luaL_checknumber(L, 3);
3326 float scale = luaL_checknumber(L, 4);
3327 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3328 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3329 luaL_getmetatable(L, className);
3330 lua_setmetatable(L, -2);
3334 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3336 luaL_checktype(L, narg, LUA_TUSERDATA);
3337 void *ud = luaL_checkudata(L, narg, className);
3338 if(!ud) luaL_typerror(L, narg, className);
3339 return *(LuaPerlinNoise**)ud; // unbox pointer
3342 static void Register(lua_State *L)
3345 int methodtable = lua_gettop(L);
3346 luaL_newmetatable(L, className);
3347 int metatable = lua_gettop(L);
3349 lua_pushliteral(L, "__metatable");
3350 lua_pushvalue(L, methodtable);
3351 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3353 lua_pushliteral(L, "__index");
3354 lua_pushvalue(L, methodtable);
3355 lua_settable(L, metatable);
3357 lua_pushliteral(L, "__gc");
3358 lua_pushcfunction(L, gc_object);
3359 lua_settable(L, metatable);
3361 lua_pop(L, 1); // drop metatable
3363 luaL_openlib(L, 0, methods, 0); // fill methodtable
3364 lua_pop(L, 1); // drop methodtable
3366 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3367 lua_register(L, className, create_object);
3370 const char LuaPerlinNoise::className[] = "PerlinNoise";
3371 const luaL_reg LuaPerlinNoise::methods[] = {
3372 method(LuaPerlinNoise, get2d),
3373 method(LuaPerlinNoise, get3d),
3380 class LuaPerlinNoiseMap
3384 static const char className[];
3385 static const luaL_reg methods[];
3387 static int gc_object(lua_State *L)
3389 LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1));
3394 static int l_get2dMap(lua_State *L)
3398 LuaPerlinNoiseMap *o = checkobject(L, 1);
3399 v2f p = read_v2f(L, 2);
3401 Noise *n = o->noise;
3402 n->perlinMap2D(p.X, p.Y);
3405 for (int y = 0; y != n->sy; y++) {
3407 for (int x = 0; x != n->sx; x++) {
3408 float noiseval = n->np->offset + n->np->scale * n->result[i++];
3409 lua_pushnumber(L, noiseval);
3410 lua_rawseti(L, -2, x + 1);
3412 lua_rawseti(L, -2, y + 1);
3417 static int l_get3dMap(lua_State *L)
3421 LuaPerlinNoiseMap *o = checkobject(L, 1);
3422 v3f p = read_v3f(L, 2);
3424 Noise *n = o->noise;
3425 n->perlinMap3D(p.X, p.Y, p.Z);
3428 for (int z = 0; z != n->sz; z++) {
3430 for (int y = 0; y != n->sy; y++) {
3432 for (int x = 0; x != n->sx; x++) {
3433 lua_pushnumber(L, n->np->offset + n->np->scale * n->result[i++]);
3434 lua_rawseti(L, -2, x + 1);
3436 lua_rawseti(L, -2, y + 1);
3438 lua_rawseti(L, -2, z + 1);
3444 LuaPerlinNoiseMap(NoiseParams *np, int seed, v3s16 size) {
3445 noise = new Noise(np, seed, size.X, size.Y, size.Z);
3448 ~LuaPerlinNoiseMap()
3454 // LuaPerlinNoiseMap(np, size)
3455 // Creates an LuaPerlinNoiseMap and leaves it on top of stack
3456 static int create_object(lua_State *L)
3458 NoiseParams *np = read_noiseparams(L, 1);
3461 v3s16 size = read_v3s16(L, 2);
3463 LuaPerlinNoiseMap *o = new LuaPerlinNoiseMap(np, 0, size);
3464 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3465 luaL_getmetatable(L, className);
3466 lua_setmetatable(L, -2);
3470 static LuaPerlinNoiseMap *checkobject(lua_State *L, int narg)
3472 luaL_checktype(L, narg, LUA_TUSERDATA);
3474 void *ud = luaL_checkudata(L, narg, className);
3476 luaL_typerror(L, narg, className);
3478 return *(LuaPerlinNoiseMap **)ud; // unbox pointer
3481 static void Register(lua_State *L)
3484 int methodtable = lua_gettop(L);
3485 luaL_newmetatable(L, className);
3486 int metatable = lua_gettop(L);
3488 lua_pushliteral(L, "__metatable");
3489 lua_pushvalue(L, methodtable);
3490 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3492 lua_pushliteral(L, "__index");
3493 lua_pushvalue(L, methodtable);
3494 lua_settable(L, metatable);
3496 lua_pushliteral(L, "__gc");
3497 lua_pushcfunction(L, gc_object);
3498 lua_settable(L, metatable);
3500 lua_pop(L, 1); // drop metatable
3502 luaL_openlib(L, 0, methods, 0); // fill methodtable
3503 lua_pop(L, 1); // drop methodtable
3505 // Can be created from Lua (PerlinNoiseMap(np, size)
3506 lua_register(L, className, create_object);
3509 const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap";
3510 const luaL_reg LuaPerlinNoiseMap::methods[] = {
3511 method(LuaPerlinNoiseMap, get2dMap),
3512 method(LuaPerlinNoiseMap, get3dMap),
3524 ServerEnvironment *m_env;
3526 static const char className[];
3527 static const luaL_reg methods[];
3529 static int gc_object(lua_State *L) {
3530 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3535 static NodeTimerRef *checkobject(lua_State *L, int narg)
3537 luaL_checktype(L, narg, LUA_TUSERDATA);
3538 void *ud = luaL_checkudata(L, narg, className);
3539 if(!ud) luaL_typerror(L, narg, className);
3540 return *(NodeTimerRef**)ud; // unbox pointer
3543 static int l_set(lua_State *L)
3545 NodeTimerRef *o = checkobject(L, 1);
3546 ServerEnvironment *env = o->m_env;
3547 if(env == NULL) return 0;
3548 f32 t = luaL_checknumber(L,2);
3549 f32 e = luaL_checknumber(L,3);
3550 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3554 static int l_start(lua_State *L)
3556 NodeTimerRef *o = checkobject(L, 1);
3557 ServerEnvironment *env = o->m_env;
3558 if(env == NULL) return 0;
3559 f32 t = luaL_checknumber(L,2);
3560 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3564 static int l_stop(lua_State *L)
3566 NodeTimerRef *o = checkobject(L, 1);
3567 ServerEnvironment *env = o->m_env;
3568 if(env == NULL) return 0;
3569 env->getMap().removeNodeTimer(o->m_p);
3573 static int l_is_started(lua_State *L)
3575 NodeTimerRef *o = checkobject(L, 1);
3576 ServerEnvironment *env = o->m_env;
3577 if(env == NULL) return 0;
3579 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3580 lua_pushboolean(L,(t.timeout != 0));
3584 static int l_get_timeout(lua_State *L)
3586 NodeTimerRef *o = checkobject(L, 1);
3587 ServerEnvironment *env = o->m_env;
3588 if(env == NULL) return 0;
3590 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3591 lua_pushnumber(L,t.timeout);
3595 static int l_get_elapsed(lua_State *L)
3597 NodeTimerRef *o = checkobject(L, 1);
3598 ServerEnvironment *env = o->m_env;
3599 if(env == NULL) return 0;
3601 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3602 lua_pushnumber(L,t.elapsed);
3607 NodeTimerRef(v3s16 p, ServerEnvironment *env):
3617 // Creates an NodeTimerRef and leaves it on top of stack
3618 // Not callable from Lua; all references are created on the C side.
3619 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3621 NodeTimerRef *o = new NodeTimerRef(p, env);
3622 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3623 luaL_getmetatable(L, className);
3624 lua_setmetatable(L, -2);
3627 static void set_null(lua_State *L)
3629 NodeTimerRef *o = checkobject(L, -1);
3633 static void Register(lua_State *L)
3636 int methodtable = lua_gettop(L);
3637 luaL_newmetatable(L, className);
3638 int metatable = lua_gettop(L);
3640 lua_pushliteral(L, "__metatable");
3641 lua_pushvalue(L, methodtable);
3642 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3644 lua_pushliteral(L, "__index");
3645 lua_pushvalue(L, methodtable);
3646 lua_settable(L, metatable);
3648 lua_pushliteral(L, "__gc");
3649 lua_pushcfunction(L, gc_object);
3650 lua_settable(L, metatable);
3652 lua_pop(L, 1); // drop metatable
3654 luaL_openlib(L, 0, methods, 0); // fill methodtable
3655 lua_pop(L, 1); // drop methodtable
3657 // Cannot be created from Lua
3658 //lua_register(L, className, create_object);
3661 const char NodeTimerRef::className[] = "NodeTimerRef";
3662 const luaL_reg NodeTimerRef::methods[] = {
3663 method(NodeTimerRef, start),
3664 method(NodeTimerRef, set),
3665 method(NodeTimerRef, stop),
3666 method(NodeTimerRef, is_started),
3667 method(NodeTimerRef, get_timeout),
3668 method(NodeTimerRef, get_elapsed),
3679 ServerEnvironment *m_env;
3681 static const char className[];
3682 static const luaL_reg methods[];
3684 static int gc_object(lua_State *L) {
3685 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3690 static EnvRef *checkobject(lua_State *L, int narg)
3692 luaL_checktype(L, narg, LUA_TUSERDATA);
3693 void *ud = luaL_checkudata(L, narg, className);
3694 if(!ud) luaL_typerror(L, narg, className);
3695 return *(EnvRef**)ud; // unbox pointer
3698 // Exported functions
3700 // EnvRef:set_node(pos, node)
3701 // pos = {x=num, y=num, z=num}
3702 static int l_set_node(lua_State *L)
3704 EnvRef *o = checkobject(L, 1);
3705 ServerEnvironment *env = o->m_env;
3706 if(env == NULL) return 0;
3707 INodeDefManager *ndef = env->getGameDef()->ndef();
3709 v3s16 pos = read_v3s16(L, 2);
3710 MapNode n = readnode(L, 3, ndef);
3712 bool succeeded = env->setNode(pos, n);
3713 lua_pushboolean(L, succeeded);
3717 static int l_add_node(lua_State *L)
3719 return l_set_node(L);
3722 // EnvRef:remove_node(pos)
3723 // pos = {x=num, y=num, z=num}
3724 static int l_remove_node(lua_State *L)
3726 EnvRef *o = checkobject(L, 1);
3727 ServerEnvironment *env = o->m_env;
3728 if(env == NULL) return 0;
3729 INodeDefManager *ndef = env->getGameDef()->ndef();
3731 v3s16 pos = read_v3s16(L, 2);
3733 bool succeeded = env->removeNode(pos);
3734 lua_pushboolean(L, succeeded);
3738 // EnvRef:get_node(pos)
3739 // pos = {x=num, y=num, z=num}
3740 static int l_get_node(lua_State *L)
3742 EnvRef *o = checkobject(L, 1);
3743 ServerEnvironment *env = o->m_env;
3744 if(env == NULL) return 0;
3746 v3s16 pos = read_v3s16(L, 2);
3748 MapNode n = env->getMap().getNodeNoEx(pos);
3750 pushnode(L, n, env->getGameDef()->ndef());
3754 // EnvRef:get_node_or_nil(pos)
3755 // pos = {x=num, y=num, z=num}
3756 static int l_get_node_or_nil(lua_State *L)
3758 EnvRef *o = checkobject(L, 1);
3759 ServerEnvironment *env = o->m_env;
3760 if(env == NULL) return 0;
3762 v3s16 pos = read_v3s16(L, 2);
3765 MapNode n = env->getMap().getNode(pos);
3767 pushnode(L, n, env->getGameDef()->ndef());
3769 } catch(InvalidPositionException &e)
3776 // EnvRef:get_node_light(pos, timeofday)
3777 // pos = {x=num, y=num, z=num}
3778 // timeofday: nil = current time, 0 = night, 0.5 = day
3779 static int l_get_node_light(lua_State *L)
3781 EnvRef *o = checkobject(L, 1);
3782 ServerEnvironment *env = o->m_env;
3783 if(env == NULL) return 0;
3785 v3s16 pos = read_v3s16(L, 2);
3786 u32 time_of_day = env->getTimeOfDay();
3787 if(lua_isnumber(L, 3))
3788 time_of_day = 24000.0 * lua_tonumber(L, 3);
3789 time_of_day %= 24000;
3790 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3791 MapNode n = env->getMap().getNodeNoEx(pos);
3793 MapNode n = env->getMap().getNode(pos);
3794 INodeDefManager *ndef = env->getGameDef()->ndef();
3795 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3797 } catch(InvalidPositionException &e)
3804 // EnvRef:place_node(pos, node)
3805 // pos = {x=num, y=num, z=num}
3806 static int l_place_node(lua_State *L)
3808 EnvRef *o = checkobject(L, 1);
3809 ServerEnvironment *env = o->m_env;
3810 if(env == NULL) return 0;
3811 v3s16 pos = read_v3s16(L, 2);
3812 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3814 // Don't attempt to load non-loaded area as of now
3815 MapNode n_old = env->getMap().getNodeNoEx(pos);
3816 if(n_old.getContent() == CONTENT_IGNORE){
3817 lua_pushboolean(L, false);
3820 // Create item to place
3821 INodeDefManager *ndef = get_server(L)->ndef();
3822 IItemDefManager *idef = get_server(L)->idef();
3823 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3824 // Make pointed position
3825 PointedThing pointed;
3826 pointed.type = POINTEDTHING_NODE;
3827 pointed.node_abovesurface = pos;
3828 pointed.node_undersurface = pos + v3s16(0,-1,0);
3829 // Place it with a NULL placer (appears in Lua as a non-functional
3831 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3832 lua_pushboolean(L, success);
3836 // EnvRef:dig_node(pos)
3837 // pos = {x=num, y=num, z=num}
3838 static int l_dig_node(lua_State *L)
3840 EnvRef *o = checkobject(L, 1);
3841 ServerEnvironment *env = o->m_env;
3842 if(env == NULL) return 0;
3843 v3s16 pos = read_v3s16(L, 2);
3845 // Don't attempt to load non-loaded area as of now
3846 MapNode n = env->getMap().getNodeNoEx(pos);
3847 if(n.getContent() == CONTENT_IGNORE){
3848 lua_pushboolean(L, false);
3851 // Dig it out with a NULL digger (appears in Lua as a
3852 // non-functional ObjectRef)
3853 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3854 lua_pushboolean(L, success);
3858 // EnvRef:punch_node(pos)
3859 // pos = {x=num, y=num, z=num}
3860 static int l_punch_node(lua_State *L)
3862 EnvRef *o = checkobject(L, 1);
3863 ServerEnvironment *env = o->m_env;
3864 if(env == NULL) return 0;
3865 v3s16 pos = read_v3s16(L, 2);
3867 // Don't attempt to load non-loaded area as of now
3868 MapNode n = env->getMap().getNodeNoEx(pos);
3869 if(n.getContent() == CONTENT_IGNORE){
3870 lua_pushboolean(L, false);
3873 // Punch it with a NULL puncher (appears in Lua as a non-functional
3875 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3876 lua_pushboolean(L, success);
3880 // EnvRef:get_meta(pos)
3881 static int l_get_meta(lua_State *L)
3883 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3884 EnvRef *o = checkobject(L, 1);
3885 ServerEnvironment *env = o->m_env;
3886 if(env == NULL) return 0;
3888 v3s16 p = read_v3s16(L, 2);
3889 NodeMetaRef::create(L, p, env);
3893 // EnvRef:get_node_timer(pos)
3894 static int l_get_node_timer(lua_State *L)
3896 EnvRef *o = checkobject(L, 1);
3897 ServerEnvironment *env = o->m_env;
3898 if(env == NULL) return 0;
3900 v3s16 p = read_v3s16(L, 2);
3901 NodeTimerRef::create(L, p, env);
3905 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3906 // pos = {x=num, y=num, z=num}
3907 static int l_add_entity(lua_State *L)
3909 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3910 EnvRef *o = checkobject(L, 1);
3911 ServerEnvironment *env = o->m_env;
3912 if(env == NULL) return 0;
3914 v3f pos = checkFloatPos(L, 2);
3916 const char *name = luaL_checkstring(L, 3);
3918 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3919 int objectid = env->addActiveObject(obj);
3920 // If failed to add, return nothing (reads as nil)
3924 objectref_get_or_create(L, obj);
3928 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3929 // pos = {x=num, y=num, z=num}
3930 static int l_add_item(lua_State *L)
3932 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3933 EnvRef *o = checkobject(L, 1);
3934 ServerEnvironment *env = o->m_env;
3935 if(env == NULL) return 0;
3937 v3f pos = checkFloatPos(L, 2);
3939 ItemStack item = read_item(L, 3);
3940 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3942 // Use minetest.spawn_item to spawn a __builtin:item
3943 lua_getglobal(L, "minetest");
3944 lua_getfield(L, -1, "spawn_item");
3945 if(lua_isnil(L, -1))
3947 lua_pushvalue(L, 2);
3948 lua_pushstring(L, item.getItemString().c_str());
3949 if(lua_pcall(L, 2, 1, 0))
3950 script_error(L, "error: %s", lua_tostring(L, -1));
3952 /*lua_pushvalue(L, 1);
3953 lua_pushstring(L, "__builtin:item");
3954 lua_pushstring(L, item.getItemString().c_str());
3955 return l_add_entity(L);*/
3957 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3958 int objectid = env->addActiveObject(obj);
3959 // If failed to add, return nothing (reads as nil)
3963 objectref_get_or_create(L, obj);
3967 // EnvRef:add_rat(pos)
3968 // pos = {x=num, y=num, z=num}
3969 static int l_add_rat(lua_State *L)
3971 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3972 <<" Doing nothing."<<std::endl;
3976 // EnvRef:add_firefly(pos)
3977 // pos = {x=num, y=num, z=num}
3978 static int l_add_firefly(lua_State *L)
3980 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3981 <<" Doing nothing."<<std::endl;
3985 // EnvRef:get_player_by_name(name)
3986 static int l_get_player_by_name(lua_State *L)
3988 EnvRef *o = checkobject(L, 1);
3989 ServerEnvironment *env = o->m_env;
3990 if(env == NULL) return 0;
3992 const char *name = luaL_checkstring(L, 2);
3993 Player *player = env->getPlayer(name);
3998 PlayerSAO *sao = player->getPlayerSAO();
4003 // Put player on stack
4004 objectref_get_or_create(L, sao);
4008 // EnvRef:get_objects_inside_radius(pos, radius)
4009 static int l_get_objects_inside_radius(lua_State *L)
4011 // Get the table insert function
4012 lua_getglobal(L, "table");
4013 lua_getfield(L, -1, "insert");
4014 int table_insert = lua_gettop(L);
4016 EnvRef *o = checkobject(L, 1);
4017 ServerEnvironment *env = o->m_env;
4018 if(env == NULL) return 0;
4020 v3f pos = checkFloatPos(L, 2);
4021 float radius = luaL_checknumber(L, 3) * BS;
4022 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
4024 int table = lua_gettop(L);
4025 for(std::set<u16>::const_iterator
4026 i = ids.begin(); i != ids.end(); i++){
4027 ServerActiveObject *obj = env->getActiveObject(*i);
4028 // Insert object reference into table
4029 lua_pushvalue(L, table_insert);
4030 lua_pushvalue(L, table);
4031 objectref_get_or_create(L, obj);
4032 if(lua_pcall(L, 2, 0, 0))
4033 script_error(L, "error: %s", lua_tostring(L, -1));
4038 // EnvRef:set_timeofday(val)
4040 static int l_set_timeofday(lua_State *L)
4042 EnvRef *o = checkobject(L, 1);
4043 ServerEnvironment *env = o->m_env;
4044 if(env == NULL) return 0;
4046 float timeofday_f = luaL_checknumber(L, 2);
4047 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
4048 int timeofday_mh = (int)(timeofday_f * 24000.0);
4049 // This should be set directly in the environment but currently
4050 // such changes aren't immediately sent to the clients, so call
4051 // the server instead.
4052 //env->setTimeOfDay(timeofday_mh);
4053 get_server(L)->setTimeOfDay(timeofday_mh);
4057 // EnvRef:get_timeofday() -> 0...1
4058 static int l_get_timeofday(lua_State *L)
4060 EnvRef *o = checkobject(L, 1);
4061 ServerEnvironment *env = o->m_env;
4062 if(env == NULL) return 0;
4064 int timeofday_mh = env->getTimeOfDay();
4065 float timeofday_f = (float)timeofday_mh / 24000.0;
4066 lua_pushnumber(L, timeofday_f);
4071 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
4072 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
4073 static int l_find_node_near(lua_State *L)
4075 EnvRef *o = checkobject(L, 1);
4076 ServerEnvironment *env = o->m_env;
4077 if(env == NULL) return 0;
4078 INodeDefManager *ndef = get_server(L)->ndef();
4079 v3s16 pos = read_v3s16(L, 2);
4080 int radius = luaL_checkinteger(L, 3);
4081 std::set<content_t> filter;
4082 if(lua_istable(L, 4)){
4085 while(lua_next(L, table) != 0){
4086 // key at index -2 and value at index -1
4087 luaL_checktype(L, -1, LUA_TSTRING);
4088 ndef->getIds(lua_tostring(L, -1), filter);
4089 // removes value, keeps key for next iteration
4092 } else if(lua_isstring(L, 4)){
4093 ndef->getIds(lua_tostring(L, 4), filter);
4096 for(int d=1; d<=radius; d++){
4097 core::list<v3s16> list;
4098 getFacePositions(list, d);
4099 for(core::list<v3s16>::Iterator i = list.begin();
4100 i != list.end(); i++){
4101 v3s16 p = pos + (*i);
4102 content_t c = env->getMap().getNodeNoEx(p).getContent();
4103 if(filter.count(c) != 0){
4112 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
4113 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
4114 static int l_find_nodes_in_area(lua_State *L)
4116 EnvRef *o = checkobject(L, 1);
4117 ServerEnvironment *env = o->m_env;
4118 if(env == NULL) return 0;
4119 INodeDefManager *ndef = get_server(L)->ndef();
4120 v3s16 minp = read_v3s16(L, 2);
4121 v3s16 maxp = read_v3s16(L, 3);
4122 std::set<content_t> filter;
4123 if(lua_istable(L, 4)){
4126 while(lua_next(L, table) != 0){
4127 // key at index -2 and value at index -1
4128 luaL_checktype(L, -1, LUA_TSTRING);
4129 ndef->getIds(lua_tostring(L, -1), filter);
4130 // removes value, keeps key for next iteration
4133 } else if(lua_isstring(L, 4)){
4134 ndef->getIds(lua_tostring(L, 4), filter);
4137 // Get the table insert function
4138 lua_getglobal(L, "table");
4139 lua_getfield(L, -1, "insert");
4140 int table_insert = lua_gettop(L);
4143 int table = lua_gettop(L);
4144 for(s16 x=minp.X; x<=maxp.X; x++)
4145 for(s16 y=minp.Y; y<=maxp.Y; y++)
4146 for(s16 z=minp.Z; z<=maxp.Z; z++)
4149 content_t c = env->getMap().getNodeNoEx(p).getContent();
4150 if(filter.count(c) != 0){
4151 lua_pushvalue(L, table_insert);
4152 lua_pushvalue(L, table);
4154 if(lua_pcall(L, 2, 0, 0))
4155 script_error(L, "error: %s", lua_tostring(L, -1));
4161 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
4162 // returns world-specific PerlinNoise
4163 static int l_get_perlin(lua_State *L)
4165 EnvRef *o = checkobject(L, 1);
4166 ServerEnvironment *env = o->m_env;
4167 if(env == NULL) return 0;
4169 int seeddiff = luaL_checkint(L, 2);
4170 int octaves = luaL_checkint(L, 3);
4171 float persistence = luaL_checknumber(L, 4);
4172 float scale = luaL_checknumber(L, 5);
4174 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
4175 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4176 luaL_getmetatable(L, "PerlinNoise");
4177 lua_setmetatable(L, -2);
4181 // EnvRef:get_perlin_map(noiseparams, size)
4182 // returns world-specific PerlinNoiseMap
4183 static int l_get_perlin_map(lua_State *L)
4185 EnvRef *o = checkobject(L, 1);
4186 ServerEnvironment *env = o->m_env;
4190 NoiseParams *np = read_noiseparams(L, 2);
4193 v3s16 size = read_v3s16(L, 3);
4195 int seed = (int)(env->getServerMap().getSeed());
4196 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(np, seed, size);
4197 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4198 luaL_getmetatable(L, "PerlinNoiseMap");
4199 lua_setmetatable(L, -2);
4203 // EnvRef:clear_objects()
4204 // clear all objects in the environment
4205 static int l_clear_objects(lua_State *L)
4207 EnvRef *o = checkobject(L, 1);
4208 o->m_env->clearAllObjects();
4212 static int l_spawn_tree(lua_State *L)
4214 EnvRef *o = checkobject(L, 1);
4215 ServerEnvironment *env = o->m_env;
4216 if(env == NULL) return 0;
4217 v3s16 p0 = read_v3s16(L, 2);
4219 treegen::TreeDef tree_def;
4220 std::string trunk,leaves,fruit;
4221 INodeDefManager *ndef = env->getGameDef()->ndef();
4223 if(lua_istable(L, 3))
4225 getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4226 getstringfield(L, 3, "rules_a", tree_def.rules_a);
4227 getstringfield(L, 3, "rules_b", tree_def.rules_b);
4228 getstringfield(L, 3, "rules_c", tree_def.rules_c);
4229 getstringfield(L, 3, "rules_d", tree_def.rules_d);
4230 getstringfield(L, 3, "trunk", trunk);
4231 tree_def.trunknode=ndef->getId(trunk);
4232 getstringfield(L, 3, "leaves", leaves);
4233 tree_def.leavesnode=ndef->getId(leaves);
4234 tree_def.leaves2_chance=0;
4235 getstringfield(L, 3, "leaves2", leaves);
4238 tree_def.leaves2node=ndef->getId(leaves);
4239 getintfield(L, 3, "leaves2_chance", tree_def.leaves2_chance);
4241 getintfield(L, 3, "angle", tree_def.angle);
4242 getintfield(L, 3, "iterations", tree_def.iterations);
4243 getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4244 getstringfield(L, 3, "trunk_type", tree_def.trunk_type);
4245 getboolfield(L, 3, "thin_branches", tree_def.thin_branches);
4246 tree_def.fruit_chance=0;
4247 getstringfield(L, 3, "fruit", fruit);
4250 tree_def.fruitnode=ndef->getId(fruit);
4251 getintfield(L, 3, "fruit_chance",tree_def.fruit_chance);
4256 treegen::spawn_ltree (env, p0, ndef, tree_def);
4261 EnvRef(ServerEnvironment *env):
4264 //infostream<<"EnvRef created"<<std::endl;
4269 //infostream<<"EnvRef destructing"<<std::endl;
4272 // Creates an EnvRef and leaves it on top of stack
4273 // Not callable from Lua; all references are created on the C side.
4274 static void create(lua_State *L, ServerEnvironment *env)
4276 EnvRef *o = new EnvRef(env);
4277 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4278 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4279 luaL_getmetatable(L, className);
4280 lua_setmetatable(L, -2);
4283 static void set_null(lua_State *L)
4285 EnvRef *o = checkobject(L, -1);
4289 static void Register(lua_State *L)
4292 int methodtable = lua_gettop(L);
4293 luaL_newmetatable(L, className);
4294 int metatable = lua_gettop(L);
4296 lua_pushliteral(L, "__metatable");
4297 lua_pushvalue(L, methodtable);
4298 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4300 lua_pushliteral(L, "__index");
4301 lua_pushvalue(L, methodtable);
4302 lua_settable(L, metatable);
4304 lua_pushliteral(L, "__gc");
4305 lua_pushcfunction(L, gc_object);
4306 lua_settable(L, metatable);
4308 lua_pop(L, 1); // drop metatable
4310 luaL_openlib(L, 0, methods, 0); // fill methodtable
4311 lua_pop(L, 1); // drop methodtable
4313 // Cannot be created from Lua
4314 //lua_register(L, className, create_object);
4317 const char EnvRef::className[] = "EnvRef";
4318 const luaL_reg EnvRef::methods[] = {
4319 method(EnvRef, set_node),
4320 method(EnvRef, add_node),
4321 method(EnvRef, remove_node),
4322 method(EnvRef, get_node),
4323 method(EnvRef, get_node_or_nil),
4324 method(EnvRef, get_node_light),
4325 method(EnvRef, place_node),
4326 method(EnvRef, dig_node),
4327 method(EnvRef, punch_node),
4328 method(EnvRef, add_entity),
4329 method(EnvRef, add_item),
4330 method(EnvRef, add_rat),
4331 method(EnvRef, add_firefly),
4332 method(EnvRef, get_meta),
4333 method(EnvRef, get_node_timer),
4334 method(EnvRef, get_player_by_name),
4335 method(EnvRef, get_objects_inside_radius),
4336 method(EnvRef, set_timeofday),
4337 method(EnvRef, get_timeofday),
4338 method(EnvRef, find_node_near),
4339 method(EnvRef, find_nodes_in_area),
4340 method(EnvRef, get_perlin),
4341 method(EnvRef, get_perlin_map),
4342 method(EnvRef, clear_objects),
4343 method(EnvRef, spawn_tree),
4352 class LuaPseudoRandom
4355 PseudoRandom m_pseudo;
4357 static const char className[];
4358 static const luaL_reg methods[];
4360 // Exported functions
4362 // garbage collector
4363 static int gc_object(lua_State *L)
4365 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4370 // next(self, min=0, max=32767) -> get next value
4371 static int l_next(lua_State *L)
4373 LuaPseudoRandom *o = checkobject(L, 1);
4376 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4377 if(!lua_isnil(L, 2))
4378 min = luaL_checkinteger(L, 2);
4379 if(!lua_isnil(L, 3))
4380 max = luaL_checkinteger(L, 3);
4382 errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4383 throw LuaError(L, "PseudoRandom.next(): max < min");
4385 if(max - min != 32767 && max - min > 32767/5)
4386 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.");
4387 PseudoRandom &pseudo = o->m_pseudo;
4388 int val = pseudo.next();
4389 val = (val % (max-min+1)) + min;
4390 lua_pushinteger(L, val);
4395 LuaPseudoRandom(int seed):
4404 const PseudoRandom& getItem() const
4408 PseudoRandom& getItem()
4413 // LuaPseudoRandom(seed)
4414 // Creates an LuaPseudoRandom and leaves it on top of stack
4415 static int create_object(lua_State *L)
4417 int seed = luaL_checknumber(L, 1);
4418 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4419 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4420 luaL_getmetatable(L, className);
4421 lua_setmetatable(L, -2);
4425 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4427 luaL_checktype(L, narg, LUA_TUSERDATA);
4428 void *ud = luaL_checkudata(L, narg, className);
4429 if(!ud) luaL_typerror(L, narg, className);
4430 return *(LuaPseudoRandom**)ud; // unbox pointer
4433 static void Register(lua_State *L)
4436 int methodtable = lua_gettop(L);
4437 luaL_newmetatable(L, className);
4438 int metatable = lua_gettop(L);
4440 lua_pushliteral(L, "__metatable");
4441 lua_pushvalue(L, methodtable);
4442 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
4444 lua_pushliteral(L, "__index");
4445 lua_pushvalue(L, methodtable);
4446 lua_settable(L, metatable);
4448 lua_pushliteral(L, "__gc");
4449 lua_pushcfunction(L, gc_object);
4450 lua_settable(L, metatable);
4452 lua_pop(L, 1); // drop metatable
4454 luaL_openlib(L, 0, methods, 0); // fill methodtable
4455 lua_pop(L, 1); // drop methodtable
4457 // Can be created from Lua (LuaPseudoRandom(seed))
4458 lua_register(L, className, create_object);
4461 const char LuaPseudoRandom::className[] = "PseudoRandom";
4462 const luaL_reg LuaPseudoRandom::methods[] = {
4463 method(LuaPseudoRandom, next),
4473 class LuaABM : public ActiveBlockModifier
4479 std::set<std::string> m_trigger_contents;
4480 std::set<std::string> m_required_neighbors;
4481 float m_trigger_interval;
4482 u32 m_trigger_chance;
4484 LuaABM(lua_State *L, int id,
4485 const std::set<std::string> &trigger_contents,
4486 const std::set<std::string> &required_neighbors,
4487 float trigger_interval, u32 trigger_chance):
4490 m_trigger_contents(trigger_contents),
4491 m_required_neighbors(required_neighbors),
4492 m_trigger_interval(trigger_interval),
4493 m_trigger_chance(trigger_chance)
4496 virtual std::set<std::string> getTriggerContents()
4498 return m_trigger_contents;
4500 virtual std::set<std::string> getRequiredNeighbors()
4502 return m_required_neighbors;
4504 virtual float getTriggerInterval()
4506 return m_trigger_interval;
4508 virtual u32 getTriggerChance()
4510 return m_trigger_chance;
4512 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4513 u32 active_object_count, u32 active_object_count_wider)
4515 lua_State *L = m_lua;
4518 assert(lua_checkstack(L, 20));
4519 StackUnroller stack_unroller(L);
4521 // Get minetest.registered_abms
4522 lua_getglobal(L, "minetest");
4523 lua_getfield(L, -1, "registered_abms");
4524 luaL_checktype(L, -1, LUA_TTABLE);
4525 int registered_abms = lua_gettop(L);
4527 // Get minetest.registered_abms[m_id]
4528 lua_pushnumber(L, m_id);
4529 lua_gettable(L, registered_abms);
4530 if(lua_isnil(L, -1))
4534 luaL_checktype(L, -1, LUA_TTABLE);
4535 lua_getfield(L, -1, "action");
4536 luaL_checktype(L, -1, LUA_TFUNCTION);
4538 pushnode(L, n, env->getGameDef()->ndef());
4539 lua_pushnumber(L, active_object_count);
4540 lua_pushnumber(L, active_object_count_wider);
4541 if(lua_pcall(L, 4, 0, 0))
4542 script_error(L, "error: %s", lua_tostring(L, -1));
4550 static void read_server_sound_params(lua_State *L, int index,
4551 ServerSoundParams ¶ms)
4554 index = lua_gettop(L) + 1 + index;
4556 params = ServerSoundParams();
4557 if(lua_istable(L, index)){
4558 getfloatfield(L, index, "gain", params.gain);
4559 getstringfield(L, index, "to_player", params.to_player);
4560 lua_getfield(L, index, "pos");
4561 if(!lua_isnil(L, -1)){
4562 v3f p = read_v3f(L, -1)*BS;
4564 params.type = ServerSoundParams::SSP_POSITIONAL;
4567 lua_getfield(L, index, "object");
4568 if(!lua_isnil(L, -1)){
4569 ObjectRef *ref = ObjectRef::checkobject(L, -1);
4570 ServerActiveObject *sao = ObjectRef::getobject(ref);
4572 params.object = sao->getId();
4573 params.type = ServerSoundParams::SSP_OBJECT;
4577 params.max_hear_distance = BS*getfloatfield_default(L, index,
4578 "max_hear_distance", params.max_hear_distance/BS);
4579 getboolfield(L, index, "loop", params.loop);
4588 // Writes a line to dstream
4589 static int l_debug(lua_State *L)
4591 std::string text = lua_tostring(L, 1);
4592 dstream << text << std::endl;
4596 // log([level,] text)
4597 // Writes a line to the logger.
4598 // The one-argument version logs to infostream.
4599 // The two-argument version accept a log level: error, action, info, or verbose.
4600 static int l_log(lua_State *L)
4603 LogMessageLevel level = LMT_INFO;
4604 if(lua_isnone(L, 2))
4606 text = lua_tostring(L, 1);
4610 std::string levelname = luaL_checkstring(L, 1);
4611 text = luaL_checkstring(L, 2);
4612 if(levelname == "error")
4614 else if(levelname == "action")
4616 else if(levelname == "verbose")
4617 level = LMT_VERBOSE;
4619 log_printline(level, text);
4623 // request_shutdown()
4624 static int l_request_shutdown(lua_State *L)
4626 get_server(L)->requestShutdown();
4630 // get_server_status()
4631 static int l_get_server_status(lua_State *L)
4633 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4637 // register_biome_groups({frequencies})
4638 static int l_register_biome_groups(lua_State *L)
4640 luaL_checktype(L, 1, LUA_TTABLE);
4642 if (!lua_istable(L, index))
4643 throw LuaError(L, "register_biome_groups: parameter is not a table");
4645 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4647 verbosestream << "register_biome_groups: BiomeDefManager not active" << std::endl;
4652 for (int i = 1; lua_next(L, index) != 0; i++) {
4653 bmgr->addBiomeGroup(lua_tonumber(L, -1));
4661 // register_biome({lots of stuff})
4662 static int l_register_biome(lua_State *L)
4664 luaL_checktype(L, 1, LUA_TTABLE);
4665 int index = 1, groupid;
4666 std::string nodename;
4668 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
4669 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4671 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
4675 groupid = getintfield_default(L, index, "group_id", 0);
4677 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
4678 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
4679 Biome *b = bmgr->createBiome(terrain);
4681 b->name = getstringfield_default(L, index, "name", "");
4683 if (getstringfield(L, index, "node_top", nodename))
4684 b->n_top = MapNode(ndef->getId(nodename));
4686 b->n_top = MapNode(CONTENT_IGNORE);
4688 if (getstringfield(L, index, "node_filler", nodename))
4689 b->n_filler = MapNode(ndef->getId(nodename));
4691 b->n_filler = b->n_top;
4693 b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
4695 b->height_min = getintfield_default(L, index, "height_min", 0);
4696 b->height_max = getintfield_default(L, index, "height_max", 0);
4697 b->heat_min = getfloatfield_default(L, index, "heat_min", 0.);
4698 b->heat_max = getfloatfield_default(L, index, "heat_max", 0.);
4699 b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
4700 b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
4702 b->np = new NoiseParams; // should read an entire NoiseParams later on...
4703 getfloatfield(L, index, "scale", b->np->scale);
4704 getfloatfield(L, index, "offset", b->np->offset);
4706 b->groupid = (s8)groupid;
4707 b->flags = 0; //reserved
4711 verbosestream << "register_biome: " << b->name << std::endl;
4715 // register_item_raw({lots of stuff})
4716 static int l_register_item_raw(lua_State *L)
4718 luaL_checktype(L, 1, LUA_TTABLE);
4721 // Get the writable item and node definition managers from the server
4722 IWritableItemDefManager *idef =
4723 get_server(L)->getWritableItemDefManager();
4724 IWritableNodeDefManager *ndef =
4725 get_server(L)->getWritableNodeDefManager();
4727 // Check if name is defined
4729 lua_getfield(L, table, "name");
4730 if(lua_isstring(L, -1)){
4731 name = lua_tostring(L, -1);
4732 verbosestream<<"register_item_raw: "<<name<<std::endl;
4734 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4737 // Check if on_use is defined
4740 // Set a distinctive default value to check if this is set
4741 def.node_placement_prediction = "__default";
4743 // Read the item definition
4744 def = read_item_definition(L, table, def);
4746 // Default to having client-side placement prediction for nodes
4747 // ("" in item definition sets it off)
4748 if(def.node_placement_prediction == "__default"){
4749 if(def.type == ITEM_NODE)
4750 def.node_placement_prediction = name;
4752 def.node_placement_prediction = "";
4755 // Register item definition
4756 idef->registerItem(def);
4758 // Read the node definition (content features) and register it
4759 if(def.type == ITEM_NODE)
4761 ContentFeatures f = read_content_features(L, table);
4762 ndef->set(f.name, f);
4765 return 0; /* number of results */
4768 // register_alias_raw(name, convert_to_name)
4769 static int l_register_alias_raw(lua_State *L)
4771 std::string name = luaL_checkstring(L, 1);
4772 std::string convert_to = luaL_checkstring(L, 2);
4774 // Get the writable item definition manager from the server
4775 IWritableItemDefManager *idef =
4776 get_server(L)->getWritableItemDefManager();
4778 idef->registerAlias(name, convert_to);
4780 return 0; /* number of results */
4783 // helper for register_craft
4784 static bool read_craft_recipe_shaped(lua_State *L, int index,
4785 int &width, std::vector<std::string> &recipe)
4788 index = lua_gettop(L) + 1 + index;
4790 if(!lua_istable(L, index))
4795 while(lua_next(L, index) != 0){
4797 // key at index -2 and value at index -1
4798 if(!lua_istable(L, -1))
4800 int table2 = lua_gettop(L);
4802 while(lua_next(L, table2) != 0){
4803 // key at index -2 and value at index -1
4804 if(!lua_isstring(L, -1))
4806 recipe.push_back(lua_tostring(L, -1));
4807 // removes value, keeps key for next iteration
4814 if(colcount != width)
4817 // removes value, keeps key for next iteration
4824 // helper for register_craft
4825 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4826 std::vector<std::string> &recipe)
4829 index = lua_gettop(L) + 1 + index;
4831 if(!lua_istable(L, index))
4835 while(lua_next(L, index) != 0){
4836 // key at index -2 and value at index -1
4837 if(!lua_isstring(L, -1))
4839 recipe.push_back(lua_tostring(L, -1));
4840 // removes value, keeps key for next iteration
4846 // helper for register_craft
4847 static bool read_craft_replacements(lua_State *L, int index,
4848 CraftReplacements &replacements)
4851 index = lua_gettop(L) + 1 + index;
4853 if(!lua_istable(L, index))
4857 while(lua_next(L, index) != 0){
4858 // key at index -2 and value at index -1
4859 if(!lua_istable(L, -1))
4861 lua_rawgeti(L, -1, 1);
4862 if(!lua_isstring(L, -1))
4864 std::string replace_from = lua_tostring(L, -1);
4866 lua_rawgeti(L, -1, 2);
4867 if(!lua_isstring(L, -1))
4869 std::string replace_to = lua_tostring(L, -1);
4871 replacements.pairs.push_back(
4872 std::make_pair(replace_from, replace_to));
4873 // removes value, keeps key for next iteration
4878 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4879 static int l_register_craft(lua_State *L)
4881 //infostream<<"register_craft"<<std::endl;
4882 luaL_checktype(L, 1, LUA_TTABLE);
4885 // Get the writable craft definition manager from the server
4886 IWritableCraftDefManager *craftdef =
4887 get_server(L)->getWritableCraftDefManager();
4889 std::string type = getstringfield_default(L, table, "type", "shaped");
4892 CraftDefinitionShaped
4894 if(type == "shaped"){
4895 std::string output = getstringfield_default(L, table, "output", "");
4897 throw LuaError(L, "Crafting definition is missing an output");
4900 std::vector<std::string> recipe;
4901 lua_getfield(L, table, "recipe");
4902 if(lua_isnil(L, -1))
4903 throw LuaError(L, "Crafting definition is missing a recipe"
4904 " (output=\"" + output + "\")");
4905 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4906 throw LuaError(L, "Invalid crafting recipe"
4907 " (output=\"" + output + "\")");
4909 CraftReplacements replacements;
4910 lua_getfield(L, table, "replacements");
4911 if(!lua_isnil(L, -1))
4913 if(!read_craft_replacements(L, -1, replacements))
4914 throw LuaError(L, "Invalid replacements"
4915 " (output=\"" + output + "\")");
4918 CraftDefinition *def = new CraftDefinitionShaped(
4919 output, width, recipe, replacements);
4920 craftdef->registerCraft(def);
4923 CraftDefinitionShapeless
4925 else if(type == "shapeless"){
4926 std::string output = getstringfield_default(L, table, "output", "");
4928 throw LuaError(L, "Crafting definition (shapeless)"
4929 " is missing an output");
4931 std::vector<std::string> recipe;
4932 lua_getfield(L, table, "recipe");
4933 if(lua_isnil(L, -1))
4934 throw LuaError(L, "Crafting definition (shapeless)"
4935 " is missing a recipe"
4936 " (output=\"" + output + "\")");
4937 if(!read_craft_recipe_shapeless(L, -1, recipe))
4938 throw LuaError(L, "Invalid crafting recipe"
4939 " (output=\"" + output + "\")");
4941 CraftReplacements replacements;
4942 lua_getfield(L, table, "replacements");
4943 if(!lua_isnil(L, -1))
4945 if(!read_craft_replacements(L, -1, replacements))
4946 throw LuaError(L, "Invalid replacements"
4947 " (output=\"" + output + "\")");
4950 CraftDefinition *def = new CraftDefinitionShapeless(
4951 output, recipe, replacements);
4952 craftdef->registerCraft(def);
4955 CraftDefinitionToolRepair
4957 else if(type == "toolrepair"){
4958 float additional_wear = getfloatfield_default(L, table,
4959 "additional_wear", 0.0);
4961 CraftDefinition *def = new CraftDefinitionToolRepair(
4963 craftdef->registerCraft(def);
4966 CraftDefinitionCooking
4968 else if(type == "cooking"){
4969 std::string output = getstringfield_default(L, table, "output", "");
4971 throw LuaError(L, "Crafting definition (cooking)"
4972 " is missing an output");
4974 std::string recipe = getstringfield_default(L, table, "recipe", "");
4976 throw LuaError(L, "Crafting definition (cooking)"
4977 " is missing a recipe"
4978 " (output=\"" + output + "\")");
4980 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4982 CraftReplacements replacements;
4983 lua_getfield(L, table, "replacements");
4984 if(!lua_isnil(L, -1))
4986 if(!read_craft_replacements(L, -1, replacements))
4987 throw LuaError(L, "Invalid replacements"
4988 " (cooking output=\"" + output + "\")");
4991 CraftDefinition *def = new CraftDefinitionCooking(
4992 output, recipe, cooktime, replacements);
4993 craftdef->registerCraft(def);
4998 else if(type == "fuel"){
4999 std::string recipe = getstringfield_default(L, table, "recipe", "");
5001 throw LuaError(L, "Crafting definition (fuel)"
5002 " is missing a recipe");
5004 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
5006 CraftReplacements replacements;
5007 lua_getfield(L, table, "replacements");
5008 if(!lua_isnil(L, -1))
5010 if(!read_craft_replacements(L, -1, replacements))
5011 throw LuaError(L, "Invalid replacements"
5012 " (fuel recipe=\"" + recipe + "\")");
5015 CraftDefinition *def = new CraftDefinitionFuel(
5016 recipe, burntime, replacements);
5017 craftdef->registerCraft(def);
5021 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
5025 return 0; /* number of results */
5028 // setting_set(name, value)
5029 static int l_setting_set(lua_State *L)
5031 const char *name = luaL_checkstring(L, 1);
5032 const char *value = luaL_checkstring(L, 2);
5033 g_settings->set(name, value);
5037 // setting_get(name)
5038 static int l_setting_get(lua_State *L)
5040 const char *name = luaL_checkstring(L, 1);
5042 std::string value = g_settings->get(name);
5043 lua_pushstring(L, value.c_str());
5044 } catch(SettingNotFoundException &e){
5050 // setting_getbool(name)
5051 static int l_setting_getbool(lua_State *L)
5053 const char *name = luaL_checkstring(L, 1);
5055 bool value = g_settings->getBool(name);
5056 lua_pushboolean(L, value);
5057 } catch(SettingNotFoundException &e){
5064 static int l_setting_save(lua_State *L)
5066 get_server(L)->saveConfig();
5070 // chat_send_all(text)
5071 static int l_chat_send_all(lua_State *L)
5073 const char *text = luaL_checkstring(L, 1);
5074 // Get server from registry
5075 Server *server = get_server(L);
5077 server->notifyPlayers(narrow_to_wide(text));
5081 // chat_send_player(name, text)
5082 static int l_chat_send_player(lua_State *L)
5084 const char *name = luaL_checkstring(L, 1);
5085 const char *text = luaL_checkstring(L, 2);
5086 // Get server from registry
5087 Server *server = get_server(L);
5089 server->notifyPlayer(name, narrow_to_wide(text));
5093 // get_player_privs(name, text)
5094 static int l_get_player_privs(lua_State *L)
5096 const char *name = luaL_checkstring(L, 1);
5097 // Get server from registry
5098 Server *server = get_server(L);
5101 int table = lua_gettop(L);
5102 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
5103 for(std::set<std::string>::const_iterator
5104 i = privs_s.begin(); i != privs_s.end(); i++){
5105 lua_pushboolean(L, true);
5106 lua_setfield(L, table, i->c_str());
5108 lua_pushvalue(L, table);
5113 static int l_get_ban_list(lua_State *L)
5115 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
5119 // get_ban_description()
5120 static int l_get_ban_description(lua_State *L)
5122 const char * ip_or_name = luaL_checkstring(L, 1);
5123 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
5128 static int l_ban_player(lua_State *L)
5130 const char * name = luaL_checkstring(L, 1);
5131 Player *player = get_env(L)->getPlayer(name);
5134 lua_pushboolean(L, false); // no such player
5139 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
5140 std::string ip_str = addr.serializeString();
5141 get_server(L)->setIpBanned(ip_str, name);
5143 catch(con::PeerNotFoundException) // unlikely
5145 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
5146 lua_pushboolean(L, false); // error
5149 lua_pushboolean(L, true);
5153 // unban_player_or_ip()
5154 static int l_unban_player_of_ip(lua_State *L)
5156 const char * ip_or_name = luaL_checkstring(L, 1);
5157 get_server(L)->unsetIpBanned(ip_or_name);
5158 lua_pushboolean(L, true);
5162 // get_inventory(location)
5163 static int l_get_inventory(lua_State *L)
5165 InventoryLocation loc;
5167 std::string type = checkstringfield(L, 1, "type");
5168 if(type == "player"){
5169 std::string name = checkstringfield(L, 1, "name");
5170 loc.setPlayer(name);
5171 } else if(type == "node"){
5172 lua_getfield(L, 1, "pos");
5173 v3s16 pos = check_v3s16(L, -1);
5174 loc.setNodeMeta(pos);
5175 } else if(type == "detached"){
5176 std::string name = checkstringfield(L, 1, "name");
5177 loc.setDetached(name);
5180 if(get_server(L)->getInventory(loc) != NULL)
5181 InvRef::create(L, loc);
5187 // create_detached_inventory_raw(name)
5188 static int l_create_detached_inventory_raw(lua_State *L)
5190 const char *name = luaL_checkstring(L, 1);
5191 if(get_server(L)->createDetachedInventory(name) != NULL){
5192 InventoryLocation loc;
5193 loc.setDetached(name);
5194 InvRef::create(L, loc);
5201 // show_formspec(playername,formname,formspec)
5202 static int l_show_formspec(lua_State *L)
5204 const char *playername = luaL_checkstring(L, 1);
5205 const char *formname = luaL_checkstring(L, 2);
5206 const char *formspec = luaL_checkstring(L, 3);
5208 if(get_server(L)->showFormspec(playername,formspec,formname))
5210 lua_pushboolean(L, true);
5212 lua_pushboolean(L, false);
5217 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5218 static int l_get_dig_params(lua_State *L)
5220 std::map<std::string, int> groups;
5221 read_groups(L, 1, groups);
5222 ToolCapabilities tp = read_tool_capabilities(L, 2);
5223 if(lua_isnoneornil(L, 3))
5224 push_dig_params(L, getDigParams(groups, &tp));
5226 push_dig_params(L, getDigParams(groups, &tp,
5227 luaL_checknumber(L, 3)));
5231 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5232 static int l_get_hit_params(lua_State *L)
5234 std::map<std::string, int> groups;
5235 read_groups(L, 1, groups);
5236 ToolCapabilities tp = read_tool_capabilities(L, 2);
5237 if(lua_isnoneornil(L, 3))
5238 push_hit_params(L, getHitParams(groups, &tp));
5240 push_hit_params(L, getHitParams(groups, &tp,
5241 luaL_checknumber(L, 3)));
5245 // get_current_modname()
5246 static int l_get_current_modname(lua_State *L)
5248 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5252 // get_modpath(modname)
5253 static int l_get_modpath(lua_State *L)
5255 std::string modname = luaL_checkstring(L, 1);
5257 if(modname == "__builtin"){
5258 std::string path = get_server(L)->getBuiltinLuaPath();
5259 lua_pushstring(L, path.c_str());
5262 const ModSpec *mod = get_server(L)->getModSpec(modname);
5267 lua_pushstring(L, mod->path.c_str());
5272 // the returned list is sorted alphabetically for you
5273 static int l_get_modnames(lua_State *L)
5275 // Get a list of mods
5276 core::list<std::string> mods_unsorted, mods_sorted;
5277 get_server(L)->getModNames(mods_unsorted);
5279 // Take unsorted items from mods_unsorted and sort them into
5280 // mods_sorted; not great performance but the number of mods on a
5281 // server will likely be small.
5282 for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5283 i != mods_unsorted.end(); i++)
5286 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5287 x != mods_unsorted.end(); x++)
5289 // I doubt anybody using Minetest will be using
5290 // anything not ASCII based :)
5291 if((*i).compare(*x) <= 0)
5293 mods_sorted.insert_before(x, *i);
5299 mods_sorted.push_back(*i);
5302 // Get the table insertion function from Lua.
5303 lua_getglobal(L, "table");
5304 lua_getfield(L, -1, "insert");
5305 int insertion_func = lua_gettop(L);
5307 // Package them up for Lua
5309 int new_table = lua_gettop(L);
5310 core::list<std::string>::Iterator i = mods_sorted.begin();
5311 while(i != mods_sorted.end())
5313 lua_pushvalue(L, insertion_func);
5314 lua_pushvalue(L, new_table);
5315 lua_pushstring(L, (*i).c_str());
5316 if(lua_pcall(L, 2, 0, 0) != 0)
5318 script_error(L, "error: %s", lua_tostring(L, -1));
5326 static int l_get_worldpath(lua_State *L)
5328 std::string worldpath = get_server(L)->getWorldPath();
5329 lua_pushstring(L, worldpath.c_str());
5333 // sound_play(spec, parameters)
5334 static int l_sound_play(lua_State *L)
5336 SimpleSoundSpec spec;
5337 read_soundspec(L, 1, spec);
5338 ServerSoundParams params;
5339 read_server_sound_params(L, 2, params);
5340 s32 handle = get_server(L)->playSound(spec, params);
5341 lua_pushinteger(L, handle);
5345 // sound_stop(handle)
5346 static int l_sound_stop(lua_State *L)
5348 int handle = luaL_checkinteger(L, 1);
5349 get_server(L)->stopSound(handle);
5353 // is_singleplayer()
5354 static int l_is_singleplayer(lua_State *L)
5356 lua_pushboolean(L, get_server(L)->isSingleplayer());
5360 // get_password_hash(name, raw_password)
5361 static int l_get_password_hash(lua_State *L)
5363 std::string name = luaL_checkstring(L, 1);
5364 std::string raw_password = luaL_checkstring(L, 2);
5365 std::string hash = translatePassword(name,
5366 narrow_to_wide(raw_password));
5367 lua_pushstring(L, hash.c_str());
5371 // notify_authentication_modified(name)
5372 static int l_notify_authentication_modified(lua_State *L)
5374 std::string name = "";
5375 if(lua_isstring(L, 1))
5376 name = lua_tostring(L, 1);
5377 get_server(L)->reportPrivsModified(name);
5381 // get_craft_result(input)
5382 static int l_get_craft_result(lua_State *L)
5385 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5386 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5387 es_CraftMethod, CRAFT_METHOD_NORMAL);
5389 lua_getfield(L, input_i, "width");
5390 if(lua_isnumber(L, -1))
5391 width = luaL_checkinteger(L, -1);
5393 lua_getfield(L, input_i, "items");
5394 std::vector<ItemStack> items = read_items(L, -1);
5395 lua_pop(L, 1); // items
5397 IGameDef *gdef = get_server(L);
5398 ICraftDefManager *cdef = gdef->cdef();
5399 CraftInput input(method, width, items);
5401 bool got = cdef->getCraftResult(input, output, true, gdef);
5402 lua_newtable(L); // output table
5405 item.deSerialize(output.item, gdef->idef());
5406 LuaItemStack::create(L, item);
5407 lua_setfield(L, -2, "item");
5408 setintfield(L, -1, "time", output.time);
5410 LuaItemStack::create(L, ItemStack());
5411 lua_setfield(L, -2, "item");
5412 setintfield(L, -1, "time", 0);
5414 lua_newtable(L); // decremented input table
5415 lua_pushstring(L, method_s.c_str());
5416 lua_setfield(L, -2, "method");
5417 lua_pushinteger(L, width);
5418 lua_setfield(L, -2, "width");
5419 push_items(L, input.items);
5420 lua_setfield(L, -2, "items");
5424 // get_craft_recipe(result item)
5425 static int l_get_craft_recipe(lua_State *L)
5430 std::string o_item = luaL_checkstring(L,input_i);
5432 IGameDef *gdef = get_server(L);
5433 ICraftDefManager *cdef = gdef->cdef();
5435 CraftOutput output(o_item,0);
5436 bool got = cdef->getCraftRecipe(input, output, gdef);
5437 lua_newtable(L); // output table
5440 for(std::vector<ItemStack>::const_iterator
5441 i = input.items.begin();
5442 i != input.items.end(); i++, k++)
5448 sprintf(tmp,"%d",k);
5449 lua_pushstring(L,tmp);
5450 lua_pushstring(L,i->name.c_str());
5451 lua_settable(L, -3);
5453 lua_setfield(L, -2, "items");
5454 setintfield(L, -1, "width", input.width);
5455 switch (input.method) {
5456 case CRAFT_METHOD_NORMAL:
5457 lua_pushstring(L,"normal");
5459 case CRAFT_METHOD_COOKING:
5460 lua_pushstring(L,"cooking");
5462 case CRAFT_METHOD_FUEL:
5463 lua_pushstring(L,"fuel");
5466 lua_pushstring(L,"unknown");
5468 lua_setfield(L, -2, "type");
5471 lua_setfield(L, -2, "items");
5472 setintfield(L, -1, "width", 0);
5477 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5478 static int l_rollback_get_last_node_actor(lua_State *L)
5480 v3s16 p = read_v3s16(L, 1);
5481 int range = luaL_checknumber(L, 2);
5482 int seconds = luaL_checknumber(L, 3);
5483 Server *server = get_server(L);
5484 IRollbackManager *rollback = server->getRollbackManager();
5486 int act_seconds = 0;
5487 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5488 lua_pushstring(L, actor.c_str());
5489 push_v3s16(L, act_p);
5490 lua_pushnumber(L, act_seconds);
5494 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5495 static int l_rollback_revert_actions_by(lua_State *L)
5497 std::string actor = luaL_checkstring(L, 1);
5498 int seconds = luaL_checknumber(L, 2);
5499 Server *server = get_server(L);
5500 IRollbackManager *rollback = server->getRollbackManager();
5501 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5502 std::list<std::string> log;
5503 bool success = server->rollbackRevertActions(actions, &log);
5504 // Push boolean result
5505 lua_pushboolean(L, success);
5506 // Get the table insert function and push the log table
5507 lua_getglobal(L, "table");
5508 lua_getfield(L, -1, "insert");
5509 int table_insert = lua_gettop(L);
5511 int table = lua_gettop(L);
5512 for(std::list<std::string>::const_iterator i = log.begin();
5513 i != log.end(); i++)
5515 lua_pushvalue(L, table_insert);
5516 lua_pushvalue(L, table);
5517 lua_pushstring(L, i->c_str());
5518 if(lua_pcall(L, 2, 0, 0))
5519 script_error(L, "error: %s", lua_tostring(L, -1));
5521 lua_remove(L, -2); // Remove table
5522 lua_remove(L, -2); // Remove insert
5526 static const struct luaL_Reg minetest_f [] = {
5529 {"request_shutdown", l_request_shutdown},
5530 {"get_server_status", l_get_server_status},
5531 {"register_item_raw", l_register_item_raw},
5532 {"register_alias_raw", l_register_alias_raw},
5533 {"register_craft", l_register_craft},
5534 {"register_biome", l_register_biome},
5535 {"register_biome_groups", l_register_biome_groups},
5536 {"setting_set", l_setting_set},
5537 {"setting_get", l_setting_get},
5538 {"setting_getbool", l_setting_getbool},
5539 {"setting_save",l_setting_save},
5540 {"chat_send_all", l_chat_send_all},
5541 {"chat_send_player", l_chat_send_player},
5542 {"get_player_privs", l_get_player_privs},
5543 {"get_ban_list", l_get_ban_list},
5544 {"get_ban_description", l_get_ban_description},
5545 {"ban_player", l_ban_player},
5546 {"unban_player_or_ip", l_unban_player_of_ip},
5547 {"get_inventory", l_get_inventory},
5548 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5549 {"show_formspec", l_show_formspec},
5550 {"get_dig_params", l_get_dig_params},
5551 {"get_hit_params", l_get_hit_params},
5552 {"get_current_modname", l_get_current_modname},
5553 {"get_modpath", l_get_modpath},
5554 {"get_modnames", l_get_modnames},
5555 {"get_worldpath", l_get_worldpath},
5556 {"sound_play", l_sound_play},
5557 {"sound_stop", l_sound_stop},
5558 {"is_singleplayer", l_is_singleplayer},
5559 {"get_password_hash", l_get_password_hash},
5560 {"notify_authentication_modified", l_notify_authentication_modified},
5561 {"get_craft_result", l_get_craft_result},
5562 {"get_craft_recipe", l_get_craft_recipe},
5563 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5564 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5569 Main export function
5572 void scriptapi_export(lua_State *L, Server *server)
5575 assert(lua_checkstack(L, 20));
5576 verbosestream<<"scriptapi_export()"<<std::endl;
5577 StackUnroller stack_unroller(L);
5579 // Store server as light userdata in registry
5580 lua_pushlightuserdata(L, server);
5581 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5583 // Register global functions in table minetest
5585 luaL_register(L, NULL, minetest_f);
5586 lua_setglobal(L, "minetest");
5588 // Get the main minetest table
5589 lua_getglobal(L, "minetest");
5591 // Add tables to minetest
5593 lua_setfield(L, -2, "object_refs");
5595 lua_setfield(L, -2, "luaentities");
5597 // Register wrappers
5598 LuaItemStack::Register(L);
5599 InvRef::Register(L);
5600 NodeMetaRef::Register(L);
5601 NodeTimerRef::Register(L);
5602 ObjectRef::Register(L);
5603 EnvRef::Register(L);
5604 LuaPseudoRandom::Register(L);
5605 LuaPerlinNoise::Register(L);
5606 LuaPerlinNoiseMap::Register(L);
5609 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5610 const std::string &modname)
5612 ModNameStorer modnamestorer(L, modname);
5614 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5616 errorstream<<"Error loading mod \""<<modname
5617 <<"\": modname does not follow naming conventions: "
5618 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5622 bool success = false;
5625 success = script_load(L, scriptpath.c_str());
5628 errorstream<<"Error loading mod \""<<modname
5629 <<"\": "<<e.what()<<std::endl;
5635 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5638 assert(lua_checkstack(L, 20));
5639 verbosestream<<"scriptapi_add_environment"<<std::endl;
5640 StackUnroller stack_unroller(L);
5642 // Create EnvRef on stack
5643 EnvRef::create(L, env);
5644 int envref = lua_gettop(L);
5646 // minetest.env = envref
5647 lua_getglobal(L, "minetest");
5648 luaL_checktype(L, -1, LUA_TTABLE);
5649 lua_pushvalue(L, envref);
5650 lua_setfield(L, -2, "env");
5652 // Store environment as light userdata in registry
5653 lua_pushlightuserdata(L, env);
5654 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5657 Add ActiveBlockModifiers to environment
5660 // Get minetest.registered_abms
5661 lua_getglobal(L, "minetest");
5662 lua_getfield(L, -1, "registered_abms");
5663 luaL_checktype(L, -1, LUA_TTABLE);
5664 int registered_abms = lua_gettop(L);
5666 if(lua_istable(L, registered_abms)){
5667 int table = lua_gettop(L);
5669 while(lua_next(L, table) != 0){
5670 // key at index -2 and value at index -1
5671 int id = lua_tonumber(L, -2);
5672 int current_abm = lua_gettop(L);
5674 std::set<std::string> trigger_contents;
5675 lua_getfield(L, current_abm, "nodenames");
5676 if(lua_istable(L, -1)){
5677 int table = lua_gettop(L);
5679 while(lua_next(L, table) != 0){
5680 // key at index -2 and value at index -1
5681 luaL_checktype(L, -1, LUA_TSTRING);
5682 trigger_contents.insert(lua_tostring(L, -1));
5683 // removes value, keeps key for next iteration
5686 } else if(lua_isstring(L, -1)){
5687 trigger_contents.insert(lua_tostring(L, -1));
5691 std::set<std::string> required_neighbors;
5692 lua_getfield(L, current_abm, "neighbors");
5693 if(lua_istable(L, -1)){
5694 int table = lua_gettop(L);
5696 while(lua_next(L, table) != 0){
5697 // key at index -2 and value at index -1
5698 luaL_checktype(L, -1, LUA_TSTRING);
5699 required_neighbors.insert(lua_tostring(L, -1));
5700 // removes value, keeps key for next iteration
5703 } else if(lua_isstring(L, -1)){
5704 required_neighbors.insert(lua_tostring(L, -1));
5708 float trigger_interval = 10.0;
5709 getfloatfield(L, current_abm, "interval", trigger_interval);
5711 int trigger_chance = 50;
5712 getintfield(L, current_abm, "chance", trigger_chance);
5714 LuaABM *abm = new LuaABM(L, id, trigger_contents,
5715 required_neighbors, trigger_interval, trigger_chance);
5717 env->addActiveBlockModifier(abm);
5719 // removes value, keeps key for next iteration
5727 // Dump stack top with the dump2 function
5728 static void dump2(lua_State *L, const char *name)
5730 // Dump object (debug)
5731 lua_getglobal(L, "dump2");
5732 luaL_checktype(L, -1, LUA_TFUNCTION);
5733 lua_pushvalue(L, -2); // Get previous stack top as first parameter
5734 lua_pushstring(L, name);
5735 if(lua_pcall(L, 2, 0, 0))
5736 script_error(L, "error: %s", lua_tostring(L, -1));
5744 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5747 assert(lua_checkstack(L, 20));
5748 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5749 StackUnroller stack_unroller(L);
5751 // Create object on stack
5752 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5753 int object = lua_gettop(L);
5755 // Get minetest.object_refs table
5756 lua_getglobal(L, "minetest");
5757 lua_getfield(L, -1, "object_refs");
5758 luaL_checktype(L, -1, LUA_TTABLE);
5759 int objectstable = lua_gettop(L);
5761 // object_refs[id] = object
5762 lua_pushnumber(L, cobj->getId()); // Push id
5763 lua_pushvalue(L, object); // Copy object to top of stack
5764 lua_settable(L, objectstable);
5767 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5770 assert(lua_checkstack(L, 20));
5771 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5772 StackUnroller stack_unroller(L);
5774 // Get minetest.object_refs table
5775 lua_getglobal(L, "minetest");
5776 lua_getfield(L, -1, "object_refs");
5777 luaL_checktype(L, -1, LUA_TTABLE);
5778 int objectstable = lua_gettop(L);
5780 // Get object_refs[id]
5781 lua_pushnumber(L, cobj->getId()); // Push id
5782 lua_gettable(L, objectstable);
5783 // Set object reference to NULL
5784 ObjectRef::set_null(L);
5785 lua_pop(L, 1); // pop object
5787 // Set object_refs[id] = nil
5788 lua_pushnumber(L, cobj->getId()); // Push id
5790 lua_settable(L, objectstable);
5797 // What scriptapi_run_callbacks does with the return values of callbacks.
5798 // Regardless of the mode, if only one callback is defined,
5799 // its return value is the total return value.
5800 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5801 enum RunCallbacksMode
5803 // Returns the return value of the first callback
5804 // Returns nil if list of callbacks is empty
5805 RUN_CALLBACKS_MODE_FIRST,
5806 // Returns the return value of the last callback
5807 // Returns nil if list of callbacks is empty
5808 RUN_CALLBACKS_MODE_LAST,
5809 // If any callback returns a false value, the first such is returned
5810 // Otherwise, the first callback's return value (trueish) is returned
5811 // Returns true if list of callbacks is empty
5812 RUN_CALLBACKS_MODE_AND,
5813 // Like above, but stops calling callbacks (short circuit)
5814 // after seeing the first false value
5815 RUN_CALLBACKS_MODE_AND_SC,
5816 // If any callback returns a true value, the first such is returned
5817 // Otherwise, the first callback's return value (falseish) is returned
5818 // Returns false if list of callbacks is empty
5819 RUN_CALLBACKS_MODE_OR,
5820 // Like above, but stops calling callbacks (short circuit)
5821 // after seeing the first true value
5822 RUN_CALLBACKS_MODE_OR_SC,
5823 // Note: "a true value" and "a false value" refer to values that
5824 // are converted by lua_toboolean to true or false, respectively.
5827 // Push the list of callbacks (a lua table).
5828 // Then push nargs arguments.
5829 // Then call this function, which
5830 // - runs the callbacks
5831 // - removes the table and arguments from the lua stack
5832 // - pushes the return value, computed depending on mode
5833 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5834 RunCallbacksMode mode)
5836 // Insert the return value into the lua stack, below the table
5837 assert(lua_gettop(L) >= nargs + 1);
5839 lua_insert(L, -(nargs + 1) - 1);
5840 // Stack now looks like this:
5841 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5843 int rv = lua_gettop(L) - nargs - 1;
5845 int arg = table + 1;
5847 luaL_checktype(L, table, LUA_TTABLE);
5851 bool first_loop = true;
5852 while(lua_next(L, table) != 0){
5853 // key at index -2 and value at index -1
5854 luaL_checktype(L, -1, LUA_TFUNCTION);
5856 for(int i = 0; i < nargs; i++)
5857 lua_pushvalue(L, arg+i);
5858 if(lua_pcall(L, nargs, 1, 0))
5859 script_error(L, "error: %s", lua_tostring(L, -1));
5861 // Move return value to designated space in stack
5864 // Result of first callback is always moved
5868 // Otherwise, what happens depends on the mode
5869 if(mode == RUN_CALLBACKS_MODE_FIRST)
5871 else if(mode == RUN_CALLBACKS_MODE_LAST)
5873 else if(mode == RUN_CALLBACKS_MODE_AND ||
5874 mode == RUN_CALLBACKS_MODE_AND_SC){
5875 if((bool)lua_toboolean(L, rv) == true &&
5876 (bool)lua_toboolean(L, -1) == false)
5881 else if(mode == RUN_CALLBACKS_MODE_OR ||
5882 mode == RUN_CALLBACKS_MODE_OR_SC){
5883 if((bool)lua_toboolean(L, rv) == false &&
5884 (bool)lua_toboolean(L, -1) == true)
5893 // Handle short circuit modes
5894 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5895 (bool)lua_toboolean(L, rv) == false)
5897 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5898 (bool)lua_toboolean(L, rv) == true)
5901 // value removed, keep key for next iteration
5904 // Remove stuff from stack, leaving only the return value
5907 // Fix return value in case no callbacks were called
5909 if(mode == RUN_CALLBACKS_MODE_AND ||
5910 mode == RUN_CALLBACKS_MODE_AND_SC){
5912 lua_pushboolean(L, true);
5914 else if(mode == RUN_CALLBACKS_MODE_OR ||
5915 mode == RUN_CALLBACKS_MODE_OR_SC){
5917 lua_pushboolean(L, false);
5922 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5923 const std::string &message)
5926 assert(lua_checkstack(L, 20));
5927 StackUnroller stack_unroller(L);
5929 // Get minetest.registered_on_chat_messages
5930 lua_getglobal(L, "minetest");
5931 lua_getfield(L, -1, "registered_on_chat_messages");
5933 lua_pushstring(L, name.c_str());
5934 lua_pushstring(L, message.c_str());
5935 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5936 bool ate = lua_toboolean(L, -1);
5940 void scriptapi_on_shutdown(lua_State *L)
5943 assert(lua_checkstack(L, 20));
5944 StackUnroller stack_unroller(L);
5946 // Get registered shutdown hooks
5947 lua_getglobal(L, "minetest");
5948 lua_getfield(L, -1, "registered_on_shutdown");
5950 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5953 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5956 assert(lua_checkstack(L, 20));
5957 StackUnroller stack_unroller(L);
5959 // Get minetest.registered_on_newplayers
5960 lua_getglobal(L, "minetest");
5961 lua_getfield(L, -1, "registered_on_newplayers");
5963 objectref_get_or_create(L, player);
5964 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5967 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5970 assert(lua_checkstack(L, 20));
5971 StackUnroller stack_unroller(L);
5973 // Get minetest.registered_on_dieplayers
5974 lua_getglobal(L, "minetest");
5975 lua_getfield(L, -1, "registered_on_dieplayers");
5977 objectref_get_or_create(L, player);
5978 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5981 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5984 assert(lua_checkstack(L, 20));
5985 StackUnroller stack_unroller(L);
5987 // Get minetest.registered_on_respawnplayers
5988 lua_getglobal(L, "minetest");
5989 lua_getfield(L, -1, "registered_on_respawnplayers");
5991 objectref_get_or_create(L, player);
5992 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5993 bool positioning_handled_by_some = lua_toboolean(L, -1);
5994 return positioning_handled_by_some;
5997 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
6000 assert(lua_checkstack(L, 20));
6001 StackUnroller stack_unroller(L);
6003 // Get minetest.registered_on_joinplayers
6004 lua_getglobal(L, "minetest");
6005 lua_getfield(L, -1, "registered_on_joinplayers");
6007 objectref_get_or_create(L, player);
6008 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6011 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
6014 assert(lua_checkstack(L, 20));
6015 StackUnroller stack_unroller(L);
6017 // Get minetest.registered_on_leaveplayers
6018 lua_getglobal(L, "minetest");
6019 lua_getfield(L, -1, "registered_on_leaveplayers");
6021 objectref_get_or_create(L, player);
6022 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6025 static void get_auth_handler(lua_State *L)
6027 lua_getglobal(L, "minetest");
6028 lua_getfield(L, -1, "registered_auth_handler");
6029 if(lua_isnil(L, -1)){
6031 lua_getfield(L, -1, "builtin_auth_handler");
6033 if(lua_type(L, -1) != LUA_TTABLE)
6034 throw LuaError(L, "Authentication handler table not valid");
6037 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
6038 std::string *dst_password, std::set<std::string> *dst_privs)
6041 assert(lua_checkstack(L, 20));
6042 StackUnroller stack_unroller(L);
6044 get_auth_handler(L);
6045 lua_getfield(L, -1, "get_auth");
6046 if(lua_type(L, -1) != LUA_TFUNCTION)
6047 throw LuaError(L, "Authentication handler missing get_auth");
6048 lua_pushstring(L, playername.c_str());
6049 if(lua_pcall(L, 1, 1, 0))
6050 script_error(L, "error: %s", lua_tostring(L, -1));
6052 // nil = login not allowed
6053 if(lua_isnil(L, -1))
6055 luaL_checktype(L, -1, LUA_TTABLE);
6057 std::string password;
6058 bool found = getstringfield(L, -1, "password", password);
6060 throw LuaError(L, "Authentication handler didn't return password");
6062 *dst_password = password;
6064 lua_getfield(L, -1, "privileges");
6065 if(!lua_istable(L, -1))
6067 "Authentication handler didn't return privilege table");
6069 read_privileges(L, -1, *dst_privs);
6075 void scriptapi_create_auth(lua_State *L, const std::string &playername,
6076 const std::string &password)
6079 assert(lua_checkstack(L, 20));
6080 StackUnroller stack_unroller(L);
6082 get_auth_handler(L);
6083 lua_getfield(L, -1, "create_auth");
6084 if(lua_type(L, -1) != LUA_TFUNCTION)
6085 throw LuaError(L, "Authentication handler missing create_auth");
6086 lua_pushstring(L, playername.c_str());
6087 lua_pushstring(L, password.c_str());
6088 if(lua_pcall(L, 2, 0, 0))
6089 script_error(L, "error: %s", lua_tostring(L, -1));
6092 bool scriptapi_set_password(lua_State *L, const std::string &playername,
6093 const std::string &password)
6096 assert(lua_checkstack(L, 20));
6097 StackUnroller stack_unroller(L);
6099 get_auth_handler(L);
6100 lua_getfield(L, -1, "set_password");
6101 if(lua_type(L, -1) != LUA_TFUNCTION)
6102 throw LuaError(L, "Authentication handler missing set_password");
6103 lua_pushstring(L, playername.c_str());
6104 lua_pushstring(L, password.c_str());
6105 if(lua_pcall(L, 2, 1, 0))
6106 script_error(L, "error: %s", lua_tostring(L, -1));
6107 return lua_toboolean(L, -1);
6114 void scriptapi_on_player_receive_fields(lua_State *L,
6115 ServerActiveObject *player,
6116 const std::string &formname,
6117 const std::map<std::string, std::string> &fields)
6120 assert(lua_checkstack(L, 20));
6121 StackUnroller stack_unroller(L);
6123 // Get minetest.registered_on_chat_messages
6124 lua_getglobal(L, "minetest");
6125 lua_getfield(L, -1, "registered_on_player_receive_fields");
6128 objectref_get_or_create(L, player);
6130 lua_pushstring(L, formname.c_str());
6133 for(std::map<std::string, std::string>::const_iterator
6134 i = fields.begin(); i != fields.end(); i++){
6135 const std::string &name = i->first;
6136 const std::string &value = i->second;
6137 lua_pushstring(L, name.c_str());
6138 lua_pushlstring(L, value.c_str(), value.size());
6139 lua_settable(L, -3);
6141 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
6145 item callbacks and node callbacks
6148 // Retrieves minetest.registered_items[name][callbackname]
6149 // If that is nil or on error, return false and stack is unchanged
6150 // If that is a function, returns true and pushes the
6151 // function onto the stack
6152 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
6153 // is tried instead so unknown items can still be manipulated to some degree
6154 static bool get_item_callback(lua_State *L,
6155 const char *name, const char *callbackname)
6157 lua_getglobal(L, "minetest");
6158 lua_getfield(L, -1, "registered_items");
6160 luaL_checktype(L, -1, LUA_TTABLE);
6161 lua_getfield(L, -1, name);
6163 // Should be a table
6164 if(lua_type(L, -1) != LUA_TTABLE)
6166 // Report error and clean up
6167 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6170 // Try minetest.nodedef_default instead
6171 lua_getglobal(L, "minetest");
6172 lua_getfield(L, -1, "nodedef_default");
6174 luaL_checktype(L, -1, LUA_TTABLE);
6176 lua_getfield(L, -1, callbackname);
6178 // Should be a function or nil
6179 if(lua_type(L, -1) == LUA_TFUNCTION)
6183 else if(lua_isnil(L, -1))
6190 errorstream<<"Item \""<<name<<"\" callback \""
6191 <<callbackname<<" is not a function"<<std::endl;
6197 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6198 ServerActiveObject *dropper, v3f pos)
6201 assert(lua_checkstack(L, 20));
6202 StackUnroller stack_unroller(L);
6204 // Push callback function on stack
6205 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6209 LuaItemStack::create(L, item);
6210 objectref_get_or_create(L, dropper);
6211 pushFloatPos(L, pos);
6212 if(lua_pcall(L, 3, 1, 0))
6213 script_error(L, "error: %s", lua_tostring(L, -1));
6214 if(!lua_isnil(L, -1))
6215 item = read_item(L, -1);
6219 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6220 ServerActiveObject *placer, const PointedThing &pointed)
6223 assert(lua_checkstack(L, 20));
6224 StackUnroller stack_unroller(L);
6226 // Push callback function on stack
6227 if(!get_item_callback(L, item.name.c_str(), "on_place"))
6231 LuaItemStack::create(L, item);
6232 objectref_get_or_create(L, placer);
6233 push_pointed_thing(L, pointed);
6234 if(lua_pcall(L, 3, 1, 0))
6235 script_error(L, "error: %s", lua_tostring(L, -1));
6236 if(!lua_isnil(L, -1))
6237 item = read_item(L, -1);
6241 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6242 ServerActiveObject *user, const PointedThing &pointed)
6245 assert(lua_checkstack(L, 20));
6246 StackUnroller stack_unroller(L);
6248 // Push callback function on stack
6249 if(!get_item_callback(L, item.name.c_str(), "on_use"))
6253 LuaItemStack::create(L, item);
6254 objectref_get_or_create(L, user);
6255 push_pointed_thing(L, pointed);
6256 if(lua_pcall(L, 3, 1, 0))
6257 script_error(L, "error: %s", lua_tostring(L, -1));
6258 if(!lua_isnil(L, -1))
6259 item = read_item(L, -1);
6263 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6264 ServerActiveObject *puncher)
6267 assert(lua_checkstack(L, 20));
6268 StackUnroller stack_unroller(L);
6270 INodeDefManager *ndef = get_server(L)->ndef();
6272 // Push callback function on stack
6273 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6278 pushnode(L, node, ndef);
6279 objectref_get_or_create(L, puncher);
6280 if(lua_pcall(L, 3, 0, 0))
6281 script_error(L, "error: %s", lua_tostring(L, -1));
6285 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6286 ServerActiveObject *digger)
6289 assert(lua_checkstack(L, 20));
6290 StackUnroller stack_unroller(L);
6292 INodeDefManager *ndef = get_server(L)->ndef();
6294 // Push callback function on stack
6295 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6300 pushnode(L, node, ndef);
6301 objectref_get_or_create(L, digger);
6302 if(lua_pcall(L, 3, 0, 0))
6303 script_error(L, "error: %s", lua_tostring(L, -1));
6307 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6310 assert(lua_checkstack(L, 20));
6311 StackUnroller stack_unroller(L);
6313 INodeDefManager *ndef = get_server(L)->ndef();
6315 // Push callback function on stack
6316 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6321 if(lua_pcall(L, 1, 0, 0))
6322 script_error(L, "error: %s", lua_tostring(L, -1));
6325 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6328 assert(lua_checkstack(L, 20));
6329 StackUnroller stack_unroller(L);
6331 INodeDefManager *ndef = get_server(L)->ndef();
6333 // Push callback function on stack
6334 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6339 if(lua_pcall(L, 1, 0, 0))
6340 script_error(L, "error: %s", lua_tostring(L, -1));
6343 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6346 assert(lua_checkstack(L, 20));
6347 StackUnroller stack_unroller(L);
6349 INodeDefManager *ndef = get_server(L)->ndef();
6351 // Push callback function on stack
6352 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6357 pushnode(L, node, ndef);
6358 if(lua_pcall(L, 2, 0, 0))
6359 script_error(L, "error: %s", lua_tostring(L, -1));
6362 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6365 assert(lua_checkstack(L, 20));
6366 StackUnroller stack_unroller(L);
6368 INodeDefManager *ndef = get_server(L)->ndef();
6370 // Push callback function on stack
6371 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6376 lua_pushnumber(L,dtime);
6377 if(lua_pcall(L, 2, 1, 0))
6378 script_error(L, "error: %s", lua_tostring(L, -1));
6379 if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6385 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6386 const std::string &formname,
6387 const std::map<std::string, std::string> &fields,
6388 ServerActiveObject *sender)
6391 assert(lua_checkstack(L, 20));
6392 StackUnroller stack_unroller(L);
6394 INodeDefManager *ndef = get_server(L)->ndef();
6396 // If node doesn't exist, we don't know what callback to call
6397 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6398 if(node.getContent() == CONTENT_IGNORE)
6401 // Push callback function on stack
6402 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6409 lua_pushstring(L, formname.c_str());
6412 for(std::map<std::string, std::string>::const_iterator
6413 i = fields.begin(); i != fields.end(); i++){
6414 const std::string &name = i->first;
6415 const std::string &value = i->second;
6416 lua_pushstring(L, name.c_str());
6417 lua_pushlstring(L, value.c_str(), value.size());
6418 lua_settable(L, -3);
6421 objectref_get_or_create(L, sender);
6422 if(lua_pcall(L, 4, 0, 0))
6423 script_error(L, "error: %s", lua_tostring(L, -1));
6427 Node metadata inventory callbacks
6430 // Return number of accepted items to be moved
6431 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6432 const std::string &from_list, int from_index,
6433 const std::string &to_list, int to_index,
6434 int count, ServerActiveObject *player)
6437 assert(lua_checkstack(L, 20));
6438 StackUnroller stack_unroller(L);
6440 INodeDefManager *ndef = get_server(L)->ndef();
6442 // If node doesn't exist, we don't know what callback to call
6443 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6444 if(node.getContent() == CONTENT_IGNORE)
6447 // Push callback function on stack
6448 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6449 "allow_metadata_inventory_move"))
6452 // function(pos, from_list, from_index, to_list, to_index, count, player)
6456 lua_pushstring(L, from_list.c_str());
6458 lua_pushinteger(L, from_index + 1);
6460 lua_pushstring(L, to_list.c_str());
6462 lua_pushinteger(L, to_index + 1);
6464 lua_pushinteger(L, count);
6466 objectref_get_or_create(L, player);
6467 if(lua_pcall(L, 7, 1, 0))
6468 script_error(L, "error: %s", lua_tostring(L, -1));
6469 if(!lua_isnumber(L, -1))
6470 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6471 return luaL_checkinteger(L, -1);
6474 // Return number of accepted items to be put
6475 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6476 const std::string &listname, int index, ItemStack &stack,
6477 ServerActiveObject *player)
6480 assert(lua_checkstack(L, 20));
6481 StackUnroller stack_unroller(L);
6483 INodeDefManager *ndef = get_server(L)->ndef();
6485 // If node doesn't exist, we don't know what callback to call
6486 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6487 if(node.getContent() == CONTENT_IGNORE)
6490 // Push callback function on stack
6491 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6492 "allow_metadata_inventory_put"))
6495 // Call function(pos, listname, index, stack, player)
6499 lua_pushstring(L, listname.c_str());
6501 lua_pushinteger(L, index + 1);
6503 LuaItemStack::create(L, stack);
6505 objectref_get_or_create(L, player);
6506 if(lua_pcall(L, 5, 1, 0))
6507 script_error(L, "error: %s", lua_tostring(L, -1));
6508 if(!lua_isnumber(L, -1))
6509 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6510 return luaL_checkinteger(L, -1);
6513 // Return number of accepted items to be taken
6514 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6515 const std::string &listname, int index, ItemStack &stack,
6516 ServerActiveObject *player)
6519 assert(lua_checkstack(L, 20));
6520 StackUnroller stack_unroller(L);
6522 INodeDefManager *ndef = get_server(L)->ndef();
6524 // If node doesn't exist, we don't know what callback to call
6525 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6526 if(node.getContent() == CONTENT_IGNORE)
6529 // Push callback function on stack
6530 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6531 "allow_metadata_inventory_take"))
6534 // Call function(pos, listname, index, count, player)
6538 lua_pushstring(L, listname.c_str());
6540 lua_pushinteger(L, index + 1);
6542 LuaItemStack::create(L, stack);
6544 objectref_get_or_create(L, player);
6545 if(lua_pcall(L, 5, 1, 0))
6546 script_error(L, "error: %s", lua_tostring(L, -1));
6547 if(!lua_isnumber(L, -1))
6548 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6549 return luaL_checkinteger(L, -1);
6552 // Report moved items
6553 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6554 const std::string &from_list, int from_index,
6555 const std::string &to_list, int to_index,
6556 int count, ServerActiveObject *player)
6559 assert(lua_checkstack(L, 20));
6560 StackUnroller stack_unroller(L);
6562 INodeDefManager *ndef = get_server(L)->ndef();
6564 // If node doesn't exist, we don't know what callback to call
6565 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6566 if(node.getContent() == CONTENT_IGNORE)
6569 // Push callback function on stack
6570 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6571 "on_metadata_inventory_move"))
6574 // function(pos, from_list, from_index, to_list, to_index, count, player)
6578 lua_pushstring(L, from_list.c_str());
6580 lua_pushinteger(L, from_index + 1);
6582 lua_pushstring(L, to_list.c_str());
6584 lua_pushinteger(L, to_index + 1);
6586 lua_pushinteger(L, count);
6588 objectref_get_or_create(L, player);
6589 if(lua_pcall(L, 7, 0, 0))
6590 script_error(L, "error: %s", lua_tostring(L, -1));
6594 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6595 const std::string &listname, int index, ItemStack &stack,
6596 ServerActiveObject *player)
6599 assert(lua_checkstack(L, 20));
6600 StackUnroller stack_unroller(L);
6602 INodeDefManager *ndef = get_server(L)->ndef();
6604 // If node doesn't exist, we don't know what callback to call
6605 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6606 if(node.getContent() == CONTENT_IGNORE)
6609 // Push callback function on stack
6610 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6611 "on_metadata_inventory_put"))
6614 // Call function(pos, listname, index, stack, player)
6618 lua_pushstring(L, listname.c_str());
6620 lua_pushinteger(L, index + 1);
6622 LuaItemStack::create(L, stack);
6624 objectref_get_or_create(L, player);
6625 if(lua_pcall(L, 5, 0, 0))
6626 script_error(L, "error: %s", lua_tostring(L, -1));
6629 // Report taken items
6630 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6631 const std::string &listname, int index, ItemStack &stack,
6632 ServerActiveObject *player)
6635 assert(lua_checkstack(L, 20));
6636 StackUnroller stack_unroller(L);
6638 INodeDefManager *ndef = get_server(L)->ndef();
6640 // If node doesn't exist, we don't know what callback to call
6641 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6642 if(node.getContent() == CONTENT_IGNORE)
6645 // Push callback function on stack
6646 if(!get_item_callback(L, ndef->get(node).name.c_str(),
6647 "on_metadata_inventory_take"))
6650 // Call function(pos, listname, index, stack, player)
6654 lua_pushstring(L, listname.c_str());
6656 lua_pushinteger(L, index + 1);
6658 LuaItemStack::create(L, stack);
6660 objectref_get_or_create(L, player);
6661 if(lua_pcall(L, 5, 0, 0))
6662 script_error(L, "error: %s", lua_tostring(L, -1));
6666 Detached inventory callbacks
6669 // Retrieves minetest.detached_inventories[name][callbackname]
6670 // If that is nil or on error, return false and stack is unchanged
6671 // If that is a function, returns true and pushes the
6672 // function onto the stack
6673 static bool get_detached_inventory_callback(lua_State *L,
6674 const std::string &name, const char *callbackname)
6676 lua_getglobal(L, "minetest");
6677 lua_getfield(L, -1, "detached_inventories");
6679 luaL_checktype(L, -1, LUA_TTABLE);
6680 lua_getfield(L, -1, name.c_str());
6682 // Should be a table
6683 if(lua_type(L, -1) != LUA_TTABLE)
6685 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6689 lua_getfield(L, -1, callbackname);
6691 // Should be a function or nil
6692 if(lua_type(L, -1) == LUA_TFUNCTION)
6696 else if(lua_isnil(L, -1))
6703 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6704 <<callbackname<<"\" is not a function"<<std::endl;
6710 // Return number of accepted items to be moved
6711 int scriptapi_detached_inventory_allow_move(lua_State *L,
6712 const std::string &name,
6713 const std::string &from_list, int from_index,
6714 const std::string &to_list, int to_index,
6715 int count, ServerActiveObject *player)
6718 assert(lua_checkstack(L, 20));
6719 StackUnroller stack_unroller(L);
6721 // Push callback function on stack
6722 if(!get_detached_inventory_callback(L, name, "allow_move"))
6725 // function(inv, from_list, from_index, to_list, to_index, count, player)
6727 InventoryLocation loc;
6728 loc.setDetached(name);
6729 InvRef::create(L, loc);
6731 lua_pushstring(L, from_list.c_str());
6733 lua_pushinteger(L, from_index + 1);
6735 lua_pushstring(L, to_list.c_str());
6737 lua_pushinteger(L, to_index + 1);
6739 lua_pushinteger(L, count);
6741 objectref_get_or_create(L, player);
6742 if(lua_pcall(L, 7, 1, 0))
6743 script_error(L, "error: %s", lua_tostring(L, -1));
6744 if(!lua_isnumber(L, -1))
6745 throw LuaError(L, "allow_move should return a number");
6746 return luaL_checkinteger(L, -1);
6749 // Return number of accepted items to be put
6750 int scriptapi_detached_inventory_allow_put(lua_State *L,
6751 const std::string &name,
6752 const std::string &listname, int index, ItemStack &stack,
6753 ServerActiveObject *player)
6756 assert(lua_checkstack(L, 20));
6757 StackUnroller stack_unroller(L);
6759 // Push callback function on stack
6760 if(!get_detached_inventory_callback(L, name, "allow_put"))
6761 return stack.count; // All will be accepted
6763 // Call function(inv, listname, index, stack, player)
6765 InventoryLocation loc;
6766 loc.setDetached(name);
6767 InvRef::create(L, loc);
6769 lua_pushstring(L, listname.c_str());
6771 lua_pushinteger(L, index + 1);
6773 LuaItemStack::create(L, stack);
6775 objectref_get_or_create(L, player);
6776 if(lua_pcall(L, 5, 1, 0))
6777 script_error(L, "error: %s", lua_tostring(L, -1));
6778 if(!lua_isnumber(L, -1))
6779 throw LuaError(L, "allow_put should return a number");
6780 return luaL_checkinteger(L, -1);
6783 // Return number of accepted items to be taken
6784 int scriptapi_detached_inventory_allow_take(lua_State *L,
6785 const std::string &name,
6786 const std::string &listname, int index, ItemStack &stack,
6787 ServerActiveObject *player)
6790 assert(lua_checkstack(L, 20));
6791 StackUnroller stack_unroller(L);
6793 // Push callback function on stack
6794 if(!get_detached_inventory_callback(L, name, "allow_take"))
6795 return stack.count; // All will be accepted
6797 // Call function(inv, listname, index, stack, player)
6799 InventoryLocation loc;
6800 loc.setDetached(name);
6801 InvRef::create(L, loc);
6803 lua_pushstring(L, listname.c_str());
6805 lua_pushinteger(L, index + 1);
6807 LuaItemStack::create(L, stack);
6809 objectref_get_or_create(L, player);
6810 if(lua_pcall(L, 5, 1, 0))
6811 script_error(L, "error: %s", lua_tostring(L, -1));
6812 if(!lua_isnumber(L, -1))
6813 throw LuaError(L, "allow_take should return a number");
6814 return luaL_checkinteger(L, -1);
6817 // Report moved items
6818 void scriptapi_detached_inventory_on_move(lua_State *L,
6819 const std::string &name,
6820 const std::string &from_list, int from_index,
6821 const std::string &to_list, int to_index,
6822 int count, ServerActiveObject *player)
6825 assert(lua_checkstack(L, 20));
6826 StackUnroller stack_unroller(L);
6828 // Push callback function on stack
6829 if(!get_detached_inventory_callback(L, name, "on_move"))
6832 // function(inv, from_list, from_index, to_list, to_index, count, player)
6834 InventoryLocation loc;
6835 loc.setDetached(name);
6836 InvRef::create(L, loc);
6838 lua_pushstring(L, from_list.c_str());
6840 lua_pushinteger(L, from_index + 1);
6842 lua_pushstring(L, to_list.c_str());
6844 lua_pushinteger(L, to_index + 1);
6846 lua_pushinteger(L, count);
6848 objectref_get_or_create(L, player);
6849 if(lua_pcall(L, 7, 0, 0))
6850 script_error(L, "error: %s", lua_tostring(L, -1));
6854 void scriptapi_detached_inventory_on_put(lua_State *L,
6855 const std::string &name,
6856 const std::string &listname, int index, ItemStack &stack,
6857 ServerActiveObject *player)
6860 assert(lua_checkstack(L, 20));
6861 StackUnroller stack_unroller(L);
6863 // Push callback function on stack
6864 if(!get_detached_inventory_callback(L, name, "on_put"))
6867 // Call function(inv, listname, index, stack, player)
6869 InventoryLocation loc;
6870 loc.setDetached(name);
6871 InvRef::create(L, loc);
6873 lua_pushstring(L, listname.c_str());
6875 lua_pushinteger(L, index + 1);
6877 LuaItemStack::create(L, stack);
6879 objectref_get_or_create(L, player);
6880 if(lua_pcall(L, 5, 0, 0))
6881 script_error(L, "error: %s", lua_tostring(L, -1));
6884 // Report taken items
6885 void scriptapi_detached_inventory_on_take(lua_State *L,
6886 const std::string &name,
6887 const std::string &listname, int index, ItemStack &stack,
6888 ServerActiveObject *player)
6891 assert(lua_checkstack(L, 20));
6892 StackUnroller stack_unroller(L);
6894 // Push callback function on stack
6895 if(!get_detached_inventory_callback(L, name, "on_take"))
6898 // Call function(inv, listname, index, stack, player)
6900 InventoryLocation loc;
6901 loc.setDetached(name);
6902 InvRef::create(L, loc);
6904 lua_pushstring(L, listname.c_str());
6906 lua_pushinteger(L, index + 1);
6908 LuaItemStack::create(L, stack);
6910 objectref_get_or_create(L, player);
6911 if(lua_pcall(L, 5, 0, 0))
6912 script_error(L, "error: %s", lua_tostring(L, -1));
6919 void scriptapi_environment_step(lua_State *L, float dtime)
6922 assert(lua_checkstack(L, 20));
6923 //infostream<<"scriptapi_environment_step"<<std::endl;
6924 StackUnroller stack_unroller(L);
6926 // Get minetest.registered_globalsteps
6927 lua_getglobal(L, "minetest");
6928 lua_getfield(L, -1, "registered_globalsteps");
6930 lua_pushnumber(L, dtime);
6931 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6934 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6938 assert(lua_checkstack(L, 20));
6939 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6940 StackUnroller stack_unroller(L);
6942 // Get minetest.registered_on_generateds
6943 lua_getglobal(L, "minetest");
6944 lua_getfield(L, -1, "registered_on_generateds");
6946 push_v3s16(L, minp);
6947 push_v3s16(L, maxp);
6948 lua_pushnumber(L, blockseed);
6949 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6956 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6959 assert(lua_checkstack(L, 20));
6960 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6961 <<name<<"\""<<std::endl;
6962 StackUnroller stack_unroller(L);
6964 // Get minetest.registered_entities[name]
6965 lua_getglobal(L, "minetest");
6966 lua_getfield(L, -1, "registered_entities");
6967 luaL_checktype(L, -1, LUA_TTABLE);
6968 lua_pushstring(L, name);
6969 lua_gettable(L, -2);
6970 // Should be a table, which we will use as a prototype
6971 //luaL_checktype(L, -1, LUA_TTABLE);
6972 if(lua_type(L, -1) != LUA_TTABLE){
6973 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6976 int prototype_table = lua_gettop(L);
6977 //dump2(L, "prototype_table");
6979 // Create entity object
6981 int object = lua_gettop(L);
6983 // Set object metatable
6984 lua_pushvalue(L, prototype_table);
6985 lua_setmetatable(L, -2);
6987 // Add object reference
6988 // This should be userdata with metatable ObjectRef
6989 objectref_get(L, id);
6990 luaL_checktype(L, -1, LUA_TUSERDATA);
6991 if(!luaL_checkudata(L, -1, "ObjectRef"))
6992 luaL_typerror(L, -1, "ObjectRef");
6993 lua_setfield(L, -2, "object");
6995 // minetest.luaentities[id] = object
6996 lua_getglobal(L, "minetest");
6997 lua_getfield(L, -1, "luaentities");
6998 luaL_checktype(L, -1, LUA_TTABLE);
6999 lua_pushnumber(L, id); // Push id
7000 lua_pushvalue(L, object); // Copy object to top of stack
7001 lua_settable(L, -3);
7006 void scriptapi_luaentity_activate(lua_State *L, u16 id,
7007 const std::string &staticdata, u32 dtime_s)
7010 assert(lua_checkstack(L, 20));
7011 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
7012 StackUnroller stack_unroller(L);
7014 // Get minetest.luaentities[id]
7015 luaentity_get(L, id);
7016 int object = lua_gettop(L);
7018 // Get on_activate function
7019 lua_pushvalue(L, object);
7020 lua_getfield(L, -1, "on_activate");
7021 if(!lua_isnil(L, -1)){
7022 luaL_checktype(L, -1, LUA_TFUNCTION);
7023 lua_pushvalue(L, object); // self
7024 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
7025 lua_pushinteger(L, dtime_s);
7026 // Call with 3 arguments, 0 results
7027 if(lua_pcall(L, 3, 0, 0))
7028 script_error(L, "error running function on_activate: %s\n",
7029 lua_tostring(L, -1));
7033 void scriptapi_luaentity_rm(lua_State *L, u16 id)
7036 assert(lua_checkstack(L, 20));
7037 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
7039 // Get minetest.luaentities table
7040 lua_getglobal(L, "minetest");
7041 lua_getfield(L, -1, "luaentities");
7042 luaL_checktype(L, -1, LUA_TTABLE);
7043 int objectstable = lua_gettop(L);
7045 // Set luaentities[id] = nil
7046 lua_pushnumber(L, id); // Push id
7048 lua_settable(L, objectstable);
7050 lua_pop(L, 2); // pop luaentities, minetest
7053 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
7056 assert(lua_checkstack(L, 20));
7057 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
7058 StackUnroller stack_unroller(L);
7060 // Get minetest.luaentities[id]
7061 luaentity_get(L, id);
7062 int object = lua_gettop(L);
7064 // Get get_staticdata function
7065 lua_pushvalue(L, object);
7066 lua_getfield(L, -1, "get_staticdata");
7067 if(lua_isnil(L, -1))
7070 luaL_checktype(L, -1, LUA_TFUNCTION);
7071 lua_pushvalue(L, object); // self
7072 // Call with 1 arguments, 1 results
7073 if(lua_pcall(L, 1, 1, 0))
7074 script_error(L, "error running function get_staticdata: %s\n",
7075 lua_tostring(L, -1));
7078 const char *s = lua_tolstring(L, -1, &len);
7079 return std::string(s, len);
7082 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
7083 ObjectProperties *prop)
7086 assert(lua_checkstack(L, 20));
7087 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
7088 StackUnroller stack_unroller(L);
7090 // Get minetest.luaentities[id]
7091 luaentity_get(L, id);
7092 //int object = lua_gettop(L);
7094 // Set default values that differ from ObjectProperties defaults
7099 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
7101 getboolfield(L, -1, "physical", prop->physical);
7103 getfloatfield(L, -1, "weight", prop->weight);
7105 lua_getfield(L, -1, "collisionbox");
7106 if(lua_istable(L, -1))
7107 prop->collisionbox = read_aabb3f(L, -1, 1.0);
7110 getstringfield(L, -1, "visual", prop->visual);
7112 getstringfield(L, -1, "mesh", prop->mesh);
7114 // Deprecated: read object properties directly
7115 read_object_properties(L, -1, prop);
7117 // Read initial_properties
7118 lua_getfield(L, -1, "initial_properties");
7119 read_object_properties(L, -1, prop);
7123 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
7126 assert(lua_checkstack(L, 20));
7127 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7128 StackUnroller stack_unroller(L);
7130 // Get minetest.luaentities[id]
7131 luaentity_get(L, id);
7132 int object = lua_gettop(L);
7133 // State: object is at top of stack
7134 // Get step function
7135 lua_getfield(L, -1, "on_step");
7136 if(lua_isnil(L, -1))
7138 luaL_checktype(L, -1, LUA_TFUNCTION);
7139 lua_pushvalue(L, object); // self
7140 lua_pushnumber(L, dtime); // dtime
7141 // Call with 2 arguments, 0 results
7142 if(lua_pcall(L, 2, 0, 0))
7143 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
7146 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
7147 // tool_capabilities, direction)
7148 void scriptapi_luaentity_punch(lua_State *L, u16 id,
7149 ServerActiveObject *puncher, float time_from_last_punch,
7150 const ToolCapabilities *toolcap, v3f dir)
7153 assert(lua_checkstack(L, 20));
7154 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7155 StackUnroller stack_unroller(L);
7157 // Get minetest.luaentities[id]
7158 luaentity_get(L, id);
7159 int object = lua_gettop(L);
7160 // State: object is at top of stack
7162 lua_getfield(L, -1, "on_punch");
7163 if(lua_isnil(L, -1))
7165 luaL_checktype(L, -1, LUA_TFUNCTION);
7166 lua_pushvalue(L, object); // self
7167 objectref_get_or_create(L, puncher); // Clicker reference
7168 lua_pushnumber(L, time_from_last_punch);
7169 push_tool_capabilities(L, *toolcap);
7171 // Call with 5 arguments, 0 results
7172 if(lua_pcall(L, 5, 0, 0))
7173 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
7176 // Calls entity:on_rightclick(ObjectRef clicker)
7177 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
7178 ServerActiveObject *clicker)
7181 assert(lua_checkstack(L, 20));
7182 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7183 StackUnroller stack_unroller(L);
7185 // Get minetest.luaentities[id]
7186 luaentity_get(L, id);
7187 int object = lua_gettop(L);
7188 // State: object is at top of stack
7190 lua_getfield(L, -1, "on_rightclick");
7191 if(lua_isnil(L, -1))
7193 luaL_checktype(L, -1, LUA_TFUNCTION);
7194 lua_pushvalue(L, object); // self
7195 objectref_get_or_create(L, clicker); // Clicker reference
7196 // Call with 2 arguments, 0 results
7197 if(lua_pcall(L, 2, 0, 0))
7198 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));