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 /* Cache existence of some callbacks */
999 lua_getfield(L, index, "on_construct");
1000 if(!lua_isnil(L, -1)) f.has_on_construct = true;
1002 lua_getfield(L, index, "on_destruct");
1003 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1005 lua_getfield(L, index, "after_destruct");
1006 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1010 getstringfield(L, index, "name", f.name);
1013 lua_getfield(L, index, "groups");
1014 read_groups(L, -1, f.groups);
1017 /* Visual definition */
1019 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1021 getfloatfield(L, index, "visual_scale", f.visual_scale);
1023 lua_getfield(L, index, "tile_images");
1024 if(lua_istable(L, -1)){
1025 int table = lua_gettop(L);
1028 while(lua_next(L, table) != 0){
1029 // key at index -2 and value at index -1
1030 if(lua_isstring(L, -1))
1031 f.tname_tiles[i] = lua_tostring(L, -1);
1033 f.tname_tiles[i] = "";
1034 // removes value, keeps key for next iteration
1042 // Copy last value to all remaining textures
1044 std::string lastname = f.tname_tiles[i-1];
1046 f.tname_tiles[i] = lastname;
1053 lua_getfield(L, index, "special_materials");
1054 if(lua_istable(L, -1)){
1055 int table = lua_gettop(L);
1058 while(lua_next(L, table) != 0){
1059 // key at index -2 and value at index -1
1060 int smtable = lua_gettop(L);
1061 std::string tname = getstringfield_default(
1062 L, smtable, "image", "");
1063 bool backface_culling = getboolfield_default(
1064 L, smtable, "backface_culling", true);
1065 MaterialSpec mspec(tname, backface_culling);
1066 f.mspec_special[i] = mspec;
1067 // removes value, keeps key for next iteration
1078 f.alpha = getintfield_default(L, index, "alpha", 255);
1082 lua_getfield(L, index, "post_effect_color");
1083 if(!lua_isnil(L, -1))
1084 f.post_effect_color = readARGB8(L, -1);
1087 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1088 es_ContentParamType, CPT_NONE);
1089 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1090 es_ContentParamType2, CPT2_NONE);
1092 // Warn about some deprecated fields
1093 warn_if_field_exists(L, index, "wall_mounted",
1094 "deprecated: use paramtype2 = 'wallmounted'");
1095 warn_if_field_exists(L, index, "light_propagates",
1096 "deprecated: determined from paramtype");
1097 warn_if_field_exists(L, index, "dug_item",
1098 "deprecated: use 'drop' field");
1099 warn_if_field_exists(L, index, "extra_dug_item",
1100 "deprecated: use 'drop' field");
1101 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1102 "deprecated: use 'drop' field");
1103 warn_if_field_exists(L, index, "metadata_name",
1104 "deprecated: use on_add and metadata callbacks");
1106 // True for all ground-like things like stone and mud, false for eg. trees
1107 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1108 f.light_propagates = (f.param_type == CPT_LIGHT);
1109 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1110 // This is used for collision detection.
1111 // Also for general solidness queries.
1112 getboolfield(L, index, "walkable", f.walkable);
1113 // Player can point to these
1114 getboolfield(L, index, "pointable", f.pointable);
1115 // Player can dig these
1116 getboolfield(L, index, "diggable", f.diggable);
1117 // Player can climb these
1118 getboolfield(L, index, "climbable", f.climbable);
1119 // Player can build on these
1120 getboolfield(L, index, "buildable_to", f.buildable_to);
1121 // Whether the node is non-liquid, source liquid or flowing liquid
1122 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1123 es_LiquidType, LIQUID_NONE);
1124 // If the content is liquid, this is the flowing version of the liquid.
1125 getstringfield(L, index, "liquid_alternative_flowing",
1126 f.liquid_alternative_flowing);
1127 // If the content is liquid, this is the source version of the liquid.
1128 getstringfield(L, index, "liquid_alternative_source",
1129 f.liquid_alternative_source);
1130 // Viscosity for fluid flow, ranging from 1 to 7, with
1131 // 1 giving almost instantaneous propagation and 7 being
1132 // the slowest possible
1133 f.liquid_viscosity = getintfield_default(L, index,
1134 "liquid_viscosity", f.liquid_viscosity);
1135 // Amount of light the node emits
1136 f.light_source = getintfield_default(L, index,
1137 "light_source", f.light_source);
1138 f.damage_per_second = getintfield_default(L, index,
1139 "damage_per_second", f.damage_per_second);
1141 lua_getfield(L, index, "selection_box");
1142 if(lua_istable(L, -1)){
1143 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1144 es_NodeBoxType, NODEBOX_REGULAR);
1146 lua_getfield(L, -1, "fixed");
1147 if(lua_istable(L, -1))
1148 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1151 lua_getfield(L, -1, "wall_top");
1152 if(lua_istable(L, -1))
1153 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1156 lua_getfield(L, -1, "wall_bottom");
1157 if(lua_istable(L, -1))
1158 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1161 lua_getfield(L, -1, "wall_side");
1162 if(lua_istable(L, -1))
1163 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1168 // Set to true if paramtype used to be 'facedir_simple'
1169 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1170 // Set to true if wall_mounted used to be set to true
1171 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1174 lua_getfield(L, index, "sounds");
1175 if(lua_istable(L, -1)){
1176 lua_getfield(L, -1, "footstep");
1177 read_soundspec(L, -1, f.sound_footstep);
1179 lua_getfield(L, -1, "dig");
1180 read_soundspec(L, -1, f.sound_dig);
1182 lua_getfield(L, -1, "dug");
1183 read_soundspec(L, -1, f.sound_dug);
1195 static ItemStack read_item(lua_State *L, int index);
1196 static std::vector<ItemStack> read_items(lua_State *L, int index);
1197 // creates a table of ItemStacks
1198 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1200 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1201 lua_State *L, int tableindex, int forcesize=-1)
1204 tableindex = lua_gettop(L) + 1 + tableindex;
1205 // If nil, delete list
1206 if(lua_isnil(L, tableindex)){
1207 inv->deleteList(name);
1210 // Otherwise set list
1211 std::vector<ItemStack> items = read_items(L, tableindex);
1212 int listsize = (forcesize != -1) ? forcesize : items.size();
1213 InventoryList *invlist = inv->addList(name, listsize);
1215 for(std::vector<ItemStack>::const_iterator
1216 i = items.begin(); i != items.end(); i++){
1217 if(forcesize != -1 && index == forcesize)
1219 invlist->changeItem(index, *i);
1222 while(forcesize != -1 && index < forcesize){
1223 invlist->deleteItem(index);
1228 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1231 InventoryList *invlist = inv->getList(name);
1232 if(invlist == NULL){
1236 std::vector<ItemStack> items;
1237 for(u32 i=0; i<invlist->getSize(); i++)
1238 items.push_back(invlist->getItem(i));
1239 push_items(L, items);
1243 Helpful macros for userdata classes
1246 #define method(class, name) {#name, class::l_##name}
1257 static const char className[];
1258 static const luaL_reg methods[];
1260 // Exported functions
1262 // garbage collector
1263 static int gc_object(lua_State *L)
1265 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1270 // is_empty(self) -> true/false
1271 static int l_is_empty(lua_State *L)
1273 LuaItemStack *o = checkobject(L, 1);
1274 ItemStack &item = o->m_stack;
1275 lua_pushboolean(L, item.empty());
1279 // get_name(self) -> string
1280 static int l_get_name(lua_State *L)
1282 LuaItemStack *o = checkobject(L, 1);
1283 ItemStack &item = o->m_stack;
1284 lua_pushstring(L, item.name.c_str());
1288 // get_count(self) -> number
1289 static int l_get_count(lua_State *L)
1291 LuaItemStack *o = checkobject(L, 1);
1292 ItemStack &item = o->m_stack;
1293 lua_pushinteger(L, item.count);
1297 // get_wear(self) -> number
1298 static int l_get_wear(lua_State *L)
1300 LuaItemStack *o = checkobject(L, 1);
1301 ItemStack &item = o->m_stack;
1302 lua_pushinteger(L, item.wear);
1306 // get_metadata(self) -> string
1307 static int l_get_metadata(lua_State *L)
1309 LuaItemStack *o = checkobject(L, 1);
1310 ItemStack &item = o->m_stack;
1311 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1315 // clear(self) -> true
1316 static int l_clear(lua_State *L)
1318 LuaItemStack *o = checkobject(L, 1);
1320 lua_pushboolean(L, true);
1324 // replace(self, itemstack or itemstring or table or nil) -> true
1325 static int l_replace(lua_State *L)
1327 LuaItemStack *o = checkobject(L, 1);
1328 o->m_stack = read_item(L, 2);
1329 lua_pushboolean(L, true);
1333 // to_string(self) -> string
1334 static int l_to_string(lua_State *L)
1336 LuaItemStack *o = checkobject(L, 1);
1337 std::string itemstring = o->m_stack.getItemString();
1338 lua_pushstring(L, itemstring.c_str());
1342 // to_table(self) -> table or nil
1343 static int l_to_table(lua_State *L)
1345 LuaItemStack *o = checkobject(L, 1);
1346 const ItemStack &item = o->m_stack;
1354 lua_pushstring(L, item.name.c_str());
1355 lua_setfield(L, -2, "name");
1356 lua_pushinteger(L, item.count);
1357 lua_setfield(L, -2, "count");
1358 lua_pushinteger(L, item.wear);
1359 lua_setfield(L, -2, "wear");
1360 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1361 lua_setfield(L, -2, "metadata");
1366 // get_stack_max(self) -> number
1367 static int l_get_stack_max(lua_State *L)
1369 LuaItemStack *o = checkobject(L, 1);
1370 ItemStack &item = o->m_stack;
1371 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1375 // get_free_space(self) -> number
1376 static int l_get_free_space(lua_State *L)
1378 LuaItemStack *o = checkobject(L, 1);
1379 ItemStack &item = o->m_stack;
1380 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1384 // is_known(self) -> true/false
1385 // Checks if the item is defined.
1386 static int l_is_known(lua_State *L)
1388 LuaItemStack *o = checkobject(L, 1);
1389 ItemStack &item = o->m_stack;
1390 bool is_known = item.isKnown(get_server(L)->idef());
1391 lua_pushboolean(L, is_known);
1395 // get_definition(self) -> table
1396 // Returns the item definition table from minetest.registered_items,
1397 // or a fallback one (name="unknown")
1398 static int l_get_definition(lua_State *L)
1400 LuaItemStack *o = checkobject(L, 1);
1401 ItemStack &item = o->m_stack;
1403 // Get minetest.registered_items[name]
1404 lua_getglobal(L, "minetest");
1405 lua_getfield(L, -1, "registered_items");
1406 luaL_checktype(L, -1, LUA_TTABLE);
1407 lua_getfield(L, -1, item.name.c_str());
1408 if(lua_isnil(L, -1))
1411 lua_getfield(L, -1, "unknown");
1416 // get_tool_capabilities(self) -> table
1417 // Returns the effective tool digging properties.
1418 // Returns those of the hand ("") if this item has none associated.
1419 static int l_get_tool_capabilities(lua_State *L)
1421 LuaItemStack *o = checkobject(L, 1);
1422 ItemStack &item = o->m_stack;
1423 const ToolCapabilities &prop =
1424 item.getToolCapabilities(get_server(L)->idef());
1425 push_tool_capabilities(L, prop);
1429 // add_wear(self, amount) -> true/false
1430 // The range for "amount" is [0,65535]. Wear is only added if the item
1431 // is a tool. Adding wear might destroy the item.
1432 // Returns true if the item is (or was) a tool.
1433 static int l_add_wear(lua_State *L)
1435 LuaItemStack *o = checkobject(L, 1);
1436 ItemStack &item = o->m_stack;
1437 int amount = lua_tointeger(L, 2);
1438 bool result = item.addWear(amount, get_server(L)->idef());
1439 lua_pushboolean(L, result);
1443 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1444 // Returns leftover item stack
1445 static int l_add_item(lua_State *L)
1447 LuaItemStack *o = checkobject(L, 1);
1448 ItemStack &item = o->m_stack;
1449 ItemStack newitem = read_item(L, 2);
1450 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1451 create(L, leftover);
1455 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1456 // First return value is true iff the new item fits fully into the stack
1457 // Second return value is the would-be-left-over item stack
1458 static int l_item_fits(lua_State *L)
1460 LuaItemStack *o = checkobject(L, 1);
1461 ItemStack &item = o->m_stack;
1462 ItemStack newitem = read_item(L, 2);
1464 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1465 lua_pushboolean(L, fits); // first return value
1466 create(L, restitem); // second return value
1470 // take_item(self, takecount=1) -> itemstack
1471 static int l_take_item(lua_State *L)
1473 LuaItemStack *o = checkobject(L, 1);
1474 ItemStack &item = o->m_stack;
1476 if(!lua_isnone(L, 2))
1477 takecount = luaL_checkinteger(L, 2);
1478 ItemStack taken = item.takeItem(takecount);
1483 // peek_item(self, peekcount=1) -> itemstack
1484 static int l_peek_item(lua_State *L)
1486 LuaItemStack *o = checkobject(L, 1);
1487 ItemStack &item = o->m_stack;
1489 if(!lua_isnone(L, 2))
1490 peekcount = lua_tointeger(L, 2);
1491 ItemStack peekaboo = item.peekItem(peekcount);
1492 create(L, peekaboo);
1497 LuaItemStack(const ItemStack &item):
1506 const ItemStack& getItem() const
1510 ItemStack& getItem()
1515 // LuaItemStack(itemstack or itemstring or table or nil)
1516 // Creates an LuaItemStack and leaves it on top of stack
1517 static int create_object(lua_State *L)
1519 ItemStack item = read_item(L, 1);
1520 LuaItemStack *o = new LuaItemStack(item);
1521 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1522 luaL_getmetatable(L, className);
1523 lua_setmetatable(L, -2);
1526 // Not callable from Lua
1527 static int create(lua_State *L, const ItemStack &item)
1529 LuaItemStack *o = new LuaItemStack(item);
1530 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1531 luaL_getmetatable(L, className);
1532 lua_setmetatable(L, -2);
1536 static LuaItemStack* checkobject(lua_State *L, int narg)
1538 luaL_checktype(L, narg, LUA_TUSERDATA);
1539 void *ud = luaL_checkudata(L, narg, className);
1540 if(!ud) luaL_typerror(L, narg, className);
1541 return *(LuaItemStack**)ud; // unbox pointer
1544 static void Register(lua_State *L)
1547 int methodtable = lua_gettop(L);
1548 luaL_newmetatable(L, className);
1549 int metatable = lua_gettop(L);
1551 lua_pushliteral(L, "__metatable");
1552 lua_pushvalue(L, methodtable);
1553 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1555 lua_pushliteral(L, "__index");
1556 lua_pushvalue(L, methodtable);
1557 lua_settable(L, metatable);
1559 lua_pushliteral(L, "__gc");
1560 lua_pushcfunction(L, gc_object);
1561 lua_settable(L, metatable);
1563 lua_pop(L, 1); // drop metatable
1565 luaL_openlib(L, 0, methods, 0); // fill methodtable
1566 lua_pop(L, 1); // drop methodtable
1568 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1569 lua_register(L, className, create_object);
1572 const char LuaItemStack::className[] = "ItemStack";
1573 const luaL_reg LuaItemStack::methods[] = {
1574 method(LuaItemStack, is_empty),
1575 method(LuaItemStack, get_name),
1576 method(LuaItemStack, get_count),
1577 method(LuaItemStack, get_wear),
1578 method(LuaItemStack, get_metadata),
1579 method(LuaItemStack, clear),
1580 method(LuaItemStack, replace),
1581 method(LuaItemStack, to_string),
1582 method(LuaItemStack, to_table),
1583 method(LuaItemStack, get_stack_max),
1584 method(LuaItemStack, get_free_space),
1585 method(LuaItemStack, is_known),
1586 method(LuaItemStack, get_definition),
1587 method(LuaItemStack, get_tool_capabilities),
1588 method(LuaItemStack, add_wear),
1589 method(LuaItemStack, add_item),
1590 method(LuaItemStack, item_fits),
1591 method(LuaItemStack, take_item),
1592 method(LuaItemStack, peek_item),
1596 static ItemStack read_item(lua_State *L, int index)
1599 index = lua_gettop(L) + 1 + index;
1601 if(lua_isnil(L, index))
1605 else if(lua_isuserdata(L, index))
1607 // Convert from LuaItemStack
1608 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1609 return o->getItem();
1611 else if(lua_isstring(L, index))
1613 // Convert from itemstring
1614 std::string itemstring = lua_tostring(L, index);
1615 IItemDefManager *idef = get_server(L)->idef();
1619 item.deSerialize(itemstring, idef);
1622 catch(SerializationError &e)
1624 infostream<<"WARNING: unable to create item from itemstring"
1625 <<": "<<itemstring<<std::endl;
1629 else if(lua_istable(L, index))
1631 // Convert from table
1632 IItemDefManager *idef = get_server(L)->idef();
1633 std::string name = getstringfield_default(L, index, "name", "");
1634 int count = getintfield_default(L, index, "count", 1);
1635 int wear = getintfield_default(L, index, "wear", 0);
1636 std::string metadata = getstringfield_default(L, index, "metadata", "");
1637 return ItemStack(name, count, wear, metadata, idef);
1641 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1645 static std::vector<ItemStack> read_items(lua_State *L, int index)
1648 index = lua_gettop(L) + 1 + index;
1650 std::vector<ItemStack> items;
1651 luaL_checktype(L, index, LUA_TTABLE);
1653 while(lua_next(L, index) != 0){
1654 // key at index -2 and value at index -1
1655 items.push_back(read_item(L, -1));
1656 // removes value, keeps key for next iteration
1662 // creates a table of ItemStacks
1663 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1665 // Get the table insert function
1666 lua_getglobal(L, "table");
1667 lua_getfield(L, -1, "insert");
1668 int table_insert = lua_gettop(L);
1669 // Create and fill table
1671 int table = lua_gettop(L);
1672 for(u32 i=0; i<items.size(); i++){
1673 ItemStack item = items[i];
1674 lua_pushvalue(L, table_insert);
1675 lua_pushvalue(L, table);
1676 LuaItemStack::create(L, item);
1677 if(lua_pcall(L, 2, 0, 0))
1678 script_error(L, "error: %s", lua_tostring(L, -1));
1680 lua_remove(L, -2); // Remove table
1681 lua_remove(L, -2); // Remove insert
1691 InventoryLocation m_loc;
1693 static const char className[];
1694 static const luaL_reg methods[];
1696 static InvRef *checkobject(lua_State *L, int narg)
1698 luaL_checktype(L, narg, LUA_TUSERDATA);
1699 void *ud = luaL_checkudata(L, narg, className);
1700 if(!ud) luaL_typerror(L, narg, className);
1701 return *(InvRef**)ud; // unbox pointer
1704 static Inventory* getinv(lua_State *L, InvRef *ref)
1706 return get_server(L)->getInventory(ref->m_loc);
1709 static InventoryList* getlist(lua_State *L, InvRef *ref,
1710 const char *listname)
1712 Inventory *inv = getinv(L, ref);
1715 return inv->getList(listname);
1718 static void reportInventoryChange(lua_State *L, InvRef *ref)
1720 // Inform other things that the inventory has changed
1721 get_server(L)->setInventoryModified(ref->m_loc);
1724 // Exported functions
1726 // garbage collector
1727 static int gc_object(lua_State *L) {
1728 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1733 // is_empty(self, listname) -> true/false
1734 static int l_is_empty(lua_State *L)
1736 InvRef *ref = checkobject(L, 1);
1737 const char *listname = luaL_checkstring(L, 2);
1738 InventoryList *list = getlist(L, ref, listname);
1739 if(list && list->getUsedSlots() > 0){
1740 lua_pushboolean(L, false);
1742 lua_pushboolean(L, true);
1747 // get_size(self, listname)
1748 static int l_get_size(lua_State *L)
1750 InvRef *ref = checkobject(L, 1);
1751 const char *listname = luaL_checkstring(L, 2);
1752 InventoryList *list = getlist(L, ref, listname);
1754 lua_pushinteger(L, list->getSize());
1756 lua_pushinteger(L, 0);
1761 // set_size(self, listname, size)
1762 static int l_set_size(lua_State *L)
1764 InvRef *ref = checkobject(L, 1);
1765 const char *listname = luaL_checkstring(L, 2);
1766 int newsize = luaL_checknumber(L, 3);
1767 Inventory *inv = getinv(L, ref);
1769 inv->deleteList(listname);
1770 reportInventoryChange(L, ref);
1773 InventoryList *list = inv->getList(listname);
1775 list->setSize(newsize);
1777 list = inv->addList(listname, newsize);
1779 reportInventoryChange(L, ref);
1783 // get_stack(self, listname, i) -> itemstack
1784 static int l_get_stack(lua_State *L)
1786 InvRef *ref = checkobject(L, 1);
1787 const char *listname = luaL_checkstring(L, 2);
1788 int i = luaL_checknumber(L, 3) - 1;
1789 InventoryList *list = getlist(L, ref, listname);
1791 if(list != NULL && i >= 0 && i < (int) list->getSize())
1792 item = list->getItem(i);
1793 LuaItemStack::create(L, item);
1797 // set_stack(self, listname, i, stack) -> true/false
1798 static int l_set_stack(lua_State *L)
1800 InvRef *ref = checkobject(L, 1);
1801 const char *listname = luaL_checkstring(L, 2);
1802 int i = luaL_checknumber(L, 3) - 1;
1803 ItemStack newitem = read_item(L, 4);
1804 InventoryList *list = getlist(L, ref, listname);
1805 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1806 list->changeItem(i, newitem);
1807 reportInventoryChange(L, ref);
1808 lua_pushboolean(L, true);
1810 lua_pushboolean(L, false);
1815 // get_list(self, listname) -> list or nil
1816 static int l_get_list(lua_State *L)
1818 InvRef *ref = checkobject(L, 1);
1819 const char *listname = luaL_checkstring(L, 2);
1820 Inventory *inv = getinv(L, ref);
1821 inventory_get_list_to_lua(inv, listname, L);
1825 // set_list(self, listname, list)
1826 static int l_set_list(lua_State *L)
1828 InvRef *ref = checkobject(L, 1);
1829 const char *listname = luaL_checkstring(L, 2);
1830 Inventory *inv = getinv(L, ref);
1831 InventoryList *list = inv->getList(listname);
1833 inventory_set_list_from_lua(inv, listname, L, 3,
1836 inventory_set_list_from_lua(inv, listname, L, 3);
1837 reportInventoryChange(L, ref);
1841 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1842 // Returns the leftover stack
1843 static int l_add_item(lua_State *L)
1845 InvRef *ref = checkobject(L, 1);
1846 const char *listname = luaL_checkstring(L, 2);
1847 ItemStack item = read_item(L, 3);
1848 InventoryList *list = getlist(L, ref, listname);
1850 ItemStack leftover = list->addItem(item);
1851 if(leftover.count != item.count)
1852 reportInventoryChange(L, ref);
1853 LuaItemStack::create(L, leftover);
1855 LuaItemStack::create(L, item);
1860 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1861 // Returns true if the item completely fits into the list
1862 static int l_room_for_item(lua_State *L)
1864 InvRef *ref = checkobject(L, 1);
1865 const char *listname = luaL_checkstring(L, 2);
1866 ItemStack item = read_item(L, 3);
1867 InventoryList *list = getlist(L, ref, listname);
1869 lua_pushboolean(L, list->roomForItem(item));
1871 lua_pushboolean(L, false);
1876 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1877 // Returns true if the list contains the given count of the given item name
1878 static int l_contains_item(lua_State *L)
1880 InvRef *ref = checkobject(L, 1);
1881 const char *listname = luaL_checkstring(L, 2);
1882 ItemStack item = read_item(L, 3);
1883 InventoryList *list = getlist(L, ref, listname);
1885 lua_pushboolean(L, list->containsItem(item));
1887 lua_pushboolean(L, false);
1892 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1893 // Returns the items that were actually removed
1894 static int l_remove_item(lua_State *L)
1896 InvRef *ref = checkobject(L, 1);
1897 const char *listname = luaL_checkstring(L, 2);
1898 ItemStack item = read_item(L, 3);
1899 InventoryList *list = getlist(L, ref, listname);
1901 ItemStack removed = list->removeItem(item);
1902 if(!removed.empty())
1903 reportInventoryChange(L, ref);
1904 LuaItemStack::create(L, removed);
1906 LuaItemStack::create(L, ItemStack());
1912 InvRef(const InventoryLocation &loc):
1921 // Creates an InvRef and leaves it on top of stack
1922 // Not callable from Lua; all references are created on the C side.
1923 static void create(lua_State *L, const InventoryLocation &loc)
1925 InvRef *o = new InvRef(loc);
1926 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1927 luaL_getmetatable(L, className);
1928 lua_setmetatable(L, -2);
1930 static void createPlayer(lua_State *L, Player *player)
1932 InventoryLocation loc;
1933 loc.setPlayer(player->getName());
1936 static void createNodeMeta(lua_State *L, v3s16 p)
1938 InventoryLocation loc;
1943 static void Register(lua_State *L)
1946 int methodtable = lua_gettop(L);
1947 luaL_newmetatable(L, className);
1948 int metatable = lua_gettop(L);
1950 lua_pushliteral(L, "__metatable");
1951 lua_pushvalue(L, methodtable);
1952 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1954 lua_pushliteral(L, "__index");
1955 lua_pushvalue(L, methodtable);
1956 lua_settable(L, metatable);
1958 lua_pushliteral(L, "__gc");
1959 lua_pushcfunction(L, gc_object);
1960 lua_settable(L, metatable);
1962 lua_pop(L, 1); // drop metatable
1964 luaL_openlib(L, 0, methods, 0); // fill methodtable
1965 lua_pop(L, 1); // drop methodtable
1967 // Cannot be created from Lua
1968 //lua_register(L, className, create_object);
1971 const char InvRef::className[] = "InvRef";
1972 const luaL_reg InvRef::methods[] = {
1973 method(InvRef, is_empty),
1974 method(InvRef, get_size),
1975 method(InvRef, set_size),
1976 method(InvRef, get_stack),
1977 method(InvRef, set_stack),
1978 method(InvRef, get_list),
1979 method(InvRef, set_list),
1980 method(InvRef, add_item),
1981 method(InvRef, room_for_item),
1982 method(InvRef, contains_item),
1983 method(InvRef, remove_item),
1995 ServerEnvironment *m_env;
1997 static const char className[];
1998 static const luaL_reg methods[];
2000 static NodeMetaRef *checkobject(lua_State *L, int narg)
2002 luaL_checktype(L, narg, LUA_TUSERDATA);
2003 void *ud = luaL_checkudata(L, narg, className);
2004 if(!ud) luaL_typerror(L, narg, className);
2005 return *(NodeMetaRef**)ud; // unbox pointer
2008 static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2010 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2011 if(meta == NULL && auto_create)
2013 meta = new NodeMetadata(ref->m_env->getGameDef());
2014 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2019 static void reportMetadataChange(NodeMetaRef *ref)
2021 // Inform other things that the metadata has changed
2022 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2024 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2026 ref->m_env->getMap().dispatchEvent(&event);
2027 // Set the block to be saved
2028 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2030 block->raiseModified(MOD_STATE_WRITE_NEEDED,
2031 "NodeMetaRef::reportMetadataChange");
2034 // Exported functions
2036 // garbage collector
2037 static int gc_object(lua_State *L) {
2038 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2043 // get_string(self, name)
2044 static int l_get_string(lua_State *L)
2046 NodeMetaRef *ref = checkobject(L, 1);
2047 std::string name = luaL_checkstring(L, 2);
2049 NodeMetadata *meta = getmeta(ref, false);
2051 lua_pushlstring(L, "", 0);
2054 std::string str = meta->getString(name);
2055 lua_pushlstring(L, str.c_str(), str.size());
2059 // set_string(self, name, var)
2060 static int l_set_string(lua_State *L)
2062 NodeMetaRef *ref = checkobject(L, 1);
2063 std::string name = luaL_checkstring(L, 2);
2065 const char *s = lua_tolstring(L, 3, &len);
2066 std::string str(s, len);
2068 NodeMetadata *meta = getmeta(ref, !str.empty());
2069 if(meta == NULL || str == meta->getString(name))
2071 meta->setString(name, str);
2072 reportMetadataChange(ref);
2076 // get_int(self, name)
2077 static int l_get_int(lua_State *L)
2079 NodeMetaRef *ref = checkobject(L, 1);
2080 std::string name = lua_tostring(L, 2);
2082 NodeMetadata *meta = getmeta(ref, false);
2084 lua_pushnumber(L, 0);
2087 std::string str = meta->getString(name);
2088 lua_pushnumber(L, stoi(str));
2092 // set_int(self, name, var)
2093 static int l_set_int(lua_State *L)
2095 NodeMetaRef *ref = checkobject(L, 1);
2096 std::string name = lua_tostring(L, 2);
2097 int a = lua_tointeger(L, 3);
2098 std::string str = itos(a);
2100 NodeMetadata *meta = getmeta(ref, true);
2101 if(meta == NULL || str == meta->getString(name))
2103 meta->setString(name, str);
2104 reportMetadataChange(ref);
2108 // get_float(self, name)
2109 static int l_get_float(lua_State *L)
2111 NodeMetaRef *ref = checkobject(L, 1);
2112 std::string name = lua_tostring(L, 2);
2114 NodeMetadata *meta = getmeta(ref, false);
2116 lua_pushnumber(L, 0);
2119 std::string str = meta->getString(name);
2120 lua_pushnumber(L, stof(str));
2124 // set_float(self, name, var)
2125 static int l_set_float(lua_State *L)
2127 NodeMetaRef *ref = checkobject(L, 1);
2128 std::string name = lua_tostring(L, 2);
2129 float a = lua_tonumber(L, 3);
2130 std::string str = ftos(a);
2132 NodeMetadata *meta = getmeta(ref, true);
2133 if(meta == NULL || str == meta->getString(name))
2135 meta->setString(name, str);
2136 reportMetadataChange(ref);
2140 // get_inventory(self)
2141 static int l_get_inventory(lua_State *L)
2143 NodeMetaRef *ref = checkobject(L, 1);
2144 getmeta(ref, true); // try to ensure the metadata exists
2145 InvRef::createNodeMeta(L, ref->m_p);
2150 static int l_to_table(lua_State *L)
2152 NodeMetaRef *ref = checkobject(L, 1);
2154 NodeMetadata *meta = getmeta(ref, true);
2163 std::map<std::string, std::string> fields = meta->getStrings();
2164 for(std::map<std::string, std::string>::const_iterator
2165 i = fields.begin(); i != fields.end(); i++){
2166 const std::string &name = i->first;
2167 const std::string &value = i->second;
2168 lua_pushlstring(L, name.c_str(), name.size());
2169 lua_pushlstring(L, value.c_str(), value.size());
2170 lua_settable(L, -3);
2173 lua_setfield(L, -2, "fields");
2176 Inventory *inv = meta->getInventory();
2178 std::vector<const InventoryList*> lists = inv->getLists();
2179 for(std::vector<const InventoryList*>::const_iterator
2180 i = lists.begin(); i != lists.end(); i++){
2181 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2182 lua_setfield(L, -2, (*i)->getName().c_str());
2185 lua_setfield(L, -2, "inventory");
2189 // from_table(self, table)
2190 static int l_from_table(lua_State *L)
2192 NodeMetaRef *ref = checkobject(L, 1);
2195 if(lua_isnil(L, base)){
2197 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2198 lua_pushboolean(L, true);
2202 // Has metadata; clear old one first
2203 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2204 // Create new metadata
2205 NodeMetadata *meta = getmeta(ref, true);
2207 lua_getfield(L, base, "fields");
2208 int fieldstable = lua_gettop(L);
2210 while(lua_next(L, fieldstable) != 0){
2211 // key at index -2 and value at index -1
2212 std::string name = lua_tostring(L, -2);
2214 const char *cs = lua_tolstring(L, -1, &cl);
2215 std::string value(cs, cl);
2216 meta->setString(name, value);
2217 lua_pop(L, 1); // removes value, keeps key for next iteration
2220 Inventory *inv = meta->getInventory();
2221 lua_getfield(L, base, "inventory");
2222 int inventorytable = lua_gettop(L);
2224 while(lua_next(L, inventorytable) != 0){
2225 // key at index -2 and value at index -1
2226 std::string name = lua_tostring(L, -2);
2227 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2228 lua_pop(L, 1); // removes value, keeps key for next iteration
2230 reportMetadataChange(ref);
2231 lua_pushboolean(L, true);
2236 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2246 // Creates an NodeMetaRef and leaves it on top of stack
2247 // Not callable from Lua; all references are created on the C side.
2248 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2250 NodeMetaRef *o = new NodeMetaRef(p, env);
2251 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2252 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2253 luaL_getmetatable(L, className);
2254 lua_setmetatable(L, -2);
2257 static void Register(lua_State *L)
2260 int methodtable = lua_gettop(L);
2261 luaL_newmetatable(L, className);
2262 int metatable = lua_gettop(L);
2264 lua_pushliteral(L, "__metatable");
2265 lua_pushvalue(L, methodtable);
2266 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2268 lua_pushliteral(L, "__index");
2269 lua_pushvalue(L, methodtable);
2270 lua_settable(L, metatable);
2272 lua_pushliteral(L, "__gc");
2273 lua_pushcfunction(L, gc_object);
2274 lua_settable(L, metatable);
2276 lua_pop(L, 1); // drop metatable
2278 luaL_openlib(L, 0, methods, 0); // fill methodtable
2279 lua_pop(L, 1); // drop methodtable
2281 // Cannot be created from Lua
2282 //lua_register(L, className, create_object);
2285 const char NodeMetaRef::className[] = "NodeMetaRef";
2286 const luaL_reg NodeMetaRef::methods[] = {
2287 method(NodeMetaRef, get_string),
2288 method(NodeMetaRef, set_string),
2289 method(NodeMetaRef, get_int),
2290 method(NodeMetaRef, set_int),
2291 method(NodeMetaRef, get_float),
2292 method(NodeMetaRef, set_float),
2293 method(NodeMetaRef, get_inventory),
2294 method(NodeMetaRef, to_table),
2295 method(NodeMetaRef, from_table),
2306 ServerActiveObject *m_object;
2308 static const char className[];
2309 static const luaL_reg methods[];
2311 static ObjectRef *checkobject(lua_State *L, int narg)
2313 luaL_checktype(L, narg, LUA_TUSERDATA);
2314 void *ud = luaL_checkudata(L, narg, className);
2315 if(!ud) luaL_typerror(L, narg, className);
2316 return *(ObjectRef**)ud; // unbox pointer
2319 static ServerActiveObject* getobject(ObjectRef *ref)
2321 ServerActiveObject *co = ref->m_object;
2325 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2327 ServerActiveObject *obj = getobject(ref);
2330 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2332 return (LuaEntitySAO*)obj;
2335 static PlayerSAO* getplayersao(ObjectRef *ref)
2337 ServerActiveObject *obj = getobject(ref);
2340 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2342 return (PlayerSAO*)obj;
2345 static Player* getplayer(ObjectRef *ref)
2347 PlayerSAO *playersao = getplayersao(ref);
2348 if(playersao == NULL)
2350 return playersao->getPlayer();
2353 // Exported functions
2355 // garbage collector
2356 static int gc_object(lua_State *L) {
2357 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2358 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2364 static int l_remove(lua_State *L)
2366 ObjectRef *ref = checkobject(L, 1);
2367 ServerActiveObject *co = getobject(ref);
2368 if(co == NULL) return 0;
2369 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2370 co->m_removed = true;
2375 // returns: {x=num, y=num, z=num}
2376 static int l_getpos(lua_State *L)
2378 ObjectRef *ref = checkobject(L, 1);
2379 ServerActiveObject *co = getobject(ref);
2380 if(co == NULL) return 0;
2381 v3f pos = co->getBasePosition() / BS;
2383 lua_pushnumber(L, pos.X);
2384 lua_setfield(L, -2, "x");
2385 lua_pushnumber(L, pos.Y);
2386 lua_setfield(L, -2, "y");
2387 lua_pushnumber(L, pos.Z);
2388 lua_setfield(L, -2, "z");
2392 // setpos(self, pos)
2393 static int l_setpos(lua_State *L)
2395 ObjectRef *ref = checkobject(L, 1);
2396 //LuaEntitySAO *co = getluaobject(ref);
2397 ServerActiveObject *co = getobject(ref);
2398 if(co == NULL) return 0;
2400 v3f pos = checkFloatPos(L, 2);
2406 // moveto(self, pos, continuous=false)
2407 static int l_moveto(lua_State *L)
2409 ObjectRef *ref = checkobject(L, 1);
2410 //LuaEntitySAO *co = getluaobject(ref);
2411 ServerActiveObject *co = getobject(ref);
2412 if(co == NULL) return 0;
2414 v3f pos = checkFloatPos(L, 2);
2416 bool continuous = lua_toboolean(L, 3);
2418 co->moveTo(pos, continuous);
2422 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2423 static int l_punch(lua_State *L)
2425 ObjectRef *ref = checkobject(L, 1);
2426 ObjectRef *puncher_ref = checkobject(L, 2);
2427 ServerActiveObject *co = getobject(ref);
2428 ServerActiveObject *puncher = getobject(puncher_ref);
2429 if(co == NULL) return 0;
2430 if(puncher == NULL) return 0;
2431 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2432 v3f dir = read_v3f(L, 4);
2433 float time_from_last_punch = 1000000;
2434 if(lua_isnumber(L, 5))
2435 time_from_last_punch = lua_tonumber(L, 5);
2437 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2441 // right_click(self, clicker); clicker = an another ObjectRef
2442 static int l_right_click(lua_State *L)
2444 ObjectRef *ref = checkobject(L, 1);
2445 ObjectRef *ref2 = checkobject(L, 2);
2446 ServerActiveObject *co = getobject(ref);
2447 ServerActiveObject *co2 = getobject(ref2);
2448 if(co == NULL) return 0;
2449 if(co2 == NULL) return 0;
2451 co->rightClick(co2);
2456 // hp = number of hitpoints (2 * number of hearts)
2458 static int l_set_hp(lua_State *L)
2460 ObjectRef *ref = checkobject(L, 1);
2461 luaL_checknumber(L, 2);
2462 ServerActiveObject *co = getobject(ref);
2463 if(co == NULL) return 0;
2464 int hp = lua_tonumber(L, 2);
2465 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2466 <<" hp="<<hp<<std::endl;*/
2474 // returns: number of hitpoints (2 * number of hearts)
2475 // 0 if not applicable to this type of object
2476 static int l_get_hp(lua_State *L)
2478 ObjectRef *ref = checkobject(L, 1);
2479 ServerActiveObject *co = getobject(ref);
2482 lua_pushnumber(L, 1);
2485 int hp = co->getHP();
2486 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2487 <<" hp="<<hp<<std::endl;*/
2489 lua_pushnumber(L, hp);
2493 // get_inventory(self)
2494 static int l_get_inventory(lua_State *L)
2496 ObjectRef *ref = checkobject(L, 1);
2497 ServerActiveObject *co = getobject(ref);
2498 if(co == NULL) return 0;
2500 InventoryLocation loc = co->getInventoryLocation();
2501 if(get_server(L)->getInventory(loc) != NULL)
2502 InvRef::create(L, loc);
2504 lua_pushnil(L); // An object may have no inventory (nil)
2508 // get_wield_list(self)
2509 static int l_get_wield_list(lua_State *L)
2511 ObjectRef *ref = checkobject(L, 1);
2512 ServerActiveObject *co = getobject(ref);
2513 if(co == NULL) return 0;
2515 lua_pushstring(L, co->getWieldList().c_str());
2519 // get_wield_index(self)
2520 static int l_get_wield_index(lua_State *L)
2522 ObjectRef *ref = checkobject(L, 1);
2523 ServerActiveObject *co = getobject(ref);
2524 if(co == NULL) return 0;
2526 lua_pushinteger(L, co->getWieldIndex() + 1);
2530 // get_wielded_item(self)
2531 static int l_get_wielded_item(lua_State *L)
2533 ObjectRef *ref = checkobject(L, 1);
2534 ServerActiveObject *co = getobject(ref);
2537 LuaItemStack::create(L, ItemStack());
2541 LuaItemStack::create(L, co->getWieldedItem());
2545 // set_wielded_item(self, itemstack or itemstring or table or nil)
2546 static int l_set_wielded_item(lua_State *L)
2548 ObjectRef *ref = checkobject(L, 1);
2549 ServerActiveObject *co = getobject(ref);
2550 if(co == NULL) return 0;
2552 ItemStack item = read_item(L, 2);
2553 bool success = co->setWieldedItem(item);
2554 lua_pushboolean(L, success);
2558 // set_armor_groups(self, groups)
2559 static int l_set_armor_groups(lua_State *L)
2561 ObjectRef *ref = checkobject(L, 1);
2562 ServerActiveObject *co = getobject(ref);
2563 if(co == NULL) return 0;
2565 ItemGroupList groups;
2566 read_groups(L, 2, groups);
2567 co->setArmorGroups(groups);
2571 // set_properties(self, properties)
2572 static int l_set_properties(lua_State *L)
2574 ObjectRef *ref = checkobject(L, 1);
2575 ServerActiveObject *co = getobject(ref);
2576 if(co == NULL) return 0;
2577 ObjectProperties *prop = co->accessObjectProperties();
2580 read_object_properties(L, 2, prop);
2581 co->notifyObjectPropertiesModified();
2585 /* LuaEntitySAO-only */
2587 // setvelocity(self, {x=num, y=num, z=num})
2588 static int l_setvelocity(lua_State *L)
2590 ObjectRef *ref = checkobject(L, 1);
2591 LuaEntitySAO *co = getluaobject(ref);
2592 if(co == NULL) return 0;
2593 v3f pos = checkFloatPos(L, 2);
2595 co->setVelocity(pos);
2599 // getvelocity(self)
2600 static int l_getvelocity(lua_State *L)
2602 ObjectRef *ref = checkobject(L, 1);
2603 LuaEntitySAO *co = getluaobject(ref);
2604 if(co == NULL) return 0;
2606 v3f v = co->getVelocity();
2611 // setacceleration(self, {x=num, y=num, z=num})
2612 static int l_setacceleration(lua_State *L)
2614 ObjectRef *ref = checkobject(L, 1);
2615 LuaEntitySAO *co = getluaobject(ref);
2616 if(co == NULL) return 0;
2618 v3f pos = checkFloatPos(L, 2);
2620 co->setAcceleration(pos);
2624 // getacceleration(self)
2625 static int l_getacceleration(lua_State *L)
2627 ObjectRef *ref = checkobject(L, 1);
2628 LuaEntitySAO *co = getluaobject(ref);
2629 if(co == NULL) return 0;
2631 v3f v = co->getAcceleration();
2636 // setyaw(self, radians)
2637 static int l_setyaw(lua_State *L)
2639 ObjectRef *ref = checkobject(L, 1);
2640 LuaEntitySAO *co = getluaobject(ref);
2641 if(co == NULL) return 0;
2642 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2649 static int l_getyaw(lua_State *L)
2651 ObjectRef *ref = checkobject(L, 1);
2652 LuaEntitySAO *co = getluaobject(ref);
2653 if(co == NULL) return 0;
2655 float yaw = co->getYaw() * core::DEGTORAD;
2656 lua_pushnumber(L, yaw);
2660 // settexturemod(self, mod)
2661 static int l_settexturemod(lua_State *L)
2663 ObjectRef *ref = checkobject(L, 1);
2664 LuaEntitySAO *co = getluaobject(ref);
2665 if(co == NULL) return 0;
2667 std::string mod = luaL_checkstring(L, 2);
2668 co->setTextureMod(mod);
2672 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2673 // select_horiz_by_yawpitch=false)
2674 static int l_setsprite(lua_State *L)
2676 ObjectRef *ref = checkobject(L, 1);
2677 LuaEntitySAO *co = getluaobject(ref);
2678 if(co == NULL) return 0;
2681 if(!lua_isnil(L, 2))
2682 p = read_v2s16(L, 2);
2684 if(!lua_isnil(L, 3))
2685 num_frames = lua_tonumber(L, 3);
2686 float framelength = 0.2;
2687 if(!lua_isnil(L, 4))
2688 framelength = lua_tonumber(L, 4);
2689 bool select_horiz_by_yawpitch = false;
2690 if(!lua_isnil(L, 5))
2691 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2692 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2697 // get_entity_name(self)
2698 static int l_get_entity_name(lua_State *L)
2700 ObjectRef *ref = checkobject(L, 1);
2701 LuaEntitySAO *co = getluaobject(ref);
2702 if(co == NULL) return 0;
2704 std::string name = co->getName();
2705 lua_pushstring(L, name.c_str());
2709 // get_luaentity(self)
2710 static int l_get_luaentity(lua_State *L)
2712 ObjectRef *ref = checkobject(L, 1);
2713 LuaEntitySAO *co = getluaobject(ref);
2714 if(co == NULL) return 0;
2716 luaentity_get(L, co->getId());
2723 static int l_is_player(lua_State *L)
2725 ObjectRef *ref = checkobject(L, 1);
2726 Player *player = getplayer(ref);
2727 lua_pushboolean(L, (player != NULL));
2731 // get_player_name(self)
2732 static int l_get_player_name(lua_State *L)
2734 ObjectRef *ref = checkobject(L, 1);
2735 Player *player = getplayer(ref);
2737 lua_pushlstring(L, "", 0);
2741 lua_pushstring(L, player->getName());
2745 // get_look_dir(self)
2746 static int l_get_look_dir(lua_State *L)
2748 ObjectRef *ref = checkobject(L, 1);
2749 Player *player = getplayer(ref);
2750 if(player == NULL) return 0;
2752 float pitch = player->getRadPitch();
2753 float yaw = player->getRadYaw();
2754 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2759 // get_look_pitch(self)
2760 static int l_get_look_pitch(lua_State *L)
2762 ObjectRef *ref = checkobject(L, 1);
2763 Player *player = getplayer(ref);
2764 if(player == NULL) return 0;
2766 lua_pushnumber(L, player->getRadPitch());
2770 // get_look_yaw(self)
2771 static int l_get_look_yaw(lua_State *L)
2773 ObjectRef *ref = checkobject(L, 1);
2774 Player *player = getplayer(ref);
2775 if(player == NULL) return 0;
2777 lua_pushnumber(L, player->getRadYaw());
2782 ObjectRef(ServerActiveObject *object):
2785 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2791 infostream<<"ObjectRef destructing for id="
2792 <<m_object->getId()<<std::endl;
2794 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2797 // Creates an ObjectRef and leaves it on top of stack
2798 // Not callable from Lua; all references are created on the C side.
2799 static void create(lua_State *L, ServerActiveObject *object)
2801 ObjectRef *o = new ObjectRef(object);
2802 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2803 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2804 luaL_getmetatable(L, className);
2805 lua_setmetatable(L, -2);
2808 static void set_null(lua_State *L)
2810 ObjectRef *o = checkobject(L, -1);
2814 static void Register(lua_State *L)
2817 int methodtable = lua_gettop(L);
2818 luaL_newmetatable(L, className);
2819 int metatable = lua_gettop(L);
2821 lua_pushliteral(L, "__metatable");
2822 lua_pushvalue(L, methodtable);
2823 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2825 lua_pushliteral(L, "__index");
2826 lua_pushvalue(L, methodtable);
2827 lua_settable(L, metatable);
2829 lua_pushliteral(L, "__gc");
2830 lua_pushcfunction(L, gc_object);
2831 lua_settable(L, metatable);
2833 lua_pop(L, 1); // drop metatable
2835 luaL_openlib(L, 0, methods, 0); // fill methodtable
2836 lua_pop(L, 1); // drop methodtable
2838 // Cannot be created from Lua
2839 //lua_register(L, className, create_object);
2842 const char ObjectRef::className[] = "ObjectRef";
2843 const luaL_reg ObjectRef::methods[] = {
2844 // ServerActiveObject
2845 method(ObjectRef, remove),
2846 method(ObjectRef, getpos),
2847 method(ObjectRef, setpos),
2848 method(ObjectRef, moveto),
2849 method(ObjectRef, punch),
2850 method(ObjectRef, right_click),
2851 method(ObjectRef, set_hp),
2852 method(ObjectRef, get_hp),
2853 method(ObjectRef, get_inventory),
2854 method(ObjectRef, get_wield_list),
2855 method(ObjectRef, get_wield_index),
2856 method(ObjectRef, get_wielded_item),
2857 method(ObjectRef, set_wielded_item),
2858 method(ObjectRef, set_armor_groups),
2859 method(ObjectRef, set_properties),
2860 // LuaEntitySAO-only
2861 method(ObjectRef, setvelocity),
2862 method(ObjectRef, getvelocity),
2863 method(ObjectRef, setacceleration),
2864 method(ObjectRef, getacceleration),
2865 method(ObjectRef, setyaw),
2866 method(ObjectRef, getyaw),
2867 method(ObjectRef, settexturemod),
2868 method(ObjectRef, setsprite),
2869 method(ObjectRef, get_entity_name),
2870 method(ObjectRef, get_luaentity),
2872 method(ObjectRef, get_player_name),
2873 method(ObjectRef, get_look_dir),
2874 method(ObjectRef, get_look_pitch),
2875 method(ObjectRef, get_look_yaw),
2879 // Creates a new anonymous reference if cobj=NULL or id=0
2880 static void objectref_get_or_create(lua_State *L,
2881 ServerActiveObject *cobj)
2883 if(cobj == NULL || cobj->getId() == 0){
2884 ObjectRef::create(L, cobj);
2886 objectref_get(L, cobj->getId());
2895 class LuaPerlinNoise
2902 static const char className[];
2903 static const luaL_reg methods[];
2905 // Exported functions
2907 // garbage collector
2908 static int gc_object(lua_State *L)
2910 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
2915 static int l_get2d(lua_State *L)
2917 LuaPerlinNoise *o = checkobject(L, 1);
2918 v2f pos2d = read_v2f(L,2);
2919 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
2920 lua_pushnumber(L, val);
2923 static int l_get3d(lua_State *L)
2925 LuaPerlinNoise *o = checkobject(L, 1);
2926 v3f pos3d = read_v3f(L,2);
2927 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
2928 lua_pushnumber(L, val);
2933 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
2937 persistence(a_persistence),
2946 // LuaPerlinNoise(seed, octaves, persistence, scale)
2947 // Creates an LuaPerlinNoise and leaves it on top of stack
2948 static int create_object(lua_State *L)
2950 int seed = luaL_checkint(L, 1);
2951 int octaves = luaL_checkint(L, 2);
2952 double persistence = luaL_checknumber(L, 3);
2953 double scale = luaL_checknumber(L, 4);
2954 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
2955 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2956 luaL_getmetatable(L, className);
2957 lua_setmetatable(L, -2);
2961 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
2963 luaL_checktype(L, narg, LUA_TUSERDATA);
2964 void *ud = luaL_checkudata(L, narg, className);
2965 if(!ud) luaL_typerror(L, narg, className);
2966 return *(LuaPerlinNoise**)ud; // unbox pointer
2969 static void Register(lua_State *L)
2972 int methodtable = lua_gettop(L);
2973 luaL_newmetatable(L, className);
2974 int metatable = lua_gettop(L);
2976 lua_pushliteral(L, "__metatable");
2977 lua_pushvalue(L, methodtable);
2978 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2980 lua_pushliteral(L, "__index");
2981 lua_pushvalue(L, methodtable);
2982 lua_settable(L, metatable);
2984 lua_pushliteral(L, "__gc");
2985 lua_pushcfunction(L, gc_object);
2986 lua_settable(L, metatable);
2988 lua_pop(L, 1); // drop metatable
2990 luaL_openlib(L, 0, methods, 0); // fill methodtable
2991 lua_pop(L, 1); // drop methodtable
2993 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
2994 lua_register(L, className, create_object);
2997 const char LuaPerlinNoise::className[] = "PerlinNoise";
2998 const luaL_reg LuaPerlinNoise::methods[] = {
2999 method(LuaPerlinNoise, get2d),
3000 method(LuaPerlinNoise, get3d),
3011 ServerEnvironment *m_env;
3013 static const char className[];
3014 static const luaL_reg methods[];
3016 static int gc_object(lua_State *L) {
3017 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3022 static EnvRef *checkobject(lua_State *L, int narg)
3024 luaL_checktype(L, narg, LUA_TUSERDATA);
3025 void *ud = luaL_checkudata(L, narg, className);
3026 if(!ud) luaL_typerror(L, narg, className);
3027 return *(EnvRef**)ud; // unbox pointer
3030 // Exported functions
3032 // EnvRef:set_node(pos, node)
3033 // pos = {x=num, y=num, z=num}
3034 static int l_set_node(lua_State *L)
3036 EnvRef *o = checkobject(L, 1);
3037 ServerEnvironment *env = o->m_env;
3038 if(env == NULL) return 0;
3039 INodeDefManager *ndef = env->getGameDef()->ndef();
3041 v3s16 pos = read_v3s16(L, 2);
3042 MapNode n = readnode(L, 3, ndef);
3044 MapNode n_old = env->getMap().getNodeNoEx(pos);
3046 if(ndef->get(n_old).has_on_destruct)
3047 scriptapi_node_on_destruct(L, pos, n_old);
3049 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3051 // Call post-destructor
3052 if(ndef->get(n_old).has_after_destruct)
3053 scriptapi_node_after_destruct(L, pos, n_old);
3055 if(ndef->get(n).has_on_construct)
3056 scriptapi_node_on_construct(L, pos, n);
3058 lua_pushboolean(L, succeeded);
3062 static int l_add_node(lua_State *L)
3064 return l_set_node(L);
3067 // EnvRef:remove_node(pos)
3068 // pos = {x=num, y=num, z=num}
3069 static int l_remove_node(lua_State *L)
3071 EnvRef *o = checkobject(L, 1);
3072 ServerEnvironment *env = o->m_env;
3073 if(env == NULL) return 0;
3074 INodeDefManager *ndef = env->getGameDef()->ndef();
3076 v3s16 pos = read_v3s16(L, 2);
3078 MapNode n_old = env->getMap().getNodeNoEx(pos);
3080 if(ndef->get(n_old).has_on_destruct)
3081 scriptapi_node_on_destruct(L, pos, n_old);
3083 // This is slightly optimized compared to addNodeWithEvent(air)
3084 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3086 // Call post-destructor
3087 if(ndef->get(n_old).has_after_destruct)
3088 scriptapi_node_after_destruct(L, pos, n_old);
3090 lua_pushboolean(L, succeeded);
3091 // Air doesn't require constructor
3095 // EnvRef:get_node(pos)
3096 // pos = {x=num, y=num, z=num}
3097 static int l_get_node(lua_State *L)
3099 EnvRef *o = checkobject(L, 1);
3100 ServerEnvironment *env = o->m_env;
3101 if(env == NULL) return 0;
3103 v3s16 pos = read_v3s16(L, 2);
3105 MapNode n = env->getMap().getNodeNoEx(pos);
3107 pushnode(L, n, env->getGameDef()->ndef());
3111 // EnvRef:get_node_or_nil(pos)
3112 // pos = {x=num, y=num, z=num}
3113 static int l_get_node_or_nil(lua_State *L)
3115 EnvRef *o = checkobject(L, 1);
3116 ServerEnvironment *env = o->m_env;
3117 if(env == NULL) return 0;
3119 v3s16 pos = read_v3s16(L, 2);
3122 MapNode n = env->getMap().getNode(pos);
3124 pushnode(L, n, env->getGameDef()->ndef());
3126 } catch(InvalidPositionException &e)
3133 // EnvRef:get_node_light(pos, timeofday)
3134 // pos = {x=num, y=num, z=num}
3135 // timeofday: nil = current time, 0 = night, 0.5 = day
3136 static int l_get_node_light(lua_State *L)
3138 EnvRef *o = checkobject(L, 1);
3139 ServerEnvironment *env = o->m_env;
3140 if(env == NULL) return 0;
3142 v3s16 pos = read_v3s16(L, 2);
3143 u32 time_of_day = env->getTimeOfDay();
3144 if(lua_isnumber(L, 3))
3145 time_of_day = 24000.0 * lua_tonumber(L, 3);
3146 time_of_day %= 24000;
3147 u32 dnr = time_to_daynight_ratio(time_of_day);
3148 MapNode n = env->getMap().getNodeNoEx(pos);
3150 MapNode n = env->getMap().getNode(pos);
3151 INodeDefManager *ndef = env->getGameDef()->ndef();
3152 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3154 } catch(InvalidPositionException &e)
3161 // EnvRef:place_node(pos, node)
3162 // pos = {x=num, y=num, z=num}
3163 static int l_place_node(lua_State *L)
3165 EnvRef *o = checkobject(L, 1);
3166 ServerEnvironment *env = o->m_env;
3167 if(env == NULL) return 0;
3168 v3s16 pos = read_v3s16(L, 2);
3169 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3171 // Don't attempt to load non-loaded area as of now
3172 MapNode n_old = env->getMap().getNodeNoEx(pos);
3173 if(n_old.getContent() == CONTENT_IGNORE){
3174 lua_pushboolean(L, false);
3177 // Create item to place
3178 INodeDefManager *ndef = get_server(L)->ndef();
3179 IItemDefManager *idef = get_server(L)->idef();
3180 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3181 // Make pointed position
3182 PointedThing pointed;
3183 pointed.type = POINTEDTHING_NODE;
3184 pointed.node_abovesurface = pos;
3185 pointed.node_undersurface = pos + v3s16(0,-1,0);
3186 // Place it with a NULL placer (appears in Lua as a non-functional
3188 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3189 lua_pushboolean(L, success);
3193 // EnvRef:dig_node(pos)
3194 // pos = {x=num, y=num, z=num}
3195 static int l_dig_node(lua_State *L)
3197 EnvRef *o = checkobject(L, 1);
3198 ServerEnvironment *env = o->m_env;
3199 if(env == NULL) return 0;
3200 v3s16 pos = read_v3s16(L, 2);
3202 // Don't attempt to load non-loaded area as of now
3203 MapNode n = env->getMap().getNodeNoEx(pos);
3204 if(n.getContent() == CONTENT_IGNORE){
3205 lua_pushboolean(L, false);
3208 // Dig it out with a NULL digger (appears in Lua as a
3209 // non-functional ObjectRef)
3210 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3211 lua_pushboolean(L, success);
3215 // EnvRef:punch_node(pos)
3216 // pos = {x=num, y=num, z=num}
3217 static int l_punch_node(lua_State *L)
3219 EnvRef *o = checkobject(L, 1);
3220 ServerEnvironment *env = o->m_env;
3221 if(env == NULL) return 0;
3222 v3s16 pos = read_v3s16(L, 2);
3224 // Don't attempt to load non-loaded area as of now
3225 MapNode n = env->getMap().getNodeNoEx(pos);
3226 if(n.getContent() == CONTENT_IGNORE){
3227 lua_pushboolean(L, false);
3230 // Punch it with a NULL puncher (appears in Lua as a non-functional
3232 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3233 lua_pushboolean(L, success);
3237 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3238 // pos = {x=num, y=num, z=num}
3239 static int l_add_entity(lua_State *L)
3241 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3242 EnvRef *o = checkobject(L, 1);
3243 ServerEnvironment *env = o->m_env;
3244 if(env == NULL) return 0;
3246 v3f pos = checkFloatPos(L, 2);
3248 const char *name = luaL_checkstring(L, 3);
3250 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3251 int objectid = env->addActiveObject(obj);
3252 // If failed to add, return nothing (reads as nil)
3256 objectref_get_or_create(L, obj);
3260 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3261 // pos = {x=num, y=num, z=num}
3262 static int l_add_item(lua_State *L)
3264 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3265 EnvRef *o = checkobject(L, 1);
3266 ServerEnvironment *env = o->m_env;
3267 if(env == NULL) return 0;
3269 v3f pos = checkFloatPos(L, 2);
3271 ItemStack item = read_item(L, 3);
3272 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3274 // Use minetest.spawn_item to spawn a __builtin:item
3275 lua_getglobal(L, "minetest");
3276 lua_getfield(L, -1, "spawn_item");
3277 if(lua_isnil(L, -1))
3279 lua_pushvalue(L, 2);
3280 lua_pushstring(L, item.getItemString().c_str());
3281 if(lua_pcall(L, 2, 1, 0))
3282 script_error(L, "error: %s", lua_tostring(L, -1));
3284 /*lua_pushvalue(L, 1);
3285 lua_pushstring(L, "__builtin:item");
3286 lua_pushstring(L, item.getItemString().c_str());
3287 return l_add_entity(L);*/
3289 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3290 int objectid = env->addActiveObject(obj);
3291 // If failed to add, return nothing (reads as nil)
3295 objectref_get_or_create(L, obj);
3299 // EnvRef:add_rat(pos)
3300 // pos = {x=num, y=num, z=num}
3301 static int l_add_rat(lua_State *L)
3303 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3304 <<" Doing nothing."<<std::endl;
3308 // EnvRef:add_firefly(pos)
3309 // pos = {x=num, y=num, z=num}
3310 static int l_add_firefly(lua_State *L)
3312 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3313 <<" Doing nothing."<<std::endl;
3317 // EnvRef:get_meta(pos)
3318 static int l_get_meta(lua_State *L)
3320 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3321 EnvRef *o = checkobject(L, 1);
3322 ServerEnvironment *env = o->m_env;
3323 if(env == NULL) return 0;
3325 v3s16 p = read_v3s16(L, 2);
3326 NodeMetaRef::create(L, p, env);
3330 // EnvRef:get_player_by_name(name)
3331 static int l_get_player_by_name(lua_State *L)
3333 EnvRef *o = checkobject(L, 1);
3334 ServerEnvironment *env = o->m_env;
3335 if(env == NULL) return 0;
3337 const char *name = luaL_checkstring(L, 2);
3338 Player *player = env->getPlayer(name);
3343 PlayerSAO *sao = player->getPlayerSAO();
3348 // Put player on stack
3349 objectref_get_or_create(L, sao);
3353 // EnvRef:get_objects_inside_radius(pos, radius)
3354 static int l_get_objects_inside_radius(lua_State *L)
3356 // Get the table insert function
3357 lua_getglobal(L, "table");
3358 lua_getfield(L, -1, "insert");
3359 int table_insert = lua_gettop(L);
3361 EnvRef *o = checkobject(L, 1);
3362 ServerEnvironment *env = o->m_env;
3363 if(env == NULL) return 0;
3365 v3f pos = checkFloatPos(L, 2);
3366 float radius = luaL_checknumber(L, 3) * BS;
3367 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3369 int table = lua_gettop(L);
3370 for(std::set<u16>::const_iterator
3371 i = ids.begin(); i != ids.end(); i++){
3372 ServerActiveObject *obj = env->getActiveObject(*i);
3373 // Insert object reference into table
3374 lua_pushvalue(L, table_insert);
3375 lua_pushvalue(L, table);
3376 objectref_get_or_create(L, obj);
3377 if(lua_pcall(L, 2, 0, 0))
3378 script_error(L, "error: %s", lua_tostring(L, -1));
3383 // EnvRef:set_timeofday(val)
3385 static int l_set_timeofday(lua_State *L)
3387 EnvRef *o = checkobject(L, 1);
3388 ServerEnvironment *env = o->m_env;
3389 if(env == NULL) return 0;
3391 float timeofday_f = luaL_checknumber(L, 2);
3392 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3393 int timeofday_mh = (int)(timeofday_f * 24000.0);
3394 // This should be set directly in the environment but currently
3395 // such changes aren't immediately sent to the clients, so call
3396 // the server instead.
3397 //env->setTimeOfDay(timeofday_mh);
3398 get_server(L)->setTimeOfDay(timeofday_mh);
3402 // EnvRef:get_timeofday() -> 0...1
3403 static int l_get_timeofday(lua_State *L)
3405 EnvRef *o = checkobject(L, 1);
3406 ServerEnvironment *env = o->m_env;
3407 if(env == NULL) return 0;
3409 int timeofday_mh = env->getTimeOfDay();
3410 float timeofday_f = (float)timeofday_mh / 24000.0;
3411 lua_pushnumber(L, timeofday_f);
3416 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3417 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3418 static int l_find_node_near(lua_State *L)
3420 EnvRef *o = checkobject(L, 1);
3421 ServerEnvironment *env = o->m_env;
3422 if(env == NULL) return 0;
3423 INodeDefManager *ndef = get_server(L)->ndef();
3424 v3s16 pos = read_v3s16(L, 2);
3425 int radius = luaL_checkinteger(L, 3);
3426 std::set<content_t> filter;
3427 if(lua_istable(L, 4)){
3430 while(lua_next(L, table) != 0){
3431 // key at index -2 and value at index -1
3432 luaL_checktype(L, -1, LUA_TSTRING);
3433 ndef->getIds(lua_tostring(L, -1), filter);
3434 // removes value, keeps key for next iteration
3437 } else if(lua_isstring(L, 4)){
3438 ndef->getIds(lua_tostring(L, 4), filter);
3441 for(int d=1; d<=radius; d++){
3442 core::list<v3s16> list;
3443 getFacePositions(list, d);
3444 for(core::list<v3s16>::Iterator i = list.begin();
3445 i != list.end(); i++){
3446 v3s16 p = pos + (*i);
3447 content_t c = env->getMap().getNodeNoEx(p).getContent();
3448 if(filter.count(c) != 0){
3457 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3458 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3459 static int l_find_nodes_in_area(lua_State *L)
3461 EnvRef *o = checkobject(L, 1);
3462 ServerEnvironment *env = o->m_env;
3463 if(env == NULL) return 0;
3464 INodeDefManager *ndef = get_server(L)->ndef();
3465 v3s16 minp = read_v3s16(L, 2);
3466 v3s16 maxp = read_v3s16(L, 3);
3467 std::set<content_t> filter;
3468 if(lua_istable(L, 4)){
3471 while(lua_next(L, table) != 0){
3472 // key at index -2 and value at index -1
3473 luaL_checktype(L, -1, LUA_TSTRING);
3474 ndef->getIds(lua_tostring(L, -1), filter);
3475 // removes value, keeps key for next iteration
3478 } else if(lua_isstring(L, 4)){
3479 ndef->getIds(lua_tostring(L, 4), filter);
3482 // Get the table insert function
3483 lua_getglobal(L, "table");
3484 lua_getfield(L, -1, "insert");
3485 int table_insert = lua_gettop(L);
3488 int table = lua_gettop(L);
3489 for(s16 x=minp.X; x<=maxp.X; x++)
3490 for(s16 y=minp.Y; y<=maxp.Y; y++)
3491 for(s16 z=minp.Z; z<=maxp.Z; z++)
3494 content_t c = env->getMap().getNodeNoEx(p).getContent();
3495 if(filter.count(c) != 0){
3496 lua_pushvalue(L, table_insert);
3497 lua_pushvalue(L, table);
3499 if(lua_pcall(L, 2, 0, 0))
3500 script_error(L, "error: %s", lua_tostring(L, -1));
3506 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3507 // returns world-specific PerlinNoise
3508 static int l_get_perlin(lua_State *L)
3510 EnvRef *o = checkobject(L, 1);
3511 ServerEnvironment *env = o->m_env;
3512 if(env == NULL) return 0;
3514 int seeddiff = luaL_checkint(L, 2);
3515 int octaves = luaL_checkint(L, 3);
3516 double persistence = luaL_checknumber(L, 4);
3517 double scale = luaL_checknumber(L, 5);
3519 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3520 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3521 luaL_getmetatable(L, "PerlinNoise");
3522 lua_setmetatable(L, -2);
3527 EnvRef(ServerEnvironment *env):
3530 //infostream<<"EnvRef created"<<std::endl;
3535 //infostream<<"EnvRef destructing"<<std::endl;
3538 // Creates an EnvRef and leaves it on top of stack
3539 // Not callable from Lua; all references are created on the C side.
3540 static void create(lua_State *L, ServerEnvironment *env)
3542 EnvRef *o = new EnvRef(env);
3543 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3544 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3545 luaL_getmetatable(L, className);
3546 lua_setmetatable(L, -2);
3549 static void set_null(lua_State *L)
3551 EnvRef *o = checkobject(L, -1);
3555 static void Register(lua_State *L)
3558 int methodtable = lua_gettop(L);
3559 luaL_newmetatable(L, className);
3560 int metatable = lua_gettop(L);
3562 lua_pushliteral(L, "__metatable");
3563 lua_pushvalue(L, methodtable);
3564 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3566 lua_pushliteral(L, "__index");
3567 lua_pushvalue(L, methodtable);
3568 lua_settable(L, metatable);
3570 lua_pushliteral(L, "__gc");
3571 lua_pushcfunction(L, gc_object);
3572 lua_settable(L, metatable);
3574 lua_pop(L, 1); // drop metatable
3576 luaL_openlib(L, 0, methods, 0); // fill methodtable
3577 lua_pop(L, 1); // drop methodtable
3579 // Cannot be created from Lua
3580 //lua_register(L, className, create_object);
3583 const char EnvRef::className[] = "EnvRef";
3584 const luaL_reg EnvRef::methods[] = {
3585 method(EnvRef, set_node),
3586 method(EnvRef, add_node),
3587 method(EnvRef, remove_node),
3588 method(EnvRef, get_node),
3589 method(EnvRef, get_node_or_nil),
3590 method(EnvRef, get_node_light),
3591 method(EnvRef, place_node),
3592 method(EnvRef, dig_node),
3593 method(EnvRef, punch_node),
3594 method(EnvRef, add_entity),
3595 method(EnvRef, add_item),
3596 method(EnvRef, add_rat),
3597 method(EnvRef, add_firefly),
3598 method(EnvRef, get_meta),
3599 method(EnvRef, get_player_by_name),
3600 method(EnvRef, get_objects_inside_radius),
3601 method(EnvRef, set_timeofday),
3602 method(EnvRef, get_timeofday),
3603 method(EnvRef, find_node_near),
3604 method(EnvRef, find_nodes_in_area),
3605 method(EnvRef, get_perlin),
3614 class LuaPseudoRandom
3617 PseudoRandom m_pseudo;
3619 static const char className[];
3620 static const luaL_reg methods[];
3622 // Exported functions
3624 // garbage collector
3625 static int gc_object(lua_State *L)
3627 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3632 // next(self, min=0, max=32767) -> get next value
3633 static int l_next(lua_State *L)
3635 LuaPseudoRandom *o = checkobject(L, 1);
3638 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3639 if(!lua_isnil(L, 2))
3640 min = luaL_checkinteger(L, 2);
3641 if(!lua_isnil(L, 3))
3642 max = luaL_checkinteger(L, 3);
3643 if(max - min != 32767 && max - min > 32767/5)
3644 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.");
3645 PseudoRandom &pseudo = o->m_pseudo;
3646 int val = pseudo.next();
3647 val = (val % (max-min+1)) + min;
3648 lua_pushinteger(L, val);
3653 LuaPseudoRandom(int seed):
3662 const PseudoRandom& getItem() const
3666 PseudoRandom& getItem()
3671 // LuaPseudoRandom(seed)
3672 // Creates an LuaPseudoRandom and leaves it on top of stack
3673 static int create_object(lua_State *L)
3675 int seed = luaL_checknumber(L, 1);
3676 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3677 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3678 luaL_getmetatable(L, className);
3679 lua_setmetatable(L, -2);
3683 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3685 luaL_checktype(L, narg, LUA_TUSERDATA);
3686 void *ud = luaL_checkudata(L, narg, className);
3687 if(!ud) luaL_typerror(L, narg, className);
3688 return *(LuaPseudoRandom**)ud; // unbox pointer
3691 static void Register(lua_State *L)
3694 int methodtable = lua_gettop(L);
3695 luaL_newmetatable(L, className);
3696 int metatable = lua_gettop(L);
3698 lua_pushliteral(L, "__metatable");
3699 lua_pushvalue(L, methodtable);
3700 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3702 lua_pushliteral(L, "__index");
3703 lua_pushvalue(L, methodtable);
3704 lua_settable(L, metatable);
3706 lua_pushliteral(L, "__gc");
3707 lua_pushcfunction(L, gc_object);
3708 lua_settable(L, metatable);
3710 lua_pop(L, 1); // drop metatable
3712 luaL_openlib(L, 0, methods, 0); // fill methodtable
3713 lua_pop(L, 1); // drop methodtable
3715 // Can be created from Lua (LuaPseudoRandom(seed))
3716 lua_register(L, className, create_object);
3719 const char LuaPseudoRandom::className[] = "PseudoRandom";
3720 const luaL_reg LuaPseudoRandom::methods[] = {
3721 method(LuaPseudoRandom, next),
3731 class LuaABM : public ActiveBlockModifier
3737 std::set<std::string> m_trigger_contents;
3738 std::set<std::string> m_required_neighbors;
3739 float m_trigger_interval;
3740 u32 m_trigger_chance;
3742 LuaABM(lua_State *L, int id,
3743 const std::set<std::string> &trigger_contents,
3744 const std::set<std::string> &required_neighbors,
3745 float trigger_interval, u32 trigger_chance):
3748 m_trigger_contents(trigger_contents),
3749 m_required_neighbors(required_neighbors),
3750 m_trigger_interval(trigger_interval),
3751 m_trigger_chance(trigger_chance)
3754 virtual std::set<std::string> getTriggerContents()
3756 return m_trigger_contents;
3758 virtual std::set<std::string> getRequiredNeighbors()
3760 return m_required_neighbors;
3762 virtual float getTriggerInterval()
3764 return m_trigger_interval;
3766 virtual u32 getTriggerChance()
3768 return m_trigger_chance;
3770 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3771 u32 active_object_count, u32 active_object_count_wider)
3773 lua_State *L = m_lua;
3776 assert(lua_checkstack(L, 20));
3777 StackUnroller stack_unroller(L);
3779 // Get minetest.registered_abms
3780 lua_getglobal(L, "minetest");
3781 lua_getfield(L, -1, "registered_abms");
3782 luaL_checktype(L, -1, LUA_TTABLE);
3783 int registered_abms = lua_gettop(L);
3785 // Get minetest.registered_abms[m_id]
3786 lua_pushnumber(L, m_id);
3787 lua_gettable(L, registered_abms);
3788 if(lua_isnil(L, -1))
3792 luaL_checktype(L, -1, LUA_TTABLE);
3793 lua_getfield(L, -1, "action");
3794 luaL_checktype(L, -1, LUA_TFUNCTION);
3796 pushnode(L, n, env->getGameDef()->ndef());
3797 lua_pushnumber(L, active_object_count);
3798 lua_pushnumber(L, active_object_count_wider);
3799 if(lua_pcall(L, 4, 0, 0))
3800 script_error(L, "error: %s", lua_tostring(L, -1));
3808 static void read_server_sound_params(lua_State *L, int index,
3809 ServerSoundParams ¶ms)
3812 index = lua_gettop(L) + 1 + index;
3814 params = ServerSoundParams();
3815 if(lua_istable(L, index)){
3816 getfloatfield(L, index, "gain", params.gain);
3817 getstringfield(L, index, "to_player", params.to_player);
3818 lua_getfield(L, index, "pos");
3819 if(!lua_isnil(L, -1)){
3820 v3f p = read_v3f(L, -1)*BS;
3822 params.type = ServerSoundParams::SSP_POSITIONAL;
3825 lua_getfield(L, index, "object");
3826 if(!lua_isnil(L, -1)){
3827 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3828 ServerActiveObject *sao = ObjectRef::getobject(ref);
3830 params.object = sao->getId();
3831 params.type = ServerSoundParams::SSP_OBJECT;
3835 params.max_hear_distance = BS*getfloatfield_default(L, index,
3836 "max_hear_distance", params.max_hear_distance/BS);
3837 getboolfield(L, index, "loop", params.loop);
3846 // Writes a line to dstream
3847 static int l_debug(lua_State *L)
3849 std::string text = lua_tostring(L, 1);
3850 dstream << text << std::endl;
3854 // log([level,] text)
3855 // Writes a line to the logger.
3856 // The one-argument version logs to infostream.
3857 // The two-argument version accept a log level: error, action, info, or verbose.
3858 static int l_log(lua_State *L)
3861 LogMessageLevel level = LMT_INFO;
3862 if(lua_isnone(L, 2))
3864 text = lua_tostring(L, 1);
3868 std::string levelname = lua_tostring(L, 1);
3869 text = lua_tostring(L, 2);
3870 if(levelname == "error")
3872 else if(levelname == "action")
3874 else if(levelname == "verbose")
3875 level = LMT_VERBOSE;
3877 log_printline(level, text);
3881 // register_item_raw({lots of stuff})
3882 static int l_register_item_raw(lua_State *L)
3884 luaL_checktype(L, 1, LUA_TTABLE);
3887 // Get the writable item and node definition managers from the server
3888 IWritableItemDefManager *idef =
3889 get_server(L)->getWritableItemDefManager();
3890 IWritableNodeDefManager *ndef =
3891 get_server(L)->getWritableNodeDefManager();
3893 // Check if name is defined
3894 lua_getfield(L, table, "name");
3895 if(lua_isstring(L, -1)){
3896 std::string name = lua_tostring(L, -1);
3897 verbosestream<<"register_item_raw: "<<name<<std::endl;
3899 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3902 // Check if on_use is defined
3904 // Read the item definition and register it
3905 ItemDefinition def = read_item_definition(L, table);
3906 idef->registerItem(def);
3908 // Read the node definition (content features) and register it
3909 if(def.type == ITEM_NODE)
3911 ContentFeatures f = read_content_features(L, table);
3912 ndef->set(f.name, f);
3915 return 0; /* number of results */
3918 // register_alias_raw(name, convert_to_name)
3919 static int l_register_alias_raw(lua_State *L)
3921 std::string name = luaL_checkstring(L, 1);
3922 std::string convert_to = luaL_checkstring(L, 2);
3924 // Get the writable item definition manager from the server
3925 IWritableItemDefManager *idef =
3926 get_server(L)->getWritableItemDefManager();
3928 idef->registerAlias(name, convert_to);
3930 return 0; /* number of results */
3933 // helper for register_craft
3934 static bool read_craft_recipe_shaped(lua_State *L, int index,
3935 int &width, std::vector<std::string> &recipe)
3938 index = lua_gettop(L) + 1 + index;
3940 if(!lua_istable(L, index))
3945 while(lua_next(L, index) != 0){
3947 // key at index -2 and value at index -1
3948 if(!lua_istable(L, -1))
3950 int table2 = lua_gettop(L);
3952 while(lua_next(L, table2) != 0){
3953 // key at index -2 and value at index -1
3954 if(!lua_isstring(L, -1))
3956 recipe.push_back(lua_tostring(L, -1));
3957 // removes value, keeps key for next iteration
3964 if(colcount != width)
3967 // removes value, keeps key for next iteration
3974 // helper for register_craft
3975 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3976 std::vector<std::string> &recipe)
3979 index = lua_gettop(L) + 1 + index;
3981 if(!lua_istable(L, index))
3985 while(lua_next(L, index) != 0){
3986 // key at index -2 and value at index -1
3987 if(!lua_isstring(L, -1))
3989 recipe.push_back(lua_tostring(L, -1));
3990 // removes value, keeps key for next iteration
3996 // helper for register_craft
3997 static bool read_craft_replacements(lua_State *L, int index,
3998 CraftReplacements &replacements)
4001 index = lua_gettop(L) + 1 + index;
4003 if(!lua_istable(L, index))
4007 while(lua_next(L, index) != 0){
4008 // key at index -2 and value at index -1
4009 if(!lua_istable(L, -1))
4011 lua_rawgeti(L, -1, 1);
4012 if(!lua_isstring(L, -1))
4014 std::string replace_from = lua_tostring(L, -1);
4016 lua_rawgeti(L, -1, 2);
4017 if(!lua_isstring(L, -1))
4019 std::string replace_to = lua_tostring(L, -1);
4021 replacements.pairs.push_back(
4022 std::make_pair(replace_from, replace_to));
4023 // removes value, keeps key for next iteration
4028 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4029 static int l_register_craft(lua_State *L)
4031 //infostream<<"register_craft"<<std::endl;
4032 luaL_checktype(L, 1, LUA_TTABLE);
4035 // Get the writable craft definition manager from the server
4036 IWritableCraftDefManager *craftdef =
4037 get_server(L)->getWritableCraftDefManager();
4039 std::string type = getstringfield_default(L, table, "type", "shaped");
4042 CraftDefinitionShaped
4044 if(type == "shaped"){
4045 std::string output = getstringfield_default(L, table, "output", "");
4047 throw LuaError(L, "Crafting definition is missing an output");
4050 std::vector<std::string> recipe;
4051 lua_getfield(L, table, "recipe");
4052 if(lua_isnil(L, -1))
4053 throw LuaError(L, "Crafting definition is missing a recipe"
4054 " (output=\"" + output + "\")");
4055 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4056 throw LuaError(L, "Invalid crafting recipe"
4057 " (output=\"" + output + "\")");
4059 CraftReplacements replacements;
4060 lua_getfield(L, table, "replacements");
4061 if(!lua_isnil(L, -1))
4063 if(!read_craft_replacements(L, -1, replacements))
4064 throw LuaError(L, "Invalid replacements"
4065 " (output=\"" + output + "\")");
4068 CraftDefinition *def = new CraftDefinitionShaped(
4069 output, width, recipe, replacements);
4070 craftdef->registerCraft(def);
4073 CraftDefinitionShapeless
4075 else if(type == "shapeless"){
4076 std::string output = getstringfield_default(L, table, "output", "");
4078 throw LuaError(L, "Crafting definition (shapeless)"
4079 " is missing an output");
4081 std::vector<std::string> recipe;
4082 lua_getfield(L, table, "recipe");
4083 if(lua_isnil(L, -1))
4084 throw LuaError(L, "Crafting definition (shapeless)"
4085 " is missing a recipe"
4086 " (output=\"" + output + "\")");
4087 if(!read_craft_recipe_shapeless(L, -1, recipe))
4088 throw LuaError(L, "Invalid crafting recipe"
4089 " (output=\"" + output + "\")");
4091 CraftReplacements replacements;
4092 lua_getfield(L, table, "replacements");
4093 if(!lua_isnil(L, -1))
4095 if(!read_craft_replacements(L, -1, replacements))
4096 throw LuaError(L, "Invalid replacements"
4097 " (output=\"" + output + "\")");
4100 CraftDefinition *def = new CraftDefinitionShapeless(
4101 output, recipe, replacements);
4102 craftdef->registerCraft(def);
4105 CraftDefinitionToolRepair
4107 else if(type == "toolrepair"){
4108 float additional_wear = getfloatfield_default(L, table,
4109 "additional_wear", 0.0);
4111 CraftDefinition *def = new CraftDefinitionToolRepair(
4113 craftdef->registerCraft(def);
4116 CraftDefinitionCooking
4118 else if(type == "cooking"){
4119 std::string output = getstringfield_default(L, table, "output", "");
4121 throw LuaError(L, "Crafting definition (cooking)"
4122 " is missing an output");
4124 std::string recipe = getstringfield_default(L, table, "recipe", "");
4126 throw LuaError(L, "Crafting definition (cooking)"
4127 " is missing a recipe"
4128 " (output=\"" + output + "\")");
4130 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4132 CraftReplacements replacements;
4133 lua_getfield(L, table, "replacements");
4134 if(!lua_isnil(L, -1))
4136 if(!read_craft_replacements(L, -1, replacements))
4137 throw LuaError(L, "Invalid replacements"
4138 " (cooking output=\"" + output + "\")");
4141 CraftDefinition *def = new CraftDefinitionCooking(
4142 output, recipe, cooktime, replacements);
4143 craftdef->registerCraft(def);
4148 else if(type == "fuel"){
4149 std::string recipe = getstringfield_default(L, table, "recipe", "");
4151 throw LuaError(L, "Crafting definition (fuel)"
4152 " is missing a recipe");
4154 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4156 CraftReplacements replacements;
4157 lua_getfield(L, table, "replacements");
4158 if(!lua_isnil(L, -1))
4160 if(!read_craft_replacements(L, -1, replacements))
4161 throw LuaError(L, "Invalid replacements"
4162 " (fuel recipe=\"" + recipe + "\")");
4165 CraftDefinition *def = new CraftDefinitionFuel(
4166 recipe, burntime, replacements);
4167 craftdef->registerCraft(def);
4171 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4175 return 0; /* number of results */
4178 // setting_set(name, value)
4179 static int l_setting_set(lua_State *L)
4181 const char *name = luaL_checkstring(L, 1);
4182 const char *value = luaL_checkstring(L, 2);
4183 g_settings->set(name, value);
4187 // setting_get(name)
4188 static int l_setting_get(lua_State *L)
4190 const char *name = luaL_checkstring(L, 1);
4192 std::string value = g_settings->get(name);
4193 lua_pushstring(L, value.c_str());
4194 } catch(SettingNotFoundException &e){
4200 // setting_getbool(name)
4201 static int l_setting_getbool(lua_State *L)
4203 const char *name = luaL_checkstring(L, 1);
4205 bool value = g_settings->getBool(name);
4206 lua_pushboolean(L, value);
4207 } catch(SettingNotFoundException &e){
4213 // chat_send_all(text)
4214 static int l_chat_send_all(lua_State *L)
4216 const char *text = luaL_checkstring(L, 1);
4217 // Get server from registry
4218 Server *server = get_server(L);
4220 server->notifyPlayers(narrow_to_wide(text));
4224 // chat_send_player(name, text)
4225 static int l_chat_send_player(lua_State *L)
4227 const char *name = luaL_checkstring(L, 1);
4228 const char *text = luaL_checkstring(L, 2);
4229 // Get server from registry
4230 Server *server = get_server(L);
4232 server->notifyPlayer(name, narrow_to_wide(text));
4236 // get_player_privs(name, text)
4237 static int l_get_player_privs(lua_State *L)
4239 const char *name = luaL_checkstring(L, 1);
4240 // Get server from registry
4241 Server *server = get_server(L);
4244 int table = lua_gettop(L);
4245 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4246 for(std::set<std::string>::const_iterator
4247 i = privs_s.begin(); i != privs_s.end(); i++){
4248 lua_pushboolean(L, true);
4249 lua_setfield(L, table, i->c_str());
4251 lua_pushvalue(L, table);
4255 // get_inventory(location)
4256 static int l_get_inventory(lua_State *L)
4258 InventoryLocation loc;
4260 std::string type = checkstringfield(L, 1, "type");
4261 if(type == "player"){
4262 std::string name = checkstringfield(L, 1, "name");
4263 loc.setPlayer(name);
4264 } else if(type == "node"){
4265 lua_getfield(L, 1, "pos");
4266 v3s16 pos = check_v3s16(L, -1);
4267 loc.setNodeMeta(pos);
4270 if(get_server(L)->getInventory(loc) != NULL)
4271 InvRef::create(L, loc);
4277 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4278 static int l_get_dig_params(lua_State *L)
4280 std::map<std::string, int> groups;
4281 read_groups(L, 1, groups);
4282 ToolCapabilities tp = read_tool_capabilities(L, 2);
4283 if(lua_isnoneornil(L, 3))
4284 push_dig_params(L, getDigParams(groups, &tp));
4286 push_dig_params(L, getDigParams(groups, &tp,
4287 luaL_checknumber(L, 3)));
4291 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4292 static int l_get_hit_params(lua_State *L)
4294 std::map<std::string, int> groups;
4295 read_groups(L, 1, groups);
4296 ToolCapabilities tp = read_tool_capabilities(L, 2);
4297 if(lua_isnoneornil(L, 3))
4298 push_hit_params(L, getHitParams(groups, &tp));
4300 push_hit_params(L, getHitParams(groups, &tp,
4301 luaL_checknumber(L, 3)));
4305 // get_current_modname()
4306 static int l_get_current_modname(lua_State *L)
4308 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4312 // get_modpath(modname)
4313 static int l_get_modpath(lua_State *L)
4315 std::string modname = luaL_checkstring(L, 1);
4317 if(modname == "__builtin"){
4318 std::string path = get_server(L)->getBuiltinLuaPath();
4319 lua_pushstring(L, path.c_str());
4322 const ModSpec *mod = get_server(L)->getModSpec(modname);
4327 lua_pushstring(L, mod->path.c_str());
4332 static int l_get_worldpath(lua_State *L)
4334 std::string worldpath = get_server(L)->getWorldPath();
4335 lua_pushstring(L, worldpath.c_str());
4339 // sound_play(spec, parameters)
4340 static int l_sound_play(lua_State *L)
4342 SimpleSoundSpec spec;
4343 read_soundspec(L, 1, spec);
4344 ServerSoundParams params;
4345 read_server_sound_params(L, 2, params);
4346 s32 handle = get_server(L)->playSound(spec, params);
4347 lua_pushinteger(L, handle);
4351 // sound_stop(handle)
4352 static int l_sound_stop(lua_State *L)
4354 int handle = luaL_checkinteger(L, 1);
4355 get_server(L)->stopSound(handle);
4359 // is_singleplayer()
4360 static int l_is_singleplayer(lua_State *L)
4362 lua_pushboolean(L, get_server(L)->isSingleplayer());
4366 // get_password_hash(name, raw_password)
4367 static int l_get_password_hash(lua_State *L)
4369 std::string name = luaL_checkstring(L, 1);
4370 std::string raw_password = luaL_checkstring(L, 2);
4371 std::string hash = translatePassword(name,
4372 narrow_to_wide(raw_password));
4373 lua_pushstring(L, hash.c_str());
4377 // notify_authentication_modified(name)
4378 static int l_notify_authentication_modified(lua_State *L)
4380 std::string name = "";
4381 if(lua_isstring(L, 1))
4382 name = lua_tostring(L, 1);
4383 get_server(L)->reportPrivsModified(name);
4387 // get_craft_result(input)
4388 static int l_get_craft_result(lua_State *L)
4391 std::string method_s = getstringfield_default(L, input_i, "method", "normal");
4392 enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
4393 es_CraftMethod, CRAFT_METHOD_NORMAL);
4395 lua_getfield(L, input_i, "width");
4396 if(lua_isnumber(L, -1))
4397 width = luaL_checkinteger(L, -1);
4399 lua_getfield(L, input_i, "items");
4400 std::vector<ItemStack> items = read_items(L, -1);
4401 lua_pop(L, 1); // items
4403 IGameDef *gdef = get_server(L);
4404 ICraftDefManager *cdef = gdef->cdef();
4405 CraftInput input(method, width, items);
4407 bool got = cdef->getCraftResult(input, output, true, gdef);
4408 lua_newtable(L); // output table
4411 item.deSerialize(output.item, gdef->idef());
4412 LuaItemStack::create(L, item);
4413 lua_setfield(L, -2, "item");
4414 setintfield(L, -1, "time", output.time);
4416 LuaItemStack::create(L, ItemStack());
4417 lua_setfield(L, -2, "item");
4418 setintfield(L, -1, "time", 0);
4420 lua_newtable(L); // decremented input table
4421 lua_pushstring(L, method_s.c_str());
4422 lua_setfield(L, -2, "method");
4423 lua_pushinteger(L, width);
4424 lua_setfield(L, -2, "width");
4425 push_items(L, input.items);
4426 lua_setfield(L, -2, "items");
4430 static const struct luaL_Reg minetest_f [] = {
4433 {"register_item_raw", l_register_item_raw},
4434 {"register_alias_raw", l_register_alias_raw},
4435 {"register_craft", l_register_craft},
4436 {"setting_set", l_setting_set},
4437 {"setting_get", l_setting_get},
4438 {"setting_getbool", l_setting_getbool},
4439 {"chat_send_all", l_chat_send_all},
4440 {"chat_send_player", l_chat_send_player},
4441 {"get_player_privs", l_get_player_privs},
4442 {"get_inventory", l_get_inventory},
4443 {"get_dig_params", l_get_dig_params},
4444 {"get_hit_params", l_get_hit_params},
4445 {"get_current_modname", l_get_current_modname},
4446 {"get_modpath", l_get_modpath},
4447 {"get_worldpath", l_get_worldpath},
4448 {"sound_play", l_sound_play},
4449 {"sound_stop", l_sound_stop},
4450 {"is_singleplayer", l_is_singleplayer},
4451 {"get_password_hash", l_get_password_hash},
4452 {"notify_authentication_modified", l_notify_authentication_modified},
4453 {"get_craft_result", l_get_craft_result},
4458 Main export function
4461 void scriptapi_export(lua_State *L, Server *server)
4464 assert(lua_checkstack(L, 20));
4465 verbosestream<<"scriptapi_export()"<<std::endl;
4466 StackUnroller stack_unroller(L);
4468 // Store server as light userdata in registry
4469 lua_pushlightuserdata(L, server);
4470 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4472 // Register global functions in table minetest
4474 luaL_register(L, NULL, minetest_f);
4475 lua_setglobal(L, "minetest");
4477 // Get the main minetest table
4478 lua_getglobal(L, "minetest");
4480 // Add tables to minetest
4482 lua_setfield(L, -2, "object_refs");
4484 lua_setfield(L, -2, "luaentities");
4486 // Register wrappers
4487 LuaItemStack::Register(L);
4488 InvRef::Register(L);
4489 NodeMetaRef::Register(L);
4490 ObjectRef::Register(L);
4491 EnvRef::Register(L);
4492 LuaPseudoRandom::Register(L);
4493 LuaPerlinNoise::Register(L);
4496 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4497 const std::string &modname)
4499 ModNameStorer modnamestorer(L, modname);
4501 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4503 errorstream<<"Error loading mod \""<<modname
4504 <<"\": modname does not follow naming conventions: "
4505 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4509 bool success = false;
4512 success = script_load(L, scriptpath.c_str());
4515 errorstream<<"Error loading mod \""<<modname
4516 <<"\": "<<e.what()<<std::endl;
4522 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4525 assert(lua_checkstack(L, 20));
4526 verbosestream<<"scriptapi_add_environment"<<std::endl;
4527 StackUnroller stack_unroller(L);
4529 // Create EnvRef on stack
4530 EnvRef::create(L, env);
4531 int envref = lua_gettop(L);
4533 // minetest.env = envref
4534 lua_getglobal(L, "minetest");
4535 luaL_checktype(L, -1, LUA_TTABLE);
4536 lua_pushvalue(L, envref);
4537 lua_setfield(L, -2, "env");
4539 // Store environment as light userdata in registry
4540 lua_pushlightuserdata(L, env);
4541 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4544 Add ActiveBlockModifiers to environment
4547 // Get minetest.registered_abms
4548 lua_getglobal(L, "minetest");
4549 lua_getfield(L, -1, "registered_abms");
4550 luaL_checktype(L, -1, LUA_TTABLE);
4551 int registered_abms = lua_gettop(L);
4553 if(lua_istable(L, registered_abms)){
4554 int table = lua_gettop(L);
4556 while(lua_next(L, table) != 0){
4557 // key at index -2 and value at index -1
4558 int id = lua_tonumber(L, -2);
4559 int current_abm = lua_gettop(L);
4561 std::set<std::string> trigger_contents;
4562 lua_getfield(L, current_abm, "nodenames");
4563 if(lua_istable(L, -1)){
4564 int table = lua_gettop(L);
4566 while(lua_next(L, table) != 0){
4567 // key at index -2 and value at index -1
4568 luaL_checktype(L, -1, LUA_TSTRING);
4569 trigger_contents.insert(lua_tostring(L, -1));
4570 // removes value, keeps key for next iteration
4573 } else if(lua_isstring(L, -1)){
4574 trigger_contents.insert(lua_tostring(L, -1));
4578 std::set<std::string> required_neighbors;
4579 lua_getfield(L, current_abm, "neighbors");
4580 if(lua_istable(L, -1)){
4581 int table = lua_gettop(L);
4583 while(lua_next(L, table) != 0){
4584 // key at index -2 and value at index -1
4585 luaL_checktype(L, -1, LUA_TSTRING);
4586 required_neighbors.insert(lua_tostring(L, -1));
4587 // removes value, keeps key for next iteration
4590 } else if(lua_isstring(L, -1)){
4591 required_neighbors.insert(lua_tostring(L, -1));
4595 float trigger_interval = 10.0;
4596 getfloatfield(L, current_abm, "interval", trigger_interval);
4598 int trigger_chance = 50;
4599 getintfield(L, current_abm, "chance", trigger_chance);
4601 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4602 required_neighbors, trigger_interval, trigger_chance);
4604 env->addActiveBlockModifier(abm);
4606 // removes value, keeps key for next iteration
4614 // Dump stack top with the dump2 function
4615 static void dump2(lua_State *L, const char *name)
4617 // Dump object (debug)
4618 lua_getglobal(L, "dump2");
4619 luaL_checktype(L, -1, LUA_TFUNCTION);
4620 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4621 lua_pushstring(L, name);
4622 if(lua_pcall(L, 2, 0, 0))
4623 script_error(L, "error: %s", lua_tostring(L, -1));
4631 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4634 assert(lua_checkstack(L, 20));
4635 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4636 StackUnroller stack_unroller(L);
4638 // Create object on stack
4639 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4640 int object = lua_gettop(L);
4642 // Get minetest.object_refs table
4643 lua_getglobal(L, "minetest");
4644 lua_getfield(L, -1, "object_refs");
4645 luaL_checktype(L, -1, LUA_TTABLE);
4646 int objectstable = lua_gettop(L);
4648 // object_refs[id] = object
4649 lua_pushnumber(L, cobj->getId()); // Push id
4650 lua_pushvalue(L, object); // Copy object to top of stack
4651 lua_settable(L, objectstable);
4654 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4657 assert(lua_checkstack(L, 20));
4658 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4659 StackUnroller stack_unroller(L);
4661 // Get minetest.object_refs table
4662 lua_getglobal(L, "minetest");
4663 lua_getfield(L, -1, "object_refs");
4664 luaL_checktype(L, -1, LUA_TTABLE);
4665 int objectstable = lua_gettop(L);
4667 // Get object_refs[id]
4668 lua_pushnumber(L, cobj->getId()); // Push id
4669 lua_gettable(L, objectstable);
4670 // Set object reference to NULL
4671 ObjectRef::set_null(L);
4672 lua_pop(L, 1); // pop object
4674 // Set object_refs[id] = nil
4675 lua_pushnumber(L, cobj->getId()); // Push id
4677 lua_settable(L, objectstable);
4684 // What scriptapi_run_callbacks does with the return values of callbacks.
4685 // Regardless of the mode, if only one callback is defined,
4686 // its return value is the total return value.
4687 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4688 enum RunCallbacksMode
4690 // Returns the return value of the first callback
4691 // Returns nil if list of callbacks is empty
4692 RUN_CALLBACKS_MODE_FIRST,
4693 // Returns the return value of the last callback
4694 // Returns nil if list of callbacks is empty
4695 RUN_CALLBACKS_MODE_LAST,
4696 // If any callback returns a false value, the first such is returned
4697 // Otherwise, the first callback's return value (trueish) is returned
4698 // Returns true if list of callbacks is empty
4699 RUN_CALLBACKS_MODE_AND,
4700 // Like above, but stops calling callbacks (short circuit)
4701 // after seeing the first false value
4702 RUN_CALLBACKS_MODE_AND_SC,
4703 // If any callback returns a true value, the first such is returned
4704 // Otherwise, the first callback's return value (falseish) is returned
4705 // Returns false if list of callbacks is empty
4706 RUN_CALLBACKS_MODE_OR,
4707 // Like above, but stops calling callbacks (short circuit)
4708 // after seeing the first true value
4709 RUN_CALLBACKS_MODE_OR_SC,
4710 // Note: "a true value" and "a false value" refer to values that
4711 // are converted by lua_toboolean to true or false, respectively.
4714 // Push the list of callbacks (a lua table).
4715 // Then push nargs arguments.
4716 // Then call this function, which
4717 // - runs the callbacks
4718 // - removes the table and arguments from the lua stack
4719 // - pushes the return value, computed depending on mode
4720 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4721 RunCallbacksMode mode)
4723 // Insert the return value into the lua stack, below the table
4724 assert(lua_gettop(L) >= nargs + 1);
4726 lua_insert(L, -(nargs + 1) - 1);
4727 // Stack now looks like this:
4728 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4730 int rv = lua_gettop(L) - nargs - 1;
4732 int arg = table + 1;
4734 luaL_checktype(L, table, LUA_TTABLE);
4738 bool first_loop = true;
4739 while(lua_next(L, table) != 0){
4740 // key at index -2 and value at index -1
4741 luaL_checktype(L, -1, LUA_TFUNCTION);
4743 for(int i = 0; i < nargs; i++)
4744 lua_pushvalue(L, arg+i);
4745 if(lua_pcall(L, nargs, 1, 0))
4746 script_error(L, "error: %s", lua_tostring(L, -1));
4748 // Move return value to designated space in stack
4751 // Result of first callback is always moved
4755 // Otherwise, what happens depends on the mode
4756 if(mode == RUN_CALLBACKS_MODE_FIRST)
4758 else if(mode == RUN_CALLBACKS_MODE_LAST)
4760 else if(mode == RUN_CALLBACKS_MODE_AND ||
4761 mode == RUN_CALLBACKS_MODE_AND_SC){
4762 if(lua_toboolean(L, rv) == true &&
4763 lua_toboolean(L, -1) == false)
4768 else if(mode == RUN_CALLBACKS_MODE_OR ||
4769 mode == RUN_CALLBACKS_MODE_OR_SC){
4770 if(lua_toboolean(L, rv) == false &&
4771 lua_toboolean(L, -1) == true)
4780 // Handle short circuit modes
4781 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4782 lua_toboolean(L, rv) == false)
4784 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4785 lua_toboolean(L, rv) == true)
4788 // value removed, keep key for next iteration
4791 // Remove stuff from stack, leaving only the return value
4794 // Fix return value in case no callbacks were called
4796 if(mode == RUN_CALLBACKS_MODE_AND ||
4797 mode == RUN_CALLBACKS_MODE_AND_SC){
4799 lua_pushboolean(L, true);
4801 else if(mode == RUN_CALLBACKS_MODE_OR ||
4802 mode == RUN_CALLBACKS_MODE_OR_SC){
4804 lua_pushboolean(L, false);
4809 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4810 const std::string &message)
4813 assert(lua_checkstack(L, 20));
4814 StackUnroller stack_unroller(L);
4816 // Get minetest.registered_on_chat_messages
4817 lua_getglobal(L, "minetest");
4818 lua_getfield(L, -1, "registered_on_chat_messages");
4820 lua_pushstring(L, name.c_str());
4821 lua_pushstring(L, message.c_str());
4822 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4823 bool ate = lua_toboolean(L, -1);
4827 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4830 assert(lua_checkstack(L, 20));
4831 StackUnroller stack_unroller(L);
4833 // Get minetest.registered_on_newplayers
4834 lua_getglobal(L, "minetest");
4835 lua_getfield(L, -1, "registered_on_newplayers");
4837 objectref_get_or_create(L, player);
4838 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4841 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4844 assert(lua_checkstack(L, 20));
4845 StackUnroller stack_unroller(L);
4847 // Get minetest.registered_on_dieplayers
4848 lua_getglobal(L, "minetest");
4849 lua_getfield(L, -1, "registered_on_dieplayers");
4851 objectref_get_or_create(L, player);
4852 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4855 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4858 assert(lua_checkstack(L, 20));
4859 StackUnroller stack_unroller(L);
4861 // Get minetest.registered_on_respawnplayers
4862 lua_getglobal(L, "minetest");
4863 lua_getfield(L, -1, "registered_on_respawnplayers");
4865 objectref_get_or_create(L, player);
4866 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4867 bool positioning_handled_by_some = lua_toboolean(L, -1);
4868 return positioning_handled_by_some;
4871 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4874 assert(lua_checkstack(L, 20));
4875 StackUnroller stack_unroller(L);
4877 // Get minetest.registered_on_joinplayers
4878 lua_getglobal(L, "minetest");
4879 lua_getfield(L, -1, "registered_on_joinplayers");
4881 objectref_get_or_create(L, player);
4882 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4885 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4888 assert(lua_checkstack(L, 20));
4889 StackUnroller stack_unroller(L);
4891 // Get minetest.registered_on_leaveplayers
4892 lua_getglobal(L, "minetest");
4893 lua_getfield(L, -1, "registered_on_leaveplayers");
4895 objectref_get_or_create(L, player);
4896 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4899 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4902 assert(lua_checkstack(L, 20));
4903 StackUnroller stack_unroller(L);
4905 Inventory *inv = player->getInventory();
4908 lua_getglobal(L, "minetest");
4909 lua_getfield(L, -1, "creative_inventory");
4910 luaL_checktype(L, -1, LUA_TTABLE);
4911 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4914 static void get_auth_handler(lua_State *L)
4916 lua_getglobal(L, "minetest");
4917 lua_getfield(L, -1, "registered_auth_handler");
4918 if(lua_isnil(L, -1)){
4920 lua_getfield(L, -1, "builtin_auth_handler");
4922 if(lua_type(L, -1) != LUA_TTABLE)
4923 throw LuaError(L, "Authentication handler table not valid");
4926 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
4927 std::string *dst_password, std::set<std::string> *dst_privs)
4930 assert(lua_checkstack(L, 20));
4931 StackUnroller stack_unroller(L);
4933 get_auth_handler(L);
4934 lua_getfield(L, -1, "get_auth");
4935 if(lua_type(L, -1) != LUA_TFUNCTION)
4936 throw LuaError(L, "Authentication handler missing get_auth");
4937 lua_pushstring(L, playername.c_str());
4938 if(lua_pcall(L, 1, 1, 0))
4939 script_error(L, "error: %s", lua_tostring(L, -1));
4941 // nil = login not allowed
4942 if(lua_isnil(L, -1))
4944 luaL_checktype(L, -1, LUA_TTABLE);
4946 std::string password;
4947 bool found = getstringfield(L, -1, "password", password);
4949 throw LuaError(L, "Authentication handler didn't return password");
4951 *dst_password = password;
4953 lua_getfield(L, -1, "privileges");
4954 if(!lua_istable(L, -1))
4956 "Authentication handler didn't return privilege table");
4958 read_privileges(L, -1, *dst_privs);
4964 void scriptapi_create_auth(lua_State *L, const std::string &playername,
4965 const std::string &password)
4968 assert(lua_checkstack(L, 20));
4969 StackUnroller stack_unroller(L);
4971 get_auth_handler(L);
4972 lua_getfield(L, -1, "create_auth");
4973 if(lua_type(L, -1) != LUA_TFUNCTION)
4974 throw LuaError(L, "Authentication handler missing create_auth");
4975 lua_pushstring(L, playername.c_str());
4976 lua_pushstring(L, password.c_str());
4977 if(lua_pcall(L, 2, 0, 0))
4978 script_error(L, "error: %s", lua_tostring(L, -1));
4981 bool scriptapi_set_password(lua_State *L, const std::string &playername,
4982 const std::string &password)
4985 assert(lua_checkstack(L, 20));
4986 StackUnroller stack_unroller(L);
4988 get_auth_handler(L);
4989 lua_getfield(L, -1, "set_password");
4990 if(lua_type(L, -1) != LUA_TFUNCTION)
4991 throw LuaError(L, "Authentication handler missing set_password");
4992 lua_pushstring(L, playername.c_str());
4993 lua_pushstring(L, password.c_str());
4994 if(lua_pcall(L, 2, 1, 0))
4995 script_error(L, "error: %s", lua_tostring(L, -1));
4996 return lua_toboolean(L, -1);
5000 item callbacks and node callbacks
5003 // Retrieves minetest.registered_items[name][callbackname]
5004 // If that is nil or on error, return false and stack is unchanged
5005 // If that is a function, returns true and pushes the
5006 // function onto the stack
5007 static bool get_item_callback(lua_State *L,
5008 const char *name, const char *callbackname)
5010 lua_getglobal(L, "minetest");
5011 lua_getfield(L, -1, "registered_items");
5013 luaL_checktype(L, -1, LUA_TTABLE);
5014 lua_getfield(L, -1, name);
5016 // Should be a table
5017 if(lua_type(L, -1) != LUA_TTABLE)
5019 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
5023 lua_getfield(L, -1, callbackname);
5025 // Should be a function or nil
5026 if(lua_type(L, -1) == LUA_TFUNCTION)
5030 else if(lua_isnil(L, -1))
5037 errorstream<<"Item \""<<name<<"\" callback \""
5038 <<callbackname<<" is not a function"<<std::endl;
5044 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
5045 ServerActiveObject *dropper, v3f pos)
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_drop"))
5056 LuaItemStack::create(L, item);
5057 objectref_get_or_create(L, dropper);
5058 pushFloatPos(L, pos);
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_item_on_place(lua_State *L, ItemStack &item,
5067 ServerActiveObject *placer, const PointedThing &pointed)
5070 assert(lua_checkstack(L, 20));
5071 StackUnroller stack_unroller(L);
5073 // Push callback function on stack
5074 if(!get_item_callback(L, item.name.c_str(), "on_place"))
5078 LuaItemStack::create(L, item);
5079 objectref_get_or_create(L, placer);
5080 push_pointed_thing(L, pointed);
5081 if(lua_pcall(L, 3, 1, 0))
5082 script_error(L, "error: %s", lua_tostring(L, -1));
5083 if(!lua_isnil(L, -1))
5084 item = read_item(L, -1);
5088 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
5089 ServerActiveObject *user, const PointedThing &pointed)
5092 assert(lua_checkstack(L, 20));
5093 StackUnroller stack_unroller(L);
5095 // Push callback function on stack
5096 if(!get_item_callback(L, item.name.c_str(), "on_use"))
5100 LuaItemStack::create(L, item);
5101 objectref_get_or_create(L, user);
5102 push_pointed_thing(L, pointed);
5103 if(lua_pcall(L, 3, 1, 0))
5104 script_error(L, "error: %s", lua_tostring(L, -1));
5105 if(!lua_isnil(L, -1))
5106 item = read_item(L, -1);
5110 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
5111 ServerActiveObject *puncher)
5114 assert(lua_checkstack(L, 20));
5115 StackUnroller stack_unroller(L);
5117 INodeDefManager *ndef = get_server(L)->ndef();
5119 // Push callback function on stack
5120 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
5125 pushnode(L, node, ndef);
5126 objectref_get_or_create(L, puncher);
5127 if(lua_pcall(L, 3, 0, 0))
5128 script_error(L, "error: %s", lua_tostring(L, -1));
5132 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
5133 ServerActiveObject *digger)
5136 assert(lua_checkstack(L, 20));
5137 StackUnroller stack_unroller(L);
5139 INodeDefManager *ndef = get_server(L)->ndef();
5141 // Push callback function on stack
5142 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
5147 pushnode(L, node, ndef);
5148 objectref_get_or_create(L, digger);
5149 if(lua_pcall(L, 3, 0, 0))
5150 script_error(L, "error: %s", lua_tostring(L, -1));
5154 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
5157 assert(lua_checkstack(L, 20));
5158 StackUnroller stack_unroller(L);
5160 INodeDefManager *ndef = get_server(L)->ndef();
5162 // Push callback function on stack
5163 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
5168 if(lua_pcall(L, 1, 0, 0))
5169 script_error(L, "error: %s", lua_tostring(L, -1));
5172 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
5175 assert(lua_checkstack(L, 20));
5176 StackUnroller stack_unroller(L);
5178 INodeDefManager *ndef = get_server(L)->ndef();
5180 // Push callback function on stack
5181 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
5186 if(lua_pcall(L, 1, 0, 0))
5187 script_error(L, "error: %s", lua_tostring(L, -1));
5190 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
5193 assert(lua_checkstack(L, 20));
5194 StackUnroller stack_unroller(L);
5196 INodeDefManager *ndef = get_server(L)->ndef();
5198 // Push callback function on stack
5199 if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
5204 pushnode(L, node, ndef);
5205 if(lua_pcall(L, 2, 0, 0))
5206 script_error(L, "error: %s", lua_tostring(L, -1));
5209 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
5210 const std::string &formname,
5211 const std::map<std::string, std::string> &fields,
5212 ServerActiveObject *sender)
5215 assert(lua_checkstack(L, 20));
5216 StackUnroller stack_unroller(L);
5218 INodeDefManager *ndef = get_server(L)->ndef();
5220 // If node doesn't exist, we don't know what callback to call
5221 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5222 if(node.getContent() == CONTENT_IGNORE)
5225 // Push callback function on stack
5226 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
5233 lua_pushstring(L, formname.c_str());
5236 for(std::map<std::string, std::string>::const_iterator
5237 i = fields.begin(); i != fields.end(); i++){
5238 const std::string &name = i->first;
5239 const std::string &value = i->second;
5240 lua_pushstring(L, name.c_str());
5241 lua_pushlstring(L, value.c_str(), value.size());
5242 lua_settable(L, -3);
5245 objectref_get_or_create(L, sender);
5246 if(lua_pcall(L, 4, 0, 0))
5247 script_error(L, "error: %s", lua_tostring(L, -1));
5250 void scriptapi_node_on_metadata_inventory_move(lua_State *L, v3s16 p,
5251 const std::string &from_list, int from_index,
5252 const std::string &to_list, int to_index,
5253 int count, 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_move"))
5271 // function(pos, from_list, from_index, to_list, to_index, count, player)
5273 lua_pushstring(L, from_list.c_str());
5274 lua_pushinteger(L, from_index + 1);
5275 lua_pushstring(L, to_list.c_str());
5276 lua_pushinteger(L, to_index + 1);
5277 lua_pushinteger(L, count);
5278 objectref_get_or_create(L, player);
5279 if(lua_pcall(L, 7, 0, 0))
5280 script_error(L, "error: %s", lua_tostring(L, -1));
5283 ItemStack scriptapi_node_on_metadata_inventory_offer(lua_State *L, v3s16 p,
5284 const std::string &listname, int index, ItemStack &stack,
5285 ServerActiveObject *player)
5288 assert(lua_checkstack(L, 20));
5289 StackUnroller stack_unroller(L);
5291 INodeDefManager *ndef = get_server(L)->ndef();
5293 // If node doesn't exist, we don't know what callback to call
5294 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5295 if(node.getContent() == CONTENT_IGNORE)
5298 // Push callback function on stack
5299 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5300 "on_metadata_inventory_offer"))
5303 // Call function(pos, listname, index, stack, player)
5305 lua_pushstring(L, listname.c_str());
5306 lua_pushinteger(L, index + 1);
5307 LuaItemStack::create(L, stack);
5308 objectref_get_or_create(L, player);
5309 if(lua_pcall(L, 5, 1, 0))
5310 script_error(L, "error: %s", lua_tostring(L, -1));
5311 return read_item(L, -1);
5314 ItemStack scriptapi_node_on_metadata_inventory_take(lua_State *L, v3s16 p,
5315 const std::string &listname, int index, int count,
5316 ServerActiveObject *player)
5319 assert(lua_checkstack(L, 20));
5320 StackUnroller stack_unroller(L);
5322 INodeDefManager *ndef = get_server(L)->ndef();
5324 // If node doesn't exist, we don't know what callback to call
5325 MapNode node = get_env(L)->getMap().getNodeNoEx(p);
5326 if(node.getContent() == CONTENT_IGNORE)
5329 // Push callback function on stack
5330 if(!get_item_callback(L, ndef->get(node).name.c_str(),
5331 "on_metadata_inventory_take"))
5334 // Call function(pos, listname, index, count, player)
5336 lua_pushstring(L, listname.c_str());
5337 lua_pushinteger(L, index + 1);
5338 lua_pushinteger(L, count);
5339 objectref_get_or_create(L, player);
5340 if(lua_pcall(L, 5, 1, 0))
5341 script_error(L, "error: %s", lua_tostring(L, -1));
5342 return read_item(L, -1);
5349 void scriptapi_environment_step(lua_State *L, float dtime)
5352 assert(lua_checkstack(L, 20));
5353 //infostream<<"scriptapi_environment_step"<<std::endl;
5354 StackUnroller stack_unroller(L);
5356 // Get minetest.registered_globalsteps
5357 lua_getglobal(L, "minetest");
5358 lua_getfield(L, -1, "registered_globalsteps");
5360 lua_pushnumber(L, dtime);
5361 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5364 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5368 assert(lua_checkstack(L, 20));
5369 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5370 StackUnroller stack_unroller(L);
5372 // Get minetest.registered_on_generateds
5373 lua_getglobal(L, "minetest");
5374 lua_getfield(L, -1, "registered_on_generateds");
5376 push_v3s16(L, minp);
5377 push_v3s16(L, maxp);
5378 lua_pushnumber(L, blockseed);
5379 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5386 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5389 assert(lua_checkstack(L, 20));
5390 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5391 <<name<<"\""<<std::endl;
5392 StackUnroller stack_unroller(L);
5394 // Get minetest.registered_entities[name]
5395 lua_getglobal(L, "minetest");
5396 lua_getfield(L, -1, "registered_entities");
5397 luaL_checktype(L, -1, LUA_TTABLE);
5398 lua_pushstring(L, name);
5399 lua_gettable(L, -2);
5400 // Should be a table, which we will use as a prototype
5401 //luaL_checktype(L, -1, LUA_TTABLE);
5402 if(lua_type(L, -1) != LUA_TTABLE){
5403 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5406 int prototype_table = lua_gettop(L);
5407 //dump2(L, "prototype_table");
5409 // Create entity object
5411 int object = lua_gettop(L);
5413 // Set object metatable
5414 lua_pushvalue(L, prototype_table);
5415 lua_setmetatable(L, -2);
5417 // Add object reference
5418 // This should be userdata with metatable ObjectRef
5419 objectref_get(L, id);
5420 luaL_checktype(L, -1, LUA_TUSERDATA);
5421 if(!luaL_checkudata(L, -1, "ObjectRef"))
5422 luaL_typerror(L, -1, "ObjectRef");
5423 lua_setfield(L, -2, "object");
5425 // minetest.luaentities[id] = object
5426 lua_getglobal(L, "minetest");
5427 lua_getfield(L, -1, "luaentities");
5428 luaL_checktype(L, -1, LUA_TTABLE);
5429 lua_pushnumber(L, id); // Push id
5430 lua_pushvalue(L, object); // Copy object to top of stack
5431 lua_settable(L, -3);
5436 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5437 const std::string &staticdata)
5440 assert(lua_checkstack(L, 20));
5441 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5442 StackUnroller stack_unroller(L);
5444 // Get minetest.luaentities[id]
5445 luaentity_get(L, id);
5446 int object = lua_gettop(L);
5448 // Get on_activate function
5449 lua_pushvalue(L, object);
5450 lua_getfield(L, -1, "on_activate");
5451 if(!lua_isnil(L, -1)){
5452 luaL_checktype(L, -1, LUA_TFUNCTION);
5453 lua_pushvalue(L, object); // self
5454 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5455 // Call with 2 arguments, 0 results
5456 if(lua_pcall(L, 2, 0, 0))
5457 script_error(L, "error running function on_activate: %s\n",
5458 lua_tostring(L, -1));
5462 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5465 assert(lua_checkstack(L, 20));
5466 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5468 // Get minetest.luaentities table
5469 lua_getglobal(L, "minetest");
5470 lua_getfield(L, -1, "luaentities");
5471 luaL_checktype(L, -1, LUA_TTABLE);
5472 int objectstable = lua_gettop(L);
5474 // Set luaentities[id] = nil
5475 lua_pushnumber(L, id); // Push id
5477 lua_settable(L, objectstable);
5479 lua_pop(L, 2); // pop luaentities, minetest
5482 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5485 assert(lua_checkstack(L, 20));
5486 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5487 StackUnroller stack_unroller(L);
5489 // Get minetest.luaentities[id]
5490 luaentity_get(L, id);
5491 int object = lua_gettop(L);
5493 // Get get_staticdata function
5494 lua_pushvalue(L, object);
5495 lua_getfield(L, -1, "get_staticdata");
5496 if(lua_isnil(L, -1))
5499 luaL_checktype(L, -1, LUA_TFUNCTION);
5500 lua_pushvalue(L, object); // self
5501 // Call with 1 arguments, 1 results
5502 if(lua_pcall(L, 1, 1, 0))
5503 script_error(L, "error running function get_staticdata: %s\n",
5504 lua_tostring(L, -1));
5507 const char *s = lua_tolstring(L, -1, &len);
5508 return std::string(s, len);
5511 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5512 ObjectProperties *prop)
5515 assert(lua_checkstack(L, 20));
5516 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5517 StackUnroller stack_unroller(L);
5519 // Get minetest.luaentities[id]
5520 luaentity_get(L, id);
5521 //int object = lua_gettop(L);
5523 // Set default values that differ from ObjectProperties defaults
5526 // Deprecated: read object properties directly
5527 read_object_properties(L, -1, prop);
5529 // Read initial_properties
5530 lua_getfield(L, -1, "initial_properties");
5531 read_object_properties(L, -1, prop);
5535 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5538 assert(lua_checkstack(L, 20));
5539 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5540 StackUnroller stack_unroller(L);
5542 // Get minetest.luaentities[id]
5543 luaentity_get(L, id);
5544 int object = lua_gettop(L);
5545 // State: object is at top of stack
5546 // Get step function
5547 lua_getfield(L, -1, "on_step");
5548 if(lua_isnil(L, -1))
5550 luaL_checktype(L, -1, LUA_TFUNCTION);
5551 lua_pushvalue(L, object); // self
5552 lua_pushnumber(L, dtime); // dtime
5553 // Call with 2 arguments, 0 results
5554 if(lua_pcall(L, 2, 0, 0))
5555 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5558 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5559 // tool_capabilities, direction)
5560 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5561 ServerActiveObject *puncher, float time_from_last_punch,
5562 const ToolCapabilities *toolcap, v3f dir)
5565 assert(lua_checkstack(L, 20));
5566 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5567 StackUnroller stack_unroller(L);
5569 // Get minetest.luaentities[id]
5570 luaentity_get(L, id);
5571 int object = lua_gettop(L);
5572 // State: object is at top of stack
5574 lua_getfield(L, -1, "on_punch");
5575 if(lua_isnil(L, -1))
5577 luaL_checktype(L, -1, LUA_TFUNCTION);
5578 lua_pushvalue(L, object); // self
5579 objectref_get_or_create(L, puncher); // Clicker reference
5580 lua_pushnumber(L, time_from_last_punch);
5581 push_tool_capabilities(L, *toolcap);
5583 // Call with 5 arguments, 0 results
5584 if(lua_pcall(L, 5, 0, 0))
5585 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5588 // Calls entity:on_rightclick(ObjectRef clicker)
5589 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5590 ServerActiveObject *clicker)
5593 assert(lua_checkstack(L, 20));
5594 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5595 StackUnroller stack_unroller(L);
5597 // Get minetest.luaentities[id]
5598 luaentity_get(L, id);
5599 int object = lua_gettop(L);
5600 // State: object is at top of stack
5602 lua_getfield(L, -1, "on_rightclick");
5603 if(lua_isnil(L, -1))
5605 luaL_checktype(L, -1, LUA_TFUNCTION);
5606 lua_pushvalue(L, object); // self
5607 objectref_get_or_create(L, clicker); // Clicker reference
5608 // Call with 2 arguments, 0 results
5609 if(lua_pcall(L, 2, 0, 0))
5610 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));