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()))
3046 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3047 int objectid = env->addActiveObject(obj);
3048 // If failed to add, return nothing (reads as nil)
3052 objectref_get_or_create(L, obj);
3056 // EnvRef:add_rat(pos)
3057 // pos = {x=num, y=num, z=num}
3058 static int l_add_rat(lua_State *L)
3060 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3061 <<" Doing nothing."<<std::endl;
3065 // EnvRef:add_firefly(pos)
3066 // pos = {x=num, y=num, z=num}
3067 static int l_add_firefly(lua_State *L)
3069 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3070 <<" Doing nothing."<<std::endl;
3074 // EnvRef:get_meta(pos)
3075 static int l_get_meta(lua_State *L)
3077 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3078 EnvRef *o = checkobject(L, 1);
3079 ServerEnvironment *env = o->m_env;
3080 if(env == NULL) return 0;
3082 v3s16 p = read_v3s16(L, 2);
3083 NodeMetaRef::create(L, p, env);
3087 // EnvRef:get_player_by_name(name)
3088 static int l_get_player_by_name(lua_State *L)
3090 EnvRef *o = checkobject(L, 1);
3091 ServerEnvironment *env = o->m_env;
3092 if(env == NULL) return 0;
3094 const char *name = luaL_checkstring(L, 2);
3095 Player *player = env->getPlayer(name);
3100 PlayerSAO *sao = player->getPlayerSAO();
3105 // Put player on stack
3106 objectref_get_or_create(L, sao);
3110 // EnvRef:get_objects_inside_radius(pos, radius)
3111 static int l_get_objects_inside_radius(lua_State *L)
3113 // Get the table insert function
3114 lua_getglobal(L, "table");
3115 lua_getfield(L, -1, "insert");
3116 int table_insert = lua_gettop(L);
3118 EnvRef *o = checkobject(L, 1);
3119 ServerEnvironment *env = o->m_env;
3120 if(env == NULL) return 0;
3122 v3f pos = checkFloatPos(L, 2);
3123 float radius = luaL_checknumber(L, 3) * BS;
3124 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3126 int table = lua_gettop(L);
3127 for(std::set<u16>::const_iterator
3128 i = ids.begin(); i != ids.end(); i++){
3129 ServerActiveObject *obj = env->getActiveObject(*i);
3130 // Insert object reference into table
3131 lua_pushvalue(L, table_insert);
3132 lua_pushvalue(L, table);
3133 objectref_get_or_create(L, obj);
3134 if(lua_pcall(L, 2, 0, 0))
3135 script_error(L, "error: %s", lua_tostring(L, -1));
3140 // EnvRef:set_timeofday(val)
3142 static int l_set_timeofday(lua_State *L)
3144 EnvRef *o = checkobject(L, 1);
3145 ServerEnvironment *env = o->m_env;
3146 if(env == NULL) return 0;
3148 float timeofday_f = luaL_checknumber(L, 2);
3149 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3150 int timeofday_mh = (int)(timeofday_f * 24000.0);
3151 // This should be set directly in the environment but currently
3152 // such changes aren't immediately sent to the clients, so call
3153 // the server instead.
3154 //env->setTimeOfDay(timeofday_mh);
3155 get_server(L)->setTimeOfDay(timeofday_mh);
3159 // EnvRef:get_timeofday() -> 0...1
3160 static int l_get_timeofday(lua_State *L)
3162 EnvRef *o = checkobject(L, 1);
3163 ServerEnvironment *env = o->m_env;
3164 if(env == NULL) return 0;
3166 int timeofday_mh = env->getTimeOfDay();
3167 float timeofday_f = (float)timeofday_mh / 24000.0;
3168 lua_pushnumber(L, timeofday_f);
3172 static int gc_object(lua_State *L) {
3173 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3179 EnvRef(ServerEnvironment *env):
3182 //infostream<<"EnvRef created"<<std::endl;
3187 //infostream<<"EnvRef destructing"<<std::endl;
3190 // Creates an EnvRef and leaves it on top of stack
3191 // Not callable from Lua; all references are created on the C side.
3192 static void create(lua_State *L, ServerEnvironment *env)
3194 EnvRef *o = new EnvRef(env);
3195 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3196 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3197 luaL_getmetatable(L, className);
3198 lua_setmetatable(L, -2);
3201 static void set_null(lua_State *L)
3203 EnvRef *o = checkobject(L, -1);
3207 static void Register(lua_State *L)
3210 int methodtable = lua_gettop(L);
3211 luaL_newmetatable(L, className);
3212 int metatable = lua_gettop(L);
3214 lua_pushliteral(L, "__metatable");
3215 lua_pushvalue(L, methodtable);
3216 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3218 lua_pushliteral(L, "__index");
3219 lua_pushvalue(L, methodtable);
3220 lua_settable(L, metatable);
3222 lua_pushliteral(L, "__gc");
3223 lua_pushcfunction(L, gc_object);
3224 lua_settable(L, metatable);
3226 lua_pop(L, 1); // drop metatable
3228 luaL_openlib(L, 0, methods, 0); // fill methodtable
3229 lua_pop(L, 1); // drop methodtable
3231 // Cannot be created from Lua
3232 //lua_register(L, className, create_object);
3235 const char EnvRef::className[] = "EnvRef";
3236 const luaL_reg EnvRef::methods[] = {
3237 method(EnvRef, set_node),
3238 method(EnvRef, add_node),
3239 method(EnvRef, remove_node),
3240 method(EnvRef, get_node),
3241 method(EnvRef, get_node_or_nil),
3242 method(EnvRef, get_node_light),
3243 method(EnvRef, add_entity),
3244 method(EnvRef, add_item),
3245 method(EnvRef, add_rat),
3246 method(EnvRef, add_firefly),
3247 method(EnvRef, get_meta),
3248 method(EnvRef, get_player_by_name),
3249 method(EnvRef, get_objects_inside_radius),
3250 method(EnvRef, set_timeofday),
3251 method(EnvRef, get_timeofday),
3259 class LuaPseudoRandom
3262 PseudoRandom m_pseudo;
3264 static const char className[];
3265 static const luaL_reg methods[];
3267 // Exported functions
3269 // garbage collector
3270 static int gc_object(lua_State *L)
3272 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3277 // next(self, min=0, max=32767) -> get next value
3278 static int l_next(lua_State *L)
3280 LuaPseudoRandom *o = checkobject(L, 1);
3283 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3284 if(!lua_isnil(L, 2))
3285 min = luaL_checkinteger(L, 2);
3286 if(!lua_isnil(L, 3))
3287 max = luaL_checkinteger(L, 3);
3288 if(max - min != 32767 && max - min > 32767/5)
3289 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.");
3290 PseudoRandom &pseudo = o->m_pseudo;
3291 int val = pseudo.next();
3292 val = (val % (max-min+1)) + min;
3293 lua_pushinteger(L, val);
3298 LuaPseudoRandom(int seed):
3307 const PseudoRandom& getItem() const
3311 PseudoRandom& getItem()
3316 // LuaPseudoRandom(seed)
3317 // Creates an LuaPseudoRandom and leaves it on top of stack
3318 static int create_object(lua_State *L)
3320 int seed = luaL_checknumber(L, 1);
3321 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3322 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3323 luaL_getmetatable(L, className);
3324 lua_setmetatable(L, -2);
3328 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3330 luaL_checktype(L, narg, LUA_TUSERDATA);
3331 void *ud = luaL_checkudata(L, narg, className);
3332 if(!ud) luaL_typerror(L, narg, className);
3333 return *(LuaPseudoRandom**)ud; // unbox pointer
3336 static void Register(lua_State *L)
3339 int methodtable = lua_gettop(L);
3340 luaL_newmetatable(L, className);
3341 int metatable = lua_gettop(L);
3343 lua_pushliteral(L, "__metatable");
3344 lua_pushvalue(L, methodtable);
3345 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3347 lua_pushliteral(L, "__index");
3348 lua_pushvalue(L, methodtable);
3349 lua_settable(L, metatable);
3351 lua_pushliteral(L, "__gc");
3352 lua_pushcfunction(L, gc_object);
3353 lua_settable(L, metatable);
3355 lua_pop(L, 1); // drop metatable
3357 luaL_openlib(L, 0, methods, 0); // fill methodtable
3358 lua_pop(L, 1); // drop methodtable
3360 // Can be created from Lua (LuaPseudoRandom(seed))
3361 lua_register(L, className, create_object);
3364 const char LuaPseudoRandom::className[] = "PseudoRandom";
3365 const luaL_reg LuaPseudoRandom::methods[] = {
3366 method(LuaPseudoRandom, next),
3374 class LuaABM : public ActiveBlockModifier
3380 std::set<std::string> m_trigger_contents;
3381 std::set<std::string> m_required_neighbors;
3382 float m_trigger_interval;
3383 u32 m_trigger_chance;
3385 LuaABM(lua_State *L, int id,
3386 const std::set<std::string> &trigger_contents,
3387 const std::set<std::string> &required_neighbors,
3388 float trigger_interval, u32 trigger_chance):
3391 m_trigger_contents(trigger_contents),
3392 m_required_neighbors(required_neighbors),
3393 m_trigger_interval(trigger_interval),
3394 m_trigger_chance(trigger_chance)
3397 virtual std::set<std::string> getTriggerContents()
3399 return m_trigger_contents;
3401 virtual std::set<std::string> getRequiredNeighbors()
3403 return m_required_neighbors;
3405 virtual float getTriggerInterval()
3407 return m_trigger_interval;
3409 virtual u32 getTriggerChance()
3411 return m_trigger_chance;
3413 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3414 u32 active_object_count, u32 active_object_count_wider)
3416 lua_State *L = m_lua;
3419 assert(lua_checkstack(L, 20));
3420 StackUnroller stack_unroller(L);
3422 // Get minetest.registered_abms
3423 lua_getglobal(L, "minetest");
3424 lua_getfield(L, -1, "registered_abms");
3425 luaL_checktype(L, -1, LUA_TTABLE);
3426 int registered_abms = lua_gettop(L);
3428 // Get minetest.registered_abms[m_id]
3429 lua_pushnumber(L, m_id);
3430 lua_gettable(L, registered_abms);
3431 if(lua_isnil(L, -1))
3435 luaL_checktype(L, -1, LUA_TTABLE);
3436 lua_getfield(L, -1, "action");
3437 luaL_checktype(L, -1, LUA_TFUNCTION);
3439 pushnode(L, n, env->getGameDef()->ndef());
3440 lua_pushnumber(L, active_object_count);
3441 lua_pushnumber(L, active_object_count_wider);
3442 if(lua_pcall(L, 4, 0, 0))
3443 script_error(L, "error: %s", lua_tostring(L, -1));
3451 static void read_server_sound_params(lua_State *L, int index,
3452 ServerSoundParams ¶ms)
3455 index = lua_gettop(L) + 1 + index;
3457 params = ServerSoundParams();
3458 if(lua_istable(L, index)){
3459 getfloatfield(L, index, "gain", params.gain);
3460 getstringfield(L, index, "to_player", params.to_player);
3461 lua_getfield(L, index, "pos");
3462 if(!lua_isnil(L, -1)){
3463 v3f p = read_v3f(L, -1)*BS;
3465 params.type = ServerSoundParams::SSP_POSITIONAL;
3468 lua_getfield(L, index, "object");
3469 if(!lua_isnil(L, -1)){
3470 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3471 ServerActiveObject *sao = ObjectRef::getobject(ref);
3473 params.object = sao->getId();
3474 params.type = ServerSoundParams::SSP_OBJECT;
3478 params.max_hear_distance = BS*getfloatfield_default(L, index,
3479 "max_hear_distance", params.max_hear_distance/BS);
3480 getboolfield(L, index, "loop", params.loop);
3489 // Writes a line to dstream
3490 static int l_debug(lua_State *L)
3492 std::string text = lua_tostring(L, 1);
3493 dstream << text << std::endl;
3497 // log([level,] text)
3498 // Writes a line to the logger.
3499 // The one-argument version logs to infostream.
3500 // The two-argument version accept a log level: error, action, info, or verbose.
3501 static int l_log(lua_State *L)
3504 LogMessageLevel level = LMT_INFO;
3505 if(lua_isnone(L, 2))
3507 text = lua_tostring(L, 1);
3511 std::string levelname = lua_tostring(L, 1);
3512 text = lua_tostring(L, 2);
3513 if(levelname == "error")
3515 else if(levelname == "action")
3517 else if(levelname == "verbose")
3518 level = LMT_VERBOSE;
3520 log_printline(level, text);
3524 // register_item_raw({lots of stuff})
3525 static int l_register_item_raw(lua_State *L)
3527 luaL_checktype(L, 1, LUA_TTABLE);
3530 // Get the writable item and node definition managers from the server
3531 IWritableItemDefManager *idef =
3532 get_server(L)->getWritableItemDefManager();
3533 IWritableNodeDefManager *ndef =
3534 get_server(L)->getWritableNodeDefManager();
3536 // Check if name is defined
3537 lua_getfield(L, table, "name");
3538 if(lua_isstring(L, -1)){
3539 std::string name = lua_tostring(L, -1);
3540 verbosestream<<"register_item_raw: "<<name<<std::endl;
3542 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3545 // Check if on_use is defined
3547 // Read the item definition and register it
3548 ItemDefinition def = read_item_definition(L, table);
3549 idef->registerItem(def);
3551 // Read the node definition (content features) and register it
3552 if(def.type == ITEM_NODE)
3554 ContentFeatures f = read_content_features(L, table);
3555 ndef->set(f.name, f);
3558 return 0; /* number of results */
3561 // register_alias_raw(name, convert_to_name)
3562 static int l_register_alias_raw(lua_State *L)
3564 std::string name = luaL_checkstring(L, 1);
3565 std::string convert_to = luaL_checkstring(L, 2);
3567 // Get the writable item definition manager from the server
3568 IWritableItemDefManager *idef =
3569 get_server(L)->getWritableItemDefManager();
3571 idef->registerAlias(name, convert_to);
3573 return 0; /* number of results */
3576 // helper for register_craft
3577 static bool read_craft_recipe_shaped(lua_State *L, int index,
3578 int &width, std::vector<std::string> &recipe)
3581 index = lua_gettop(L) + 1 + index;
3583 if(!lua_istable(L, index))
3588 while(lua_next(L, index) != 0){
3590 // key at index -2 and value at index -1
3591 if(!lua_istable(L, -1))
3593 int table2 = lua_gettop(L);
3595 while(lua_next(L, table2) != 0){
3596 // key at index -2 and value at index -1
3597 if(!lua_isstring(L, -1))
3599 recipe.push_back(lua_tostring(L, -1));
3600 // removes value, keeps key for next iteration
3607 if(colcount != width)
3610 // removes value, keeps key for next iteration
3617 // helper for register_craft
3618 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3619 std::vector<std::string> &recipe)
3622 index = lua_gettop(L) + 1 + index;
3624 if(!lua_istable(L, index))
3628 while(lua_next(L, index) != 0){
3629 // key at index -2 and value at index -1
3630 if(!lua_isstring(L, -1))
3632 recipe.push_back(lua_tostring(L, -1));
3633 // removes value, keeps key for next iteration
3639 // helper for register_craft
3640 static bool read_craft_replacements(lua_State *L, int index,
3641 CraftReplacements &replacements)
3644 index = lua_gettop(L) + 1 + index;
3646 if(!lua_istable(L, index))
3650 while(lua_next(L, index) != 0){
3651 // key at index -2 and value at index -1
3652 if(!lua_istable(L, -1))
3654 lua_rawgeti(L, -1, 1);
3655 if(!lua_isstring(L, -1))
3657 std::string replace_from = lua_tostring(L, -1);
3659 lua_rawgeti(L, -1, 2);
3660 if(!lua_isstring(L, -1))
3662 std::string replace_to = lua_tostring(L, -1);
3664 replacements.pairs.push_back(
3665 std::make_pair(replace_from, replace_to));
3666 // removes value, keeps key for next iteration
3671 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3672 static int l_register_craft(lua_State *L)
3674 //infostream<<"register_craft"<<std::endl;
3675 luaL_checktype(L, 1, LUA_TTABLE);
3678 // Get the writable craft definition manager from the server
3679 IWritableCraftDefManager *craftdef =
3680 get_server(L)->getWritableCraftDefManager();
3682 std::string type = getstringfield_default(L, table, "type", "shaped");
3685 CraftDefinitionShaped
3687 if(type == "shaped"){
3688 std::string output = getstringfield_default(L, table, "output", "");
3690 throw LuaError(L, "Crafting definition is missing an output");
3693 std::vector<std::string> recipe;
3694 lua_getfield(L, table, "recipe");
3695 if(lua_isnil(L, -1))
3696 throw LuaError(L, "Crafting definition is missing a recipe"
3697 " (output=\"" + output + "\")");
3698 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3699 throw LuaError(L, "Invalid crafting recipe"
3700 " (output=\"" + output + "\")");
3702 CraftReplacements replacements;
3703 lua_getfield(L, table, "replacements");
3704 if(!lua_isnil(L, -1))
3706 if(!read_craft_replacements(L, -1, replacements))
3707 throw LuaError(L, "Invalid replacements"
3708 " (output=\"" + output + "\")");
3711 CraftDefinition *def = new CraftDefinitionShaped(
3712 output, width, recipe, replacements);
3713 craftdef->registerCraft(def);
3716 CraftDefinitionShapeless
3718 else if(type == "shapeless"){
3719 std::string output = getstringfield_default(L, table, "output", "");
3721 throw LuaError(L, "Crafting definition (shapeless)"
3722 " is missing an output");
3724 std::vector<std::string> recipe;
3725 lua_getfield(L, table, "recipe");
3726 if(lua_isnil(L, -1))
3727 throw LuaError(L, "Crafting definition (shapeless)"
3728 " is missing a recipe"
3729 " (output=\"" + output + "\")");
3730 if(!read_craft_recipe_shapeless(L, -1, recipe))
3731 throw LuaError(L, "Invalid crafting recipe"
3732 " (output=\"" + output + "\")");
3734 CraftReplacements replacements;
3735 lua_getfield(L, table, "replacements");
3736 if(!lua_isnil(L, -1))
3738 if(!read_craft_replacements(L, -1, replacements))
3739 throw LuaError(L, "Invalid replacements"
3740 " (output=\"" + output + "\")");
3743 CraftDefinition *def = new CraftDefinitionShapeless(
3744 output, recipe, replacements);
3745 craftdef->registerCraft(def);
3748 CraftDefinitionToolRepair
3750 else if(type == "toolrepair"){
3751 float additional_wear = getfloatfield_default(L, table,
3752 "additional_wear", 0.0);
3754 CraftDefinition *def = new CraftDefinitionToolRepair(
3756 craftdef->registerCraft(def);
3759 CraftDefinitionCooking
3761 else if(type == "cooking"){
3762 std::string output = getstringfield_default(L, table, "output", "");
3764 throw LuaError(L, "Crafting definition (cooking)"
3765 " is missing an output");
3767 std::string recipe = getstringfield_default(L, table, "recipe", "");
3769 throw LuaError(L, "Crafting definition (cooking)"
3770 " is missing a recipe"
3771 " (output=\"" + output + "\")");
3773 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
3775 CraftDefinition *def = new CraftDefinitionCooking(
3776 output, recipe, cooktime);
3777 craftdef->registerCraft(def);
3782 else if(type == "fuel"){
3783 std::string recipe = getstringfield_default(L, table, "recipe", "");
3785 throw LuaError(L, "Crafting definition (fuel)"
3786 " is missing a recipe");
3788 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
3790 CraftDefinition *def = new CraftDefinitionFuel(
3792 craftdef->registerCraft(def);
3796 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
3800 return 0; /* number of results */
3803 // setting_get(name)
3804 static int l_setting_get(lua_State *L)
3806 const char *name = luaL_checkstring(L, 1);
3808 std::string value = g_settings->get(name);
3809 lua_pushstring(L, value.c_str());
3810 } catch(SettingNotFoundException &e){
3816 // setting_getbool(name)
3817 static int l_setting_getbool(lua_State *L)
3819 const char *name = luaL_checkstring(L, 1);
3821 bool value = g_settings->getBool(name);
3822 lua_pushboolean(L, value);
3823 } catch(SettingNotFoundException &e){
3829 // chat_send_all(text)
3830 static int l_chat_send_all(lua_State *L)
3832 const char *text = luaL_checkstring(L, 1);
3833 // Get server from registry
3834 Server *server = get_server(L);
3836 server->notifyPlayers(narrow_to_wide(text));
3840 // chat_send_player(name, text)
3841 static int l_chat_send_player(lua_State *L)
3843 const char *name = luaL_checkstring(L, 1);
3844 const char *text = luaL_checkstring(L, 2);
3845 // Get server from registry
3846 Server *server = get_server(L);
3848 server->notifyPlayer(name, narrow_to_wide(text));
3852 // get_player_privs(name, text)
3853 static int l_get_player_privs(lua_State *L)
3855 const char *name = luaL_checkstring(L, 1);
3856 // Get server from registry
3857 Server *server = get_server(L);
3860 int table = lua_gettop(L);
3861 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
3862 for(std::set<std::string>::const_iterator
3863 i = privs_s.begin(); i != privs_s.end(); i++){
3864 lua_pushboolean(L, true);
3865 lua_setfield(L, table, i->c_str());
3867 lua_pushvalue(L, table);
3871 // get_inventory(location)
3872 static int l_get_inventory(lua_State *L)
3874 InventoryLocation loc;
3876 std::string type = checkstringfield(L, 1, "type");
3877 if(type == "player"){
3878 std::string name = checkstringfield(L, 1, "name");
3879 loc.setPlayer(name);
3880 } else if(type == "node"){
3881 lua_getfield(L, 1, "pos");
3882 v3s16 pos = check_v3s16(L, -1);
3883 loc.setNodeMeta(pos);
3886 if(get_server(L)->getInventory(loc) != NULL)
3887 InvRef::create(L, loc);
3893 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
3894 static int l_get_dig_params(lua_State *L)
3896 std::map<std::string, int> groups;
3897 read_groups(L, 1, groups);
3898 ToolCapabilities tp = read_tool_capabilities(L, 2);
3899 if(lua_isnoneornil(L, 3))
3900 push_dig_params(L, getDigParams(groups, &tp));
3902 push_dig_params(L, getDigParams(groups, &tp,
3903 luaL_checknumber(L, 3)));
3907 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
3908 static int l_get_hit_params(lua_State *L)
3910 std::map<std::string, int> groups;
3911 read_groups(L, 1, groups);
3912 ToolCapabilities tp = read_tool_capabilities(L, 2);
3913 if(lua_isnoneornil(L, 3))
3914 push_hit_params(L, getHitParams(groups, &tp));
3916 push_hit_params(L, getHitParams(groups, &tp,
3917 luaL_checknumber(L, 3)));
3921 // get_current_modname()
3922 static int l_get_current_modname(lua_State *L)
3924 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
3928 // get_modpath(modname)
3929 static int l_get_modpath(lua_State *L)
3931 std::string modname = luaL_checkstring(L, 1);
3933 if(modname == "__builtin"){
3934 std::string path = get_server(L)->getBuiltinLuaPath();
3935 lua_pushstring(L, path.c_str());
3938 const ModSpec *mod = get_server(L)->getModSpec(modname);
3943 lua_pushstring(L, mod->path.c_str());
3948 static int l_get_worldpath(lua_State *L)
3950 std::string worldpath = get_server(L)->getWorldPath();
3951 lua_pushstring(L, worldpath.c_str());
3955 // sound_play(spec, parameters)
3956 static int l_sound_play(lua_State *L)
3958 SimpleSoundSpec spec;
3959 read_soundspec(L, 1, spec);
3960 ServerSoundParams params;
3961 read_server_sound_params(L, 2, params);
3962 s32 handle = get_server(L)->playSound(spec, params);
3963 lua_pushinteger(L, handle);
3967 // sound_stop(handle)
3968 static int l_sound_stop(lua_State *L)
3970 int handle = luaL_checkinteger(L, 1);
3971 get_server(L)->stopSound(handle);
3975 // is_singleplayer()
3976 static int l_is_singleplayer(lua_State *L)
3978 lua_pushboolean(L, get_server(L)->isSingleplayer());
3982 // get_password_hash(name, raw_password)
3983 static int l_get_password_hash(lua_State *L)
3985 std::string name = luaL_checkstring(L, 1);
3986 std::string raw_password = luaL_checkstring(L, 2);
3987 std::string hash = translatePassword(name,
3988 narrow_to_wide(raw_password));
3989 lua_pushstring(L, hash.c_str());
3993 // notify_authentication_modified(name)
3994 static int l_notify_authentication_modified(lua_State *L)
3996 std::string name = "";
3997 if(lua_isstring(L, 1))
3998 name = lua_tostring(L, 1);
3999 get_server(L)->reportPrivsModified(name);
4003 static const struct luaL_Reg minetest_f [] = {
4006 {"register_item_raw", l_register_item_raw},
4007 {"register_alias_raw", l_register_alias_raw},
4008 {"register_craft", l_register_craft},
4009 {"setting_get", l_setting_get},
4010 {"setting_getbool", l_setting_getbool},
4011 {"chat_send_all", l_chat_send_all},
4012 {"chat_send_player", l_chat_send_player},
4013 {"get_player_privs", l_get_player_privs},
4014 {"get_inventory", l_get_inventory},
4015 {"get_dig_params", l_get_dig_params},
4016 {"get_hit_params", l_get_hit_params},
4017 {"get_current_modname", l_get_current_modname},
4018 {"get_modpath", l_get_modpath},
4019 {"get_worldpath", l_get_worldpath},
4020 {"sound_play", l_sound_play},
4021 {"sound_stop", l_sound_stop},
4022 {"is_singleplayer", l_is_singleplayer},
4023 {"get_password_hash", l_get_password_hash},
4024 {"notify_authentication_modified", l_notify_authentication_modified},
4029 Main export function
4032 void scriptapi_export(lua_State *L, Server *server)
4035 assert(lua_checkstack(L, 20));
4036 verbosestream<<"scriptapi_export()"<<std::endl;
4037 StackUnroller stack_unroller(L);
4039 // Store server as light userdata in registry
4040 lua_pushlightuserdata(L, server);
4041 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4043 // Register global functions in table minetest
4045 luaL_register(L, NULL, minetest_f);
4046 lua_setglobal(L, "minetest");
4048 // Get the main minetest table
4049 lua_getglobal(L, "minetest");
4051 // Add tables to minetest
4054 lua_setfield(L, -2, "object_refs");
4056 lua_setfield(L, -2, "luaentities");
4058 // Register wrappers
4059 LuaItemStack::Register(L);
4060 InvRef::Register(L);
4061 NodeMetaRef::Register(L);
4062 ObjectRef::Register(L);
4063 EnvRef::Register(L);
4064 LuaPseudoRandom::Register(L);
4067 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4068 const std::string &modname)
4070 ModNameStorer modnamestorer(L, modname);
4072 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4074 errorstream<<"Error loading mod \""<<modname
4075 <<"\": modname does not follow naming conventions: "
4076 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4080 bool success = false;
4083 success = script_load(L, scriptpath.c_str());
4086 errorstream<<"Error loading mod \""<<modname
4087 <<"\": "<<e.what()<<std::endl;
4093 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4096 assert(lua_checkstack(L, 20));
4097 verbosestream<<"scriptapi_add_environment"<<std::endl;
4098 StackUnroller stack_unroller(L);
4100 // Create EnvRef on stack
4101 EnvRef::create(L, env);
4102 int envref = lua_gettop(L);
4104 // minetest.env = envref
4105 lua_getglobal(L, "minetest");
4106 luaL_checktype(L, -1, LUA_TTABLE);
4107 lua_pushvalue(L, envref);
4108 lua_setfield(L, -2, "env");
4110 // Store environment as light userdata in registry
4111 lua_pushlightuserdata(L, env);
4112 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4115 Add ActiveBlockModifiers to environment
4118 // Get minetest.registered_abms
4119 lua_getglobal(L, "minetest");
4120 lua_getfield(L, -1, "registered_abms");
4121 luaL_checktype(L, -1, LUA_TTABLE);
4122 int registered_abms = lua_gettop(L);
4124 if(lua_istable(L, registered_abms)){
4125 int table = lua_gettop(L);
4127 while(lua_next(L, table) != 0){
4128 // key at index -2 and value at index -1
4129 int id = lua_tonumber(L, -2);
4130 int current_abm = lua_gettop(L);
4132 std::set<std::string> trigger_contents;
4133 lua_getfield(L, current_abm, "nodenames");
4134 if(lua_istable(L, -1)){
4135 int table = lua_gettop(L);
4137 while(lua_next(L, table) != 0){
4138 // key at index -2 and value at index -1
4139 luaL_checktype(L, -1, LUA_TSTRING);
4140 trigger_contents.insert(lua_tostring(L, -1));
4141 // removes value, keeps key for next iteration
4144 } else if(lua_isstring(L, -1)){
4145 trigger_contents.insert(lua_tostring(L, -1));
4149 std::set<std::string> required_neighbors;
4150 lua_getfield(L, current_abm, "neighbors");
4151 if(lua_istable(L, -1)){
4152 int table = lua_gettop(L);
4154 while(lua_next(L, table) != 0){
4155 // key at index -2 and value at index -1
4156 luaL_checktype(L, -1, LUA_TSTRING);
4157 required_neighbors.insert(lua_tostring(L, -1));
4158 // removes value, keeps key for next iteration
4161 } else if(lua_isstring(L, -1)){
4162 required_neighbors.insert(lua_tostring(L, -1));
4166 float trigger_interval = 10.0;
4167 getfloatfield(L, current_abm, "interval", trigger_interval);
4169 int trigger_chance = 50;
4170 getintfield(L, current_abm, "chance", trigger_chance);
4172 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4173 required_neighbors, trigger_interval, trigger_chance);
4175 env->addActiveBlockModifier(abm);
4177 // removes value, keeps key for next iteration
4185 // Dump stack top with the dump2 function
4186 static void dump2(lua_State *L, const char *name)
4188 // Dump object (debug)
4189 lua_getglobal(L, "dump2");
4190 luaL_checktype(L, -1, LUA_TFUNCTION);
4191 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4192 lua_pushstring(L, name);
4193 if(lua_pcall(L, 2, 0, 0))
4194 script_error(L, "error: %s", lua_tostring(L, -1));
4202 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4205 assert(lua_checkstack(L, 20));
4206 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4207 StackUnroller stack_unroller(L);
4209 // Create object on stack
4210 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4211 int object = lua_gettop(L);
4213 // Get minetest.object_refs table
4214 lua_getglobal(L, "minetest");
4215 lua_getfield(L, -1, "object_refs");
4216 luaL_checktype(L, -1, LUA_TTABLE);
4217 int objectstable = lua_gettop(L);
4219 // object_refs[id] = object
4220 lua_pushnumber(L, cobj->getId()); // Push id
4221 lua_pushvalue(L, object); // Copy object to top of stack
4222 lua_settable(L, objectstable);
4225 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4228 assert(lua_checkstack(L, 20));
4229 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4230 StackUnroller stack_unroller(L);
4232 // Get minetest.object_refs table
4233 lua_getglobal(L, "minetest");
4234 lua_getfield(L, -1, "object_refs");
4235 luaL_checktype(L, -1, LUA_TTABLE);
4236 int objectstable = lua_gettop(L);
4238 // Get object_refs[id]
4239 lua_pushnumber(L, cobj->getId()); // Push id
4240 lua_gettable(L, objectstable);
4241 // Set object reference to NULL
4242 ObjectRef::set_null(L);
4243 lua_pop(L, 1); // pop object
4245 // Set object_refs[id] = nil
4246 lua_pushnumber(L, cobj->getId()); // Push id
4248 lua_settable(L, objectstable);
4255 // What scriptapi_run_callbacks does with the return values of callbacks.
4256 // Regardless of the mode, if only one callback is defined,
4257 // its return value is the total return value.
4258 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4259 enum RunCallbacksMode
4261 // Returns the return value of the first callback
4262 // Returns nil if list of callbacks is empty
4263 RUN_CALLBACKS_MODE_FIRST,
4264 // Returns the return value of the last callback
4265 // Returns nil if list of callbacks is empty
4266 RUN_CALLBACKS_MODE_LAST,
4267 // If any callback returns a false value, the first such is returned
4268 // Otherwise, the first callback's return value (trueish) is returned
4269 // Returns true if list of callbacks is empty
4270 RUN_CALLBACKS_MODE_AND,
4271 // Like above, but stops calling callbacks (short circuit)
4272 // after seeing the first false value
4273 RUN_CALLBACKS_MODE_AND_SC,
4274 // If any callback returns a true value, the first such is returned
4275 // Otherwise, the first callback's return value (falseish) is returned
4276 // Returns false if list of callbacks is empty
4277 RUN_CALLBACKS_MODE_OR,
4278 // Like above, but stops calling callbacks (short circuit)
4279 // after seeing the first true value
4280 RUN_CALLBACKS_MODE_OR_SC,
4281 // Note: "a true value" and "a false value" refer to values that
4282 // are converted by lua_toboolean to true or false, respectively.
4285 // Push the list of callbacks (a lua table).
4286 // Then push nargs arguments.
4287 // Then call this function, which
4288 // - runs the callbacks
4289 // - removes the table and arguments from the lua stack
4290 // - pushes the return value, computed depending on mode
4291 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4292 RunCallbacksMode mode)
4294 // Insert the return value into the lua stack, below the table
4295 assert(lua_gettop(L) >= nargs + 1);
4297 lua_insert(L, -(nargs + 1) - 1);
4298 // Stack now looks like this:
4299 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4301 int rv = lua_gettop(L) - nargs - 1;
4303 int arg = table + 1;
4305 luaL_checktype(L, table, LUA_TTABLE);
4309 bool first_loop = true;
4310 while(lua_next(L, table) != 0){
4311 // key at index -2 and value at index -1
4312 luaL_checktype(L, -1, LUA_TFUNCTION);
4314 for(int i = 0; i < nargs; i++)
4315 lua_pushvalue(L, arg+i);
4316 if(lua_pcall(L, nargs, 1, 0))
4317 script_error(L, "error: %s", lua_tostring(L, -1));
4319 // Move return value to designated space in stack
4322 // Result of first callback is always moved
4326 // Otherwise, what happens depends on the mode
4327 if(mode == RUN_CALLBACKS_MODE_FIRST)
4329 else if(mode == RUN_CALLBACKS_MODE_LAST)
4331 else if(mode == RUN_CALLBACKS_MODE_AND ||
4332 mode == RUN_CALLBACKS_MODE_AND_SC){
4333 if(lua_toboolean(L, rv) == true &&
4334 lua_toboolean(L, -1) == false)
4339 else if(mode == RUN_CALLBACKS_MODE_OR ||
4340 mode == RUN_CALLBACKS_MODE_OR_SC){
4341 if(lua_toboolean(L, rv) == false &&
4342 lua_toboolean(L, -1) == true)
4351 // Handle short circuit modes
4352 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4353 lua_toboolean(L, rv) == false)
4355 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4356 lua_toboolean(L, rv) == true)
4359 // value removed, keep key for next iteration
4362 // Remove stuff from stack, leaving only the return value
4365 // Fix return value in case no callbacks were called
4367 if(mode == RUN_CALLBACKS_MODE_AND ||
4368 mode == RUN_CALLBACKS_MODE_AND_SC){
4370 lua_pushboolean(L, true);
4372 else if(mode == RUN_CALLBACKS_MODE_OR ||
4373 mode == RUN_CALLBACKS_MODE_OR_SC){
4375 lua_pushboolean(L, false);
4380 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4381 const std::string &message)
4384 assert(lua_checkstack(L, 20));
4385 StackUnroller stack_unroller(L);
4387 // Get minetest.registered_on_chat_messages
4388 lua_getglobal(L, "minetest");
4389 lua_getfield(L, -1, "registered_on_chat_messages");
4391 lua_pushstring(L, name.c_str());
4392 lua_pushstring(L, message.c_str());
4393 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4394 bool ate = lua_toboolean(L, -1);
4398 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4401 assert(lua_checkstack(L, 20));
4402 StackUnroller stack_unroller(L);
4404 // Get minetest.registered_on_newplayers
4405 lua_getglobal(L, "minetest");
4406 lua_getfield(L, -1, "registered_on_newplayers");
4408 objectref_get_or_create(L, player);
4409 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4412 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4415 assert(lua_checkstack(L, 20));
4416 StackUnroller stack_unroller(L);
4418 // Get minetest.registered_on_dieplayers
4419 lua_getglobal(L, "minetest");
4420 lua_getfield(L, -1, "registered_on_dieplayers");
4422 objectref_get_or_create(L, player);
4423 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4426 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4429 assert(lua_checkstack(L, 20));
4430 StackUnroller stack_unroller(L);
4432 // Get minetest.registered_on_respawnplayers
4433 lua_getglobal(L, "minetest");
4434 lua_getfield(L, -1, "registered_on_respawnplayers");
4436 objectref_get_or_create(L, player);
4437 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4438 bool positioning_handled_by_some = lua_toboolean(L, -1);
4439 return positioning_handled_by_some;
4442 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4445 assert(lua_checkstack(L, 20));
4446 StackUnroller stack_unroller(L);
4448 // Get minetest.registered_on_joinplayers
4449 lua_getglobal(L, "minetest");
4450 lua_getfield(L, -1, "registered_on_joinplayers");
4452 objectref_get_or_create(L, player);
4453 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4456 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4459 assert(lua_checkstack(L, 20));
4460 StackUnroller stack_unroller(L);
4462 // Get minetest.registered_on_leaveplayers
4463 lua_getglobal(L, "minetest");
4464 lua_getfield(L, -1, "registered_on_leaveplayers");
4466 objectref_get_or_create(L, player);
4467 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4470 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4473 assert(lua_checkstack(L, 20));
4474 StackUnroller stack_unroller(L);
4476 Inventory *inv = player->getInventory();
4479 lua_getglobal(L, "minetest");
4480 lua_getfield(L, -1, "creative_inventory");
4481 luaL_checktype(L, -1, LUA_TTABLE);
4482 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4485 static void get_auth_handler(lua_State *L)
4487 lua_getglobal(L, "minetest");
4488 lua_getfield(L, -1, "registered_auth_handler");
4489 if(lua_isnil(L, -1)){
4491 lua_getfield(L, -1, "builtin_auth_handler");
4493 if(lua_type(L, -1) != LUA_TTABLE)
4494 throw LuaError(L, "Authentication handler table not valid");
4497 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
4498 std::string *dst_password, std::set<std::string> *dst_privs)
4501 assert(lua_checkstack(L, 20));
4502 StackUnroller stack_unroller(L);
4504 get_auth_handler(L);
4505 lua_getfield(L, -1, "get_auth");
4506 if(lua_type(L, -1) != LUA_TFUNCTION)
4507 throw LuaError(L, "Authentication handler missing get_auth");
4508 lua_pushstring(L, playername.c_str());
4509 if(lua_pcall(L, 1, 1, 0))
4510 script_error(L, "error: %s", lua_tostring(L, -1));
4512 // nil = login not allowed
4513 if(lua_isnil(L, -1))
4515 luaL_checktype(L, -1, LUA_TTABLE);
4517 std::string password;
4518 bool found = getstringfield(L, -1, "password", password);
4520 throw LuaError(L, "Authentication handler didn't return password");
4522 *dst_password = password;
4524 lua_getfield(L, -1, "privileges");
4525 if(!lua_istable(L, -1))
4527 "Authentication handler didn't return privilege table");
4529 read_privileges(L, -1, *dst_privs);
4535 void scriptapi_create_auth(lua_State *L, const std::string &playername,
4536 const std::string &password)
4539 assert(lua_checkstack(L, 20));
4540 StackUnroller stack_unroller(L);
4542 get_auth_handler(L);
4543 lua_getfield(L, -1, "create_auth");
4544 if(lua_type(L, -1) != LUA_TFUNCTION)
4545 throw LuaError(L, "Authentication handler missing create_auth");
4546 lua_pushstring(L, playername.c_str());
4547 lua_pushstring(L, password.c_str());
4548 if(lua_pcall(L, 2, 0, 0))
4549 script_error(L, "error: %s", lua_tostring(L, -1));
4552 bool scriptapi_set_password(lua_State *L, const std::string &playername,
4553 const std::string &password)
4556 assert(lua_checkstack(L, 20));
4557 StackUnroller stack_unroller(L);
4559 get_auth_handler(L);
4560 lua_getfield(L, -1, "set_password");
4561 if(lua_type(L, -1) != LUA_TFUNCTION)
4562 throw LuaError(L, "Authentication handler missing set_password");
4563 lua_pushstring(L, playername.c_str());
4564 lua_pushstring(L, password.c_str());
4565 if(lua_pcall(L, 2, 1, 0))
4566 script_error(L, "error: %s", lua_tostring(L, -1));
4567 return lua_toboolean(L, -1);
4571 item callbacks and node callbacks
4574 // Retrieves minetest.registered_items[name][callbackname]
4575 // If that is nil or on error, return false and stack is unchanged
4576 // If that is a function, returns true and pushes the
4577 // function onto the stack
4578 static bool get_item_callback(lua_State *L,
4579 const char *name, const char *callbackname)
4581 lua_getglobal(L, "minetest");
4582 lua_getfield(L, -1, "registered_items");
4584 luaL_checktype(L, -1, LUA_TTABLE);
4585 lua_getfield(L, -1, name);
4587 // Should be a table
4588 if(lua_type(L, -1) != LUA_TTABLE)
4590 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4594 lua_getfield(L, -1, callbackname);
4596 // Should be a function or nil
4597 if(lua_type(L, -1) == LUA_TFUNCTION)
4601 else if(lua_isnil(L, -1))
4608 errorstream<<"Item \""<<name<<"\" callback \""
4609 <<callbackname<<" is not a function"<<std::endl;
4615 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4616 ServerActiveObject *dropper, v3f pos)
4619 assert(lua_checkstack(L, 20));
4620 StackUnroller stack_unroller(L);
4622 // Push callback function on stack
4623 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4627 LuaItemStack::create(L, item);
4628 objectref_get_or_create(L, dropper);
4629 pushFloatPos(L, pos);
4630 if(lua_pcall(L, 3, 1, 0))
4631 script_error(L, "error: %s", lua_tostring(L, -1));
4632 if(!lua_isnil(L, -1))
4633 item = read_item(L, -1);
4637 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4638 ServerActiveObject *placer, const PointedThing &pointed)
4641 assert(lua_checkstack(L, 20));
4642 StackUnroller stack_unroller(L);
4644 // Push callback function on stack
4645 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4649 LuaItemStack::create(L, item);
4650 objectref_get_or_create(L, placer);
4651 push_pointed_thing(L, pointed);
4652 if(lua_pcall(L, 3, 1, 0))
4653 script_error(L, "error: %s", lua_tostring(L, -1));
4654 if(!lua_isnil(L, -1))
4655 item = read_item(L, -1);
4659 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4660 ServerActiveObject *user, const PointedThing &pointed)
4663 assert(lua_checkstack(L, 20));
4664 StackUnroller stack_unroller(L);
4666 // Push callback function on stack
4667 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4671 LuaItemStack::create(L, item);
4672 objectref_get_or_create(L, user);
4673 push_pointed_thing(L, pointed);
4674 if(lua_pcall(L, 3, 1, 0))
4675 script_error(L, "error: %s", lua_tostring(L, -1));
4676 if(!lua_isnil(L, -1))
4677 item = read_item(L, -1);
4681 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4682 ServerActiveObject *puncher)
4685 assert(lua_checkstack(L, 20));
4686 StackUnroller stack_unroller(L);
4688 INodeDefManager *ndef = get_server(L)->ndef();
4690 // Push callback function on stack
4691 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4696 pushnode(L, node, ndef);
4697 objectref_get_or_create(L, puncher);
4698 if(lua_pcall(L, 3, 0, 0))
4699 script_error(L, "error: %s", lua_tostring(L, -1));
4703 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4704 ServerActiveObject *digger)
4707 assert(lua_checkstack(L, 20));
4708 StackUnroller stack_unroller(L);
4710 INodeDefManager *ndef = get_server(L)->ndef();
4712 // Push callback function on stack
4713 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4718 pushnode(L, node, ndef);
4719 objectref_get_or_create(L, digger);
4720 if(lua_pcall(L, 3, 0, 0))
4721 script_error(L, "error: %s", lua_tostring(L, -1));
4729 void scriptapi_environment_step(lua_State *L, float dtime)
4732 assert(lua_checkstack(L, 20));
4733 //infostream<<"scriptapi_environment_step"<<std::endl;
4734 StackUnroller stack_unroller(L);
4736 // Get minetest.registered_globalsteps
4737 lua_getglobal(L, "minetest");
4738 lua_getfield(L, -1, "registered_globalsteps");
4740 lua_pushnumber(L, dtime);
4741 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4744 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
4748 assert(lua_checkstack(L, 20));
4749 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
4750 StackUnroller stack_unroller(L);
4752 // Get minetest.registered_on_generateds
4753 lua_getglobal(L, "minetest");
4754 lua_getfield(L, -1, "registered_on_generateds");
4756 push_v3s16(L, minp);
4757 push_v3s16(L, maxp);
4758 lua_pushnumber(L, blockseed);
4759 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
4766 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
4769 assert(lua_checkstack(L, 20));
4770 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
4771 <<name<<"\""<<std::endl;
4772 StackUnroller stack_unroller(L);
4774 // Get minetest.registered_entities[name]
4775 lua_getglobal(L, "minetest");
4776 lua_getfield(L, -1, "registered_entities");
4777 luaL_checktype(L, -1, LUA_TTABLE);
4778 lua_pushstring(L, name);
4779 lua_gettable(L, -2);
4780 // Should be a table, which we will use as a prototype
4781 //luaL_checktype(L, -1, LUA_TTABLE);
4782 if(lua_type(L, -1) != LUA_TTABLE){
4783 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
4786 int prototype_table = lua_gettop(L);
4787 //dump2(L, "prototype_table");
4789 // Create entity object
4791 int object = lua_gettop(L);
4793 // Set object metatable
4794 lua_pushvalue(L, prototype_table);
4795 lua_setmetatable(L, -2);
4797 // Add object reference
4798 // This should be userdata with metatable ObjectRef
4799 objectref_get(L, id);
4800 luaL_checktype(L, -1, LUA_TUSERDATA);
4801 if(!luaL_checkudata(L, -1, "ObjectRef"))
4802 luaL_typerror(L, -1, "ObjectRef");
4803 lua_setfield(L, -2, "object");
4805 // minetest.luaentities[id] = object
4806 lua_getglobal(L, "minetest");
4807 lua_getfield(L, -1, "luaentities");
4808 luaL_checktype(L, -1, LUA_TTABLE);
4809 lua_pushnumber(L, id); // Push id
4810 lua_pushvalue(L, object); // Copy object to top of stack
4811 lua_settable(L, -3);
4816 void scriptapi_luaentity_activate(lua_State *L, u16 id,
4817 const std::string &staticdata)
4820 assert(lua_checkstack(L, 20));
4821 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
4822 StackUnroller stack_unroller(L);
4824 // Get minetest.luaentities[id]
4825 luaentity_get(L, id);
4826 int object = lua_gettop(L);
4828 // Get on_activate function
4829 lua_pushvalue(L, object);
4830 lua_getfield(L, -1, "on_activate");
4831 if(!lua_isnil(L, -1)){
4832 luaL_checktype(L, -1, LUA_TFUNCTION);
4833 lua_pushvalue(L, object); // self
4834 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
4835 // Call with 2 arguments, 0 results
4836 if(lua_pcall(L, 2, 0, 0))
4837 script_error(L, "error running function on_activate: %s\n",
4838 lua_tostring(L, -1));
4842 void scriptapi_luaentity_rm(lua_State *L, u16 id)
4845 assert(lua_checkstack(L, 20));
4846 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
4848 // Get minetest.luaentities table
4849 lua_getglobal(L, "minetest");
4850 lua_getfield(L, -1, "luaentities");
4851 luaL_checktype(L, -1, LUA_TTABLE);
4852 int objectstable = lua_gettop(L);
4854 // Set luaentities[id] = nil
4855 lua_pushnumber(L, id); // Push id
4857 lua_settable(L, objectstable);
4859 lua_pop(L, 2); // pop luaentities, minetest
4862 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
4865 assert(lua_checkstack(L, 20));
4866 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
4867 StackUnroller stack_unroller(L);
4869 // Get minetest.luaentities[id]
4870 luaentity_get(L, id);
4871 int object = lua_gettop(L);
4873 // Get get_staticdata function
4874 lua_pushvalue(L, object);
4875 lua_getfield(L, -1, "get_staticdata");
4876 if(lua_isnil(L, -1))
4879 luaL_checktype(L, -1, LUA_TFUNCTION);
4880 lua_pushvalue(L, object); // self
4881 // Call with 1 arguments, 1 results
4882 if(lua_pcall(L, 1, 1, 0))
4883 script_error(L, "error running function get_staticdata: %s\n",
4884 lua_tostring(L, -1));
4887 const char *s = lua_tolstring(L, -1, &len);
4888 return std::string(s, len);
4891 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
4892 ObjectProperties *prop)
4895 assert(lua_checkstack(L, 20));
4896 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
4897 StackUnroller stack_unroller(L);
4899 // Get minetest.luaentities[id]
4900 luaentity_get(L, id);
4901 //int object = lua_gettop(L);
4903 // Set default values that differ from ObjectProperties defaults
4906 // Deprecated: read object properties directly
4907 read_object_properties(L, -1, prop);
4909 // Read initial_properties
4910 lua_getfield(L, -1, "initial_properties");
4911 read_object_properties(L, -1, prop);
4915 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
4918 assert(lua_checkstack(L, 20));
4919 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4920 StackUnroller stack_unroller(L);
4922 // Get minetest.luaentities[id]
4923 luaentity_get(L, id);
4924 int object = lua_gettop(L);
4925 // State: object is at top of stack
4926 // Get step function
4927 lua_getfield(L, -1, "on_step");
4928 if(lua_isnil(L, -1))
4930 luaL_checktype(L, -1, LUA_TFUNCTION);
4931 lua_pushvalue(L, object); // self
4932 lua_pushnumber(L, dtime); // dtime
4933 // Call with 2 arguments, 0 results
4934 if(lua_pcall(L, 2, 0, 0))
4935 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
4938 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
4939 // tool_capabilities, direction)
4940 void scriptapi_luaentity_punch(lua_State *L, u16 id,
4941 ServerActiveObject *puncher, float time_from_last_punch,
4942 const ToolCapabilities *toolcap, v3f dir)
4945 assert(lua_checkstack(L, 20));
4946 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4947 StackUnroller stack_unroller(L);
4949 // Get minetest.luaentities[id]
4950 luaentity_get(L, id);
4951 int object = lua_gettop(L);
4952 // State: object is at top of stack
4954 lua_getfield(L, -1, "on_punch");
4955 if(lua_isnil(L, -1))
4957 luaL_checktype(L, -1, LUA_TFUNCTION);
4958 lua_pushvalue(L, object); // self
4959 objectref_get_or_create(L, puncher); // Clicker reference
4960 lua_pushnumber(L, time_from_last_punch);
4961 push_tool_capabilities(L, *toolcap);
4963 // Call with 5 arguments, 0 results
4964 if(lua_pcall(L, 5, 0, 0))
4965 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
4968 // Calls entity:on_rightclick(ObjectRef clicker)
4969 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
4970 ServerActiveObject *clicker)
4973 assert(lua_checkstack(L, 20));
4974 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
4975 StackUnroller stack_unroller(L);
4977 // Get minetest.luaentities[id]
4978 luaentity_get(L, id);
4979 int object = lua_gettop(L);
4980 // State: object is at top of stack
4982 lua_getfield(L, -1, "on_rightclick");
4983 if(lua_isnil(L, -1))
4985 luaL_checktype(L, -1, LUA_TFUNCTION);
4986 lua_pushvalue(L, object); // self
4987 objectref_get_or_create(L, clicker); // Clicker reference
4988 // Call with 2 arguments, 0 results
4989 if(lua_pcall(L, 2, 0, 0))
4990 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));