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
41 #include "main.h" // For g_settings
42 #include "settings.h" // For accessing g_settings
43 #include "nodemetadata.h"
44 #include "mapblock.h" // For getNodeBlockPos
45 #include "content_nodemeta.h"
47 #include "daynightratio.h"
48 #include "noise.h" // PseudoRandom for LuaPseudoRandom
49 #include "util/pointedthing.h"
51 static void stackDump(lua_State *L, std::ostream &o)
54 int top = lua_gettop(L);
55 for (i = 1; i <= top; i++) { /* repeat for each level */
56 int t = lua_type(L, i);
59 case LUA_TSTRING: /* strings */
60 o<<"\""<<lua_tostring(L, i)<<"\"";
63 case LUA_TBOOLEAN: /* booleans */
64 o<<(lua_toboolean(L, i) ? "true" : "false");
67 case LUA_TNUMBER: /* numbers */ {
69 snprintf(buf, 10, "%g", lua_tonumber(L, i));
73 default: /* other values */
74 o<<lua_typename(L, t);
83 static void realitycheck(lua_State *L)
85 int top = lua_gettop(L);
87 dstream<<"Stack is over 30:"<<std::endl;
88 stackDump(L, dstream);
89 script_error(L, "Stack is over 30 (reality check)");
99 StackUnroller(lua_State *L):
103 m_original_top = lua_gettop(m_lua); // store stack height
107 lua_settop(m_lua, m_original_top); // restore stack height
116 ModNameStorer(lua_State *L_, const std::string modname):
119 // Store current modname in registry
120 lua_pushstring(L, modname.c_str());
121 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
125 // Clear current modname in registry
127 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
132 Getters for stuff in main tables
135 static Server* get_server(lua_State *L)
137 // Get server from registry
138 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
139 Server *server = (Server*)lua_touserdata(L, -1);
144 static ServerEnvironment* get_env(lua_State *L)
146 // Get environment from registry
147 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
148 ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
153 static void objectref_get(lua_State *L, u16 id)
155 // Get minetest.object_refs[i]
156 lua_getglobal(L, "minetest");
157 lua_getfield(L, -1, "object_refs");
158 luaL_checktype(L, -1, LUA_TTABLE);
159 lua_pushnumber(L, id);
161 lua_remove(L, -2); // object_refs
162 lua_remove(L, -2); // minetest
165 static void luaentity_get(lua_State *L, u16 id)
167 // Get minetest.luaentities[i]
168 lua_getglobal(L, "minetest");
169 lua_getfield(L, -1, "luaentities");
170 luaL_checktype(L, -1, LUA_TTABLE);
171 lua_pushnumber(L, id);
173 lua_remove(L, -2); // luaentities
174 lua_remove(L, -2); // minetest
181 static bool getstringfield(lua_State *L, int table,
182 const char *fieldname, std::string &result)
184 lua_getfield(L, table, fieldname);
186 if(lua_isstring(L, -1)){
188 const char *ptr = lua_tolstring(L, -1, &len);
189 result.assign(ptr, len);
196 static bool getintfield(lua_State *L, int table,
197 const char *fieldname, int &result)
199 lua_getfield(L, table, fieldname);
201 if(lua_isnumber(L, -1)){
202 result = lua_tonumber(L, -1);
209 static bool getfloatfield(lua_State *L, int table,
210 const char *fieldname, float &result)
212 lua_getfield(L, table, fieldname);
214 if(lua_isnumber(L, -1)){
215 result = lua_tonumber(L, -1);
222 static bool getboolfield(lua_State *L, int table,
223 const char *fieldname, bool &result)
225 lua_getfield(L, table, fieldname);
227 if(lua_isboolean(L, -1)){
228 result = lua_toboolean(L, -1);
235 static std::string checkstringfield(lua_State *L, int table,
236 const char *fieldname)
238 lua_getfield(L, table, fieldname);
239 std::string s = luaL_checkstring(L, -1);
244 static std::string getstringfield_default(lua_State *L, int table,
245 const char *fieldname, const std::string &default_)
247 std::string result = default_;
248 getstringfield(L, table, fieldname, result);
252 static int getintfield_default(lua_State *L, int table,
253 const char *fieldname, int default_)
255 int result = default_;
256 getintfield(L, table, fieldname, result);
260 static float getfloatfield_default(lua_State *L, int table,
261 const char *fieldname, float default_)
263 float result = default_;
264 getfloatfield(L, table, fieldname, result);
268 static bool getboolfield_default(lua_State *L, int table,
269 const char *fieldname, bool default_)
271 bool result = default_;
272 getboolfield(L, table, fieldname, result);
282 static bool string_to_enum(const EnumString *spec, int &result,
283 const std::string &str)
285 const EnumString *esp = spec;
287 if(str == std::string(esp->str)){
296 /*static bool enum_to_string(const EnumString *spec, std::string &result,
299 const EnumString *esp = spec;
310 static int getenumfield(lua_State *L, int table,
311 const char *fieldname, const EnumString *spec, int default_)
313 int result = default_;
314 string_to_enum(spec, result,
315 getstringfield_default(L, table, fieldname, ""));
319 static void setintfield(lua_State *L, int table,
320 const char *fieldname, int value)
322 lua_pushinteger(L, value);
325 lua_setfield(L, table, fieldname);
328 static void setfloatfield(lua_State *L, int table,
329 const char *fieldname, float value)
331 lua_pushnumber(L, value);
334 lua_setfield(L, table, fieldname);
337 static void setboolfield(lua_State *L, int table,
338 const char *fieldname, bool value)
340 lua_pushboolean(L, value);
343 lua_setfield(L, table, fieldname);
346 static void warn_if_field_exists(lua_State *L, int table,
347 const char *fieldname, const std::string &message)
349 lua_getfield(L, table, fieldname);
350 if(!lua_isnil(L, -1)){
351 infostream<<script_get_backtrace(L)<<std::endl;
352 infostream<<"WARNING: field \""<<fieldname<<"\": "
353 <<message<<std::endl;
359 EnumString definitions
362 struct EnumString es_ItemType[] =
366 {ITEM_CRAFT, "craft"},
371 struct EnumString es_DrawType[] =
373 {NDT_NORMAL, "normal"},
374 {NDT_AIRLIKE, "airlike"},
375 {NDT_LIQUID, "liquid"},
376 {NDT_FLOWINGLIQUID, "flowingliquid"},
377 {NDT_GLASSLIKE, "glasslike"},
378 {NDT_ALLFACES, "allfaces"},
379 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
380 {NDT_TORCHLIKE, "torchlike"},
381 {NDT_SIGNLIKE, "signlike"},
382 {NDT_PLANTLIKE, "plantlike"},
383 {NDT_FENCELIKE, "fencelike"},
384 {NDT_RAILLIKE, "raillike"},
385 {NDT_NODEBOX, "nodebox"},
389 struct EnumString es_ContentParamType[] =
392 {CPT_LIGHT, "light"},
396 struct EnumString es_ContentParamType2[] =
400 {CPT2_FLOWINGLIQUID, "flowingliquid"},
401 {CPT2_FACEDIR, "facedir"},
402 {CPT2_WALLMOUNTED, "wallmounted"},
406 struct EnumString es_LiquidType[] =
408 {LIQUID_NONE, "none"},
409 {LIQUID_FLOWING, "flowing"},
410 {LIQUID_SOURCE, "source"},
414 struct EnumString es_NodeBoxType[] =
416 {NODEBOX_REGULAR, "regular"},
417 {NODEBOX_FIXED, "fixed"},
418 {NODEBOX_WALLMOUNTED, "wallmounted"},
422 struct EnumString es_CraftMethod[] =
424 {CRAFT_METHOD_NORMAL, "normal"},
425 {CRAFT_METHOD_COOKING, "cooking"},
426 {CRAFT_METHOD_FUEL, "fuel"},
430 struct EnumString es_TileAnimationType[] =
433 {TAT_VERTICAL_FRAMES, "vertical_frames"},
438 C struct <-> Lua table converter functions
441 static void push_v3f(lua_State *L, v3f p)
444 lua_pushnumber(L, p.X);
445 lua_setfield(L, -2, "x");
446 lua_pushnumber(L, p.Y);
447 lua_setfield(L, -2, "y");
448 lua_pushnumber(L, p.Z);
449 lua_setfield(L, -2, "z");
452 static v2s16 read_v2s16(lua_State *L, int index)
455 luaL_checktype(L, index, LUA_TTABLE);
456 lua_getfield(L, index, "x");
457 p.X = lua_tonumber(L, -1);
459 lua_getfield(L, index, "y");
460 p.Y = lua_tonumber(L, -1);
465 static v2f read_v2f(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 v3f read_v3f(lua_State *L, int index)
481 luaL_checktype(L, index, LUA_TTABLE);
482 lua_getfield(L, index, "x");
483 pos.X = lua_tonumber(L, -1);
485 lua_getfield(L, index, "y");
486 pos.Y = lua_tonumber(L, -1);
488 lua_getfield(L, index, "z");
489 pos.Z = lua_tonumber(L, -1);
494 static v3f check_v3f(lua_State *L, int index)
497 luaL_checktype(L, index, LUA_TTABLE);
498 lua_getfield(L, index, "x");
499 pos.X = luaL_checknumber(L, -1);
501 lua_getfield(L, index, "y");
502 pos.Y = luaL_checknumber(L, -1);
504 lua_getfield(L, index, "z");
505 pos.Z = luaL_checknumber(L, -1);
510 static void pushFloatPos(lua_State *L, v3f p)
516 static v3f checkFloatPos(lua_State *L, int index)
518 return check_v3f(L, index) * BS;
521 static void push_v3s16(lua_State *L, v3s16 p)
524 lua_pushnumber(L, p.X);
525 lua_setfield(L, -2, "x");
526 lua_pushnumber(L, p.Y);
527 lua_setfield(L, -2, "y");
528 lua_pushnumber(L, p.Z);
529 lua_setfield(L, -2, "z");
532 static v3s16 read_v3s16(lua_State *L, int index)
534 // Correct rounding at <0
535 v3f pf = read_v3f(L, index);
536 return floatToInt(pf, 1.0);
539 static v3s16 check_v3s16(lua_State *L, int index)
541 // Correct rounding at <0
542 v3f pf = check_v3f(L, index);
543 return floatToInt(pf, 1.0);
546 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
549 lua_pushstring(L, ndef->get(n).name.c_str());
550 lua_setfield(L, -2, "name");
551 lua_pushnumber(L, n.getParam1());
552 lua_setfield(L, -2, "param1");
553 lua_pushnumber(L, n.getParam2());
554 lua_setfield(L, -2, "param2");
557 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
559 lua_getfield(L, index, "name");
560 const char *name = luaL_checkstring(L, -1);
563 lua_getfield(L, index, "param1");
567 param1 = lua_tonumber(L, -1);
570 lua_getfield(L, index, "param2");
574 param2 = lua_tonumber(L, -1);
576 return MapNode(ndef, name, param1, param2);
579 static video::SColor readARGB8(lua_State *L, int index)
582 luaL_checktype(L, index, LUA_TTABLE);
583 lua_getfield(L, index, "a");
584 if(lua_isnumber(L, -1))
585 color.setAlpha(lua_tonumber(L, -1));
587 lua_getfield(L, index, "r");
588 color.setRed(lua_tonumber(L, -1));
590 lua_getfield(L, index, "g");
591 color.setGreen(lua_tonumber(L, -1));
593 lua_getfield(L, index, "b");
594 color.setBlue(lua_tonumber(L, -1));
599 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
602 if(lua_istable(L, index)){
603 lua_rawgeti(L, index, 1);
604 box.MinEdge.X = lua_tonumber(L, -1) * scale;
606 lua_rawgeti(L, index, 2);
607 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
609 lua_rawgeti(L, index, 3);
610 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
612 lua_rawgeti(L, index, 4);
613 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
615 lua_rawgeti(L, index, 5);
616 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
618 lua_rawgeti(L, index, 6);
619 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
625 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
627 std::vector<aabb3f> boxes;
628 if(lua_istable(L, index)){
629 int n = lua_objlen(L, index);
630 // Check if it's a single box or a list of boxes
631 bool possibly_single_box = (n == 6);
632 for(int i = 1; i <= n && possibly_single_box; i++){
633 lua_rawgeti(L, index, i);
634 if(!lua_isnumber(L, -1))
635 possibly_single_box = false;
638 if(possibly_single_box){
640 boxes.push_back(read_aabb3f(L, index, scale));
642 // Read a list of boxes
643 for(int i = 1; i <= n; i++){
644 lua_rawgeti(L, index, i);
645 boxes.push_back(read_aabb3f(L, -1, scale));
653 static NodeBox read_nodebox(lua_State *L, int index)
656 if(lua_istable(L, -1)){
657 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
658 es_NodeBoxType, NODEBOX_REGULAR);
660 lua_getfield(L, index, "fixed");
661 if(lua_istable(L, -1))
662 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
665 lua_getfield(L, index, "wall_top");
666 if(lua_istable(L, -1))
667 nodebox.wall_top = read_aabb3f(L, -1, BS);
670 lua_getfield(L, index, "wall_bottom");
671 if(lua_istable(L, -1))
672 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
675 lua_getfield(L, index, "wall_side");
676 if(lua_istable(L, -1))
677 nodebox.wall_side = read_aabb3f(L, -1, BS);
686 static void read_groups(lua_State *L, int index,
687 std::map<std::string, int> &result)
693 while(lua_next(L, index) != 0){
694 // key at index -2 and value at index -1
695 std::string name = luaL_checkstring(L, -2);
696 int rating = luaL_checkinteger(L, -1);
697 result[name] = rating;
698 // removes value, keeps key for next iteration
706 static void read_privileges(lua_State *L, int index,
707 std::set<std::string> &result)
713 while(lua_next(L, index) != 0){
714 // key at index -2 and value at index -1
715 std::string key = luaL_checkstring(L, -2);
716 bool value = lua_toboolean(L, -1);
719 // removes value, keeps key for next iteration
728 static ToolCapabilities read_tool_capabilities(
729 lua_State *L, int table)
731 ToolCapabilities toolcap;
732 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
733 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
734 lua_getfield(L, table, "groupcaps");
735 if(lua_istable(L, -1)){
736 int table_groupcaps = lua_gettop(L);
738 while(lua_next(L, table_groupcaps) != 0){
739 // key at index -2 and value at index -1
740 std::string groupname = luaL_checkstring(L, -2);
741 if(lua_istable(L, -1)){
742 int table_groupcap = lua_gettop(L);
743 // This will be created
744 ToolGroupCap groupcap;
745 // Read simple parameters
746 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
747 getintfield(L, table_groupcap, "uses", groupcap.uses);
748 // DEPRECATED: maxwear
750 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
752 groupcap.uses = 1.0/maxwear;
755 infostream<<script_get_backtrace(L)<<std::endl;
756 infostream<<"WARNING: field \"maxwear\" is deprecated; "
757 <<"should replace with uses=1/maxwear"<<std::endl;
759 // Read "times" table
760 lua_getfield(L, table_groupcap, "times");
761 if(lua_istable(L, -1)){
762 int table_times = lua_gettop(L);
764 while(lua_next(L, table_times) != 0){
765 // key at index -2 and value at index -1
766 int rating = luaL_checkinteger(L, -2);
767 float time = luaL_checknumber(L, -1);
768 groupcap.times[rating] = time;
769 // removes value, keeps key for next iteration
774 // Insert groupcap into toolcap
775 toolcap.groupcaps[groupname] = groupcap;
777 // removes value, keeps key for next iteration
785 static void set_tool_capabilities(lua_State *L, int table,
786 const ToolCapabilities &toolcap)
788 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
789 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
790 // Create groupcaps table
793 for(std::map<std::string, ToolGroupCap>::const_iterator
794 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
795 // Create groupcap table
797 const std::string &name = i->first;
798 const ToolGroupCap &groupcap = i->second;
799 // Create subtable "times"
801 for(std::map<int, float>::const_iterator
802 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
803 int rating = i->first;
804 float time = i->second;
805 lua_pushinteger(L, rating);
806 lua_pushnumber(L, time);
809 // Set subtable "times"
810 lua_setfield(L, -2, "times");
811 // Set simple parameters
812 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
813 setintfield(L, -1, "uses", groupcap.uses);
814 // Insert groupcap table into groupcaps table
815 lua_setfield(L, -2, name.c_str());
817 // Set groupcaps table
818 lua_setfield(L, -2, "groupcaps");
821 static void push_tool_capabilities(lua_State *L,
822 const ToolCapabilities &prop)
825 set_tool_capabilities(L, -1, prop);
832 static void set_dig_params(lua_State *L, int table,
833 const DigParams ¶ms)
835 setboolfield(L, table, "diggable", params.diggable);
836 setfloatfield(L, table, "time", params.time);
837 setintfield(L, table, "wear", params.wear);
840 static void push_dig_params(lua_State *L,
841 const DigParams ¶ms)
844 set_dig_params(L, -1, params);
851 static void set_hit_params(lua_State *L, int table,
852 const HitParams ¶ms)
854 setintfield(L, table, "hp", params.hp);
855 setintfield(L, table, "wear", params.wear);
858 static void push_hit_params(lua_State *L,
859 const HitParams ¶ms)
862 set_hit_params(L, -1, params);
869 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
872 if(pointed.type == POINTEDTHING_NODE)
874 lua_pushstring(L, "node");
875 lua_setfield(L, -2, "type");
876 push_v3s16(L, pointed.node_undersurface);
877 lua_setfield(L, -2, "under");
878 push_v3s16(L, pointed.node_abovesurface);
879 lua_setfield(L, -2, "above");
881 else if(pointed.type == POINTEDTHING_OBJECT)
883 lua_pushstring(L, "object");
884 lua_setfield(L, -2, "type");
885 objectref_get(L, pointed.object_id);
886 lua_setfield(L, -2, "ref");
890 lua_pushstring(L, "nothing");
891 lua_setfield(L, -2, "type");
899 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
902 index = lua_gettop(L) + 1 + index;
903 if(lua_isnil(L, index)){
904 } else if(lua_istable(L, index)){
905 getstringfield(L, index, "name", spec.name);
906 getfloatfield(L, index, "gain", spec.gain);
907 } else if(lua_isstring(L, index)){
908 spec.name = lua_tostring(L, index);
916 static void read_object_properties(lua_State *L, int index,
917 ObjectProperties *prop)
920 index = lua_gettop(L) + 1 + index;
921 if(!lua_istable(L, index))
924 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
926 getboolfield(L, -1, "physical", prop->physical);
928 getfloatfield(L, -1, "weight", prop->weight);
930 lua_getfield(L, -1, "collisionbox");
931 if(lua_istable(L, -1))
932 prop->collisionbox = read_aabb3f(L, -1, 1.0);
935 getstringfield(L, -1, "visual", prop->visual);
937 lua_getfield(L, -1, "visual_size");
938 if(lua_istable(L, -1))
939 prop->visual_size = read_v2f(L, -1);
942 lua_getfield(L, -1, "textures");
943 if(lua_istable(L, -1)){
944 prop->textures.clear();
945 int table = lua_gettop(L);
947 while(lua_next(L, table) != 0){
948 // key at index -2 and value at index -1
949 if(lua_isstring(L, -1))
950 prop->textures.push_back(lua_tostring(L, -1));
952 prop->textures.push_back("");
953 // removes value, keeps key for next iteration
959 lua_getfield(L, -1, "spritediv");
960 if(lua_istable(L, -1))
961 prop->spritediv = read_v2s16(L, -1);
964 lua_getfield(L, -1, "initial_sprite_basepos");
965 if(lua_istable(L, -1))
966 prop->initial_sprite_basepos = read_v2s16(L, -1);
969 getboolfield(L, -1, "is_visible", prop->is_visible);
970 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
971 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
978 static ItemDefinition read_item_definition(lua_State *L, int index,
979 ItemDefinition default_def = ItemDefinition())
982 index = lua_gettop(L) + 1 + index;
984 // Read the item definition
985 ItemDefinition def = default_def;
987 def.type = (ItemType)getenumfield(L, index, "type",
988 es_ItemType, ITEM_NONE);
989 getstringfield(L, index, "name", def.name);
990 getstringfield(L, index, "description", def.description);
991 getstringfield(L, index, "inventory_image", def.inventory_image);
992 getstringfield(L, index, "wield_image", def.wield_image);
994 lua_getfield(L, index, "wield_scale");
995 if(lua_istable(L, -1)){
996 def.wield_scale = check_v3f(L, -1);
1000 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1001 if(def.stack_max == 0)
1004 lua_getfield(L, index, "on_use");
1005 def.usable = lua_isfunction(L, -1);
1008 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1010 warn_if_field_exists(L, index, "tool_digging_properties",
1011 "deprecated: use tool_capabilities");
1013 lua_getfield(L, index, "tool_capabilities");
1014 if(lua_istable(L, -1)){
1015 def.tool_capabilities = new ToolCapabilities(
1016 read_tool_capabilities(L, -1));
1019 // If name is "" (hand), ensure there are ToolCapabilities
1020 // because it will be looked up there whenever any other item has
1021 // no ToolCapabilities
1022 if(def.name == "" && def.tool_capabilities == NULL){
1023 def.tool_capabilities = new ToolCapabilities();
1026 lua_getfield(L, index, "groups");
1027 read_groups(L, -1, def.groups);
1030 // Client shall immediately place this node when player places the item.
1031 // Server will update the precise end result a moment later.
1032 // "" = no prediction
1033 getstringfield(L, index, "node_placement_prediction",
1034 def.node_placement_prediction);
1043 static TileDef read_tiledef(lua_State *L, int index)
1046 index = lua_gettop(L) + 1 + index;
1050 // key at index -2 and value at index
1051 if(lua_isstring(L, index)){
1052 // "default_lava.png"
1053 tiledef.name = lua_tostring(L, index);
1055 else if(lua_istable(L, index))
1057 // {name="default_lava.png", animation={}}
1059 getstringfield(L, index, "name", tiledef.name);
1060 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1061 tiledef.backface_culling = getboolfield_default(
1062 L, index, "backface_culling", true);
1064 lua_getfield(L, index, "animation");
1065 if(lua_istable(L, -1)){
1066 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1067 tiledef.animation.type = (TileAnimationType)
1068 getenumfield(L, -1, "type", es_TileAnimationType,
1070 tiledef.animation.aspect_w =
1071 getintfield_default(L, -1, "aspect_w", 16);
1072 tiledef.animation.aspect_h =
1073 getintfield_default(L, -1, "aspect_h", 16);
1074 tiledef.animation.length =
1075 getfloatfield_default(L, -1, "length", 1.0);
1087 static ContentFeatures read_content_features(lua_State *L, int index)
1090 index = lua_gettop(L) + 1 + index;
1094 /* Cache existence of some callbacks */
1095 lua_getfield(L, index, "on_construct");
1096 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1098 lua_getfield(L, index, "on_destruct");
1099 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1101 lua_getfield(L, index, "after_destruct");
1102 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1106 getstringfield(L, index, "name", f.name);
1109 lua_getfield(L, index, "groups");
1110 read_groups(L, -1, f.groups);
1113 /* Visual definition */
1115 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1117 getfloatfield(L, index, "visual_scale", f.visual_scale);
1120 lua_getfield(L, index, "tiles");
1121 // If nil, try the deprecated name "tile_images" instead
1122 if(lua_isnil(L, -1)){
1124 warn_if_field_exists(L, index, "tile_images",
1125 "Deprecated; new name is \"tiles\".");
1126 lua_getfield(L, index, "tile_images");
1128 if(lua_istable(L, -1)){
1129 int table = lua_gettop(L);
1132 while(lua_next(L, table) != 0){
1133 // Read tiledef from value
1134 f.tiledef[i] = read_tiledef(L, -1);
1135 // removes value, keeps key for next iteration
1143 // Copy last value to all remaining textures
1145 TileDef lasttile = f.tiledef[i-1];
1147 f.tiledef[i] = lasttile;
1154 // special_tiles = {}
1155 lua_getfield(L, index, "special_tiles");
1156 // If nil, try the deprecated name "special_materials" instead
1157 if(lua_isnil(L, -1)){
1159 warn_if_field_exists(L, index, "special_materials",
1160 "Deprecated; new name is \"special_tiles\".");
1161 lua_getfield(L, index, "special_materials");
1163 if(lua_istable(L, -1)){
1164 int table = lua_gettop(L);
1167 while(lua_next(L, table) != 0){
1168 // Read tiledef from value
1169 f.tiledef_special[i] = read_tiledef(L, -1);
1170 // removes value, keeps key for next iteration
1181 f.alpha = getintfield_default(L, index, "alpha", 255);
1185 lua_getfield(L, index, "post_effect_color");
1186 if(!lua_isnil(L, -1))
1187 f.post_effect_color = readARGB8(L, -1);
1190 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1191 es_ContentParamType, CPT_NONE);
1192 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1193 es_ContentParamType2, CPT2_NONE);
1195 // Warn about some deprecated fields
1196 warn_if_field_exists(L, index, "wall_mounted",
1197 "deprecated: use paramtype2 = 'wallmounted'");
1198 warn_if_field_exists(L, index, "light_propagates",
1199 "deprecated: determined from paramtype");
1200 warn_if_field_exists(L, index, "dug_item",
1201 "deprecated: use 'drop' field");
1202 warn_if_field_exists(L, index, "extra_dug_item",
1203 "deprecated: use 'drop' field");
1204 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1205 "deprecated: use 'drop' field");
1206 warn_if_field_exists(L, index, "metadata_name",
1207 "deprecated: use on_add and metadata callbacks");
1209 // True for all ground-like things like stone and mud, false for eg. trees
1210 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1211 f.light_propagates = (f.param_type == CPT_LIGHT);
1212 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1213 // This is used for collision detection.
1214 // Also for general solidness queries.
1215 getboolfield(L, index, "walkable", f.walkable);
1216 // Player can point to these
1217 getboolfield(L, index, "pointable", f.pointable);
1218 // Player can dig these
1219 getboolfield(L, index, "diggable", f.diggable);
1220 // Player can climb these
1221 getboolfield(L, index, "climbable", f.climbable);
1222 // Player can build on these
1223 getboolfield(L, index, "buildable_to", f.buildable_to);
1224 // Whether the node is non-liquid, source liquid or flowing liquid
1225 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1226 es_LiquidType, LIQUID_NONE);
1227 // If the content is liquid, this is the flowing version of the liquid.
1228 getstringfield(L, index, "liquid_alternative_flowing",
1229 f.liquid_alternative_flowing);
1230 // If the content is liquid, this is the source version of the liquid.
1231 getstringfield(L, index, "liquid_alternative_source",
1232 f.liquid_alternative_source);
1233 // Viscosity for fluid flow, ranging from 1 to 7, with
1234 // 1 giving almost instantaneous propagation and 7 being
1235 // the slowest possible
1236 f.liquid_viscosity = getintfield_default(L, index,
1237 "liquid_viscosity", f.liquid_viscosity);
1238 // Amount of light the node emits
1239 f.light_source = getintfield_default(L, index,
1240 "light_source", f.light_source);
1241 f.damage_per_second = getintfield_default(L, index,
1242 "damage_per_second", f.damage_per_second);
1244 lua_getfield(L, index, "node_box");
1245 if(lua_istable(L, -1))
1246 f.node_box = read_nodebox(L, -1);
1249 lua_getfield(L, index, "selection_box");
1250 if(lua_istable(L, -1))
1251 f.selection_box = read_nodebox(L, -1);
1254 // Set to true if paramtype used to be 'facedir_simple'
1255 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1256 // Set to true if wall_mounted used to be set to true
1257 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1260 lua_getfield(L, index, "sounds");
1261 if(lua_istable(L, -1)){
1262 lua_getfield(L, -1, "footstep");
1263 read_soundspec(L, -1, f.sound_footstep);
1265 lua_getfield(L, -1, "dig");
1266 read_soundspec(L, -1, f.sound_dig);
1268 lua_getfield(L, -1, "dug");
1269 read_soundspec(L, -1, f.sound_dug);
1281 static ItemStack read_item(lua_State *L, int index);
1282 static std::vector<ItemStack> read_items(lua_State *L, int index);
1283 // creates a table of ItemStacks
1284 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1286 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1287 lua_State *L, int tableindex, int forcesize=-1)
1290 tableindex = lua_gettop(L) + 1 + tableindex;
1291 // If nil, delete list
1292 if(lua_isnil(L, tableindex)){
1293 inv->deleteList(name);
1296 // Otherwise set list
1297 std::vector<ItemStack> items = read_items(L, tableindex);
1298 int listsize = (forcesize != -1) ? forcesize : items.size();
1299 InventoryList *invlist = inv->addList(name, listsize);
1301 for(std::vector<ItemStack>::const_iterator
1302 i = items.begin(); i != items.end(); i++){
1303 if(forcesize != -1 && index == forcesize)
1305 invlist->changeItem(index, *i);
1308 while(forcesize != -1 && index < forcesize){
1309 invlist->deleteItem(index);
1314 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1317 InventoryList *invlist = inv->getList(name);
1318 if(invlist == NULL){
1322 std::vector<ItemStack> items;
1323 for(u32 i=0; i<invlist->getSize(); i++)
1324 items.push_back(invlist->getItem(i));
1325 push_items(L, items);
1329 Helpful macros for userdata classes
1332 #define method(class, name) {#name, class::l_##name}
1343 static const char className[];
1344 static const luaL_reg methods[];
1346 // Exported functions
1348 // garbage collector
1349 static int gc_object(lua_State *L)
1351 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1356 // is_empty(self) -> true/false
1357 static int l_is_empty(lua_State *L)
1359 LuaItemStack *o = checkobject(L, 1);
1360 ItemStack &item = o->m_stack;
1361 lua_pushboolean(L, item.empty());
1365 // get_name(self) -> string
1366 static int l_get_name(lua_State *L)
1368 LuaItemStack *o = checkobject(L, 1);
1369 ItemStack &item = o->m_stack;
1370 lua_pushstring(L, item.name.c_str());
1374 // get_count(self) -> number
1375 static int l_get_count(lua_State *L)
1377 LuaItemStack *o = checkobject(L, 1);
1378 ItemStack &item = o->m_stack;
1379 lua_pushinteger(L, item.count);
1383 // get_wear(self) -> number
1384 static int l_get_wear(lua_State *L)
1386 LuaItemStack *o = checkobject(L, 1);
1387 ItemStack &item = o->m_stack;
1388 lua_pushinteger(L, item.wear);
1392 // get_metadata(self) -> string
1393 static int l_get_metadata(lua_State *L)
1395 LuaItemStack *o = checkobject(L, 1);
1396 ItemStack &item = o->m_stack;
1397 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1401 // clear(self) -> true
1402 static int l_clear(lua_State *L)
1404 LuaItemStack *o = checkobject(L, 1);
1406 lua_pushboolean(L, true);
1410 // replace(self, itemstack or itemstring or table or nil) -> true
1411 static int l_replace(lua_State *L)
1413 LuaItemStack *o = checkobject(L, 1);
1414 o->m_stack = read_item(L, 2);
1415 lua_pushboolean(L, true);
1419 // to_string(self) -> string
1420 static int l_to_string(lua_State *L)
1422 LuaItemStack *o = checkobject(L, 1);
1423 std::string itemstring = o->m_stack.getItemString();
1424 lua_pushstring(L, itemstring.c_str());
1428 // to_table(self) -> table or nil
1429 static int l_to_table(lua_State *L)
1431 LuaItemStack *o = checkobject(L, 1);
1432 const ItemStack &item = o->m_stack;
1440 lua_pushstring(L, item.name.c_str());
1441 lua_setfield(L, -2, "name");
1442 lua_pushinteger(L, item.count);
1443 lua_setfield(L, -2, "count");
1444 lua_pushinteger(L, item.wear);
1445 lua_setfield(L, -2, "wear");
1446 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1447 lua_setfield(L, -2, "metadata");
1452 // get_stack_max(self) -> number
1453 static int l_get_stack_max(lua_State *L)
1455 LuaItemStack *o = checkobject(L, 1);
1456 ItemStack &item = o->m_stack;
1457 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1461 // get_free_space(self) -> number
1462 static int l_get_free_space(lua_State *L)
1464 LuaItemStack *o = checkobject(L, 1);
1465 ItemStack &item = o->m_stack;
1466 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1470 // is_known(self) -> true/false
1471 // Checks if the item is defined.
1472 static int l_is_known(lua_State *L)
1474 LuaItemStack *o = checkobject(L, 1);
1475 ItemStack &item = o->m_stack;
1476 bool is_known = item.isKnown(get_server(L)->idef());
1477 lua_pushboolean(L, is_known);
1481 // get_definition(self) -> table
1482 // Returns the item definition table from minetest.registered_items,
1483 // or a fallback one (name="unknown")
1484 static int l_get_definition(lua_State *L)
1486 LuaItemStack *o = checkobject(L, 1);
1487 ItemStack &item = o->m_stack;
1489 // Get minetest.registered_items[name]
1490 lua_getglobal(L, "minetest");
1491 lua_getfield(L, -1, "registered_items");
1492 luaL_checktype(L, -1, LUA_TTABLE);
1493 lua_getfield(L, -1, item.name.c_str());
1494 if(lua_isnil(L, -1))
1497 lua_getfield(L, -1, "unknown");
1502 // get_tool_capabilities(self) -> table
1503 // Returns the effective tool digging properties.
1504 // Returns those of the hand ("") if this item has none associated.
1505 static int l_get_tool_capabilities(lua_State *L)
1507 LuaItemStack *o = checkobject(L, 1);
1508 ItemStack &item = o->m_stack;
1509 const ToolCapabilities &prop =
1510 item.getToolCapabilities(get_server(L)->idef());
1511 push_tool_capabilities(L, prop);
1515 // add_wear(self, amount) -> true/false
1516 // The range for "amount" is [0,65535]. Wear is only added if the item
1517 // is a tool. Adding wear might destroy the item.
1518 // Returns true if the item is (or was) a tool.
1519 static int l_add_wear(lua_State *L)
1521 LuaItemStack *o = checkobject(L, 1);
1522 ItemStack &item = o->m_stack;
1523 int amount = lua_tointeger(L, 2);
1524 bool result = item.addWear(amount, get_server(L)->idef());
1525 lua_pushboolean(L, result);
1529 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1530 // Returns leftover item stack
1531 static int l_add_item(lua_State *L)
1533 LuaItemStack *o = checkobject(L, 1);
1534 ItemStack &item = o->m_stack;
1535 ItemStack newitem = read_item(L, 2);
1536 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1537 create(L, leftover);
1541 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1542 // First return value is true iff the new item fits fully into the stack
1543 // Second return value is the would-be-left-over item stack
1544 static int l_item_fits(lua_State *L)
1546 LuaItemStack *o = checkobject(L, 1);
1547 ItemStack &item = o->m_stack;
1548 ItemStack newitem = read_item(L, 2);
1550 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1551 lua_pushboolean(L, fits); // first return value
1552 create(L, restitem); // second return value
1556 // take_item(self, takecount=1) -> itemstack
1557 static int l_take_item(lua_State *L)
1559 LuaItemStack *o = checkobject(L, 1);
1560 ItemStack &item = o->m_stack;
1562 if(!lua_isnone(L, 2))
1563 takecount = luaL_checkinteger(L, 2);
1564 ItemStack taken = item.takeItem(takecount);
1569 // peek_item(self, peekcount=1) -> itemstack
1570 static int l_peek_item(lua_State *L)
1572 LuaItemStack *o = checkobject(L, 1);
1573 ItemStack &item = o->m_stack;
1575 if(!lua_isnone(L, 2))
1576 peekcount = lua_tointeger(L, 2);
1577 ItemStack peekaboo = item.peekItem(peekcount);
1578 create(L, peekaboo);
1583 LuaItemStack(const ItemStack &item):
1592 const ItemStack& getItem() const
1596 ItemStack& getItem()
1601 // LuaItemStack(itemstack or itemstring or table or nil)
1602 // Creates an LuaItemStack and leaves it on top of stack
1603 static int create_object(lua_State *L)
1605 ItemStack item = read_item(L, 1);
1606 LuaItemStack *o = new LuaItemStack(item);
1607 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1608 luaL_getmetatable(L, className);
1609 lua_setmetatable(L, -2);
1612 // Not callable from Lua
1613 static int create(lua_State *L, const ItemStack &item)
1615 LuaItemStack *o = new LuaItemStack(item);
1616 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1617 luaL_getmetatable(L, className);
1618 lua_setmetatable(L, -2);
1622 static LuaItemStack* checkobject(lua_State *L, int narg)
1624 luaL_checktype(L, narg, LUA_TUSERDATA);
1625 void *ud = luaL_checkudata(L, narg, className);
1626 if(!ud) luaL_typerror(L, narg, className);
1627 return *(LuaItemStack**)ud; // unbox pointer
1630 static void Register(lua_State *L)
1633 int methodtable = lua_gettop(L);
1634 luaL_newmetatable(L, className);
1635 int metatable = lua_gettop(L);
1637 lua_pushliteral(L, "__metatable");
1638 lua_pushvalue(L, methodtable);
1639 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1641 lua_pushliteral(L, "__index");
1642 lua_pushvalue(L, methodtable);
1643 lua_settable(L, metatable);
1645 lua_pushliteral(L, "__gc");
1646 lua_pushcfunction(L, gc_object);
1647 lua_settable(L, metatable);
1649 lua_pop(L, 1); // drop metatable
1651 luaL_openlib(L, 0, methods, 0); // fill methodtable
1652 lua_pop(L, 1); // drop methodtable
1654 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1655 lua_register(L, className, create_object);
1658 const char LuaItemStack::className[] = "ItemStack";
1659 const luaL_reg LuaItemStack::methods[] = {
1660 method(LuaItemStack, is_empty),
1661 method(LuaItemStack, get_name),
1662 method(LuaItemStack, get_count),
1663 method(LuaItemStack, get_wear),
1664 method(LuaItemStack, get_metadata),
1665 method(LuaItemStack, clear),
1666 method(LuaItemStack, replace),
1667 method(LuaItemStack, to_string),
1668 method(LuaItemStack, to_table),
1669 method(LuaItemStack, get_stack_max),
1670 method(LuaItemStack, get_free_space),
1671 method(LuaItemStack, is_known),
1672 method(LuaItemStack, get_definition),
1673 method(LuaItemStack, get_tool_capabilities),
1674 method(LuaItemStack, add_wear),
1675 method(LuaItemStack, add_item),
1676 method(LuaItemStack, item_fits),
1677 method(LuaItemStack, take_item),
1678 method(LuaItemStack, peek_item),
1682 static ItemStack read_item(lua_State *L, int index)
1685 index = lua_gettop(L) + 1 + index;
1687 if(lua_isnil(L, index))
1691 else if(lua_isuserdata(L, index))
1693 // Convert from LuaItemStack
1694 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1695 return o->getItem();
1697 else if(lua_isstring(L, index))
1699 // Convert from itemstring
1700 std::string itemstring = lua_tostring(L, index);
1701 IItemDefManager *idef = get_server(L)->idef();
1705 item.deSerialize(itemstring, idef);
1708 catch(SerializationError &e)
1710 infostream<<"WARNING: unable to create item from itemstring"
1711 <<": "<<itemstring<<std::endl;
1715 else if(lua_istable(L, index))
1717 // Convert from table
1718 IItemDefManager *idef = get_server(L)->idef();
1719 std::string name = getstringfield_default(L, index, "name", "");
1720 int count = getintfield_default(L, index, "count", 1);
1721 int wear = getintfield_default(L, index, "wear", 0);
1722 std::string metadata = getstringfield_default(L, index, "metadata", "");
1723 return ItemStack(name, count, wear, metadata, idef);
1727 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1731 static std::vector<ItemStack> read_items(lua_State *L, int index)
1734 index = lua_gettop(L) + 1 + index;
1736 std::vector<ItemStack> items;
1737 luaL_checktype(L, index, LUA_TTABLE);
1739 while(lua_next(L, index) != 0){
1740 // key at index -2 and value at index -1
1741 items.push_back(read_item(L, -1));
1742 // removes value, keeps key for next iteration
1748 // creates a table of ItemStacks
1749 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1751 // Get the table insert function
1752 lua_getglobal(L, "table");
1753 lua_getfield(L, -1, "insert");
1754 int table_insert = lua_gettop(L);
1755 // Create and fill table
1757 int table = lua_gettop(L);
1758 for(u32 i=0; i<items.size(); i++){
1759 ItemStack item = items[i];
1760 lua_pushvalue(L, table_insert);
1761 lua_pushvalue(L, table);
1762 LuaItemStack::create(L, item);
1763 if(lua_pcall(L, 2, 0, 0))
1764 script_error(L, "error: %s", lua_tostring(L, -1));
1766 lua_remove(L, -2); // Remove table
1767 lua_remove(L, -2); // Remove insert
1777 InventoryLocation m_loc;
1779 static const char className[];
1780 static const luaL_reg methods[];
1782 static InvRef *checkobject(lua_State *L, int narg)
1784 luaL_checktype(L, narg, LUA_TUSERDATA);
1785 void *ud = luaL_checkudata(L, narg, className);
1786 if(!ud) luaL_typerror(L, narg, className);
1787 return *(InvRef**)ud; // unbox pointer
1790 static Inventory* getinv(lua_State *L, InvRef *ref)
1792 return get_server(L)->getInventory(ref->m_loc);
1795 static InventoryList* getlist(lua_State *L, InvRef *ref,
1796 const char *listname)
1798 Inventory *inv = getinv(L, ref);
1801 return inv->getList(listname);
1804 static void reportInventoryChange(lua_State *L, InvRef *ref)
1806 // Inform other things that the inventory has changed
1807 get_server(L)->setInventoryModified(ref->m_loc);
1810 // Exported functions
1812 // garbage collector
1813 static int gc_object(lua_State *L) {
1814 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1819 // is_empty(self, listname) -> true/false
1820 static int l_is_empty(lua_State *L)
1822 InvRef *ref = checkobject(L, 1);
1823 const char *listname = luaL_checkstring(L, 2);
1824 InventoryList *list = getlist(L, ref, listname);
1825 if(list && list->getUsedSlots() > 0){
1826 lua_pushboolean(L, false);
1828 lua_pushboolean(L, true);
1833 // get_size(self, listname)
1834 static int l_get_size(lua_State *L)
1836 InvRef *ref = checkobject(L, 1);
1837 const char *listname = luaL_checkstring(L, 2);
1838 InventoryList *list = getlist(L, ref, listname);
1840 lua_pushinteger(L, list->getSize());
1842 lua_pushinteger(L, 0);
1847 // set_size(self, listname, size)
1848 static int l_set_size(lua_State *L)
1850 InvRef *ref = checkobject(L, 1);
1851 const char *listname = luaL_checkstring(L, 2);
1852 int newsize = luaL_checknumber(L, 3);
1853 Inventory *inv = getinv(L, ref);
1855 inv->deleteList(listname);
1856 reportInventoryChange(L, ref);
1859 InventoryList *list = inv->getList(listname);
1861 list->setSize(newsize);
1863 list = inv->addList(listname, newsize);
1865 reportInventoryChange(L, ref);
1869 // get_stack(self, listname, i) -> itemstack
1870 static int l_get_stack(lua_State *L)
1872 InvRef *ref = checkobject(L, 1);
1873 const char *listname = luaL_checkstring(L, 2);
1874 int i = luaL_checknumber(L, 3) - 1;
1875 InventoryList *list = getlist(L, ref, listname);
1877 if(list != NULL && i >= 0 && i < (int) list->getSize())
1878 item = list->getItem(i);
1879 LuaItemStack::create(L, item);
1883 // set_stack(self, listname, i, stack) -> true/false
1884 static int l_set_stack(lua_State *L)
1886 InvRef *ref = checkobject(L, 1);
1887 const char *listname = luaL_checkstring(L, 2);
1888 int i = luaL_checknumber(L, 3) - 1;
1889 ItemStack newitem = read_item(L, 4);
1890 InventoryList *list = getlist(L, ref, listname);
1891 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1892 list->changeItem(i, newitem);
1893 reportInventoryChange(L, ref);
1894 lua_pushboolean(L, true);
1896 lua_pushboolean(L, false);
1901 // get_list(self, listname) -> list or nil
1902 static int l_get_list(lua_State *L)
1904 InvRef *ref = checkobject(L, 1);
1905 const char *listname = luaL_checkstring(L, 2);
1906 Inventory *inv = getinv(L, ref);
1907 inventory_get_list_to_lua(inv, listname, L);
1911 // set_list(self, listname, list)
1912 static int l_set_list(lua_State *L)
1914 InvRef *ref = checkobject(L, 1);
1915 const char *listname = luaL_checkstring(L, 2);
1916 Inventory *inv = getinv(L, ref);
1917 InventoryList *list = inv->getList(listname);
1919 inventory_set_list_from_lua(inv, listname, L, 3,
1922 inventory_set_list_from_lua(inv, listname, L, 3);
1923 reportInventoryChange(L, ref);
1927 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1928 // Returns the leftover stack
1929 static int l_add_item(lua_State *L)
1931 InvRef *ref = checkobject(L, 1);
1932 const char *listname = luaL_checkstring(L, 2);
1933 ItemStack item = read_item(L, 3);
1934 InventoryList *list = getlist(L, ref, listname);
1936 ItemStack leftover = list->addItem(item);
1937 if(leftover.count != item.count)
1938 reportInventoryChange(L, ref);
1939 LuaItemStack::create(L, leftover);
1941 LuaItemStack::create(L, item);
1946 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1947 // Returns true if the item completely fits into the list
1948 static int l_room_for_item(lua_State *L)
1950 InvRef *ref = checkobject(L, 1);
1951 const char *listname = luaL_checkstring(L, 2);
1952 ItemStack item = read_item(L, 3);
1953 InventoryList *list = getlist(L, ref, listname);
1955 lua_pushboolean(L, list->roomForItem(item));
1957 lua_pushboolean(L, false);
1962 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1963 // Returns true if the list contains the given count of the given item name
1964 static int l_contains_item(lua_State *L)
1966 InvRef *ref = checkobject(L, 1);
1967 const char *listname = luaL_checkstring(L, 2);
1968 ItemStack item = read_item(L, 3);
1969 InventoryList *list = getlist(L, ref, listname);
1971 lua_pushboolean(L, list->containsItem(item));
1973 lua_pushboolean(L, false);
1978 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1979 // Returns the items that were actually removed
1980 static int l_remove_item(lua_State *L)
1982 InvRef *ref = checkobject(L, 1);
1983 const char *listname = luaL_checkstring(L, 2);
1984 ItemStack item = read_item(L, 3);
1985 InventoryList *list = getlist(L, ref, listname);
1987 ItemStack removed = list->removeItem(item);
1988 if(!removed.empty())
1989 reportInventoryChange(L, ref);
1990 LuaItemStack::create(L, removed);
1992 LuaItemStack::create(L, ItemStack());
1998 InvRef(const InventoryLocation &loc):
2007 // Creates an InvRef and leaves it on top of stack
2008 // Not callable from Lua; all references are created on the C side.
2009 static void create(lua_State *L, const InventoryLocation &loc)
2011 InvRef *o = new InvRef(loc);
2012 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2013 luaL_getmetatable(L, className);
2014 lua_setmetatable(L, -2);
2016 static void createPlayer(lua_State *L, Player *player)
2018 InventoryLocation loc;
2019 loc.setPlayer(player->getName());
2022 static void createNodeMeta(lua_State *L, v3s16 p)
2024 InventoryLocation loc;
2029 static void Register(lua_State *L)
2032 int methodtable = lua_gettop(L);
2033 luaL_newmetatable(L, className);
2034 int metatable = lua_gettop(L);
2036 lua_pushliteral(L, "__metatable");
2037 lua_pushvalue(L, methodtable);
2038 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2040 lua_pushliteral(L, "__index");
2041 lua_pushvalue(L, methodtable);
2042 lua_settable(L, metatable);
2044 lua_pushliteral(L, "__gc");
2045 lua_pushcfunction(L, gc_object);
2046 lua_settable(L, metatable);
2048 lua_pop(L, 1); // drop metatable
2050 luaL_openlib(L, 0, methods, 0); // fill methodtable
2051 lua_pop(L, 1); // drop methodtable
2053 // Cannot be created from Lua
2054 //lua_register(L, className, create_object);
2057 const char InvRef::className[] = "InvRef";
2058 const luaL_reg InvRef::methods[] = {
2059 method(InvRef, is_empty),
2060 method(InvRef, get_size),
2061 method(InvRef, set_size),
2062 method(InvRef, get_stack),
2063 method(InvRef, set_stack),
2064 method(InvRef, get_list),
2065 method(InvRef, set_list),
2066 method(InvRef, add_item),
2067 method(InvRef, room_for_item),
2068 method(InvRef, contains_item),
2069 method(InvRef, remove_item),
2081 ServerEnvironment *m_env;
2083 static const char className[];
2084 static const luaL_reg methods[];
2086 static NodeMetaRef *checkobject(lua_State *L, int narg)
2088 luaL_checktype(L, narg, LUA_TUSERDATA);
2089 void *ud = luaL_checkudata(L, narg, className);
2090 if(!ud) luaL_typerror(L, narg, className);
2091 return *(NodeMetaRef**)ud; // unbox pointer
2094 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2096 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2097 if(meta == NULL && auto_create)
2099 meta = new NodeMetadata(ref->m_env->getGameDef());
2100 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2105 static void reportMetadataChange(NodeMetaRef *ref)
2107 // Inform other things that the metadata has changed
2108 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2110 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2112 ref->m_env->getMap().dispatchEvent(&event);
2113 // Set the block to be saved
2114 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2116 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2117 "NodeMetaRef::reportMetadataChange");
2120 // Exported functions
2122 // garbage collector
2123 static int gc_object(lua_State *L) {
2124 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2129 // get_string(self, name)
2130 static int l_get_string(lua_State *L)
2132 NodeMetaRef *ref = checkobject(L, 1);
2133 std::string name = luaL_checkstring(L, 2);
2135 NodeMetadata *meta = getmeta(ref, false);
2137 lua_pushlstring(L, "", 0);
2140 std::string str = meta->getString(name);
2141 lua_pushlstring(L, str.c_str(), str.size());
2145 // set_string(self, name, var)
2146 static int l_set_string(lua_State *L)
2148 NodeMetaRef *ref = checkobject(L, 1);
2149 std::string name = luaL_checkstring(L, 2);
2151 const char *s = lua_tolstring(L, 3, &len);
2152 std::string str(s, len);
2154 NodeMetadata *meta = getmeta(ref, !str.empty());
2155 if(meta == NULL || str == meta->getString(name))
2157 meta->setString(name, str);
2158 reportMetadataChange(ref);
2162 // get_int(self, name)
2163 static int l_get_int(lua_State *L)
2165 NodeMetaRef *ref = checkobject(L, 1);
2166 std::string name = lua_tostring(L, 2);
2168 NodeMetadata *meta = getmeta(ref, false);
2170 lua_pushnumber(L, 0);
2173 std::string str = meta->getString(name);
2174 lua_pushnumber(L, stoi(str));
2178 // set_int(self, name, var)
2179 static int l_set_int(lua_State *L)
2181 NodeMetaRef *ref = checkobject(L, 1);
2182 std::string name = lua_tostring(L, 2);
2183 int a = lua_tointeger(L, 3);
2184 std::string str = itos(a);
2186 NodeMetadata *meta = getmeta(ref, true);
2187 if(meta == NULL || str == meta->getString(name))
2189 meta->setString(name, str);
2190 reportMetadataChange(ref);
2194 // get_float(self, name)
2195 static int l_get_float(lua_State *L)
2197 NodeMetaRef *ref = checkobject(L, 1);
2198 std::string name = lua_tostring(L, 2);
2200 NodeMetadata *meta = getmeta(ref, false);
2202 lua_pushnumber(L, 0);
2205 std::string str = meta->getString(name);
2206 lua_pushnumber(L, stof(str));
2210 // set_float(self, name, var)
2211 static int l_set_float(lua_State *L)
2213 NodeMetaRef *ref = checkobject(L, 1);
2214 std::string name = lua_tostring(L, 2);
2215 float a = lua_tonumber(L, 3);
2216 std::string str = ftos(a);
2218 NodeMetadata *meta = getmeta(ref, true);
2219 if(meta == NULL || str == meta->getString(name))
2221 meta->setString(name, str);
2222 reportMetadataChange(ref);
2226 // get_inventory(self)
2227 static int l_get_inventory(lua_State *L)
2229 NodeMetaRef *ref = checkobject(L, 1);
2230 getmeta(ref, true); // try to ensure the metadata exists
2231 InvRef::createNodeMeta(L, ref->m_p);
2236 static int l_to_table(lua_State *L)
2238 NodeMetaRef *ref = checkobject(L, 1);
2240 NodeMetadata *meta = getmeta(ref, true);
2249 std::map<std::string, std::string> fields = meta->getStrings();
2250 for(std::map<std::string, std::string>::const_iterator
2251 i = fields.begin(); i != fields.end(); i++){
2252 const std::string &name = i->first;
2253 const std::string &value = i->second;
2254 lua_pushlstring(L, name.c_str(), name.size());
2255 lua_pushlstring(L, value.c_str(), value.size());
2256 lua_settable(L, -3);
2259 lua_setfield(L, -2, "fields");
2262 Inventory *inv = meta->getInventory();
2264 std::vector<const InventoryList*> lists = inv->getLists();
2265 for(std::vector<const InventoryList*>::const_iterator
2266 i = lists.begin(); i != lists.end(); i++){
2267 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2268 lua_setfield(L, -2, (*i)->getName().c_str());
2271 lua_setfield(L, -2, "inventory");
2275 // from_table(self, table)
2276 static int l_from_table(lua_State *L)
2278 NodeMetaRef *ref = checkobject(L, 1);
2281 if(lua_isnil(L, base)){
2283 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2284 lua_pushboolean(L, true);
2288 // Has metadata; clear old one first
2289 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2290 // Create new metadata
2291 NodeMetadata *meta = getmeta(ref, true);
2293 lua_getfield(L, base, "fields");
2294 int fieldstable = lua_gettop(L);
2296 while(lua_next(L, fieldstable) != 0){
2297 // key at index -2 and value at index -1
2298 std::string name = lua_tostring(L, -2);
2300 const char *cs = lua_tolstring(L, -1, &cl);
2301 std::string value(cs, cl);
2302 meta->setString(name, value);
2303 lua_pop(L, 1); // removes value, keeps key for next iteration
2306 Inventory *inv = meta->getInventory();
2307 lua_getfield(L, base, "inventory");
2308 int inventorytable = lua_gettop(L);
2310 while(lua_next(L, inventorytable) != 0){
2311 // key at index -2 and value at index -1
2312 std::string name = lua_tostring(L, -2);
2313 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2314 lua_pop(L, 1); // removes value, keeps key for next iteration
2316 reportMetadataChange(ref);
2317 lua_pushboolean(L, true);
2322 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2332 // Creates an NodeMetaRef and leaves it on top of stack
2333 // Not callable from Lua; all references are created on the C side.
2334 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2336 NodeMetaRef *o = new NodeMetaRef(p, env);
2337 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2338 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2339 luaL_getmetatable(L, className);
2340 lua_setmetatable(L, -2);
2343 static void Register(lua_State *L)
2346 int methodtable = lua_gettop(L);
2347 luaL_newmetatable(L, className);
2348 int metatable = lua_gettop(L);
2350 lua_pushliteral(L, "__metatable");
2351 lua_pushvalue(L, methodtable);
2352 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2354 lua_pushliteral(L, "__index");
2355 lua_pushvalue(L, methodtable);
2356 lua_settable(L, metatable);
2358 lua_pushliteral(L, "__gc");
2359 lua_pushcfunction(L, gc_object);
2360 lua_settable(L, metatable);
2362 lua_pop(L, 1); // drop metatable
2364 luaL_openlib(L, 0, methods, 0); // fill methodtable
2365 lua_pop(L, 1); // drop methodtable
2367 // Cannot be created from Lua
2368 //lua_register(L, className, create_object);
2371 const char NodeMetaRef::className[] = "NodeMetaRef";
2372 const luaL_reg NodeMetaRef::methods[] = {
2373 method(NodeMetaRef, get_string),
2374 method(NodeMetaRef, set_string),
2375 method(NodeMetaRef, get_int),
2376 method(NodeMetaRef, set_int),
2377 method(NodeMetaRef, get_float),
2378 method(NodeMetaRef, set_float),
2379 method(NodeMetaRef, get_inventory),
2380 method(NodeMetaRef, to_table),
2381 method(NodeMetaRef, from_table),
2392 ServerActiveObject *m_object;
2394 static const char className[];
2395 static const luaL_reg methods[];
2397 static ObjectRef *checkobject(lua_State *L, int narg)
2399 luaL_checktype(L, narg, LUA_TUSERDATA);
2400 void *ud = luaL_checkudata(L, narg, className);
2401 if(!ud) luaL_typerror(L, narg, className);
2402 return *(ObjectRef**)ud; // unbox pointer
2405 static ServerActiveObject* getobject(ObjectRef *ref)
2407 ServerActiveObject *co = ref->m_object;
2411 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2413 ServerActiveObject *obj = getobject(ref);
2416 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2418 return (LuaEntitySAO*)obj;
2421 static PlayerSAO* getplayersao(ObjectRef *ref)
2423 ServerActiveObject *obj = getobject(ref);
2426 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2428 return (PlayerSAO*)obj;
2431 static Player* getplayer(ObjectRef *ref)
2433 PlayerSAO *playersao = getplayersao(ref);
2434 if(playersao == NULL)
2436 return playersao->getPlayer();
2439 // Exported functions
2441 // garbage collector
2442 static int gc_object(lua_State *L) {
2443 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2444 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2450 static int l_remove(lua_State *L)
2452 ObjectRef *ref = checkobject(L, 1);
2453 ServerActiveObject *co = getobject(ref);
2454 if(co == NULL) return 0;
2455 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2456 co->m_removed = true;
2461 // returns: {x=num, y=num, z=num}
2462 static int l_getpos(lua_State *L)
2464 ObjectRef *ref = checkobject(L, 1);
2465 ServerActiveObject *co = getobject(ref);
2466 if(co == NULL) return 0;
2467 v3f pos = co->getBasePosition() / BS;
2469 lua_pushnumber(L, pos.X);
2470 lua_setfield(L, -2, "x");
2471 lua_pushnumber(L, pos.Y);
2472 lua_setfield(L, -2, "y");
2473 lua_pushnumber(L, pos.Z);
2474 lua_setfield(L, -2, "z");
2478 // setpos(self, pos)
2479 static int l_setpos(lua_State *L)
2481 ObjectRef *ref = checkobject(L, 1);
2482 //LuaEntitySAO *co = getluaobject(ref);
2483 ServerActiveObject *co = getobject(ref);
2484 if(co == NULL) return 0;
2486 v3f pos = checkFloatPos(L, 2);
2492 // moveto(self, pos, continuous=false)
2493 static int l_moveto(lua_State *L)
2495 ObjectRef *ref = checkobject(L, 1);
2496 //LuaEntitySAO *co = getluaobject(ref);
2497 ServerActiveObject *co = getobject(ref);
2498 if(co == NULL) return 0;
2500 v3f pos = checkFloatPos(L, 2);
2502 bool continuous = lua_toboolean(L, 3);
2504 co->moveTo(pos, continuous);
2508 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2509 static int l_punch(lua_State *L)
2511 ObjectRef *ref = checkobject(L, 1);
2512 ObjectRef *puncher_ref = checkobject(L, 2);
2513 ServerActiveObject *co = getobject(ref);
2514 ServerActiveObject *puncher = getobject(puncher_ref);
2515 if(co == NULL) return 0;
2516 if(puncher == NULL) return 0;
2517 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2518 v3f dir = read_v3f(L, 4);
2519 float time_from_last_punch = 1000000;
2520 if(lua_isnumber(L, 5))
2521 time_from_last_punch = lua_tonumber(L, 5);
2523 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2527 // right_click(self, clicker); clicker = an another ObjectRef
2528 static int l_right_click(lua_State *L)
2530 ObjectRef *ref = checkobject(L, 1);
2531 ObjectRef *ref2 = checkobject(L, 2);
2532 ServerActiveObject *co = getobject(ref);
2533 ServerActiveObject *co2 = getobject(ref2);
2534 if(co == NULL) return 0;
2535 if(co2 == NULL) return 0;
2537 co->rightClick(co2);
2542 // hp = number of hitpoints (2 * number of hearts)
2544 static int l_set_hp(lua_State *L)
2546 ObjectRef *ref = checkobject(L, 1);
2547 luaL_checknumber(L, 2);
2548 ServerActiveObject *co = getobject(ref);
2549 if(co == NULL) return 0;
2550 int hp = lua_tonumber(L, 2);
2551 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2552 <<" hp="<<hp<<std::endl;*/
2560 // returns: number of hitpoints (2 * number of hearts)
2561 // 0 if not applicable to this type of object
2562 static int l_get_hp(lua_State *L)
2564 ObjectRef *ref = checkobject(L, 1);
2565 ServerActiveObject *co = getobject(ref);
2568 lua_pushnumber(L, 1);
2571 int hp = co->getHP();
2572 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2573 <<" hp="<<hp<<std::endl;*/
2575 lua_pushnumber(L, hp);
2579 // get_inventory(self)
2580 static int l_get_inventory(lua_State *L)
2582 ObjectRef *ref = checkobject(L, 1);
2583 ServerActiveObject *co = getobject(ref);
2584 if(co == NULL) return 0;
2586 InventoryLocation loc = co->getInventoryLocation();
2587 if(get_server(L)->getInventory(loc) != NULL)
2588 InvRef::create(L, loc);
2590 lua_pushnil(L); // An object may have no inventory (nil)
2594 // get_wield_list(self)
2595 static int l_get_wield_list(lua_State *L)
2597 ObjectRef *ref = checkobject(L, 1);
2598 ServerActiveObject *co = getobject(ref);
2599 if(co == NULL) return 0;
2601 lua_pushstring(L, co->getWieldList().c_str());
2605 // get_wield_index(self)
2606 static int l_get_wield_index(lua_State *L)
2608 ObjectRef *ref = checkobject(L, 1);
2609 ServerActiveObject *co = getobject(ref);
2610 if(co == NULL) return 0;
2612 lua_pushinteger(L, co->getWieldIndex() + 1);
2616 // get_wielded_item(self)
2617 static int l_get_wielded_item(lua_State *L)
2619 ObjectRef *ref = checkobject(L, 1);
2620 ServerActiveObject *co = getobject(ref);
2623 LuaItemStack::create(L, ItemStack());
2627 LuaItemStack::create(L, co->getWieldedItem());
2631 // set_wielded_item(self, itemstack or itemstring or table or nil)
2632 static int l_set_wielded_item(lua_State *L)
2634 ObjectRef *ref = checkobject(L, 1);
2635 ServerActiveObject *co = getobject(ref);
2636 if(co == NULL) return 0;
2638 ItemStack item = read_item(L, 2);
2639 bool success = co->setWieldedItem(item);
2640 lua_pushboolean(L, success);
2644 // set_armor_groups(self, groups)
2645 static int l_set_armor_groups(lua_State *L)
2647 ObjectRef *ref = checkobject(L, 1);
2648 ServerActiveObject *co = getobject(ref);
2649 if(co == NULL) return 0;
2651 ItemGroupList groups;
2652 read_groups(L, 2, groups);
2653 co->setArmorGroups(groups);
2657 // set_properties(self, properties)
2658 static int l_set_properties(lua_State *L)
2660 ObjectRef *ref = checkobject(L, 1);
2661 ServerActiveObject *co = getobject(ref);
2662 if(co == NULL) return 0;
2663 ObjectProperties *prop = co->accessObjectProperties();
2666 read_object_properties(L, 2, prop);
2667 co->notifyObjectPropertiesModified();
2671 /* LuaEntitySAO-only */
2673 // setvelocity(self, {x=num, y=num, z=num})
2674 static int l_setvelocity(lua_State *L)
2676 ObjectRef *ref = checkobject(L, 1);
2677 LuaEntitySAO *co = getluaobject(ref);
2678 if(co == NULL) return 0;
2679 v3f pos = checkFloatPos(L, 2);
2681 co->setVelocity(pos);
2685 // getvelocity(self)
2686 static int l_getvelocity(lua_State *L)
2688 ObjectRef *ref = checkobject(L, 1);
2689 LuaEntitySAO *co = getluaobject(ref);
2690 if(co == NULL) return 0;
2692 v3f v = co->getVelocity();
2697 // setacceleration(self, {x=num, y=num, z=num})
2698 static int l_setacceleration(lua_State *L)
2700 ObjectRef *ref = checkobject(L, 1);
2701 LuaEntitySAO *co = getluaobject(ref);
2702 if(co == NULL) return 0;
2704 v3f pos = checkFloatPos(L, 2);
2706 co->setAcceleration(pos);
2710 // getacceleration(self)
2711 static int l_getacceleration(lua_State *L)
2713 ObjectRef *ref = checkobject(L, 1);
2714 LuaEntitySAO *co = getluaobject(ref);
2715 if(co == NULL) return 0;
2717 v3f v = co->getAcceleration();
2722 // setyaw(self, radians)
2723 static int l_setyaw(lua_State *L)
2725 ObjectRef *ref = checkobject(L, 1);
2726 LuaEntitySAO *co = getluaobject(ref);
2727 if(co == NULL) return 0;
2728 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2735 static int l_getyaw(lua_State *L)
2737 ObjectRef *ref = checkobject(L, 1);
2738 LuaEntitySAO *co = getluaobject(ref);
2739 if(co == NULL) return 0;
2741 float yaw = co->getYaw() * core::DEGTORAD;
2742 lua_pushnumber(L, yaw);
2746 // settexturemod(self, mod)
2747 static int l_settexturemod(lua_State *L)
2749 ObjectRef *ref = checkobject(L, 1);
2750 LuaEntitySAO *co = getluaobject(ref);
2751 if(co == NULL) return 0;
2753 std::string mod = luaL_checkstring(L, 2);
2754 co->setTextureMod(mod);
2758 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2759 // select_horiz_by_yawpitch=false)
2760 static int l_setsprite(lua_State *L)
2762 ObjectRef *ref = checkobject(L, 1);
2763 LuaEntitySAO *co = getluaobject(ref);
2764 if(co == NULL) return 0;
2767 if(!lua_isnil(L, 2))
2768 p = read_v2s16(L, 2);
2770 if(!lua_isnil(L, 3))
2771 num_frames = lua_tonumber(L, 3);
2772 float framelength = 0.2;
2773 if(!lua_isnil(L, 4))
2774 framelength = lua_tonumber(L, 4);
2775 bool select_horiz_by_yawpitch = false;
2776 if(!lua_isnil(L, 5))
2777 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2778 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2783 // get_entity_name(self)
2784 static int l_get_entity_name(lua_State *L)
2786 ObjectRef *ref = checkobject(L, 1);
2787 LuaEntitySAO *co = getluaobject(ref);
2788 if(co == NULL) return 0;
2790 std::string name = co->getName();
2791 lua_pushstring(L, name.c_str());
2795 // get_luaentity(self)
2796 static int l_get_luaentity(lua_State *L)
2798 ObjectRef *ref = checkobject(L, 1);
2799 LuaEntitySAO *co = getluaobject(ref);
2800 if(co == NULL) return 0;
2802 luaentity_get(L, co->getId());
2809 static int l_is_player(lua_State *L)
2811 ObjectRef *ref = checkobject(L, 1);
2812 Player *player = getplayer(ref);
2813 lua_pushboolean(L, (player != NULL));
2817 // get_player_name(self)
2818 static int l_get_player_name(lua_State *L)
2820 ObjectRef *ref = checkobject(L, 1);
2821 Player *player = getplayer(ref);
2823 lua_pushlstring(L, "", 0);
2827 lua_pushstring(L, player->getName());
2831 // get_look_dir(self)
2832 static int l_get_look_dir(lua_State *L)
2834 ObjectRef *ref = checkobject(L, 1);
2835 Player *player = getplayer(ref);
2836 if(player == NULL) return 0;
2838 float pitch = player->getRadPitch();
2839 float yaw = player->getRadYaw();
2840 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2845 // get_look_pitch(self)
2846 static int l_get_look_pitch(lua_State *L)
2848 ObjectRef *ref = checkobject(L, 1);
2849 Player *player = getplayer(ref);
2850 if(player == NULL) return 0;
2852 lua_pushnumber(L, player->getRadPitch());
2856 // get_look_yaw(self)
2857 static int l_get_look_yaw(lua_State *L)
2859 ObjectRef *ref = checkobject(L, 1);
2860 Player *player = getplayer(ref);
2861 if(player == NULL) return 0;
2863 lua_pushnumber(L, player->getRadYaw());
2867 // set_inventory_formspec(self, formspec)
2868 static int l_set_inventory_formspec(lua_State *L)
2870 ObjectRef *ref = checkobject(L, 1);
2871 Player *player = getplayer(ref);
2872 if(player == NULL) return 0;
2873 std::string formspec = luaL_checkstring(L, 2);
2875 player->inventory_formspec = formspec;
2876 get_server(L)->reportInventoryFormspecModified(player->getName());
2877 lua_pushboolean(L, true);
2881 // get_inventory_formspec(self) -> formspec
2882 static int l_get_inventory_formspec(lua_State *L)
2884 ObjectRef *ref = checkobject(L, 1);
2885 Player *player = getplayer(ref);
2886 if(player == NULL) return 0;
2888 std::string formspec = player->inventory_formspec;
2889 lua_pushlstring(L, formspec.c_str(), formspec.size());
2894 ObjectRef(ServerActiveObject *object):
2897 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2903 infostream<<"ObjectRef destructing for id="
2904 <<m_object->getId()<<std::endl;
2906 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2909 // Creates an ObjectRef and leaves it on top of stack
2910 // Not callable from Lua; all references are created on the C side.
2911 static void create(lua_State *L, ServerActiveObject *object)
2913 ObjectRef *o = new ObjectRef(object);
2914 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2915 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2916 luaL_getmetatable(L, className);
2917 lua_setmetatable(L, -2);
2920 static void set_null(lua_State *L)
2922 ObjectRef *o = checkobject(L, -1);
2926 static void Register(lua_State *L)
2929 int methodtable = lua_gettop(L);
2930 luaL_newmetatable(L, className);
2931 int metatable = lua_gettop(L);
2933 lua_pushliteral(L, "__metatable");
2934 lua_pushvalue(L, methodtable);
2935 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2937 lua_pushliteral(L, "__index");
2938 lua_pushvalue(L, methodtable);
2939 lua_settable(L, metatable);
2941 lua_pushliteral(L, "__gc");
2942 lua_pushcfunction(L, gc_object);
2943 lua_settable(L, metatable);
2945 lua_pop(L, 1); // drop metatable
2947 luaL_openlib(L, 0, methods, 0); // fill methodtable
2948 lua_pop(L, 1); // drop methodtable
2950 // Cannot be created from Lua
2951 //lua_register(L, className, create_object);
2954 const char ObjectRef::className[] = "ObjectRef";
2955 const luaL_reg ObjectRef::methods[] = {
2956 // ServerActiveObject
2957 method(ObjectRef, remove),
2958 method(ObjectRef, getpos),
2959 method(ObjectRef, setpos),
2960 method(ObjectRef, moveto),
2961 method(ObjectRef, punch),
2962 method(ObjectRef, right_click),
2963 method(ObjectRef, set_hp),
2964 method(ObjectRef, get_hp),
2965 method(ObjectRef, get_inventory),
2966 method(ObjectRef, get_wield_list),
2967 method(ObjectRef, get_wield_index),
2968 method(ObjectRef, get_wielded_item),
2969 method(ObjectRef, set_wielded_item),
2970 method(ObjectRef, set_armor_groups),
2971 method(ObjectRef, set_properties),
2972 // LuaEntitySAO-only
2973 method(ObjectRef, setvelocity),
2974 method(ObjectRef, getvelocity),
2975 method(ObjectRef, setacceleration),
2976 method(ObjectRef, getacceleration),
2977 method(ObjectRef, setyaw),
2978 method(ObjectRef, getyaw),
2979 method(ObjectRef, settexturemod),
2980 method(ObjectRef, setsprite),
2981 method(ObjectRef, get_entity_name),
2982 method(ObjectRef, get_luaentity),
2984 method(ObjectRef, is_player),
2985 method(ObjectRef, get_player_name),
2986 method(ObjectRef, get_look_dir),
2987 method(ObjectRef, get_look_pitch),
2988 method(ObjectRef, get_look_yaw),
2989 method(ObjectRef, set_inventory_formspec),
2990 method(ObjectRef, get_inventory_formspec),
2994 // Creates a new anonymous reference if cobj=NULL or id=0
2995 static void objectref_get_or_create(lua_State *L,
2996 ServerActiveObject *cobj)
2998 if(cobj == NULL || cobj->getId() == 0){
2999 ObjectRef::create(L, cobj);
3001 objectref_get(L, cobj->getId());
3010 class LuaPerlinNoise
3017 static const char className[];
3018 static const luaL_reg methods[];
3020 // Exported functions
3022 // garbage collector
3023 static int gc_object(lua_State *L)
3025 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3030 static int l_get2d(lua_State *L)
3032 LuaPerlinNoise *o = checkobject(L, 1);
3033 v2f pos2d = read_v2f(L,2);
3034 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3035 lua_pushnumber(L, val);
3038 static int l_get3d(lua_State *L)
3040 LuaPerlinNoise *o = checkobject(L, 1);
3041 v3f pos3d = read_v3f(L,2);
3042 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3043 lua_pushnumber(L, val);
3048 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
3052 persistence(a_persistence),
3061 // LuaPerlinNoise(seed, octaves, persistence, scale)
3062 // Creates an LuaPerlinNoise and leaves it on top of stack
3063 static int create_object(lua_State *L)
3065 int seed = luaL_checkint(L, 1);
3066 int octaves = luaL_checkint(L, 2);
3067 double persistence = luaL_checknumber(L, 3);
3068 double scale = luaL_checknumber(L, 4);
3069 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3070 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3071 luaL_getmetatable(L, className);
3072 lua_setmetatable(L, -2);
3076 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3078 luaL_checktype(L, narg, LUA_TUSERDATA);
3079 void *ud = luaL_checkudata(L, narg, className);
3080 if(!ud) luaL_typerror(L, narg, className);
3081 return *(LuaPerlinNoise**)ud; // unbox pointer
3084 static void Register(lua_State *L)
3087 int methodtable = lua_gettop(L);
3088 luaL_newmetatable(L, className);
3089 int metatable = lua_gettop(L);
3091 lua_pushliteral(L, "__metatable");
3092 lua_pushvalue(L, methodtable);
3093 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3095 lua_pushliteral(L, "__index");
3096 lua_pushvalue(L, methodtable);
3097 lua_settable(L, metatable);
3099 lua_pushliteral(L, "__gc");
3100 lua_pushcfunction(L, gc_object);
3101 lua_settable(L, metatable);
3103 lua_pop(L, 1); // drop metatable
3105 luaL_openlib(L, 0, methods, 0); // fill methodtable
3106 lua_pop(L, 1); // drop methodtable
3108 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3109 lua_register(L, className, create_object);
3112 const char LuaPerlinNoise::className[] = "PerlinNoise";
3113 const luaL_reg LuaPerlinNoise::methods[] = {
3114 method(LuaPerlinNoise, get2d),
3115 method(LuaPerlinNoise, get3d),
3126 ServerEnvironment *m_env;
3128 static const char className[];
3129 static const luaL_reg methods[];
3131 static int gc_object(lua_State *L) {
3132 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3137 static EnvRef *checkobject(lua_State *L, int narg)
3139 luaL_checktype(L, narg, LUA_TUSERDATA);
3140 void *ud = luaL_checkudata(L, narg, className);
3141 if(!ud) luaL_typerror(L, narg, className);
3142 return *(EnvRef**)ud; // unbox pointer
3145 // Exported functions
3147 // EnvRef:set_node(pos, node)
3148 // pos = {x=num, y=num, z=num}
3149 static int l_set_node(lua_State *L)
3151 EnvRef *o = checkobject(L, 1);
3152 ServerEnvironment *env = o->m_env;
3153 if(env == NULL) return 0;
3154 INodeDefManager *ndef = env->getGameDef()->ndef();
3156 v3s16 pos = read_v3s16(L, 2);
3157 MapNode n = readnode(L, 3, ndef);
3159 MapNode n_old = env->getMap().getNodeNoEx(pos);
3161 if(ndef->get(n_old).has_on_destruct)
3162 scriptapi_node_on_destruct(L, pos, n_old);
3164 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3166 // Call post-destructor
3167 if(ndef->get(n_old).has_after_destruct)
3168 scriptapi_node_after_destruct(L, pos, n_old);
3170 if(ndef->get(n).has_on_construct)
3171 scriptapi_node_on_construct(L, pos, n);
3173 lua_pushboolean(L, succeeded);
3177 static int l_add_node(lua_State *L)
3179 return l_set_node(L);
3182 // EnvRef:remove_node(pos)
3183 // pos = {x=num, y=num, z=num}
3184 static int l_remove_node(lua_State *L)
3186 EnvRef *o = checkobject(L, 1);
3187 ServerEnvironment *env = o->m_env;
3188 if(env == NULL) return 0;
3189 INodeDefManager *ndef = env->getGameDef()->ndef();
3191 v3s16 pos = read_v3s16(L, 2);
3193 MapNode n_old = env->getMap().getNodeNoEx(pos);
3195 if(ndef->get(n_old).has_on_destruct)
3196 scriptapi_node_on_destruct(L, pos, n_old);
3198 // This is slightly optimized compared to addNodeWithEvent(air)
3199 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3201 // Call post-destructor
3202 if(ndef->get(n_old).has_after_destruct)
3203 scriptapi_node_after_destruct(L, pos, n_old);
3205 lua_pushboolean(L, succeeded);
3206 // Air doesn't require constructor
3210 // EnvRef:get_node(pos)
3211 // pos = {x=num, y=num, z=num}
3212 static int l_get_node(lua_State *L)
3214 EnvRef *o = checkobject(L, 1);
3215 ServerEnvironment *env = o->m_env;
3216 if(env == NULL) return 0;
3218 v3s16 pos = read_v3s16(L, 2);
3220 MapNode n = env->getMap().getNodeNoEx(pos);
3222 pushnode(L, n, env->getGameDef()->ndef());
3226 // EnvRef:get_node_or_nil(pos)
3227 // pos = {x=num, y=num, z=num}
3228 static int l_get_node_or_nil(lua_State *L)
3230 EnvRef *o = checkobject(L, 1);
3231 ServerEnvironment *env = o->m_env;
3232 if(env == NULL) return 0;
3234 v3s16 pos = read_v3s16(L, 2);
3237 MapNode n = env->getMap().getNode(pos);
3239 pushnode(L, n, env->getGameDef()->ndef());
3241 } catch(InvalidPositionException &e)
3248 // EnvRef:get_node_light(pos, timeofday)
3249 // pos = {x=num, y=num, z=num}
3250 // timeofday: nil = current time, 0 = night, 0.5 = day
3251 static int l_get_node_light(lua_State *L)
3253 EnvRef *o = checkobject(L, 1);
3254 ServerEnvironment *env = o->m_env;
3255 if(env == NULL) return 0;
3257 v3s16 pos = read_v3s16(L, 2);
3258 u32 time_of_day = env->getTimeOfDay();
3259 if(lua_isnumber(L, 3))
3260 time_of_day = 24000.0 * lua_tonumber(L, 3);
3261 time_of_day %= 24000;
3262 u32 dnr = time_to_daynight_ratio(time_of_day);
3263 MapNode n = env->getMap().getNodeNoEx(pos);
3265 MapNode n = env->getMap().getNode(pos);
3266 INodeDefManager *ndef = env->getGameDef()->ndef();
3267 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3269 } catch(InvalidPositionException &e)
3276 // EnvRef:place_node(pos, node)
3277 // pos = {x=num, y=num, z=num}
3278 static int l_place_node(lua_State *L)
3280 EnvRef *o = checkobject(L, 1);
3281 ServerEnvironment *env = o->m_env;
3282 if(env == NULL) return 0;
3283 v3s16 pos = read_v3s16(L, 2);
3284 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3286 // Don't attempt to load non-loaded area as of now
3287 MapNode n_old = env->getMap().getNodeNoEx(pos);
3288 if(n_old.getContent() == CONTENT_IGNORE){
3289 lua_pushboolean(L, false);
3292 // Create item to place
3293 INodeDefManager *ndef = get_server(L)->ndef();
3294 IItemDefManager *idef = get_server(L)->idef();
3295 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3296 // Make pointed position
3297 PointedThing pointed;
3298 pointed.type = POINTEDTHING_NODE;
3299 pointed.node_abovesurface = pos;
3300 pointed.node_undersurface = pos + v3s16(0,-1,0);
3301 // Place it with a NULL placer (appears in Lua as a non-functional
3303 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3304 lua_pushboolean(L, success);
3308 // EnvRef:dig_node(pos)
3309 // pos = {x=num, y=num, z=num}
3310 static int l_dig_node(lua_State *L)
3312 EnvRef *o = checkobject(L, 1);
3313 ServerEnvironment *env = o->m_env;
3314 if(env == NULL) return 0;
3315 v3s16 pos = read_v3s16(L, 2);
3317 // Don't attempt to load non-loaded area as of now
3318 MapNode n = env->getMap().getNodeNoEx(pos);
3319 if(n.getContent() == CONTENT_IGNORE){
3320 lua_pushboolean(L, false);
3323 // Dig it out with a NULL digger (appears in Lua as a
3324 // non-functional ObjectRef)
3325 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3326 lua_pushboolean(L, success);
3330 // EnvRef:punch_node(pos)
3331 // pos = {x=num, y=num, z=num}
3332 static int l_punch_node(lua_State *L)
3334 EnvRef *o = checkobject(L, 1);
3335 ServerEnvironment *env = o->m_env;
3336 if(env == NULL) return 0;
3337 v3s16 pos = read_v3s16(L, 2);
3339 // Don't attempt to load non-loaded area as of now
3340 MapNode n = env->getMap().getNodeNoEx(pos);
3341 if(n.getContent() == CONTENT_IGNORE){
3342 lua_pushboolean(L, false);
3345 // Punch it with a NULL puncher (appears in Lua as a non-functional
3347 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3348 lua_pushboolean(L, success);
3352 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3353 // pos = {x=num, y=num, z=num}
3354 static int l_add_entity(lua_State *L)
3356 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3357 EnvRef *o = checkobject(L, 1);
3358 ServerEnvironment *env = o->m_env;
3359 if(env == NULL) return 0;
3361 v3f pos = checkFloatPos(L, 2);
3363 const char *name = luaL_checkstring(L, 3);
3365 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3366 int objectid = env->addActiveObject(obj);
3367 // If failed to add, return nothing (reads as nil)
3371 objectref_get_or_create(L, obj);
3375 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3376 // pos = {x=num, y=num, z=num}
3377 static int l_add_item(lua_State *L)
3379 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3380 EnvRef *o = checkobject(L, 1);
3381 ServerEnvironment *env = o->m_env;
3382 if(env == NULL) return 0;
3384 v3f pos = checkFloatPos(L, 2);
3386 ItemStack item = read_item(L, 3);
3387 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3389 // Use minetest.spawn_item to spawn a __builtin:item
3390 lua_getglobal(L, "minetest");
3391 lua_getfield(L, -1, "spawn_item");
3392 if(lua_isnil(L, -1))
3394 lua_pushvalue(L, 2);
3395 lua_pushstring(L, item.getItemString().c_str());
3396 if(lua_pcall(L, 2, 1, 0))
3397 script_error(L, "error: %s", lua_tostring(L, -1));
3399 /*lua_pushvalue(L, 1);
3400 lua_pushstring(L, "__builtin:item");
3401 lua_pushstring(L, item.getItemString().c_str());
3402 return l_add_entity(L);*/
3404 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3405 int objectid = env->addActiveObject(obj);
3406 // If failed to add, return nothing (reads as nil)
3410 objectref_get_or_create(L, obj);
3414 // EnvRef:add_rat(pos)
3415 // pos = {x=num, y=num, z=num}
3416 static int l_add_rat(lua_State *L)
3418 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3419 <<" Doing nothing."<<std::endl;
3423 // EnvRef:add_firefly(pos)
3424 // pos = {x=num, y=num, z=num}
3425 static int l_add_firefly(lua_State *L)
3427 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3428 <<" Doing nothing."<<std::endl;
3432 // EnvRef:get_meta(pos)
3433 static int l_get_meta(lua_State *L)
3435 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3436 EnvRef *o = checkobject(L, 1);
3437 ServerEnvironment *env = o->m_env;
3438 if(env == NULL) return 0;
3440 v3s16 p = read_v3s16(L, 2);
3441 NodeMetaRef::create(L, p, env);
3445 // EnvRef:get_player_by_name(name)
3446 static int l_get_player_by_name(lua_State *L)
3448 EnvRef *o = checkobject(L, 1);
3449 ServerEnvironment *env = o->m_env;
3450 if(env == NULL) return 0;
3452 const char *name = luaL_checkstring(L, 2);
3453 Player *player = env->getPlayer(name);
3458 PlayerSAO *sao = player->getPlayerSAO();
3463 // Put player on stack
3464 objectref_get_or_create(L, sao);
3468 // EnvRef:get_objects_inside_radius(pos, radius)
3469 static int l_get_objects_inside_radius(lua_State *L)
3471 // Get the table insert function
3472 lua_getglobal(L, "table");
3473 lua_getfield(L, -1, "insert");
3474 int table_insert = lua_gettop(L);
3476 EnvRef *o = checkobject(L, 1);
3477 ServerEnvironment *env = o->m_env;
3478 if(env == NULL) return 0;
3480 v3f pos = checkFloatPos(L, 2);
3481 float radius = luaL_checknumber(L, 3) * BS;
3482 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3484 int table = lua_gettop(L);
3485 for(std::set<u16>::const_iterator
3486 i = ids.begin(); i != ids.end(); i++){
3487 ServerActiveObject *obj = env->getActiveObject(*i);
3488 // Insert object reference into table
3489 lua_pushvalue(L, table_insert);
3490 lua_pushvalue(L, table);
3491 objectref_get_or_create(L, obj);
3492 if(lua_pcall(L, 2, 0, 0))
3493 script_error(L, "error: %s", lua_tostring(L, -1));
3498 // EnvRef:set_timeofday(val)
3500 static int l_set_timeofday(lua_State *L)
3502 EnvRef *o = checkobject(L, 1);
3503 ServerEnvironment *env = o->m_env;
3504 if(env == NULL) return 0;
3506 float timeofday_f = luaL_checknumber(L, 2);
3507 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3508 int timeofday_mh = (int)(timeofday_f * 24000.0);
3509 // This should be set directly in the environment but currently
3510 // such changes aren't immediately sent to the clients, so call
3511 // the server instead.
3512 //env->setTimeOfDay(timeofday_mh);
3513 get_server(L)->setTimeOfDay(timeofday_mh);
3517 // EnvRef:get_timeofday() -> 0...1
3518 static int l_get_timeofday(lua_State *L)
3520 EnvRef *o = checkobject(L, 1);
3521 ServerEnvironment *env = o->m_env;
3522 if(env == NULL) return 0;
3524 int timeofday_mh = env->getTimeOfDay();
3525 float timeofday_f = (float)timeofday_mh / 24000.0;
3526 lua_pushnumber(L, timeofday_f);
3531 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3532 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3533 static int l_find_node_near(lua_State *L)
3535 EnvRef *o = checkobject(L, 1);
3536 ServerEnvironment *env = o->m_env;
3537 if(env == NULL) return 0;
3538 INodeDefManager *ndef = get_server(L)->ndef();
3539 v3s16 pos = read_v3s16(L, 2);
3540 int radius = luaL_checkinteger(L, 3);
3541 std::set<content_t> filter;
3542 if(lua_istable(L, 4)){
3545 while(lua_next(L, table) != 0){
3546 // key at index -2 and value at index -1
3547 luaL_checktype(L, -1, LUA_TSTRING);
3548 ndef->getIds(lua_tostring(L, -1), filter);
3549 // removes value, keeps key for next iteration
3552 } else if(lua_isstring(L, 4)){
3553 ndef->getIds(lua_tostring(L, 4), filter);
3556 for(int d=1; d<=radius; d++){
3557 core::list<v3s16> list;
3558 getFacePositions(list, d);
3559 for(core::list<v3s16>::Iterator i = list.begin();
3560 i != list.end(); i++){
3561 v3s16 p = pos + (*i);
3562 content_t c = env->getMap().getNodeNoEx(p).getContent();
3563 if(filter.count(c) != 0){
3572 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3573 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3574 static int l_find_nodes_in_area(lua_State *L)
3576 EnvRef *o = checkobject(L, 1);
3577 ServerEnvironment *env = o->m_env;
3578 if(env == NULL) return 0;
3579 INodeDefManager *ndef = get_server(L)->ndef();
3580 v3s16 minp = read_v3s16(L, 2);
3581 v3s16 maxp = read_v3s16(L, 3);
3582 std::set<content_t> filter;
3583 if(lua_istable(L, 4)){
3586 while(lua_next(L, table) != 0){
3587 // key at index -2 and value at index -1
3588 luaL_checktype(L, -1, LUA_TSTRING);
3589 ndef->getIds(lua_tostring(L, -1), filter);
3590 // removes value, keeps key for next iteration
3593 } else if(lua_isstring(L, 4)){
3594 ndef->getIds(lua_tostring(L, 4), filter);
3597 // Get the table insert function
3598 lua_getglobal(L, "table");
3599 lua_getfield(L, -1, "insert");
3600 int table_insert = lua_gettop(L);
3603 int table = lua_gettop(L);
3604 for(s16 x=minp.X; x<=maxp.X; x++)
3605 for(s16 y=minp.Y; y<=maxp.Y; y++)
3606 for(s16 z=minp.Z; z<=maxp.Z; z++)
3609 content_t c = env->getMap().getNodeNoEx(p).getContent();
3610 if(filter.count(c) != 0){
3611 lua_pushvalue(L, table_insert);
3612 lua_pushvalue(L, table);
3614 if(lua_pcall(L, 2, 0, 0))
3615 script_error(L, "error: %s", lua_tostring(L, -1));
3621 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3622 // returns world-specific PerlinNoise
3623 static int l_get_perlin(lua_State *L)
3625 EnvRef *o = checkobject(L, 1);
3626 ServerEnvironment *env = o->m_env;
3627 if(env == NULL) return 0;
3629 int seeddiff = luaL_checkint(L, 2);
3630 int octaves = luaL_checkint(L, 3);
3631 double persistence = luaL_checknumber(L, 4);
3632 double scale = luaL_checknumber(L, 5);
3634 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3635 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3636 luaL_getmetatable(L, "PerlinNoise");
3637 lua_setmetatable(L, -2);
3642 EnvRef(ServerEnvironment *env):
3645 //infostream<<"EnvRef created"<<std::endl;
3650 //infostream<<"EnvRef destructing"<<std::endl;
3653 // Creates an EnvRef and leaves it on top of stack
3654 // Not callable from Lua; all references are created on the C side.
3655 static void create(lua_State *L, ServerEnvironment *env)
3657 EnvRef *o = new EnvRef(env);
3658 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3659 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3660 luaL_getmetatable(L, className);
3661 lua_setmetatable(L, -2);
3664 static void set_null(lua_State *L)
3666 EnvRef *o = checkobject(L, -1);
3670 static void Register(lua_State *L)
3673 int methodtable = lua_gettop(L);
3674 luaL_newmetatable(L, className);
3675 int metatable = lua_gettop(L);
3677 lua_pushliteral(L, "__metatable");
3678 lua_pushvalue(L, methodtable);
3679 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3681 lua_pushliteral(L, "__index");
3682 lua_pushvalue(L, methodtable);
3683 lua_settable(L, metatable);
3685 lua_pushliteral(L, "__gc");
3686 lua_pushcfunction(L, gc_object);
3687 lua_settable(L, metatable);
3689 lua_pop(L, 1); // drop metatable
3691 luaL_openlib(L, 0, methods, 0); // fill methodtable
3692 lua_pop(L, 1); // drop methodtable
3694 // Cannot be created from Lua
3695 //lua_register(L, className, create_object);
3698 const char EnvRef::className[] = "EnvRef";
3699 const luaL_reg EnvRef::methods[] = {
3700 method(EnvRef, set_node),
3701 method(EnvRef, add_node),
3702 method(EnvRef, remove_node),
3703 method(EnvRef, get_node),
3704 method(EnvRef, get_node_or_nil),
3705 method(EnvRef, get_node_light),
3706 method(EnvRef, place_node),
3707 method(EnvRef, dig_node),
3708 method(EnvRef, punch_node),
3709 method(EnvRef, add_entity),
3710 method(EnvRef, add_item),
3711 method(EnvRef, add_rat),
3712 method(EnvRef, add_firefly),
3713 method(EnvRef, get_meta),
3714 method(EnvRef, get_player_by_name),
3715 method(EnvRef, get_objects_inside_radius),
3716 method(EnvRef, set_timeofday),
3717 method(EnvRef, get_timeofday),
3718 method(EnvRef, find_node_near),
3719 method(EnvRef, find_nodes_in_area),
3720 method(EnvRef, get_perlin),
3729 class LuaPseudoRandom
3732 PseudoRandom m_pseudo;
3734 static const char className[];
3735 static const luaL_reg methods[];
3737 // Exported functions
3739 // garbage collector
3740 static int gc_object(lua_State *L)
3742 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3747 // next(self, min=0, max=32767) -> get next value
3748 static int l_next(lua_State *L)
3750 LuaPseudoRandom *o = checkobject(L, 1);
3753 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3754 if(!lua_isnil(L, 2))
3755 min = luaL_checkinteger(L, 2);
3756 if(!lua_isnil(L, 3))
3757 max = luaL_checkinteger(L, 3);
3758 if(max - min != 32767 && max - min > 32767/5)
3759 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.");
3760 PseudoRandom &pseudo = o->m_pseudo;
3761 int val = pseudo.next();
3762 val = (val % (max-min+1)) + min;
3763 lua_pushinteger(L, val);
3768 LuaPseudoRandom(int seed):
3777 const PseudoRandom& getItem() const
3781 PseudoRandom& getItem()
3786 // LuaPseudoRandom(seed)
3787 // Creates an LuaPseudoRandom and leaves it on top of stack
3788 static int create_object(lua_State *L)
3790 int seed = luaL_checknumber(L, 1);
3791 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3792 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3793 luaL_getmetatable(L, className);
3794 lua_setmetatable(L, -2);
3798 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3800 luaL_checktype(L, narg, LUA_TUSERDATA);
3801 void *ud = luaL_checkudata(L, narg, className);
3802 if(!ud) luaL_typerror(L, narg, className);
3803 return *(LuaPseudoRandom**)ud; // unbox pointer
3806 static void Register(lua_State *L)
3809 int methodtable = lua_gettop(L);
3810 luaL_newmetatable(L, className);
3811 int metatable = lua_gettop(L);
3813 lua_pushliteral(L, "__metatable");
3814 lua_pushvalue(L, methodtable);
3815 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3817 lua_pushliteral(L, "__index");
3818 lua_pushvalue(L, methodtable);
3819 lua_settable(L, metatable);
3821 lua_pushliteral(L, "__gc");
3822 lua_pushcfunction(L, gc_object);
3823 lua_settable(L, metatable);
3825 lua_pop(L, 1); // drop metatable
3827 luaL_openlib(L, 0, methods, 0); // fill methodtable
3828 lua_pop(L, 1); // drop methodtable
3830 // Can be created from Lua (LuaPseudoRandom(seed))
3831 lua_register(L, className, create_object);
3834 const char LuaPseudoRandom::className[] = "PseudoRandom";
3835 const luaL_reg LuaPseudoRandom::methods[] = {
3836 method(LuaPseudoRandom, next),
3846 class LuaABM : public ActiveBlockModifier
3852 std::set<std::string> m_trigger_contents;
3853 std::set<std::string> m_required_neighbors;
3854 float m_trigger_interval;
3855 u32 m_trigger_chance;
3857 LuaABM(lua_State *L, int id,
3858 const std::set<std::string> &trigger_contents,
3859 const std::set<std::string> &required_neighbors,
3860 float trigger_interval, u32 trigger_chance):
3863 m_trigger_contents(trigger_contents),
3864 m_required_neighbors(required_neighbors),
3865 m_trigger_interval(trigger_interval),
3866 m_trigger_chance(trigger_chance)
3869 virtual std::set<std::string> getTriggerContents()
3871 return m_trigger_contents;
3873 virtual std::set<std::string> getRequiredNeighbors()
3875 return m_required_neighbors;
3877 virtual float getTriggerInterval()
3879 return m_trigger_interval;
3881 virtual u32 getTriggerChance()
3883 return m_trigger_chance;
3885 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3886 u32 active_object_count, u32 active_object_count_wider)
3888 lua_State *L = m_lua;
3891 assert(lua_checkstack(L, 20));
3892 StackUnroller stack_unroller(L);
3894 // Get minetest.registered_abms
3895 lua_getglobal(L, "minetest");
3896 lua_getfield(L, -1, "registered_abms");
3897 luaL_checktype(L, -1, LUA_TTABLE);
3898 int registered_abms = lua_gettop(L);
3900 // Get minetest.registered_abms[m_id]
3901 lua_pushnumber(L, m_id);
3902 lua_gettable(L, registered_abms);
3903 if(lua_isnil(L, -1))
3907 luaL_checktype(L, -1, LUA_TTABLE);
3908 lua_getfield(L, -1, "action");
3909 luaL_checktype(L, -1, LUA_TFUNCTION);
3911 pushnode(L, n, env->getGameDef()->ndef());
3912 lua_pushnumber(L, active_object_count);
3913 lua_pushnumber(L, active_object_count_wider);
3914 if(lua_pcall(L, 4, 0, 0))
3915 script_error(L, "error: %s", lua_tostring(L, -1));
3923 static void read_server_sound_params(lua_State *L, int index,
3924 ServerSoundParams ¶ms)
3927 index = lua_gettop(L) + 1 + index;
3929 params = ServerSoundParams();
3930 if(lua_istable(L, index)){
3931 getfloatfield(L, index, "gain", params.gain);
3932 getstringfield(L, index, "to_player", params.to_player);
3933 lua_getfield(L, index, "pos");
3934 if(!lua_isnil(L, -1)){
3935 v3f p = read_v3f(L, -1)*BS;
3937 params.type = ServerSoundParams::SSP_POSITIONAL;
3940 lua_getfield(L, index, "object");
3941 if(!lua_isnil(L, -1)){
3942 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3943 ServerActiveObject *sao = ObjectRef::getobject(ref);
3945 params.object = sao->getId();
3946 params.type = ServerSoundParams::SSP_OBJECT;
3950 params.max_hear_distance = BS*getfloatfield_default(L, index,
3951 "max_hear_distance", params.max_hear_distance/BS);
3952 getboolfield(L, index, "loop", params.loop);
3961 // Writes a line to dstream
3962 static int l_debug(lua_State *L)
3964 std::string text = lua_tostring(L, 1);
3965 dstream << text << std::endl;
3969 // log([level,] text)
3970 // Writes a line to the logger.
3971 // The one-argument version logs to infostream.
3972 // The two-argument version accept a log level: error, action, info, or verbose.
3973 static int l_log(lua_State *L)
3976 LogMessageLevel level = LMT_INFO;
3977 if(lua_isnone(L, 2))
3979 text = lua_tostring(L, 1);
3983 std::string levelname = lua_tostring(L, 1);
3984 text = lua_tostring(L, 2);
3985 if(levelname == "error")
3987 else if(levelname == "action")
3989 else if(levelname == "verbose")
3990 level = LMT_VERBOSE;
3992 log_printline(level, text);
3996 // register_item_raw({lots of stuff})
3997 static int l_register_item_raw(lua_State *L)
3999 luaL_checktype(L, 1, LUA_TTABLE);
4002 // Get the writable item and node definition managers from the server
4003 IWritableItemDefManager *idef =
4004 get_server(L)->getWritableItemDefManager();
4005 IWritableNodeDefManager *ndef =
4006 get_server(L)->getWritableNodeDefManager();
4008 // Check if name is defined
4010 lua_getfield(L, table, "name");
4011 if(lua_isstring(L, -1)){
4012 name = lua_tostring(L, -1);
4013 verbosestream<<"register_item_raw: "<<name<<std::endl;
4015 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4018 // Check if on_use is defined
4021 // Set a distinctive default value to check if this is set
4022 def.node_placement_prediction = "__default";
4024 // Read the item definition
4025 def = read_item_definition(L, table, def);
4027 // Default to having client-side placement prediction for nodes
4028 // ("" in item definition sets it off)
4029 if(def.node_placement_prediction == "__default"){
4030 if(def.type == ITEM_NODE)
4031 def.node_placement_prediction = name;
4033 def.node_placement_prediction = "";
4036 // Register item definition
4037 idef->registerItem(def);
4039 // Read the node definition (content features) and register it
4040 if(def.type == ITEM_NODE)
4042 ContentFeatures f = read_content_features(L, table);
4043 ndef->set(f.name, f);
4046 return 0; /* number of results */
4049 // register_alias_raw(name, convert_to_name)
4050 static int l_register_alias_raw(lua_State *L)
4052 std::string name = luaL_checkstring(L, 1);
4053 std::string convert_to = luaL_checkstring(L, 2);
4055 // Get the writable item definition manager from the server
4056 IWritableItemDefManager *idef =
4057 get_server(L)->getWritableItemDefManager();
4059 idef->registerAlias(name, convert_to);
4061 return 0; /* number of results */
4064 // helper for register_craft
4065 static bool read_craft_recipe_shaped(lua_State *L, int index,
4066 int &width, std::vector<std::string> &recipe)
4069 index = lua_gettop(L) + 1 + index;
4071 if(!lua_istable(L, index))
4076 while(lua_next(L, index) != 0){
4078 // key at index -2 and value at index -1
4079 if(!lua_istable(L, -1))
4081 int table2 = lua_gettop(L);
4083 while(lua_next(L, table2) != 0){
4084 // key at index -2 and value at index -1
4085 if(!lua_isstring(L, -1))
4087 recipe.push_back(lua_tostring(L, -1));
4088 // removes value, keeps key for next iteration
4095 if(colcount != width)
4098 // removes value, keeps key for next iteration
4105 // helper for register_craft
4106 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4107 std::vector<std::string> &recipe)
4110 index = lua_gettop(L) + 1 + index;
4112 if(!lua_istable(L, index))
4116 while(lua_next(L, index) != 0){
4117 // key at index -2 and value at index -1
4118 if(!lua_isstring(L, -1))
4120 recipe.push_back(lua_tostring(L, -1));
4121 // removes value, keeps key for next iteration
4127 // helper for register_craft
4128 static bool read_craft_replacements(lua_State *L, int index,
4129 CraftReplacements &replacements)
4132 index = lua_gettop(L) + 1 + index;
4134 if(!lua_istable(L, index))
4138 while(lua_next(L, index) != 0){
4139 // key at index -2 and value at index -1
4140 if(!lua_istable(L, -1))
4142 lua_rawgeti(L, -1, 1);
4143 if(!lua_isstring(L, -1))
4145 std::string replace_from = lua_tostring(L, -1);
4147 lua_rawgeti(L, -1, 2);
4148 if(!lua_isstring(L, -1))
4150 std::string replace_to = lua_tostring(L, -1);
4152 replacements.pairs.push_back(
4153 std::make_pair(replace_from, replace_to));
4154 // removes value, keeps key for next iteration
4159 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4160 static int l_register_craft(lua_State *L)
4162 //infostream<<"register_craft"<<std::endl;
4163 luaL_checktype(L, 1, LUA_TTABLE);
4166 // Get the writable craft definition manager from the server
4167 IWritableCraftDefManager *craftdef =
4168 get_server(L)->getWritableCraftDefManager();
4170 std::string type = getstringfield_default(L, table, "type", "shaped");
4173 CraftDefinitionShaped
4175 if(type == "shaped"){
4176 std::string output = getstringfield_default(L, table, "output", "");
4178 throw LuaError(L, "Crafting definition is missing an output");
4181 std::vector<std::string> recipe;
4182 lua_getfield(L, table, "recipe");
4183 if(lua_isnil(L, -1))
4184 throw LuaError(L, "Crafting definition is missing a recipe"
4185 " (output=\"" + output + "\")");
4186 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4187 throw LuaError(L, "Invalid crafting recipe"
4188 " (output=\"" + output + "\")");
4190 CraftReplacements replacements;
4191 lua_getfield(L, table, "replacements");
4192 if(!lua_isnil(L, -1))
4194 if(!read_craft_replacements(L, -1, replacements))
4195 throw LuaError(L, "Invalid replacements"
4196 " (output=\"" + output + "\")");
4199 CraftDefinition *def = new CraftDefinitionShaped(
4200 output, width, recipe, replacements);
4201 craftdef->registerCraft(def);
4204 CraftDefinitionShapeless
4206 else if(type == "shapeless"){
4207 std::string output = getstringfield_default(L, table, "output", "");
4209 throw LuaError(L, "Crafting definition (shapeless)"
4210 " is missing an output");
4212 std::vector<std::string> recipe;
4213 lua_getfield(L, table, "recipe");
4214 if(lua_isnil(L, -1))
4215 throw LuaError(L, "Crafting definition (shapeless)"
4216 " is missing a recipe"
4217 " (output=\"" + output + "\")");
4218 if(!read_craft_recipe_shapeless(L, -1, recipe))
4219 throw LuaError(L, "Invalid crafting recipe"
4220 " (output=\"" + output + "\")");
4222 CraftReplacements replacements;
4223 lua_getfield(L, table, "replacements");
4224 if(!lua_isnil(L, -1))
4226 if(!read_craft_replacements(L, -1, replacements))
4227 throw LuaError(L, "Invalid replacements"
4228 " (output=\"" + output + "\")");
4231 CraftDefinition *def = new CraftDefinitionShapeless(
4232 output, recipe, replacements);
4233 craftdef->registerCraft(def);
4236 CraftDefinitionToolRepair
4238 else if(type == "toolrepair"){
4239 float additional_wear = getfloatfield_default(L, table,
4240 "additional_wear", 0.0);
4242 CraftDefinition *def = new CraftDefinitionToolRepair(
4244 craftdef->registerCraft(def);
4247 CraftDefinitionCooking
4249 else if(type == "cooking"){
4250 std::string output = getstringfield_default(L, table, "output", "");
4252 throw LuaError(L, "Crafting definition (cooking)"
4253 " is missing an output");
4255 std::string recipe = getstringfield_default(L, table, "recipe", "");
4257 throw LuaError(L, "Crafting definition (cooking)"
4258 " is missing a recipe"
4259 " (output=\"" + output + "\")");
4261 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4263 CraftReplacements replacements;
4264 lua_getfield(L, table, "replacements");
4265 if(!lua_isnil(L, -1))
4267 if(!read_craft_replacements(L, -1, replacements))
4268 throw LuaError(L, "Invalid replacements"
4269 " (cooking output=\"" + output + "\")");
4272 CraftDefinition *def = new CraftDefinitionCooking(
4273 output, recipe, cooktime, replacements);
4274 craftdef->registerCraft(def);
4279 else if(type == "fuel"){
4280 std::string recipe = getstringfield_default(L, table, "recipe", "");
4282 throw LuaError(L, "Crafting definition (fuel)"
4283 " is missing a recipe");
4285 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4287 CraftReplacements replacements;
4288 lua_getfield(L, table, "replacements");
4289 if(!lua_isnil(L, -1))
4291 if(!read_craft_replacements(L, -1, replacements))
4292 throw LuaError(L, "Invalid replacements"
4293 " (fuel recipe=\"" + recipe + "\")");
4296 CraftDefinition *def = new CraftDefinitionFuel(
4297 recipe, burntime, replacements);
4298 craftdef->registerCraft(def);
4302 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4306 return 0; /* number of results */
4309 // setting_set(name, value)
4310 static int l_setting_set(lua_State *L)
4312 const char *name = luaL_checkstring(L, 1);
4313 const char *value = luaL_checkstring(L, 2);
4314 g_settings->set(name, value);
4318 // setting_get(name)
4319 static int l_setting_get(lua_State *L)
4321 const char *name = luaL_checkstring(L, 1);
4323 std::string value = g_settings->get(name);
4324 lua_pushstring(L, value.c_str());
4325 } catch(SettingNotFoundException &e){
4331 // setting_getbool(name)
4332 static int l_setting_getbool(lua_State *L)
4334 const char *name = luaL_checkstring(L, 1);
4336 bool value = g_settings->getBool(name);
4337 lua_pushboolean(L, value);
4338 } catch(SettingNotFoundException &e){
4344 // chat_send_all(text)
4345 static int l_chat_send_all(lua_State *L)
4347 const char *text = luaL_checkstring(L, 1);
4348 // Get server from registry
4349 Server *server = get_server(L);
4351 server->notifyPlayers(narrow_to_wide(text));
4355 // chat_send_player(name, text)
4356 static int l_chat_send_player(lua_State *L)
4358 const char *name = luaL_checkstring(L, 1);
4359 const char *text = luaL_checkstring(L, 2);
4360 // Get server from registry
4361 Server *server = get_server(L);
4363 server->notifyPlayer(name, narrow_to_wide(text));
4367 // get_player_privs(name, text)
4368 static int l_get_player_privs(lua_State *L)
4370 const char *name = luaL_checkstring(L, 1);
4371 // Get server from registry
4372 Server *server = get_server(L);
4375 int table = lua_gettop(L);
4376 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4377 for(std::set<std::string>::const_iterator
4378 i = privs_s.begin(); i != privs_s.end(); i++){
4379 lua_pushboolean(L, true);
4380 lua_setfield(L, table, i->c_str());
4382 lua_pushvalue(L, table);
4386 // get_inventory(location)
4387 static int l_get_inventory(lua_State *L)
4389 InventoryLocation loc;
4391 std::string type = checkstringfield(L, 1, "type");
4392 if(type == "player"){
4393 std::string name = checkstringfield(L, 1, "name");
4394 loc.setPlayer(name);
4395 } else if(type == "node"){
4396 lua_getfield(L, 1, "pos");
4397 v3s16 pos = check_v3s16(L, -1);
4398 loc.setNodeMeta(pos);
4401 if(get_server(L)->getInventory(loc) != NULL)
4402 InvRef::create(L, loc);
4408 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4409 static int l_get_dig_params(lua_State *L)
4411 std::map<std::string, int> groups;
4412 read_groups(L, 1, groups);
4413 ToolCapabilities tp = read_tool_capabilities(L, 2);
4414 if(lua_isnoneornil(L, 3))
4415 push_dig_params(L, getDigParams(groups, &tp));
4417 push_dig_params(L, getDigParams(groups, &tp,
4418 luaL_checknumber(L, 3)));
4422 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4423 static int l_get_hit_params(lua_State *L)
4425 std::map<std::string, int> groups;
4426 read_groups(L, 1, groups);
4427 ToolCapabilities tp = read_tool_capabilities(L, 2);
4428 if(lua_isnoneornil(L, 3))
4429 push_hit_params(L, getHitParams(groups, &tp));
4431 push_hit_params(L, getHitParams(groups, &tp,
4432 luaL_checknumber(L, 3)));
4436 // get_current_modname()
4437 static int l_get_current_modname(lua_State *L)
4439 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4443 // get_modpath(modname)
4444 static int l_get_modpath(lua_State *L)
4446 std::string modname = luaL_checkstring(L, 1);
4448 if(modname == "__builtin"){
4449 std::string path = get_server(L)->getBuiltinLuaPath();
4450 lua_pushstring(L, path.c_str());
4453 const ModSpec *mod = get_server(L)->getModSpec(modname);
4458 lua_pushstring(L, mod->path.c_str());
4463 static int l_get_worldpath(lua_State *L)
4465 std::string worldpath = get_server(L)->getWorldPath();
4466 lua_pushstring(L, worldpath.c_str());
4470 // sound_play(spec, parameters)
4471 static int l_sound_play(lua_State *L)
4473 SimpleSoundSpec spec;
4474 read_soundspec(L, 1, spec);
4475 ServerSoundParams params;
4476 read_server_sound_params(L, 2, params);
4477 s32 handle = get_server(L)->playSound(spec, params);
4478 lua_pushinteger(L, handle);
4482 // sound_stop(handle)
4483 static int l_sound_stop(lua_State *L)
4485 int handle = luaL_checkinteger(L, 1);
4486 get_server(L)->stopSound(handle);
4490 // is_singleplayer()
4491 static int l_is_singleplayer(lua_State *L)
4493 lua_pushboolean(L, get_server(L)->isSingleplayer());
4497 // get_password_hash(name, raw_password)
4498 static int l_get_password_hash(lua_State *L)
4500 std::string name = luaL_checkstring(L, 1);
4501 std::string raw_password = luaL_checkstring(L, 2);
4502 std::string hash = translatePassword(name,
4503 narrow_to_wide(raw_password));
4504 lua_pushstring(L, hash.c_str());
4508 // notify_authentication_modified(name)
4509 static int l_notify_authentication_modified(lua_State *L)
4511 std::string name = "";
4512 if(lua_isstring(L, 1))
4513 name = lua_tostring(L, 1);
4514 get_server(L)->reportPrivsModified(name);
4518 // get_craft_result(input)
4519 static int l_get_craft_result(lua_State *L)
4522 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4523 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4524 es_CraftMethod, CRAFT_METHOD_NORMAL);
4526 lua_getfield(L, input_i, "width");
4527 if(lua_isnumber(L, -1))
4528 width = luaL_checkinteger(L, -1);
4530 lua_getfield(L, input_i, "items");
4531 std::vector<ItemStack> items = read_items(L, -1);
4532 lua_pop(L, 1); // items
4534 IGameDef *gdef = get_server(L);
4535 ICraftDefManager *cdef = gdef->cdef();
4536 CraftInput input(method, width, items);
4538 bool got = cdef->getCraftResult(input, output, true, gdef);
4539 lua_newtable(L); // output table
4542 item.deSerialize(output.item, gdef->idef());
4543 LuaItemStack::create(L, item);
4544 lua_setfield(L, -2, "item");
4545 setintfield(L, -1, "time", output.time);
4547 LuaItemStack::create(L, ItemStack());
4548 lua_setfield(L, -2, "item");
4549 setintfield(L, -1, "time", 0);
4551 lua_newtable(L); // decremented input table
4552 lua_pushstring(L, method_s.c_str());
4553 lua_setfield(L, -2, "method");
4554 lua_pushinteger(L, width);
4555 lua_setfield(L, -2, "width");
4556 push_items(L, input.items);
4557 lua_setfield(L, -2, "items");
4561 static const struct luaL_Reg minetest_f [] = {
4564 {"register_item_raw", l_register_item_raw},
4565 {"register_alias_raw", l_register_alias_raw},
4566 {"register_craft", l_register_craft},
4567 {"setting_set", l_setting_set},
4568 {"setting_get", l_setting_get},
4569 {"setting_getbool", l_setting_getbool},
4570 {"chat_send_all", l_chat_send_all},
4571 {"chat_send_player", l_chat_send_player},
4572 {"get_player_privs", l_get_player_privs},
4573 {"get_inventory", l_get_inventory},
4574 {"get_dig_params", l_get_dig_params},
4575 {"get_hit_params", l_get_hit_params},
4576 {"get_current_modname", l_get_current_modname},
4577 {"get_modpath", l_get_modpath},
4578 {"get_worldpath", l_get_worldpath},
4579 {"sound_play", l_sound_play},
4580 {"sound_stop", l_sound_stop},
4581 {"is_singleplayer", l_is_singleplayer},
4582 {"get_password_hash", l_get_password_hash},
4583 {"notify_authentication_modified", l_notify_authentication_modified},
4584 {"get_craft_result", l_get_craft_result},
4589 Main export function
4592 void scriptapi_export(lua_State *L, Server *server)
4595 assert(lua_checkstack(L, 20));
4596 verbosestream<<"scriptapi_export()"<<std::endl;
4597 StackUnroller stack_unroller(L);
4599 // Store server as light userdata in registry
4600 lua_pushlightuserdata(L, server);
4601 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4603 // Register global functions in table minetest
4605 luaL_register(L, NULL, minetest_f);
4606 lua_setglobal(L, "minetest");
4608 // Get the main minetest table
4609 lua_getglobal(L, "minetest");
4611 // Add tables to minetest
4613 lua_setfield(L, -2, "object_refs");
4615 lua_setfield(L, -2, "luaentities");
4617 // Register wrappers
4618 LuaItemStack::Register(L);
4619 InvRef::Register(L);
4620 NodeMetaRef::Register(L);
4621 ObjectRef::Register(L);
4622 EnvRef::Register(L);
4623 LuaPseudoRandom::Register(L);
4624 LuaPerlinNoise::Register(L);
4627 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4628 const std::string &modname)
4630 ModNameStorer modnamestorer(L, modname);
4632 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4634 errorstream<<"Error loading mod \""<<modname
4635 <<"\": modname does not follow naming conventions: "
4636 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4640 bool success = false;
4643 success = script_load(L, scriptpath.c_str());
4646 errorstream<<"Error loading mod \""<<modname
4647 <<"\": "<<e.what()<<std::endl;
4653 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4656 assert(lua_checkstack(L, 20));
4657 verbosestream<<"scriptapi_add_environment"<<std::endl;
4658 StackUnroller stack_unroller(L);
4660 // Create EnvRef on stack
4661 EnvRef::create(L, env);
4662 int envref = lua_gettop(L);
4664 // minetest.env = envref
4665 lua_getglobal(L, "minetest");
4666 luaL_checktype(L, -1, LUA_TTABLE);
4667 lua_pushvalue(L, envref);
4668 lua_setfield(L, -2, "env");
4670 // Store environment as light userdata in registry
4671 lua_pushlightuserdata(L, env);
4672 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4675 Add ActiveBlockModifiers to environment
4678 // Get minetest.registered_abms
4679 lua_getglobal(L, "minetest");
4680 lua_getfield(L, -1, "registered_abms");
4681 luaL_checktype(L, -1, LUA_TTABLE);
4682 int registered_abms = lua_gettop(L);
4684 if(lua_istable(L, registered_abms)){
4685 int table = lua_gettop(L);
4687 while(lua_next(L, table) != 0){
4688 // key at index -2 and value at index -1
4689 int id = lua_tonumber(L, -2);
4690 int current_abm = lua_gettop(L);
4692 std::set<std::string> trigger_contents;
4693 lua_getfield(L, current_abm, "nodenames");
4694 if(lua_istable(L, -1)){
4695 int table = lua_gettop(L);
4697 while(lua_next(L, table) != 0){
4698 // key at index -2 and value at index -1
4699 luaL_checktype(L, -1, LUA_TSTRING);
4700 trigger_contents.insert(lua_tostring(L, -1));
4701 // removes value, keeps key for next iteration
4704 } else if(lua_isstring(L, -1)){
4705 trigger_contents.insert(lua_tostring(L, -1));
4709 std::set<std::string> required_neighbors;
4710 lua_getfield(L, current_abm, "neighbors");
4711 if(lua_istable(L, -1)){
4712 int table = lua_gettop(L);
4714 while(lua_next(L, table) != 0){
4715 // key at index -2 and value at index -1
4716 luaL_checktype(L, -1, LUA_TSTRING);
4717 required_neighbors.insert(lua_tostring(L, -1));
4718 // removes value, keeps key for next iteration
4721 } else if(lua_isstring(L, -1)){
4722 required_neighbors.insert(lua_tostring(L, -1));
4726 float trigger_interval = 10.0;
4727 getfloatfield(L, current_abm, "interval", trigger_interval);
4729 int trigger_chance = 50;
4730 getintfield(L, current_abm, "chance", trigger_chance);
4732 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4733 required_neighbors, trigger_interval, trigger_chance);
4735 env->addActiveBlockModifier(abm);
4737 // removes value, keeps key for next iteration
4745 // Dump stack top with the dump2 function
4746 static void dump2(lua_State *L, const char *name)
4748 // Dump object (debug)
4749 lua_getglobal(L, "dump2");
4750 luaL_checktype(L, -1, LUA_TFUNCTION);
4751 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4752 lua_pushstring(L, name);
4753 if(lua_pcall(L, 2, 0, 0))
4754 script_error(L, "error: %s", lua_tostring(L, -1));
4762 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4765 assert(lua_checkstack(L, 20));
4766 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4767 StackUnroller stack_unroller(L);
4769 // Create object on stack
4770 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4771 int object = lua_gettop(L);
4773 // Get minetest.object_refs table
4774 lua_getglobal(L, "minetest");
4775 lua_getfield(L, -1, "object_refs");
4776 luaL_checktype(L, -1, LUA_TTABLE);
4777 int objectstable = lua_gettop(L);
4779 // object_refs[id] = object
4780 lua_pushnumber(L, cobj->getId()); // Push id
4781 lua_pushvalue(L, object); // Copy object to top of stack
4782 lua_settable(L, objectstable);
4785 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4788 assert(lua_checkstack(L, 20));
4789 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4790 StackUnroller stack_unroller(L);
4792 // Get minetest.object_refs table
4793 lua_getglobal(L, "minetest");
4794 lua_getfield(L, -1, "object_refs");
4795 luaL_checktype(L, -1, LUA_TTABLE);
4796 int objectstable = lua_gettop(L);
4798 // Get object_refs[id]
4799 lua_pushnumber(L, cobj->getId()); // Push id
4800 lua_gettable(L, objectstable);
4801 // Set object reference to NULL
4802 ObjectRef::set_null(L);
4803 lua_pop(L, 1); // pop object
4805 // Set object_refs[id] = nil
4806 lua_pushnumber(L, cobj->getId()); // Push id
4808 lua_settable(L, objectstable);
4815 // What scriptapi_run_callbacks does with the return values of callbacks.
4816 // Regardless of the mode, if only one callback is defined,
4817 // its return value is the total return value.
4818 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4819 enum RunCallbacksMode
4821 // Returns the return value of the first callback
4822 // Returns nil if list of callbacks is empty
4823 RUN_CALLBACKS_MODE_FIRST,
4824 // Returns the return value of the last callback
4825 // Returns nil if list of callbacks is empty
4826 RUN_CALLBACKS_MODE_LAST,
4827 // If any callback returns a false value, the first such is returned
4828 // Otherwise, the first callback's return value (trueish) is returned
4829 // Returns true if list of callbacks is empty
4830 RUN_CALLBACKS_MODE_AND,
4831 // Like above, but stops calling callbacks (short circuit)
4832 // after seeing the first false value
4833 RUN_CALLBACKS_MODE_AND_SC,
4834 // If any callback returns a true value, the first such is returned
4835 // Otherwise, the first callback's return value (falseish) is returned
4836 // Returns false if list of callbacks is empty
4837 RUN_CALLBACKS_MODE_OR,
4838 // Like above, but stops calling callbacks (short circuit)
4839 // after seeing the first true value
4840 RUN_CALLBACKS_MODE_OR_SC,
4841 // Note: "a true value" and "a false value" refer to values that
4842 // are converted by lua_toboolean to true or false, respectively.
4845 // Push the list of callbacks (a lua table).
4846 // Then push nargs arguments.
4847 // Then call this function, which
4848 // - runs the callbacks
4849 // - removes the table and arguments from the lua stack
4850 // - pushes the return value, computed depending on mode
4851 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4852 RunCallbacksMode mode)
4854 // Insert the return value into the lua stack, below the table
4855 assert(lua_gettop(L) >= nargs + 1);
4857 lua_insert(L, -(nargs + 1) - 1);
4858 // Stack now looks like this:
4859 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4861 int rv = lua_gettop(L) - nargs - 1;
4863 int arg = table + 1;
4865 luaL_checktype(L, table, LUA_TTABLE);
4869 bool first_loop = true;
4870 while(lua_next(L, table) != 0){
4871 // key at index -2 and value at index -1
4872 luaL_checktype(L, -1, LUA_TFUNCTION);
4874 for(int i = 0; i < nargs; i++)
4875 lua_pushvalue(L, arg+i);
4876 if(lua_pcall(L, nargs, 1, 0))
4877 script_error(L, "error: %s", lua_tostring(L, -1));
4879 // Move return value to designated space in stack
4882 // Result of first callback is always moved
4886 // Otherwise, what happens depends on the mode
4887 if(mode == RUN_CALLBACKS_MODE_FIRST)
4889 else if(mode == RUN_CALLBACKS_MODE_LAST)
4891 else if(mode == RUN_CALLBACKS_MODE_AND ||
4892 mode == RUN_CALLBACKS_MODE_AND_SC){
4893 if(lua_toboolean(L, rv) == true &&
4894 lua_toboolean(L, -1) == false)
4899 else if(mode == RUN_CALLBACKS_MODE_OR ||
4900 mode == RUN_CALLBACKS_MODE_OR_SC){
4901 if(lua_toboolean(L, rv) == false &&
4902 lua_toboolean(L, -1) == true)
4911 // Handle short circuit modes
4912 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4913 lua_toboolean(L, rv) == false)
4915 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4916 lua_toboolean(L, rv) == true)
4919 // value removed, keep key for next iteration
4922 // Remove stuff from stack, leaving only the return value
4925 // Fix return value in case no callbacks were called
4927 if(mode == RUN_CALLBACKS_MODE_AND ||
4928 mode == RUN_CALLBACKS_MODE_AND_SC){
4930 lua_pushboolean(L, true);
4932 else if(mode == RUN_CALLBACKS_MODE_OR ||
4933 mode == RUN_CALLBACKS_MODE_OR_SC){
4935 lua_pushboolean(L, false);
4940 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4941 const std::string &message)
4944 assert(lua_checkstack(L, 20));
4945 StackUnroller stack_unroller(L);
4947 // Get minetest.registered_on_chat_messages
4948 lua_getglobal(L, "minetest");
4949 lua_getfield(L, -1, "registered_on_chat_messages");
4951 lua_pushstring(L, name.c_str());
4952 lua_pushstring(L, message.c_str());
4953 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4954 bool ate = lua_toboolean(L, -1);
4958 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4961 assert(lua_checkstack(L, 20));
4962 StackUnroller stack_unroller(L);
4964 // Get minetest.registered_on_newplayers
4965 lua_getglobal(L, "minetest");
4966 lua_getfield(L, -1, "registered_on_newplayers");
4968 objectref_get_or_create(L, player);
4969 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4972 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4975 assert(lua_checkstack(L, 20));
4976 StackUnroller stack_unroller(L);
4978 // Get minetest.registered_on_dieplayers
4979 lua_getglobal(L, "minetest");
4980 lua_getfield(L, -1, "registered_on_dieplayers");
4982 objectref_get_or_create(L, player);
4983 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4986 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4989 assert(lua_checkstack(L, 20));
4990 StackUnroller stack_unroller(L);
4992 // Get minetest.registered_on_respawnplayers
4993 lua_getglobal(L, "minetest");
4994 lua_getfield(L, -1, "registered_on_respawnplayers");
4996 objectref_get_or_create(L, player);
4997 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4998 bool positioning_handled_by_some = lua_toboolean(L, -1);
4999 return positioning_handled_by_some;
5002 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
5005 assert(lua_checkstack(L, 20));
5006 StackUnroller stack_unroller(L);
5008 // Get minetest.registered_on_joinplayers
5009 lua_getglobal(L, "minetest");
5010 lua_getfield(L, -1, "registered_on_joinplayers");
5012 objectref_get_or_create(L, player);
5013 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5016 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
5019 assert(lua_checkstack(L, 20));
5020 StackUnroller stack_unroller(L);
5022 // Get minetest.registered_on_leaveplayers
5023 lua_getglobal(L, "minetest");
5024 lua_getfield(L, -1, "registered_on_leaveplayers");
5026 objectref_get_or_create(L, player);
5027 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5030 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
5033 assert(lua_checkstack(L, 20));
5034 StackUnroller stack_unroller(L);
5036 Inventory *inv = player->getInventory();
5039 lua_getglobal(L, "minetest");
5040 lua_getfield(L, -1, "creative_inventory");
5041 luaL_checktype(L, -1, LUA_TTABLE);
5042 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
5045 static void get_auth_handler(lua_State *L)
5047 lua_getglobal(L, "minetest");
5048 lua_getfield(L, -1, "registered_auth_handler");
5049 if(lua_isnil(L, -1)){
5051 lua_getfield(L, -1, "builtin_auth_handler");
5053 if(lua_type(L, -1) != LUA_TTABLE)
5054 throw LuaError(L, "Authentication handler table not valid");
5057 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
5058 std::string *dst_password, std::set<std::string> *dst_privs)
5061 assert(lua_checkstack(L, 20));
5062 StackUnroller stack_unroller(L);
5064 get_auth_handler(L);
5065 lua_getfield(L, -1, "get_auth");
5066 if(lua_type(L, -1) != LUA_TFUNCTION)
5067 throw LuaError(L, "Authentication handler missing get_auth");
5068 lua_pushstring(L, playername.c_str());
5069 if(lua_pcall(L, 1, 1, 0))
5070 script_error(L, "error: %s", lua_tostring(L, -1));
5072 // nil = login not allowed
5073 if(lua_isnil(L, -1))
5075 luaL_checktype(L, -1, LUA_TTABLE);
5077 std::string password;
5078 bool found = getstringfield(L, -1, "password", password);
5080 throw LuaError(L, "Authentication handler didn't return password");
5082 *dst_password = password;
5084 lua_getfield(L, -1, "privileges");
5085 if(!lua_istable(L, -1))
5087 "Authentication handler didn't return privilege table");
5089 read_privileges(L, -1, *dst_privs);
5095 void scriptapi_create_auth(lua_State *L, const std::string &playername,
5096 const std::string &password)
5099 assert(lua_checkstack(L, 20));
5100 StackUnroller stack_unroller(L);
5102 get_auth_handler(L);
5103 lua_getfield(L, -1, "create_auth");
5104 if(lua_type(L, -1) != LUA_TFUNCTION)
5105 throw LuaError(L, "Authentication handler missing create_auth");
5106 lua_pushstring(L, playername.c_str());
5107 lua_pushstring(L, password.c_str());
5108 if(lua_pcall(L, 2, 0, 0))
5109 script_error(L, "error: %s", lua_tostring(L, -1));
5112 bool scriptapi_set_password(lua_State *L, const std::string &playername,
5113 const std::string &password)
5116 assert(lua_checkstack(L, 20));
5117 StackUnroller stack_unroller(L);
5119 get_auth_handler(L);
5120 lua_getfield(L, -1, "set_password");
5121 if(lua_type(L, -1) != LUA_TFUNCTION)
5122 throw LuaError(L, "Authentication handler missing set_password");
5123 lua_pushstring(L, playername.c_str());
5124 lua_pushstring(L, password.c_str());
5125 if(lua_pcall(L, 2, 1, 0))
5126 script_error(L, "error: %s", lua_tostring(L, -1));
5127 return lua_toboolean(L, -1);
5131 item callbacks and node callbacks
5134 // Retrieves minetest.registered_items[name][callbackname]
5135 // If that is nil or on error, return false and stack is unchanged
5136 // If that is a function, returns true and pushes the
5137 // function onto the stack
5138 static bool get_item_callback(lua_State *L,
5139 const char *name, const char *callbackname)
5141 lua_getglobal(L, "minetest");
5142 lua_getfield(L, -1, "registered_items");
5144 luaL_checktype(L, -1, LUA_TTABLE);
5145 lua_getfield(L, -1, name);
5147 // Should be a table
5148 if(lua_type(L, -1) != LUA_TTABLE)
5150 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5154 lua_getfield(L, -1, callbackname);
5156 // Should be a function or nil
5157 if(lua_type(L, -1) == LUA_TFUNCTION)
5161 else if(lua_isnil(L, -1))
5168 errorstream<<"Item \""<<name<<"\" callback \""
5169 <<callbackname<<" is not a function"<<std::endl;
5175 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5176 ServerActiveObject *dropper, v3f pos)
5179 assert(lua_checkstack(L, 20));
5180 StackUnroller stack_unroller(L);
5182 // Push callback function on stack
5183 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5187 LuaItemStack::create(L, item);
5188 objectref_get_or_create(L, dropper);
5189 pushFloatPos(L, pos);
5190 if(lua_pcall(L, 3, 1, 0))
5191 script_error(L, "error: %s", lua_tostring(L, -1));
5192 if(!lua_isnil(L, -1))
5193 item = read_item(L, -1);
5197 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5198 ServerActiveObject *placer, const PointedThing &pointed)
5201 assert(lua_checkstack(L, 20));
5202 StackUnroller stack_unroller(L);
5204 // Push callback function on stack
5205 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5209 LuaItemStack::create(L, item);
5210 objectref_get_or_create(L, placer);
5211 push_pointed_thing(L, pointed);
5212 if(lua_pcall(L, 3, 1, 0))
5213 script_error(L, "error: %s", lua_tostring(L, -1));
5214 if(!lua_isnil(L, -1))
5215 item = read_item(L, -1);
5219 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5220 ServerActiveObject *user, const PointedThing &pointed)
5223 assert(lua_checkstack(L, 20));
5224 StackUnroller stack_unroller(L);
5226 // Push callback function on stack
5227 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5231 LuaItemStack::create(L, item);
5232 objectref_get_or_create(L, user);
5233 push_pointed_thing(L, pointed);
5234 if(lua_pcall(L, 3, 1, 0))
5235 script_error(L, "error: %s", lua_tostring(L, -1));
5236 if(!lua_isnil(L, -1))
5237 item = read_item(L, -1);
5241 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5242 ServerActiveObject *puncher)
5245 assert(lua_checkstack(L, 20));
5246 StackUnroller stack_unroller(L);
5248 INodeDefManager *ndef = get_server(L)->ndef();
5250 // Push callback function on stack
5251 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5256 pushnode(L, node, ndef);
5257 objectref_get_or_create(L, puncher);
5258 if(lua_pcall(L, 3, 0, 0))
5259 script_error(L, "error: %s", lua_tostring(L, -1));
5263 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5264 ServerActiveObject *digger)
5267 assert(lua_checkstack(L, 20));
5268 StackUnroller stack_unroller(L);
5270 INodeDefManager *ndef = get_server(L)->ndef();
5272 // Push callback function on stack
5273 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5278 pushnode(L, node, ndef);
5279 objectref_get_or_create(L, digger);
5280 if(lua_pcall(L, 3, 0, 0))
5281 script_error(L, "error: %s", lua_tostring(L, -1));
5285 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5288 assert(lua_checkstack(L, 20));
5289 StackUnroller stack_unroller(L);
5291 INodeDefManager *ndef = get_server(L)->ndef();
5293 // Push callback function on stack
5294 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5299 if(lua_pcall(L, 1, 0, 0))
5300 script_error(L, "error: %s", lua_tostring(L, -1));
5303 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5306 assert(lua_checkstack(L, 20));
5307 StackUnroller stack_unroller(L);
5309 INodeDefManager *ndef = get_server(L)->ndef();
5311 // Push callback function on stack
5312 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5317 if(lua_pcall(L, 1, 0, 0))
5318 script_error(L, "error: %s", lua_tostring(L, -1));
5321 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5324 assert(lua_checkstack(L, 20));
5325 StackUnroller stack_unroller(L);
5327 INodeDefManager *ndef = get_server(L)->ndef();
5329 // Push callback function on stack
5330 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5335 pushnode(L, node, ndef);
5336 if(lua_pcall(L, 2, 0, 0))
5337 script_error(L, "error: %s", lua_tostring(L, -1));
5340 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5341 const std::string &formname,
5342 const std::map<std::string, std::string> &fields,
5343 ServerActiveObject *sender)
5346 assert(lua_checkstack(L, 20));
5347 StackUnroller stack_unroller(L);
5349 INodeDefManager *ndef = get_server(L)->ndef();
5351 // If node doesn't exist, we don't know what callback to call
5352 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5353 if(node.getContent() == CONTENT_IGNORE)
5356 // Push callback function on stack
5357 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5364 lua_pushstring(L, formname.c_str());
5367 for(std::map<std::string, std::string>::const_iterator
5368 i = fields.begin(); i != fields.end(); i++){
5369 const std::string &name = i->first;
5370 const std::string &value = i->second;
5371 lua_pushstring(L, name.c_str());
5372 lua_pushlstring(L, value.c_str(), value.size());
5373 lua_settable(L, -3);
5376 objectref_get_or_create(L, sender);
5377 if(lua_pcall(L, 4, 0, 0))
5378 script_error(L, "error: %s", lua_tostring(L, -1));
5381 void scriptapi_node_on_metadata_inventory_move(lua_State *L, v3s16 p,
5382 const std::string &from_list, int from_index,
5383 const std::string &to_list, int to_index,
5384 int count, ServerActiveObject *player)
5387 assert(lua_checkstack(L, 20));
5388 StackUnroller stack_unroller(L);
5390 INodeDefManager *ndef = get_server(L)->ndef();
5392 // If node doesn't exist, we don't know what callback to call
5393 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5394 if(node.getContent() == CONTENT_IGNORE)
5397 // Push callback function on stack
5398 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5399 "on_metadata_inventory_move"))
5402 // function(pos, from_list, from_index, to_list, to_index, count, player)
5404 lua_pushstring(L, from_list.c_str());
5405 lua_pushinteger(L, from_index + 1);
5406 lua_pushstring(L, to_list.c_str());
5407 lua_pushinteger(L, to_index + 1);
5408 lua_pushinteger(L, count);
5409 objectref_get_or_create(L, player);
5410 if(lua_pcall(L, 7, 0, 0))
5411 script_error(L, "error: %s", lua_tostring(L, -1));
5414 ItemStack scriptapi_node_on_metadata_inventory_offer(lua_State *L, v3s16 p,
5415 const std::string &listname, int index, ItemStack &stack,
5416 ServerActiveObject *player)
5419 assert(lua_checkstack(L, 20));
5420 StackUnroller stack_unroller(L);
5422 INodeDefManager *ndef = get_server(L)->ndef();
5424 // If node doesn't exist, we don't know what callback to call
5425 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5426 if(node.getContent() == CONTENT_IGNORE)
5429 // Push callback function on stack
5430 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5431 "on_metadata_inventory_offer"))
5434 // Call function(pos, listname, index, stack, player)
5436 lua_pushstring(L, listname.c_str());
5437 lua_pushinteger(L, index + 1);
5438 LuaItemStack::create(L, stack);
5439 objectref_get_or_create(L, player);
5440 if(lua_pcall(L, 5, 1, 0))
5441 script_error(L, "error: %s", lua_tostring(L, -1));
5442 return read_item(L, -1);
5445 ItemStack scriptapi_node_on_metadata_inventory_take(lua_State *L, v3s16 p,
5446 const std::string &listname, int index, int count,
5447 ServerActiveObject *player)
5450 assert(lua_checkstack(L, 20));
5451 StackUnroller stack_unroller(L);
5453 INodeDefManager *ndef = get_server(L)->ndef();
5455 // If node doesn't exist, we don't know what callback to call
5456 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5457 if(node.getContent() == CONTENT_IGNORE)
5460 // Push callback function on stack
5461 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5462 "on_metadata_inventory_take"))
5465 // Call function(pos, listname, index, count, player)
5467 lua_pushstring(L, listname.c_str());
5468 lua_pushinteger(L, index + 1);
5469 lua_pushinteger(L, count);
5470 objectref_get_or_create(L, player);
5471 if(lua_pcall(L, 5, 1, 0))
5472 script_error(L, "error: %s", lua_tostring(L, -1));
5473 return read_item(L, -1);
5480 void scriptapi_environment_step(lua_State *L, float dtime)
5483 assert(lua_checkstack(L, 20));
5484 //infostream<<"scriptapi_environment_step"<<std::endl;
5485 StackUnroller stack_unroller(L);
5487 // Get minetest.registered_globalsteps
5488 lua_getglobal(L, "minetest");
5489 lua_getfield(L, -1, "registered_globalsteps");
5491 lua_pushnumber(L, dtime);
5492 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5495 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5499 assert(lua_checkstack(L, 20));
5500 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5501 StackUnroller stack_unroller(L);
5503 // Get minetest.registered_on_generateds
5504 lua_getglobal(L, "minetest");
5505 lua_getfield(L, -1, "registered_on_generateds");
5507 push_v3s16(L, minp);
5508 push_v3s16(L, maxp);
5509 lua_pushnumber(L, blockseed);
5510 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5517 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5520 assert(lua_checkstack(L, 20));
5521 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5522 <<name<<"\""<<std::endl;
5523 StackUnroller stack_unroller(L);
5525 // Get minetest.registered_entities[name]
5526 lua_getglobal(L, "minetest");
5527 lua_getfield(L, -1, "registered_entities");
5528 luaL_checktype(L, -1, LUA_TTABLE);
5529 lua_pushstring(L, name);
5530 lua_gettable(L, -2);
5531 // Should be a table, which we will use as a prototype
5532 //luaL_checktype(L, -1, LUA_TTABLE);
5533 if(lua_type(L, -1) != LUA_TTABLE){
5534 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5537 int prototype_table = lua_gettop(L);
5538 //dump2(L, "prototype_table");
5540 // Create entity object
5542 int object = lua_gettop(L);
5544 // Set object metatable
5545 lua_pushvalue(L, prototype_table);
5546 lua_setmetatable(L, -2);
5548 // Add object reference
5549 // This should be userdata with metatable ObjectRef
5550 objectref_get(L, id);
5551 luaL_checktype(L, -1, LUA_TUSERDATA);
5552 if(!luaL_checkudata(L, -1, "ObjectRef"))
5553 luaL_typerror(L, -1, "ObjectRef");
5554 lua_setfield(L, -2, "object");
5556 // minetest.luaentities[id] = object
5557 lua_getglobal(L, "minetest");
5558 lua_getfield(L, -1, "luaentities");
5559 luaL_checktype(L, -1, LUA_TTABLE);
5560 lua_pushnumber(L, id); // Push id
5561 lua_pushvalue(L, object); // Copy object to top of stack
5562 lua_settable(L, -3);
5567 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5568 const std::string &staticdata)
5571 assert(lua_checkstack(L, 20));
5572 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5573 StackUnroller stack_unroller(L);
5575 // Get minetest.luaentities[id]
5576 luaentity_get(L, id);
5577 int object = lua_gettop(L);
5579 // Get on_activate function
5580 lua_pushvalue(L, object);
5581 lua_getfield(L, -1, "on_activate");
5582 if(!lua_isnil(L, -1)){
5583 luaL_checktype(L, -1, LUA_TFUNCTION);
5584 lua_pushvalue(L, object); // self
5585 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5586 // Call with 2 arguments, 0 results
5587 if(lua_pcall(L, 2, 0, 0))
5588 script_error(L, "error running function on_activate: %s\n",
5589 lua_tostring(L, -1));
5593 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5596 assert(lua_checkstack(L, 20));
5597 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5599 // Get minetest.luaentities table
5600 lua_getglobal(L, "minetest");
5601 lua_getfield(L, -1, "luaentities");
5602 luaL_checktype(L, -1, LUA_TTABLE);
5603 int objectstable = lua_gettop(L);
5605 // Set luaentities[id] = nil
5606 lua_pushnumber(L, id); // Push id
5608 lua_settable(L, objectstable);
5610 lua_pop(L, 2); // pop luaentities, minetest
5613 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5616 assert(lua_checkstack(L, 20));
5617 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5618 StackUnroller stack_unroller(L);
5620 // Get minetest.luaentities[id]
5621 luaentity_get(L, id);
5622 int object = lua_gettop(L);
5624 // Get get_staticdata function
5625 lua_pushvalue(L, object);
5626 lua_getfield(L, -1, "get_staticdata");
5627 if(lua_isnil(L, -1))
5630 luaL_checktype(L, -1, LUA_TFUNCTION);
5631 lua_pushvalue(L, object); // self
5632 // Call with 1 arguments, 1 results
5633 if(lua_pcall(L, 1, 1, 0))
5634 script_error(L, "error running function get_staticdata: %s\n",
5635 lua_tostring(L, -1));
5638 const char *s = lua_tolstring(L, -1, &len);
5639 return std::string(s, len);
5642 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5643 ObjectProperties *prop)
5646 assert(lua_checkstack(L, 20));
5647 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5648 StackUnroller stack_unroller(L);
5650 // Get minetest.luaentities[id]
5651 luaentity_get(L, id);
5652 //int object = lua_gettop(L);
5654 // Set default values that differ from ObjectProperties defaults
5659 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
5661 getboolfield(L, -1, "physical", prop->physical);
5663 getfloatfield(L, -1, "weight", prop->weight);
5665 lua_getfield(L, -1, "collisionbox");
5666 if(lua_istable(L, -1))
5667 prop->collisionbox = read_aabb3f(L, -1, 1.0);
5670 getstringfield(L, -1, "visual", prop->visual);
5672 // Deprecated: read object properties directly
5673 read_object_properties(L, -1, prop);
5675 // Read initial_properties
5676 lua_getfield(L, -1, "initial_properties");
5677 read_object_properties(L, -1, prop);
5681 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5684 assert(lua_checkstack(L, 20));
5685 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5686 StackUnroller stack_unroller(L);
5688 // Get minetest.luaentities[id]
5689 luaentity_get(L, id);
5690 int object = lua_gettop(L);
5691 // State: object is at top of stack
5692 // Get step function
5693 lua_getfield(L, -1, "on_step");
5694 if(lua_isnil(L, -1))
5696 luaL_checktype(L, -1, LUA_TFUNCTION);
5697 lua_pushvalue(L, object); // self
5698 lua_pushnumber(L, dtime); // dtime
5699 // Call with 2 arguments, 0 results
5700 if(lua_pcall(L, 2, 0, 0))
5701 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5704 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5705 // tool_capabilities, direction)
5706 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5707 ServerActiveObject *puncher, float time_from_last_punch,
5708 const ToolCapabilities *toolcap, v3f dir)
5711 assert(lua_checkstack(L, 20));
5712 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5713 StackUnroller stack_unroller(L);
5715 // Get minetest.luaentities[id]
5716 luaentity_get(L, id);
5717 int object = lua_gettop(L);
5718 // State: object is at top of stack
5720 lua_getfield(L, -1, "on_punch");
5721 if(lua_isnil(L, -1))
5723 luaL_checktype(L, -1, LUA_TFUNCTION);
5724 lua_pushvalue(L, object); // self
5725 objectref_get_or_create(L, puncher); // Clicker reference
5726 lua_pushnumber(L, time_from_last_punch);
5727 push_tool_capabilities(L, *toolcap);
5729 // Call with 5 arguments, 0 results
5730 if(lua_pcall(L, 5, 0, 0))
5731 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5734 // Calls entity:on_rightclick(ObjectRef clicker)
5735 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5736 ServerActiveObject *clicker)
5739 assert(lua_checkstack(L, 20));
5740 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5741 StackUnroller stack_unroller(L);
5743 // Get minetest.luaentities[id]
5744 luaentity_get(L, id);
5745 int object = lua_gettop(L);
5746 // State: object is at top of stack
5748 lua_getfield(L, -1, "on_rightclick");
5749 if(lua_isnil(L, -1))
5751 luaL_checktype(L, -1, LUA_TFUNCTION);
5752 lua_pushvalue(L, object); // self
5753 objectref_get_or_create(L, clicker); // Clicker reference
5754 // Call with 2 arguments, 0 results
5755 if(lua_pcall(L, 2, 0, 0))
5756 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));