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"
48 #include "daynightratio.h"
49 #include "noise.h" // PseudoRandom for LuaPseudoRandom
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"},
388 struct EnumString es_ContentParamType[] =
391 {CPT_LIGHT, "light"},
395 struct EnumString es_ContentParamType2[] =
399 {CPT2_FLOWINGLIQUID, "flowingliquid"},
400 {CPT2_FACEDIR, "facedir"},
401 {CPT2_WALLMOUNTED, "wallmounted"},
405 struct EnumString es_LiquidType[] =
407 {LIQUID_NONE, "none"},
408 {LIQUID_FLOWING, "flowing"},
409 {LIQUID_SOURCE, "source"},
413 struct EnumString es_NodeBoxType[] =
415 {NODEBOX_REGULAR, "regular"},
416 {NODEBOX_FIXED, "fixed"},
417 {NODEBOX_WALLMOUNTED, "wallmounted"},
421 struct EnumString es_CraftMethod[] =
423 {CRAFT_METHOD_NORMAL, "normal"},
424 {CRAFT_METHOD_COOKING, "cooking"},
425 {CRAFT_METHOD_FUEL, "fuel"},
430 C struct <-> Lua table converter functions
433 static void push_v3f(lua_State *L, v3f p)
436 lua_pushnumber(L, p.X);
437 lua_setfield(L, -2, "x");
438 lua_pushnumber(L, p.Y);
439 lua_setfield(L, -2, "y");
440 lua_pushnumber(L, p.Z);
441 lua_setfield(L, -2, "z");
444 static v2s16 read_v2s16(lua_State *L, int index)
447 luaL_checktype(L, index, LUA_TTABLE);
448 lua_getfield(L, index, "x");
449 p.X = lua_tonumber(L, -1);
451 lua_getfield(L, index, "y");
452 p.Y = lua_tonumber(L, -1);
457 static v2f read_v2f(lua_State *L, int index)
460 luaL_checktype(L, index, LUA_TTABLE);
461 lua_getfield(L, index, "x");
462 p.X = lua_tonumber(L, -1);
464 lua_getfield(L, index, "y");
465 p.Y = lua_tonumber(L, -1);
470 static v3f read_v3f(lua_State *L, int index)
473 luaL_checktype(L, index, LUA_TTABLE);
474 lua_getfield(L, index, "x");
475 pos.X = lua_tonumber(L, -1);
477 lua_getfield(L, index, "y");
478 pos.Y = lua_tonumber(L, -1);
480 lua_getfield(L, index, "z");
481 pos.Z = lua_tonumber(L, -1);
486 static v3f check_v3f(lua_State *L, int index)
489 luaL_checktype(L, index, LUA_TTABLE);
490 lua_getfield(L, index, "x");
491 pos.X = luaL_checknumber(L, -1);
493 lua_getfield(L, index, "y");
494 pos.Y = luaL_checknumber(L, -1);
496 lua_getfield(L, index, "z");
497 pos.Z = luaL_checknumber(L, -1);
502 static void pushFloatPos(lua_State *L, v3f p)
508 static v3f checkFloatPos(lua_State *L, int index)
510 return check_v3f(L, index) * BS;
513 static void push_v3s16(lua_State *L, v3s16 p)
516 lua_pushnumber(L, p.X);
517 lua_setfield(L, -2, "x");
518 lua_pushnumber(L, p.Y);
519 lua_setfield(L, -2, "y");
520 lua_pushnumber(L, p.Z);
521 lua_setfield(L, -2, "z");
524 static v3s16 read_v3s16(lua_State *L, int index)
526 // Correct rounding at <0
527 v3f pf = read_v3f(L, index);
528 return floatToInt(pf, 1.0);
531 static v3s16 check_v3s16(lua_State *L, int index)
533 // Correct rounding at <0
534 v3f pf = check_v3f(L, index);
535 return floatToInt(pf, 1.0);
538 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
541 lua_pushstring(L, ndef->get(n).name.c_str());
542 lua_setfield(L, -2, "name");
543 lua_pushnumber(L, n.getParam1());
544 lua_setfield(L, -2, "param1");
545 lua_pushnumber(L, n.getParam2());
546 lua_setfield(L, -2, "param2");
549 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
551 lua_getfield(L, index, "name");
552 const char *name = luaL_checkstring(L, -1);
555 lua_getfield(L, index, "param1");
559 param1 = lua_tonumber(L, -1);
562 lua_getfield(L, index, "param2");
566 param2 = lua_tonumber(L, -1);
568 return MapNode(ndef, name, param1, param2);
571 static video::SColor readARGB8(lua_State *L, int index)
574 luaL_checktype(L, index, LUA_TTABLE);
575 lua_getfield(L, index, "a");
576 if(lua_isnumber(L, -1))
577 color.setAlpha(lua_tonumber(L, -1));
579 lua_getfield(L, index, "r");
580 color.setRed(lua_tonumber(L, -1));
582 lua_getfield(L, index, "g");
583 color.setGreen(lua_tonumber(L, -1));
585 lua_getfield(L, index, "b");
586 color.setBlue(lua_tonumber(L, -1));
591 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
593 core::aabbox3d<f32> box;
594 if(lua_istable(L, -1)){
595 lua_rawgeti(L, -1, 1);
596 box.MinEdge.X = lua_tonumber(L, -1) * scale;
598 lua_rawgeti(L, -1, 2);
599 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
601 lua_rawgeti(L, -1, 3);
602 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
604 lua_rawgeti(L, -1, 4);
605 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
607 lua_rawgeti(L, -1, 5);
608 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
610 lua_rawgeti(L, -1, 6);
611 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
622 static MaterialProperties read_material_properties(
623 lua_State *L, int table)
625 MaterialProperties prop;
626 prop.diggability = (Diggability)getenumfield(L, -1, "diggability",
627 es_Diggability, DIGGABLE_NORMAL);
628 getfloatfield(L, -1, "constant_time", prop.constant_time);
629 getfloatfield(L, -1, "weight", prop.weight);
630 getfloatfield(L, -1, "crackiness", prop.crackiness);
631 getfloatfield(L, -1, "crumbliness", prop.crumbliness);
632 getfloatfield(L, -1, "cuttability", prop.cuttability);
633 getfloatfield(L, -1, "flammability", prop.flammability);
641 static void read_groups(lua_State *L, int index,
642 std::map<std::string, int> &result)
648 while(lua_next(L, index) != 0){
649 // key at index -2 and value at index -1
650 std::string name = luaL_checkstring(L, -2);
651 int rating = luaL_checkinteger(L, -1);
652 result[name] = rating;
653 // removes value, keeps key for next iteration
661 static void read_privileges(lua_State *L, int index,
662 std::set<std::string> &result)
668 while(lua_next(L, index) != 0){
669 // key at index -2 and value at index -1
670 std::string key = luaL_checkstring(L, -2);
671 bool value = lua_toboolean(L, -1);
674 // removes value, keeps key for next iteration
683 static ToolCapabilities read_tool_capabilities(
684 lua_State *L, int table)
686 ToolCapabilities toolcap;
687 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
688 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
689 lua_getfield(L, table, "groupcaps");
690 if(lua_istable(L, -1)){
691 int table_groupcaps = lua_gettop(L);
693 while(lua_next(L, table_groupcaps) != 0){
694 // key at index -2 and value at index -1
695 std::string groupname = luaL_checkstring(L, -2);
696 if(lua_istable(L, -1)){
697 int table_groupcap = lua_gettop(L);
698 // This will be created
699 ToolGroupCap groupcap;
700 // Read simple parameters
701 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
702 getintfield(L, table_groupcap, "uses", groupcap.uses);
703 // DEPRECATED: maxwear
705 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
707 groupcap.uses = 1.0/maxwear;
710 infostream<<script_get_backtrace(L)<<std::endl;
711 infostream<<"WARNING: field \"maxwear\" is deprecated; "
712 <<"should replace with uses=1/maxwear"<<std::endl;
714 // Read "times" table
715 lua_getfield(L, table_groupcap, "times");
716 if(lua_istable(L, -1)){
717 int table_times = lua_gettop(L);
719 while(lua_next(L, table_times) != 0){
720 // key at index -2 and value at index -1
721 int rating = luaL_checkinteger(L, -2);
722 float time = luaL_checknumber(L, -1);
723 groupcap.times[rating] = time;
724 // removes value, keeps key for next iteration
729 // Insert groupcap into toolcap
730 toolcap.groupcaps[groupname] = groupcap;
732 // removes value, keeps key for next iteration
740 static void set_tool_capabilities(lua_State *L, int table,
741 const ToolCapabilities &toolcap)
743 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
744 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
745 // Create groupcaps table
748 for(std::map<std::string, ToolGroupCap>::const_iterator
749 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
750 // Create groupcap table
752 const std::string &name = i->first;
753 const ToolGroupCap &groupcap = i->second;
754 // Create subtable "times"
756 for(std::map<int, float>::const_iterator
757 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
758 int rating = i->first;
759 float time = i->second;
760 lua_pushinteger(L, rating);
761 lua_pushnumber(L, time);
764 // Set subtable "times"
765 lua_setfield(L, -2, "times");
766 // Set simple parameters
767 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
768 setintfield(L, -1, "uses", groupcap.uses);
769 // Insert groupcap table into groupcaps table
770 lua_setfield(L, -2, name.c_str());
772 // Set groupcaps table
773 lua_setfield(L, -2, "groupcaps");
776 static void push_tool_capabilities(lua_State *L,
777 const ToolCapabilities &prop)
780 set_tool_capabilities(L, -1, prop);
787 static void set_dig_params(lua_State *L, int table,
788 const DigParams ¶ms)
790 setboolfield(L, table, "diggable", params.diggable);
791 setfloatfield(L, table, "time", params.time);
792 setintfield(L, table, "wear", params.wear);
795 static void push_dig_params(lua_State *L,
796 const DigParams ¶ms)
799 set_dig_params(L, -1, params);
806 static void set_hit_params(lua_State *L, int table,
807 const HitParams ¶ms)
809 setintfield(L, table, "hp", params.hp);
810 setintfield(L, table, "wear", params.wear);
813 static void push_hit_params(lua_State *L,
814 const HitParams ¶ms)
817 set_hit_params(L, -1, params);
824 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
827 if(pointed.type == POINTEDTHING_NODE)
829 lua_pushstring(L, "node");
830 lua_setfield(L, -2, "type");
831 push_v3s16(L, pointed.node_undersurface);
832 lua_setfield(L, -2, "under");
833 push_v3s16(L, pointed.node_abovesurface);
834 lua_setfield(L, -2, "above");
836 else if(pointed.type == POINTEDTHING_OBJECT)
838 lua_pushstring(L, "object");
839 lua_setfield(L, -2, "type");
840 objectref_get(L, pointed.object_id);
841 lua_setfield(L, -2, "ref");
845 lua_pushstring(L, "nothing");
846 lua_setfield(L, -2, "type");
854 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
857 index = lua_gettop(L) + 1 + index;
858 if(lua_isnil(L, index)){
859 } else if(lua_istable(L, index)){
860 getstringfield(L, index, "name", spec.name);
861 getfloatfield(L, index, "gain", spec.gain);
862 } else if(lua_isstring(L, index)){
863 spec.name = lua_tostring(L, index);
871 static void read_object_properties(lua_State *L, int index,
872 ObjectProperties *prop)
875 index = lua_gettop(L) + 1 + index;
876 if(!lua_istable(L, index))
879 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
881 getboolfield(L, -1, "physical", prop->physical);
883 getfloatfield(L, -1, "weight", prop->weight);
885 lua_getfield(L, -1, "collisionbox");
886 if(lua_istable(L, -1))
887 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
890 getstringfield(L, -1, "visual", prop->visual);
892 lua_getfield(L, -1, "visual_size");
893 if(lua_istable(L, -1))
894 prop->visual_size = read_v2f(L, -1);
897 lua_getfield(L, -1, "textures");
898 if(lua_istable(L, -1)){
899 prop->textures.clear();
900 int table = lua_gettop(L);
902 while(lua_next(L, table) != 0){
903 // key at index -2 and value at index -1
904 if(lua_isstring(L, -1))
905 prop->textures.push_back(lua_tostring(L, -1));
907 prop->textures.push_back("");
908 // removes value, keeps key for next iteration
914 lua_getfield(L, -1, "spritediv");
915 if(lua_istable(L, -1))
916 prop->spritediv = read_v2s16(L, -1);
919 lua_getfield(L, -1, "initial_sprite_basepos");
920 if(lua_istable(L, -1))
921 prop->initial_sprite_basepos = read_v2s16(L, -1);
924 getboolfield(L, -1, "is_visible", prop->is_visible);
925 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
926 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
933 static ItemDefinition read_item_definition(lua_State *L, int index)
936 index = lua_gettop(L) + 1 + index;
938 // Read the item definition
941 def.type = (ItemType)getenumfield(L, index, "type",
942 es_ItemType, ITEM_NONE);
943 getstringfield(L, index, "name", def.name);
944 getstringfield(L, index, "description", def.description);
945 getstringfield(L, index, "inventory_image", def.inventory_image);
946 getstringfield(L, index, "wield_image", def.wield_image);
948 lua_getfield(L, index, "wield_scale");
949 if(lua_istable(L, -1)){
950 def.wield_scale = check_v3f(L, -1);
954 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
955 if(def.stack_max == 0)
958 lua_getfield(L, index, "on_use");
959 def.usable = lua_isfunction(L, -1);
962 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
964 warn_if_field_exists(L, index, "tool_digging_properties",
965 "deprecated: use tool_capabilities");
967 lua_getfield(L, index, "tool_capabilities");
968 if(lua_istable(L, -1)){
969 def.tool_capabilities = new ToolCapabilities(
970 read_tool_capabilities(L, -1));
973 // If name is "" (hand), ensure there are ToolCapabilities
974 // because it will be looked up there whenever any other item has
975 // no ToolCapabilities
976 if(def.name == "" && def.tool_capabilities == NULL){
977 def.tool_capabilities = new ToolCapabilities();
980 lua_getfield(L, index, "groups");
981 read_groups(L, -1, def.groups);
991 static ContentFeatures read_content_features(lua_State *L, int index)
994 index = lua_gettop(L) + 1 + index;
998 getstringfield(L, index, "name", f.name);
1001 lua_getfield(L, index, "groups");
1002 read_groups(L, -1, f.groups);
1005 /* Visual definition */
1007 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1009 getfloatfield(L, index, "visual_scale", f.visual_scale);
1011 lua_getfield(L, index, "tile_images");
1012 if(lua_istable(L, -1)){
1013 int table = lua_gettop(L);
1016 while(lua_next(L, table) != 0){
1017 // key at index -2 and value at index -1
1018 if(lua_isstring(L, -1))
1019 f.tname_tiles[i] = lua_tostring(L, -1);
1021 f.tname_tiles[i] = "";
1022 // removes value, keeps key for next iteration
1030 // Copy last value to all remaining textures
1032 std::string lastname = f.tname_tiles[i-1];
1034 f.tname_tiles[i] = lastname;
1041 lua_getfield(L, index, "special_materials");
1042 if(lua_istable(L, -1)){
1043 int table = lua_gettop(L);
1046 while(lua_next(L, table) != 0){
1047 // key at index -2 and value at index -1
1048 int smtable = lua_gettop(L);
1049 std::string tname = getstringfield_default(
1050 L, smtable, "image", "");
1051 bool backface_culling = getboolfield_default(
1052 L, smtable, "backface_culling", true);
1053 MaterialSpec mspec(tname, backface_culling);
1054 f.mspec_special[i] = mspec;
1055 // removes value, keeps key for next iteration
1066 f.alpha = getintfield_default(L, index, "alpha", 255);
1070 lua_getfield(L, index, "post_effect_color");
1071 if(!lua_isnil(L, -1))
1072 f.post_effect_color = readARGB8(L, -1);
1075 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1076 es_ContentParamType, CPT_NONE);
1077 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1078 es_ContentParamType2, CPT2_NONE);
1080 // Warn about some deprecated fields
1081 warn_if_field_exists(L, index, "wall_mounted",
1082 "deprecated: use paramtype2 = 'wallmounted'");
1083 warn_if_field_exists(L, index, "light_propagates",
1084 "deprecated: determined from paramtype");
1085 warn_if_field_exists(L, index, "dug_item",
1086 "deprecated: use 'drop' field");
1087 warn_if_field_exists(L, index, "extra_dug_item",
1088 "deprecated: use 'drop' field");
1089 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1090 "deprecated: use 'drop' field");
1091 warn_if_field_exists(L, index, "metadata_name",
1092 "deprecated: use on_add and metadata callbacks");
1094 // True for all ground-like things like stone and mud, false for eg. trees
1095 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1096 f.light_propagates = (f.param_type == CPT_LIGHT);
1097 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1098 // This is used for collision detection.
1099 // Also for general solidness queries.
1100 getboolfield(L, index, "walkable", f.walkable);
1101 // Player can point to these
1102 getboolfield(L, index, "pointable", f.pointable);
1103 // Player can dig these
1104 getboolfield(L, index, "diggable", f.diggable);
1105 // Player can climb these
1106 getboolfield(L, index, "climbable", f.climbable);
1107 // Player can build on these
1108 getboolfield(L, index, "buildable_to", f.buildable_to);
1109 // Whether the node is non-liquid, source liquid or flowing liquid
1110 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1111 es_LiquidType, LIQUID_NONE);
1112 // If the content is liquid, this is the flowing version of the liquid.
1113 getstringfield(L, index, "liquid_alternative_flowing",
1114 f.liquid_alternative_flowing);
1115 // If the content is liquid, this is the source version of the liquid.
1116 getstringfield(L, index, "liquid_alternative_source",
1117 f.liquid_alternative_source);
1118 // Viscosity for fluid flow, ranging from 1 to 7, with
1119 // 1 giving almost instantaneous propagation and 7 being
1120 // the slowest possible
1121 f.liquid_viscosity = getintfield_default(L, index,
1122 "liquid_viscosity", f.liquid_viscosity);
1123 // Amount of light the node emits
1124 f.light_source = getintfield_default(L, index,
1125 "light_source", f.light_source);
1126 f.damage_per_second = getintfield_default(L, index,
1127 "damage_per_second", f.damage_per_second);
1129 lua_getfield(L, index, "selection_box");
1130 if(lua_istable(L, -1)){
1131 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1132 es_NodeBoxType, NODEBOX_REGULAR);
1134 lua_getfield(L, -1, "fixed");
1135 if(lua_istable(L, -1))
1136 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1139 lua_getfield(L, -1, "wall_top");
1140 if(lua_istable(L, -1))
1141 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1144 lua_getfield(L, -1, "wall_bottom");
1145 if(lua_istable(L, -1))
1146 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1149 lua_getfield(L, -1, "wall_side");
1150 if(lua_istable(L, -1))
1151 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1156 // Set to true if paramtype used to be 'facedir_simple'
1157 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1158 // Set to true if wall_mounted used to be set to true
1159 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1162 lua_getfield(L, index, "sounds");
1163 if(lua_istable(L, -1)){
1164 lua_getfield(L, -1, "footstep");
1165 read_soundspec(L, -1, f.sound_footstep);
1167 lua_getfield(L, -1, "dig");
1168 read_soundspec(L, -1, f.sound_dig);
1170 lua_getfield(L, -1, "dug");
1171 read_soundspec(L, -1, f.sound_dug);
1183 static ItemStack read_item(lua_State *L, int index);
1184 static std::vector<ItemStack> read_items(lua_State *L, int index);
1185 // creates a table of ItemStacks
1186 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1188 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1189 lua_State *L, int tableindex, int forcesize=-1)
1192 tableindex = lua_gettop(L) + 1 + tableindex;
1193 // If nil, delete list
1194 if(lua_isnil(L, tableindex)){
1195 inv->deleteList(name);
1198 // Otherwise set list
1199 std::vector<ItemStack> items = read_items(L, tableindex);
1200 int listsize = (forcesize != -1) ? forcesize : items.size();
1201 InventoryList *invlist = inv->addList(name, listsize);
1203 for(std::vector<ItemStack>::const_iterator
1204 i = items.begin(); i != items.end(); i++){
1205 if(forcesize != -1 && index == forcesize)
1207 invlist->changeItem(index, *i);
1210 while(forcesize != -1 && index < forcesize){
1211 invlist->deleteItem(index);
1216 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1219 InventoryList *invlist = inv->getList(name);
1220 if(invlist == NULL){
1224 std::vector<ItemStack> items;
1225 for(u32 i=0; i<invlist->getSize(); i++)
1226 items.push_back(invlist->getItem(i));
1227 push_items(L, items);
1231 Helpful macros for userdata classes
1234 #define method(class, name) {#name, class::l_##name}
1245 static const char className[];
1246 static const luaL_reg methods[];
1248 // Exported functions
1250 // garbage collector
1251 static int gc_object(lua_State *L)
1253 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1258 // is_empty(self) -> true/false
1259 static int l_is_empty(lua_State *L)
1261 LuaItemStack *o = checkobject(L, 1);
1262 ItemStack &item = o->m_stack;
1263 lua_pushboolean(L, item.empty());
1267 // get_name(self) -> string
1268 static int l_get_name(lua_State *L)
1270 LuaItemStack *o = checkobject(L, 1);
1271 ItemStack &item = o->m_stack;
1272 lua_pushstring(L, item.name.c_str());
1276 // get_count(self) -> number
1277 static int l_get_count(lua_State *L)
1279 LuaItemStack *o = checkobject(L, 1);
1280 ItemStack &item = o->m_stack;
1281 lua_pushinteger(L, item.count);
1285 // get_wear(self) -> number
1286 static int l_get_wear(lua_State *L)
1288 LuaItemStack *o = checkobject(L, 1);
1289 ItemStack &item = o->m_stack;
1290 lua_pushinteger(L, item.wear);
1294 // get_metadata(self) -> string
1295 static int l_get_metadata(lua_State *L)
1297 LuaItemStack *o = checkobject(L, 1);
1298 ItemStack &item = o->m_stack;
1299 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1303 // clear(self) -> true
1304 static int l_clear(lua_State *L)
1306 LuaItemStack *o = checkobject(L, 1);
1308 lua_pushboolean(L, true);
1312 // replace(self, itemstack or itemstring or table or nil) -> true
1313 static int l_replace(lua_State *L)
1315 LuaItemStack *o = checkobject(L, 1);
1316 o->m_stack = read_item(L, 2);
1317 lua_pushboolean(L, true);
1321 // to_string(self) -> string
1322 static int l_to_string(lua_State *L)
1324 LuaItemStack *o = checkobject(L, 1);
1325 std::string itemstring = o->m_stack.getItemString();
1326 lua_pushstring(L, itemstring.c_str());
1330 // to_table(self) -> table or nil
1331 static int l_to_table(lua_State *L)
1333 LuaItemStack *o = checkobject(L, 1);
1334 const ItemStack &item = o->m_stack;
1342 lua_pushstring(L, item.name.c_str());
1343 lua_setfield(L, -2, "name");
1344 lua_pushinteger(L, item.count);
1345 lua_setfield(L, -2, "count");
1346 lua_pushinteger(L, item.wear);
1347 lua_setfield(L, -2, "wear");
1348 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1349 lua_setfield(L, -2, "metadata");
1354 // get_stack_max(self) -> number
1355 static int l_get_stack_max(lua_State *L)
1357 LuaItemStack *o = checkobject(L, 1);
1358 ItemStack &item = o->m_stack;
1359 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1363 // get_free_space(self) -> number
1364 static int l_get_free_space(lua_State *L)
1366 LuaItemStack *o = checkobject(L, 1);
1367 ItemStack &item = o->m_stack;
1368 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1372 // is_known(self) -> true/false
1373 // Checks if the item is defined.
1374 static int l_is_known(lua_State *L)
1376 LuaItemStack *o = checkobject(L, 1);
1377 ItemStack &item = o->m_stack;
1378 bool is_known = item.isKnown(get_server(L)->idef());
1379 lua_pushboolean(L, is_known);
1383 // get_definition(self) -> table
1384 // Returns the item definition table from minetest.registered_items,
1385 // or a fallback one (name="unknown")
1386 static int l_get_definition(lua_State *L)
1388 LuaItemStack *o = checkobject(L, 1);
1389 ItemStack &item = o->m_stack;
1391 // Get minetest.registered_items[name]
1392 lua_getglobal(L, "minetest");
1393 lua_getfield(L, -1, "registered_items");
1394 luaL_checktype(L, -1, LUA_TTABLE);
1395 lua_getfield(L, -1, item.name.c_str());
1396 if(lua_isnil(L, -1))
1399 lua_getfield(L, -1, "unknown");
1404 // get_tool_capabilities(self) -> table
1405 // Returns the effective tool digging properties.
1406 // Returns those of the hand ("") if this item has none associated.
1407 static int l_get_tool_capabilities(lua_State *L)
1409 LuaItemStack *o = checkobject(L, 1);
1410 ItemStack &item = o->m_stack;
1411 const ToolCapabilities &prop =
1412 item.getToolCapabilities(get_server(L)->idef());
1413 push_tool_capabilities(L, prop);
1417 // add_wear(self, amount) -> true/false
1418 // The range for "amount" is [0,65535]. Wear is only added if the item
1419 // is a tool. Adding wear might destroy the item.
1420 // Returns true if the item is (or was) a tool.
1421 static int l_add_wear(lua_State *L)
1423 LuaItemStack *o = checkobject(L, 1);
1424 ItemStack &item = o->m_stack;
1425 int amount = lua_tointeger(L, 2);
1426 bool result = item.addWear(amount, get_server(L)->idef());
1427 lua_pushboolean(L, result);
1431 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1432 // Returns leftover item stack
1433 static int l_add_item(lua_State *L)
1435 LuaItemStack *o = checkobject(L, 1);
1436 ItemStack &item = o->m_stack;
1437 ItemStack newitem = read_item(L, 2);
1438 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1439 create(L, leftover);
1443 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1444 // First return value is true iff the new item fits fully into the stack
1445 // Second return value is the would-be-left-over item stack
1446 static int l_item_fits(lua_State *L)
1448 LuaItemStack *o = checkobject(L, 1);
1449 ItemStack &item = o->m_stack;
1450 ItemStack newitem = read_item(L, 2);
1452 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1453 lua_pushboolean(L, fits); // first return value
1454 create(L, restitem); // second return value
1458 // take_item(self, takecount=1) -> itemstack
1459 static int l_take_item(lua_State *L)
1461 LuaItemStack *o = checkobject(L, 1);
1462 ItemStack &item = o->m_stack;
1464 if(!lua_isnone(L, 2))
1465 takecount = luaL_checkinteger(L, 2);
1466 ItemStack taken = item.takeItem(takecount);
1471 // peek_item(self, peekcount=1) -> itemstack
1472 static int l_peek_item(lua_State *L)
1474 LuaItemStack *o = checkobject(L, 1);
1475 ItemStack &item = o->m_stack;
1477 if(!lua_isnone(L, 2))
1478 peekcount = lua_tointeger(L, 2);
1479 ItemStack peekaboo = item.peekItem(peekcount);
1480 create(L, peekaboo);
1485 LuaItemStack(const ItemStack &item):
1494 const ItemStack& getItem() const
1498 ItemStack& getItem()
1503 // LuaItemStack(itemstack or itemstring or table or nil)
1504 // Creates an LuaItemStack and leaves it on top of stack
1505 static int create_object(lua_State *L)
1507 ItemStack item = read_item(L, 1);
1508 LuaItemStack *o = new LuaItemStack(item);
1509 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1510 luaL_getmetatable(L, className);
1511 lua_setmetatable(L, -2);
1514 // Not callable from Lua
1515 static int create(lua_State *L, const ItemStack &item)
1517 LuaItemStack *o = new LuaItemStack(item);
1518 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1519 luaL_getmetatable(L, className);
1520 lua_setmetatable(L, -2);
1524 static LuaItemStack* checkobject(lua_State *L, int narg)
1526 luaL_checktype(L, narg, LUA_TUSERDATA);
1527 void *ud = luaL_checkudata(L, narg, className);
1528 if(!ud) luaL_typerror(L, narg, className);
1529 return *(LuaItemStack**)ud; // unbox pointer
1532 static void Register(lua_State *L)
1535 int methodtable = lua_gettop(L);
1536 luaL_newmetatable(L, className);
1537 int metatable = lua_gettop(L);
1539 lua_pushliteral(L, "__metatable");
1540 lua_pushvalue(L, methodtable);
1541 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1543 lua_pushliteral(L, "__index");
1544 lua_pushvalue(L, methodtable);
1545 lua_settable(L, metatable);
1547 lua_pushliteral(L, "__gc");
1548 lua_pushcfunction(L, gc_object);
1549 lua_settable(L, metatable);
1551 lua_pop(L, 1); // drop metatable
1553 luaL_openlib(L, 0, methods, 0); // fill methodtable
1554 lua_pop(L, 1); // drop methodtable
1556 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1557 lua_register(L, className, create_object);
1560 const char LuaItemStack::className[] = "ItemStack";
1561 const luaL_reg LuaItemStack::methods[] = {
1562 method(LuaItemStack, is_empty),
1563 method(LuaItemStack, get_name),
1564 method(LuaItemStack, get_count),
1565 method(LuaItemStack, get_wear),
1566 method(LuaItemStack, get_metadata),
1567 method(LuaItemStack, clear),
1568 method(LuaItemStack, replace),
1569 method(LuaItemStack, to_string),
1570 method(LuaItemStack, to_table),
1571 method(LuaItemStack, get_stack_max),
1572 method(LuaItemStack, get_free_space),
1573 method(LuaItemStack, is_known),
1574 method(LuaItemStack, get_definition),
1575 method(LuaItemStack, get_tool_capabilities),
1576 method(LuaItemStack, add_wear),
1577 method(LuaItemStack, add_item),
1578 method(LuaItemStack, item_fits),
1579 method(LuaItemStack, take_item),
1580 method(LuaItemStack, peek_item),
1584 static ItemStack read_item(lua_State *L, int index)
1587 index = lua_gettop(L) + 1 + index;
1589 if(lua_isnil(L, index))
1593 else if(lua_isuserdata(L, index))
1595 // Convert from LuaItemStack
1596 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1597 return o->getItem();
1599 else if(lua_isstring(L, index))
1601 // Convert from itemstring
1602 std::string itemstring = lua_tostring(L, index);
1603 IItemDefManager *idef = get_server(L)->idef();
1607 item.deSerialize(itemstring, idef);
1610 catch(SerializationError &e)
1612 infostream<<"WARNING: unable to create item from itemstring"
1613 <<": "<<itemstring<<std::endl;
1617 else if(lua_istable(L, index))
1619 // Convert from table
1620 IItemDefManager *idef = get_server(L)->idef();
1621 std::string name = getstringfield_default(L, index, "name", "");
1622 int count = getintfield_default(L, index, "count", 1);
1623 int wear = getintfield_default(L, index, "wear", 0);
1624 std::string metadata = getstringfield_default(L, index, "metadata", "");
1625 return ItemStack(name, count, wear, metadata, idef);
1629 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1633 static std::vector<ItemStack> read_items(lua_State *L, int index)
1636 index = lua_gettop(L) + 1 + index;
1638 std::vector<ItemStack> items;
1639 luaL_checktype(L, index, LUA_TTABLE);
1641 while(lua_next(L, index) != 0){
1642 // key at index -2 and value at index -1
1643 items.push_back(read_item(L, -1));
1644 // removes value, keeps key for next iteration
1650 // creates a table of ItemStacks
1651 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1653 // Get the table insert function
1654 lua_getglobal(L, "table");
1655 lua_getfield(L, -1, "insert");
1656 int table_insert = lua_gettop(L);
1657 // Create and fill table
1659 int table = lua_gettop(L);
1660 for(u32 i=0; i<items.size(); i++){
1661 ItemStack item = items[i];
1662 lua_pushvalue(L, table_insert);
1663 lua_pushvalue(L, table);
1664 LuaItemStack::create(L, item);
1665 if(lua_pcall(L, 2, 0, 0))
1666 script_error(L, "error: %s", lua_tostring(L, -1));
1668 lua_remove(L, -2); // Remove table
1669 lua_remove(L, -2); // Remove insert
1679 InventoryLocation m_loc;
1681 static const char className[];
1682 static const luaL_reg methods[];
1684 static InvRef *checkobject(lua_State *L, int narg)
1686 luaL_checktype(L, narg, LUA_TUSERDATA);
1687 void *ud = luaL_checkudata(L, narg, className);
1688 if(!ud) luaL_typerror(L, narg, className);
1689 return *(InvRef**)ud; // unbox pointer
1692 static Inventory* getinv(lua_State *L, InvRef *ref)
1694 return get_server(L)->getInventory(ref->m_loc);
1697 static InventoryList* getlist(lua_State *L, InvRef *ref,
1698 const char *listname)
1700 Inventory *inv = getinv(L, ref);
1703 return inv->getList(listname);
1706 static void reportInventoryChange(lua_State *L, InvRef *ref)
1708 // Inform other things that the inventory has changed
1709 get_server(L)->setInventoryModified(ref->m_loc);
1712 // Exported functions
1714 // garbage collector
1715 static int gc_object(lua_State *L) {
1716 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1721 // is_empty(self, listname) -> true/false
1722 static int l_is_empty(lua_State *L)
1724 InvRef *ref = checkobject(L, 1);
1725 const char *listname = luaL_checkstring(L, 2);
1726 InventoryList *list = getlist(L, ref, listname);
1727 if(list && list->getUsedSlots() > 0){
1728 lua_pushboolean(L, false);
1730 lua_pushboolean(L, true);
1735 // get_size(self, listname)
1736 static int l_get_size(lua_State *L)
1738 InvRef *ref = checkobject(L, 1);
1739 const char *listname = luaL_checkstring(L, 2);
1740 InventoryList *list = getlist(L, ref, listname);
1742 lua_pushinteger(L, list->getSize());
1744 lua_pushinteger(L, 0);
1749 // set_size(self, listname, size)
1750 static int l_set_size(lua_State *L)
1752 InvRef *ref = checkobject(L, 1);
1753 const char *listname = luaL_checkstring(L, 2);
1754 int newsize = luaL_checknumber(L, 3);
1755 Inventory *inv = getinv(L, ref);
1757 inv->deleteList(listname);
1758 reportInventoryChange(L, ref);
1761 InventoryList *list = inv->getList(listname);
1763 list->setSize(newsize);
1765 list = inv->addList(listname, newsize);
1767 reportInventoryChange(L, ref);
1771 // get_stack(self, listname, i) -> itemstack
1772 static int l_get_stack(lua_State *L)
1774 InvRef *ref = checkobject(L, 1);
1775 const char *listname = luaL_checkstring(L, 2);
1776 int i = luaL_checknumber(L, 3) - 1;
1777 InventoryList *list = getlist(L, ref, listname);
1779 if(list != NULL && i >= 0 && i < (int) list->getSize())
1780 item = list->getItem(i);
1781 LuaItemStack::create(L, item);
1785 // set_stack(self, listname, i, stack) -> true/false
1786 static int l_set_stack(lua_State *L)
1788 InvRef *ref = checkobject(L, 1);
1789 const char *listname = luaL_checkstring(L, 2);
1790 int i = luaL_checknumber(L, 3) - 1;
1791 ItemStack newitem = read_item(L, 4);
1792 InventoryList *list = getlist(L, ref, listname);
1793 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1794 list->changeItem(i, newitem);
1795 reportInventoryChange(L, ref);
1796 lua_pushboolean(L, true);
1798 lua_pushboolean(L, false);
1803 // get_list(self, listname) -> list or nil
1804 static int l_get_list(lua_State *L)
1806 InvRef *ref = checkobject(L, 1);
1807 const char *listname = luaL_checkstring(L, 2);
1808 Inventory *inv = getinv(L, ref);
1809 inventory_get_list_to_lua(inv, listname, L);
1813 // set_list(self, listname, list)
1814 static int l_set_list(lua_State *L)
1816 InvRef *ref = checkobject(L, 1);
1817 const char *listname = luaL_checkstring(L, 2);
1818 Inventory *inv = getinv(L, ref);
1819 InventoryList *list = inv->getList(listname);
1821 inventory_set_list_from_lua(inv, listname, L, 3,
1824 inventory_set_list_from_lua(inv, listname, L, 3);
1825 reportInventoryChange(L, ref);
1829 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1830 // Returns the leftover stack
1831 static int l_add_item(lua_State *L)
1833 InvRef *ref = checkobject(L, 1);
1834 const char *listname = luaL_checkstring(L, 2);
1835 ItemStack item = read_item(L, 3);
1836 InventoryList *list = getlist(L, ref, listname);
1838 ItemStack leftover = list->addItem(item);
1839 if(leftover.count != item.count)
1840 reportInventoryChange(L, ref);
1841 LuaItemStack::create(L, leftover);
1843 LuaItemStack::create(L, item);
1848 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1849 // Returns true if the item completely fits into the list
1850 static int l_room_for_item(lua_State *L)
1852 InvRef *ref = checkobject(L, 1);
1853 const char *listname = luaL_checkstring(L, 2);
1854 ItemStack item = read_item(L, 3);
1855 InventoryList *list = getlist(L, ref, listname);
1857 lua_pushboolean(L, list->roomForItem(item));
1859 lua_pushboolean(L, false);
1864 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1865 // Returns true if the list contains the given count of the given item name
1866 static int l_contains_item(lua_State *L)
1868 InvRef *ref = checkobject(L, 1);
1869 const char *listname = luaL_checkstring(L, 2);
1870 ItemStack item = read_item(L, 3);
1871 InventoryList *list = getlist(L, ref, listname);
1873 lua_pushboolean(L, list->containsItem(item));
1875 lua_pushboolean(L, false);
1880 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1881 // Returns the items that were actually removed
1882 static int l_remove_item(lua_State *L)
1884 InvRef *ref = checkobject(L, 1);
1885 const char *listname = luaL_checkstring(L, 2);
1886 ItemStack item = read_item(L, 3);
1887 InventoryList *list = getlist(L, ref, listname);
1889 ItemStack removed = list->removeItem(item);
1890 if(!removed.empty())
1891 reportInventoryChange(L, ref);
1892 LuaItemStack::create(L, removed);
1894 LuaItemStack::create(L, ItemStack());
1900 InvRef(const InventoryLocation &loc):
1909 // Creates an InvRef and leaves it on top of stack
1910 // Not callable from Lua; all references are created on the C side.
1911 static void create(lua_State *L, const InventoryLocation &loc)
1913 InvRef *o = new InvRef(loc);
1914 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1915 luaL_getmetatable(L, className);
1916 lua_setmetatable(L, -2);
1918 static void createPlayer(lua_State *L, Player *player)
1920 InventoryLocation loc;
1921 loc.setPlayer(player->getName());
1924 static void createNodeMeta(lua_State *L, v3s16 p)
1926 InventoryLocation loc;
1931 static void Register(lua_State *L)
1934 int methodtable = lua_gettop(L);
1935 luaL_newmetatable(L, className);
1936 int metatable = lua_gettop(L);
1938 lua_pushliteral(L, "__metatable");
1939 lua_pushvalue(L, methodtable);
1940 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1942 lua_pushliteral(L, "__index");
1943 lua_pushvalue(L, methodtable);
1944 lua_settable(L, metatable);
1946 lua_pushliteral(L, "__gc");
1947 lua_pushcfunction(L, gc_object);
1948 lua_settable(L, metatable);
1950 lua_pop(L, 1); // drop metatable
1952 luaL_openlib(L, 0, methods, 0); // fill methodtable
1953 lua_pop(L, 1); // drop methodtable
1955 // Cannot be created from Lua
1956 //lua_register(L, className, create_object);
1959 const char InvRef::className[] = "InvRef";
1960 const luaL_reg InvRef::methods[] = {
1961 method(InvRef, is_empty),
1962 method(InvRef, get_size),
1963 method(InvRef, set_size),
1964 method(InvRef, get_stack),
1965 method(InvRef, set_stack),
1966 method(InvRef, get_list),
1967 method(InvRef, set_list),
1968 method(InvRef, add_item),
1969 method(InvRef, room_for_item),
1970 method(InvRef, contains_item),
1971 method(InvRef, remove_item),
1983 ServerEnvironment *m_env;
1985 static const char className[];
1986 static const luaL_reg methods[];
1988 static NodeMetaRef *checkobject(lua_State *L, int narg)
1990 luaL_checktype(L, narg, LUA_TUSERDATA);
1991 void *ud = luaL_checkudata(L, narg, className);
1992 if(!ud) luaL_typerror(L, narg, className);
1993 return *(NodeMetaRef**)ud; // unbox pointer
1996 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
1998 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1999 if(meta == NULL && auto_create)
2001 meta = new NodeMetadata(ref->m_env->getGameDef());
2002 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2007 static void reportMetadataChange(NodeMetaRef *ref)
2009 // Inform other things that the metadata has changed
2010 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2012 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2014 ref->m_env->getMap().dispatchEvent(&event);
2015 // Set the block to be saved
2016 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2018 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2019 "NodeMetaRef::reportMetadataChange");
2022 // Exported functions
2024 // garbage collector
2025 static int gc_object(lua_State *L) {
2026 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2031 // get_string(self, name)
2032 static int l_get_string(lua_State *L)
2034 NodeMetaRef *ref = checkobject(L, 1);
2035 std::string name = luaL_checkstring(L, 2);
2037 NodeMetadata *meta = getmeta(ref, false);
2039 lua_pushlstring(L, "", 0);
2042 std::string str = meta->getString(name);
2043 lua_pushlstring(L, str.c_str(), str.size());
2047 // set_string(self, name, var)
2048 static int l_set_string(lua_State *L)
2050 NodeMetaRef *ref = checkobject(L, 1);
2051 std::string name = luaL_checkstring(L, 2);
2053 const char *s = lua_tolstring(L, 3, &len);
2054 std::string str(s, len);
2056 NodeMetadata *meta = getmeta(ref, !str.empty());
2057 if(meta == NULL || str == meta->getString(name))
2059 meta->setString(name, str);
2060 reportMetadataChange(ref);
2064 // get_int(self, name)
2065 static int l_get_int(lua_State *L)
2067 NodeMetaRef *ref = checkobject(L, 1);
2068 std::string name = lua_tostring(L, 2);
2070 NodeMetadata *meta = getmeta(ref, false);
2072 lua_pushnumber(L, 0);
2075 std::string str = meta->getString(name);
2076 lua_pushnumber(L, stoi(str));
2080 // set_int(self, name, var)
2081 static int l_set_int(lua_State *L)
2083 NodeMetaRef *ref = checkobject(L, 1);
2084 std::string name = lua_tostring(L, 2);
2085 int a = lua_tointeger(L, 3);
2086 std::string str = itos(a);
2088 NodeMetadata *meta = getmeta(ref, true);
2089 if(meta == NULL || str == meta->getString(name))
2091 meta->setString(name, str);
2092 reportMetadataChange(ref);
2096 // get_float(self, name)
2097 static int l_get_float(lua_State *L)
2099 NodeMetaRef *ref = checkobject(L, 1);
2100 std::string name = lua_tostring(L, 2);
2102 NodeMetadata *meta = getmeta(ref, false);
2104 lua_pushnumber(L, 0);
2107 std::string str = meta->getString(name);
2108 lua_pushnumber(L, stof(str));
2112 // set_float(self, name, var)
2113 static int l_set_float(lua_State *L)
2115 NodeMetaRef *ref = checkobject(L, 1);
2116 std::string name = lua_tostring(L, 2);
2117 float a = lua_tonumber(L, 3);
2118 std::string str = ftos(a);
2120 NodeMetadata *meta = getmeta(ref, true);
2121 if(meta == NULL || str == meta->getString(name))
2123 meta->setString(name, str);
2124 reportMetadataChange(ref);
2128 // get_inventory(self)
2129 static int l_get_inventory(lua_State *L)
2131 NodeMetaRef *ref = checkobject(L, 1);
2132 getmeta(ref, true); // try to ensure the metadata exists
2133 InvRef::createNodeMeta(L, ref->m_p);
2138 static int l_to_table(lua_State *L)
2140 NodeMetaRef *ref = checkobject(L, 1);
2142 NodeMetadata *meta = getmeta(ref, true);
2151 std::map<std::string, std::string> fields = meta->getStrings();
2152 for(std::map<std::string, std::string>::const_iterator
2153 i = fields.begin(); i != fields.end(); i++){
2154 const std::string &name = i->first;
2155 const std::string &value = i->second;
2156 lua_pushlstring(L, name.c_str(), name.size());
2157 lua_pushlstring(L, value.c_str(), value.size());
2158 lua_settable(L, -3);
2161 lua_setfield(L, -2, "fields");
2164 Inventory *inv = meta->getInventory();
2166 std::vector<const InventoryList*> lists = inv->getLists();
2167 for(std::vector<const InventoryList*>::const_iterator
2168 i = lists.begin(); i != lists.end(); i++){
2169 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2170 lua_setfield(L, -2, (*i)->getName().c_str());
2173 lua_setfield(L, -2, "inventory");
2177 // from_table(self, table)
2178 static int l_from_table(lua_State *L)
2180 NodeMetaRef *ref = checkobject(L, 1);
2183 if(lua_isnil(L, base)){
2185 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2186 lua_pushboolean(L, true);
2190 // Has metadata; clear old one first
2191 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2192 // Create new metadata
2193 NodeMetadata *meta = getmeta(ref, true);
2195 lua_getfield(L, base, "fields");
2196 int fieldstable = lua_gettop(L);
2198 while(lua_next(L, fieldstable) != 0){
2199 // key at index -2 and value at index -1
2200 std::string name = lua_tostring(L, -2);
2202 const char *cs = lua_tolstring(L, -1, &cl);
2203 std::string value(cs, cl);
2204 meta->setString(name, value);
2205 lua_pop(L, 1); // removes value, keeps key for next iteration
2208 Inventory *inv = meta->getInventory();
2209 lua_getfield(L, base, "inventory");
2210 int inventorytable = lua_gettop(L);
2212 while(lua_next(L, inventorytable) != 0){
2213 // key at index -2 and value at index -1
2214 std::string name = lua_tostring(L, -2);
2215 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2216 lua_pop(L, 1); // removes value, keeps key for next iteration
2218 reportMetadataChange(ref);
2219 lua_pushboolean(L, true);
2224 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2234 // Creates an NodeMetaRef and leaves it on top of stack
2235 // Not callable from Lua; all references are created on the C side.
2236 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2238 NodeMetaRef *o = new NodeMetaRef(p, env);
2239 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2240 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2241 luaL_getmetatable(L, className);
2242 lua_setmetatable(L, -2);
2245 static void Register(lua_State *L)
2248 int methodtable = lua_gettop(L);
2249 luaL_newmetatable(L, className);
2250 int metatable = lua_gettop(L);
2252 lua_pushliteral(L, "__metatable");
2253 lua_pushvalue(L, methodtable);
2254 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2256 lua_pushliteral(L, "__index");
2257 lua_pushvalue(L, methodtable);
2258 lua_settable(L, metatable);
2260 lua_pushliteral(L, "__gc");
2261 lua_pushcfunction(L, gc_object);
2262 lua_settable(L, metatable);
2264 lua_pop(L, 1); // drop metatable
2266 luaL_openlib(L, 0, methods, 0); // fill methodtable
2267 lua_pop(L, 1); // drop methodtable
2269 // Cannot be created from Lua
2270 //lua_register(L, className, create_object);
2273 const char NodeMetaRef::className[] = "NodeMetaRef";
2274 const luaL_reg NodeMetaRef::methods[] = {
2275 method(NodeMetaRef, get_string),
2276 method(NodeMetaRef, set_string),
2277 method(NodeMetaRef, get_int),
2278 method(NodeMetaRef, set_int),
2279 method(NodeMetaRef, get_float),
2280 method(NodeMetaRef, set_float),
2281 method(NodeMetaRef, get_inventory),
2282 method(NodeMetaRef, to_table),
2283 method(NodeMetaRef, from_table),
2294 ServerActiveObject *m_object;
2296 static const char className[];
2297 static const luaL_reg methods[];
2299 static ObjectRef *checkobject(lua_State *L, int narg)
2301 luaL_checktype(L, narg, LUA_TUSERDATA);
2302 void *ud = luaL_checkudata(L, narg, className);
2303 if(!ud) luaL_typerror(L, narg, className);
2304 return *(ObjectRef**)ud; // unbox pointer
2307 static ServerActiveObject* getobject(ObjectRef *ref)
2309 ServerActiveObject *co = ref->m_object;
2313 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2315 ServerActiveObject *obj = getobject(ref);
2318 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2320 return (LuaEntitySAO*)obj;
2323 static PlayerSAO* getplayersao(ObjectRef *ref)
2325 ServerActiveObject *obj = getobject(ref);
2328 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2330 return (PlayerSAO*)obj;
2333 static Player* getplayer(ObjectRef *ref)
2335 PlayerSAO *playersao = getplayersao(ref);
2336 if(playersao == NULL)
2338 return playersao->getPlayer();
2341 // Exported functions
2343 // garbage collector
2344 static int gc_object(lua_State *L) {
2345 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2346 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2352 static int l_remove(lua_State *L)
2354 ObjectRef *ref = checkobject(L, 1);
2355 ServerActiveObject *co = getobject(ref);
2356 if(co == NULL) return 0;
2357 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2358 co->m_removed = true;
2363 // returns: {x=num, y=num, z=num}
2364 static int l_getpos(lua_State *L)
2366 ObjectRef *ref = checkobject(L, 1);
2367 ServerActiveObject *co = getobject(ref);
2368 if(co == NULL) return 0;
2369 v3f pos = co->getBasePosition() / BS;
2371 lua_pushnumber(L, pos.X);
2372 lua_setfield(L, -2, "x");
2373 lua_pushnumber(L, pos.Y);
2374 lua_setfield(L, -2, "y");
2375 lua_pushnumber(L, pos.Z);
2376 lua_setfield(L, -2, "z");
2380 // setpos(self, pos)
2381 static int l_setpos(lua_State *L)
2383 ObjectRef *ref = checkobject(L, 1);
2384 //LuaEntitySAO *co = getluaobject(ref);
2385 ServerActiveObject *co = getobject(ref);
2386 if(co == NULL) return 0;
2388 v3f pos = checkFloatPos(L, 2);
2394 // moveto(self, pos, continuous=false)
2395 static int l_moveto(lua_State *L)
2397 ObjectRef *ref = checkobject(L, 1);
2398 //LuaEntitySAO *co = getluaobject(ref);
2399 ServerActiveObject *co = getobject(ref);
2400 if(co == NULL) return 0;
2402 v3f pos = checkFloatPos(L, 2);
2404 bool continuous = lua_toboolean(L, 3);
2406 co->moveTo(pos, continuous);
2410 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2411 static int l_punch(lua_State *L)
2413 ObjectRef *ref = checkobject(L, 1);
2414 ObjectRef *puncher_ref = checkobject(L, 2);
2415 ServerActiveObject *co = getobject(ref);
2416 ServerActiveObject *puncher = getobject(puncher_ref);
2417 if(co == NULL) return 0;
2418 if(puncher == NULL) return 0;
2419 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2420 v3f dir = read_v3f(L, 4);
2421 float time_from_last_punch = 1000000;
2422 if(lua_isnumber(L, 5))
2423 time_from_last_punch = lua_tonumber(L, 5);
2425 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2429 // right_click(self, clicker); clicker = an another ObjectRef
2430 static int l_right_click(lua_State *L)
2432 ObjectRef *ref = checkobject(L, 1);
2433 ObjectRef *ref2 = checkobject(L, 2);
2434 ServerActiveObject *co = getobject(ref);
2435 ServerActiveObject *co2 = getobject(ref2);
2436 if(co == NULL) return 0;
2437 if(co2 == NULL) return 0;
2439 co->rightClick(co2);
2444 // hp = number of hitpoints (2 * number of hearts)
2446 static int l_set_hp(lua_State *L)
2448 ObjectRef *ref = checkobject(L, 1);
2449 luaL_checknumber(L, 2);
2450 ServerActiveObject *co = getobject(ref);
2451 if(co == NULL) return 0;
2452 int hp = lua_tonumber(L, 2);
2453 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2454 <<" hp="<<hp<<std::endl;*/
2462 // returns: number of hitpoints (2 * number of hearts)
2463 // 0 if not applicable to this type of object
2464 static int l_get_hp(lua_State *L)
2466 ObjectRef *ref = checkobject(L, 1);
2467 ServerActiveObject *co = getobject(ref);
2470 lua_pushnumber(L, 1);
2473 int hp = co->getHP();
2474 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2475 <<" hp="<<hp<<std::endl;*/
2477 lua_pushnumber(L, hp);
2481 // get_inventory(self)
2482 static int l_get_inventory(lua_State *L)
2484 ObjectRef *ref = checkobject(L, 1);
2485 ServerActiveObject *co = getobject(ref);
2486 if(co == NULL) return 0;
2488 InventoryLocation loc = co->getInventoryLocation();
2489 if(get_server(L)->getInventory(loc) != NULL)
2490 InvRef::create(L, loc);
2492 lua_pushnil(L); // An object may have no inventory (nil)
2496 // get_wield_list(self)
2497 static int l_get_wield_list(lua_State *L)
2499 ObjectRef *ref = checkobject(L, 1);
2500 ServerActiveObject *co = getobject(ref);
2501 if(co == NULL) return 0;
2503 lua_pushstring(L, co->getWieldList().c_str());
2507 // get_wield_index(self)
2508 static int l_get_wield_index(lua_State *L)
2510 ObjectRef *ref = checkobject(L, 1);
2511 ServerActiveObject *co = getobject(ref);
2512 if(co == NULL) return 0;
2514 lua_pushinteger(L, co->getWieldIndex() + 1);
2518 // get_wielded_item(self)
2519 static int l_get_wielded_item(lua_State *L)
2521 ObjectRef *ref = checkobject(L, 1);
2522 ServerActiveObject *co = getobject(ref);
2525 LuaItemStack::create(L, ItemStack());
2529 LuaItemStack::create(L, co->getWieldedItem());
2533 // set_wielded_item(self, itemstack or itemstring or table or nil)
2534 static int l_set_wielded_item(lua_State *L)
2536 ObjectRef *ref = checkobject(L, 1);
2537 ServerActiveObject *co = getobject(ref);
2538 if(co == NULL) return 0;
2540 ItemStack item = read_item(L, 2);
2541 bool success = co->setWieldedItem(item);
2542 lua_pushboolean(L, success);
2546 // set_armor_groups(self, groups)
2547 static int l_set_armor_groups(lua_State *L)
2549 ObjectRef *ref = checkobject(L, 1);
2550 ServerActiveObject *co = getobject(ref);
2551 if(co == NULL) return 0;
2553 ItemGroupList groups;
2554 read_groups(L, 2, groups);
2555 co->setArmorGroups(groups);
2559 // set_properties(self, properties)
2560 static int l_set_properties(lua_State *L)
2562 ObjectRef *ref = checkobject(L, 1);
2563 ServerActiveObject *co = getobject(ref);
2564 if(co == NULL) return 0;
2565 ObjectProperties *prop = co->accessObjectProperties();
2568 read_object_properties(L, 2, prop);
2569 co->notifyObjectPropertiesModified();
2573 /* LuaEntitySAO-only */
2575 // setvelocity(self, {x=num, y=num, z=num})
2576 static int l_setvelocity(lua_State *L)
2578 ObjectRef *ref = checkobject(L, 1);
2579 LuaEntitySAO *co = getluaobject(ref);
2580 if(co == NULL) return 0;
2581 v3f pos = checkFloatPos(L, 2);
2583 co->setVelocity(pos);
2587 // getvelocity(self)
2588 static int l_getvelocity(lua_State *L)
2590 ObjectRef *ref = checkobject(L, 1);
2591 LuaEntitySAO *co = getluaobject(ref);
2592 if(co == NULL) return 0;
2594 v3f v = co->getVelocity();
2599 // setacceleration(self, {x=num, y=num, z=num})
2600 static int l_setacceleration(lua_State *L)
2602 ObjectRef *ref = checkobject(L, 1);
2603 LuaEntitySAO *co = getluaobject(ref);
2604 if(co == NULL) return 0;
2606 v3f pos = checkFloatPos(L, 2);
2608 co->setAcceleration(pos);
2612 // getacceleration(self)
2613 static int l_getacceleration(lua_State *L)
2615 ObjectRef *ref = checkobject(L, 1);
2616 LuaEntitySAO *co = getluaobject(ref);
2617 if(co == NULL) return 0;
2619 v3f v = co->getAcceleration();
2624 // setyaw(self, radians)
2625 static int l_setyaw(lua_State *L)
2627 ObjectRef *ref = checkobject(L, 1);
2628 LuaEntitySAO *co = getluaobject(ref);
2629 if(co == NULL) return 0;
2630 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2637 static int l_getyaw(lua_State *L)
2639 ObjectRef *ref = checkobject(L, 1);
2640 LuaEntitySAO *co = getluaobject(ref);
2641 if(co == NULL) return 0;
2643 float yaw = co->getYaw() * core::DEGTORAD;
2644 lua_pushnumber(L, yaw);
2648 // settexturemod(self, mod)
2649 static int l_settexturemod(lua_State *L)
2651 ObjectRef *ref = checkobject(L, 1);
2652 LuaEntitySAO *co = getluaobject(ref);
2653 if(co == NULL) return 0;
2655 std::string mod = luaL_checkstring(L, 2);
2656 co->setTextureMod(mod);
2660 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2661 // select_horiz_by_yawpitch=false)
2662 static int l_setsprite(lua_State *L)
2664 ObjectRef *ref = checkobject(L, 1);
2665 LuaEntitySAO *co = getluaobject(ref);
2666 if(co == NULL) return 0;
2669 if(!lua_isnil(L, 2))
2670 p = read_v2s16(L, 2);
2672 if(!lua_isnil(L, 3))
2673 num_frames = lua_tonumber(L, 3);
2674 float framelength = 0.2;
2675 if(!lua_isnil(L, 4))
2676 framelength = lua_tonumber(L, 4);
2677 bool select_horiz_by_yawpitch = false;
2678 if(!lua_isnil(L, 5))
2679 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2680 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2685 // get_entity_name(self)
2686 static int l_get_entity_name(lua_State *L)
2688 ObjectRef *ref = checkobject(L, 1);
2689 LuaEntitySAO *co = getluaobject(ref);
2690 if(co == NULL) return 0;
2692 std::string name = co->getName();
2693 lua_pushstring(L, name.c_str());
2697 // get_luaentity(self)
2698 static int l_get_luaentity(lua_State *L)
2700 ObjectRef *ref = checkobject(L, 1);
2701 LuaEntitySAO *co = getluaobject(ref);
2702 if(co == NULL) return 0;
2704 luaentity_get(L, co->getId());
2711 static int l_is_player(lua_State *L)
2713 ObjectRef *ref = checkobject(L, 1);
2714 Player *player = getplayer(ref);
2715 lua_pushboolean(L, (player != NULL));
2719 // get_player_name(self)
2720 static int l_get_player_name(lua_State *L)
2722 ObjectRef *ref = checkobject(L, 1);
2723 Player *player = getplayer(ref);
2725 lua_pushlstring(L, "", 0);
2729 lua_pushstring(L, player->getName());
2733 // get_look_dir(self)
2734 static int l_get_look_dir(lua_State *L)
2736 ObjectRef *ref = checkobject(L, 1);
2737 Player *player = getplayer(ref);
2738 if(player == NULL) return 0;
2740 float pitch = player->getRadPitch();
2741 float yaw = player->getRadYaw();
2742 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2747 // get_look_pitch(self)
2748 static int l_get_look_pitch(lua_State *L)
2750 ObjectRef *ref = checkobject(L, 1);
2751 Player *player = getplayer(ref);
2752 if(player == NULL) return 0;
2754 lua_pushnumber(L, player->getRadPitch());
2758 // get_look_yaw(self)
2759 static int l_get_look_yaw(lua_State *L)
2761 ObjectRef *ref = checkobject(L, 1);
2762 Player *player = getplayer(ref);
2763 if(player == NULL) return 0;
2765 lua_pushnumber(L, player->getRadYaw());
2770 ObjectRef(ServerActiveObject *object):
2773 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2779 infostream<<"ObjectRef destructing for id="
2780 <<m_object->getId()<<std::endl;
2782 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2785 // Creates an ObjectRef and leaves it on top of stack
2786 // Not callable from Lua; all references are created on the C side.
2787 static void create(lua_State *L, ServerActiveObject *object)
2789 ObjectRef *o = new ObjectRef(object);
2790 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2791 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2792 luaL_getmetatable(L, className);
2793 lua_setmetatable(L, -2);
2796 static void set_null(lua_State *L)
2798 ObjectRef *o = checkobject(L, -1);
2802 static void Register(lua_State *L)
2805 int methodtable = lua_gettop(L);
2806 luaL_newmetatable(L, className);
2807 int metatable = lua_gettop(L);
2809 lua_pushliteral(L, "__metatable");
2810 lua_pushvalue(L, methodtable);
2811 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2813 lua_pushliteral(L, "__index");
2814 lua_pushvalue(L, methodtable);
2815 lua_settable(L, metatable);
2817 lua_pushliteral(L, "__gc");
2818 lua_pushcfunction(L, gc_object);
2819 lua_settable(L, metatable);
2821 lua_pop(L, 1); // drop metatable
2823 luaL_openlib(L, 0, methods, 0); // fill methodtable
2824 lua_pop(L, 1); // drop methodtable
2826 // Cannot be created from Lua
2827 //lua_register(L, className, create_object);
2830 const char ObjectRef::className[] = "ObjectRef";
2831 const luaL_reg ObjectRef::methods[] = {
2832 // ServerActiveObject
2833 method(ObjectRef, remove),
2834 method(ObjectRef, getpos),
2835 method(ObjectRef, setpos),
2836 method(ObjectRef, moveto),
2837 method(ObjectRef, punch),
2838 method(ObjectRef, right_click),
2839 method(ObjectRef, set_hp),
2840 method(ObjectRef, get_hp),
2841 method(ObjectRef, get_inventory),
2842 method(ObjectRef, get_wield_list),
2843 method(ObjectRef, get_wield_index),
2844 method(ObjectRef, get_wielded_item),
2845 method(ObjectRef, set_wielded_item),
2846 method(ObjectRef, set_armor_groups),
2847 method(ObjectRef, set_properties),
2848 // LuaEntitySAO-only
2849 method(ObjectRef, setvelocity),
2850 method(ObjectRef, getvelocity),
2851 method(ObjectRef, setacceleration),
2852 method(ObjectRef, getacceleration),
2853 method(ObjectRef, setyaw),
2854 method(ObjectRef, getyaw),
2855 method(ObjectRef, settexturemod),
2856 method(ObjectRef, setsprite),
2857 method(ObjectRef, get_entity_name),
2858 method(ObjectRef, get_luaentity),
2860 method(ObjectRef, get_player_name),
2861 method(ObjectRef, get_look_dir),
2862 method(ObjectRef, get_look_pitch),
2863 method(ObjectRef, get_look_yaw),
2867 // Creates a new anonymous reference if cobj=NULL or id=0
2868 static void objectref_get_or_create(lua_State *L,
2869 ServerActiveObject *cobj)
2871 if(cobj == NULL || cobj->getId() == 0){
2872 ObjectRef::create(L, cobj);
2874 objectref_get(L, cobj->getId());
2883 class LuaPerlinNoise
2890 static const char className[];
2891 static const luaL_reg methods[];
2893 // Exported functions
2895 // garbage collector
2896 static int gc_object(lua_State *L)
2898 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
2903 static int l_get2d(lua_State *L)
2905 LuaPerlinNoise *o = checkobject(L, 1);
2906 v2f pos2d = read_v2f(L,2);
2907 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
2908 lua_pushnumber(L, val);
2911 static int l_get3d(lua_State *L)
2913 LuaPerlinNoise *o = checkobject(L, 1);
2914 v3f pos3d = read_v3f(L,2);
2915 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
2916 lua_pushnumber(L, val);
2921 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
2925 persistence(a_persistence),
2934 // LuaPerlinNoise(seed, octaves, persistence, scale)
2935 // Creates an LuaPerlinNoise and leaves it on top of stack
2936 static int create_object(lua_State *L)
2938 int seed = luaL_checkint(L, 1);
2939 int octaves = luaL_checkint(L, 2);
2940 double persistence = luaL_checknumber(L, 3);
2941 double scale = luaL_checknumber(L, 4);
2942 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
2943 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2944 luaL_getmetatable(L, className);
2945 lua_setmetatable(L, -2);
2949 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
2951 luaL_checktype(L, narg, LUA_TUSERDATA);
2952 void *ud = luaL_checkudata(L, narg, className);
2953 if(!ud) luaL_typerror(L, narg, className);
2954 return *(LuaPerlinNoise**)ud; // unbox pointer
2957 static void Register(lua_State *L)
2960 int methodtable = lua_gettop(L);
2961 luaL_newmetatable(L, className);
2962 int metatable = lua_gettop(L);
2964 lua_pushliteral(L, "__metatable");
2965 lua_pushvalue(L, methodtable);
2966 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2968 lua_pushliteral(L, "__index");
2969 lua_pushvalue(L, methodtable);
2970 lua_settable(L, metatable);
2972 lua_pushliteral(L, "__gc");
2973 lua_pushcfunction(L, gc_object);
2974 lua_settable(L, metatable);
2976 lua_pop(L, 1); // drop metatable
2978 luaL_openlib(L, 0, methods, 0); // fill methodtable
2979 lua_pop(L, 1); // drop methodtable
2981 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
2982 lua_register(L, className, create_object);
2985 const char LuaPerlinNoise::className[] = "PerlinNoise";
2986 const luaL_reg LuaPerlinNoise::methods[] = {
2987 method(LuaPerlinNoise, get2d),
2988 method(LuaPerlinNoise, get3d),
2999 ServerEnvironment *m_env;
3001 static const char className[];
3002 static const luaL_reg methods[];
3004 static int gc_object(lua_State *L) {
3005 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3010 static EnvRef *checkobject(lua_State *L, int narg)
3012 luaL_checktype(L, narg, LUA_TUSERDATA);
3013 void *ud = luaL_checkudata(L, narg, className);
3014 if(!ud) luaL_typerror(L, narg, className);
3015 return *(EnvRef**)ud; // unbox pointer
3018 // Exported functions
3020 // EnvRef:set_node(pos, node)
3021 // pos = {x=num, y=num, z=num}
3022 static int l_set_node(lua_State *L)
3024 EnvRef *o = checkobject(L, 1);
3025 ServerEnvironment *env = o->m_env;
3026 if(env == NULL) return 0;
3028 v3s16 pos = read_v3s16(L, 2);
3030 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3033 MapNode n_old = env->getMap().getNodeNoEx(pos);
3034 scriptapi_node_on_destruct(L, pos, n_old);
3036 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3037 lua_pushboolean(L, succeeded);
3040 scriptapi_node_on_construct(L, pos, n);
3044 static int l_add_node(lua_State *L)
3046 return l_set_node(L);
3049 // EnvRef:remove_node(pos)
3050 // pos = {x=num, y=num, z=num}
3051 static int l_remove_node(lua_State *L)
3053 EnvRef *o = checkobject(L, 1);
3054 ServerEnvironment *env = o->m_env;
3055 if(env == NULL) return 0;
3056 v3s16 pos = read_v3s16(L, 2);
3059 MapNode n = env->getMap().getNodeNoEx(pos);
3060 scriptapi_node_on_destruct(L, pos, n);
3062 // This is slightly optimized compared to addNodeWithEvent(air)
3063 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3064 lua_pushboolean(L, succeeded);
3065 // Air doesn't require constructor
3069 // EnvRef:get_node(pos)
3070 // pos = {x=num, y=num, z=num}
3071 static int l_get_node(lua_State *L)
3073 EnvRef *o = checkobject(L, 1);
3074 ServerEnvironment *env = o->m_env;
3075 if(env == NULL) return 0;
3077 v3s16 pos = read_v3s16(L, 2);
3079 MapNode n = env->getMap().getNodeNoEx(pos);
3081 pushnode(L, n, env->getGameDef()->ndef());
3085 // EnvRef:get_node_or_nil(pos)
3086 // pos = {x=num, y=num, z=num}
3087 static int l_get_node_or_nil(lua_State *L)
3089 EnvRef *o = checkobject(L, 1);
3090 ServerEnvironment *env = o->m_env;
3091 if(env == NULL) return 0;
3093 v3s16 pos = read_v3s16(L, 2);
3096 MapNode n = env->getMap().getNode(pos);
3098 pushnode(L, n, env->getGameDef()->ndef());
3100 } catch(InvalidPositionException &e)
3107 // EnvRef:get_node_light(pos, timeofday)
3108 // pos = {x=num, y=num, z=num}
3109 // timeofday: nil = current time, 0 = night, 0.5 = day
3110 static int l_get_node_light(lua_State *L)
3112 EnvRef *o = checkobject(L, 1);
3113 ServerEnvironment *env = o->m_env;
3114 if(env == NULL) return 0;
3116 v3s16 pos = read_v3s16(L, 2);
3117 u32 time_of_day = env->getTimeOfDay();
3118 if(lua_isnumber(L, 3))
3119 time_of_day = 24000.0 * lua_tonumber(L, 3);
3120 time_of_day %= 24000;
3121 u32 dnr = time_to_daynight_ratio(time_of_day);
3122 MapNode n = env->getMap().getNodeNoEx(pos);
3124 MapNode n = env->getMap().getNode(pos);
3125 INodeDefManager *ndef = env->getGameDef()->ndef();
3126 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3128 } catch(InvalidPositionException &e)
3135 // EnvRef:place_node(pos, node)
3136 // pos = {x=num, y=num, z=num}
3137 static int l_place_node(lua_State *L)
3139 EnvRef *o = checkobject(L, 1);
3140 ServerEnvironment *env = o->m_env;
3141 if(env == NULL) return 0;
3142 v3s16 pos = read_v3s16(L, 2);
3143 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3145 // Don't attempt to load non-loaded area as of now
3146 MapNode n_old = env->getMap().getNodeNoEx(pos);
3147 if(n_old.getContent() == CONTENT_IGNORE){
3148 lua_pushboolean(L, false);
3151 // Create item to place
3152 INodeDefManager *ndef = get_server(L)->ndef();
3153 IItemDefManager *idef = get_server(L)->idef();
3154 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3155 // Make pointed position
3156 PointedThing pointed;
3157 pointed.type = POINTEDTHING_NODE;
3158 pointed.node_abovesurface = pos;
3159 pointed.node_undersurface = pos + v3s16(0,-1,0);
3160 // Place it with a NULL placer (appears in Lua as a non-functional
3162 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3163 lua_pushboolean(L, success);
3167 // EnvRef:dig_node(pos)
3168 // pos = {x=num, y=num, z=num}
3169 static int l_dig_node(lua_State *L)
3171 EnvRef *o = checkobject(L, 1);
3172 ServerEnvironment *env = o->m_env;
3173 if(env == NULL) return 0;
3174 v3s16 pos = read_v3s16(L, 2);
3176 // Don't attempt to load non-loaded area as of now
3177 MapNode n = env->getMap().getNodeNoEx(pos);
3178 if(n.getContent() == CONTENT_IGNORE){
3179 lua_pushboolean(L, false);
3182 // Dig it out with a NULL digger (appears in Lua as a
3183 // non-functional ObjectRef)
3184 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3185 lua_pushboolean(L, success);
3189 // EnvRef:punch_node(pos)
3190 // pos = {x=num, y=num, z=num}
3191 static int l_punch_node(lua_State *L)
3193 EnvRef *o = checkobject(L, 1);
3194 ServerEnvironment *env = o->m_env;
3195 if(env == NULL) return 0;
3196 v3s16 pos = read_v3s16(L, 2);
3198 // Don't attempt to load non-loaded area as of now
3199 MapNode n = env->getMap().getNodeNoEx(pos);
3200 if(n.getContent() == CONTENT_IGNORE){
3201 lua_pushboolean(L, false);
3204 // Punch it with a NULL puncher (appears in Lua as a non-functional
3206 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3207 lua_pushboolean(L, success);
3211 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3212 // pos = {x=num, y=num, z=num}
3213 static int l_add_entity(lua_State *L)
3215 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3216 EnvRef *o = checkobject(L, 1);
3217 ServerEnvironment *env = o->m_env;
3218 if(env == NULL) return 0;
3220 v3f pos = checkFloatPos(L, 2);
3222 const char *name = luaL_checkstring(L, 3);
3224 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3225 int objectid = env->addActiveObject(obj);
3226 // If failed to add, return nothing (reads as nil)
3230 objectref_get_or_create(L, obj);
3234 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3235 // pos = {x=num, y=num, z=num}
3236 static int l_add_item(lua_State *L)
3238 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3239 EnvRef *o = checkobject(L, 1);
3240 ServerEnvironment *env = o->m_env;
3241 if(env == NULL) return 0;
3243 v3f pos = checkFloatPos(L, 2);
3245 ItemStack item = read_item(L, 3);
3246 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3248 // Use minetest.spawn_item to spawn a __builtin:item
3249 lua_getglobal(L, "minetest");
3250 lua_getfield(L, -1, "spawn_item");
3251 if(lua_isnil(L, -1))
3253 lua_pushvalue(L, 2);
3254 lua_pushstring(L, item.getItemString().c_str());
3255 if(lua_pcall(L, 2, 1, 0))
3256 script_error(L, "error: %s", lua_tostring(L, -1));
3258 /*lua_pushvalue(L, 1);
3259 lua_pushstring(L, "__builtin:item");
3260 lua_pushstring(L, item.getItemString().c_str());
3261 return l_add_entity(L);*/
3263 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3264 int objectid = env->addActiveObject(obj);
3265 // If failed to add, return nothing (reads as nil)
3269 objectref_get_or_create(L, obj);
3273 // EnvRef:add_rat(pos)
3274 // pos = {x=num, y=num, z=num}
3275 static int l_add_rat(lua_State *L)
3277 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3278 <<" Doing nothing."<<std::endl;
3282 // EnvRef:add_firefly(pos)
3283 // pos = {x=num, y=num, z=num}
3284 static int l_add_firefly(lua_State *L)
3286 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3287 <<" Doing nothing."<<std::endl;
3291 // EnvRef:get_meta(pos)
3292 static int l_get_meta(lua_State *L)
3294 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3295 EnvRef *o = checkobject(L, 1);
3296 ServerEnvironment *env = o->m_env;
3297 if(env == NULL) return 0;
3299 v3s16 p = read_v3s16(L, 2);
3300 NodeMetaRef::create(L, p, env);
3304 // EnvRef:get_player_by_name(name)
3305 static int l_get_player_by_name(lua_State *L)
3307 EnvRef *o = checkobject(L, 1);
3308 ServerEnvironment *env = o->m_env;
3309 if(env == NULL) return 0;
3311 const char *name = luaL_checkstring(L, 2);
3312 Player *player = env->getPlayer(name);
3317 PlayerSAO *sao = player->getPlayerSAO();
3322 // Put player on stack
3323 objectref_get_or_create(L, sao);
3327 // EnvRef:get_objects_inside_radius(pos, radius)
3328 static int l_get_objects_inside_radius(lua_State *L)
3330 // Get the table insert function
3331 lua_getglobal(L, "table");
3332 lua_getfield(L, -1, "insert");
3333 int table_insert = lua_gettop(L);
3335 EnvRef *o = checkobject(L, 1);
3336 ServerEnvironment *env = o->m_env;
3337 if(env == NULL) return 0;
3339 v3f pos = checkFloatPos(L, 2);
3340 float radius = luaL_checknumber(L, 3) * BS;
3341 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3343 int table = lua_gettop(L);
3344 for(std::set<u16>::const_iterator
3345 i = ids.begin(); i != ids.end(); i++){
3346 ServerActiveObject *obj = env->getActiveObject(*i);
3347 // Insert object reference into table
3348 lua_pushvalue(L, table_insert);
3349 lua_pushvalue(L, table);
3350 objectref_get_or_create(L, obj);
3351 if(lua_pcall(L, 2, 0, 0))
3352 script_error(L, "error: %s", lua_tostring(L, -1));
3357 // EnvRef:set_timeofday(val)
3359 static int l_set_timeofday(lua_State *L)
3361 EnvRef *o = checkobject(L, 1);
3362 ServerEnvironment *env = o->m_env;
3363 if(env == NULL) return 0;
3365 float timeofday_f = luaL_checknumber(L, 2);
3366 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3367 int timeofday_mh = (int)(timeofday_f * 24000.0);
3368 // This should be set directly in the environment but currently
3369 // such changes aren't immediately sent to the clients, so call
3370 // the server instead.
3371 //env->setTimeOfDay(timeofday_mh);
3372 get_server(L)->setTimeOfDay(timeofday_mh);
3376 // EnvRef:get_timeofday() -> 0...1
3377 static int l_get_timeofday(lua_State *L)
3379 EnvRef *o = checkobject(L, 1);
3380 ServerEnvironment *env = o->m_env;
3381 if(env == NULL) return 0;
3383 int timeofday_mh = env->getTimeOfDay();
3384 float timeofday_f = (float)timeofday_mh / 24000.0;
3385 lua_pushnumber(L, timeofday_f);
3390 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3391 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3392 static int l_find_node_near(lua_State *L)
3394 EnvRef *o = checkobject(L, 1);
3395 ServerEnvironment *env = o->m_env;
3396 if(env == NULL) return 0;
3397 INodeDefManager *ndef = get_server(L)->ndef();
3398 v3s16 pos = read_v3s16(L, 2);
3399 int radius = luaL_checkinteger(L, 3);
3400 std::set<content_t> filter;
3401 if(lua_istable(L, 4)){
3404 while(lua_next(L, table) != 0){
3405 // key at index -2 and value at index -1
3406 luaL_checktype(L, -1, LUA_TSTRING);
3407 ndef->getIds(lua_tostring(L, -1), filter);
3408 // removes value, keeps key for next iteration
3411 } else if(lua_isstring(L, 4)){
3412 ndef->getIds(lua_tostring(L, 4), filter);
3415 for(int d=1; d<=radius; d++){
3416 core::list<v3s16> list;
3417 getFacePositions(list, d);
3418 for(core::list<v3s16>::Iterator i = list.begin();
3419 i != list.end(); i++){
3420 v3s16 p = pos + (*i);
3421 content_t c = env->getMap().getNodeNoEx(p).getContent();
3422 if(filter.count(c) != 0){
3431 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3432 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3433 static int l_find_nodes_in_area(lua_State *L)
3435 EnvRef *o = checkobject(L, 1);
3436 ServerEnvironment *env = o->m_env;
3437 if(env == NULL) return 0;
3438 INodeDefManager *ndef = get_server(L)->ndef();
3439 v3s16 minp = read_v3s16(L, 2);
3440 v3s16 maxp = read_v3s16(L, 3);
3441 std::set<content_t> filter;
3442 if(lua_istable(L, 4)){
3445 while(lua_next(L, table) != 0){
3446 // key at index -2 and value at index -1
3447 luaL_checktype(L, -1, LUA_TSTRING);
3448 ndef->getIds(lua_tostring(L, -1), filter);
3449 // removes value, keeps key for next iteration
3452 } else if(lua_isstring(L, 4)){
3453 ndef->getIds(lua_tostring(L, 4), filter);
3456 // Get the table insert function
3457 lua_getglobal(L, "table");
3458 lua_getfield(L, -1, "insert");
3459 int table_insert = lua_gettop(L);
3462 int table = lua_gettop(L);
3463 for(s16 x=minp.X; x<=maxp.X; x++)
3464 for(s16 y=minp.Y; y<=maxp.Y; y++)
3465 for(s16 z=minp.Z; z<=maxp.Z; z++)
3468 content_t c = env->getMap().getNodeNoEx(p).getContent();
3469 if(filter.count(c) != 0){
3470 lua_pushvalue(L, table_insert);
3471 lua_pushvalue(L, table);
3473 if(lua_pcall(L, 2, 0, 0))
3474 script_error(L, "error: %s", lua_tostring(L, -1));
3480 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3481 // returns world-specific PerlinNoise
3482 static int l_get_perlin(lua_State *L)
3484 EnvRef *o = checkobject(L, 1);
3485 ServerEnvironment *env = o->m_env;
3486 if(env == NULL) return 0;
3488 int seeddiff = luaL_checkint(L, 2);
3489 int octaves = luaL_checkint(L, 3);
3490 double persistence = luaL_checknumber(L, 4);
3491 double scale = luaL_checknumber(L, 5);
3493 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3494 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3495 luaL_getmetatable(L, "PerlinNoise");
3496 lua_setmetatable(L, -2);
3501 EnvRef(ServerEnvironment *env):
3504 //infostream<<"EnvRef created"<<std::endl;
3509 //infostream<<"EnvRef destructing"<<std::endl;
3512 // Creates an EnvRef and leaves it on top of stack
3513 // Not callable from Lua; all references are created on the C side.
3514 static void create(lua_State *L, ServerEnvironment *env)
3516 EnvRef *o = new EnvRef(env);
3517 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3518 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3519 luaL_getmetatable(L, className);
3520 lua_setmetatable(L, -2);
3523 static void set_null(lua_State *L)
3525 EnvRef *o = checkobject(L, -1);
3529 static void Register(lua_State *L)
3532 int methodtable = lua_gettop(L);
3533 luaL_newmetatable(L, className);
3534 int metatable = lua_gettop(L);
3536 lua_pushliteral(L, "__metatable");
3537 lua_pushvalue(L, methodtable);
3538 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3540 lua_pushliteral(L, "__index");
3541 lua_pushvalue(L, methodtable);
3542 lua_settable(L, metatable);
3544 lua_pushliteral(L, "__gc");
3545 lua_pushcfunction(L, gc_object);
3546 lua_settable(L, metatable);
3548 lua_pop(L, 1); // drop metatable
3550 luaL_openlib(L, 0, methods, 0); // fill methodtable
3551 lua_pop(L, 1); // drop methodtable
3553 // Cannot be created from Lua
3554 //lua_register(L, className, create_object);
3557 const char EnvRef::className[] = "EnvRef";
3558 const luaL_reg EnvRef::methods[] = {
3559 method(EnvRef, set_node),
3560 method(EnvRef, add_node),
3561 method(EnvRef, remove_node),
3562 method(EnvRef, get_node),
3563 method(EnvRef, get_node_or_nil),
3564 method(EnvRef, get_node_light),
3565 method(EnvRef, place_node),
3566 method(EnvRef, dig_node),
3567 method(EnvRef, punch_node),
3568 method(EnvRef, add_entity),
3569 method(EnvRef, add_item),
3570 method(EnvRef, add_rat),
3571 method(EnvRef, add_firefly),
3572 method(EnvRef, get_meta),
3573 method(EnvRef, get_player_by_name),
3574 method(EnvRef, get_objects_inside_radius),
3575 method(EnvRef, set_timeofday),
3576 method(EnvRef, get_timeofday),
3577 method(EnvRef, find_node_near),
3578 method(EnvRef, find_nodes_in_area),
3579 method(EnvRef, get_perlin),
3588 class LuaPseudoRandom
3591 PseudoRandom m_pseudo;
3593 static const char className[];
3594 static const luaL_reg methods[];
3596 // Exported functions
3598 // garbage collector
3599 static int gc_object(lua_State *L)
3601 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3606 // next(self, min=0, max=32767) -> get next value
3607 static int l_next(lua_State *L)
3609 LuaPseudoRandom *o = checkobject(L, 1);
3612 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3613 if(!lua_isnil(L, 2))
3614 min = luaL_checkinteger(L, 2);
3615 if(!lua_isnil(L, 3))
3616 max = luaL_checkinteger(L, 3);
3617 if(max - min != 32767 && max - min > 32767/5)
3618 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.");
3619 PseudoRandom &pseudo = o->m_pseudo;
3620 int val = pseudo.next();
3621 val = (val % (max-min+1)) + min;
3622 lua_pushinteger(L, val);
3627 LuaPseudoRandom(int seed):
3636 const PseudoRandom& getItem() const
3640 PseudoRandom& getItem()
3645 // LuaPseudoRandom(seed)
3646 // Creates an LuaPseudoRandom and leaves it on top of stack
3647 static int create_object(lua_State *L)
3649 int seed = luaL_checknumber(L, 1);
3650 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3651 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3652 luaL_getmetatable(L, className);
3653 lua_setmetatable(L, -2);
3657 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3659 luaL_checktype(L, narg, LUA_TUSERDATA);
3660 void *ud = luaL_checkudata(L, narg, className);
3661 if(!ud) luaL_typerror(L, narg, className);
3662 return *(LuaPseudoRandom**)ud; // unbox pointer
3665 static void Register(lua_State *L)
3668 int methodtable = lua_gettop(L);
3669 luaL_newmetatable(L, className);
3670 int metatable = lua_gettop(L);
3672 lua_pushliteral(L, "__metatable");
3673 lua_pushvalue(L, methodtable);
3674 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3676 lua_pushliteral(L, "__index");
3677 lua_pushvalue(L, methodtable);
3678 lua_settable(L, metatable);
3680 lua_pushliteral(L, "__gc");
3681 lua_pushcfunction(L, gc_object);
3682 lua_settable(L, metatable);
3684 lua_pop(L, 1); // drop metatable
3686 luaL_openlib(L, 0, methods, 0); // fill methodtable
3687 lua_pop(L, 1); // drop methodtable
3689 // Can be created from Lua (LuaPseudoRandom(seed))
3690 lua_register(L, className, create_object);
3693 const char LuaPseudoRandom::className[] = "PseudoRandom";
3694 const luaL_reg LuaPseudoRandom::methods[] = {
3695 method(LuaPseudoRandom, next),
3705 class LuaABM : public ActiveBlockModifier
3711 std::set<std::string> m_trigger_contents;
3712 std::set<std::string> m_required_neighbors;
3713 float m_trigger_interval;
3714 u32 m_trigger_chance;
3716 LuaABM(lua_State *L, int id,
3717 const std::set<std::string> &trigger_contents,
3718 const std::set<std::string> &required_neighbors,
3719 float trigger_interval, u32 trigger_chance):
3722 m_trigger_contents(trigger_contents),
3723 m_required_neighbors(required_neighbors),
3724 m_trigger_interval(trigger_interval),
3725 m_trigger_chance(trigger_chance)
3728 virtual std::set<std::string> getTriggerContents()
3730 return m_trigger_contents;
3732 virtual std::set<std::string> getRequiredNeighbors()
3734 return m_required_neighbors;
3736 virtual float getTriggerInterval()
3738 return m_trigger_interval;
3740 virtual u32 getTriggerChance()
3742 return m_trigger_chance;
3744 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3745 u32 active_object_count, u32 active_object_count_wider)
3747 lua_State *L = m_lua;
3750 assert(lua_checkstack(L, 20));
3751 StackUnroller stack_unroller(L);
3753 // Get minetest.registered_abms
3754 lua_getglobal(L, "minetest");
3755 lua_getfield(L, -1, "registered_abms");
3756 luaL_checktype(L, -1, LUA_TTABLE);
3757 int registered_abms = lua_gettop(L);
3759 // Get minetest.registered_abms[m_id]
3760 lua_pushnumber(L, m_id);
3761 lua_gettable(L, registered_abms);
3762 if(lua_isnil(L, -1))
3766 luaL_checktype(L, -1, LUA_TTABLE);
3767 lua_getfield(L, -1, "action");
3768 luaL_checktype(L, -1, LUA_TFUNCTION);
3770 pushnode(L, n, env->getGameDef()->ndef());
3771 lua_pushnumber(L, active_object_count);
3772 lua_pushnumber(L, active_object_count_wider);
3773 if(lua_pcall(L, 4, 0, 0))
3774 script_error(L, "error: %s", lua_tostring(L, -1));
3782 static void read_server_sound_params(lua_State *L, int index,
3783 ServerSoundParams ¶ms)
3786 index = lua_gettop(L) + 1 + index;
3788 params = ServerSoundParams();
3789 if(lua_istable(L, index)){
3790 getfloatfield(L, index, "gain", params.gain);
3791 getstringfield(L, index, "to_player", params.to_player);
3792 lua_getfield(L, index, "pos");
3793 if(!lua_isnil(L, -1)){
3794 v3f p = read_v3f(L, -1)*BS;
3796 params.type = ServerSoundParams::SSP_POSITIONAL;
3799 lua_getfield(L, index, "object");
3800 if(!lua_isnil(L, -1)){
3801 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3802 ServerActiveObject *sao = ObjectRef::getobject(ref);
3804 params.object = sao->getId();
3805 params.type = ServerSoundParams::SSP_OBJECT;
3809 params.max_hear_distance = BS*getfloatfield_default(L, index,
3810 "max_hear_distance", params.max_hear_distance/BS);
3811 getboolfield(L, index, "loop", params.loop);
3820 // Writes a line to dstream
3821 static int l_debug(lua_State *L)
3823 std::string text = lua_tostring(L, 1);
3824 dstream << text << std::endl;
3828 // log([level,] text)
3829 // Writes a line to the logger.
3830 // The one-argument version logs to infostream.
3831 // The two-argument version accept a log level: error, action, info, or verbose.
3832 static int l_log(lua_State *L)
3835 LogMessageLevel level = LMT_INFO;
3836 if(lua_isnone(L, 2))
3838 text = lua_tostring(L, 1);
3842 std::string levelname = lua_tostring(L, 1);
3843 text = lua_tostring(L, 2);
3844 if(levelname == "error")
3846 else if(levelname == "action")
3848 else if(levelname == "verbose")
3849 level = LMT_VERBOSE;
3851 log_printline(level, text);
3855 // register_item_raw({lots of stuff})
3856 static int l_register_item_raw(lua_State *L)
3858 luaL_checktype(L, 1, LUA_TTABLE);
3861 // Get the writable item and node definition managers from the server
3862 IWritableItemDefManager *idef =
3863 get_server(L)->getWritableItemDefManager();
3864 IWritableNodeDefManager *ndef =
3865 get_server(L)->getWritableNodeDefManager();
3867 // Check if name is defined
3868 lua_getfield(L, table, "name");
3869 if(lua_isstring(L, -1)){
3870 std::string name = lua_tostring(L, -1);
3871 verbosestream<<"register_item_raw: "<<name<<std::endl;
3873 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3876 // Check if on_use is defined
3878 // Read the item definition and register it
3879 ItemDefinition def = read_item_definition(L, table);
3880 idef->registerItem(def);
3882 // Read the node definition (content features) and register it
3883 if(def.type == ITEM_NODE)
3885 ContentFeatures f = read_content_features(L, table);
3886 ndef->set(f.name, f);
3889 return 0; /* number of results */
3892 // register_alias_raw(name, convert_to_name)
3893 static int l_register_alias_raw(lua_State *L)
3895 std::string name = luaL_checkstring(L, 1);
3896 std::string convert_to = luaL_checkstring(L, 2);
3898 // Get the writable item definition manager from the server
3899 IWritableItemDefManager *idef =
3900 get_server(L)->getWritableItemDefManager();
3902 idef->registerAlias(name, convert_to);
3904 return 0; /* number of results */
3907 // helper for register_craft
3908 static bool read_craft_recipe_shaped(lua_State *L, int index,
3909 int &width, std::vector<std::string> &recipe)
3912 index = lua_gettop(L) + 1 + index;
3914 if(!lua_istable(L, index))
3919 while(lua_next(L, index) != 0){
3921 // key at index -2 and value at index -1
3922 if(!lua_istable(L, -1))
3924 int table2 = lua_gettop(L);
3926 while(lua_next(L, table2) != 0){
3927 // key at index -2 and value at index -1
3928 if(!lua_isstring(L, -1))
3930 recipe.push_back(lua_tostring(L, -1));
3931 // removes value, keeps key for next iteration
3938 if(colcount != width)
3941 // removes value, keeps key for next iteration
3948 // helper for register_craft
3949 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3950 std::vector<std::string> &recipe)
3953 index = lua_gettop(L) + 1 + index;
3955 if(!lua_istable(L, index))
3959 while(lua_next(L, index) != 0){
3960 // key at index -2 and value at index -1
3961 if(!lua_isstring(L, -1))
3963 recipe.push_back(lua_tostring(L, -1));
3964 // removes value, keeps key for next iteration
3970 // helper for register_craft
3971 static bool read_craft_replacements(lua_State *L, int index,
3972 CraftReplacements &replacements)
3975 index = lua_gettop(L) + 1 + index;
3977 if(!lua_istable(L, index))
3981 while(lua_next(L, index) != 0){
3982 // key at index -2 and value at index -1
3983 if(!lua_istable(L, -1))
3985 lua_rawgeti(L, -1, 1);
3986 if(!lua_isstring(L, -1))
3988 std::string replace_from = lua_tostring(L, -1);
3990 lua_rawgeti(L, -1, 2);
3991 if(!lua_isstring(L, -1))
3993 std::string replace_to = lua_tostring(L, -1);
3995 replacements.pairs.push_back(
3996 std::make_pair(replace_from, replace_to));
3997 // removes value, keeps key for next iteration
4002 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4003 static int l_register_craft(lua_State *L)
4005 //infostream<<"register_craft"<<std::endl;
4006 luaL_checktype(L, 1, LUA_TTABLE);
4009 // Get the writable craft definition manager from the server
4010 IWritableCraftDefManager *craftdef =
4011 get_server(L)->getWritableCraftDefManager();
4013 std::string type = getstringfield_default(L, table, "type", "shaped");
4016 CraftDefinitionShaped
4018 if(type == "shaped"){
4019 std::string output = getstringfield_default(L, table, "output", "");
4021 throw LuaError(L, "Crafting definition is missing an output");
4024 std::vector<std::string> recipe;
4025 lua_getfield(L, table, "recipe");
4026 if(lua_isnil(L, -1))
4027 throw LuaError(L, "Crafting definition is missing a recipe"
4028 " (output=\"" + output + "\")");
4029 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4030 throw LuaError(L, "Invalid crafting recipe"
4031 " (output=\"" + output + "\")");
4033 CraftReplacements replacements;
4034 lua_getfield(L, table, "replacements");
4035 if(!lua_isnil(L, -1))
4037 if(!read_craft_replacements(L, -1, replacements))
4038 throw LuaError(L, "Invalid replacements"
4039 " (output=\"" + output + "\")");
4042 CraftDefinition *def = new CraftDefinitionShaped(
4043 output, width, recipe, replacements);
4044 craftdef->registerCraft(def);
4047 CraftDefinitionShapeless
4049 else if(type == "shapeless"){
4050 std::string output = getstringfield_default(L, table, "output", "");
4052 throw LuaError(L, "Crafting definition (shapeless)"
4053 " is missing an output");
4055 std::vector<std::string> recipe;
4056 lua_getfield(L, table, "recipe");
4057 if(lua_isnil(L, -1))
4058 throw LuaError(L, "Crafting definition (shapeless)"
4059 " is missing a recipe"
4060 " (output=\"" + output + "\")");
4061 if(!read_craft_recipe_shapeless(L, -1, recipe))
4062 throw LuaError(L, "Invalid crafting recipe"
4063 " (output=\"" + output + "\")");
4065 CraftReplacements replacements;
4066 lua_getfield(L, table, "replacements");
4067 if(!lua_isnil(L, -1))
4069 if(!read_craft_replacements(L, -1, replacements))
4070 throw LuaError(L, "Invalid replacements"
4071 " (output=\"" + output + "\")");
4074 CraftDefinition *def = new CraftDefinitionShapeless(
4075 output, recipe, replacements);
4076 craftdef->registerCraft(def);
4079 CraftDefinitionToolRepair
4081 else if(type == "toolrepair"){
4082 float additional_wear = getfloatfield_default(L, table,
4083 "additional_wear", 0.0);
4085 CraftDefinition *def = new CraftDefinitionToolRepair(
4087 craftdef->registerCraft(def);
4090 CraftDefinitionCooking
4092 else if(type == "cooking"){
4093 std::string output = getstringfield_default(L, table, "output", "");
4095 throw LuaError(L, "Crafting definition (cooking)"
4096 " is missing an output");
4098 std::string recipe = getstringfield_default(L, table, "recipe", "");
4100 throw LuaError(L, "Crafting definition (cooking)"
4101 " is missing a recipe"
4102 " (output=\"" + output + "\")");
4104 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4106 CraftDefinition *def = new CraftDefinitionCooking(
4107 output, recipe, cooktime);
4108 craftdef->registerCraft(def);
4113 else if(type == "fuel"){
4114 std::string recipe = getstringfield_default(L, table, "recipe", "");
4116 throw LuaError(L, "Crafting definition (fuel)"
4117 " is missing a recipe");
4119 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4121 CraftDefinition *def = new CraftDefinitionFuel(
4123 craftdef->registerCraft(def);
4127 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4131 return 0; /* number of results */
4134 // setting_set(name, value)
4135 static int l_setting_set(lua_State *L)
4137 const char *name = luaL_checkstring(L, 1);
4138 const char *value = luaL_checkstring(L, 2);
4139 g_settings->set(name, value);
4143 // setting_get(name)
4144 static int l_setting_get(lua_State *L)
4146 const char *name = luaL_checkstring(L, 1);
4148 std::string value = g_settings->get(name);
4149 lua_pushstring(L, value.c_str());
4150 } catch(SettingNotFoundException &e){
4156 // setting_getbool(name)
4157 static int l_setting_getbool(lua_State *L)
4159 const char *name = luaL_checkstring(L, 1);
4161 bool value = g_settings->getBool(name);
4162 lua_pushboolean(L, value);
4163 } catch(SettingNotFoundException &e){
4169 // chat_send_all(text)
4170 static int l_chat_send_all(lua_State *L)
4172 const char *text = luaL_checkstring(L, 1);
4173 // Get server from registry
4174 Server *server = get_server(L);
4176 server->notifyPlayers(narrow_to_wide(text));
4180 // chat_send_player(name, text)
4181 static int l_chat_send_player(lua_State *L)
4183 const char *name = luaL_checkstring(L, 1);
4184 const char *text = luaL_checkstring(L, 2);
4185 // Get server from registry
4186 Server *server = get_server(L);
4188 server->notifyPlayer(name, narrow_to_wide(text));
4192 // get_player_privs(name, text)
4193 static int l_get_player_privs(lua_State *L)
4195 const char *name = luaL_checkstring(L, 1);
4196 // Get server from registry
4197 Server *server = get_server(L);
4200 int table = lua_gettop(L);
4201 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4202 for(std::set<std::string>::const_iterator
4203 i = privs_s.begin(); i != privs_s.end(); i++){
4204 lua_pushboolean(L, true);
4205 lua_setfield(L, table, i->c_str());
4207 lua_pushvalue(L, table);
4211 // get_inventory(location)
4212 static int l_get_inventory(lua_State *L)
4214 InventoryLocation loc;
4216 std::string type = checkstringfield(L, 1, "type");
4217 if(type == "player"){
4218 std::string name = checkstringfield(L, 1, "name");
4219 loc.setPlayer(name);
4220 } else if(type == "node"){
4221 lua_getfield(L, 1, "pos");
4222 v3s16 pos = check_v3s16(L, -1);
4223 loc.setNodeMeta(pos);
4226 if(get_server(L)->getInventory(loc) != NULL)
4227 InvRef::create(L, loc);
4233 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4234 static int l_get_dig_params(lua_State *L)
4236 std::map<std::string, int> groups;
4237 read_groups(L, 1, groups);
4238 ToolCapabilities tp = read_tool_capabilities(L, 2);
4239 if(lua_isnoneornil(L, 3))
4240 push_dig_params(L, getDigParams(groups, &tp));
4242 push_dig_params(L, getDigParams(groups, &tp,
4243 luaL_checknumber(L, 3)));
4247 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4248 static int l_get_hit_params(lua_State *L)
4250 std::map<std::string, int> groups;
4251 read_groups(L, 1, groups);
4252 ToolCapabilities tp = read_tool_capabilities(L, 2);
4253 if(lua_isnoneornil(L, 3))
4254 push_hit_params(L, getHitParams(groups, &tp));
4256 push_hit_params(L, getHitParams(groups, &tp,
4257 luaL_checknumber(L, 3)));
4261 // get_current_modname()
4262 static int l_get_current_modname(lua_State *L)
4264 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4268 // get_modpath(modname)
4269 static int l_get_modpath(lua_State *L)
4271 std::string modname = luaL_checkstring(L, 1);
4273 if(modname == "__builtin"){
4274 std::string path = get_server(L)->getBuiltinLuaPath();
4275 lua_pushstring(L, path.c_str());
4278 const ModSpec *mod = get_server(L)->getModSpec(modname);
4283 lua_pushstring(L, mod->path.c_str());
4288 static int l_get_worldpath(lua_State *L)
4290 std::string worldpath = get_server(L)->getWorldPath();
4291 lua_pushstring(L, worldpath.c_str());
4295 // sound_play(spec, parameters)
4296 static int l_sound_play(lua_State *L)
4298 SimpleSoundSpec spec;
4299 read_soundspec(L, 1, spec);
4300 ServerSoundParams params;
4301 read_server_sound_params(L, 2, params);
4302 s32 handle = get_server(L)->playSound(spec, params);
4303 lua_pushinteger(L, handle);
4307 // sound_stop(handle)
4308 static int l_sound_stop(lua_State *L)
4310 int handle = luaL_checkinteger(L, 1);
4311 get_server(L)->stopSound(handle);
4315 // is_singleplayer()
4316 static int l_is_singleplayer(lua_State *L)
4318 lua_pushboolean(L, get_server(L)->isSingleplayer());
4322 // get_password_hash(name, raw_password)
4323 static int l_get_password_hash(lua_State *L)
4325 std::string name = luaL_checkstring(L, 1);
4326 std::string raw_password = luaL_checkstring(L, 2);
4327 std::string hash = translatePassword(name,
4328 narrow_to_wide(raw_password));
4329 lua_pushstring(L, hash.c_str());
4333 // notify_authentication_modified(name)
4334 static int l_notify_authentication_modified(lua_State *L)
4336 std::string name = "";
4337 if(lua_isstring(L, 1))
4338 name = lua_tostring(L, 1);
4339 get_server(L)->reportPrivsModified(name);
4343 // get_craft_result(input)
4344 static int l_get_craft_result(lua_State *L)
4347 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4348 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4349 es_CraftMethod, CRAFT_METHOD_NORMAL);
4351 lua_getfield(L, input_i, "width");
4352 if(lua_isnumber(L, -1))
4353 width = luaL_checkinteger(L, -1);
4355 lua_getfield(L, input_i, "items");
4356 std::vector<ItemStack> items = read_items(L, -1);
4357 lua_pop(L, 1); // items
4359 IGameDef *gdef = get_server(L);
4360 ICraftDefManager *cdef = gdef->cdef();
4361 CraftInput input(method, width, items);
4363 bool got = cdef->getCraftResult(input, output, true, gdef);
4364 lua_newtable(L); // output table
4367 item.deSerialize(output.item, gdef->idef());
4368 LuaItemStack::create(L, item);
4369 lua_setfield(L, -2, "item");
4370 setintfield(L, -1, "time", output.time);
4372 LuaItemStack::create(L, ItemStack());
4373 lua_setfield(L, -2, "item");
4374 setintfield(L, -1, "time", 0);
4376 lua_newtable(L); // decremented input table
4377 lua_pushstring(L, method_s.c_str());
4378 lua_setfield(L, -2, "method");
4379 lua_pushinteger(L, width);
4380 lua_setfield(L, -2, "width");
4381 push_items(L, input.items);
4382 lua_setfield(L, -2, "items");
4386 static const struct luaL_Reg minetest_f [] = {
4389 {"register_item_raw", l_register_item_raw},
4390 {"register_alias_raw", l_register_alias_raw},
4391 {"register_craft", l_register_craft},
4392 {"setting_set", l_setting_set},
4393 {"setting_get", l_setting_get},
4394 {"setting_getbool", l_setting_getbool},
4395 {"chat_send_all", l_chat_send_all},
4396 {"chat_send_player", l_chat_send_player},
4397 {"get_player_privs", l_get_player_privs},
4398 {"get_inventory", l_get_inventory},
4399 {"get_dig_params", l_get_dig_params},
4400 {"get_hit_params", l_get_hit_params},
4401 {"get_current_modname", l_get_current_modname},
4402 {"get_modpath", l_get_modpath},
4403 {"get_worldpath", l_get_worldpath},
4404 {"sound_play", l_sound_play},
4405 {"sound_stop", l_sound_stop},
4406 {"is_singleplayer", l_is_singleplayer},
4407 {"get_password_hash", l_get_password_hash},
4408 {"notify_authentication_modified", l_notify_authentication_modified},
4409 {"get_craft_result", l_get_craft_result},
4414 Main export function
4417 void scriptapi_export(lua_State *L, Server *server)
4420 assert(lua_checkstack(L, 20));
4421 verbosestream<<"scriptapi_export()"<<std::endl;
4422 StackUnroller stack_unroller(L);
4424 // Store server as light userdata in registry
4425 lua_pushlightuserdata(L, server);
4426 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4428 // Register global functions in table minetest
4430 luaL_register(L, NULL, minetest_f);
4431 lua_setglobal(L, "minetest");
4433 // Get the main minetest table
4434 lua_getglobal(L, "minetest");
4436 // Add tables to minetest
4438 lua_setfield(L, -2, "object_refs");
4440 lua_setfield(L, -2, "luaentities");
4442 // Register wrappers
4443 LuaItemStack::Register(L);
4444 InvRef::Register(L);
4445 NodeMetaRef::Register(L);
4446 ObjectRef::Register(L);
4447 EnvRef::Register(L);
4448 LuaPseudoRandom::Register(L);
4449 LuaPerlinNoise::Register(L);
4452 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4453 const std::string &modname)
4455 ModNameStorer modnamestorer(L, modname);
4457 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4459 errorstream<<"Error loading mod \""<<modname
4460 <<"\": modname does not follow naming conventions: "
4461 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4465 bool success = false;
4468 success = script_load(L, scriptpath.c_str());
4471 errorstream<<"Error loading mod \""<<modname
4472 <<"\": "<<e.what()<<std::endl;
4478 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4481 assert(lua_checkstack(L, 20));
4482 verbosestream<<"scriptapi_add_environment"<<std::endl;
4483 StackUnroller stack_unroller(L);
4485 // Create EnvRef on stack
4486 EnvRef::create(L, env);
4487 int envref = lua_gettop(L);
4489 // minetest.env = envref
4490 lua_getglobal(L, "minetest");
4491 luaL_checktype(L, -1, LUA_TTABLE);
4492 lua_pushvalue(L, envref);
4493 lua_setfield(L, -2, "env");
4495 // Store environment as light userdata in registry
4496 lua_pushlightuserdata(L, env);
4497 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4500 Add ActiveBlockModifiers to environment
4503 // Get minetest.registered_abms
4504 lua_getglobal(L, "minetest");
4505 lua_getfield(L, -1, "registered_abms");
4506 luaL_checktype(L, -1, LUA_TTABLE);
4507 int registered_abms = lua_gettop(L);
4509 if(lua_istable(L, registered_abms)){
4510 int table = lua_gettop(L);
4512 while(lua_next(L, table) != 0){
4513 // key at index -2 and value at index -1
4514 int id = lua_tonumber(L, -2);
4515 int current_abm = lua_gettop(L);
4517 std::set<std::string> trigger_contents;
4518 lua_getfield(L, current_abm, "nodenames");
4519 if(lua_istable(L, -1)){
4520 int table = lua_gettop(L);
4522 while(lua_next(L, table) != 0){
4523 // key at index -2 and value at index -1
4524 luaL_checktype(L, -1, LUA_TSTRING);
4525 trigger_contents.insert(lua_tostring(L, -1));
4526 // removes value, keeps key for next iteration
4529 } else if(lua_isstring(L, -1)){
4530 trigger_contents.insert(lua_tostring(L, -1));
4534 std::set<std::string> required_neighbors;
4535 lua_getfield(L, current_abm, "neighbors");
4536 if(lua_istable(L, -1)){
4537 int table = lua_gettop(L);
4539 while(lua_next(L, table) != 0){
4540 // key at index -2 and value at index -1
4541 luaL_checktype(L, -1, LUA_TSTRING);
4542 required_neighbors.insert(lua_tostring(L, -1));
4543 // removes value, keeps key for next iteration
4546 } else if(lua_isstring(L, -1)){
4547 required_neighbors.insert(lua_tostring(L, -1));
4551 float trigger_interval = 10.0;
4552 getfloatfield(L, current_abm, "interval", trigger_interval);
4554 int trigger_chance = 50;
4555 getintfield(L, current_abm, "chance", trigger_chance);
4557 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4558 required_neighbors, trigger_interval, trigger_chance);
4560 env->addActiveBlockModifier(abm);
4562 // removes value, keeps key for next iteration
4570 // Dump stack top with the dump2 function
4571 static void dump2(lua_State *L, const char *name)
4573 // Dump object (debug)
4574 lua_getglobal(L, "dump2");
4575 luaL_checktype(L, -1, LUA_TFUNCTION);
4576 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4577 lua_pushstring(L, name);
4578 if(lua_pcall(L, 2, 0, 0))
4579 script_error(L, "error: %s", lua_tostring(L, -1));
4587 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4590 assert(lua_checkstack(L, 20));
4591 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4592 StackUnroller stack_unroller(L);
4594 // Create object on stack
4595 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4596 int object = lua_gettop(L);
4598 // Get minetest.object_refs table
4599 lua_getglobal(L, "minetest");
4600 lua_getfield(L, -1, "object_refs");
4601 luaL_checktype(L, -1, LUA_TTABLE);
4602 int objectstable = lua_gettop(L);
4604 // object_refs[id] = object
4605 lua_pushnumber(L, cobj->getId()); // Push id
4606 lua_pushvalue(L, object); // Copy object to top of stack
4607 lua_settable(L, objectstable);
4610 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4613 assert(lua_checkstack(L, 20));
4614 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4615 StackUnroller stack_unroller(L);
4617 // Get minetest.object_refs table
4618 lua_getglobal(L, "minetest");
4619 lua_getfield(L, -1, "object_refs");
4620 luaL_checktype(L, -1, LUA_TTABLE);
4621 int objectstable = lua_gettop(L);
4623 // Get object_refs[id]
4624 lua_pushnumber(L, cobj->getId()); // Push id
4625 lua_gettable(L, objectstable);
4626 // Set object reference to NULL
4627 ObjectRef::set_null(L);
4628 lua_pop(L, 1); // pop object
4630 // Set object_refs[id] = nil
4631 lua_pushnumber(L, cobj->getId()); // Push id
4633 lua_settable(L, objectstable);
4640 // What scriptapi_run_callbacks does with the return values of callbacks.
4641 // Regardless of the mode, if only one callback is defined,
4642 // its return value is the total return value.
4643 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4644 enum RunCallbacksMode
4646 // Returns the return value of the first callback
4647 // Returns nil if list of callbacks is empty
4648 RUN_CALLBACKS_MODE_FIRST,
4649 // Returns the return value of the last callback
4650 // Returns nil if list of callbacks is empty
4651 RUN_CALLBACKS_MODE_LAST,
4652 // If any callback returns a false value, the first such is returned
4653 // Otherwise, the first callback's return value (trueish) is returned
4654 // Returns true if list of callbacks is empty
4655 RUN_CALLBACKS_MODE_AND,
4656 // Like above, but stops calling callbacks (short circuit)
4657 // after seeing the first false value
4658 RUN_CALLBACKS_MODE_AND_SC,
4659 // If any callback returns a true value, the first such is returned
4660 // Otherwise, the first callback's return value (falseish) is returned
4661 // Returns false if list of callbacks is empty
4662 RUN_CALLBACKS_MODE_OR,
4663 // Like above, but stops calling callbacks (short circuit)
4664 // after seeing the first true value
4665 RUN_CALLBACKS_MODE_OR_SC,
4666 // Note: "a true value" and "a false value" refer to values that
4667 // are converted by lua_toboolean to true or false, respectively.
4670 // Push the list of callbacks (a lua table).
4671 // Then push nargs arguments.
4672 // Then call this function, which
4673 // - runs the callbacks
4674 // - removes the table and arguments from the lua stack
4675 // - pushes the return value, computed depending on mode
4676 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4677 RunCallbacksMode mode)
4679 // Insert the return value into the lua stack, below the table
4680 assert(lua_gettop(L) >= nargs + 1);
4682 lua_insert(L, -(nargs + 1) - 1);
4683 // Stack now looks like this:
4684 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4686 int rv = lua_gettop(L) - nargs - 1;
4688 int arg = table + 1;
4690 luaL_checktype(L, table, LUA_TTABLE);
4694 bool first_loop = true;
4695 while(lua_next(L, table) != 0){
4696 // key at index -2 and value at index -1
4697 luaL_checktype(L, -1, LUA_TFUNCTION);
4699 for(int i = 0; i < nargs; i++)
4700 lua_pushvalue(L, arg+i);
4701 if(lua_pcall(L, nargs, 1, 0))
4702 script_error(L, "error: %s", lua_tostring(L, -1));
4704 // Move return value to designated space in stack
4707 // Result of first callback is always moved
4711 // Otherwise, what happens depends on the mode
4712 if(mode == RUN_CALLBACKS_MODE_FIRST)
4714 else if(mode == RUN_CALLBACKS_MODE_LAST)
4716 else if(mode == RUN_CALLBACKS_MODE_AND ||
4717 mode == RUN_CALLBACKS_MODE_AND_SC){
4718 if(lua_toboolean(L, rv) == true &&
4719 lua_toboolean(L, -1) == false)
4724 else if(mode == RUN_CALLBACKS_MODE_OR ||
4725 mode == RUN_CALLBACKS_MODE_OR_SC){
4726 if(lua_toboolean(L, rv) == false &&
4727 lua_toboolean(L, -1) == true)
4736 // Handle short circuit modes
4737 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4738 lua_toboolean(L, rv) == false)
4740 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4741 lua_toboolean(L, rv) == true)
4744 // value removed, keep key for next iteration
4747 // Remove stuff from stack, leaving only the return value
4750 // Fix return value in case no callbacks were called
4752 if(mode == RUN_CALLBACKS_MODE_AND ||
4753 mode == RUN_CALLBACKS_MODE_AND_SC){
4755 lua_pushboolean(L, true);
4757 else if(mode == RUN_CALLBACKS_MODE_OR ||
4758 mode == RUN_CALLBACKS_MODE_OR_SC){
4760 lua_pushboolean(L, false);
4765 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4766 const std::string &message)
4769 assert(lua_checkstack(L, 20));
4770 StackUnroller stack_unroller(L);
4772 // Get minetest.registered_on_chat_messages
4773 lua_getglobal(L, "minetest");
4774 lua_getfield(L, -1, "registered_on_chat_messages");
4776 lua_pushstring(L, name.c_str());
4777 lua_pushstring(L, message.c_str());
4778 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4779 bool ate = lua_toboolean(L, -1);
4783 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4786 assert(lua_checkstack(L, 20));
4787 StackUnroller stack_unroller(L);
4789 // Get minetest.registered_on_newplayers
4790 lua_getglobal(L, "minetest");
4791 lua_getfield(L, -1, "registered_on_newplayers");
4793 objectref_get_or_create(L, player);
4794 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4797 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4800 assert(lua_checkstack(L, 20));
4801 StackUnroller stack_unroller(L);
4803 // Get minetest.registered_on_dieplayers
4804 lua_getglobal(L, "minetest");
4805 lua_getfield(L, -1, "registered_on_dieplayers");
4807 objectref_get_or_create(L, player);
4808 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4811 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4814 assert(lua_checkstack(L, 20));
4815 StackUnroller stack_unroller(L);
4817 // Get minetest.registered_on_respawnplayers
4818 lua_getglobal(L, "minetest");
4819 lua_getfield(L, -1, "registered_on_respawnplayers");
4821 objectref_get_or_create(L, player);
4822 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4823 bool positioning_handled_by_some = lua_toboolean(L, -1);
4824 return positioning_handled_by_some;
4827 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4830 assert(lua_checkstack(L, 20));
4831 StackUnroller stack_unroller(L);
4833 // Get minetest.registered_on_joinplayers
4834 lua_getglobal(L, "minetest");
4835 lua_getfield(L, -1, "registered_on_joinplayers");
4837 objectref_get_or_create(L, player);
4838 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4841 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4844 assert(lua_checkstack(L, 20));
4845 StackUnroller stack_unroller(L);
4847 // Get minetest.registered_on_leaveplayers
4848 lua_getglobal(L, "minetest");
4849 lua_getfield(L, -1, "registered_on_leaveplayers");
4851 objectref_get_or_create(L, player);
4852 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4855 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4858 assert(lua_checkstack(L, 20));
4859 StackUnroller stack_unroller(L);
4861 Inventory *inv = player->getInventory();
4864 lua_getglobal(L, "minetest");
4865 lua_getfield(L, -1, "creative_inventory");
4866 luaL_checktype(L, -1, LUA_TTABLE);
4867 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4870 static void get_auth_handler(lua_State *L)
4872 lua_getglobal(L, "minetest");
4873 lua_getfield(L, -1, "registered_auth_handler");
4874 if(lua_isnil(L, -1)){
4876 lua_getfield(L, -1, "builtin_auth_handler");
4878 if(lua_type(L, -1) != LUA_TTABLE)
4879 throw LuaError(L, "Authentication handler table not valid");
4882 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
4883 std::string *dst_password, std::set<std::string> *dst_privs)
4886 assert(lua_checkstack(L, 20));
4887 StackUnroller stack_unroller(L);
4889 get_auth_handler(L);
4890 lua_getfield(L, -1, "get_auth");
4891 if(lua_type(L, -1) != LUA_TFUNCTION)
4892 throw LuaError(L, "Authentication handler missing get_auth");
4893 lua_pushstring(L, playername.c_str());
4894 if(lua_pcall(L, 1, 1, 0))
4895 script_error(L, "error: %s", lua_tostring(L, -1));
4897 // nil = login not allowed
4898 if(lua_isnil(L, -1))
4900 luaL_checktype(L, -1, LUA_TTABLE);
4902 std::string password;
4903 bool found = getstringfield(L, -1, "password", password);
4905 throw LuaError(L, "Authentication handler didn't return password");
4907 *dst_password = password;
4909 lua_getfield(L, -1, "privileges");
4910 if(!lua_istable(L, -1))
4912 "Authentication handler didn't return privilege table");
4914 read_privileges(L, -1, *dst_privs);
4920 void scriptapi_create_auth(lua_State *L, const std::string &playername,
4921 const std::string &password)
4924 assert(lua_checkstack(L, 20));
4925 StackUnroller stack_unroller(L);
4927 get_auth_handler(L);
4928 lua_getfield(L, -1, "create_auth");
4929 if(lua_type(L, -1) != LUA_TFUNCTION)
4930 throw LuaError(L, "Authentication handler missing create_auth");
4931 lua_pushstring(L, playername.c_str());
4932 lua_pushstring(L, password.c_str());
4933 if(lua_pcall(L, 2, 0, 0))
4934 script_error(L, "error: %s", lua_tostring(L, -1));
4937 bool scriptapi_set_password(lua_State *L, const std::string &playername,
4938 const std::string &password)
4941 assert(lua_checkstack(L, 20));
4942 StackUnroller stack_unroller(L);
4944 get_auth_handler(L);
4945 lua_getfield(L, -1, "set_password");
4946 if(lua_type(L, -1) != LUA_TFUNCTION)
4947 throw LuaError(L, "Authentication handler missing set_password");
4948 lua_pushstring(L, playername.c_str());
4949 lua_pushstring(L, password.c_str());
4950 if(lua_pcall(L, 2, 1, 0))
4951 script_error(L, "error: %s", lua_tostring(L, -1));
4952 return lua_toboolean(L, -1);
4956 item callbacks and node callbacks
4959 // Retrieves minetest.registered_items[name][callbackname]
4960 // If that is nil or on error, return false and stack is unchanged
4961 // If that is a function, returns true and pushes the
4962 // function onto the stack
4963 static bool get_item_callback(lua_State *L,
4964 const char *name, const char *callbackname)
4966 lua_getglobal(L, "minetest");
4967 lua_getfield(L, -1, "registered_items");
4969 luaL_checktype(L, -1, LUA_TTABLE);
4970 lua_getfield(L, -1, name);
4972 // Should be a table
4973 if(lua_type(L, -1) != LUA_TTABLE)
4975 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4979 lua_getfield(L, -1, callbackname);
4981 // Should be a function or nil
4982 if(lua_type(L, -1) == LUA_TFUNCTION)
4986 else if(lua_isnil(L, -1))
4993 errorstream<<"Item \""<<name<<"\" callback \""
4994 <<callbackname<<" is not a function"<<std::endl;
5000 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5001 ServerActiveObject *dropper, v3f pos)
5004 assert(lua_checkstack(L, 20));
5005 StackUnroller stack_unroller(L);
5007 // Push callback function on stack
5008 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
5012 LuaItemStack::create(L, item);
5013 objectref_get_or_create(L, dropper);
5014 pushFloatPos(L, pos);
5015 if(lua_pcall(L, 3, 1, 0))
5016 script_error(L, "error: %s", lua_tostring(L, -1));
5017 if(!lua_isnil(L, -1))
5018 item = read_item(L, -1);
5022 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
5023 ServerActiveObject *placer, const PointedThing &pointed)
5026 assert(lua_checkstack(L, 20));
5027 StackUnroller stack_unroller(L);
5029 // Push callback function on stack
5030 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5034 LuaItemStack::create(L, item);
5035 objectref_get_or_create(L, placer);
5036 push_pointed_thing(L, pointed);
5037 if(lua_pcall(L, 3, 1, 0))
5038 script_error(L, "error: %s", lua_tostring(L, -1));
5039 if(!lua_isnil(L, -1))
5040 item = read_item(L, -1);
5044 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5045 ServerActiveObject *user, const PointedThing &pointed)
5048 assert(lua_checkstack(L, 20));
5049 StackUnroller stack_unroller(L);
5051 // Push callback function on stack
5052 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5056 LuaItemStack::create(L, item);
5057 objectref_get_or_create(L, user);
5058 push_pointed_thing(L, pointed);
5059 if(lua_pcall(L, 3, 1, 0))
5060 script_error(L, "error: %s", lua_tostring(L, -1));
5061 if(!lua_isnil(L, -1))
5062 item = read_item(L, -1);
5066 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5067 ServerActiveObject *puncher)
5070 assert(lua_checkstack(L, 20));
5071 StackUnroller stack_unroller(L);
5073 INodeDefManager *ndef = get_server(L)->ndef();
5075 // Push callback function on stack
5076 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5081 pushnode(L, node, ndef);
5082 objectref_get_or_create(L, puncher);
5083 if(lua_pcall(L, 3, 0, 0))
5084 script_error(L, "error: %s", lua_tostring(L, -1));
5088 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5089 ServerActiveObject *digger)
5092 assert(lua_checkstack(L, 20));
5093 StackUnroller stack_unroller(L);
5095 INodeDefManager *ndef = get_server(L)->ndef();
5097 // Push callback function on stack
5098 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5103 pushnode(L, node, ndef);
5104 objectref_get_or_create(L, digger);
5105 if(lua_pcall(L, 3, 0, 0))
5106 script_error(L, "error: %s", lua_tostring(L, -1));
5110 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5113 assert(lua_checkstack(L, 20));
5114 StackUnroller stack_unroller(L);
5116 INodeDefManager *ndef = get_server(L)->ndef();
5118 // Push callback function on stack
5119 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5124 if(lua_pcall(L, 1, 0, 0))
5125 script_error(L, "error: %s", lua_tostring(L, -1));
5128 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5131 assert(lua_checkstack(L, 20));
5132 StackUnroller stack_unroller(L);
5134 INodeDefManager *ndef = get_server(L)->ndef();
5136 // Push callback function on stack
5137 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5142 if(lua_pcall(L, 1, 0, 0))
5143 script_error(L, "error: %s", lua_tostring(L, -1));
5146 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5147 const std::string &formname,
5148 const std::map<std::string, std::string> &fields,
5149 ServerActiveObject *sender)
5152 assert(lua_checkstack(L, 20));
5153 StackUnroller stack_unroller(L);
5155 INodeDefManager *ndef = get_server(L)->ndef();
5157 // If node doesn't exist, we don't know what callback to call
5158 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5159 if(node.getContent() == CONTENT_IGNORE)
5162 // Push callback function on stack
5163 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5170 lua_pushstring(L, formname.c_str());
5173 for(std::map<std::string, std::string>::const_iterator
5174 i = fields.begin(); i != fields.end(); i++){
5175 const std::string &name = i->first;
5176 const std::string &value = i->second;
5177 lua_pushstring(L, name.c_str());
5178 lua_pushlstring(L, value.c_str(), value.size());
5179 lua_settable(L, -3);
5182 objectref_get_or_create(L, sender);
5183 if(lua_pcall(L, 4, 0, 0))
5184 script_error(L, "error: %s", lua_tostring(L, -1));
5187 void scriptapi_node_on_metadata_inventory_move(lua_State *L, v3s16 p,
5188 const std::string &from_list, int from_index,
5189 const std::string &to_list, int to_index,
5190 int count, ServerActiveObject *player)
5193 assert(lua_checkstack(L, 20));
5194 StackUnroller stack_unroller(L);
5196 INodeDefManager *ndef = get_server(L)->ndef();
5198 // If node doesn't exist, we don't know what callback to call
5199 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5200 if(node.getContent() == CONTENT_IGNORE)
5203 // Push callback function on stack
5204 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5205 "on_metadata_inventory_move"))
5208 // function(pos, from_list, from_index, to_list, to_index, count, player)
5210 lua_pushstring(L, from_list.c_str());
5211 lua_pushinteger(L, from_index + 1);
5212 lua_pushstring(L, to_list.c_str());
5213 lua_pushinteger(L, to_index + 1);
5214 lua_pushinteger(L, count);
5215 objectref_get_or_create(L, player);
5216 if(lua_pcall(L, 7, 0, 0))
5217 script_error(L, "error: %s", lua_tostring(L, -1));
5220 ItemStack scriptapi_node_on_metadata_inventory_offer(lua_State *L, v3s16 p,
5221 const std::string &listname, int index, ItemStack &stack,
5222 ServerActiveObject *player)
5225 assert(lua_checkstack(L, 20));
5226 StackUnroller stack_unroller(L);
5228 INodeDefManager *ndef = get_server(L)->ndef();
5230 // If node doesn't exist, we don't know what callback to call
5231 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5232 if(node.getContent() == CONTENT_IGNORE)
5235 // Push callback function on stack
5236 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5237 "on_metadata_inventory_offer"))
5240 // Call function(pos, listname, index, stack, player)
5242 lua_pushstring(L, listname.c_str());
5243 lua_pushinteger(L, index + 1);
5244 LuaItemStack::create(L, stack);
5245 objectref_get_or_create(L, player);
5246 if(lua_pcall(L, 5, 1, 0))
5247 script_error(L, "error: %s", lua_tostring(L, -1));
5248 return read_item(L, -1);
5251 ItemStack scriptapi_node_on_metadata_inventory_take(lua_State *L, v3s16 p,
5252 const std::string &listname, int index, int count,
5253 ServerActiveObject *player)
5256 assert(lua_checkstack(L, 20));
5257 StackUnroller stack_unroller(L);
5259 INodeDefManager *ndef = get_server(L)->ndef();
5261 // If node doesn't exist, we don't know what callback to call
5262 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5263 if(node.getContent() == CONTENT_IGNORE)
5266 // Push callback function on stack
5267 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5268 "on_metadata_inventory_take"))
5271 // Call function(pos, listname, index, count, player)
5273 lua_pushstring(L, listname.c_str());
5274 lua_pushinteger(L, index + 1);
5275 lua_pushinteger(L, count);
5276 objectref_get_or_create(L, player);
5277 if(lua_pcall(L, 5, 1, 0))
5278 script_error(L, "error: %s", lua_tostring(L, -1));
5279 return read_item(L, -1);
5286 void scriptapi_environment_step(lua_State *L, float dtime)
5289 assert(lua_checkstack(L, 20));
5290 //infostream<<"scriptapi_environment_step"<<std::endl;
5291 StackUnroller stack_unroller(L);
5293 // Get minetest.registered_globalsteps
5294 lua_getglobal(L, "minetest");
5295 lua_getfield(L, -1, "registered_globalsteps");
5297 lua_pushnumber(L, dtime);
5298 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5301 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5305 assert(lua_checkstack(L, 20));
5306 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5307 StackUnroller stack_unroller(L);
5309 // Get minetest.registered_on_generateds
5310 lua_getglobal(L, "minetest");
5311 lua_getfield(L, -1, "registered_on_generateds");
5313 push_v3s16(L, minp);
5314 push_v3s16(L, maxp);
5315 lua_pushnumber(L, blockseed);
5316 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5323 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5326 assert(lua_checkstack(L, 20));
5327 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5328 <<name<<"\""<<std::endl;
5329 StackUnroller stack_unroller(L);
5331 // Get minetest.registered_entities[name]
5332 lua_getglobal(L, "minetest");
5333 lua_getfield(L, -1, "registered_entities");
5334 luaL_checktype(L, -1, LUA_TTABLE);
5335 lua_pushstring(L, name);
5336 lua_gettable(L, -2);
5337 // Should be a table, which we will use as a prototype
5338 //luaL_checktype(L, -1, LUA_TTABLE);
5339 if(lua_type(L, -1) != LUA_TTABLE){
5340 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5343 int prototype_table = lua_gettop(L);
5344 //dump2(L, "prototype_table");
5346 // Create entity object
5348 int object = lua_gettop(L);
5350 // Set object metatable
5351 lua_pushvalue(L, prototype_table);
5352 lua_setmetatable(L, -2);
5354 // Add object reference
5355 // This should be userdata with metatable ObjectRef
5356 objectref_get(L, id);
5357 luaL_checktype(L, -1, LUA_TUSERDATA);
5358 if(!luaL_checkudata(L, -1, "ObjectRef"))
5359 luaL_typerror(L, -1, "ObjectRef");
5360 lua_setfield(L, -2, "object");
5362 // minetest.luaentities[id] = object
5363 lua_getglobal(L, "minetest");
5364 lua_getfield(L, -1, "luaentities");
5365 luaL_checktype(L, -1, LUA_TTABLE);
5366 lua_pushnumber(L, id); // Push id
5367 lua_pushvalue(L, object); // Copy object to top of stack
5368 lua_settable(L, -3);
5373 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5374 const std::string &staticdata)
5377 assert(lua_checkstack(L, 20));
5378 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5379 StackUnroller stack_unroller(L);
5381 // Get minetest.luaentities[id]
5382 luaentity_get(L, id);
5383 int object = lua_gettop(L);
5385 // Get on_activate function
5386 lua_pushvalue(L, object);
5387 lua_getfield(L, -1, "on_activate");
5388 if(!lua_isnil(L, -1)){
5389 luaL_checktype(L, -1, LUA_TFUNCTION);
5390 lua_pushvalue(L, object); // self
5391 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5392 // Call with 2 arguments, 0 results
5393 if(lua_pcall(L, 2, 0, 0))
5394 script_error(L, "error running function on_activate: %s\n",
5395 lua_tostring(L, -1));
5399 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5402 assert(lua_checkstack(L, 20));
5403 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5405 // Get minetest.luaentities table
5406 lua_getglobal(L, "minetest");
5407 lua_getfield(L, -1, "luaentities");
5408 luaL_checktype(L, -1, LUA_TTABLE);
5409 int objectstable = lua_gettop(L);
5411 // Set luaentities[id] = nil
5412 lua_pushnumber(L, id); // Push id
5414 lua_settable(L, objectstable);
5416 lua_pop(L, 2); // pop luaentities, minetest
5419 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5422 assert(lua_checkstack(L, 20));
5423 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5424 StackUnroller stack_unroller(L);
5426 // Get minetest.luaentities[id]
5427 luaentity_get(L, id);
5428 int object = lua_gettop(L);
5430 // Get get_staticdata function
5431 lua_pushvalue(L, object);
5432 lua_getfield(L, -1, "get_staticdata");
5433 if(lua_isnil(L, -1))
5436 luaL_checktype(L, -1, LUA_TFUNCTION);
5437 lua_pushvalue(L, object); // self
5438 // Call with 1 arguments, 1 results
5439 if(lua_pcall(L, 1, 1, 0))
5440 script_error(L, "error running function get_staticdata: %s\n",
5441 lua_tostring(L, -1));
5444 const char *s = lua_tolstring(L, -1, &len);
5445 return std::string(s, len);
5448 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5449 ObjectProperties *prop)
5452 assert(lua_checkstack(L, 20));
5453 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5454 StackUnroller stack_unroller(L);
5456 // Get minetest.luaentities[id]
5457 luaentity_get(L, id);
5458 //int object = lua_gettop(L);
5460 // Set default values that differ from ObjectProperties defaults
5463 // Deprecated: read object properties directly
5464 read_object_properties(L, -1, prop);
5466 // Read initial_properties
5467 lua_getfield(L, -1, "initial_properties");
5468 read_object_properties(L, -1, prop);
5472 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5475 assert(lua_checkstack(L, 20));
5476 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5477 StackUnroller stack_unroller(L);
5479 // Get minetest.luaentities[id]
5480 luaentity_get(L, id);
5481 int object = lua_gettop(L);
5482 // State: object is at top of stack
5483 // Get step function
5484 lua_getfield(L, -1, "on_step");
5485 if(lua_isnil(L, -1))
5487 luaL_checktype(L, -1, LUA_TFUNCTION);
5488 lua_pushvalue(L, object); // self
5489 lua_pushnumber(L, dtime); // dtime
5490 // Call with 2 arguments, 0 results
5491 if(lua_pcall(L, 2, 0, 0))
5492 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5495 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5496 // tool_capabilities, direction)
5497 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5498 ServerActiveObject *puncher, float time_from_last_punch,
5499 const ToolCapabilities *toolcap, v3f dir)
5502 assert(lua_checkstack(L, 20));
5503 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5504 StackUnroller stack_unroller(L);
5506 // Get minetest.luaentities[id]
5507 luaentity_get(L, id);
5508 int object = lua_gettop(L);
5509 // State: object is at top of stack
5511 lua_getfield(L, -1, "on_punch");
5512 if(lua_isnil(L, -1))
5514 luaL_checktype(L, -1, LUA_TFUNCTION);
5515 lua_pushvalue(L, object); // self
5516 objectref_get_or_create(L, puncher); // Clicker reference
5517 lua_pushnumber(L, time_from_last_punch);
5518 push_tool_capabilities(L, *toolcap);
5520 // Call with 5 arguments, 0 results
5521 if(lua_pcall(L, 5, 0, 0))
5522 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5525 // Calls entity:on_rightclick(ObjectRef clicker)
5526 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5527 ServerActiveObject *clicker)
5530 assert(lua_checkstack(L, 20));
5531 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5532 StackUnroller stack_unroller(L);
5534 // Get minetest.luaentities[id]
5535 luaentity_get(L, id);
5536 int object = lua_gettop(L);
5537 // State: object is at top of stack
5539 lua_getfield(L, -1, "on_rightclick");
5540 if(lua_isnil(L, -1))
5542 luaL_checktype(L, -1, LUA_TFUNCTION);
5543 lua_pushvalue(L, object); // self
5544 objectref_get_or_create(L, clicker); // Clicker reference
5545 // Call with 2 arguments, 0 results
5546 if(lua_pcall(L, 2, 0, 0))
5547 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));