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
653 static void read_privileges(lua_State *L, int index,
654 std::set<std::string> &result)
660 while(lua_next(L, index) != 0){
661 // key at index -2 and value at index -1
662 std::string key = luaL_checkstring(L, -2);
663 bool value = lua_toboolean(L, -1);
666 // removes value, keeps key for next iteration
675 static ToolCapabilities read_tool_capabilities(
676 lua_State *L, int table)
678 ToolCapabilities toolcap;
679 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
680 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
681 lua_getfield(L, table, "groupcaps");
682 if(lua_istable(L, -1)){
683 int table_groupcaps = lua_gettop(L);
685 while(lua_next(L, table_groupcaps) != 0){
686 // key at index -2 and value at index -1
687 std::string groupname = luaL_checkstring(L, -2);
688 if(lua_istable(L, -1)){
689 int table_groupcap = lua_gettop(L);
690 // This will be created
691 ToolGroupCap groupcap;
692 // Read simple parameters
693 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
694 getintfield(L, table_groupcap, "uses", groupcap.uses);
695 // DEPRECATED: maxwear
697 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
699 groupcap.uses = 1.0/maxwear;
702 infostream<<script_get_backtrace(L)<<std::endl;
703 infostream<<"WARNING: field \"maxwear\" is deprecated; "
704 <<"should replace with uses=1/maxwear"<<std::endl;
706 // Read "times" table
707 lua_getfield(L, table_groupcap, "times");
708 if(lua_istable(L, -1)){
709 int table_times = lua_gettop(L);
711 while(lua_next(L, table_times) != 0){
712 // key at index -2 and value at index -1
713 int rating = luaL_checkinteger(L, -2);
714 float time = luaL_checknumber(L, -1);
715 groupcap.times[rating] = time;
716 // removes value, keeps key for next iteration
721 // Insert groupcap into toolcap
722 toolcap.groupcaps[groupname] = groupcap;
724 // removes value, keeps key for next iteration
732 static void set_tool_capabilities(lua_State *L, int table,
733 const ToolCapabilities &toolcap)
735 setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
736 setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
737 // Create groupcaps table
740 for(std::map<std::string, ToolGroupCap>::const_iterator
741 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
742 // Create groupcap table
744 const std::string &name = i->first;
745 const ToolGroupCap &groupcap = i->second;
746 // Create subtable "times"
748 for(std::map<int, float>::const_iterator
749 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
750 int rating = i->first;
751 float time = i->second;
752 lua_pushinteger(L, rating);
753 lua_pushnumber(L, time);
756 // Set subtable "times"
757 lua_setfield(L, -2, "times");
758 // Set simple parameters
759 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
760 setintfield(L, -1, "uses", groupcap.uses);
761 // Insert groupcap table into groupcaps table
762 lua_setfield(L, -2, name.c_str());
764 // Set groupcaps table
765 lua_setfield(L, -2, "groupcaps");
768 static void push_tool_capabilities(lua_State *L,
769 const ToolCapabilities &prop)
772 set_tool_capabilities(L, -1, prop);
779 static void set_dig_params(lua_State *L, int table,
780 const DigParams ¶ms)
782 setboolfield(L, table, "diggable", params.diggable);
783 setfloatfield(L, table, "time", params.time);
784 setintfield(L, table, "wear", params.wear);
787 static void push_dig_params(lua_State *L,
788 const DigParams ¶ms)
791 set_dig_params(L, -1, params);
798 static void set_hit_params(lua_State *L, int table,
799 const HitParams ¶ms)
801 setintfield(L, table, "hp", params.hp);
802 setintfield(L, table, "wear", params.wear);
805 static void push_hit_params(lua_State *L,
806 const HitParams ¶ms)
809 set_hit_params(L, -1, params);
816 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
819 if(pointed.type == POINTEDTHING_NODE)
821 lua_pushstring(L, "node");
822 lua_setfield(L, -2, "type");
823 push_v3s16(L, pointed.node_undersurface);
824 lua_setfield(L, -2, "under");
825 push_v3s16(L, pointed.node_abovesurface);
826 lua_setfield(L, -2, "above");
828 else if(pointed.type == POINTEDTHING_OBJECT)
830 lua_pushstring(L, "object");
831 lua_setfield(L, -2, "type");
832 objectref_get(L, pointed.object_id);
833 lua_setfield(L, -2, "ref");
837 lua_pushstring(L, "nothing");
838 lua_setfield(L, -2, "type");
846 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
849 index = lua_gettop(L) + 1 + index;
850 if(lua_isnil(L, index)){
851 } else if(lua_istable(L, index)){
852 getstringfield(L, index, "name", spec.name);
853 getfloatfield(L, index, "gain", spec.gain);
854 } else if(lua_isstring(L, index)){
855 spec.name = lua_tostring(L, index);
863 static void read_object_properties(lua_State *L, int index,
864 ObjectProperties *prop)
867 index = lua_gettop(L) + 1 + index;
868 if(!lua_istable(L, index))
871 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
873 getboolfield(L, -1, "physical", prop->physical);
875 getfloatfield(L, -1, "weight", prop->weight);
877 lua_getfield(L, -1, "collisionbox");
878 if(lua_istable(L, -1))
879 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
882 getstringfield(L, -1, "visual", prop->visual);
884 lua_getfield(L, -1, "visual_size");
885 if(lua_istable(L, -1))
886 prop->visual_size = read_v2f(L, -1);
889 lua_getfield(L, -1, "textures");
890 if(lua_istable(L, -1)){
891 prop->textures.clear();
892 int table = lua_gettop(L);
894 while(lua_next(L, table) != 0){
895 // key at index -2 and value at index -1
896 if(lua_isstring(L, -1))
897 prop->textures.push_back(lua_tostring(L, -1));
899 prop->textures.push_back("");
900 // removes value, keeps key for next iteration
906 lua_getfield(L, -1, "spritediv");
907 if(lua_istable(L, -1))
908 prop->spritediv = read_v2s16(L, -1);
911 lua_getfield(L, -1, "initial_sprite_basepos");
912 if(lua_istable(L, -1))
913 prop->initial_sprite_basepos = read_v2s16(L, -1);
916 getboolfield(L, -1, "is_visible", prop->is_visible);
917 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
924 static ItemDefinition read_item_definition(lua_State *L, int index)
927 index = lua_gettop(L) + 1 + index;
929 // Read the item definition
932 def.type = (ItemType)getenumfield(L, index, "type",
933 es_ItemType, ITEM_NONE);
934 getstringfield(L, index, "name", def.name);
935 getstringfield(L, index, "description", def.description);
936 getstringfield(L, index, "inventory_image", def.inventory_image);
937 getstringfield(L, index, "wield_image", def.wield_image);
939 lua_getfield(L, index, "wield_scale");
940 if(lua_istable(L, -1)){
941 def.wield_scale = check_v3f(L, -1);
945 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
946 if(def.stack_max == 0)
949 lua_getfield(L, index, "on_use");
950 def.usable = lua_isfunction(L, -1);
953 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
955 warn_if_field_exists(L, index, "tool_digging_properties",
956 "deprecated: use tool_capabilities");
958 lua_getfield(L, index, "tool_capabilities");
959 if(lua_istable(L, -1)){
960 def.tool_capabilities = new ToolCapabilities(
961 read_tool_capabilities(L, -1));
964 // If name is "" (hand), ensure there are ToolCapabilities
965 // because it will be looked up there whenever any other item has
966 // no ToolCapabilities
967 if(def.name == "" && def.tool_capabilities == NULL){
968 def.tool_capabilities = new ToolCapabilities();
971 lua_getfield(L, index, "groups");
972 read_groups(L, -1, def.groups);
982 static ContentFeatures read_content_features(lua_State *L, int index)
985 index = lua_gettop(L) + 1 + index;
989 getstringfield(L, index, "name", f.name);
992 lua_getfield(L, index, "groups");
993 read_groups(L, -1, f.groups);
996 /* Visual definition */
998 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1000 getfloatfield(L, index, "visual_scale", f.visual_scale);
1002 lua_getfield(L, index, "tile_images");
1003 if(lua_istable(L, -1)){
1004 int table = lua_gettop(L);
1007 while(lua_next(L, table) != 0){
1008 // key at index -2 and value at index -1
1009 if(lua_isstring(L, -1))
1010 f.tname_tiles[i] = lua_tostring(L, -1);
1012 f.tname_tiles[i] = "";
1013 // removes value, keeps key for next iteration
1021 // Copy last value to all remaining textures
1023 std::string lastname = f.tname_tiles[i-1];
1025 f.tname_tiles[i] = lastname;
1032 lua_getfield(L, index, "special_materials");
1033 if(lua_istable(L, -1)){
1034 int table = lua_gettop(L);
1037 while(lua_next(L, table) != 0){
1038 // key at index -2 and value at index -1
1039 int smtable = lua_gettop(L);
1040 std::string tname = getstringfield_default(
1041 L, smtable, "image", "");
1042 bool backface_culling = getboolfield_default(
1043 L, smtable, "backface_culling", true);
1044 MaterialSpec mspec(tname, backface_culling);
1045 f.mspec_special[i] = mspec;
1046 // removes value, keeps key for next iteration
1057 f.alpha = getintfield_default(L, index, "alpha", 255);
1061 lua_getfield(L, index, "post_effect_color");
1062 if(!lua_isnil(L, -1))
1063 f.post_effect_color = readARGB8(L, -1);
1066 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1067 es_ContentParamType, CPT_NONE);
1068 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1069 es_ContentParamType2, CPT2_NONE);
1071 // Warn about some deprecated fields
1072 warn_if_field_exists(L, index, "wall_mounted",
1073 "deprecated: use paramtype2 = 'wallmounted'");
1074 warn_if_field_exists(L, index, "light_propagates",
1075 "deprecated: determined from paramtype");
1076 warn_if_field_exists(L, index, "dug_item",
1077 "deprecated: use 'drop' field");
1078 warn_if_field_exists(L, index, "extra_dug_item",
1079 "deprecated: use 'drop' field");
1080 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1081 "deprecated: use 'drop' field");
1083 // True for all ground-like things like stone and mud, false for eg. trees
1084 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1085 f.light_propagates = (f.param_type == CPT_LIGHT);
1086 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1087 // This is used for collision detection.
1088 // Also for general solidness queries.
1089 getboolfield(L, index, "walkable", f.walkable);
1090 // Player can point to these
1091 getboolfield(L, index, "pointable", f.pointable);
1092 // Player can dig these
1093 getboolfield(L, index, "diggable", f.diggable);
1094 // Player can climb these
1095 getboolfield(L, index, "climbable", f.climbable);
1096 // Player can build on these
1097 getboolfield(L, index, "buildable_to", f.buildable_to);
1098 // Metadata name of node (eg. "furnace")
1099 getstringfield(L, index, "metadata_name", f.metadata_name);
1100 // Whether the node is non-liquid, source liquid or flowing liquid
1101 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1102 es_LiquidType, LIQUID_NONE);
1103 // If the content is liquid, this is the flowing version of the liquid.
1104 getstringfield(L, index, "liquid_alternative_flowing",
1105 f.liquid_alternative_flowing);
1106 // If the content is liquid, this is the source version of the liquid.
1107 getstringfield(L, index, "liquid_alternative_source",
1108 f.liquid_alternative_source);
1109 // Viscosity for fluid flow, ranging from 1 to 7, with
1110 // 1 giving almost instantaneous propagation and 7 being
1111 // the slowest possible
1112 f.liquid_viscosity = getintfield_default(L, index,
1113 "liquid_viscosity", f.liquid_viscosity);
1114 // Amount of light the node emits
1115 f.light_source = getintfield_default(L, index,
1116 "light_source", f.light_source);
1117 f.damage_per_second = getintfield_default(L, index,
1118 "damage_per_second", f.damage_per_second);
1120 lua_getfield(L, index, "selection_box");
1121 if(lua_istable(L, -1)){
1122 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1123 es_NodeBoxType, NODEBOX_REGULAR);
1125 lua_getfield(L, -1, "fixed");
1126 if(lua_istable(L, -1))
1127 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1130 lua_getfield(L, -1, "wall_top");
1131 if(lua_istable(L, -1))
1132 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1135 lua_getfield(L, -1, "wall_bottom");
1136 if(lua_istable(L, -1))
1137 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1140 lua_getfield(L, -1, "wall_side");
1141 if(lua_istable(L, -1))
1142 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1147 // Set to true if paramtype used to be 'facedir_simple'
1148 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1149 // Set to true if wall_mounted used to be set to true
1150 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1153 lua_getfield(L, index, "sounds");
1154 if(lua_istable(L, -1)){
1155 lua_getfield(L, -1, "footstep");
1156 read_soundspec(L, -1, f.sound_footstep);
1158 lua_getfield(L, -1, "dig");
1159 read_soundspec(L, -1, f.sound_dig);
1161 lua_getfield(L, -1, "dug");
1162 read_soundspec(L, -1, f.sound_dug);
1174 static ItemStack read_item(lua_State *L, int index);
1176 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1177 lua_State *L, int tableindex, int forcesize=-1)
1180 tableindex = lua_gettop(L) + 1 + tableindex;
1181 // If nil, delete list
1182 if(lua_isnil(L, tableindex)){
1183 inv->deleteList(name);
1186 // Otherwise set list
1187 std::vector<ItemStack> items;
1188 luaL_checktype(L, tableindex, LUA_TTABLE);
1190 while(lua_next(L, tableindex) != 0){
1191 // key at index -2 and value at index -1
1192 items.push_back(read_item(L, -1));
1193 // removes value, keeps key for next iteration
1196 int listsize = (forcesize != -1) ? forcesize : items.size();
1197 InventoryList *invlist = inv->addList(name, listsize);
1199 for(std::vector<ItemStack>::const_iterator
1200 i = items.begin(); i != items.end(); i++){
1201 if(forcesize != -1 && index == forcesize)
1203 invlist->changeItem(index, *i);
1206 while(forcesize != -1 && index < forcesize){
1207 invlist->deleteItem(index);
1212 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1215 InventoryList *invlist = inv->getList(name);
1216 if(invlist == NULL){
1220 // Get the table insert function
1221 lua_getglobal(L, "table");
1222 lua_getfield(L, -1, "insert");
1223 int table_insert = lua_gettop(L);
1224 // Create and fill table
1226 int table = lua_gettop(L);
1227 for(u32 i=0; i<invlist->getSize(); i++){
1228 ItemStack item = invlist->getItem(i);
1229 lua_pushvalue(L, table_insert);
1230 lua_pushvalue(L, table);
1231 lua_pushstring(L, item.getItemString().c_str());
1232 if(lua_pcall(L, 2, 0, 0))
1233 script_error(L, "error: %s", lua_tostring(L, -1));
1238 Helpful macros for userdata classes
1241 #define method(class, name) {#name, class::l_##name}
1252 static const char className[];
1253 static const luaL_reg methods[];
1255 // Exported functions
1257 // garbage collector
1258 static int gc_object(lua_State *L)
1260 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1265 // is_empty(self) -> true/false
1266 static int l_is_empty(lua_State *L)
1268 LuaItemStack *o = checkobject(L, 1);
1269 ItemStack &item = o->m_stack;
1270 lua_pushboolean(L, item.empty());
1274 // get_name(self) -> string
1275 static int l_get_name(lua_State *L)
1277 LuaItemStack *o = checkobject(L, 1);
1278 ItemStack &item = o->m_stack;
1279 lua_pushstring(L, item.name.c_str());
1283 // get_count(self) -> number
1284 static int l_get_count(lua_State *L)
1286 LuaItemStack *o = checkobject(L, 1);
1287 ItemStack &item = o->m_stack;
1288 lua_pushinteger(L, item.count);
1292 // get_wear(self) -> number
1293 static int l_get_wear(lua_State *L)
1295 LuaItemStack *o = checkobject(L, 1);
1296 ItemStack &item = o->m_stack;
1297 lua_pushinteger(L, item.wear);
1301 // get_metadata(self) -> string
1302 static int l_get_metadata(lua_State *L)
1304 LuaItemStack *o = checkobject(L, 1);
1305 ItemStack &item = o->m_stack;
1306 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1310 // clear(self) -> true
1311 static int l_clear(lua_State *L)
1313 LuaItemStack *o = checkobject(L, 1);
1315 lua_pushboolean(L, true);
1319 // replace(self, itemstack or itemstring or table or nil) -> true
1320 static int l_replace(lua_State *L)
1322 LuaItemStack *o = checkobject(L, 1);
1323 o->m_stack = read_item(L, 2);
1324 lua_pushboolean(L, true);
1328 // to_string(self) -> string
1329 static int l_to_string(lua_State *L)
1331 LuaItemStack *o = checkobject(L, 1);
1332 std::string itemstring = o->m_stack.getItemString();
1333 lua_pushstring(L, itemstring.c_str());
1337 // to_table(self) -> table or nil
1338 static int l_to_table(lua_State *L)
1340 LuaItemStack *o = checkobject(L, 1);
1341 const ItemStack &item = o->m_stack;
1349 lua_pushstring(L, item.name.c_str());
1350 lua_setfield(L, -2, "name");
1351 lua_pushinteger(L, item.count);
1352 lua_setfield(L, -2, "count");
1353 lua_pushinteger(L, item.wear);
1354 lua_setfield(L, -2, "wear");
1355 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1356 lua_setfield(L, -2, "metadata");
1361 // get_stack_max(self) -> number
1362 static int l_get_stack_max(lua_State *L)
1364 LuaItemStack *o = checkobject(L, 1);
1365 ItemStack &item = o->m_stack;
1366 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1370 // get_free_space(self) -> number
1371 static int l_get_free_space(lua_State *L)
1373 LuaItemStack *o = checkobject(L, 1);
1374 ItemStack &item = o->m_stack;
1375 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1379 // is_known(self) -> true/false
1380 // Checks if the item is defined.
1381 static int l_is_known(lua_State *L)
1383 LuaItemStack *o = checkobject(L, 1);
1384 ItemStack &item = o->m_stack;
1385 bool is_known = item.isKnown(get_server(L)->idef());
1386 lua_pushboolean(L, is_known);
1390 // get_definition(self) -> table
1391 // Returns the item definition table from minetest.registered_items,
1392 // or a fallback one (name="unknown")
1393 static int l_get_definition(lua_State *L)
1395 LuaItemStack *o = checkobject(L, 1);
1396 ItemStack &item = o->m_stack;
1398 // Get minetest.registered_items[name]
1399 lua_getglobal(L, "minetest");
1400 lua_getfield(L, -1, "registered_items");
1401 luaL_checktype(L, -1, LUA_TTABLE);
1402 lua_getfield(L, -1, item.name.c_str());
1403 if(lua_isnil(L, -1))
1406 lua_getfield(L, -1, "unknown");
1411 // get_tool_capabilities(self) -> table
1412 // Returns the effective tool digging properties.
1413 // Returns those of the hand ("") if this item has none associated.
1414 static int l_get_tool_capabilities(lua_State *L)
1416 LuaItemStack *o = checkobject(L, 1);
1417 ItemStack &item = o->m_stack;
1418 const ToolCapabilities &prop =
1419 item.getToolCapabilities(get_server(L)->idef());
1420 push_tool_capabilities(L, prop);
1424 // add_wear(self, amount) -> true/false
1425 // The range for "amount" is [0,65535]. Wear is only added if the item
1426 // is a tool. Adding wear might destroy the item.
1427 // Returns true if the item is (or was) a tool.
1428 static int l_add_wear(lua_State *L)
1430 LuaItemStack *o = checkobject(L, 1);
1431 ItemStack &item = o->m_stack;
1432 int amount = lua_tointeger(L, 2);
1433 bool result = item.addWear(amount, get_server(L)->idef());
1434 lua_pushboolean(L, result);
1438 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1439 // Returns leftover item stack
1440 static int l_add_item(lua_State *L)
1442 LuaItemStack *o = checkobject(L, 1);
1443 ItemStack &item = o->m_stack;
1444 ItemStack newitem = read_item(L, 2);
1445 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1446 create(L, leftover);
1450 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1451 // First return value is true iff the new item fits fully into the stack
1452 // Second return value is the would-be-left-over item stack
1453 static int l_item_fits(lua_State *L)
1455 LuaItemStack *o = checkobject(L, 1);
1456 ItemStack &item = o->m_stack;
1457 ItemStack newitem = read_item(L, 2);
1459 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1460 lua_pushboolean(L, fits); // first return value
1461 create(L, restitem); // second return value
1465 // take_item(self, takecount=1) -> itemstack
1466 static int l_take_item(lua_State *L)
1468 LuaItemStack *o = checkobject(L, 1);
1469 ItemStack &item = o->m_stack;
1471 if(!lua_isnone(L, 2))
1472 takecount = lua_tointeger(L, 2);
1473 ItemStack taken = item.takeItem(takecount);
1478 // peek_item(self, peekcount=1) -> itemstack
1479 static int l_peek_item(lua_State *L)
1481 LuaItemStack *o = checkobject(L, 1);
1482 ItemStack &item = o->m_stack;
1484 if(!lua_isnone(L, 2))
1485 peekcount = lua_tointeger(L, 2);
1486 ItemStack peekaboo = item.peekItem(peekcount);
1487 create(L, peekaboo);
1492 LuaItemStack(const ItemStack &item):
1501 const ItemStack& getItem() const
1505 ItemStack& getItem()
1510 // LuaItemStack(itemstack or itemstring or table or nil)
1511 // Creates an LuaItemStack and leaves it on top of stack
1512 static int create_object(lua_State *L)
1514 ItemStack item = read_item(L, 1);
1515 LuaItemStack *o = new LuaItemStack(item);
1516 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1517 luaL_getmetatable(L, className);
1518 lua_setmetatable(L, -2);
1521 // Not callable from Lua
1522 static int create(lua_State *L, const ItemStack &item)
1524 LuaItemStack *o = new LuaItemStack(item);
1525 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1526 luaL_getmetatable(L, className);
1527 lua_setmetatable(L, -2);
1531 static LuaItemStack* checkobject(lua_State *L, int narg)
1533 luaL_checktype(L, narg, LUA_TUSERDATA);
1534 void *ud = luaL_checkudata(L, narg, className);
1535 if(!ud) luaL_typerror(L, narg, className);
1536 return *(LuaItemStack**)ud; // unbox pointer
1539 static void Register(lua_State *L)
1542 int methodtable = lua_gettop(L);
1543 luaL_newmetatable(L, className);
1544 int metatable = lua_gettop(L);
1546 lua_pushliteral(L, "__metatable");
1547 lua_pushvalue(L, methodtable);
1548 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1550 lua_pushliteral(L, "__index");
1551 lua_pushvalue(L, methodtable);
1552 lua_settable(L, metatable);
1554 lua_pushliteral(L, "__gc");
1555 lua_pushcfunction(L, gc_object);
1556 lua_settable(L, metatable);
1558 lua_pop(L, 1); // drop metatable
1560 luaL_openlib(L, 0, methods, 0); // fill methodtable
1561 lua_pop(L, 1); // drop methodtable
1563 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1564 lua_register(L, className, create_object);
1567 const char LuaItemStack::className[] = "ItemStack";
1568 const luaL_reg LuaItemStack::methods[] = {
1569 method(LuaItemStack, is_empty),
1570 method(LuaItemStack, get_name),
1571 method(LuaItemStack, get_count),
1572 method(LuaItemStack, get_wear),
1573 method(LuaItemStack, get_metadata),
1574 method(LuaItemStack, clear),
1575 method(LuaItemStack, replace),
1576 method(LuaItemStack, to_string),
1577 method(LuaItemStack, to_table),
1578 method(LuaItemStack, get_stack_max),
1579 method(LuaItemStack, get_free_space),
1580 method(LuaItemStack, is_known),
1581 method(LuaItemStack, get_definition),
1582 method(LuaItemStack, get_tool_capabilities),
1583 method(LuaItemStack, add_wear),
1584 method(LuaItemStack, add_item),
1585 method(LuaItemStack, item_fits),
1586 method(LuaItemStack, take_item),
1587 method(LuaItemStack, peek_item),
1591 static ItemStack read_item(lua_State *L, int index)
1594 index = lua_gettop(L) + 1 + index;
1596 if(lua_isnil(L, index))
1600 else if(lua_isuserdata(L, index))
1602 // Convert from LuaItemStack
1603 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1604 return o->getItem();
1606 else if(lua_isstring(L, index))
1608 // Convert from itemstring
1609 std::string itemstring = lua_tostring(L, index);
1610 IItemDefManager *idef = get_server(L)->idef();
1614 item.deSerialize(itemstring, idef);
1617 catch(SerializationError &e)
1619 infostream<<"WARNING: unable to create item from itemstring"
1620 <<": "<<itemstring<<std::endl;
1624 else if(lua_istable(L, index))
1626 // Convert from table
1627 IItemDefManager *idef = get_server(L)->idef();
1628 std::string name = getstringfield_default(L, index, "name", "");
1629 int count = getintfield_default(L, index, "count", 1);
1630 int wear = getintfield_default(L, index, "wear", 0);
1631 std::string metadata = getstringfield_default(L, index, "metadata", "");
1632 return ItemStack(name, count, wear, metadata, idef);
1636 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1647 InventoryLocation m_loc;
1649 static const char className[];
1650 static const luaL_reg methods[];
1652 static InvRef *checkobject(lua_State *L, int narg)
1654 luaL_checktype(L, narg, LUA_TUSERDATA);
1655 void *ud = luaL_checkudata(L, narg, className);
1656 if(!ud) luaL_typerror(L, narg, className);
1657 return *(InvRef**)ud; // unbox pointer
1660 static Inventory* getinv(lua_State *L, InvRef *ref)
1662 return get_server(L)->getInventory(ref->m_loc);
1665 static InventoryList* getlist(lua_State *L, InvRef *ref,
1666 const char *listname)
1668 Inventory *inv = getinv(L, ref);
1671 return inv->getList(listname);
1674 static void reportInventoryChange(lua_State *L, InvRef *ref)
1676 // Inform other things that the inventory has changed
1677 get_server(L)->setInventoryModified(ref->m_loc);
1680 // Exported functions
1682 // garbage collector
1683 static int gc_object(lua_State *L) {
1684 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1689 // get_size(self, listname)
1690 static int l_get_size(lua_State *L)
1692 InvRef *ref = checkobject(L, 1);
1693 const char *listname = luaL_checkstring(L, 2);
1694 InventoryList *list = getlist(L, ref, listname);
1696 lua_pushinteger(L, list->getSize());
1698 lua_pushinteger(L, 0);
1703 // set_size(self, listname, size)
1704 static int l_set_size(lua_State *L)
1706 InvRef *ref = checkobject(L, 1);
1707 const char *listname = luaL_checkstring(L, 2);
1708 int newsize = luaL_checknumber(L, 3);
1709 Inventory *inv = getinv(L, ref);
1711 inv->deleteList(listname);
1712 reportInventoryChange(L, ref);
1715 InventoryList *list = inv->getList(listname);
1717 list->setSize(newsize);
1719 list = inv->addList(listname, newsize);
1721 reportInventoryChange(L, ref);
1725 // get_stack(self, listname, i) -> itemstack
1726 static int l_get_stack(lua_State *L)
1728 InvRef *ref = checkobject(L, 1);
1729 const char *listname = luaL_checkstring(L, 2);
1730 int i = luaL_checknumber(L, 3) - 1;
1731 InventoryList *list = getlist(L, ref, listname);
1733 if(list != NULL && i >= 0 && i < (int) list->getSize())
1734 item = list->getItem(i);
1735 LuaItemStack::create(L, item);
1739 // set_stack(self, listname, i, stack) -> true/false
1740 static int l_set_stack(lua_State *L)
1742 InvRef *ref = checkobject(L, 1);
1743 const char *listname = luaL_checkstring(L, 2);
1744 int i = luaL_checknumber(L, 3) - 1;
1745 ItemStack newitem = read_item(L, 4);
1746 InventoryList *list = getlist(L, ref, listname);
1747 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1748 list->changeItem(i, newitem);
1749 reportInventoryChange(L, ref);
1750 lua_pushboolean(L, true);
1752 lua_pushboolean(L, false);
1757 // get_list(self, listname) -> list or nil
1758 static int l_get_list(lua_State *L)
1760 InvRef *ref = checkobject(L, 1);
1761 const char *listname = luaL_checkstring(L, 2);
1762 Inventory *inv = getinv(L, ref);
1763 inventory_get_list_to_lua(inv, listname, L);
1767 // set_list(self, listname, list)
1768 static int l_set_list(lua_State *L)
1770 InvRef *ref = checkobject(L, 1);
1771 const char *listname = luaL_checkstring(L, 2);
1772 Inventory *inv = getinv(L, ref);
1773 InventoryList *list = inv->getList(listname);
1775 inventory_set_list_from_lua(inv, listname, L, 3,
1778 inventory_set_list_from_lua(inv, listname, L, 3);
1779 reportInventoryChange(L, ref);
1783 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1784 // Returns the leftover stack
1785 static int l_add_item(lua_State *L)
1787 InvRef *ref = checkobject(L, 1);
1788 const char *listname = luaL_checkstring(L, 2);
1789 ItemStack item = read_item(L, 3);
1790 InventoryList *list = getlist(L, ref, listname);
1792 ItemStack leftover = list->addItem(item);
1793 if(leftover.count != item.count)
1794 reportInventoryChange(L, ref);
1795 LuaItemStack::create(L, leftover);
1797 LuaItemStack::create(L, item);
1802 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1803 // Returns true if the item completely fits into the list
1804 static int l_room_for_item(lua_State *L)
1806 InvRef *ref = checkobject(L, 1);
1807 const char *listname = luaL_checkstring(L, 2);
1808 ItemStack item = read_item(L, 3);
1809 InventoryList *list = getlist(L, ref, listname);
1811 lua_pushboolean(L, list->roomForItem(item));
1813 lua_pushboolean(L, false);
1818 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1819 // Returns true if the list contains the given count of the given item name
1820 static int l_contains_item(lua_State *L)
1822 InvRef *ref = checkobject(L, 1);
1823 const char *listname = luaL_checkstring(L, 2);
1824 ItemStack item = read_item(L, 3);
1825 InventoryList *list = getlist(L, ref, listname);
1827 lua_pushboolean(L, list->containsItem(item));
1829 lua_pushboolean(L, false);
1834 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1835 // Returns the items that were actually removed
1836 static int l_remove_item(lua_State *L)
1838 InvRef *ref = checkobject(L, 1);
1839 const char *listname = luaL_checkstring(L, 2);
1840 ItemStack item = read_item(L, 3);
1841 InventoryList *list = getlist(L, ref, listname);
1843 ItemStack removed = list->removeItem(item);
1844 if(!removed.empty())
1845 reportInventoryChange(L, ref);
1846 LuaItemStack::create(L, removed);
1848 LuaItemStack::create(L, ItemStack());
1854 InvRef(const InventoryLocation &loc):
1863 // Creates an InvRef and leaves it on top of stack
1864 // Not callable from Lua; all references are created on the C side.
1865 static void create(lua_State *L, const InventoryLocation &loc)
1867 InvRef *o = new InvRef(loc);
1868 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1869 luaL_getmetatable(L, className);
1870 lua_setmetatable(L, -2);
1872 static void createPlayer(lua_State *L, Player *player)
1874 InventoryLocation loc;
1875 loc.setPlayer(player->getName());
1878 static void createNodeMeta(lua_State *L, v3s16 p)
1880 InventoryLocation loc;
1885 static void Register(lua_State *L)
1888 int methodtable = lua_gettop(L);
1889 luaL_newmetatable(L, className);
1890 int metatable = lua_gettop(L);
1892 lua_pushliteral(L, "__metatable");
1893 lua_pushvalue(L, methodtable);
1894 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1896 lua_pushliteral(L, "__index");
1897 lua_pushvalue(L, methodtable);
1898 lua_settable(L, metatable);
1900 lua_pushliteral(L, "__gc");
1901 lua_pushcfunction(L, gc_object);
1902 lua_settable(L, metatable);
1904 lua_pop(L, 1); // drop metatable
1906 luaL_openlib(L, 0, methods, 0); // fill methodtable
1907 lua_pop(L, 1); // drop methodtable
1909 // Cannot be created from Lua
1910 //lua_register(L, className, create_object);
1913 const char InvRef::className[] = "InvRef";
1914 const luaL_reg InvRef::methods[] = {
1915 method(InvRef, get_size),
1916 method(InvRef, set_size),
1917 method(InvRef, get_stack),
1918 method(InvRef, set_stack),
1919 method(InvRef, get_list),
1920 method(InvRef, set_list),
1921 method(InvRef, add_item),
1922 method(InvRef, room_for_item),
1923 method(InvRef, contains_item),
1924 method(InvRef, remove_item),
1936 ServerEnvironment *m_env;
1938 static const char className[];
1939 static const luaL_reg methods[];
1941 static NodeMetaRef *checkobject(lua_State *L, int narg)
1943 luaL_checktype(L, narg, LUA_TUSERDATA);
1944 void *ud = luaL_checkudata(L, narg, className);
1945 if(!ud) luaL_typerror(L, narg, className);
1946 return *(NodeMetaRef**)ud; // unbox pointer
1949 static NodeMetadata* getmeta(NodeMetaRef *ref)
1951 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1955 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1957 NodeMetadata *meta = getmeta(ref);
1960 if(meta->typeId() != NODEMETA_GENERIC)
1962 return (IGenericNodeMetadata*)meta;
1965 static void reportMetadataChange(NodeMetaRef *ref)
1967 // Inform other things that the metadata has changed
1968 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1970 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1972 ref->m_env->getMap().dispatchEvent(&event);
1973 // Set the block to be saved
1974 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1976 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1977 "NodeMetaRef::reportMetadataChange");
1980 // Exported functions
1982 // garbage collector
1983 static int gc_object(lua_State *L) {
1984 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1990 static int l_get_type(lua_State *L)
1992 NodeMetaRef *ref = checkobject(L, 1);
1993 NodeMetadata *meta = getmeta(ref);
1999 lua_pushstring(L, meta->typeName());
2003 // allows_text_input(self)
2004 static int l_allows_text_input(lua_State *L)
2006 NodeMetaRef *ref = checkobject(L, 1);
2007 NodeMetadata *meta = getmeta(ref);
2008 if(meta == NULL) return 0;
2010 lua_pushboolean(L, meta->allowsTextInput());
2014 // set_text(self, text)
2015 static int l_set_text(lua_State *L)
2017 NodeMetaRef *ref = checkobject(L, 1);
2018 NodeMetadata *meta = getmeta(ref);
2019 if(meta == NULL) return 0;
2021 std::string text = luaL_checkstring(L, 2);
2022 meta->setText(text);
2023 reportMetadataChange(ref);
2028 static int l_get_text(lua_State *L)
2030 NodeMetaRef *ref = checkobject(L, 1);
2031 NodeMetadata *meta = getmeta(ref);
2032 if(meta == NULL) return 0;
2034 std::string text = meta->getText();
2035 lua_pushstring(L, text.c_str());
2040 static int l_get_owner(lua_State *L)
2042 NodeMetaRef *ref = checkobject(L, 1);
2043 NodeMetadata *meta = getmeta(ref);
2044 if(meta == NULL) return 0;
2046 std::string owner = meta->getOwner();
2047 lua_pushstring(L, owner.c_str());
2051 // set_owner(self, string)
2052 static int l_set_owner(lua_State *L)
2054 NodeMetaRef *ref = checkobject(L, 1);
2055 NodeMetadata *meta = getmeta(ref);
2056 if(meta == NULL) return 0;
2058 std::string owner = luaL_checkstring(L, 2);
2059 meta->setOwner(owner);
2060 reportMetadataChange(ref);
2064 // get_allow_removal(self)
2065 static int l_get_allow_removal(lua_State *L)
2067 NodeMetaRef *ref = checkobject(L, 1);
2068 NodeMetadata *meta = getmeta(ref);
2070 lua_pushboolean(L, true);
2074 lua_pushboolean(L, !meta->nodeRemovalDisabled());
2078 /* IGenericNodeMetadata interface */
2080 // set_infotext(self, text)
2081 static int l_set_infotext(lua_State *L)
2083 NodeMetaRef *ref = checkobject(L, 1);
2084 NodeMetadata *meta = getmeta(ref);
2085 if(meta == NULL) return 0;
2087 std::string text = luaL_checkstring(L, 2);
2088 meta->setInfoText(text);
2089 reportMetadataChange(ref);
2093 // get_inventory(self)
2094 static int l_get_inventory(lua_State *L)
2096 NodeMetaRef *ref = checkobject(L, 1);
2097 NodeMetadata *meta = getmeta(ref);
2098 if(meta == NULL) return 0;
2100 InvRef::createNodeMeta(L, ref->m_p);
2104 // set_inventory_draw_spec(self, text)
2105 static int l_set_inventory_draw_spec(lua_State *L)
2107 NodeMetaRef *ref = checkobject(L, 1);
2108 NodeMetadata *meta = getmeta(ref);
2109 if(meta == NULL) return 0;
2111 std::string text = luaL_checkstring(L, 2);
2112 meta->setInventoryDrawSpec(text);
2113 reportMetadataChange(ref);
2117 // set_allow_text_input(self, text)
2118 static int l_set_allow_text_input(lua_State *L)
2120 NodeMetaRef *ref = checkobject(L, 1);
2121 NodeMetadata *meta = getmeta(ref);
2122 if(meta == NULL) return 0;
2124 bool b = lua_toboolean(L, 2);
2125 meta->setAllowTextInput(b);
2126 reportMetadataChange(ref);
2130 // set_allow_removal(self, text)
2131 static int l_set_allow_removal(lua_State *L)
2133 NodeMetaRef *ref = checkobject(L, 1);
2134 NodeMetadata *meta = getmeta(ref);
2135 if(meta == NULL) return 0;
2137 bool b = lua_toboolean(L, 2);
2138 meta->setRemovalDisabled(!b);
2139 reportMetadataChange(ref);
2143 // set_enforce_owner(self, text)
2144 static int l_set_enforce_owner(lua_State *L)
2146 NodeMetaRef *ref = checkobject(L, 1);
2147 NodeMetadata *meta = getmeta(ref);
2148 if(meta == NULL) return 0;
2150 bool b = lua_toboolean(L, 2);
2151 meta->setEnforceOwner(b);
2152 reportMetadataChange(ref);
2156 // is_inventory_modified(self)
2157 static int l_is_inventory_modified(lua_State *L)
2159 NodeMetaRef *ref = checkobject(L, 1);
2160 NodeMetadata *meta = getmeta(ref);
2161 if(meta == NULL) return 0;
2163 lua_pushboolean(L, meta->isInventoryModified());
2167 // reset_inventory_modified(self)
2168 static int l_reset_inventory_modified(lua_State *L)
2170 NodeMetaRef *ref = checkobject(L, 1);
2171 NodeMetadata *meta = getmeta(ref);
2172 if(meta == NULL) return 0;
2174 meta->resetInventoryModified();
2175 reportMetadataChange(ref);
2179 // is_text_modified(self)
2180 static int l_is_text_modified(lua_State *L)
2182 NodeMetaRef *ref = checkobject(L, 1);
2183 NodeMetadata *meta = getmeta(ref);
2184 if(meta == NULL) return 0;
2186 lua_pushboolean(L, meta->isTextModified());
2190 // reset_text_modified(self)
2191 static int l_reset_text_modified(lua_State *L)
2193 NodeMetaRef *ref = checkobject(L, 1);
2194 NodeMetadata *meta = getmeta(ref);
2195 if(meta == NULL) return 0;
2197 meta->resetTextModified();
2198 reportMetadataChange(ref);
2202 // set_string(self, name, var)
2203 static int l_set_string(lua_State *L)
2205 NodeMetaRef *ref = checkobject(L, 1);
2206 NodeMetadata *meta = getmeta(ref);
2207 if(meta == NULL) return 0;
2209 std::string name = luaL_checkstring(L, 2);
2211 const char *s = lua_tolstring(L, 3, &len);
2212 std::string str(s, len);
2213 meta->setString(name, str);
2214 reportMetadataChange(ref);
2218 // get_string(self, name)
2219 static int l_get_string(lua_State *L)
2221 NodeMetaRef *ref = checkobject(L, 1);
2222 NodeMetadata *meta = getmeta(ref);
2223 if(meta == NULL) return 0;
2225 std::string name = luaL_checkstring(L, 2);
2226 std::string str = meta->getString(name);
2227 lua_pushlstring(L, str.c_str(), str.size());
2232 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2242 // Creates an NodeMetaRef and leaves it on top of stack
2243 // Not callable from Lua; all references are created on the C side.
2244 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2246 NodeMetaRef *o = new NodeMetaRef(p, env);
2247 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2248 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2249 luaL_getmetatable(L, className);
2250 lua_setmetatable(L, -2);
2253 static void Register(lua_State *L)
2256 int methodtable = lua_gettop(L);
2257 luaL_newmetatable(L, className);
2258 int metatable = lua_gettop(L);
2260 lua_pushliteral(L, "__metatable");
2261 lua_pushvalue(L, methodtable);
2262 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2264 lua_pushliteral(L, "__index");
2265 lua_pushvalue(L, methodtable);
2266 lua_settable(L, metatable);
2268 lua_pushliteral(L, "__gc");
2269 lua_pushcfunction(L, gc_object);
2270 lua_settable(L, metatable);
2272 lua_pop(L, 1); // drop metatable
2274 luaL_openlib(L, 0, methods, 0); // fill methodtable
2275 lua_pop(L, 1); // drop methodtable
2277 // Cannot be created from Lua
2278 //lua_register(L, className, create_object);
2281 const char NodeMetaRef::className[] = "NodeMetaRef";
2282 const luaL_reg NodeMetaRef::methods[] = {
2283 method(NodeMetaRef, get_type),
2284 method(NodeMetaRef, allows_text_input),
2285 method(NodeMetaRef, set_text),
2286 method(NodeMetaRef, get_text),
2287 method(NodeMetaRef, get_owner),
2288 method(NodeMetaRef, set_owner),
2289 method(NodeMetaRef, get_allow_removal),
2290 method(NodeMetaRef, set_infotext),
2291 method(NodeMetaRef, get_inventory),
2292 method(NodeMetaRef, set_inventory_draw_spec),
2293 method(NodeMetaRef, set_allow_text_input),
2294 method(NodeMetaRef, set_allow_removal),
2295 method(NodeMetaRef, set_enforce_owner),
2296 method(NodeMetaRef, is_inventory_modified),
2297 method(NodeMetaRef, reset_inventory_modified),
2298 method(NodeMetaRef, is_text_modified),
2299 method(NodeMetaRef, reset_text_modified),
2300 method(NodeMetaRef, set_string),
2301 method(NodeMetaRef, get_string),
2312 ServerActiveObject *m_object;
2314 static const char className[];
2315 static const luaL_reg methods[];
2317 static ObjectRef *checkobject(lua_State *L, int narg)
2319 luaL_checktype(L, narg, LUA_TUSERDATA);
2320 void *ud = luaL_checkudata(L, narg, className);
2321 if(!ud) luaL_typerror(L, narg, className);
2322 return *(ObjectRef**)ud; // unbox pointer
2325 static ServerActiveObject* getobject(ObjectRef *ref)
2327 ServerActiveObject *co = ref->m_object;
2331 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2333 ServerActiveObject *obj = getobject(ref);
2336 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2338 return (LuaEntitySAO*)obj;
2341 static PlayerSAO* getplayersao(ObjectRef *ref)
2343 ServerActiveObject *obj = getobject(ref);
2346 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2348 return (PlayerSAO*)obj;
2351 static Player* getplayer(ObjectRef *ref)
2353 PlayerSAO *playersao = getplayersao(ref);
2354 if(playersao == NULL)
2356 return playersao->getPlayer();
2359 // Exported functions
2361 // garbage collector
2362 static int gc_object(lua_State *L) {
2363 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2364 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2370 static int l_remove(lua_State *L)
2372 ObjectRef *ref = checkobject(L, 1);
2373 ServerActiveObject *co = getobject(ref);
2374 if(co == NULL) return 0;
2375 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2376 co->m_removed = true;
2381 // returns: {x=num, y=num, z=num}
2382 static int l_getpos(lua_State *L)
2384 ObjectRef *ref = checkobject(L, 1);
2385 ServerActiveObject *co = getobject(ref);
2386 if(co == NULL) return 0;
2387 v3f pos = co->getBasePosition() / BS;
2389 lua_pushnumber(L, pos.X);
2390 lua_setfield(L, -2, "x");
2391 lua_pushnumber(L, pos.Y);
2392 lua_setfield(L, -2, "y");
2393 lua_pushnumber(L, pos.Z);
2394 lua_setfield(L, -2, "z");
2398 // setpos(self, pos)
2399 static int l_setpos(lua_State *L)
2401 ObjectRef *ref = checkobject(L, 1);
2402 //LuaEntitySAO *co = getluaobject(ref);
2403 ServerActiveObject *co = getobject(ref);
2404 if(co == NULL) return 0;
2406 v3f pos = checkFloatPos(L, 2);
2412 // moveto(self, pos, continuous=false)
2413 static int l_moveto(lua_State *L)
2415 ObjectRef *ref = checkobject(L, 1);
2416 //LuaEntitySAO *co = getluaobject(ref);
2417 ServerActiveObject *co = getobject(ref);
2418 if(co == NULL) return 0;
2420 v3f pos = checkFloatPos(L, 2);
2422 bool continuous = lua_toboolean(L, 3);
2424 co->moveTo(pos, continuous);
2428 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2429 static int l_punch(lua_State *L)
2431 ObjectRef *ref = checkobject(L, 1);
2432 ObjectRef *puncher_ref = checkobject(L, 2);
2433 ServerActiveObject *co = getobject(ref);
2434 ServerActiveObject *puncher = getobject(puncher_ref);
2435 if(co == NULL) return 0;
2436 if(puncher == NULL) return 0;
2437 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2438 v3f dir = read_v3f(L, 4);
2439 float time_from_last_punch = 1000000;
2440 if(lua_isnumber(L, 5))
2441 time_from_last_punch = lua_tonumber(L, 5);
2443 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2447 // right_click(self, clicker); clicker = an another ObjectRef
2448 static int l_right_click(lua_State *L)
2450 ObjectRef *ref = checkobject(L, 1);
2451 ObjectRef *ref2 = checkobject(L, 2);
2452 ServerActiveObject *co = getobject(ref);
2453 ServerActiveObject *co2 = getobject(ref2);
2454 if(co == NULL) return 0;
2455 if(co2 == NULL) return 0;
2457 co->rightClick(co2);
2462 // hp = number of hitpoints (2 * number of hearts)
2464 static int l_set_hp(lua_State *L)
2466 ObjectRef *ref = checkobject(L, 1);
2467 luaL_checknumber(L, 2);
2468 ServerActiveObject *co = getobject(ref);
2469 if(co == NULL) return 0;
2470 int hp = lua_tonumber(L, 2);
2471 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2472 <<" hp="<<hp<<std::endl;*/
2480 // returns: number of hitpoints (2 * number of hearts)
2481 // 0 if not applicable to this type of object
2482 static int l_get_hp(lua_State *L)
2484 ObjectRef *ref = checkobject(L, 1);
2485 ServerActiveObject *co = getobject(ref);
2486 if(co == NULL) return 0;
2487 int hp = co->getHP();
2488 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2489 <<" hp="<<hp<<std::endl;*/
2491 lua_pushnumber(L, hp);
2495 // get_inventory(self)
2496 static int l_get_inventory(lua_State *L)
2498 ObjectRef *ref = checkobject(L, 1);
2499 ServerActiveObject *co = getobject(ref);
2500 if(co == NULL) return 0;
2502 InventoryLocation loc = co->getInventoryLocation();
2503 if(get_server(L)->getInventory(loc) != NULL)
2504 InvRef::create(L, loc);
2510 // get_wield_list(self)
2511 static int l_get_wield_list(lua_State *L)
2513 ObjectRef *ref = checkobject(L, 1);
2514 ServerActiveObject *co = getobject(ref);
2515 if(co == NULL) return 0;
2517 lua_pushstring(L, co->getWieldList().c_str());
2521 // get_wield_index(self)
2522 static int l_get_wield_index(lua_State *L)
2524 ObjectRef *ref = checkobject(L, 1);
2525 ServerActiveObject *co = getobject(ref);
2526 if(co == NULL) return 0;
2528 lua_pushinteger(L, co->getWieldIndex() + 1);
2532 // get_wielded_item(self)
2533 static int l_get_wielded_item(lua_State *L)
2535 ObjectRef *ref = checkobject(L, 1);
2536 ServerActiveObject *co = getobject(ref);
2537 if(co == NULL) return 0;
2539 LuaItemStack::create(L, co->getWieldedItem());
2543 // set_wielded_item(self, itemstack or itemstring or table or nil)
2544 static int l_set_wielded_item(lua_State *L)
2546 ObjectRef *ref = checkobject(L, 1);
2547 ServerActiveObject *co = getobject(ref);
2548 if(co == NULL) return 0;
2550 ItemStack item = read_item(L, 2);
2551 bool success = co->setWieldedItem(item);
2552 lua_pushboolean(L, success);
2556 // set_armor_groups(self, groups)
2557 static int l_set_armor_groups(lua_State *L)
2559 ObjectRef *ref = checkobject(L, 1);
2560 ServerActiveObject *co = getobject(ref);
2561 if(co == NULL) return 0;
2563 ItemGroupList groups;
2564 read_groups(L, 2, groups);
2565 co->setArmorGroups(groups);
2569 // set_properties(self, properties)
2570 static int l_set_properties(lua_State *L)
2572 ObjectRef *ref = checkobject(L, 1);
2573 ServerActiveObject *co = getobject(ref);
2574 if(co == NULL) return 0;
2575 ObjectProperties *prop = co->accessObjectProperties();
2578 read_object_properties(L, 2, prop);
2579 co->notifyObjectPropertiesModified();
2583 /* LuaEntitySAO-only */
2585 // setvelocity(self, {x=num, y=num, z=num})
2586 static int l_setvelocity(lua_State *L)
2588 ObjectRef *ref = checkobject(L, 1);
2589 LuaEntitySAO *co = getluaobject(ref);
2590 if(co == NULL) return 0;
2591 v3f pos = checkFloatPos(L, 2);
2593 co->setVelocity(pos);
2597 // getvelocity(self)
2598 static int l_getvelocity(lua_State *L)
2600 ObjectRef *ref = checkobject(L, 1);
2601 LuaEntitySAO *co = getluaobject(ref);
2602 if(co == NULL) return 0;
2604 v3f v = co->getVelocity();
2609 // setacceleration(self, {x=num, y=num, z=num})
2610 static int l_setacceleration(lua_State *L)
2612 ObjectRef *ref = checkobject(L, 1);
2613 LuaEntitySAO *co = getluaobject(ref);
2614 if(co == NULL) return 0;
2616 v3f pos = checkFloatPos(L, 2);
2618 co->setAcceleration(pos);
2622 // getacceleration(self)
2623 static int l_getacceleration(lua_State *L)
2625 ObjectRef *ref = checkobject(L, 1);
2626 LuaEntitySAO *co = getluaobject(ref);
2627 if(co == NULL) return 0;
2629 v3f v = co->getAcceleration();
2634 // setyaw(self, radians)
2635 static int l_setyaw(lua_State *L)
2637 ObjectRef *ref = checkobject(L, 1);
2638 LuaEntitySAO *co = getluaobject(ref);
2639 if(co == NULL) return 0;
2640 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2647 static int l_getyaw(lua_State *L)
2649 ObjectRef *ref = checkobject(L, 1);
2650 LuaEntitySAO *co = getluaobject(ref);
2651 if(co == NULL) return 0;
2653 float yaw = co->getYaw() * core::DEGTORAD;
2654 lua_pushnumber(L, yaw);
2658 // settexturemod(self, mod)
2659 static int l_settexturemod(lua_State *L)
2661 ObjectRef *ref = checkobject(L, 1);
2662 LuaEntitySAO *co = getluaobject(ref);
2663 if(co == NULL) return 0;
2665 std::string mod = luaL_checkstring(L, 2);
2666 co->setTextureMod(mod);
2670 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2671 // select_horiz_by_yawpitch=false)
2672 static int l_setsprite(lua_State *L)
2674 ObjectRef *ref = checkobject(L, 1);
2675 LuaEntitySAO *co = getluaobject(ref);
2676 if(co == NULL) return 0;
2679 if(!lua_isnil(L, 2))
2680 p = read_v2s16(L, 2);
2682 if(!lua_isnil(L, 3))
2683 num_frames = lua_tonumber(L, 3);
2684 float framelength = 0.2;
2685 if(!lua_isnil(L, 4))
2686 framelength = lua_tonumber(L, 4);
2687 bool select_horiz_by_yawpitch = false;
2688 if(!lua_isnil(L, 5))
2689 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2690 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2695 // get_entity_name(self)
2696 static int l_get_entity_name(lua_State *L)
2698 ObjectRef *ref = checkobject(L, 1);
2699 LuaEntitySAO *co = getluaobject(ref);
2700 if(co == NULL) return 0;
2702 std::string name = co->getName();
2703 lua_pushstring(L, name.c_str());
2707 // get_luaentity(self)
2708 static int l_get_luaentity(lua_State *L)
2710 ObjectRef *ref = checkobject(L, 1);
2711 LuaEntitySAO *co = getluaobject(ref);
2712 if(co == NULL) return 0;
2714 luaentity_get(L, co->getId());
2720 // get_player_name(self)
2721 static int l_get_player_name(lua_State *L)
2723 ObjectRef *ref = checkobject(L, 1);
2724 Player *player = getplayer(ref);
2730 lua_pushstring(L, player->getName());
2734 // get_look_dir(self)
2735 static int l_get_look_dir(lua_State *L)
2737 ObjectRef *ref = checkobject(L, 1);
2738 Player *player = getplayer(ref);
2739 if(player == NULL) return 0;
2741 float pitch = player->getRadPitch();
2742 float yaw = player->getRadYaw();
2743 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2748 // get_look_pitch(self)
2749 static int l_get_look_pitch(lua_State *L)
2751 ObjectRef *ref = checkobject(L, 1);
2752 Player *player = getplayer(ref);
2753 if(player == NULL) return 0;
2755 lua_pushnumber(L, player->getRadPitch());
2759 // get_look_yaw(self)
2760 static int l_get_look_yaw(lua_State *L)
2762 ObjectRef *ref = checkobject(L, 1);
2763 Player *player = getplayer(ref);
2764 if(player == NULL) return 0;
2766 lua_pushnumber(L, player->getRadYaw());
2771 ObjectRef(ServerActiveObject *object):
2774 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2780 infostream<<"ObjectRef destructing for id="
2781 <<m_object->getId()<<std::endl;
2783 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2786 // Creates an ObjectRef and leaves it on top of stack
2787 // Not callable from Lua; all references are created on the C side.
2788 static void create(lua_State *L, ServerActiveObject *object)
2790 ObjectRef *o = new ObjectRef(object);
2791 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2792 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2793 luaL_getmetatable(L, className);
2794 lua_setmetatable(L, -2);
2797 static void set_null(lua_State *L)
2799 ObjectRef *o = checkobject(L, -1);
2803 static void Register(lua_State *L)
2806 int methodtable = lua_gettop(L);
2807 luaL_newmetatable(L, className);
2808 int metatable = lua_gettop(L);
2810 lua_pushliteral(L, "__metatable");
2811 lua_pushvalue(L, methodtable);
2812 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2814 lua_pushliteral(L, "__index");
2815 lua_pushvalue(L, methodtable);
2816 lua_settable(L, metatable);
2818 lua_pushliteral(L, "__gc");
2819 lua_pushcfunction(L, gc_object);
2820 lua_settable(L, metatable);
2822 lua_pop(L, 1); // drop metatable
2824 luaL_openlib(L, 0, methods, 0); // fill methodtable
2825 lua_pop(L, 1); // drop methodtable
2827 // Cannot be created from Lua
2828 //lua_register(L, className, create_object);
2831 const char ObjectRef::className[] = "ObjectRef";
2832 const luaL_reg ObjectRef::methods[] = {
2833 // ServerActiveObject
2834 method(ObjectRef, remove),
2835 method(ObjectRef, getpos),
2836 method(ObjectRef, setpos),
2837 method(ObjectRef, moveto),
2838 method(ObjectRef, punch),
2839 method(ObjectRef, right_click),
2840 method(ObjectRef, set_hp),
2841 method(ObjectRef, get_hp),
2842 method(ObjectRef, get_inventory),
2843 method(ObjectRef, get_wield_list),
2844 method(ObjectRef, get_wield_index),
2845 method(ObjectRef, get_wielded_item),
2846 method(ObjectRef, set_wielded_item),
2847 method(ObjectRef, set_armor_groups),
2848 method(ObjectRef, set_properties),
2849 // LuaEntitySAO-only
2850 method(ObjectRef, setvelocity),
2851 method(ObjectRef, getvelocity),
2852 method(ObjectRef, setacceleration),
2853 method(ObjectRef, getacceleration),
2854 method(ObjectRef, setyaw),
2855 method(ObjectRef, getyaw),
2856 method(ObjectRef, settexturemod),
2857 method(ObjectRef, setsprite),
2858 method(ObjectRef, get_entity_name),
2859 method(ObjectRef, get_luaentity),
2861 method(ObjectRef, get_player_name),
2862 method(ObjectRef, get_look_dir),
2863 method(ObjectRef, get_look_pitch),
2864 method(ObjectRef, get_look_yaw),
2868 // Creates a new anonymous reference if id=0
2869 static void objectref_get_or_create(lua_State *L,
2870 ServerActiveObject *cobj)
2872 if(cobj->getId() == 0){
2873 ObjectRef::create(L, cobj);
2875 objectref_get(L, cobj->getId());
2886 ServerEnvironment *m_env;
2888 static const char className[];
2889 static const luaL_reg methods[];
2891 static EnvRef *checkobject(lua_State *L, int narg)
2893 luaL_checktype(L, narg, LUA_TUSERDATA);
2894 void *ud = luaL_checkudata(L, narg, className);
2895 if(!ud) luaL_typerror(L, narg, className);
2896 return *(EnvRef**)ud; // unbox pointer
2899 // Exported functions
2901 // EnvRef:set_node(pos, node)
2902 // pos = {x=num, y=num, z=num}
2903 static int l_set_node(lua_State *L)
2905 //infostream<<"EnvRef::l_set_node()"<<std::endl;
2906 EnvRef *o = checkobject(L, 1);
2907 ServerEnvironment *env = o->m_env;
2908 if(env == NULL) return 0;
2910 v3s16 pos = read_v3s16(L, 2);
2912 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
2914 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
2915 lua_pushboolean(L, succeeded);
2919 static int l_add_node(lua_State *L)
2921 return l_set_node(L);
2924 // EnvRef:remove_node(pos)
2925 // pos = {x=num, y=num, z=num}
2926 static int l_remove_node(lua_State *L)
2928 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
2929 EnvRef *o = checkobject(L, 1);
2930 ServerEnvironment *env = o->m_env;
2931 if(env == NULL) return 0;
2933 v3s16 pos = read_v3s16(L, 2);
2935 bool succeeded = env->getMap().removeNodeWithEvent(pos);
2936 lua_pushboolean(L, succeeded);
2940 // EnvRef:get_node(pos)
2941 // pos = {x=num, y=num, z=num}
2942 static int l_get_node(lua_State *L)
2944 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2945 EnvRef *o = checkobject(L, 1);
2946 ServerEnvironment *env = o->m_env;
2947 if(env == NULL) return 0;
2949 v3s16 pos = read_v3s16(L, 2);
2951 MapNode n = env->getMap().getNodeNoEx(pos);
2953 pushnode(L, n, env->getGameDef()->ndef());
2957 // EnvRef:get_node_or_nil(pos)
2958 // pos = {x=num, y=num, z=num}
2959 static int l_get_node_or_nil(lua_State *L)
2961 //infostream<<"EnvRef::l_get_node()"<<std::endl;
2962 EnvRef *o = checkobject(L, 1);
2963 ServerEnvironment *env = o->m_env;
2964 if(env == NULL) return 0;
2966 v3s16 pos = read_v3s16(L, 2);
2969 MapNode n = env->getMap().getNode(pos);
2971 pushnode(L, n, env->getGameDef()->ndef());
2973 } catch(InvalidPositionException &e)
2980 // EnvRef:get_node_light(pos, timeofday)
2981 // pos = {x=num, y=num, z=num}
2982 // timeofday: nil = current time, 0 = night, 0.5 = day
2983 static int l_get_node_light(lua_State *L)
2985 EnvRef *o = checkobject(L, 1);
2986 ServerEnvironment *env = o->m_env;
2987 if(env == NULL) return 0;
2989 v3s16 pos = read_v3s16(L, 2);
2990 u32 time_of_day = env->getTimeOfDay();
2991 if(lua_isnumber(L, 3))
2992 time_of_day = 24000.0 * lua_tonumber(L, 3);
2993 time_of_day %= 24000;
2994 u32 dnr = time_to_daynight_ratio(time_of_day);
2995 MapNode n = env->getMap().getNodeNoEx(pos);
2997 MapNode n = env->getMap().getNode(pos);
2998 INodeDefManager *ndef = env->getGameDef()->ndef();
2999 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3001 } catch(InvalidPositionException &e)
3008 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3009 // pos = {x=num, y=num, z=num}
3010 static int l_add_entity(lua_State *L)
3012 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3013 EnvRef *o = checkobject(L, 1);
3014 ServerEnvironment *env = o->m_env;
3015 if(env == NULL) return 0;
3017 v3f pos = checkFloatPos(L, 2);
3019 const char *name = luaL_checkstring(L, 3);
3021 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3022 int objectid = env->addActiveObject(obj);
3023 // If failed to add, return nothing (reads as nil)
3027 objectref_get_or_create(L, obj);
3031 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3032 // pos = {x=num, y=num, z=num}
3033 static int l_add_item(lua_State *L)
3035 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3036 EnvRef *o = checkobject(L, 1);
3037 ServerEnvironment *env = o->m_env;
3038 if(env == NULL) return 0;
3040 v3f pos = checkFloatPos(L, 2);
3042 ItemStack item = read_item(L, 3);
3043 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3045 // Use minetest.spawn_item to spawn a __builtin:item
3046 lua_getglobal(L, "minetest");
3047 lua_getfield(L, -1, "spawn_item");
3048 if(lua_isnil(L, -1))
3050 lua_pushvalue(L, 2);
3051 lua_pushstring(L, item.getItemString().c_str());
3052 if(lua_pcall(L, 2, 1, 0))
3053 script_error(L, "error: %s", lua_tostring(L, -1));
3055 /*lua_pushvalue(L, 1);
3056 lua_pushstring(L, "__builtin:item");
3057 lua_pushstring(L, item.getItemString().c_str());
3058 return l_add_entity(L);*/
3060 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3061 int objectid = env->addActiveObject(obj);
3062 // If failed to add, return nothing (reads as nil)
3066 objectref_get_or_create(L, obj);
3070 // EnvRef:add_rat(pos)
3071 // pos = {x=num, y=num, z=num}
3072 static int l_add_rat(lua_State *L)
3074 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3075 <<" Doing nothing."<<std::endl;
3079 // EnvRef:add_firefly(pos)
3080 // pos = {x=num, y=num, z=num}
3081 static int l_add_firefly(lua_State *L)
3083 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3084 <<" Doing nothing."<<std::endl;
3088 // EnvRef:get_meta(pos)
3089 static int l_get_meta(lua_State *L)
3091 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3092 EnvRef *o = checkobject(L, 1);
3093 ServerEnvironment *env = o->m_env;
3094 if(env == NULL) return 0;
3096 v3s16 p = read_v3s16(L, 2);
3097 NodeMetaRef::create(L, p, env);
3101 // EnvRef:get_player_by_name(name)
3102 static int l_get_player_by_name(lua_State *L)
3104 EnvRef *o = checkobject(L, 1);
3105 ServerEnvironment *env = o->m_env;
3106 if(env == NULL) return 0;
3108 const char *name = luaL_checkstring(L, 2);
3109 Player *player = env->getPlayer(name);
3114 PlayerSAO *sao = player->getPlayerSAO();
3119 // Put player on stack
3120 objectref_get_or_create(L, sao);
3124 // EnvRef:get_objects_inside_radius(pos, radius)
3125 static int l_get_objects_inside_radius(lua_State *L)
3127 // Get the table insert function
3128 lua_getglobal(L, "table");
3129 lua_getfield(L, -1, "insert");
3130 int table_insert = lua_gettop(L);
3132 EnvRef *o = checkobject(L, 1);
3133 ServerEnvironment *env = o->m_env;
3134 if(env == NULL) return 0;
3136 v3f pos = checkFloatPos(L, 2);
3137 float radius = luaL_checknumber(L, 3) * BS;
3138 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3140 int table = lua_gettop(L);
3141 for(std::set<u16>::const_iterator
3142 i = ids.begin(); i != ids.end(); i++){
3143 ServerActiveObject *obj = env->getActiveObject(*i);
3144 // Insert object reference into table
3145 lua_pushvalue(L, table_insert);
3146 lua_pushvalue(L, table);
3147 objectref_get_or_create(L, obj);
3148 if(lua_pcall(L, 2, 0, 0))
3149 script_error(L, "error: %s", lua_tostring(L, -1));
3154 // EnvRef:set_timeofday(val)
3156 static int l_set_timeofday(lua_State *L)
3158 EnvRef *o = checkobject(L, 1);
3159 ServerEnvironment *env = o->m_env;
3160 if(env == NULL) return 0;
3162 float timeofday_f = luaL_checknumber(L, 2);
3163 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3164 int timeofday_mh = (int)(timeofday_f * 24000.0);
3165 // This should be set directly in the environment but currently
3166 // such changes aren't immediately sent to the clients, so call
3167 // the server instead.
3168 //env->setTimeOfDay(timeofday_mh);
3169 get_server(L)->setTimeOfDay(timeofday_mh);
3173 // EnvRef:get_timeofday() -> 0...1
3174 static int l_get_timeofday(lua_State *L)
3176 EnvRef *o = checkobject(L, 1);
3177 ServerEnvironment *env = o->m_env;
3178 if(env == NULL) return 0;
3180 int timeofday_mh = env->getTimeOfDay();
3181 float timeofday_f = (float)timeofday_mh / 24000.0;
3182 lua_pushnumber(L, timeofday_f);
3186 static int gc_object(lua_State *L) {
3187 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3193 EnvRef(ServerEnvironment *env):
3196 //infostream<<"EnvRef created"<<std::endl;
3201 //infostream<<"EnvRef destructing"<<std::endl;
3204 // Creates an EnvRef and leaves it on top of stack
3205 // Not callable from Lua; all references are created on the C side.
3206 static void create(lua_State *L, ServerEnvironment *env)
3208 EnvRef *o = new EnvRef(env);
3209 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3210 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3211 luaL_getmetatable(L, className);
3212 lua_setmetatable(L, -2);
3215 static void set_null(lua_State *L)
3217 EnvRef *o = checkobject(L, -1);
3221 static void Register(lua_State *L)
3224 int methodtable = lua_gettop(L);
3225 luaL_newmetatable(L, className);
3226 int metatable = lua_gettop(L);
3228 lua_pushliteral(L, "__metatable");
3229 lua_pushvalue(L, methodtable);
3230 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3232 lua_pushliteral(L, "__index");
3233 lua_pushvalue(L, methodtable);
3234 lua_settable(L, metatable);
3236 lua_pushliteral(L, "__gc");
3237 lua_pushcfunction(L, gc_object);
3238 lua_settable(L, metatable);
3240 lua_pop(L, 1); // drop metatable
3242 luaL_openlib(L, 0, methods, 0); // fill methodtable
3243 lua_pop(L, 1); // drop methodtable
3245 // Cannot be created from Lua
3246 //lua_register(L, className, create_object);
3249 const char EnvRef::className[] = "EnvRef";
3250 const luaL_reg EnvRef::methods[] = {
3251 method(EnvRef, set_node),
3252 method(EnvRef, add_node),
3253 method(EnvRef, remove_node),
3254 method(EnvRef, get_node),
3255 method(EnvRef, get_node_or_nil),
3256 method(EnvRef, get_node_light),
3257 method(EnvRef, add_entity),
3258 method(EnvRef, add_item),
3259 method(EnvRef, add_rat),
3260 method(EnvRef, add_firefly),
3261 method(EnvRef, get_meta),
3262 method(EnvRef, get_player_by_name),
3263 method(EnvRef, get_objects_inside_radius),
3264 method(EnvRef, set_timeofday),
3265 method(EnvRef, get_timeofday),
3273 class LuaPseudoRandom
3276 PseudoRandom m_pseudo;
3278 static const char className[];
3279 static const luaL_reg methods[];
3281 // Exported functions
3283 // garbage collector
3284 static int gc_object(lua_State *L)
3286 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3291 // next(self, min=0, max=32767) -> get next value
3292 static int l_next(lua_State *L)
3294 LuaPseudoRandom *o = checkobject(L, 1);
3297 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3298 if(!lua_isnil(L, 2))
3299 min = luaL_checkinteger(L, 2);
3300 if(!lua_isnil(L, 3))
3301 max = luaL_checkinteger(L, 3);
3302 if(max - min != 32767 && max - min > 32767/5)
3303 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.");
3304 PseudoRandom &pseudo = o->m_pseudo;
3305 int val = pseudo.next();
3306 val = (val % (max-min+1)) + min;
3307 lua_pushinteger(L, val);
3312 LuaPseudoRandom(int seed):
3321 const PseudoRandom& getItem() const
3325 PseudoRandom& getItem()
3330 // LuaPseudoRandom(seed)
3331 // Creates an LuaPseudoRandom and leaves it on top of stack
3332 static int create_object(lua_State *L)
3334 int seed = luaL_checknumber(L, 1);
3335 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3336 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3337 luaL_getmetatable(L, className);
3338 lua_setmetatable(L, -2);
3342 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3344 luaL_checktype(L, narg, LUA_TUSERDATA);
3345 void *ud = luaL_checkudata(L, narg, className);
3346 if(!ud) luaL_typerror(L, narg, className);
3347 return *(LuaPseudoRandom**)ud; // unbox pointer
3350 static void Register(lua_State *L)
3353 int methodtable = lua_gettop(L);
3354 luaL_newmetatable(L, className);
3355 int metatable = lua_gettop(L);
3357 lua_pushliteral(L, "__metatable");
3358 lua_pushvalue(L, methodtable);
3359 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3361 lua_pushliteral(L, "__index");
3362 lua_pushvalue(L, methodtable);
3363 lua_settable(L, metatable);
3365 lua_pushliteral(L, "__gc");
3366 lua_pushcfunction(L, gc_object);
3367 lua_settable(L, metatable);
3369 lua_pop(L, 1); // drop metatable
3371 luaL_openlib(L, 0, methods, 0); // fill methodtable
3372 lua_pop(L, 1); // drop methodtable
3374 // Can be created from Lua (LuaPseudoRandom(seed))
3375 lua_register(L, className, create_object);
3378 const char LuaPseudoRandom::className[] = "PseudoRandom";
3379 const luaL_reg LuaPseudoRandom::methods[] = {
3380 method(LuaPseudoRandom, next),
3388 class LuaABM : public ActiveBlockModifier
3394 std::set<std::string> m_trigger_contents;
3395 std::set<std::string> m_required_neighbors;
3396 float m_trigger_interval;
3397 u32 m_trigger_chance;
3399 LuaABM(lua_State *L, int id,
3400 const std::set<std::string> &trigger_contents,
3401 const std::set<std::string> &required_neighbors,
3402 float trigger_interval, u32 trigger_chance):
3405 m_trigger_contents(trigger_contents),
3406 m_required_neighbors(required_neighbors),
3407 m_trigger_interval(trigger_interval),
3408 m_trigger_chance(trigger_chance)
3411 virtual std::set<std::string> getTriggerContents()
3413 return m_trigger_contents;
3415 virtual std::set<std::string> getRequiredNeighbors()
3417 return m_required_neighbors;
3419 virtual float getTriggerInterval()
3421 return m_trigger_interval;
3423 virtual u32 getTriggerChance()
3425 return m_trigger_chance;
3427 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3428 u32 active_object_count, u32 active_object_count_wider)
3430 lua_State *L = m_lua;
3433 assert(lua_checkstack(L, 20));
3434 StackUnroller stack_unroller(L);
3436 // Get minetest.registered_abms
3437 lua_getglobal(L, "minetest");
3438 lua_getfield(L, -1, "registered_abms");
3439 luaL_checktype(L, -1, LUA_TTABLE);
3440 int registered_abms = lua_gettop(L);
3442 // Get minetest.registered_abms[m_id]
3443 lua_pushnumber(L, m_id);
3444 lua_gettable(L, registered_abms);
3445 if(lua_isnil(L, -1))
3449 luaL_checktype(L, -1, LUA_TTABLE);
3450 lua_getfield(L, -1, "action");
3451 luaL_checktype(L, -1, LUA_TFUNCTION);
3453 pushnode(L, n, env->getGameDef()->ndef());
3454 lua_pushnumber(L, active_object_count);
3455 lua_pushnumber(L, active_object_count_wider);
3456 if(lua_pcall(L, 4, 0, 0))
3457 script_error(L, "error: %s", lua_tostring(L, -1));
3465 static void read_server_sound_params(lua_State *L, int index,
3466 ServerSoundParams ¶ms)
3469 index = lua_gettop(L) + 1 + index;
3471 params = ServerSoundParams();
3472 if(lua_istable(L, index)){
3473 getfloatfield(L, index, "gain", params.gain);
3474 getstringfield(L, index, "to_player", params.to_player);
3475 lua_getfield(L, index, "pos");
3476 if(!lua_isnil(L, -1)){
3477 v3f p = read_v3f(L, -1)*BS;
3479 params.type = ServerSoundParams::SSP_POSITIONAL;
3482 lua_getfield(L, index, "object");
3483 if(!lua_isnil(L, -1)){
3484 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3485 ServerActiveObject *sao = ObjectRef::getobject(ref);
3487 params.object = sao->getId();
3488 params.type = ServerSoundParams::SSP_OBJECT;
3492 params.max_hear_distance = BS*getfloatfield_default(L, index,
3493 "max_hear_distance", params.max_hear_distance/BS);
3494 getboolfield(L, index, "loop", params.loop);
3503 // Writes a line to dstream
3504 static int l_debug(lua_State *L)
3506 std::string text = lua_tostring(L, 1);
3507 dstream << text << std::endl;
3511 // log([level,] text)
3512 // Writes a line to the logger.
3513 // The one-argument version logs to infostream.
3514 // The two-argument version accept a log level: error, action, info, or verbose.
3515 static int l_log(lua_State *L)
3518 LogMessageLevel level = LMT_INFO;
3519 if(lua_isnone(L, 2))
3521 text = lua_tostring(L, 1);
3525 std::string levelname = lua_tostring(L, 1);
3526 text = lua_tostring(L, 2);
3527 if(levelname == "error")
3529 else if(levelname == "action")
3531 else if(levelname == "verbose")
3532 level = LMT_VERBOSE;
3534 log_printline(level, text);
3538 // register_item_raw({lots of stuff})
3539 static int l_register_item_raw(lua_State *L)
3541 luaL_checktype(L, 1, LUA_TTABLE);
3544 // Get the writable item and node definition managers from the server
3545 IWritableItemDefManager *idef =
3546 get_server(L)->getWritableItemDefManager();
3547 IWritableNodeDefManager *ndef =
3548 get_server(L)->getWritableNodeDefManager();
3550 // Check if name is defined
3551 lua_getfield(L, table, "name");
3552 if(lua_isstring(L, -1)){
3553 std::string name = lua_tostring(L, -1);
3554 verbosestream<<"register_item_raw: "<<name<<std::endl;
3556 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3559 // Check if on_use is defined
3561 // Read the item definition and register it
3562 ItemDefinition def = read_item_definition(L, table);
3563 idef->registerItem(def);
3565 // Read the node definition (content features) and register it
3566 if(def.type == ITEM_NODE)
3568 ContentFeatures f = read_content_features(L, table);
3569 ndef->set(f.name, f);
3572 return 0; /* number of results */
3575 // register_alias_raw(name, convert_to_name)
3576 static int l_register_alias_raw(lua_State *L)
3578 std::string name = luaL_checkstring(L, 1);
3579 std::string convert_to = luaL_checkstring(L, 2);
3581 // Get the writable item definition manager from the server
3582 IWritableItemDefManager *idef =
3583 get_server(L)->getWritableItemDefManager();
3585 idef->registerAlias(name, convert_to);
3587 return 0; /* number of results */
3590 // helper for register_craft
3591 static bool read_craft_recipe_shaped(lua_State *L, int index,
3592 int &width, std::vector<std::string> &recipe)
3595 index = lua_gettop(L) + 1 + index;
3597 if(!lua_istable(L, index))
3602 while(lua_next(L, index) != 0){
3604 // key at index -2 and value at index -1
3605 if(!lua_istable(L, -1))
3607 int table2 = lua_gettop(L);
3609 while(lua_next(L, table2) != 0){
3610 // key at index -2 and value at index -1
3611 if(!lua_isstring(L, -1))
3613 recipe.push_back(lua_tostring(L, -1));
3614 // removes value, keeps key for next iteration
3621 if(colcount != width)
3624 // removes value, keeps key for next iteration
3631 // helper for register_craft
3632 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3633 std::vector<std::string> &recipe)
3636 index = lua_gettop(L) + 1 + index;
3638 if(!lua_istable(L, index))
3642 while(lua_next(L, index) != 0){
3643 // key at index -2 and value at index -1
3644 if(!lua_isstring(L, -1))
3646 recipe.push_back(lua_tostring(L, -1));
3647 // removes value, keeps key for next iteration
3653 // helper for register_craft
3654 static bool read_craft_replacements(lua_State *L, int index,
3655 CraftReplacements &replacements)
3658 index = lua_gettop(L) + 1 + index;
3660 if(!lua_istable(L, index))
3664 while(lua_next(L, index) != 0){
3665 // key at index -2 and value at index -1
3666 if(!lua_istable(L, -1))
3668 lua_rawgeti(L, -1, 1);
3669 if(!lua_isstring(L, -1))
3671 std::string replace_from = lua_tostring(L, -1);
3673 lua_rawgeti(L, -1, 2);
3674 if(!lua_isstring(L, -1))
3676 std::string replace_to = lua_tostring(L, -1);
3678 replacements.pairs.push_back(
3679 std::make_pair(replace_from, replace_to));
3680 // removes value, keeps key for next iteration
3685 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3686 static int l_register_craft(lua_State *L)
3688 //infostream<<"register_craft"<<std::endl;
3689 luaL_checktype(L, 1, LUA_TTABLE);
3692 // Get the writable craft definition manager from the server
3693 IWritableCraftDefManager *craftdef =
3694 get_server(L)->getWritableCraftDefManager();
3696 std::string type = getstringfield_default(L, table, "type", "shaped");
3699 CraftDefinitionShaped
3701 if(type == "shaped"){
3702 std::string output = getstringfield_default(L, table, "output", "");
3704 throw LuaError(L, "Crafting definition is missing an output");
3707 std::vector<std::string> recipe;
3708 lua_getfield(L, table, "recipe");
3709 if(lua_isnil(L, -1))
3710 throw LuaError(L, "Crafting definition is missing a recipe"
3711 " (output=\"" + output + "\")");
3712 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3713 throw LuaError(L, "Invalid crafting recipe"
3714 " (output=\"" + output + "\")");
3716 CraftReplacements replacements;
3717 lua_getfield(L, table, "replacements");
3718 if(!lua_isnil(L, -1))
3720 if(!read_craft_replacements(L, -1, replacements))
3721 throw LuaError(L, "Invalid replacements"
3722 " (output=\"" + output + "\")");
3725 CraftDefinition *def = new CraftDefinitionShaped(
3726 output, width, recipe, replacements);
3727 craftdef->registerCraft(def);
3730 CraftDefinitionShapeless
3732 else if(type == "shapeless"){
3733 std::string output = getstringfield_default(L, table, "output", "");
3735 throw LuaError(L, "Crafting definition (shapeless)"
3736 " is missing an output");
3738 std::vector<std::string> recipe;
3739 lua_getfield(L, table, "recipe");
3740 if(lua_isnil(L, -1))
3741 throw LuaError(L, "Crafting definition (shapeless)"
3742 " is missing a recipe"
3743 " (output=\"" + output + "\")");
3744 if(!read_craft_recipe_shapeless(L, -1, recipe))
3745 throw LuaError(L, "Invalid crafting recipe"
3746 " (output=\"" + output + "\")");
3748 CraftReplacements replacements;
3749 lua_getfield(L, table, "replacements");
3750 if(!lua_isnil(L, -1))
3752 if(!read_craft_replacements(L, -1, replacements))
3753 throw LuaError(L, "Invalid replacements"
3754 " (output=\"" + output + "\")");
3757 CraftDefinition *def = new CraftDefinitionShapeless(
3758 output, recipe, replacements);
3759 craftdef->registerCraft(def);
3762 CraftDefinitionToolRepair
3764 else if(type == "toolrepair"){
3765 float additional_wear = getfloatfield_default(L, table,
3766 "additional_wear", 0.0);
3768 CraftDefinition *def = new CraftDefinitionToolRepair(
3770 craftdef->registerCraft(def);
3773 CraftDefinitionCooking
3775 else if(type == "cooking"){
3776 std::string output = getstringfield_default(L, table, "output", "");
3778 throw LuaError(L, "Crafting definition (cooking)"
3779 " is missing an output");
3781 std::string recipe = getstringfield_default(L, table, "recipe", "");
3783 throw LuaError(L, "Crafting definition (cooking)"
3784 " is missing a recipe"
3785 " (output=\"" + output + "\")");
3787 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3789 CraftDefinition *def = new CraftDefinitionCooking(
3790 output, recipe, cooktime);
3791 craftdef->registerCraft(def);
3796 else if(type == "fuel"){
3797 std::string recipe = getstringfield_default(L, table, "recipe", "");
3799 throw LuaError(L, "Crafting definition (fuel)"
3800 " is missing a recipe");
3802 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3804 CraftDefinition *def = new CraftDefinitionFuel(
3806 craftdef->registerCraft(def);
3810 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3814 return 0; /* number of results */
3817 // setting_set(name, value)
3818 static int l_setting_set(lua_State *L)
3820 const char *name = luaL_checkstring(L, 1);
3821 const char *value = luaL_checkstring(L, 2);
3822 g_settings->set(name, value);
3826 // setting_get(name)
3827 static int l_setting_get(lua_State *L)
3829 const char *name = luaL_checkstring(L, 1);
3831 std::string value = g_settings->get(name);
3832 lua_pushstring(L, value.c_str());
3833 } catch(SettingNotFoundException &e){
3839 // setting_getbool(name)
3840 static int l_setting_getbool(lua_State *L)
3842 const char *name = luaL_checkstring(L, 1);
3844 bool value = g_settings->getBool(name);
3845 lua_pushboolean(L, value);
3846 } catch(SettingNotFoundException &e){
3852 // chat_send_all(text)
3853 static int l_chat_send_all(lua_State *L)
3855 const char *text = luaL_checkstring(L, 1);
3856 // Get server from registry
3857 Server *server = get_server(L);
3859 server->notifyPlayers(narrow_to_wide(text));
3863 // chat_send_player(name, text)
3864 static int l_chat_send_player(lua_State *L)
3866 const char *name = luaL_checkstring(L, 1);
3867 const char *text = luaL_checkstring(L, 2);
3868 // Get server from registry
3869 Server *server = get_server(L);
3871 server->notifyPlayer(name, narrow_to_wide(text));
3875 // get_player_privs(name, text)
3876 static int l_get_player_privs(lua_State *L)
3878 const char *name = luaL_checkstring(L, 1);
3879 // Get server from registry
3880 Server *server = get_server(L);
3883 int table = lua_gettop(L);
3884 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
3885 for(std::set<std::string>::const_iterator
3886 i = privs_s.begin(); i != privs_s.end(); i++){
3887 lua_pushboolean(L, true);
3888 lua_setfield(L, table, i->c_str());
3890 lua_pushvalue(L, table);
3894 // get_inventory(location)
3895 static int l_get_inventory(lua_State *L)
3897 InventoryLocation loc;
3899 std::string type = checkstringfield(L, 1, "type");
3900 if(type == "player"){
3901 std::string name = checkstringfield(L, 1, "name");
3902 loc.setPlayer(name);
3903 } else if(type == "node"){
3904 lua_getfield(L, 1, "pos");
3905 v3s16 pos = check_v3s16(L, -1);
3906 loc.setNodeMeta(pos);
3909 if(get_server(L)->getInventory(loc) != NULL)
3910 InvRef::create(L, loc);
3916 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3917 static int l_get_dig_params(lua_State *L)
3919 std::map<std::string, int> groups;
3920 read_groups(L, 1, groups);
3921 ToolCapabilities tp = read_tool_capabilities(L, 2);
3922 if(lua_isnoneornil(L, 3))
3923 push_dig_params(L, getDigParams(groups, &tp));
3925 push_dig_params(L, getDigParams(groups, &tp,
3926 luaL_checknumber(L, 3)));
3930 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3931 static int l_get_hit_params(lua_State *L)
3933 std::map<std::string, int> groups;
3934 read_groups(L, 1, groups);
3935 ToolCapabilities tp = read_tool_capabilities(L, 2);
3936 if(lua_isnoneornil(L, 3))
3937 push_hit_params(L, getHitParams(groups, &tp));
3939 push_hit_params(L, getHitParams(groups, &tp,
3940 luaL_checknumber(L, 3)));
3944 // get_current_modname()
3945 static int l_get_current_modname(lua_State *L)
3947 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3951 // get_modpath(modname)
3952 static int l_get_modpath(lua_State *L)
3954 std::string modname = luaL_checkstring(L, 1);
3956 if(modname == "__builtin"){
3957 std::string path = get_server(L)->getBuiltinLuaPath();
3958 lua_pushstring(L, path.c_str());
3961 const ModSpec *mod = get_server(L)->getModSpec(modname);
3966 lua_pushstring(L, mod->path.c_str());
3971 static int l_get_worldpath(lua_State *L)
3973 std::string worldpath = get_server(L)->getWorldPath();
3974 lua_pushstring(L, worldpath.c_str());
3978 // sound_play(spec, parameters)
3979 static int l_sound_play(lua_State *L)
3981 SimpleSoundSpec spec;
3982 read_soundspec(L, 1, spec);
3983 ServerSoundParams params;
3984 read_server_sound_params(L, 2, params);
3985 s32 handle = get_server(L)->playSound(spec, params);
3986 lua_pushinteger(L, handle);
3990 // sound_stop(handle)
3991 static int l_sound_stop(lua_State *L)
3993 int handle = luaL_checkinteger(L, 1);
3994 get_server(L)->stopSound(handle);
3998 // is_singleplayer()
3999 static int l_is_singleplayer(lua_State *L)
4001 lua_pushboolean(L, get_server(L)->isSingleplayer());
4005 // get_password_hash(name, raw_password)
4006 static int l_get_password_hash(lua_State *L)
4008 std::string name = luaL_checkstring(L, 1);
4009 std::string raw_password = luaL_checkstring(L, 2);
4010 std::string hash = translatePassword(name,
4011 narrow_to_wide(raw_password));
4012 lua_pushstring(L, hash.c_str());
4016 // notify_authentication_modified(name)
4017 static int l_notify_authentication_modified(lua_State *L)
4019 std::string name = "";
4020 if(lua_isstring(L, 1))
4021 name = lua_tostring(L, 1);
4022 get_server(L)->reportPrivsModified(name);
4026 static const struct luaL_Reg minetest_f [] = {
4029 {"register_item_raw", l_register_item_raw},
4030 {"register_alias_raw", l_register_alias_raw},
4031 {"register_craft", l_register_craft},
4032 {"setting_set", l_setting_set},
4033 {"setting_get", l_setting_get},
4034 {"setting_getbool", l_setting_getbool},
4035 {"chat_send_all", l_chat_send_all},
4036 {"chat_send_player", l_chat_send_player},
4037 {"get_player_privs", l_get_player_privs},
4038 {"get_inventory", l_get_inventory},
4039 {"get_dig_params", l_get_dig_params},
4040 {"get_hit_params", l_get_hit_params},
4041 {"get_current_modname", l_get_current_modname},
4042 {"get_modpath", l_get_modpath},
4043 {"get_worldpath", l_get_worldpath},
4044 {"sound_play", l_sound_play},
4045 {"sound_stop", l_sound_stop},
4046 {"is_singleplayer", l_is_singleplayer},
4047 {"get_password_hash", l_get_password_hash},
4048 {"notify_authentication_modified", l_notify_authentication_modified},
4053 Main export function
4056 void scriptapi_export(lua_State *L, Server *server)
4059 assert(lua_checkstack(L, 20));
4060 verbosestream<<"scriptapi_export()"<<std::endl;
4061 StackUnroller stack_unroller(L);
4063 // Store server as light userdata in registry
4064 lua_pushlightuserdata(L, server);
4065 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4067 // Register global functions in table minetest
4069 luaL_register(L, NULL, minetest_f);
4070 lua_setglobal(L, "minetest");
4072 // Get the main minetest table
4073 lua_getglobal(L, "minetest");
4075 // Add tables to minetest
4078 lua_setfield(L, -2, "object_refs");
4080 lua_setfield(L, -2, "luaentities");
4082 // Register wrappers
4083 LuaItemStack::Register(L);
4084 InvRef::Register(L);
4085 NodeMetaRef::Register(L);
4086 ObjectRef::Register(L);
4087 EnvRef::Register(L);
4088 LuaPseudoRandom::Register(L);
4091 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4092 const std::string &modname)
4094 ModNameStorer modnamestorer(L, modname);
4096 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4098 errorstream<<"Error loading mod \""<<modname
4099 <<"\": modname does not follow naming conventions: "
4100 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4104 bool success = false;
4107 success = script_load(L, scriptpath.c_str());
4110 errorstream<<"Error loading mod \""<<modname
4111 <<"\": "<<e.what()<<std::endl;
4117 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4120 assert(lua_checkstack(L, 20));
4121 verbosestream<<"scriptapi_add_environment"<<std::endl;
4122 StackUnroller stack_unroller(L);
4124 // Create EnvRef on stack
4125 EnvRef::create(L, env);
4126 int envref = lua_gettop(L);
4128 // minetest.env = envref
4129 lua_getglobal(L, "minetest");
4130 luaL_checktype(L, -1, LUA_TTABLE);
4131 lua_pushvalue(L, envref);
4132 lua_setfield(L, -2, "env");
4134 // Store environment as light userdata in registry
4135 lua_pushlightuserdata(L, env);
4136 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4139 Add ActiveBlockModifiers to environment
4142 // Get minetest.registered_abms
4143 lua_getglobal(L, "minetest");
4144 lua_getfield(L, -1, "registered_abms");
4145 luaL_checktype(L, -1, LUA_TTABLE);
4146 int registered_abms = lua_gettop(L);
4148 if(lua_istable(L, registered_abms)){
4149 int table = lua_gettop(L);
4151 while(lua_next(L, table) != 0){
4152 // key at index -2 and value at index -1
4153 int id = lua_tonumber(L, -2);
4154 int current_abm = lua_gettop(L);
4156 std::set<std::string> trigger_contents;
4157 lua_getfield(L, current_abm, "nodenames");
4158 if(lua_istable(L, -1)){
4159 int table = lua_gettop(L);
4161 while(lua_next(L, table) != 0){
4162 // key at index -2 and value at index -1
4163 luaL_checktype(L, -1, LUA_TSTRING);
4164 trigger_contents.insert(lua_tostring(L, -1));
4165 // removes value, keeps key for next iteration
4168 } else if(lua_isstring(L, -1)){
4169 trigger_contents.insert(lua_tostring(L, -1));
4173 std::set<std::string> required_neighbors;
4174 lua_getfield(L, current_abm, "neighbors");
4175 if(lua_istable(L, -1)){
4176 int table = lua_gettop(L);
4178 while(lua_next(L, table) != 0){
4179 // key at index -2 and value at index -1
4180 luaL_checktype(L, -1, LUA_TSTRING);
4181 required_neighbors.insert(lua_tostring(L, -1));
4182 // removes value, keeps key for next iteration
4185 } else if(lua_isstring(L, -1)){
4186 required_neighbors.insert(lua_tostring(L, -1));
4190 float trigger_interval = 10.0;
4191 getfloatfield(L, current_abm, "interval", trigger_interval);
4193 int trigger_chance = 50;
4194 getintfield(L, current_abm, "chance", trigger_chance);
4196 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4197 required_neighbors, trigger_interval, trigger_chance);
4199 env->addActiveBlockModifier(abm);
4201 // removes value, keeps key for next iteration
4209 // Dump stack top with the dump2 function
4210 static void dump2(lua_State *L, const char *name)
4212 // Dump object (debug)
4213 lua_getglobal(L, "dump2");
4214 luaL_checktype(L, -1, LUA_TFUNCTION);
4215 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4216 lua_pushstring(L, name);
4217 if(lua_pcall(L, 2, 0, 0))
4218 script_error(L, "error: %s", lua_tostring(L, -1));
4226 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4229 assert(lua_checkstack(L, 20));
4230 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4231 StackUnroller stack_unroller(L);
4233 // Create object on stack
4234 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4235 int object = lua_gettop(L);
4237 // Get minetest.object_refs table
4238 lua_getglobal(L, "minetest");
4239 lua_getfield(L, -1, "object_refs");
4240 luaL_checktype(L, -1, LUA_TTABLE);
4241 int objectstable = lua_gettop(L);
4243 // object_refs[id] = object
4244 lua_pushnumber(L, cobj->getId()); // Push id
4245 lua_pushvalue(L, object); // Copy object to top of stack
4246 lua_settable(L, objectstable);
4249 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4252 assert(lua_checkstack(L, 20));
4253 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4254 StackUnroller stack_unroller(L);
4256 // Get minetest.object_refs table
4257 lua_getglobal(L, "minetest");
4258 lua_getfield(L, -1, "object_refs");
4259 luaL_checktype(L, -1, LUA_TTABLE);
4260 int objectstable = lua_gettop(L);
4262 // Get object_refs[id]
4263 lua_pushnumber(L, cobj->getId()); // Push id
4264 lua_gettable(L, objectstable);
4265 // Set object reference to NULL
4266 ObjectRef::set_null(L);
4267 lua_pop(L, 1); // pop object
4269 // Set object_refs[id] = nil
4270 lua_pushnumber(L, cobj->getId()); // Push id
4272 lua_settable(L, objectstable);
4279 // What scriptapi_run_callbacks does with the return values of callbacks.
4280 // Regardless of the mode, if only one callback is defined,
4281 // its return value is the total return value.
4282 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4283 enum RunCallbacksMode
4285 // Returns the return value of the first callback
4286 // Returns nil if list of callbacks is empty
4287 RUN_CALLBACKS_MODE_FIRST,
4288 // Returns the return value of the last callback
4289 // Returns nil if list of callbacks is empty
4290 RUN_CALLBACKS_MODE_LAST,
4291 // If any callback returns a false value, the first such is returned
4292 // Otherwise, the first callback's return value (trueish) is returned
4293 // Returns true if list of callbacks is empty
4294 RUN_CALLBACKS_MODE_AND,
4295 // Like above, but stops calling callbacks (short circuit)
4296 // after seeing the first false value
4297 RUN_CALLBACKS_MODE_AND_SC,
4298 // If any callback returns a true value, the first such is returned
4299 // Otherwise, the first callback's return value (falseish) is returned
4300 // Returns false if list of callbacks is empty
4301 RUN_CALLBACKS_MODE_OR,
4302 // Like above, but stops calling callbacks (short circuit)
4303 // after seeing the first true value
4304 RUN_CALLBACKS_MODE_OR_SC,
4305 // Note: "a true value" and "a false value" refer to values that
4306 // are converted by lua_toboolean to true or false, respectively.
4309 // Push the list of callbacks (a lua table).
4310 // Then push nargs arguments.
4311 // Then call this function, which
4312 // - runs the callbacks
4313 // - removes the table and arguments from the lua stack
4314 // - pushes the return value, computed depending on mode
4315 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4316 RunCallbacksMode mode)
4318 // Insert the return value into the lua stack, below the table
4319 assert(lua_gettop(L) >= nargs + 1);
4321 lua_insert(L, -(nargs + 1) - 1);
4322 // Stack now looks like this:
4323 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4325 int rv = lua_gettop(L) - nargs - 1;
4327 int arg = table + 1;
4329 luaL_checktype(L, table, LUA_TTABLE);
4333 bool first_loop = true;
4334 while(lua_next(L, table) != 0){
4335 // key at index -2 and value at index -1
4336 luaL_checktype(L, -1, LUA_TFUNCTION);
4338 for(int i = 0; i < nargs; i++)
4339 lua_pushvalue(L, arg+i);
4340 if(lua_pcall(L, nargs, 1, 0))
4341 script_error(L, "error: %s", lua_tostring(L, -1));
4343 // Move return value to designated space in stack
4346 // Result of first callback is always moved
4350 // Otherwise, what happens depends on the mode
4351 if(mode == RUN_CALLBACKS_MODE_FIRST)
4353 else if(mode == RUN_CALLBACKS_MODE_LAST)
4355 else if(mode == RUN_CALLBACKS_MODE_AND ||
4356 mode == RUN_CALLBACKS_MODE_AND_SC){
4357 if(lua_toboolean(L, rv) == true &&
4358 lua_toboolean(L, -1) == false)
4363 else if(mode == RUN_CALLBACKS_MODE_OR ||
4364 mode == RUN_CALLBACKS_MODE_OR_SC){
4365 if(lua_toboolean(L, rv) == false &&
4366 lua_toboolean(L, -1) == true)
4375 // Handle short circuit modes
4376 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4377 lua_toboolean(L, rv) == false)
4379 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4380 lua_toboolean(L, rv) == true)
4383 // value removed, keep key for next iteration
4386 // Remove stuff from stack, leaving only the return value
4389 // Fix return value in case no callbacks were called
4391 if(mode == RUN_CALLBACKS_MODE_AND ||
4392 mode == RUN_CALLBACKS_MODE_AND_SC){
4394 lua_pushboolean(L, true);
4396 else if(mode == RUN_CALLBACKS_MODE_OR ||
4397 mode == RUN_CALLBACKS_MODE_OR_SC){
4399 lua_pushboolean(L, false);
4404 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4405 const std::string &message)
4408 assert(lua_checkstack(L, 20));
4409 StackUnroller stack_unroller(L);
4411 // Get minetest.registered_on_chat_messages
4412 lua_getglobal(L, "minetest");
4413 lua_getfield(L, -1, "registered_on_chat_messages");
4415 lua_pushstring(L, name.c_str());
4416 lua_pushstring(L, message.c_str());
4417 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4418 bool ate = lua_toboolean(L, -1);
4422 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4425 assert(lua_checkstack(L, 20));
4426 StackUnroller stack_unroller(L);
4428 // Get minetest.registered_on_newplayers
4429 lua_getglobal(L, "minetest");
4430 lua_getfield(L, -1, "registered_on_newplayers");
4432 objectref_get_or_create(L, player);
4433 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4436 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4439 assert(lua_checkstack(L, 20));
4440 StackUnroller stack_unroller(L);
4442 // Get minetest.registered_on_dieplayers
4443 lua_getglobal(L, "minetest");
4444 lua_getfield(L, -1, "registered_on_dieplayers");
4446 objectref_get_or_create(L, player);
4447 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4450 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4453 assert(lua_checkstack(L, 20));
4454 StackUnroller stack_unroller(L);
4456 // Get minetest.registered_on_respawnplayers
4457 lua_getglobal(L, "minetest");
4458 lua_getfield(L, -1, "registered_on_respawnplayers");
4460 objectref_get_or_create(L, player);
4461 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4462 bool positioning_handled_by_some = lua_toboolean(L, -1);
4463 return positioning_handled_by_some;
4466 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4469 assert(lua_checkstack(L, 20));
4470 StackUnroller stack_unroller(L);
4472 // Get minetest.registered_on_joinplayers
4473 lua_getglobal(L, "minetest");
4474 lua_getfield(L, -1, "registered_on_joinplayers");
4476 objectref_get_or_create(L, player);
4477 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4480 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4483 assert(lua_checkstack(L, 20));
4484 StackUnroller stack_unroller(L);
4486 // Get minetest.registered_on_leaveplayers
4487 lua_getglobal(L, "minetest");
4488 lua_getfield(L, -1, "registered_on_leaveplayers");
4490 objectref_get_or_create(L, player);
4491 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4494 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4497 assert(lua_checkstack(L, 20));
4498 StackUnroller stack_unroller(L);
4500 Inventory *inv = player->getInventory();
4503 lua_getglobal(L, "minetest");
4504 lua_getfield(L, -1, "creative_inventory");
4505 luaL_checktype(L, -1, LUA_TTABLE);
4506 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4509 static void get_auth_handler(lua_State *L)
4511 lua_getglobal(L, "minetest");
4512 lua_getfield(L, -1, "registered_auth_handler");
4513 if(lua_isnil(L, -1)){
4515 lua_getfield(L, -1, "builtin_auth_handler");
4517 if(lua_type(L, -1) != LUA_TTABLE)
4518 throw LuaError(L, "Authentication handler table not valid");
4521 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
4522 std::string *dst_password, std::set<std::string> *dst_privs)
4525 assert(lua_checkstack(L, 20));
4526 StackUnroller stack_unroller(L);
4528 get_auth_handler(L);
4529 lua_getfield(L, -1, "get_auth");
4530 if(lua_type(L, -1) != LUA_TFUNCTION)
4531 throw LuaError(L, "Authentication handler missing get_auth");
4532 lua_pushstring(L, playername.c_str());
4533 if(lua_pcall(L, 1, 1, 0))
4534 script_error(L, "error: %s", lua_tostring(L, -1));
4536 // nil = login not allowed
4537 if(lua_isnil(L, -1))
4539 luaL_checktype(L, -1, LUA_TTABLE);
4541 std::string password;
4542 bool found = getstringfield(L, -1, "password", password);
4544 throw LuaError(L, "Authentication handler didn't return password");
4546 *dst_password = password;
4548 lua_getfield(L, -1, "privileges");
4549 if(!lua_istable(L, -1))
4551 "Authentication handler didn't return privilege table");
4553 read_privileges(L, -1, *dst_privs);
4559 void scriptapi_create_auth(lua_State *L, const std::string &playername,
4560 const std::string &password)
4563 assert(lua_checkstack(L, 20));
4564 StackUnroller stack_unroller(L);
4566 get_auth_handler(L);
4567 lua_getfield(L, -1, "create_auth");
4568 if(lua_type(L, -1) != LUA_TFUNCTION)
4569 throw LuaError(L, "Authentication handler missing create_auth");
4570 lua_pushstring(L, playername.c_str());
4571 lua_pushstring(L, password.c_str());
4572 if(lua_pcall(L, 2, 0, 0))
4573 script_error(L, "error: %s", lua_tostring(L, -1));
4576 bool scriptapi_set_password(lua_State *L, const std::string &playername,
4577 const std::string &password)
4580 assert(lua_checkstack(L, 20));
4581 StackUnroller stack_unroller(L);
4583 get_auth_handler(L);
4584 lua_getfield(L, -1, "set_password");
4585 if(lua_type(L, -1) != LUA_TFUNCTION)
4586 throw LuaError(L, "Authentication handler missing set_password");
4587 lua_pushstring(L, playername.c_str());
4588 lua_pushstring(L, password.c_str());
4589 if(lua_pcall(L, 2, 1, 0))
4590 script_error(L, "error: %s", lua_tostring(L, -1));
4591 return lua_toboolean(L, -1);
4595 item callbacks and node callbacks
4598 // Retrieves minetest.registered_items[name][callbackname]
4599 // If that is nil or on error, return false and stack is unchanged
4600 // If that is a function, returns true and pushes the
4601 // function onto the stack
4602 static bool get_item_callback(lua_State *L,
4603 const char *name, const char *callbackname)
4605 lua_getglobal(L, "minetest");
4606 lua_getfield(L, -1, "registered_items");
4608 luaL_checktype(L, -1, LUA_TTABLE);
4609 lua_getfield(L, -1, name);
4611 // Should be a table
4612 if(lua_type(L, -1) != LUA_TTABLE)
4614 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4618 lua_getfield(L, -1, callbackname);
4620 // Should be a function or nil
4621 if(lua_type(L, -1) == LUA_TFUNCTION)
4625 else if(lua_isnil(L, -1))
4632 errorstream<<"Item \""<<name<<"\" callback \""
4633 <<callbackname<<" is not a function"<<std::endl;
4639 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4640 ServerActiveObject *dropper, v3f pos)
4643 assert(lua_checkstack(L, 20));
4644 StackUnroller stack_unroller(L);
4646 // Push callback function on stack
4647 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4651 LuaItemStack::create(L, item);
4652 objectref_get_or_create(L, dropper);
4653 pushFloatPos(L, pos);
4654 if(lua_pcall(L, 3, 1, 0))
4655 script_error(L, "error: %s", lua_tostring(L, -1));
4656 if(!lua_isnil(L, -1))
4657 item = read_item(L, -1);
4661 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4662 ServerActiveObject *placer, const PointedThing &pointed)
4665 assert(lua_checkstack(L, 20));
4666 StackUnroller stack_unroller(L);
4668 // Push callback function on stack
4669 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4673 LuaItemStack::create(L, item);
4674 objectref_get_or_create(L, placer);
4675 push_pointed_thing(L, pointed);
4676 if(lua_pcall(L, 3, 1, 0))
4677 script_error(L, "error: %s", lua_tostring(L, -1));
4678 if(!lua_isnil(L, -1))
4679 item = read_item(L, -1);
4683 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4684 ServerActiveObject *user, const PointedThing &pointed)
4687 assert(lua_checkstack(L, 20));
4688 StackUnroller stack_unroller(L);
4690 // Push callback function on stack
4691 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4695 LuaItemStack::create(L, item);
4696 objectref_get_or_create(L, user);
4697 push_pointed_thing(L, pointed);
4698 if(lua_pcall(L, 3, 1, 0))
4699 script_error(L, "error: %s", lua_tostring(L, -1));
4700 if(!lua_isnil(L, -1))
4701 item = read_item(L, -1);
4705 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4706 ServerActiveObject *puncher)
4709 assert(lua_checkstack(L, 20));
4710 StackUnroller stack_unroller(L);
4712 INodeDefManager *ndef = get_server(L)->ndef();
4714 // Push callback function on stack
4715 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4720 pushnode(L, node, ndef);
4721 objectref_get_or_create(L, puncher);
4722 if(lua_pcall(L, 3, 0, 0))
4723 script_error(L, "error: %s", lua_tostring(L, -1));
4727 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4728 ServerActiveObject *digger)
4731 assert(lua_checkstack(L, 20));
4732 StackUnroller stack_unroller(L);
4734 INodeDefManager *ndef = get_server(L)->ndef();
4736 // Push callback function on stack
4737 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4742 pushnode(L, node, ndef);
4743 objectref_get_or_create(L, digger);
4744 if(lua_pcall(L, 3, 0, 0))
4745 script_error(L, "error: %s", lua_tostring(L, -1));
4753 void scriptapi_environment_step(lua_State *L, float dtime)
4756 assert(lua_checkstack(L, 20));
4757 //infostream<<"scriptapi_environment_step"<<std::endl;
4758 StackUnroller stack_unroller(L);
4760 // Get minetest.registered_globalsteps
4761 lua_getglobal(L, "minetest");
4762 lua_getfield(L, -1, "registered_globalsteps");
4764 lua_pushnumber(L, dtime);
4765 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4768 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
4772 assert(lua_checkstack(L, 20));
4773 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4774 StackUnroller stack_unroller(L);
4776 // Get minetest.registered_on_generateds
4777 lua_getglobal(L, "minetest");
4778 lua_getfield(L, -1, "registered_on_generateds");
4780 push_v3s16(L, minp);
4781 push_v3s16(L, maxp);
4782 lua_pushnumber(L, blockseed);
4783 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
4790 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4793 assert(lua_checkstack(L, 20));
4794 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4795 <<name<<"\""<<std::endl;
4796 StackUnroller stack_unroller(L);
4798 // Get minetest.registered_entities[name]
4799 lua_getglobal(L, "minetest");
4800 lua_getfield(L, -1, "registered_entities");
4801 luaL_checktype(L, -1, LUA_TTABLE);
4802 lua_pushstring(L, name);
4803 lua_gettable(L, -2);
4804 // Should be a table, which we will use as a prototype
4805 //luaL_checktype(L, -1, LUA_TTABLE);
4806 if(lua_type(L, -1) != LUA_TTABLE){
4807 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4810 int prototype_table = lua_gettop(L);
4811 //dump2(L, "prototype_table");
4813 // Create entity object
4815 int object = lua_gettop(L);
4817 // Set object metatable
4818 lua_pushvalue(L, prototype_table);
4819 lua_setmetatable(L, -2);
4821 // Add object reference
4822 // This should be userdata with metatable ObjectRef
4823 objectref_get(L, id);
4824 luaL_checktype(L, -1, LUA_TUSERDATA);
4825 if(!luaL_checkudata(L, -1, "ObjectRef"))
4826 luaL_typerror(L, -1, "ObjectRef");
4827 lua_setfield(L, -2, "object");
4829 // minetest.luaentities[id] = object
4830 lua_getglobal(L, "minetest");
4831 lua_getfield(L, -1, "luaentities");
4832 luaL_checktype(L, -1, LUA_TTABLE);
4833 lua_pushnumber(L, id); // Push id
4834 lua_pushvalue(L, object); // Copy object to top of stack
4835 lua_settable(L, -3);
4840 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4841 const std::string &staticdata)
4844 assert(lua_checkstack(L, 20));
4845 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4846 StackUnroller stack_unroller(L);
4848 // Get minetest.luaentities[id]
4849 luaentity_get(L, id);
4850 int object = lua_gettop(L);
4852 // Get on_activate function
4853 lua_pushvalue(L, object);
4854 lua_getfield(L, -1, "on_activate");
4855 if(!lua_isnil(L, -1)){
4856 luaL_checktype(L, -1, LUA_TFUNCTION);
4857 lua_pushvalue(L, object); // self
4858 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4859 // Call with 2 arguments, 0 results
4860 if(lua_pcall(L, 2, 0, 0))
4861 script_error(L, "error running function on_activate: %s\n",
4862 lua_tostring(L, -1));
4866 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4869 assert(lua_checkstack(L, 20));
4870 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4872 // Get minetest.luaentities table
4873 lua_getglobal(L, "minetest");
4874 lua_getfield(L, -1, "luaentities");
4875 luaL_checktype(L, -1, LUA_TTABLE);
4876 int objectstable = lua_gettop(L);
4878 // Set luaentities[id] = nil
4879 lua_pushnumber(L, id); // Push id
4881 lua_settable(L, objectstable);
4883 lua_pop(L, 2); // pop luaentities, minetest
4886 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4889 assert(lua_checkstack(L, 20));
4890 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4891 StackUnroller stack_unroller(L);
4893 // Get minetest.luaentities[id]
4894 luaentity_get(L, id);
4895 int object = lua_gettop(L);
4897 // Get get_staticdata function
4898 lua_pushvalue(L, object);
4899 lua_getfield(L, -1, "get_staticdata");
4900 if(lua_isnil(L, -1))
4903 luaL_checktype(L, -1, LUA_TFUNCTION);
4904 lua_pushvalue(L, object); // self
4905 // Call with 1 arguments, 1 results
4906 if(lua_pcall(L, 1, 1, 0))
4907 script_error(L, "error running function get_staticdata: %s\n",
4908 lua_tostring(L, -1));
4911 const char *s = lua_tolstring(L, -1, &len);
4912 return std::string(s, len);
4915 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4916 ObjectProperties *prop)
4919 assert(lua_checkstack(L, 20));
4920 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4921 StackUnroller stack_unroller(L);
4923 // Get minetest.luaentities[id]
4924 luaentity_get(L, id);
4925 //int object = lua_gettop(L);
4927 // Set default values that differ from ObjectProperties defaults
4930 // Deprecated: read object properties directly
4931 read_object_properties(L, -1, prop);
4933 // Read initial_properties
4934 lua_getfield(L, -1, "initial_properties");
4935 read_object_properties(L, -1, prop);
4939 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4942 assert(lua_checkstack(L, 20));
4943 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4944 StackUnroller stack_unroller(L);
4946 // Get minetest.luaentities[id]
4947 luaentity_get(L, id);
4948 int object = lua_gettop(L);
4949 // State: object is at top of stack
4950 // Get step function
4951 lua_getfield(L, -1, "on_step");
4952 if(lua_isnil(L, -1))
4954 luaL_checktype(L, -1, LUA_TFUNCTION);
4955 lua_pushvalue(L, object); // self
4956 lua_pushnumber(L, dtime); // dtime
4957 // Call with 2 arguments, 0 results
4958 if(lua_pcall(L, 2, 0, 0))
4959 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4962 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4963 // tool_capabilities, direction)
4964 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4965 ServerActiveObject *puncher, float time_from_last_punch,
4966 const ToolCapabilities *toolcap, v3f dir)
4969 assert(lua_checkstack(L, 20));
4970 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4971 StackUnroller stack_unroller(L);
4973 // Get minetest.luaentities[id]
4974 luaentity_get(L, id);
4975 int object = lua_gettop(L);
4976 // State: object is at top of stack
4978 lua_getfield(L, -1, "on_punch");
4979 if(lua_isnil(L, -1))
4981 luaL_checktype(L, -1, LUA_TFUNCTION);
4982 lua_pushvalue(L, object); // self
4983 objectref_get_or_create(L, puncher); // Clicker reference
4984 lua_pushnumber(L, time_from_last_punch);
4985 push_tool_capabilities(L, *toolcap);
4987 // Call with 5 arguments, 0 results
4988 if(lua_pcall(L, 5, 0, 0))
4989 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4992 // Calls entity:on_rightclick(ObjectRef clicker)
4993 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4994 ServerActiveObject *clicker)
4997 assert(lua_checkstack(L, 20));
4998 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4999 StackUnroller stack_unroller(L);
5001 // Get minetest.luaentities[id]
5002 luaentity_get(L, id);
5003 int object = lua_gettop(L);
5004 // State: object is at top of stack
5006 lua_getfield(L, -1, "on_rightclick");
5007 if(lua_isnil(L, -1))
5009 luaL_checktype(L, -1, LUA_TFUNCTION);
5010 lua_pushvalue(L, object); // self
5011 objectref_get_or_create(L, clicker); // Clicker reference
5012 // Call with 2 arguments, 0 results
5013 if(lua_pcall(L, 2, 0, 0))
5014 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));