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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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"},
422 C struct <-> Lua table converter functions
425 static void push_v3f(lua_State *L, v3f p)
428 lua_pushnumber(L, p.X);
429 lua_setfield(L, -2, "x");
430 lua_pushnumber(L, p.Y);
431 lua_setfield(L, -2, "y");
432 lua_pushnumber(L, p.Z);
433 lua_setfield(L, -2, "z");
436 static v2s16 read_v2s16(lua_State *L, int index)
439 luaL_checktype(L, index, LUA_TTABLE);
440 lua_getfield(L, index, "x");
441 p.X = lua_tonumber(L, -1);
443 lua_getfield(L, index, "y");
444 p.Y = lua_tonumber(L, -1);
449 static v2f read_v2f(lua_State *L, int index)
452 luaL_checktype(L, index, LUA_TTABLE);
453 lua_getfield(L, index, "x");
454 p.X = lua_tonumber(L, -1);
456 lua_getfield(L, index, "y");
457 p.Y = lua_tonumber(L, -1);
462 static v3f read_v3f(lua_State *L, int index)
465 luaL_checktype(L, index, LUA_TTABLE);
466 lua_getfield(L, index, "x");
467 pos.X = lua_tonumber(L, -1);
469 lua_getfield(L, index, "y");
470 pos.Y = lua_tonumber(L, -1);
472 lua_getfield(L, index, "z");
473 pos.Z = lua_tonumber(L, -1);
478 static v3f check_v3f(lua_State *L, int index)
481 luaL_checktype(L, index, LUA_TTABLE);
482 lua_getfield(L, index, "x");
483 pos.X = luaL_checknumber(L, -1);
485 lua_getfield(L, index, "y");
486 pos.Y = luaL_checknumber(L, -1);
488 lua_getfield(L, index, "z");
489 pos.Z = luaL_checknumber(L, -1);
494 static void pushFloatPos(lua_State *L, v3f p)
500 static v3f checkFloatPos(lua_State *L, int index)
502 return check_v3f(L, index) * BS;
505 static void push_v3s16(lua_State *L, v3s16 p)
508 lua_pushnumber(L, p.X);
509 lua_setfield(L, -2, "x");
510 lua_pushnumber(L, p.Y);
511 lua_setfield(L, -2, "y");
512 lua_pushnumber(L, p.Z);
513 lua_setfield(L, -2, "z");
516 static v3s16 read_v3s16(lua_State *L, int index)
518 // Correct rounding at <0
519 v3f pf = read_v3f(L, index);
520 return floatToInt(pf, 1.0);
523 static v3s16 check_v3s16(lua_State *L, int index)
525 // Correct rounding at <0
526 v3f pf = check_v3f(L, index);
527 return floatToInt(pf, 1.0);
530 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
533 lua_pushstring(L, ndef->get(n).name.c_str());
534 lua_setfield(L, -2, "name");
535 lua_pushnumber(L, n.getParam1());
536 lua_setfield(L, -2, "param1");
537 lua_pushnumber(L, n.getParam2());
538 lua_setfield(L, -2, "param2");
541 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
543 lua_getfield(L, index, "name");
544 const char *name = luaL_checkstring(L, -1);
547 lua_getfield(L, index, "param1");
551 param1 = lua_tonumber(L, -1);
554 lua_getfield(L, index, "param2");
558 param2 = lua_tonumber(L, -1);
560 return MapNode(ndef, name, param1, param2);
563 static video::SColor readARGB8(lua_State *L, int index)
566 luaL_checktype(L, index, LUA_TTABLE);
567 lua_getfield(L, index, "a");
568 if(lua_isnumber(L, -1))
569 color.setAlpha(lua_tonumber(L, -1));
571 lua_getfield(L, index, "r");
572 color.setRed(lua_tonumber(L, -1));
574 lua_getfield(L, index, "g");
575 color.setGreen(lua_tonumber(L, -1));
577 lua_getfield(L, index, "b");
578 color.setBlue(lua_tonumber(L, -1));
583 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
585 core::aabbox3d<f32> box;
586 if(lua_istable(L, -1)){
587 lua_rawgeti(L, -1, 1);
588 box.MinEdge.X = lua_tonumber(L, -1) * scale;
590 lua_rawgeti(L, -1, 2);
591 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
593 lua_rawgeti(L, -1, 3);
594 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
596 lua_rawgeti(L, -1, 4);
597 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
599 lua_rawgeti(L, -1, 5);
600 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
602 lua_rawgeti(L, -1, 6);
603 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
614 static MaterialProperties read_material_properties(
615 lua_State *L, int table)
617 MaterialProperties prop;
618 prop.diggability = (Diggability)getenumfield(L, -1, "diggability",
619 es_Diggability, DIGGABLE_NORMAL);
620 getfloatfield(L, -1, "constant_time", prop.constant_time);
621 getfloatfield(L, -1, "weight", prop.weight);
622 getfloatfield(L, -1, "crackiness", prop.crackiness);
623 getfloatfield(L, -1, "crumbliness", prop.crumbliness);
624 getfloatfield(L, -1, "cuttability", prop.cuttability);
625 getfloatfield(L, -1, "flammability", prop.flammability);
633 static void read_groups(lua_State *L, int index,
634 std::map<std::string, int> &result)
640 while(lua_next(L, index) != 0){
641 // key at index -2 and value at index -1
642 std::string name = luaL_checkstring(L, -2);
643 int rating = luaL_checkinteger(L, -1);
644 result[name] = rating;
645 // removes value, keeps key for next iteration
654 static ToolCapabilities read_tool_capabilities(
655 lua_State *L, int table)
657 ToolCapabilities toolcap;
658 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
659 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
660 lua_getfield(L, table, "groupcaps");
661 if(lua_istable(L, -1)){
662 int table_groupcaps = lua_gettop(L);
664 while(lua_next(L, table_groupcaps) != 0){
665 // key at index -2 and value at index -1
666 std::string groupname = luaL_checkstring(L, -2);
667 if(lua_istable(L, -1)){
668 int table_groupcap = lua_gettop(L);
669 // This will be created
670 ToolGroupCap groupcap;
671 // Read simple parameters
672 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
673 getintfield(L, table_groupcap, "uses", groupcap.uses);
674 // DEPRECATED: maxwear
676 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
678 groupcap.uses = 1.0/maxwear;
681 infostream<<script_get_backtrace(L)<<std::endl;
682 infostream<<"WARNING: field \"maxwear\" is deprecated; "
683 <<"should replace with uses=1/maxwear"<<std::endl;
685 // Read "times" table
686 lua_getfield(L, table_groupcap, "times");
687 if(lua_istable(L, -1)){
688 int table_times = lua_gettop(L);
690 while(lua_next(L, table_times) != 0){
691 // key at index -2 and value at index -1
692 int rating = luaL_checkinteger(L, -2);
693 float time = luaL_checknumber(L, -1);
694 groupcap.times[rating] = time;
695 // removes value, keeps key for next iteration
700 // Insert groupcap into toolcap
701 toolcap.groupcaps[groupname] = groupcap;
703 // removes value, keeps key for next iteration
711 static void set_tool_capabilities(lua_State *L, int table,
712 const ToolCapabilities &toolcap)
714 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
715 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
716 // Create groupcaps table
719 for(std::map<std::string, ToolGroupCap>::const_iterator
720 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
721 // Create groupcap table
723 const std::string &name = i->first;
724 const ToolGroupCap &groupcap = i->second;
725 // Create subtable "times"
727 for(std::map<int, float>::const_iterator
728 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
729 int rating = i->first;
730 float time = i->second;
731 lua_pushinteger(L, rating);
732 lua_pushnumber(L, time);
735 // Set subtable "times"
736 lua_setfield(L, -2, "times");
737 // Set simple parameters
738 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
739 setintfield(L, -1, "uses", groupcap.uses);
740 // Insert groupcap table into groupcaps table
741 lua_setfield(L, -2, name.c_str());
743 // Set groupcaps table
744 lua_setfield(L, -2, "groupcaps");
747 static void push_tool_capabilities(lua_State *L,
748 const ToolCapabilities &prop)
751 set_tool_capabilities(L, -1, prop);
758 static void set_dig_params(lua_State *L, int table,
759 const DigParams ¶ms)
761 setboolfield(L, table, "diggable", params.diggable);
762 setfloatfield(L, table, "time", params.time);
763 setintfield(L, table, "wear", params.wear);
766 static void push_dig_params(lua_State *L,
767 const DigParams ¶ms)
770 set_dig_params(L, -1, params);
777 static void set_hit_params(lua_State *L, int table,
778 const HitParams ¶ms)
780 setintfield(L, table, "hp", params.hp);
781 setintfield(L, table, "wear", params.wear);
784 static void push_hit_params(lua_State *L,
785 const HitParams ¶ms)
788 set_hit_params(L, -1, params);
795 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
798 if(pointed.type == POINTEDTHING_NODE)
800 lua_pushstring(L, "node");
801 lua_setfield(L, -2, "type");
802 push_v3s16(L, pointed.node_undersurface);
803 lua_setfield(L, -2, "under");
804 push_v3s16(L, pointed.node_abovesurface);
805 lua_setfield(L, -2, "above");
807 else if(pointed.type == POINTEDTHING_OBJECT)
809 lua_pushstring(L, "object");
810 lua_setfield(L, -2, "type");
811 objectref_get(L, pointed.object_id);
812 lua_setfield(L, -2, "ref");
816 lua_pushstring(L, "nothing");
817 lua_setfield(L, -2, "type");
825 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
828 index = lua_gettop(L) + 1 + index;
829 if(lua_isnil(L, index)){
830 } else if(lua_istable(L, index)){
831 getstringfield(L, index, "name", spec.name);
832 getfloatfield(L, index, "gain", spec.gain);
833 } else if(lua_isstring(L, index)){
834 spec.name = lua_tostring(L, index);
842 static void read_object_properties(lua_State *L, int index,
843 ObjectProperties *prop)
846 index = lua_gettop(L) + 1 + index;
847 if(!lua_istable(L, index))
850 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
852 getboolfield(L, -1, "physical", prop->physical);
854 getfloatfield(L, -1, "weight", prop->weight);
856 lua_getfield(L, -1, "collisionbox");
857 if(lua_istable(L, -1))
858 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
861 getstringfield(L, -1, "visual", prop->visual);
863 lua_getfield(L, -1, "visual_size");
864 if(lua_istable(L, -1))
865 prop->visual_size = read_v2f(L, -1);
868 lua_getfield(L, -1, "textures");
869 if(lua_istable(L, -1)){
870 prop->textures.clear();
871 int table = lua_gettop(L);
873 while(lua_next(L, table) != 0){
874 // key at index -2 and value at index -1
875 if(lua_isstring(L, -1))
876 prop->textures.push_back(lua_tostring(L, -1));
878 prop->textures.push_back("");
879 // removes value, keeps key for next iteration
885 lua_getfield(L, -1, "spritediv");
886 if(lua_istable(L, -1))
887 prop->spritediv = read_v2s16(L, -1);
890 lua_getfield(L, -1, "initial_sprite_basepos");
891 if(lua_istable(L, -1))
892 prop->initial_sprite_basepos = read_v2s16(L, -1);
895 getboolfield(L, -1, "is_visible", prop->is_visible);
896 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
903 static ItemDefinition read_item_definition(lua_State *L, int index)
906 index = lua_gettop(L) + 1 + index;
908 // Read the item definition
911 def.type = (ItemType)getenumfield(L, index, "type",
912 es_ItemType, ITEM_NONE);
913 getstringfield(L, index, "name", def.name);
914 getstringfield(L, index, "description", def.description);
915 getstringfield(L, index, "inventory_image", def.inventory_image);
916 getstringfield(L, index, "wield_image", def.wield_image);
918 lua_getfield(L, index, "wield_scale");
919 if(lua_istable(L, -1)){
920 def.wield_scale = check_v3f(L, -1);
924 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
925 if(def.stack_max == 0)
928 lua_getfield(L, index, "on_use");
929 def.usable = lua_isfunction(L, -1);
932 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
934 warn_if_field_exists(L, index, "tool_digging_properties",
935 "deprecated: use tool_capabilities");
937 lua_getfield(L, index, "tool_capabilities");
938 if(lua_istable(L, -1)){
939 def.tool_capabilities = new ToolCapabilities(
940 read_tool_capabilities(L, -1));
943 // If name is "" (hand), ensure there are ToolCapabilities
944 // because it will be looked up there whenever any other item has
945 // no ToolCapabilities
946 if(def.name == "" && def.tool_capabilities == NULL){
947 def.tool_capabilities = new ToolCapabilities();
950 lua_getfield(L, index, "groups");
951 read_groups(L, -1, def.groups);
961 static ContentFeatures read_content_features(lua_State *L, int index)
964 index = lua_gettop(L) + 1 + index;
968 getstringfield(L, index, "name", f.name);
971 lua_getfield(L, index, "groups");
972 read_groups(L, -1, f.groups);
975 /* Visual definition */
977 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
979 getfloatfield(L, index, "visual_scale", f.visual_scale);
981 lua_getfield(L, index, "tile_images");
982 if(lua_istable(L, -1)){
983 int table = lua_gettop(L);
986 while(lua_next(L, table) != 0){
987 // key at index -2 and value at index -1
988 if(lua_isstring(L, -1))
989 f.tname_tiles[i] = lua_tostring(L, -1);
991 f.tname_tiles[i] = "";
992 // removes value, keeps key for next iteration
1000 // Copy last value to all remaining textures
1002 std::string lastname = f.tname_tiles[i-1];
1004 f.tname_tiles[i] = lastname;
1011 lua_getfield(L, index, "special_materials");
1012 if(lua_istable(L, -1)){
1013 int table = lua_gettop(L);
1016 while(lua_next(L, table) != 0){
1017 // key at index -2 and value at index -1
1018 int smtable = lua_gettop(L);
1019 std::string tname = getstringfield_default(
1020 L, smtable, "image", "");
1021 bool backface_culling = getboolfield_default(
1022 L, smtable, "backface_culling", true);
1023 MaterialSpec mspec(tname, backface_culling);
1024 f.mspec_special[i] = mspec;
1025 // removes value, keeps key for next iteration
1036 f.alpha = getintfield_default(L, index, "alpha", 255);
1040 lua_getfield(L, index, "post_effect_color");
1041 if(!lua_isnil(L, -1))
1042 f.post_effect_color = readARGB8(L, -1);
1045 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1046 es_ContentParamType, CPT_NONE);
1047 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1048 es_ContentParamType2, CPT2_NONE);
1050 // Warn about some deprecated fields
1051 warn_if_field_exists(L, index, "wall_mounted",
1052 "deprecated: use paramtype2 = 'wallmounted'");
1053 warn_if_field_exists(L, index, "light_propagates",
1054 "deprecated: determined from paramtype");
1055 warn_if_field_exists(L, index, "dug_item",
1056 "deprecated: use 'drop' field");
1057 warn_if_field_exists(L, index, "extra_dug_item",
1058 "deprecated: use 'drop' field");
1059 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1060 "deprecated: use 'drop' field");
1062 // True for all ground-like things like stone and mud, false for eg. trees
1063 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1064 f.light_propagates = (f.param_type == CPT_LIGHT);
1065 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1066 // This is used for collision detection.
1067 // Also for general solidness queries.
1068 getboolfield(L, index, "walkable", f.walkable);
1069 // Player can point to these
1070 getboolfield(L, index, "pointable", f.pointable);
1071 // Player can dig these
1072 getboolfield(L, index, "diggable", f.diggable);
1073 // Player can climb these
1074 getboolfield(L, index, "climbable", f.climbable);
1075 // Player can build on these
1076 getboolfield(L, index, "buildable_to", f.buildable_to);
1077 // Metadata name of node (eg. "furnace")
1078 getstringfield(L, index, "metadata_name", f.metadata_name);
1079 // Whether the node is non-liquid, source liquid or flowing liquid
1080 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1081 es_LiquidType, LIQUID_NONE);
1082 // If the content is liquid, this is the flowing version of the liquid.
1083 getstringfield(L, index, "liquid_alternative_flowing",
1084 f.liquid_alternative_flowing);
1085 // If the content is liquid, this is the source version of the liquid.
1086 getstringfield(L, index, "liquid_alternative_source",
1087 f.liquid_alternative_source);
1088 // Viscosity for fluid flow, ranging from 1 to 7, with
1089 // 1 giving almost instantaneous propagation and 7 being
1090 // the slowest possible
1091 f.liquid_viscosity = getintfield_default(L, index,
1092 "liquid_viscosity", f.liquid_viscosity);
1093 // Amount of light the node emits
1094 f.light_source = getintfield_default(L, index,
1095 "light_source", f.light_source);
1096 f.damage_per_second = getintfield_default(L, index,
1097 "damage_per_second", f.damage_per_second);
1099 lua_getfield(L, index, "selection_box");
1100 if(lua_istable(L, -1)){
1101 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1102 es_NodeBoxType, NODEBOX_REGULAR);
1104 lua_getfield(L, -1, "fixed");
1105 if(lua_istable(L, -1))
1106 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1109 lua_getfield(L, -1, "wall_top");
1110 if(lua_istable(L, -1))
1111 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1114 lua_getfield(L, -1, "wall_bottom");
1115 if(lua_istable(L, -1))
1116 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1119 lua_getfield(L, -1, "wall_side");
1120 if(lua_istable(L, -1))
1121 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1126 // Set to true if paramtype used to be 'facedir_simple'
1127 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1128 // Set to true if wall_mounted used to be set to true
1129 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1132 lua_getfield(L, index, "sounds");
1133 if(lua_istable(L, -1)){
1134 lua_getfield(L, -1, "footstep");
1135 read_soundspec(L, -1, f.sound_footstep);
1137 lua_getfield(L, -1, "dig");
1138 read_soundspec(L, -1, f.sound_dig);
1140 lua_getfield(L, -1, "dug");
1141 read_soundspec(L, -1, f.sound_dug);
1153 static ItemStack read_item(lua_State *L, int index);
1155 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1156 lua_State *L, int tableindex, int forcesize=-1)
1159 tableindex = lua_gettop(L) + 1 + tableindex;
1160 // If nil, delete list
1161 if(lua_isnil(L, tableindex)){
1162 inv->deleteList(name);
1165 // Otherwise set list
1166 std::vector<ItemStack> items;
1167 luaL_checktype(L, tableindex, LUA_TTABLE);
1169 while(lua_next(L, tableindex) != 0){
1170 // key at index -2 and value at index -1
1171 items.push_back(read_item(L, -1));
1172 // removes value, keeps key for next iteration
1175 int listsize = (forcesize != -1) ? forcesize : items.size();
1176 InventoryList *invlist = inv->addList(name, listsize);
1178 for(std::vector<ItemStack>::const_iterator
1179 i = items.begin(); i != items.end(); i++){
1180 if(forcesize != -1 && index == forcesize)
1182 invlist->changeItem(index, *i);
1185 while(forcesize != -1 && index < forcesize){
1186 invlist->deleteItem(index);
1191 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1194 InventoryList *invlist = inv->getList(name);
1195 if(invlist == NULL){
1199 // Get the table insert function
1200 lua_getglobal(L, "table");
1201 lua_getfield(L, -1, "insert");
1202 int table_insert = lua_gettop(L);
1203 // Create and fill table
1205 int table = lua_gettop(L);
1206 for(u32 i=0; i<invlist->getSize(); i++){
1207 ItemStack item = invlist->getItem(i);
1208 lua_pushvalue(L, table_insert);
1209 lua_pushvalue(L, table);
1210 lua_pushstring(L, item.getItemString().c_str());
1211 if(lua_pcall(L, 2, 0, 0))
1212 script_error(L, "error: %s", lua_tostring(L, -1));
1217 Helpful macros for userdata classes
1220 #define method(class, name) {#name, class::l_##name}
1231 static const char className[];
1232 static const luaL_reg methods[];
1234 // Exported functions
1236 // garbage collector
1237 static int gc_object(lua_State *L)
1239 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1244 // is_empty(self) -> true/false
1245 static int l_is_empty(lua_State *L)
1247 LuaItemStack *o = checkobject(L, 1);
1248 ItemStack &item = o->m_stack;
1249 lua_pushboolean(L, item.empty());
1253 // get_name(self) -> string
1254 static int l_get_name(lua_State *L)
1256 LuaItemStack *o = checkobject(L, 1);
1257 ItemStack &item = o->m_stack;
1258 lua_pushstring(L, item.name.c_str());
1262 // get_count(self) -> number
1263 static int l_get_count(lua_State *L)
1265 LuaItemStack *o = checkobject(L, 1);
1266 ItemStack &item = o->m_stack;
1267 lua_pushinteger(L, item.count);
1271 // get_wear(self) -> number
1272 static int l_get_wear(lua_State *L)
1274 LuaItemStack *o = checkobject(L, 1);
1275 ItemStack &item = o->m_stack;
1276 lua_pushinteger(L, item.wear);
1280 // get_metadata(self) -> string
1281 static int l_get_metadata(lua_State *L)
1283 LuaItemStack *o = checkobject(L, 1);
1284 ItemStack &item = o->m_stack;
1285 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1289 // clear(self) -> true
1290 static int l_clear(lua_State *L)
1292 LuaItemStack *o = checkobject(L, 1);
1294 lua_pushboolean(L, true);
1298 // replace(self, itemstack or itemstring or table or nil) -> true
1299 static int l_replace(lua_State *L)
1301 LuaItemStack *o = checkobject(L, 1);
1302 o->m_stack = read_item(L, 2);
1303 lua_pushboolean(L, true);
1307 // to_string(self) -> string
1308 static int l_to_string(lua_State *L)
1310 LuaItemStack *o = checkobject(L, 1);
1311 std::string itemstring = o->m_stack.getItemString();
1312 lua_pushstring(L, itemstring.c_str());
1316 // to_table(self) -> table or nil
1317 static int l_to_table(lua_State *L)
1319 LuaItemStack *o = checkobject(L, 1);
1320 const ItemStack &item = o->m_stack;
1328 lua_pushstring(L, item.name.c_str());
1329 lua_setfield(L, -2, "name");
1330 lua_pushinteger(L, item.count);
1331 lua_setfield(L, -2, "count");
1332 lua_pushinteger(L, item.wear);
1333 lua_setfield(L, -2, "wear");
1334 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1335 lua_setfield(L, -2, "metadata");
1340 // get_stack_max(self) -> number
1341 static int l_get_stack_max(lua_State *L)
1343 LuaItemStack *o = checkobject(L, 1);
1344 ItemStack &item = o->m_stack;
1345 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1349 // get_free_space(self) -> number
1350 static int l_get_free_space(lua_State *L)
1352 LuaItemStack *o = checkobject(L, 1);
1353 ItemStack &item = o->m_stack;
1354 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1358 // is_known(self) -> true/false
1359 // Checks if the item is defined.
1360 static int l_is_known(lua_State *L)
1362 LuaItemStack *o = checkobject(L, 1);
1363 ItemStack &item = o->m_stack;
1364 bool is_known = item.isKnown(get_server(L)->idef());
1365 lua_pushboolean(L, is_known);
1369 // get_definition(self) -> table
1370 // Returns the item definition table from minetest.registered_items,
1371 // or a fallback one (name="unknown")
1372 static int l_get_definition(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1377 // Get minetest.registered_items[name]
1378 lua_getglobal(L, "minetest");
1379 lua_getfield(L, -1, "registered_items");
1380 luaL_checktype(L, -1, LUA_TTABLE);
1381 lua_getfield(L, -1, item.name.c_str());
1382 if(lua_isnil(L, -1))
1385 lua_getfield(L, -1, "unknown");
1390 // get_tool_capabilities(self) -> table
1391 // Returns the effective tool digging properties.
1392 // Returns those of the hand ("") if this item has none associated.
1393 static int l_get_tool_capabilities(lua_State *L)
1395 LuaItemStack *o = checkobject(L, 1);
1396 ItemStack &item = o->m_stack;
1397 const ToolCapabilities &prop =
1398 item.getToolCapabilities(get_server(L)->idef());
1399 push_tool_capabilities(L, prop);
1403 // add_wear(self, amount) -> true/false
1404 // The range for "amount" is [0,65535]. Wear is only added if the item
1405 // is a tool. Adding wear might destroy the item.
1406 // Returns true if the item is (or was) a tool.
1407 static int l_add_wear(lua_State *L)
1409 LuaItemStack *o = checkobject(L, 1);
1410 ItemStack &item = o->m_stack;
1411 int amount = lua_tointeger(L, 2);
1412 bool result = item.addWear(amount, get_server(L)->idef());
1413 lua_pushboolean(L, result);
1417 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1418 // Returns leftover item stack
1419 static int l_add_item(lua_State *L)
1421 LuaItemStack *o = checkobject(L, 1);
1422 ItemStack &item = o->m_stack;
1423 ItemStack newitem = read_item(L, 2);
1424 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1425 create(L, leftover);
1429 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1430 // First return value is true iff the new item fits fully into the stack
1431 // Second return value is the would-be-left-over item stack
1432 static int l_item_fits(lua_State *L)
1434 LuaItemStack *o = checkobject(L, 1);
1435 ItemStack &item = o->m_stack;
1436 ItemStack newitem = read_item(L, 2);
1438 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1439 lua_pushboolean(L, fits); // first return value
1440 create(L, restitem); // second return value
1444 // take_item(self, takecount=1) -> itemstack
1445 static int l_take_item(lua_State *L)
1447 LuaItemStack *o = checkobject(L, 1);
1448 ItemStack &item = o->m_stack;
1450 if(!lua_isnone(L, 2))
1451 takecount = lua_tointeger(L, 2);
1452 ItemStack taken = item.takeItem(takecount);
1457 // peek_item(self, peekcount=1) -> itemstack
1458 static int l_peek_item(lua_State *L)
1460 LuaItemStack *o = checkobject(L, 1);
1461 ItemStack &item = o->m_stack;
1463 if(!lua_isnone(L, 2))
1464 peekcount = lua_tointeger(L, 2);
1465 ItemStack peekaboo = item.peekItem(peekcount);
1466 create(L, peekaboo);
1471 LuaItemStack(const ItemStack &item):
1480 const ItemStack& getItem() const
1484 ItemStack& getItem()
1489 // LuaItemStack(itemstack or itemstring or table or nil)
1490 // Creates an LuaItemStack and leaves it on top of stack
1491 static int create_object(lua_State *L)
1493 ItemStack item = read_item(L, 1);
1494 LuaItemStack *o = new LuaItemStack(item);
1495 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1496 luaL_getmetatable(L, className);
1497 lua_setmetatable(L, -2);
1500 // Not callable from Lua
1501 static int create(lua_State *L, const ItemStack &item)
1503 LuaItemStack *o = new LuaItemStack(item);
1504 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1505 luaL_getmetatable(L, className);
1506 lua_setmetatable(L, -2);
1510 static LuaItemStack* checkobject(lua_State *L, int narg)
1512 luaL_checktype(L, narg, LUA_TUSERDATA);
1513 void *ud = luaL_checkudata(L, narg, className);
1514 if(!ud) luaL_typerror(L, narg, className);
1515 return *(LuaItemStack**)ud; // unbox pointer
1518 static void Register(lua_State *L)
1521 int methodtable = lua_gettop(L);
1522 luaL_newmetatable(L, className);
1523 int metatable = lua_gettop(L);
1525 lua_pushliteral(L, "__metatable");
1526 lua_pushvalue(L, methodtable);
1527 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1529 lua_pushliteral(L, "__index");
1530 lua_pushvalue(L, methodtable);
1531 lua_settable(L, metatable);
1533 lua_pushliteral(L, "__gc");
1534 lua_pushcfunction(L, gc_object);
1535 lua_settable(L, metatable);
1537 lua_pop(L, 1); // drop metatable
1539 luaL_openlib(L, 0, methods, 0); // fill methodtable
1540 lua_pop(L, 1); // drop methodtable
1542 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1543 lua_register(L, className, create_object);
1546 const char LuaItemStack::className[] = "ItemStack";
1547 const luaL_reg LuaItemStack::methods[] = {
1548 method(LuaItemStack, is_empty),
1549 method(LuaItemStack, get_name),
1550 method(LuaItemStack, get_count),
1551 method(LuaItemStack, get_wear),
1552 method(LuaItemStack, get_metadata),
1553 method(LuaItemStack, clear),
1554 method(LuaItemStack, replace),
1555 method(LuaItemStack, to_string),
1556 method(LuaItemStack, to_table),
1557 method(LuaItemStack, get_stack_max),
1558 method(LuaItemStack, get_free_space),
1559 method(LuaItemStack, is_known),
1560 method(LuaItemStack, get_definition),
1561 method(LuaItemStack, get_tool_capabilities),
1562 method(LuaItemStack, add_wear),
1563 method(LuaItemStack, add_item),
1564 method(LuaItemStack, item_fits),
1565 method(LuaItemStack, take_item),
1566 method(LuaItemStack, peek_item),
1570 static ItemStack read_item(lua_State *L, int index)
1573 index = lua_gettop(L) + 1 + index;
1575 if(lua_isnil(L, index))
1579 else if(lua_isuserdata(L, index))
1581 // Convert from LuaItemStack
1582 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1583 return o->getItem();
1585 else if(lua_isstring(L, index))
1587 // Convert from itemstring
1588 std::string itemstring = lua_tostring(L, index);
1589 IItemDefManager *idef = get_server(L)->idef();
1593 item.deSerialize(itemstring, idef);
1596 catch(SerializationError &e)
1598 infostream<<"WARNING: unable to create item from itemstring"
1599 <<": "<<itemstring<<std::endl;
1603 else if(lua_istable(L, index))
1605 // Convert from table
1606 IItemDefManager *idef = get_server(L)->idef();
1607 std::string name = getstringfield_default(L, index, "name", "");
1608 int count = getintfield_default(L, index, "count", 1);
1609 int wear = getintfield_default(L, index, "wear", 0);
1610 std::string metadata = getstringfield_default(L, index, "metadata", "");
1611 return ItemStack(name, count, wear, metadata, idef);
1615 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1626 InventoryLocation m_loc;
1628 static const char className[];
1629 static const luaL_reg methods[];
1631 static InvRef *checkobject(lua_State *L, int narg)
1633 luaL_checktype(L, narg, LUA_TUSERDATA);
1634 void *ud = luaL_checkudata(L, narg, className);
1635 if(!ud) luaL_typerror(L, narg, className);
1636 return *(InvRef**)ud; // unbox pointer
1639 static Inventory* getinv(lua_State *L, InvRef *ref)
1641 return get_server(L)->getInventory(ref->m_loc);
1644 static InventoryList* getlist(lua_State *L, InvRef *ref,
1645 const char *listname)
1647 Inventory *inv = getinv(L, ref);
1650 return inv->getList(listname);
1653 static void reportInventoryChange(lua_State *L, InvRef *ref)
1655 // Inform other things that the inventory has changed
1656 get_server(L)->setInventoryModified(ref->m_loc);
1659 // Exported functions
1661 // garbage collector
1662 static int gc_object(lua_State *L) {
1663 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1668 // get_size(self, listname)
1669 static int l_get_size(lua_State *L)
1671 InvRef *ref = checkobject(L, 1);
1672 const char *listname = luaL_checkstring(L, 2);
1673 InventoryList *list = getlist(L, ref, listname);
1675 lua_pushinteger(L, list->getSize());
1677 lua_pushinteger(L, 0);
1682 // set_size(self, listname, size)
1683 static int l_set_size(lua_State *L)
1685 InvRef *ref = checkobject(L, 1);
1686 const char *listname = luaL_checkstring(L, 2);
1687 int newsize = luaL_checknumber(L, 3);
1688 Inventory *inv = getinv(L, ref);
1690 inv->deleteList(listname);
1691 reportInventoryChange(L, ref);
1694 InventoryList *list = inv->getList(listname);
1696 list->setSize(newsize);
1698 list = inv->addList(listname, newsize);
1700 reportInventoryChange(L, ref);
1704 // get_stack(self, listname, i) -> itemstack
1705 static int l_get_stack(lua_State *L)
1707 InvRef *ref = checkobject(L, 1);
1708 const char *listname = luaL_checkstring(L, 2);
1709 int i = luaL_checknumber(L, 3) - 1;
1710 InventoryList *list = getlist(L, ref, listname);
1712 if(list != NULL && i >= 0 && i < (int) list->getSize())
1713 item = list->getItem(i);
1714 LuaItemStack::create(L, item);
1718 // set_stack(self, listname, i, stack) -> true/false
1719 static int l_set_stack(lua_State *L)
1721 InvRef *ref = checkobject(L, 1);
1722 const char *listname = luaL_checkstring(L, 2);
1723 int i = luaL_checknumber(L, 3) - 1;
1724 ItemStack newitem = read_item(L, 4);
1725 InventoryList *list = getlist(L, ref, listname);
1726 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1727 list->changeItem(i, newitem);
1728 reportInventoryChange(L, ref);
1729 lua_pushboolean(L, true);
1731 lua_pushboolean(L, false);
1736 // get_list(self, listname) -> list or nil
1737 static int l_get_list(lua_State *L)
1739 InvRef *ref = checkobject(L, 1);
1740 const char *listname = luaL_checkstring(L, 2);
1741 Inventory *inv = getinv(L, ref);
1742 inventory_get_list_to_lua(inv, listname, L);
1746 // set_list(self, listname, list)
1747 static int l_set_list(lua_State *L)
1749 InvRef *ref = checkobject(L, 1);
1750 const char *listname = luaL_checkstring(L, 2);
1751 Inventory *inv = getinv(L, ref);
1752 InventoryList *list = inv->getList(listname);
1754 inventory_set_list_from_lua(inv, listname, L, 3,
1757 inventory_set_list_from_lua(inv, listname, L, 3);
1758 reportInventoryChange(L, ref);
1762 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1763 // Returns the leftover stack
1764 static int l_add_item(lua_State *L)
1766 InvRef *ref = checkobject(L, 1);
1767 const char *listname = luaL_checkstring(L, 2);
1768 ItemStack item = read_item(L, 3);
1769 InventoryList *list = getlist(L, ref, listname);
1771 ItemStack leftover = list->addItem(item);
1772 if(leftover.count != item.count)
1773 reportInventoryChange(L, ref);
1774 LuaItemStack::create(L, leftover);
1776 LuaItemStack::create(L, item);
1781 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1782 // Returns true if the item completely fits into the list
1783 static int l_room_for_item(lua_State *L)
1785 InvRef *ref = checkobject(L, 1);
1786 const char *listname = luaL_checkstring(L, 2);
1787 ItemStack item = read_item(L, 3);
1788 InventoryList *list = getlist(L, ref, listname);
1790 lua_pushboolean(L, list->roomForItem(item));
1792 lua_pushboolean(L, false);
1797 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1798 // Returns true if the list contains the given count of the given item name
1799 static int l_contains_item(lua_State *L)
1801 InvRef *ref = checkobject(L, 1);
1802 const char *listname = luaL_checkstring(L, 2);
1803 ItemStack item = read_item(L, 3);
1804 InventoryList *list = getlist(L, ref, listname);
1806 lua_pushboolean(L, list->containsItem(item));
1808 lua_pushboolean(L, false);
1813 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1814 // Returns the items that were actually removed
1815 static int l_remove_item(lua_State *L)
1817 InvRef *ref = checkobject(L, 1);
1818 const char *listname = luaL_checkstring(L, 2);
1819 ItemStack item = read_item(L, 3);
1820 InventoryList *list = getlist(L, ref, listname);
1822 ItemStack removed = list->removeItem(item);
1823 if(!removed.empty())
1824 reportInventoryChange(L, ref);
1825 LuaItemStack::create(L, removed);
1827 LuaItemStack::create(L, ItemStack());
1833 InvRef(const InventoryLocation &loc):
1842 // Creates an InvRef and leaves it on top of stack
1843 // Not callable from Lua; all references are created on the C side.
1844 static void create(lua_State *L, const InventoryLocation &loc)
1846 InvRef *o = new InvRef(loc);
1847 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1848 luaL_getmetatable(L, className);
1849 lua_setmetatable(L, -2);
1851 static void createPlayer(lua_State *L, Player *player)
1853 InventoryLocation loc;
1854 loc.setPlayer(player->getName());
1857 static void createNodeMeta(lua_State *L, v3s16 p)
1859 InventoryLocation loc;
1864 static void Register(lua_State *L)
1867 int methodtable = lua_gettop(L);
1868 luaL_newmetatable(L, className);
1869 int metatable = lua_gettop(L);
1871 lua_pushliteral(L, "__metatable");
1872 lua_pushvalue(L, methodtable);
1873 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1875 lua_pushliteral(L, "__index");
1876 lua_pushvalue(L, methodtable);
1877 lua_settable(L, metatable);
1879 lua_pushliteral(L, "__gc");
1880 lua_pushcfunction(L, gc_object);
1881 lua_settable(L, metatable);
1883 lua_pop(L, 1); // drop metatable
1885 luaL_openlib(L, 0, methods, 0); // fill methodtable
1886 lua_pop(L, 1); // drop methodtable
1888 // Cannot be created from Lua
1889 //lua_register(L, className, create_object);
1892 const char InvRef::className[] = "InvRef";
1893 const luaL_reg InvRef::methods[] = {
1894 method(InvRef, get_size),
1895 method(InvRef, set_size),
1896 method(InvRef, get_stack),
1897 method(InvRef, set_stack),
1898 method(InvRef, get_list),
1899 method(InvRef, set_list),
1900 method(InvRef, add_item),
1901 method(InvRef, room_for_item),
1902 method(InvRef, contains_item),
1903 method(InvRef, remove_item),
1915 ServerEnvironment *m_env;
1917 static const char className[];
1918 static const luaL_reg methods[];
1920 static NodeMetaRef *checkobject(lua_State *L, int narg)
1922 luaL_checktype(L, narg, LUA_TUSERDATA);
1923 void *ud = luaL_checkudata(L, narg, className);
1924 if(!ud) luaL_typerror(L, narg, className);
1925 return *(NodeMetaRef**)ud; // unbox pointer
1928 static NodeMetadata* getmeta(NodeMetaRef *ref)
1930 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1934 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1936 NodeMetadata *meta = getmeta(ref);
1939 if(meta->typeId() != NODEMETA_GENERIC)
1941 return (IGenericNodeMetadata*)meta;
1944 static void reportMetadataChange(NodeMetaRef *ref)
1946 // Inform other things that the metadata has changed
1947 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1949 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1951 ref->m_env->getMap().dispatchEvent(&event);
1952 // Set the block to be saved
1953 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1955 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1956 "NodeMetaRef::reportMetadataChange");
1959 // Exported functions
1961 // garbage collector
1962 static int gc_object(lua_State *L) {
1963 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1969 static int l_get_type(lua_State *L)
1971 NodeMetaRef *ref = checkobject(L, 1);
1972 NodeMetadata *meta = getmeta(ref);
1978 lua_pushstring(L, meta->typeName());
1982 // allows_text_input(self)
1983 static int l_allows_text_input(lua_State *L)
1985 NodeMetaRef *ref = checkobject(L, 1);
1986 NodeMetadata *meta = getmeta(ref);
1987 if(meta == NULL) return 0;
1989 lua_pushboolean(L, meta->allowsTextInput());
1993 // set_text(self, text)
1994 static int l_set_text(lua_State *L)
1996 NodeMetaRef *ref = checkobject(L, 1);
1997 NodeMetadata *meta = getmeta(ref);
1998 if(meta == NULL) return 0;
2000 std::string text = luaL_checkstring(L, 2);
2001 meta->setText(text);
2002 reportMetadataChange(ref);
2007 static int l_get_text(lua_State *L)
2009 NodeMetaRef *ref = checkobject(L, 1);
2010 NodeMetadata *meta = getmeta(ref);
2011 if(meta == NULL) return 0;
2013 std::string text = meta->getText();
2014 lua_pushstring(L, text.c_str());
2019 static int l_get_owner(lua_State *L)
2021 NodeMetaRef *ref = checkobject(L, 1);
2022 NodeMetadata *meta = getmeta(ref);
2023 if(meta == NULL) return 0;
2025 std::string owner = meta->getOwner();
2026 lua_pushstring(L, owner.c_str());
2030 // set_owner(self, string)
2031 static int l_set_owner(lua_State *L)
2033 NodeMetaRef *ref = checkobject(L, 1);
2034 NodeMetadata *meta = getmeta(ref);
2035 if(meta == NULL) return 0;
2037 std::string owner = luaL_checkstring(L, 2);
2038 meta->setOwner(owner);
2039 reportMetadataChange(ref);
2043 // get_allow_removal(self)
2044 static int l_get_allow_removal(lua_State *L)
2046 NodeMetaRef *ref = checkobject(L, 1);
2047 NodeMetadata *meta = getmeta(ref);
2049 lua_pushboolean(L, true);
2053 lua_pushboolean(L, !meta->nodeRemovalDisabled());
2057 /* IGenericNodeMetadata interface */
2059 // set_infotext(self, text)
2060 static int l_set_infotext(lua_State *L)
2062 NodeMetaRef *ref = checkobject(L, 1);
2063 NodeMetadata *meta = getmeta(ref);
2064 if(meta == NULL) return 0;
2066 std::string text = luaL_checkstring(L, 2);
2067 meta->setInfoText(text);
2068 reportMetadataChange(ref);
2072 // get_inventory(self)
2073 static int l_get_inventory(lua_State *L)
2075 NodeMetaRef *ref = checkobject(L, 1);
2076 NodeMetadata *meta = getmeta(ref);
2077 if(meta == NULL) return 0;
2079 InvRef::createNodeMeta(L, ref->m_p);
2083 // set_inventory_draw_spec(self, text)
2084 static int l_set_inventory_draw_spec(lua_State *L)
2086 NodeMetaRef *ref = checkobject(L, 1);
2087 NodeMetadata *meta = getmeta(ref);
2088 if(meta == NULL) return 0;
2090 std::string text = luaL_checkstring(L, 2);
2091 meta->setInventoryDrawSpec(text);
2092 reportMetadataChange(ref);
2096 // set_allow_text_input(self, text)
2097 static int l_set_allow_text_input(lua_State *L)
2099 NodeMetaRef *ref = checkobject(L, 1);
2100 NodeMetadata *meta = getmeta(ref);
2101 if(meta == NULL) return 0;
2103 bool b = lua_toboolean(L, 2);
2104 meta->setAllowTextInput(b);
2105 reportMetadataChange(ref);
2109 // set_allow_removal(self, text)
2110 static int l_set_allow_removal(lua_State *L)
2112 NodeMetaRef *ref = checkobject(L, 1);
2113 NodeMetadata *meta = getmeta(ref);
2114 if(meta == NULL) return 0;
2116 bool b = lua_toboolean(L, 2);
2117 meta->setRemovalDisabled(!b);
2118 reportMetadataChange(ref);
2122 // set_enforce_owner(self, text)
2123 static int l_set_enforce_owner(lua_State *L)
2125 NodeMetaRef *ref = checkobject(L, 1);
2126 NodeMetadata *meta = getmeta(ref);
2127 if(meta == NULL) return 0;
2129 bool b = lua_toboolean(L, 2);
2130 meta->setEnforceOwner(b);
2131 reportMetadataChange(ref);
2135 // is_inventory_modified(self)
2136 static int l_is_inventory_modified(lua_State *L)
2138 NodeMetaRef *ref = checkobject(L, 1);
2139 NodeMetadata *meta = getmeta(ref);
2140 if(meta == NULL) return 0;
2142 lua_pushboolean(L, meta->isInventoryModified());
2146 // reset_inventory_modified(self)
2147 static int l_reset_inventory_modified(lua_State *L)
2149 NodeMetaRef *ref = checkobject(L, 1);
2150 NodeMetadata *meta = getmeta(ref);
2151 if(meta == NULL) return 0;
2153 meta->resetInventoryModified();
2154 reportMetadataChange(ref);
2158 // is_text_modified(self)
2159 static int l_is_text_modified(lua_State *L)
2161 NodeMetaRef *ref = checkobject(L, 1);
2162 NodeMetadata *meta = getmeta(ref);
2163 if(meta == NULL) return 0;
2165 lua_pushboolean(L, meta->isTextModified());
2169 // reset_text_modified(self)
2170 static int l_reset_text_modified(lua_State *L)
2172 NodeMetaRef *ref = checkobject(L, 1);
2173 NodeMetadata *meta = getmeta(ref);
2174 if(meta == NULL) return 0;
2176 meta->resetTextModified();
2177 reportMetadataChange(ref);
2181 // set_string(self, name, var)
2182 static int l_set_string(lua_State *L)
2184 NodeMetaRef *ref = checkobject(L, 1);
2185 NodeMetadata *meta = getmeta(ref);
2186 if(meta == NULL) return 0;
2188 std::string name = luaL_checkstring(L, 2);
2190 const char *s = lua_tolstring(L, 3, &len);
2191 std::string str(s, len);
2192 meta->setString(name, str);
2193 reportMetadataChange(ref);
2197 // get_string(self, name)
2198 static int l_get_string(lua_State *L)
2200 NodeMetaRef *ref = checkobject(L, 1);
2201 NodeMetadata *meta = getmeta(ref);
2202 if(meta == NULL) return 0;
2204 std::string name = luaL_checkstring(L, 2);
2205 std::string str = meta->getString(name);
2206 lua_pushlstring(L, str.c_str(), str.size());
2211 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2221 // Creates an NodeMetaRef and leaves it on top of stack
2222 // Not callable from Lua; all references are created on the C side.
2223 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2225 NodeMetaRef *o = new NodeMetaRef(p, env);
2226 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2227 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2228 luaL_getmetatable(L, className);
2229 lua_setmetatable(L, -2);
2232 static void Register(lua_State *L)
2235 int methodtable = lua_gettop(L);
2236 luaL_newmetatable(L, className);
2237 int metatable = lua_gettop(L);
2239 lua_pushliteral(L, "__metatable");
2240 lua_pushvalue(L, methodtable);
2241 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2243 lua_pushliteral(L, "__index");
2244 lua_pushvalue(L, methodtable);
2245 lua_settable(L, metatable);
2247 lua_pushliteral(L, "__gc");
2248 lua_pushcfunction(L, gc_object);
2249 lua_settable(L, metatable);
2251 lua_pop(L, 1); // drop metatable
2253 luaL_openlib(L, 0, methods, 0); // fill methodtable
2254 lua_pop(L, 1); // drop methodtable
2256 // Cannot be created from Lua
2257 //lua_register(L, className, create_object);
2260 const char NodeMetaRef::className[] = "NodeMetaRef";
2261 const luaL_reg NodeMetaRef::methods[] = {
2262 method(NodeMetaRef, get_type),
2263 method(NodeMetaRef, allows_text_input),
2264 method(NodeMetaRef, set_text),
2265 method(NodeMetaRef, get_text),
2266 method(NodeMetaRef, get_owner),
2267 method(NodeMetaRef, set_owner),
2268 method(NodeMetaRef, get_allow_removal),
2269 method(NodeMetaRef, set_infotext),
2270 method(NodeMetaRef, get_inventory),
2271 method(NodeMetaRef, set_inventory_draw_spec),
2272 method(NodeMetaRef, set_allow_text_input),
2273 method(NodeMetaRef, set_allow_removal),
2274 method(NodeMetaRef, set_enforce_owner),
2275 method(NodeMetaRef, is_inventory_modified),
2276 method(NodeMetaRef, reset_inventory_modified),
2277 method(NodeMetaRef, is_text_modified),
2278 method(NodeMetaRef, reset_text_modified),
2279 method(NodeMetaRef, set_string),
2280 method(NodeMetaRef, get_string),
2291 ServerActiveObject *m_object;
2293 static const char className[];
2294 static const luaL_reg methods[];
2296 static ObjectRef *checkobject(lua_State *L, int narg)
2298 luaL_checktype(L, narg, LUA_TUSERDATA);
2299 void *ud = luaL_checkudata(L, narg, className);
2300 if(!ud) luaL_typerror(L, narg, className);
2301 return *(ObjectRef**)ud; // unbox pointer
2304 static ServerActiveObject* getobject(ObjectRef *ref)
2306 ServerActiveObject *co = ref->m_object;
2310 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2312 ServerActiveObject *obj = getobject(ref);
2315 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2317 return (LuaEntitySAO*)obj;
2320 static PlayerSAO* getplayersao(ObjectRef *ref)
2322 ServerActiveObject *obj = getobject(ref);
2325 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2327 return (PlayerSAO*)obj;
2330 static Player* getplayer(ObjectRef *ref)
2332 PlayerSAO *playersao = getplayersao(ref);
2333 if(playersao == NULL)
2335 return playersao->getPlayer();
2338 // Exported functions
2340 // garbage collector
2341 static int gc_object(lua_State *L) {
2342 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2343 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2349 static int l_remove(lua_State *L)
2351 ObjectRef *ref = checkobject(L, 1);
2352 ServerActiveObject *co = getobject(ref);
2353 if(co == NULL) return 0;
2354 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2355 co->m_removed = true;
2360 // returns: {x=num, y=num, z=num}
2361 static int l_getpos(lua_State *L)
2363 ObjectRef *ref = checkobject(L, 1);
2364 ServerActiveObject *co = getobject(ref);
2365 if(co == NULL) return 0;
2366 v3f pos = co->getBasePosition() / BS;
2368 lua_pushnumber(L, pos.X);
2369 lua_setfield(L, -2, "x");
2370 lua_pushnumber(L, pos.Y);
2371 lua_setfield(L, -2, "y");
2372 lua_pushnumber(L, pos.Z);
2373 lua_setfield(L, -2, "z");
2377 // setpos(self, pos)
2378 static int l_setpos(lua_State *L)
2380 ObjectRef *ref = checkobject(L, 1);
2381 //LuaEntitySAO *co = getluaobject(ref);
2382 ServerActiveObject *co = getobject(ref);
2383 if(co == NULL) return 0;
2385 v3f pos = checkFloatPos(L, 2);
2391 // moveto(self, pos, continuous=false)
2392 static int l_moveto(lua_State *L)
2394 ObjectRef *ref = checkobject(L, 1);
2395 //LuaEntitySAO *co = getluaobject(ref);
2396 ServerActiveObject *co = getobject(ref);
2397 if(co == NULL) return 0;
2399 v3f pos = checkFloatPos(L, 2);
2401 bool continuous = lua_toboolean(L, 3);
2403 co->moveTo(pos, continuous);
2407 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2408 static int l_punch(lua_State *L)
2410 ObjectRef *ref = checkobject(L, 1);
2411 ObjectRef *puncher_ref = checkobject(L, 2);
2412 ServerActiveObject *co = getobject(ref);
2413 ServerActiveObject *puncher = getobject(puncher_ref);
2414 if(co == NULL) return 0;
2415 if(puncher == NULL) return 0;
2416 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2417 v3f dir = read_v3f(L, 4);
2418 float time_from_last_punch = 1000000;
2419 if(lua_isnumber(L, 5))
2420 time_from_last_punch = lua_tonumber(L, 5);
2422 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2426 // right_click(self, clicker); clicker = an another ObjectRef
2427 static int l_right_click(lua_State *L)
2429 ObjectRef *ref = checkobject(L, 1);
2430 ObjectRef *ref2 = checkobject(L, 2);
2431 ServerActiveObject *co = getobject(ref);
2432 ServerActiveObject *co2 = getobject(ref2);
2433 if(co == NULL) return 0;
2434 if(co2 == NULL) return 0;
2436 co->rightClick(co2);
2441 // hp = number of hitpoints (2 * number of hearts)
2443 static int l_set_hp(lua_State *L)
2445 ObjectRef *ref = checkobject(L, 1);
2446 luaL_checknumber(L, 2);
2447 ServerActiveObject *co = getobject(ref);
2448 if(co == NULL) return 0;
2449 int hp = lua_tonumber(L, 2);
2450 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2451 <<" hp="<<hp<<std::endl;*/
2459 // returns: number of hitpoints (2 * number of hearts)
2460 // 0 if not applicable to this type of object
2461 static int l_get_hp(lua_State *L)
2463 ObjectRef *ref = checkobject(L, 1);
2464 ServerActiveObject *co = getobject(ref);
2465 if(co == NULL) return 0;
2466 int hp = co->getHP();
2467 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2468 <<" hp="<<hp<<std::endl;*/
2470 lua_pushnumber(L, hp);
2474 // get_inventory(self)
2475 static int l_get_inventory(lua_State *L)
2477 ObjectRef *ref = checkobject(L, 1);
2478 ServerActiveObject *co = getobject(ref);
2479 if(co == NULL) return 0;
2481 InventoryLocation loc = co->getInventoryLocation();
2482 if(get_server(L)->getInventory(loc) != NULL)
2483 InvRef::create(L, loc);
2489 // get_wield_list(self)
2490 static int l_get_wield_list(lua_State *L)
2492 ObjectRef *ref = checkobject(L, 1);
2493 ServerActiveObject *co = getobject(ref);
2494 if(co == NULL) return 0;
2496 lua_pushstring(L, co->getWieldList().c_str());
2500 // get_wield_index(self)
2501 static int l_get_wield_index(lua_State *L)
2503 ObjectRef *ref = checkobject(L, 1);
2504 ServerActiveObject *co = getobject(ref);
2505 if(co == NULL) return 0;
2507 lua_pushinteger(L, co->getWieldIndex() + 1);
2511 // get_wielded_item(self)
2512 static int l_get_wielded_item(lua_State *L)
2514 ObjectRef *ref = checkobject(L, 1);
2515 ServerActiveObject *co = getobject(ref);
2516 if(co == NULL) return 0;
2518 LuaItemStack::create(L, co->getWieldedItem());
2522 // set_wielded_item(self, itemstack or itemstring or table or nil)
2523 static int l_set_wielded_item(lua_State *L)
2525 ObjectRef *ref = checkobject(L, 1);
2526 ServerActiveObject *co = getobject(ref);
2527 if(co == NULL) return 0;
2529 ItemStack item = read_item(L, 2);
2530 bool success = co->setWieldedItem(item);
2531 lua_pushboolean(L, success);
2535 // set_armor_groups(self, groups)
2536 static int l_set_armor_groups(lua_State *L)
2538 ObjectRef *ref = checkobject(L, 1);
2539 ServerActiveObject *co = getobject(ref);
2540 if(co == NULL) return 0;
2542 ItemGroupList groups;
2543 read_groups(L, 2, groups);
2544 co->setArmorGroups(groups);
2548 // set_properties(self, properties)
2549 static int l_set_properties(lua_State *L)
2551 ObjectRef *ref = checkobject(L, 1);
2552 ServerActiveObject *co = getobject(ref);
2553 if(co == NULL) return 0;
2554 ObjectProperties *prop = co->accessObjectProperties();
2557 read_object_properties(L, 2, prop);
2558 co->notifyObjectPropertiesModified();
2562 /* LuaEntitySAO-only */
2564 // setvelocity(self, {x=num, y=num, z=num})
2565 static int l_setvelocity(lua_State *L)
2567 ObjectRef *ref = checkobject(L, 1);
2568 LuaEntitySAO *co = getluaobject(ref);
2569 if(co == NULL) return 0;
2570 v3f pos = checkFloatPos(L, 2);
2572 co->setVelocity(pos);
2576 // getvelocity(self)
2577 static int l_getvelocity(lua_State *L)
2579 ObjectRef *ref = checkobject(L, 1);
2580 LuaEntitySAO *co = getluaobject(ref);
2581 if(co == NULL) return 0;
2583 v3f v = co->getVelocity();
2588 // setacceleration(self, {x=num, y=num, z=num})
2589 static int l_setacceleration(lua_State *L)
2591 ObjectRef *ref = checkobject(L, 1);
2592 LuaEntitySAO *co = getluaobject(ref);
2593 if(co == NULL) return 0;
2595 v3f pos = checkFloatPos(L, 2);
2597 co->setAcceleration(pos);
2601 // getacceleration(self)
2602 static int l_getacceleration(lua_State *L)
2604 ObjectRef *ref = checkobject(L, 1);
2605 LuaEntitySAO *co = getluaobject(ref);
2606 if(co == NULL) return 0;
2608 v3f v = co->getAcceleration();
2613 // setyaw(self, radians)
2614 static int l_setyaw(lua_State *L)
2616 ObjectRef *ref = checkobject(L, 1);
2617 LuaEntitySAO *co = getluaobject(ref);
2618 if(co == NULL) return 0;
2619 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2626 static int l_getyaw(lua_State *L)
2628 ObjectRef *ref = checkobject(L, 1);
2629 LuaEntitySAO *co = getluaobject(ref);
2630 if(co == NULL) return 0;
2632 float yaw = co->getYaw() * core::DEGTORAD;
2633 lua_pushnumber(L, yaw);
2637 // settexturemod(self, mod)
2638 static int l_settexturemod(lua_State *L)
2640 ObjectRef *ref = checkobject(L, 1);
2641 LuaEntitySAO *co = getluaobject(ref);
2642 if(co == NULL) return 0;
2644 std::string mod = luaL_checkstring(L, 2);
2645 co->setTextureMod(mod);
2649 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2650 // select_horiz_by_yawpitch=false)
2651 static int l_setsprite(lua_State *L)
2653 ObjectRef *ref = checkobject(L, 1);
2654 LuaEntitySAO *co = getluaobject(ref);
2655 if(co == NULL) return 0;
2658 if(!lua_isnil(L, 2))
2659 p = read_v2s16(L, 2);
2661 if(!lua_isnil(L, 3))
2662 num_frames = lua_tonumber(L, 3);
2663 float framelength = 0.2;
2664 if(!lua_isnil(L, 4))
2665 framelength = lua_tonumber(L, 4);
2666 bool select_horiz_by_yawpitch = false;
2667 if(!lua_isnil(L, 5))
2668 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2669 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2674 // get_entity_name(self)
2675 static int l_get_entity_name(lua_State *L)
2677 ObjectRef *ref = checkobject(L, 1);
2678 LuaEntitySAO *co = getluaobject(ref);
2679 if(co == NULL) return 0;
2681 std::string name = co->getName();
2682 lua_pushstring(L, name.c_str());
2686 // get_luaentity(self)
2687 static int l_get_luaentity(lua_State *L)
2689 ObjectRef *ref = checkobject(L, 1);
2690 LuaEntitySAO *co = getluaobject(ref);
2691 if(co == NULL) return 0;
2693 luaentity_get(L, co->getId());
2699 // get_player_name(self)
2700 static int l_get_player_name(lua_State *L)
2702 ObjectRef *ref = checkobject(L, 1);
2703 Player *player = getplayer(ref);
2709 lua_pushstring(L, player->getName());
2713 // get_look_dir(self)
2714 static int l_get_look_dir(lua_State *L)
2716 ObjectRef *ref = checkobject(L, 1);
2717 Player *player = getplayer(ref);
2718 if(player == NULL) return 0;
2720 float pitch = player->getRadPitch();
2721 float yaw = player->getRadYaw();
2722 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2727 // get_look_pitch(self)
2728 static int l_get_look_pitch(lua_State *L)
2730 ObjectRef *ref = checkobject(L, 1);
2731 Player *player = getplayer(ref);
2732 if(player == NULL) return 0;
2734 lua_pushnumber(L, player->getRadPitch());
2738 // get_look_yaw(self)
2739 static int l_get_look_yaw(lua_State *L)
2741 ObjectRef *ref = checkobject(L, 1);
2742 Player *player = getplayer(ref);
2743 if(player == NULL) return 0;
2745 lua_pushnumber(L, player->getRadYaw());
2750 ObjectRef(ServerActiveObject *object):
2753 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2759 infostream<<"ObjectRef destructing for id="
2760 <<m_object->getId()<<std::endl;
2762 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2765 // Creates an ObjectRef and leaves it on top of stack
2766 // Not callable from Lua; all references are created on the C side.
2767 static void create(lua_State *L, ServerActiveObject *object)
2769 ObjectRef *o = new ObjectRef(object);
2770 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2771 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2772 luaL_getmetatable(L, className);
2773 lua_setmetatable(L, -2);
2776 static void set_null(lua_State *L)
2778 ObjectRef *o = checkobject(L, -1);
2782 static void Register(lua_State *L)
2785 int methodtable = lua_gettop(L);
2786 luaL_newmetatable(L, className);
2787 int metatable = lua_gettop(L);
2789 lua_pushliteral(L, "__metatable");
2790 lua_pushvalue(L, methodtable);
2791 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2793 lua_pushliteral(L, "__index");
2794 lua_pushvalue(L, methodtable);
2795 lua_settable(L, metatable);
2797 lua_pushliteral(L, "__gc");
2798 lua_pushcfunction(L, gc_object);
2799 lua_settable(L, metatable);
2801 lua_pop(L, 1); // drop metatable
2803 luaL_openlib(L, 0, methods, 0); // fill methodtable
2804 lua_pop(L, 1); // drop methodtable
2806 // Cannot be created from Lua
2807 //lua_register(L, className, create_object);
2810 const char ObjectRef::className[] = "ObjectRef";
2811 const luaL_reg ObjectRef::methods[] = {
2812 // ServerActiveObject
2813 method(ObjectRef, remove),
2814 method(ObjectRef, getpos),
2815 method(ObjectRef, setpos),
2816 method(ObjectRef, moveto),
2817 method(ObjectRef, punch),
2818 method(ObjectRef, right_click),
2819 method(ObjectRef, set_hp),
2820 method(ObjectRef, get_hp),
2821 method(ObjectRef, get_inventory),
2822 method(ObjectRef, get_wield_list),
2823 method(ObjectRef, get_wield_index),
2824 method(ObjectRef, get_wielded_item),
2825 method(ObjectRef, set_wielded_item),
2826 method(ObjectRef, set_armor_groups),
2827 method(ObjectRef, set_properties),
2828 // LuaEntitySAO-only
2829 method(ObjectRef, setvelocity),
2830 method(ObjectRef, getvelocity),
2831 method(ObjectRef, setacceleration),
2832 method(ObjectRef, getacceleration),
2833 method(ObjectRef, setyaw),
2834 method(ObjectRef, getyaw),
2835 method(ObjectRef, settexturemod),
2836 method(ObjectRef, setsprite),
2837 method(ObjectRef, get_entity_name),
2838 method(ObjectRef, get_luaentity),
2840 method(ObjectRef, get_player_name),
2841 method(ObjectRef, get_look_dir),
2842 method(ObjectRef, get_look_pitch),
2843 method(ObjectRef, get_look_yaw),
2847 // Creates a new anonymous reference if id=0
2848 static void objectref_get_or_create(lua_State *L,
2849 ServerActiveObject *cobj)
2851 if(cobj->getId() == 0){
2852 ObjectRef::create(L, cobj);
2854 objectref_get(L, cobj->getId());
2865 ServerEnvironment *m_env;
2867 static const char className[];
2868 static const luaL_reg methods[];
2870 static EnvRef *checkobject(lua_State *L, int narg)
2872 luaL_checktype(L, narg, LUA_TUSERDATA);
2873 void *ud = luaL_checkudata(L, narg, className);
2874 if(!ud) luaL_typerror(L, narg, className);
2875 return *(EnvRef**)ud; // unbox pointer
2878 // Exported functions
2880 // EnvRef:set_node(pos, node)
2881 // pos = {x=num, y=num, z=num}
2882 static int l_set_node(lua_State *L)
2884 //infostream<<"EnvRef::l_set_node()"<<std::endl;
2885 EnvRef *o = checkobject(L, 1);
2886 ServerEnvironment *env = o->m_env;
2887 if(env == NULL) return 0;
2889 v3s16 pos = read_v3s16(L, 2);
2891 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2893 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2894 lua_pushboolean(L, succeeded);
2898 static int l_add_node(lua_State *L)
2900 return l_set_node(L);
2903 // EnvRef:remove_node(pos)
2904 // pos = {x=num, y=num, z=num}
2905 static int l_remove_node(lua_State *L)
2907 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2908 EnvRef *o = checkobject(L, 1);
2909 ServerEnvironment *env = o->m_env;
2910 if(env == NULL) return 0;
2912 v3s16 pos = read_v3s16(L, 2);
2914 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2915 lua_pushboolean(L, succeeded);
2919 // EnvRef:get_node(pos)
2920 // pos = {x=num, y=num, z=num}
2921 static int l_get_node(lua_State *L)
2923 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2924 EnvRef *o = checkobject(L, 1);
2925 ServerEnvironment *env = o->m_env;
2926 if(env == NULL) return 0;
2928 v3s16 pos = read_v3s16(L, 2);
2930 MapNode n = env->getMap().getNodeNoEx(pos);
2932 pushnode(L, n, env->getGameDef()->ndef());
2936 // EnvRef:get_node_or_nil(pos)
2937 // pos = {x=num, y=num, z=num}
2938 static int l_get_node_or_nil(lua_State *L)
2940 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2941 EnvRef *o = checkobject(L, 1);
2942 ServerEnvironment *env = o->m_env;
2943 if(env == NULL) return 0;
2945 v3s16 pos = read_v3s16(L, 2);
2948 MapNode n = env->getMap().getNode(pos);
2950 pushnode(L, n, env->getGameDef()->ndef());
2952 } catch(InvalidPositionException &e)
2959 // EnvRef:get_node_light(pos, timeofday)
2960 // pos = {x=num, y=num, z=num}
2961 // timeofday: nil = current time, 0 = night, 0.5 = day
2962 static int l_get_node_light(lua_State *L)
2964 EnvRef *o = checkobject(L, 1);
2965 ServerEnvironment *env = o->m_env;
2966 if(env == NULL) return 0;
2968 v3s16 pos = read_v3s16(L, 2);
2969 u32 time_of_day = env->getTimeOfDay();
2970 if(lua_isnumber(L, 3))
2971 time_of_day = 24000.0 * lua_tonumber(L, 3);
2972 time_of_day %= 24000;
2973 u32 dnr = time_to_daynight_ratio(time_of_day);
2974 MapNode n = env->getMap().getNodeNoEx(pos);
2976 MapNode n = env->getMap().getNode(pos);
2977 INodeDefManager *ndef = env->getGameDef()->ndef();
2978 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
2980 } catch(InvalidPositionException &e)
2987 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
2988 // pos = {x=num, y=num, z=num}
2989 static int l_add_entity(lua_State *L)
2991 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
2992 EnvRef *o = checkobject(L, 1);
2993 ServerEnvironment *env = o->m_env;
2994 if(env == NULL) return 0;
2996 v3f pos = checkFloatPos(L, 2);
2998 const char *name = luaL_checkstring(L, 3);
3000 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3001 int objectid = env->addActiveObject(obj);
3002 // If failed to add, return nothing (reads as nil)
3006 objectref_get_or_create(L, obj);
3010 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3011 // pos = {x=num, y=num, z=num}
3012 static int l_add_item(lua_State *L)
3014 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3015 EnvRef *o = checkobject(L, 1);
3016 ServerEnvironment *env = o->m_env;
3017 if(env == NULL) return 0;
3019 v3f pos = checkFloatPos(L, 2);
3021 ItemStack item = read_item(L, 3);
3022 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3025 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3026 int objectid = env->addActiveObject(obj);
3027 // If failed to add, return nothing (reads as nil)
3031 objectref_get_or_create(L, obj);
3035 // EnvRef:add_rat(pos)
3036 // pos = {x=num, y=num, z=num}
3037 static int l_add_rat(lua_State *L)
3039 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3040 <<" Doing nothing."<<std::endl;
3044 // EnvRef:add_firefly(pos)
3045 // pos = {x=num, y=num, z=num}
3046 static int l_add_firefly(lua_State *L)
3048 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3049 <<" Doing nothing."<<std::endl;
3053 // EnvRef:get_meta(pos)
3054 static int l_get_meta(lua_State *L)
3056 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3057 EnvRef *o = checkobject(L, 1);
3058 ServerEnvironment *env = o->m_env;
3059 if(env == NULL) return 0;
3061 v3s16 p = read_v3s16(L, 2);
3062 NodeMetaRef::create(L, p, env);
3066 // EnvRef:get_player_by_name(name)
3067 static int l_get_player_by_name(lua_State *L)
3069 EnvRef *o = checkobject(L, 1);
3070 ServerEnvironment *env = o->m_env;
3071 if(env == NULL) return 0;
3073 const char *name = luaL_checkstring(L, 2);
3074 Player *player = env->getPlayer(name);
3079 PlayerSAO *sao = player->getPlayerSAO();
3084 // Put player on stack
3085 objectref_get_or_create(L, sao);
3089 // EnvRef:get_objects_inside_radius(pos, radius)
3090 static int l_get_objects_inside_radius(lua_State *L)
3092 // Get the table insert function
3093 lua_getglobal(L, "table");
3094 lua_getfield(L, -1, "insert");
3095 int table_insert = lua_gettop(L);
3097 EnvRef *o = checkobject(L, 1);
3098 ServerEnvironment *env = o->m_env;
3099 if(env == NULL) return 0;
3101 v3f pos = checkFloatPos(L, 2);
3102 float radius = luaL_checknumber(L, 3) * BS;
3103 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3105 int table = lua_gettop(L);
3106 for(std::set<u16>::const_iterator
3107 i = ids.begin(); i != ids.end(); i++){
3108 ServerActiveObject *obj = env->getActiveObject(*i);
3109 // Insert object reference into table
3110 lua_pushvalue(L, table_insert);
3111 lua_pushvalue(L, table);
3112 objectref_get_or_create(L, obj);
3113 if(lua_pcall(L, 2, 0, 0))
3114 script_error(L, "error: %s", lua_tostring(L, -1));
3119 // EnvRef:set_timeofday(val)
3121 static int l_set_timeofday(lua_State *L)
3123 EnvRef *o = checkobject(L, 1);
3124 ServerEnvironment *env = o->m_env;
3125 if(env == NULL) return 0;
3127 float timeofday_f = luaL_checknumber(L, 2);
3128 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3129 int timeofday_mh = (int)(timeofday_f * 24000.0);
3130 // This should be set directly in the environment but currently
3131 // such changes aren't immediately sent to the clients, so call
3132 // the server instead.
3133 //env->setTimeOfDay(timeofday_mh);
3134 get_server(L)->setTimeOfDay(timeofday_mh);
3138 // EnvRef:get_timeofday() -> 0...1
3139 static int l_get_timeofday(lua_State *L)
3141 EnvRef *o = checkobject(L, 1);
3142 ServerEnvironment *env = o->m_env;
3143 if(env == NULL) return 0;
3145 int timeofday_mh = env->getTimeOfDay();
3146 float timeofday_f = (float)timeofday_mh / 24000.0;
3147 lua_pushnumber(L, timeofday_f);
3151 static int gc_object(lua_State *L) {
3152 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3158 EnvRef(ServerEnvironment *env):
3161 //infostream<<"EnvRef created"<<std::endl;
3166 //infostream<<"EnvRef destructing"<<std::endl;
3169 // Creates an EnvRef and leaves it on top of stack
3170 // Not callable from Lua; all references are created on the C side.
3171 static void create(lua_State *L, ServerEnvironment *env)
3173 EnvRef *o = new EnvRef(env);
3174 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3175 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3176 luaL_getmetatable(L, className);
3177 lua_setmetatable(L, -2);
3180 static void set_null(lua_State *L)
3182 EnvRef *o = checkobject(L, -1);
3186 static void Register(lua_State *L)
3189 int methodtable = lua_gettop(L);
3190 luaL_newmetatable(L, className);
3191 int metatable = lua_gettop(L);
3193 lua_pushliteral(L, "__metatable");
3194 lua_pushvalue(L, methodtable);
3195 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3197 lua_pushliteral(L, "__index");
3198 lua_pushvalue(L, methodtable);
3199 lua_settable(L, metatable);
3201 lua_pushliteral(L, "__gc");
3202 lua_pushcfunction(L, gc_object);
3203 lua_settable(L, metatable);
3205 lua_pop(L, 1); // drop metatable
3207 luaL_openlib(L, 0, methods, 0); // fill methodtable
3208 lua_pop(L, 1); // drop methodtable
3210 // Cannot be created from Lua
3211 //lua_register(L, className, create_object);
3214 const char EnvRef::className[] = "EnvRef";
3215 const luaL_reg EnvRef::methods[] = {
3216 method(EnvRef, set_node),
3217 method(EnvRef, add_node),
3218 method(EnvRef, remove_node),
3219 method(EnvRef, get_node),
3220 method(EnvRef, get_node_or_nil),
3221 method(EnvRef, get_node_light),
3222 method(EnvRef, add_entity),
3223 method(EnvRef, add_item),
3224 method(EnvRef, add_rat),
3225 method(EnvRef, add_firefly),
3226 method(EnvRef, get_meta),
3227 method(EnvRef, get_player_by_name),
3228 method(EnvRef, get_objects_inside_radius),
3229 method(EnvRef, set_timeofday),
3230 method(EnvRef, get_timeofday),
3238 class LuaPseudoRandom
3241 PseudoRandom m_pseudo;
3243 static const char className[];
3244 static const luaL_reg methods[];
3246 // Exported functions
3248 // garbage collector
3249 static int gc_object(lua_State *L)
3251 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3256 // next(self, min=0, max=32767) -> get next value
3257 static int l_next(lua_State *L)
3259 LuaPseudoRandom *o = checkobject(L, 1);
3262 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3263 if(!lua_isnil(L, 2))
3264 min = luaL_checkinteger(L, 2);
3265 if(!lua_isnil(L, 3))
3266 max = luaL_checkinteger(L, 3);
3267 if(max - min != 32767 && max - min > 32767/5)
3268 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.");
3269 PseudoRandom &pseudo = o->m_pseudo;
3270 int val = pseudo.next();
3271 val = (val % (max-min+1)) + min;
3272 lua_pushinteger(L, val);
3277 LuaPseudoRandom(int seed):
3286 const PseudoRandom& getItem() const
3290 PseudoRandom& getItem()
3295 // LuaPseudoRandom(seed)
3296 // Creates an LuaPseudoRandom and leaves it on top of stack
3297 static int create_object(lua_State *L)
3299 int seed = luaL_checknumber(L, 1);
3300 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3301 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3302 luaL_getmetatable(L, className);
3303 lua_setmetatable(L, -2);
3307 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3309 luaL_checktype(L, narg, LUA_TUSERDATA);
3310 void *ud = luaL_checkudata(L, narg, className);
3311 if(!ud) luaL_typerror(L, narg, className);
3312 return *(LuaPseudoRandom**)ud; // unbox pointer
3315 static void Register(lua_State *L)
3318 int methodtable = lua_gettop(L);
3319 luaL_newmetatable(L, className);
3320 int metatable = lua_gettop(L);
3322 lua_pushliteral(L, "__metatable");
3323 lua_pushvalue(L, methodtable);
3324 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3326 lua_pushliteral(L, "__index");
3327 lua_pushvalue(L, methodtable);
3328 lua_settable(L, metatable);
3330 lua_pushliteral(L, "__gc");
3331 lua_pushcfunction(L, gc_object);
3332 lua_settable(L, metatable);
3334 lua_pop(L, 1); // drop metatable
3336 luaL_openlib(L, 0, methods, 0); // fill methodtable
3337 lua_pop(L, 1); // drop methodtable
3339 // Can be created from Lua (LuaPseudoRandom(seed))
3340 lua_register(L, className, create_object);
3343 const char LuaPseudoRandom::className[] = "PseudoRandom";
3344 const luaL_reg LuaPseudoRandom::methods[] = {
3345 method(LuaPseudoRandom, next),
3353 class LuaABM : public ActiveBlockModifier
3359 std::set<std::string> m_trigger_contents;
3360 std::set<std::string> m_required_neighbors;
3361 float m_trigger_interval;
3362 u32 m_trigger_chance;
3364 LuaABM(lua_State *L, int id,
3365 const std::set<std::string> &trigger_contents,
3366 const std::set<std::string> &required_neighbors,
3367 float trigger_interval, u32 trigger_chance):
3370 m_trigger_contents(trigger_contents),
3371 m_required_neighbors(required_neighbors),
3372 m_trigger_interval(trigger_interval),
3373 m_trigger_chance(trigger_chance)
3376 virtual std::set<std::string> getTriggerContents()
3378 return m_trigger_contents;
3380 virtual std::set<std::string> getRequiredNeighbors()
3382 return m_required_neighbors;
3384 virtual float getTriggerInterval()
3386 return m_trigger_interval;
3388 virtual u32 getTriggerChance()
3390 return m_trigger_chance;
3392 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3393 u32 active_object_count, u32 active_object_count_wider)
3395 lua_State *L = m_lua;
3398 assert(lua_checkstack(L, 20));
3399 StackUnroller stack_unroller(L);
3401 // Get minetest.registered_abms
3402 lua_getglobal(L, "minetest");
3403 lua_getfield(L, -1, "registered_abms");
3404 luaL_checktype(L, -1, LUA_TTABLE);
3405 int registered_abms = lua_gettop(L);
3407 // Get minetest.registered_abms[m_id]
3408 lua_pushnumber(L, m_id);
3409 lua_gettable(L, registered_abms);
3410 if(lua_isnil(L, -1))
3414 luaL_checktype(L, -1, LUA_TTABLE);
3415 lua_getfield(L, -1, "action");
3416 luaL_checktype(L, -1, LUA_TFUNCTION);
3418 pushnode(L, n, env->getGameDef()->ndef());
3419 lua_pushnumber(L, active_object_count);
3420 lua_pushnumber(L, active_object_count_wider);
3421 if(lua_pcall(L, 4, 0, 0))
3422 script_error(L, "error: %s", lua_tostring(L, -1));
3430 static void read_server_sound_params(lua_State *L, int index,
3431 ServerSoundParams ¶ms)
3434 index = lua_gettop(L) + 1 + index;
3436 params = ServerSoundParams();
3437 if(lua_istable(L, index)){
3438 getfloatfield(L, index, "gain", params.gain);
3439 getstringfield(L, index, "to_player", params.to_player);
3440 lua_getfield(L, index, "pos");
3441 if(!lua_isnil(L, -1)){
3442 v3f p = read_v3f(L, -1)*BS;
3444 params.type = ServerSoundParams::SSP_POSITIONAL;
3447 lua_getfield(L, index, "object");
3448 if(!lua_isnil(L, -1)){
3449 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3450 ServerActiveObject *sao = ObjectRef::getobject(ref);
3452 params.object = sao->getId();
3453 params.type = ServerSoundParams::SSP_OBJECT;
3457 params.max_hear_distance = BS*getfloatfield_default(L, index,
3458 "max_hear_distance", params.max_hear_distance/BS);
3459 getboolfield(L, index, "loop", params.loop);
3468 // Writes a line to dstream
3469 static int l_debug(lua_State *L)
3471 std::string text = lua_tostring(L, 1);
3472 dstream << text << std::endl;
3476 // log([level,] text)
3477 // Writes a line to the logger.
3478 // The one-argument version logs to infostream.
3479 // The two-argument version accept a log level: error, action, info, or verbose.
3480 static int l_log(lua_State *L)
3483 LogMessageLevel level = LMT_INFO;
3484 if(lua_isnone(L, 2))
3486 text = lua_tostring(L, 1);
3490 std::string levelname = lua_tostring(L, 1);
3491 text = lua_tostring(L, 2);
3492 if(levelname == "error")
3494 else if(levelname == "action")
3496 else if(levelname == "verbose")
3497 level = LMT_VERBOSE;
3499 log_printline(level, text);
3503 // register_item_raw({lots of stuff})
3504 static int l_register_item_raw(lua_State *L)
3506 luaL_checktype(L, 1, LUA_TTABLE);
3509 // Get the writable item and node definition managers from the server
3510 IWritableItemDefManager *idef =
3511 get_server(L)->getWritableItemDefManager();
3512 IWritableNodeDefManager *ndef =
3513 get_server(L)->getWritableNodeDefManager();
3515 // Check if name is defined
3516 lua_getfield(L, table, "name");
3517 if(lua_isstring(L, -1)){
3518 std::string name = lua_tostring(L, -1);
3519 verbosestream<<"register_item_raw: "<<name<<std::endl;
3521 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3524 // Check if on_use is defined
3526 // Read the item definition and register it
3527 ItemDefinition def = read_item_definition(L, table);
3528 idef->registerItem(def);
3530 // Read the node definition (content features) and register it
3531 if(def.type == ITEM_NODE)
3533 ContentFeatures f = read_content_features(L, table);
3534 ndef->set(f.name, f);
3537 return 0; /* number of results */
3540 // register_alias_raw(name, convert_to_name)
3541 static int l_register_alias_raw(lua_State *L)
3543 std::string name = luaL_checkstring(L, 1);
3544 std::string convert_to = luaL_checkstring(L, 2);
3546 // Get the writable item definition manager from the server
3547 IWritableItemDefManager *idef =
3548 get_server(L)->getWritableItemDefManager();
3550 idef->registerAlias(name, convert_to);
3552 return 0; /* number of results */
3555 // helper for register_craft
3556 static bool read_craft_recipe_shaped(lua_State *L, int index,
3557 int &width, std::vector<std::string> &recipe)
3560 index = lua_gettop(L) + 1 + index;
3562 if(!lua_istable(L, index))
3567 while(lua_next(L, index) != 0){
3569 // key at index -2 and value at index -1
3570 if(!lua_istable(L, -1))
3572 int table2 = lua_gettop(L);
3574 while(lua_next(L, table2) != 0){
3575 // key at index -2 and value at index -1
3576 if(!lua_isstring(L, -1))
3578 recipe.push_back(lua_tostring(L, -1));
3579 // removes value, keeps key for next iteration
3586 if(colcount != width)
3589 // removes value, keeps key for next iteration
3596 // helper for register_craft
3597 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3598 std::vector<std::string> &recipe)
3601 index = lua_gettop(L) + 1 + index;
3603 if(!lua_istable(L, index))
3607 while(lua_next(L, index) != 0){
3608 // key at index -2 and value at index -1
3609 if(!lua_isstring(L, -1))
3611 recipe.push_back(lua_tostring(L, -1));
3612 // removes value, keeps key for next iteration
3618 // helper for register_craft
3619 static bool read_craft_replacements(lua_State *L, int index,
3620 CraftReplacements &replacements)
3623 index = lua_gettop(L) + 1 + index;
3625 if(!lua_istable(L, index))
3629 while(lua_next(L, index) != 0){
3630 // key at index -2 and value at index -1
3631 if(!lua_istable(L, -1))
3633 lua_rawgeti(L, -1, 1);
3634 if(!lua_isstring(L, -1))
3636 std::string replace_from = lua_tostring(L, -1);
3638 lua_rawgeti(L, -1, 2);
3639 if(!lua_isstring(L, -1))
3641 std::string replace_to = lua_tostring(L, -1);
3643 replacements.pairs.push_back(
3644 std::make_pair(replace_from, replace_to));
3645 // removes value, keeps key for next iteration
3650 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3651 static int l_register_craft(lua_State *L)
3653 //infostream<<"register_craft"<<std::endl;
3654 luaL_checktype(L, 1, LUA_TTABLE);
3657 // Get the writable craft definition manager from the server
3658 IWritableCraftDefManager *craftdef =
3659 get_server(L)->getWritableCraftDefManager();
3661 std::string type = getstringfield_default(L, table, "type", "shaped");
3664 CraftDefinitionShaped
3666 if(type == "shaped"){
3667 std::string output = getstringfield_default(L, table, "output", "");
3669 throw LuaError(L, "Crafting definition is missing an output");
3672 std::vector<std::string> recipe;
3673 lua_getfield(L, table, "recipe");
3674 if(lua_isnil(L, -1))
3675 throw LuaError(L, "Crafting definition is missing a recipe"
3676 " (output=\"" + output + "\")");
3677 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3678 throw LuaError(L, "Invalid crafting recipe"
3679 " (output=\"" + output + "\")");
3681 CraftReplacements replacements;
3682 lua_getfield(L, table, "replacements");
3683 if(!lua_isnil(L, -1))
3685 if(!read_craft_replacements(L, -1, replacements))
3686 throw LuaError(L, "Invalid replacements"
3687 " (output=\"" + output + "\")");
3690 CraftDefinition *def = new CraftDefinitionShaped(
3691 output, width, recipe, replacements);
3692 craftdef->registerCraft(def);
3695 CraftDefinitionShapeless
3697 else if(type == "shapeless"){
3698 std::string output = getstringfield_default(L, table, "output", "");
3700 throw LuaError(L, "Crafting definition (shapeless)"
3701 " is missing an output");
3703 std::vector<std::string> recipe;
3704 lua_getfield(L, table, "recipe");
3705 if(lua_isnil(L, -1))
3706 throw LuaError(L, "Crafting definition (shapeless)"
3707 " is missing a recipe"
3708 " (output=\"" + output + "\")");
3709 if(!read_craft_recipe_shapeless(L, -1, recipe))
3710 throw LuaError(L, "Invalid crafting recipe"
3711 " (output=\"" + output + "\")");
3713 CraftReplacements replacements;
3714 lua_getfield(L, table, "replacements");
3715 if(!lua_isnil(L, -1))
3717 if(!read_craft_replacements(L, -1, replacements))
3718 throw LuaError(L, "Invalid replacements"
3719 " (output=\"" + output + "\")");
3722 CraftDefinition *def = new CraftDefinitionShapeless(
3723 output, recipe, replacements);
3724 craftdef->registerCraft(def);
3727 CraftDefinitionToolRepair
3729 else if(type == "toolrepair"){
3730 float additional_wear = getfloatfield_default(L, table,
3731 "additional_wear", 0.0);
3733 CraftDefinition *def = new CraftDefinitionToolRepair(
3735 craftdef->registerCraft(def);
3738 CraftDefinitionCooking
3740 else if(type == "cooking"){
3741 std::string output = getstringfield_default(L, table, "output", "");
3743 throw LuaError(L, "Crafting definition (cooking)"
3744 " is missing an output");
3746 std::string recipe = getstringfield_default(L, table, "recipe", "");
3748 throw LuaError(L, "Crafting definition (cooking)"
3749 " is missing a recipe"
3750 " (output=\"" + output + "\")");
3752 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3754 CraftDefinition *def = new CraftDefinitionCooking(
3755 output, recipe, cooktime);
3756 craftdef->registerCraft(def);
3761 else if(type == "fuel"){
3762 std::string recipe = getstringfield_default(L, table, "recipe", "");
3764 throw LuaError(L, "Crafting definition (fuel)"
3765 " is missing a recipe");
3767 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3769 CraftDefinition *def = new CraftDefinitionFuel(
3771 craftdef->registerCraft(def);
3775 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3779 return 0; /* number of results */
3782 // setting_get(name)
3783 static int l_setting_get(lua_State *L)
3785 const char *name = luaL_checkstring(L, 1);
3787 std::string value = g_settings->get(name);
3788 lua_pushstring(L, value.c_str());
3789 } catch(SettingNotFoundException &e){
3795 // setting_getbool(name)
3796 static int l_setting_getbool(lua_State *L)
3798 const char *name = luaL_checkstring(L, 1);
3800 bool value = g_settings->getBool(name);
3801 lua_pushboolean(L, value);
3802 } catch(SettingNotFoundException &e){
3808 // chat_send_all(text)
3809 static int l_chat_send_all(lua_State *L)
3811 const char *text = luaL_checkstring(L, 1);
3812 // Get server from registry
3813 Server *server = get_server(L);
3815 server->notifyPlayers(narrow_to_wide(text));
3819 // chat_send_player(name, text)
3820 static int l_chat_send_player(lua_State *L)
3822 const char *name = luaL_checkstring(L, 1);
3823 const char *text = luaL_checkstring(L, 2);
3824 // Get server from registry
3825 Server *server = get_server(L);
3827 server->notifyPlayer(name, narrow_to_wide(text));
3831 // get_player_privs(name, text)
3832 static int l_get_player_privs(lua_State *L)
3834 const char *name = luaL_checkstring(L, 1);
3835 // Get server from registry
3836 Server *server = get_server(L);
3839 int table = lua_gettop(L);
3840 u64 privs_i = server->getPlayerEffectivePrivs(name);
3841 std::set<std::string> privs_s = privsToSet(privs_i);
3842 for(std::set<std::string>::const_iterator
3843 i = privs_s.begin(); i != privs_s.end(); i++){
3844 lua_pushboolean(L, true);
3845 lua_setfield(L, table, i->c_str());
3847 lua_pushvalue(L, table);
3851 // get_inventory(location)
3852 static int l_get_inventory(lua_State *L)
3854 InventoryLocation loc;
3856 std::string type = checkstringfield(L, 1, "type");
3857 if(type == "player"){
3858 std::string name = checkstringfield(L, 1, "name");
3859 loc.setPlayer(name);
3860 } else if(type == "node"){
3861 lua_getfield(L, 1, "pos");
3862 v3s16 pos = check_v3s16(L, -1);
3863 loc.setNodeMeta(pos);
3866 if(get_server(L)->getInventory(loc) != NULL)
3867 InvRef::create(L, loc);
3873 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3874 static int l_get_dig_params(lua_State *L)
3876 std::map<std::string, int> groups;
3877 read_groups(L, 1, groups);
3878 ToolCapabilities tp = read_tool_capabilities(L, 2);
3879 if(lua_isnoneornil(L, 3))
3880 push_dig_params(L, getDigParams(groups, &tp));
3882 push_dig_params(L, getDigParams(groups, &tp,
3883 luaL_checknumber(L, 3)));
3887 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3888 static int l_get_hit_params(lua_State *L)
3890 std::map<std::string, int> groups;
3891 read_groups(L, 1, groups);
3892 ToolCapabilities tp = read_tool_capabilities(L, 2);
3893 if(lua_isnoneornil(L, 3))
3894 push_hit_params(L, getHitParams(groups, &tp));
3896 push_hit_params(L, getHitParams(groups, &tp,
3897 luaL_checknumber(L, 3)));
3901 // get_current_modname()
3902 static int l_get_current_modname(lua_State *L)
3904 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3908 // get_modpath(modname)
3909 static int l_get_modpath(lua_State *L)
3911 const char *modname = luaL_checkstring(L, 1);
3913 const ModSpec *mod = get_server(L)->getModSpec(modname);
3918 lua_pushstring(L, mod->path.c_str());
3923 static int l_get_worldpath(lua_State *L)
3925 std::string worldpath = get_server(L)->getWorldPath();
3926 lua_pushstring(L, worldpath.c_str());
3930 // sound_play(spec, parameters)
3931 static int l_sound_play(lua_State *L)
3933 SimpleSoundSpec spec;
3934 read_soundspec(L, 1, spec);
3935 ServerSoundParams params;
3936 read_server_sound_params(L, 2, params);
3937 s32 handle = get_server(L)->playSound(spec, params);
3938 lua_pushinteger(L, handle);
3942 // sound_stop(handle)
3943 static int l_sound_stop(lua_State *L)
3945 int handle = luaL_checkinteger(L, 1);
3946 get_server(L)->stopSound(handle);
3950 // is_singleplayer()
3951 static int l_is_singleplayer(lua_State *L)
3953 lua_pushboolean(L, get_server(L)->isSingleplayer());
3957 static const struct luaL_Reg minetest_f [] = {
3960 {"register_item_raw", l_register_item_raw},
3961 {"register_alias_raw", l_register_alias_raw},
3962 {"register_craft", l_register_craft},
3963 {"setting_get", l_setting_get},
3964 {"setting_getbool", l_setting_getbool},
3965 {"chat_send_all", l_chat_send_all},
3966 {"chat_send_player", l_chat_send_player},
3967 {"get_player_privs", l_get_player_privs},
3968 {"get_inventory", l_get_inventory},
3969 {"get_dig_params", l_get_dig_params},
3970 {"get_hit_params", l_get_hit_params},
3971 {"get_current_modname", l_get_current_modname},
3972 {"get_modpath", l_get_modpath},
3973 {"get_worldpath", l_get_worldpath},
3974 {"sound_play", l_sound_play},
3975 {"sound_stop", l_sound_stop},
3976 {"is_singleplayer", l_is_singleplayer},
3981 Main export function
3984 void scriptapi_export(lua_State *L, Server *server)
3987 assert(lua_checkstack(L, 20));
3988 verbosestream<<"scriptapi_export()"<<std::endl;
3989 StackUnroller stack_unroller(L);
3991 // Store server as light userdata in registry
3992 lua_pushlightuserdata(L, server);
3993 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
3995 // Register global functions in table minetest
3997 luaL_register(L, NULL, minetest_f);
3998 lua_setglobal(L, "minetest");
4000 // Get the main minetest table
4001 lua_getglobal(L, "minetest");
4003 // Add tables to minetest
4006 lua_setfield(L, -2, "object_refs");
4008 lua_setfield(L, -2, "luaentities");
4010 // Register wrappers
4011 LuaItemStack::Register(L);
4012 InvRef::Register(L);
4013 NodeMetaRef::Register(L);
4014 ObjectRef::Register(L);
4015 EnvRef::Register(L);
4016 LuaPseudoRandom::Register(L);
4019 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4020 const std::string &modname)
4022 ModNameStorer modnamestorer(L, modname);
4024 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4026 errorstream<<"Error loading mod \""<<modname
4027 <<"\": modname does not follow naming conventions: "
4028 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4032 bool success = false;
4035 success = script_load(L, scriptpath.c_str());
4038 errorstream<<"Error loading mod \""<<modname
4039 <<"\": "<<e.what()<<std::endl;
4045 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4048 assert(lua_checkstack(L, 20));
4049 verbosestream<<"scriptapi_add_environment"<<std::endl;
4050 StackUnroller stack_unroller(L);
4052 // Create EnvRef on stack
4053 EnvRef::create(L, env);
4054 int envref = lua_gettop(L);
4056 // minetest.env = envref
4057 lua_getglobal(L, "minetest");
4058 luaL_checktype(L, -1, LUA_TTABLE);
4059 lua_pushvalue(L, envref);
4060 lua_setfield(L, -2, "env");
4062 // Store environment as light userdata in registry
4063 lua_pushlightuserdata(L, env);
4064 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4067 Add ActiveBlockModifiers to environment
4070 // Get minetest.registered_abms
4071 lua_getglobal(L, "minetest");
4072 lua_getfield(L, -1, "registered_abms");
4073 luaL_checktype(L, -1, LUA_TTABLE);
4074 int registered_abms = lua_gettop(L);
4076 if(lua_istable(L, registered_abms)){
4077 int table = lua_gettop(L);
4079 while(lua_next(L, table) != 0){
4080 // key at index -2 and value at index -1
4081 int id = lua_tonumber(L, -2);
4082 int current_abm = lua_gettop(L);
4084 std::set<std::string> trigger_contents;
4085 lua_getfield(L, current_abm, "nodenames");
4086 if(lua_istable(L, -1)){
4087 int table = lua_gettop(L);
4089 while(lua_next(L, table) != 0){
4090 // key at index -2 and value at index -1
4091 luaL_checktype(L, -1, LUA_TSTRING);
4092 trigger_contents.insert(lua_tostring(L, -1));
4093 // removes value, keeps key for next iteration
4096 } else if(lua_isstring(L, -1)){
4097 trigger_contents.insert(lua_tostring(L, -1));
4101 std::set<std::string> required_neighbors;
4102 lua_getfield(L, current_abm, "neighbors");
4103 if(lua_istable(L, -1)){
4104 int table = lua_gettop(L);
4106 while(lua_next(L, table) != 0){
4107 // key at index -2 and value at index -1
4108 luaL_checktype(L, -1, LUA_TSTRING);
4109 required_neighbors.insert(lua_tostring(L, -1));
4110 // removes value, keeps key for next iteration
4113 } else if(lua_isstring(L, -1)){
4114 required_neighbors.insert(lua_tostring(L, -1));
4118 float trigger_interval = 10.0;
4119 getfloatfield(L, current_abm, "interval", trigger_interval);
4121 int trigger_chance = 50;
4122 getintfield(L, current_abm, "chance", trigger_chance);
4124 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4125 required_neighbors, trigger_interval, trigger_chance);
4127 env->addActiveBlockModifier(abm);
4129 // removes value, keeps key for next iteration
4137 // Dump stack top with the dump2 function
4138 static void dump2(lua_State *L, const char *name)
4140 // Dump object (debug)
4141 lua_getglobal(L, "dump2");
4142 luaL_checktype(L, -1, LUA_TFUNCTION);
4143 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4144 lua_pushstring(L, name);
4145 if(lua_pcall(L, 2, 0, 0))
4146 script_error(L, "error: %s", lua_tostring(L, -1));
4154 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4157 assert(lua_checkstack(L, 20));
4158 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4159 StackUnroller stack_unroller(L);
4161 // Create object on stack
4162 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4163 int object = lua_gettop(L);
4165 // Get minetest.object_refs table
4166 lua_getglobal(L, "minetest");
4167 lua_getfield(L, -1, "object_refs");
4168 luaL_checktype(L, -1, LUA_TTABLE);
4169 int objectstable = lua_gettop(L);
4171 // object_refs[id] = object
4172 lua_pushnumber(L, cobj->getId()); // Push id
4173 lua_pushvalue(L, object); // Copy object to top of stack
4174 lua_settable(L, objectstable);
4177 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4180 assert(lua_checkstack(L, 20));
4181 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4182 StackUnroller stack_unroller(L);
4184 // Get minetest.object_refs table
4185 lua_getglobal(L, "minetest");
4186 lua_getfield(L, -1, "object_refs");
4187 luaL_checktype(L, -1, LUA_TTABLE);
4188 int objectstable = lua_gettop(L);
4190 // Get object_refs[id]
4191 lua_pushnumber(L, cobj->getId()); // Push id
4192 lua_gettable(L, objectstable);
4193 // Set object reference to NULL
4194 ObjectRef::set_null(L);
4195 lua_pop(L, 1); // pop object
4197 // Set object_refs[id] = nil
4198 lua_pushnumber(L, cobj->getId()); // Push id
4200 lua_settable(L, objectstable);
4207 // What scriptapi_run_callbacks does with the return values of callbacks.
4208 // Regardless of the mode, if only one callback is defined,
4209 // its return value is the total return value.
4210 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4211 enum RunCallbacksMode
4213 // Returns the return value of the first callback
4214 // Returns nil if list of callbacks is empty
4215 RUN_CALLBACKS_MODE_FIRST,
4216 // Returns the return value of the last callback
4217 // Returns nil if list of callbacks is empty
4218 RUN_CALLBACKS_MODE_LAST,
4219 // If any callback returns a false value, the first such is returned
4220 // Otherwise, the first callback's return value (trueish) is returned
4221 // Returns true if list of callbacks is empty
4222 RUN_CALLBACKS_MODE_AND,
4223 // Like above, but stops calling callbacks (short circuit)
4224 // after seeing the first false value
4225 RUN_CALLBACKS_MODE_AND_SC,
4226 // If any callback returns a true value, the first such is returned
4227 // Otherwise, the first callback's return value (falseish) is returned
4228 // Returns false if list of callbacks is empty
4229 RUN_CALLBACKS_MODE_OR,
4230 // Like above, but stops calling callbacks (short circuit)
4231 // after seeing the first true value
4232 RUN_CALLBACKS_MODE_OR_SC,
4233 // Note: "a true value" and "a false value" refer to values that
4234 // are converted by lua_toboolean to true or false, respectively.
4237 // Push the list of callbacks (a lua table).
4238 // Then push nargs arguments.
4239 // Then call this function, which
4240 // - runs the callbacks
4241 // - removes the table and arguments from the lua stack
4242 // - pushes the return value, computed depending on mode
4243 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4244 RunCallbacksMode mode)
4246 // Insert the return value into the lua stack, below the table
4247 assert(lua_gettop(L) >= nargs + 1);
4249 lua_insert(L, -(nargs + 1) - 1);
4250 // Stack now looks like this:
4251 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4253 int rv = lua_gettop(L) - nargs - 1;
4255 int arg = table + 1;
4257 luaL_checktype(L, table, LUA_TTABLE);
4261 bool first_loop = true;
4262 while(lua_next(L, table) != 0){
4263 // key at index -2 and value at index -1
4264 luaL_checktype(L, -1, LUA_TFUNCTION);
4266 for(int i = 0; i < nargs; i++)
4267 lua_pushvalue(L, arg+i);
4268 if(lua_pcall(L, nargs, 1, 0))
4269 script_error(L, "error: %s", lua_tostring(L, -1));
4271 // Move return value to designated space in stack
4274 // Result of first callback is always moved
4278 // Otherwise, what happens depends on the mode
4279 if(mode == RUN_CALLBACKS_MODE_FIRST)
4281 else if(mode == RUN_CALLBACKS_MODE_LAST)
4283 else if(mode == RUN_CALLBACKS_MODE_AND ||
4284 mode == RUN_CALLBACKS_MODE_AND_SC){
4285 if(lua_toboolean(L, rv) == true &&
4286 lua_toboolean(L, -1) == false)
4291 else if(mode == RUN_CALLBACKS_MODE_OR ||
4292 mode == RUN_CALLBACKS_MODE_OR_SC){
4293 if(lua_toboolean(L, rv) == false &&
4294 lua_toboolean(L, -1) == true)
4303 // Handle short circuit modes
4304 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4305 lua_toboolean(L, rv) == false)
4307 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4308 lua_toboolean(L, rv) == true)
4311 // value removed, keep key for next iteration
4314 // Remove stuff from stack, leaving only the return value
4317 // Fix return value in case no callbacks were called
4319 if(mode == RUN_CALLBACKS_MODE_AND ||
4320 mode == RUN_CALLBACKS_MODE_AND_SC){
4322 lua_pushboolean(L, true);
4324 else if(mode == RUN_CALLBACKS_MODE_OR ||
4325 mode == RUN_CALLBACKS_MODE_OR_SC){
4327 lua_pushboolean(L, false);
4332 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4333 const std::string &message)
4336 assert(lua_checkstack(L, 20));
4337 StackUnroller stack_unroller(L);
4339 // Get minetest.registered_on_chat_messages
4340 lua_getglobal(L, "minetest");
4341 lua_getfield(L, -1, "registered_on_chat_messages");
4343 lua_pushstring(L, name.c_str());
4344 lua_pushstring(L, message.c_str());
4345 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4346 bool ate = lua_toboolean(L, -1);
4350 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4353 assert(lua_checkstack(L, 20));
4354 StackUnroller stack_unroller(L);
4356 // Get minetest.registered_on_newplayers
4357 lua_getglobal(L, "minetest");
4358 lua_getfield(L, -1, "registered_on_newplayers");
4360 objectref_get_or_create(L, player);
4361 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4364 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4367 assert(lua_checkstack(L, 20));
4368 StackUnroller stack_unroller(L);
4370 // Get minetest.registered_on_dieplayers
4371 lua_getglobal(L, "minetest");
4372 lua_getfield(L, -1, "registered_on_dieplayers");
4374 objectref_get_or_create(L, player);
4375 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4378 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4381 assert(lua_checkstack(L, 20));
4382 StackUnroller stack_unroller(L);
4384 // Get minetest.registered_on_respawnplayers
4385 lua_getglobal(L, "minetest");
4386 lua_getfield(L, -1, "registered_on_respawnplayers");
4388 objectref_get_or_create(L, player);
4389 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4390 bool positioning_handled_by_some = lua_toboolean(L, -1);
4391 return positioning_handled_by_some;
4394 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4397 assert(lua_checkstack(L, 20));
4398 StackUnroller stack_unroller(L);
4400 // Get minetest.registered_on_joinplayers
4401 lua_getglobal(L, "minetest");
4402 lua_getfield(L, -1, "registered_on_joinplayers");
4404 objectref_get_or_create(L, player);
4405 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4408 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4411 assert(lua_checkstack(L, 20));
4412 StackUnroller stack_unroller(L);
4414 // Get minetest.registered_on_leaveplayers
4415 lua_getglobal(L, "minetest");
4416 lua_getfield(L, -1, "registered_on_leaveplayers");
4418 objectref_get_or_create(L, player);
4419 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4422 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4424 Inventory *inv = player->getInventory();
4427 lua_getglobal(L, "minetest");
4428 lua_getfield(L, -1, "creative_inventory");
4429 luaL_checktype(L, -1, LUA_TTABLE);
4430 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4434 item callbacks and node callbacks
4437 // Retrieves minetest.registered_items[name][callbackname]
4438 // If that is nil or on error, return false and stack is unchanged
4439 // If that is a function, returns true and pushes the
4440 // function onto the stack
4441 static bool get_item_callback(lua_State *L,
4442 const char *name, const char *callbackname)
4444 lua_getglobal(L, "minetest");
4445 lua_getfield(L, -1, "registered_items");
4447 luaL_checktype(L, -1, LUA_TTABLE);
4448 lua_getfield(L, -1, name);
4450 // Should be a table
4451 if(lua_type(L, -1) != LUA_TTABLE)
4453 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4457 lua_getfield(L, -1, callbackname);
4459 // Should be a function or nil
4460 if(lua_type(L, -1) == LUA_TFUNCTION)
4464 else if(lua_isnil(L, -1))
4471 errorstream<<"Item \""<<name<<"\" callback \""
4472 <<callbackname<<" is not a function"<<std::endl;
4478 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4479 ServerActiveObject *dropper, v3f pos)
4482 assert(lua_checkstack(L, 20));
4483 StackUnroller stack_unroller(L);
4485 // Push callback function on stack
4486 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4490 LuaItemStack::create(L, item);
4491 objectref_get_or_create(L, dropper);
4492 pushFloatPos(L, pos);
4493 if(lua_pcall(L, 3, 1, 0))
4494 script_error(L, "error: %s", lua_tostring(L, -1));
4495 if(!lua_isnil(L, -1))
4496 item = read_item(L, -1);
4500 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4501 ServerActiveObject *placer, const PointedThing &pointed)
4504 assert(lua_checkstack(L, 20));
4505 StackUnroller stack_unroller(L);
4507 // Push callback function on stack
4508 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4512 LuaItemStack::create(L, item);
4513 objectref_get_or_create(L, placer);
4514 push_pointed_thing(L, pointed);
4515 if(lua_pcall(L, 3, 1, 0))
4516 script_error(L, "error: %s", lua_tostring(L, -1));
4517 if(!lua_isnil(L, -1))
4518 item = read_item(L, -1);
4522 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4523 ServerActiveObject *user, const PointedThing &pointed)
4526 assert(lua_checkstack(L, 20));
4527 StackUnroller stack_unroller(L);
4529 // Push callback function on stack
4530 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4534 LuaItemStack::create(L, item);
4535 objectref_get_or_create(L, user);
4536 push_pointed_thing(L, pointed);
4537 if(lua_pcall(L, 3, 1, 0))
4538 script_error(L, "error: %s", lua_tostring(L, -1));
4539 if(!lua_isnil(L, -1))
4540 item = read_item(L, -1);
4544 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4545 ServerActiveObject *puncher)
4548 assert(lua_checkstack(L, 20));
4549 StackUnroller stack_unroller(L);
4551 INodeDefManager *ndef = get_server(L)->ndef();
4553 // Push callback function on stack
4554 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4559 pushnode(L, node, ndef);
4560 objectref_get_or_create(L, puncher);
4561 if(lua_pcall(L, 3, 0, 0))
4562 script_error(L, "error: %s", lua_tostring(L, -1));
4566 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4567 ServerActiveObject *digger)
4570 assert(lua_checkstack(L, 20));
4571 StackUnroller stack_unroller(L);
4573 INodeDefManager *ndef = get_server(L)->ndef();
4575 // Push callback function on stack
4576 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4581 pushnode(L, node, ndef);
4582 objectref_get_or_create(L, digger);
4583 if(lua_pcall(L, 3, 0, 0))
4584 script_error(L, "error: %s", lua_tostring(L, -1));
4592 void scriptapi_environment_step(lua_State *L, float dtime)
4595 assert(lua_checkstack(L, 20));
4596 //infostream<<"scriptapi_environment_step"<<std::endl;
4597 StackUnroller stack_unroller(L);
4599 // Get minetest.registered_globalsteps
4600 lua_getglobal(L, "minetest");
4601 lua_getfield(L, -1, "registered_globalsteps");
4603 lua_pushnumber(L, dtime);
4604 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4607 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
4611 assert(lua_checkstack(L, 20));
4612 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4613 StackUnroller stack_unroller(L);
4615 // Get minetest.registered_on_generateds
4616 lua_getglobal(L, "minetest");
4617 lua_getfield(L, -1, "registered_on_generateds");
4619 push_v3s16(L, minp);
4620 push_v3s16(L, maxp);
4621 lua_pushnumber(L, blockseed);
4622 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
4629 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4632 assert(lua_checkstack(L, 20));
4633 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4634 <<name<<"\""<<std::endl;
4635 StackUnroller stack_unroller(L);
4637 // Get minetest.registered_entities[name]
4638 lua_getglobal(L, "minetest");
4639 lua_getfield(L, -1, "registered_entities");
4640 luaL_checktype(L, -1, LUA_TTABLE);
4641 lua_pushstring(L, name);
4642 lua_gettable(L, -2);
4643 // Should be a table, which we will use as a prototype
4644 //luaL_checktype(L, -1, LUA_TTABLE);
4645 if(lua_type(L, -1) != LUA_TTABLE){
4646 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4649 int prototype_table = lua_gettop(L);
4650 //dump2(L, "prototype_table");
4652 // Create entity object
4654 int object = lua_gettop(L);
4656 // Set object metatable
4657 lua_pushvalue(L, prototype_table);
4658 lua_setmetatable(L, -2);
4660 // Add object reference
4661 // This should be userdata with metatable ObjectRef
4662 objectref_get(L, id);
4663 luaL_checktype(L, -1, LUA_TUSERDATA);
4664 if(!luaL_checkudata(L, -1, "ObjectRef"))
4665 luaL_typerror(L, -1, "ObjectRef");
4666 lua_setfield(L, -2, "object");
4668 // minetest.luaentities[id] = object
4669 lua_getglobal(L, "minetest");
4670 lua_getfield(L, -1, "luaentities");
4671 luaL_checktype(L, -1, LUA_TTABLE);
4672 lua_pushnumber(L, id); // Push id
4673 lua_pushvalue(L, object); // Copy object to top of stack
4674 lua_settable(L, -3);
4679 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4680 const std::string &staticdata)
4683 assert(lua_checkstack(L, 20));
4684 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4685 StackUnroller stack_unroller(L);
4687 // Get minetest.luaentities[id]
4688 luaentity_get(L, id);
4689 int object = lua_gettop(L);
4691 // Get on_activate function
4692 lua_pushvalue(L, object);
4693 lua_getfield(L, -1, "on_activate");
4694 if(!lua_isnil(L, -1)){
4695 luaL_checktype(L, -1, LUA_TFUNCTION);
4696 lua_pushvalue(L, object); // self
4697 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4698 // Call with 2 arguments, 0 results
4699 if(lua_pcall(L, 2, 0, 0))
4700 script_error(L, "error running function on_activate: %s\n",
4701 lua_tostring(L, -1));
4705 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4708 assert(lua_checkstack(L, 20));
4709 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4711 // Get minetest.luaentities table
4712 lua_getglobal(L, "minetest");
4713 lua_getfield(L, -1, "luaentities");
4714 luaL_checktype(L, -1, LUA_TTABLE);
4715 int objectstable = lua_gettop(L);
4717 // Set luaentities[id] = nil
4718 lua_pushnumber(L, id); // Push id
4720 lua_settable(L, objectstable);
4722 lua_pop(L, 2); // pop luaentities, minetest
4725 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4728 assert(lua_checkstack(L, 20));
4729 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4730 StackUnroller stack_unroller(L);
4732 // Get minetest.luaentities[id]
4733 luaentity_get(L, id);
4734 int object = lua_gettop(L);
4736 // Get get_staticdata function
4737 lua_pushvalue(L, object);
4738 lua_getfield(L, -1, "get_staticdata");
4739 if(lua_isnil(L, -1))
4742 luaL_checktype(L, -1, LUA_TFUNCTION);
4743 lua_pushvalue(L, object); // self
4744 // Call with 1 arguments, 1 results
4745 if(lua_pcall(L, 1, 1, 0))
4746 script_error(L, "error running function get_staticdata: %s\n",
4747 lua_tostring(L, -1));
4750 const char *s = lua_tolstring(L, -1, &len);
4751 return std::string(s, len);
4754 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4755 ObjectProperties *prop)
4758 assert(lua_checkstack(L, 20));
4759 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4760 StackUnroller stack_unroller(L);
4762 // Get minetest.luaentities[id]
4763 luaentity_get(L, id);
4764 //int object = lua_gettop(L);
4766 // Set default values that differ from ObjectProperties defaults
4770 read_object_properties(L, -1, prop);
4773 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4776 assert(lua_checkstack(L, 20));
4777 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4778 StackUnroller stack_unroller(L);
4780 // Get minetest.luaentities[id]
4781 luaentity_get(L, id);
4782 int object = lua_gettop(L);
4783 // State: object is at top of stack
4784 // Get step function
4785 lua_getfield(L, -1, "on_step");
4786 if(lua_isnil(L, -1))
4788 luaL_checktype(L, -1, LUA_TFUNCTION);
4789 lua_pushvalue(L, object); // self
4790 lua_pushnumber(L, dtime); // dtime
4791 // Call with 2 arguments, 0 results
4792 if(lua_pcall(L, 2, 0, 0))
4793 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4796 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4797 // tool_capabilities, direction)
4798 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4799 ServerActiveObject *puncher, float time_from_last_punch,
4800 const ToolCapabilities *toolcap, v3f dir)
4803 assert(lua_checkstack(L, 20));
4804 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4805 StackUnroller stack_unroller(L);
4807 // Get minetest.luaentities[id]
4808 luaentity_get(L, id);
4809 int object = lua_gettop(L);
4810 // State: object is at top of stack
4812 lua_getfield(L, -1, "on_punch");
4813 if(lua_isnil(L, -1))
4815 luaL_checktype(L, -1, LUA_TFUNCTION);
4816 lua_pushvalue(L, object); // self
4817 objectref_get_or_create(L, puncher); // Clicker reference
4818 lua_pushnumber(L, time_from_last_punch);
4819 push_tool_capabilities(L, *toolcap);
4821 // Call with 5 arguments, 0 results
4822 if(lua_pcall(L, 5, 0, 0))
4823 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4826 // Calls entity:on_rightclick(ObjectRef clicker)
4827 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4828 ServerActiveObject *clicker)
4831 assert(lua_checkstack(L, 20));
4832 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4833 StackUnroller stack_unroller(L);
4835 // Get minetest.luaentities[id]
4836 luaentity_get(L, id);
4837 int object = lua_gettop(L);
4838 // State: object is at top of stack
4840 lua_getfield(L, -1, "on_rightclick");
4841 if(lua_isnil(L, -1))
4843 luaL_checktype(L, -1, LUA_TFUNCTION);
4844 lua_pushvalue(L, object); // self
4845 objectref_get_or_create(L, clicker); // Clicker reference
4846 // Call with 2 arguments, 0 results
4847 if(lua_pcall(L, 2, 0, 0))
4848 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));