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);
918 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
925 static ItemDefinition read_item_definition(lua_State *L, int index)
928 index = lua_gettop(L) + 1 + index;
930 // Read the item definition
933 def.type = (ItemType)getenumfield(L, index, "type",
934 es_ItemType, ITEM_NONE);
935 getstringfield(L, index, "name", def.name);
936 getstringfield(L, index, "description", def.description);
937 getstringfield(L, index, "inventory_image", def.inventory_image);
938 getstringfield(L, index, "wield_image", def.wield_image);
940 lua_getfield(L, index, "wield_scale");
941 if(lua_istable(L, -1)){
942 def.wield_scale = check_v3f(L, -1);
946 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
947 if(def.stack_max == 0)
950 lua_getfield(L, index, "on_use");
951 def.usable = lua_isfunction(L, -1);
954 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
956 warn_if_field_exists(L, index, "tool_digging_properties",
957 "deprecated: use tool_capabilities");
959 lua_getfield(L, index, "tool_capabilities");
960 if(lua_istable(L, -1)){
961 def.tool_capabilities = new ToolCapabilities(
962 read_tool_capabilities(L, -1));
965 // If name is "" (hand), ensure there are ToolCapabilities
966 // because it will be looked up there whenever any other item has
967 // no ToolCapabilities
968 if(def.name == "" && def.tool_capabilities == NULL){
969 def.tool_capabilities = new ToolCapabilities();
972 lua_getfield(L, index, "groups");
973 read_groups(L, -1, def.groups);
983 static ContentFeatures read_content_features(lua_State *L, int index)
986 index = lua_gettop(L) + 1 + index;
990 getstringfield(L, index, "name", f.name);
993 lua_getfield(L, index, "groups");
994 read_groups(L, -1, f.groups);
997 /* Visual definition */
999 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1001 getfloatfield(L, index, "visual_scale", f.visual_scale);
1003 lua_getfield(L, index, "tile_images");
1004 if(lua_istable(L, -1)){
1005 int table = lua_gettop(L);
1008 while(lua_next(L, table) != 0){
1009 // key at index -2 and value at index -1
1010 if(lua_isstring(L, -1))
1011 f.tname_tiles[i] = lua_tostring(L, -1);
1013 f.tname_tiles[i] = "";
1014 // removes value, keeps key for next iteration
1022 // Copy last value to all remaining textures
1024 std::string lastname = f.tname_tiles[i-1];
1026 f.tname_tiles[i] = lastname;
1033 lua_getfield(L, index, "special_materials");
1034 if(lua_istable(L, -1)){
1035 int table = lua_gettop(L);
1038 while(lua_next(L, table) != 0){
1039 // key at index -2 and value at index -1
1040 int smtable = lua_gettop(L);
1041 std::string tname = getstringfield_default(
1042 L, smtable, "image", "");
1043 bool backface_culling = getboolfield_default(
1044 L, smtable, "backface_culling", true);
1045 MaterialSpec mspec(tname, backface_culling);
1046 f.mspec_special[i] = mspec;
1047 // removes value, keeps key for next iteration
1058 f.alpha = getintfield_default(L, index, "alpha", 255);
1062 lua_getfield(L, index, "post_effect_color");
1063 if(!lua_isnil(L, -1))
1064 f.post_effect_color = readARGB8(L, -1);
1067 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1068 es_ContentParamType, CPT_NONE);
1069 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1070 es_ContentParamType2, CPT2_NONE);
1072 // Warn about some deprecated fields
1073 warn_if_field_exists(L, index, "wall_mounted",
1074 "deprecated: use paramtype2 = 'wallmounted'");
1075 warn_if_field_exists(L, index, "light_propagates",
1076 "deprecated: determined from paramtype");
1077 warn_if_field_exists(L, index, "dug_item",
1078 "deprecated: use 'drop' field");
1079 warn_if_field_exists(L, index, "extra_dug_item",
1080 "deprecated: use 'drop' field");
1081 warn_if_field_exists(L, index, "extra_dug_item_rarity",
1082 "deprecated: use 'drop' field");
1084 // True for all ground-like things like stone and mud, false for eg. trees
1085 getboolfield(L, index, "is_ground_content", f.is_ground_content);
1086 f.light_propagates = (f.param_type == CPT_LIGHT);
1087 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1088 // This is used for collision detection.
1089 // Also for general solidness queries.
1090 getboolfield(L, index, "walkable", f.walkable);
1091 // Player can point to these
1092 getboolfield(L, index, "pointable", f.pointable);
1093 // Player can dig these
1094 getboolfield(L, index, "diggable", f.diggable);
1095 // Player can climb these
1096 getboolfield(L, index, "climbable", f.climbable);
1097 // Player can build on these
1098 getboolfield(L, index, "buildable_to", f.buildable_to);
1099 // Metadata name of node (eg. "furnace")
1100 getstringfield(L, index, "metadata_name", f.metadata_name);
1101 // Whether the node is non-liquid, source liquid or flowing liquid
1102 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1103 es_LiquidType, LIQUID_NONE);
1104 // If the content is liquid, this is the flowing version of the liquid.
1105 getstringfield(L, index, "liquid_alternative_flowing",
1106 f.liquid_alternative_flowing);
1107 // If the content is liquid, this is the source version of the liquid.
1108 getstringfield(L, index, "liquid_alternative_source",
1109 f.liquid_alternative_source);
1110 // Viscosity for fluid flow, ranging from 1 to 7, with
1111 // 1 giving almost instantaneous propagation and 7 being
1112 // the slowest possible
1113 f.liquid_viscosity = getintfield_default(L, index,
1114 "liquid_viscosity", f.liquid_viscosity);
1115 // Amount of light the node emits
1116 f.light_source = getintfield_default(L, index,
1117 "light_source", f.light_source);
1118 f.damage_per_second = getintfield_default(L, index,
1119 "damage_per_second", f.damage_per_second);
1121 lua_getfield(L, index, "selection_box");
1122 if(lua_istable(L, -1)){
1123 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
1124 es_NodeBoxType, NODEBOX_REGULAR);
1126 lua_getfield(L, -1, "fixed");
1127 if(lua_istable(L, -1))
1128 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
1131 lua_getfield(L, -1, "wall_top");
1132 if(lua_istable(L, -1))
1133 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
1136 lua_getfield(L, -1, "wall_bottom");
1137 if(lua_istable(L, -1))
1138 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
1141 lua_getfield(L, -1, "wall_side");
1142 if(lua_istable(L, -1))
1143 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
1148 // Set to true if paramtype used to be 'facedir_simple'
1149 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1150 // Set to true if wall_mounted used to be set to true
1151 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1154 lua_getfield(L, index, "sounds");
1155 if(lua_istable(L, -1)){
1156 lua_getfield(L, -1, "footstep");
1157 read_soundspec(L, -1, f.sound_footstep);
1159 lua_getfield(L, -1, "dig");
1160 read_soundspec(L, -1, f.sound_dig);
1162 lua_getfield(L, -1, "dug");
1163 read_soundspec(L, -1, f.sound_dug);
1175 static ItemStack read_item(lua_State *L, int index);
1177 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1178 lua_State *L, int tableindex, int forcesize=-1)
1181 tableindex = lua_gettop(L) + 1 + tableindex;
1182 // If nil, delete list
1183 if(lua_isnil(L, tableindex)){
1184 inv->deleteList(name);
1187 // Otherwise set list
1188 std::vector<ItemStack> items;
1189 luaL_checktype(L, tableindex, LUA_TTABLE);
1191 while(lua_next(L, tableindex) != 0){
1192 // key at index -2 and value at index -1
1193 items.push_back(read_item(L, -1));
1194 // removes value, keeps key for next iteration
1197 int listsize = (forcesize != -1) ? forcesize : items.size();
1198 InventoryList *invlist = inv->addList(name, listsize);
1200 for(std::vector<ItemStack>::const_iterator
1201 i = items.begin(); i != items.end(); i++){
1202 if(forcesize != -1 && index == forcesize)
1204 invlist->changeItem(index, *i);
1207 while(forcesize != -1 && index < forcesize){
1208 invlist->deleteItem(index);
1213 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1216 InventoryList *invlist = inv->getList(name);
1217 if(invlist == NULL){
1221 // Get the table insert function
1222 lua_getglobal(L, "table");
1223 lua_getfield(L, -1, "insert");
1224 int table_insert = lua_gettop(L);
1225 // Create and fill table
1227 int table = lua_gettop(L);
1228 for(u32 i=0; i<invlist->getSize(); i++){
1229 ItemStack item = invlist->getItem(i);
1230 lua_pushvalue(L, table_insert);
1231 lua_pushvalue(L, table);
1232 lua_pushstring(L, item.getItemString().c_str());
1233 if(lua_pcall(L, 2, 0, 0))
1234 script_error(L, "error: %s", lua_tostring(L, -1));
1239 Helpful macros for userdata classes
1242 #define method(class, name) {#name, class::l_##name}
1253 static const char className[];
1254 static const luaL_reg methods[];
1256 // Exported functions
1258 // garbage collector
1259 static int gc_object(lua_State *L)
1261 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1266 // is_empty(self) -> true/false
1267 static int l_is_empty(lua_State *L)
1269 LuaItemStack *o = checkobject(L, 1);
1270 ItemStack &item = o->m_stack;
1271 lua_pushboolean(L, item.empty());
1275 // get_name(self) -> string
1276 static int l_get_name(lua_State *L)
1278 LuaItemStack *o = checkobject(L, 1);
1279 ItemStack &item = o->m_stack;
1280 lua_pushstring(L, item.name.c_str());
1284 // get_count(self) -> number
1285 static int l_get_count(lua_State *L)
1287 LuaItemStack *o = checkobject(L, 1);
1288 ItemStack &item = o->m_stack;
1289 lua_pushinteger(L, item.count);
1293 // get_wear(self) -> number
1294 static int l_get_wear(lua_State *L)
1296 LuaItemStack *o = checkobject(L, 1);
1297 ItemStack &item = o->m_stack;
1298 lua_pushinteger(L, item.wear);
1302 // get_metadata(self) -> string
1303 static int l_get_metadata(lua_State *L)
1305 LuaItemStack *o = checkobject(L, 1);
1306 ItemStack &item = o->m_stack;
1307 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1311 // clear(self) -> true
1312 static int l_clear(lua_State *L)
1314 LuaItemStack *o = checkobject(L, 1);
1316 lua_pushboolean(L, true);
1320 // replace(self, itemstack or itemstring or table or nil) -> true
1321 static int l_replace(lua_State *L)
1323 LuaItemStack *o = checkobject(L, 1);
1324 o->m_stack = read_item(L, 2);
1325 lua_pushboolean(L, true);
1329 // to_string(self) -> string
1330 static int l_to_string(lua_State *L)
1332 LuaItemStack *o = checkobject(L, 1);
1333 std::string itemstring = o->m_stack.getItemString();
1334 lua_pushstring(L, itemstring.c_str());
1338 // to_table(self) -> table or nil
1339 static int l_to_table(lua_State *L)
1341 LuaItemStack *o = checkobject(L, 1);
1342 const ItemStack &item = o->m_stack;
1350 lua_pushstring(L, item.name.c_str());
1351 lua_setfield(L, -2, "name");
1352 lua_pushinteger(L, item.count);
1353 lua_setfield(L, -2, "count");
1354 lua_pushinteger(L, item.wear);
1355 lua_setfield(L, -2, "wear");
1356 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1357 lua_setfield(L, -2, "metadata");
1362 // get_stack_max(self) -> number
1363 static int l_get_stack_max(lua_State *L)
1365 LuaItemStack *o = checkobject(L, 1);
1366 ItemStack &item = o->m_stack;
1367 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1371 // get_free_space(self) -> number
1372 static int l_get_free_space(lua_State *L)
1374 LuaItemStack *o = checkobject(L, 1);
1375 ItemStack &item = o->m_stack;
1376 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1380 // is_known(self) -> true/false
1381 // Checks if the item is defined.
1382 static int l_is_known(lua_State *L)
1384 LuaItemStack *o = checkobject(L, 1);
1385 ItemStack &item = o->m_stack;
1386 bool is_known = item.isKnown(get_server(L)->idef());
1387 lua_pushboolean(L, is_known);
1391 // get_definition(self) -> table
1392 // Returns the item definition table from minetest.registered_items,
1393 // or a fallback one (name="unknown")
1394 static int l_get_definition(lua_State *L)
1396 LuaItemStack *o = checkobject(L, 1);
1397 ItemStack &item = o->m_stack;
1399 // Get minetest.registered_items[name]
1400 lua_getglobal(L, "minetest");
1401 lua_getfield(L, -1, "registered_items");
1402 luaL_checktype(L, -1, LUA_TTABLE);
1403 lua_getfield(L, -1, item.name.c_str());
1404 if(lua_isnil(L, -1))
1407 lua_getfield(L, -1, "unknown");
1412 // get_tool_capabilities(self) -> table
1413 // Returns the effective tool digging properties.
1414 // Returns those of the hand ("") if this item has none associated.
1415 static int l_get_tool_capabilities(lua_State *L)
1417 LuaItemStack *o = checkobject(L, 1);
1418 ItemStack &item = o->m_stack;
1419 const ToolCapabilities &prop =
1420 item.getToolCapabilities(get_server(L)->idef());
1421 push_tool_capabilities(L, prop);
1425 // add_wear(self, amount) -> true/false
1426 // The range for "amount" is [0,65535]. Wear is only added if the item
1427 // is a tool. Adding wear might destroy the item.
1428 // Returns true if the item is (or was) a tool.
1429 static int l_add_wear(lua_State *L)
1431 LuaItemStack *o = checkobject(L, 1);
1432 ItemStack &item = o->m_stack;
1433 int amount = lua_tointeger(L, 2);
1434 bool result = item.addWear(amount, get_server(L)->idef());
1435 lua_pushboolean(L, result);
1439 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1440 // Returns leftover item stack
1441 static int l_add_item(lua_State *L)
1443 LuaItemStack *o = checkobject(L, 1);
1444 ItemStack &item = o->m_stack;
1445 ItemStack newitem = read_item(L, 2);
1446 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1447 create(L, leftover);
1451 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1452 // First return value is true iff the new item fits fully into the stack
1453 // Second return value is the would-be-left-over item stack
1454 static int l_item_fits(lua_State *L)
1456 LuaItemStack *o = checkobject(L, 1);
1457 ItemStack &item = o->m_stack;
1458 ItemStack newitem = read_item(L, 2);
1460 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1461 lua_pushboolean(L, fits); // first return value
1462 create(L, restitem); // second return value
1466 // take_item(self, takecount=1) -> itemstack
1467 static int l_take_item(lua_State *L)
1469 LuaItemStack *o = checkobject(L, 1);
1470 ItemStack &item = o->m_stack;
1472 if(!lua_isnone(L, 2))
1473 takecount = lua_tointeger(L, 2);
1474 ItemStack taken = item.takeItem(takecount);
1479 // peek_item(self, peekcount=1) -> itemstack
1480 static int l_peek_item(lua_State *L)
1482 LuaItemStack *o = checkobject(L, 1);
1483 ItemStack &item = o->m_stack;
1485 if(!lua_isnone(L, 2))
1486 peekcount = lua_tointeger(L, 2);
1487 ItemStack peekaboo = item.peekItem(peekcount);
1488 create(L, peekaboo);
1493 LuaItemStack(const ItemStack &item):
1502 const ItemStack& getItem() const
1506 ItemStack& getItem()
1511 // LuaItemStack(itemstack or itemstring or table or nil)
1512 // Creates an LuaItemStack and leaves it on top of stack
1513 static int create_object(lua_State *L)
1515 ItemStack item = read_item(L, 1);
1516 LuaItemStack *o = new LuaItemStack(item);
1517 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1518 luaL_getmetatable(L, className);
1519 lua_setmetatable(L, -2);
1522 // Not callable from Lua
1523 static int create(lua_State *L, const ItemStack &item)
1525 LuaItemStack *o = new LuaItemStack(item);
1526 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1527 luaL_getmetatable(L, className);
1528 lua_setmetatable(L, -2);
1532 static LuaItemStack* checkobject(lua_State *L, int narg)
1534 luaL_checktype(L, narg, LUA_TUSERDATA);
1535 void *ud = luaL_checkudata(L, narg, className);
1536 if(!ud) luaL_typerror(L, narg, className);
1537 return *(LuaItemStack**)ud; // unbox pointer
1540 static void Register(lua_State *L)
1543 int methodtable = lua_gettop(L);
1544 luaL_newmetatable(L, className);
1545 int metatable = lua_gettop(L);
1547 lua_pushliteral(L, "__metatable");
1548 lua_pushvalue(L, methodtable);
1549 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1551 lua_pushliteral(L, "__index");
1552 lua_pushvalue(L, methodtable);
1553 lua_settable(L, metatable);
1555 lua_pushliteral(L, "__gc");
1556 lua_pushcfunction(L, gc_object);
1557 lua_settable(L, metatable);
1559 lua_pop(L, 1); // drop metatable
1561 luaL_openlib(L, 0, methods, 0); // fill methodtable
1562 lua_pop(L, 1); // drop methodtable
1564 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1565 lua_register(L, className, create_object);
1568 const char LuaItemStack::className[] = "ItemStack";
1569 const luaL_reg LuaItemStack::methods[] = {
1570 method(LuaItemStack, is_empty),
1571 method(LuaItemStack, get_name),
1572 method(LuaItemStack, get_count),
1573 method(LuaItemStack, get_wear),
1574 method(LuaItemStack, get_metadata),
1575 method(LuaItemStack, clear),
1576 method(LuaItemStack, replace),
1577 method(LuaItemStack, to_string),
1578 method(LuaItemStack, to_table),
1579 method(LuaItemStack, get_stack_max),
1580 method(LuaItemStack, get_free_space),
1581 method(LuaItemStack, is_known),
1582 method(LuaItemStack, get_definition),
1583 method(LuaItemStack, get_tool_capabilities),
1584 method(LuaItemStack, add_wear),
1585 method(LuaItemStack, add_item),
1586 method(LuaItemStack, item_fits),
1587 method(LuaItemStack, take_item),
1588 method(LuaItemStack, peek_item),
1592 static ItemStack read_item(lua_State *L, int index)
1595 index = lua_gettop(L) + 1 + index;
1597 if(lua_isnil(L, index))
1601 else if(lua_isuserdata(L, index))
1603 // Convert from LuaItemStack
1604 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1605 return o->getItem();
1607 else if(lua_isstring(L, index))
1609 // Convert from itemstring
1610 std::string itemstring = lua_tostring(L, index);
1611 IItemDefManager *idef = get_server(L)->idef();
1615 item.deSerialize(itemstring, idef);
1618 catch(SerializationError &e)
1620 infostream<<"WARNING: unable to create item from itemstring"
1621 <<": "<<itemstring<<std::endl;
1625 else if(lua_istable(L, index))
1627 // Convert from table
1628 IItemDefManager *idef = get_server(L)->idef();
1629 std::string name = getstringfield_default(L, index, "name", "");
1630 int count = getintfield_default(L, index, "count", 1);
1631 int wear = getintfield_default(L, index, "wear", 0);
1632 std::string metadata = getstringfield_default(L, index, "metadata", "");
1633 return ItemStack(name, count, wear, metadata, idef);
1637 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1648 InventoryLocation m_loc;
1650 static const char className[];
1651 static const luaL_reg methods[];
1653 static InvRef *checkobject(lua_State *L, int narg)
1655 luaL_checktype(L, narg, LUA_TUSERDATA);
1656 void *ud = luaL_checkudata(L, narg, className);
1657 if(!ud) luaL_typerror(L, narg, className);
1658 return *(InvRef**)ud; // unbox pointer
1661 static Inventory* getinv(lua_State *L, InvRef *ref)
1663 return get_server(L)->getInventory(ref->m_loc);
1666 static InventoryList* getlist(lua_State *L, InvRef *ref,
1667 const char *listname)
1669 Inventory *inv = getinv(L, ref);
1672 return inv->getList(listname);
1675 static void reportInventoryChange(lua_State *L, InvRef *ref)
1677 // Inform other things that the inventory has changed
1678 get_server(L)->setInventoryModified(ref->m_loc);
1681 // Exported functions
1683 // garbage collector
1684 static int gc_object(lua_State *L) {
1685 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1690 // get_size(self, listname)
1691 static int l_get_size(lua_State *L)
1693 InvRef *ref = checkobject(L, 1);
1694 const char *listname = luaL_checkstring(L, 2);
1695 InventoryList *list = getlist(L, ref, listname);
1697 lua_pushinteger(L, list->getSize());
1699 lua_pushinteger(L, 0);
1704 // set_size(self, listname, size)
1705 static int l_set_size(lua_State *L)
1707 InvRef *ref = checkobject(L, 1);
1708 const char *listname = luaL_checkstring(L, 2);
1709 int newsize = luaL_checknumber(L, 3);
1710 Inventory *inv = getinv(L, ref);
1712 inv->deleteList(listname);
1713 reportInventoryChange(L, ref);
1716 InventoryList *list = inv->getList(listname);
1718 list->setSize(newsize);
1720 list = inv->addList(listname, newsize);
1722 reportInventoryChange(L, ref);
1726 // get_stack(self, listname, i) -> itemstack
1727 static int l_get_stack(lua_State *L)
1729 InvRef *ref = checkobject(L, 1);
1730 const char *listname = luaL_checkstring(L, 2);
1731 int i = luaL_checknumber(L, 3) - 1;
1732 InventoryList *list = getlist(L, ref, listname);
1734 if(list != NULL && i >= 0 && i < (int) list->getSize())
1735 item = list->getItem(i);
1736 LuaItemStack::create(L, item);
1740 // set_stack(self, listname, i, stack) -> true/false
1741 static int l_set_stack(lua_State *L)
1743 InvRef *ref = checkobject(L, 1);
1744 const char *listname = luaL_checkstring(L, 2);
1745 int i = luaL_checknumber(L, 3) - 1;
1746 ItemStack newitem = read_item(L, 4);
1747 InventoryList *list = getlist(L, ref, listname);
1748 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1749 list->changeItem(i, newitem);
1750 reportInventoryChange(L, ref);
1751 lua_pushboolean(L, true);
1753 lua_pushboolean(L, false);
1758 // get_list(self, listname) -> list or nil
1759 static int l_get_list(lua_State *L)
1761 InvRef *ref = checkobject(L, 1);
1762 const char *listname = luaL_checkstring(L, 2);
1763 Inventory *inv = getinv(L, ref);
1764 inventory_get_list_to_lua(inv, listname, L);
1768 // set_list(self, listname, list)
1769 static int l_set_list(lua_State *L)
1771 InvRef *ref = checkobject(L, 1);
1772 const char *listname = luaL_checkstring(L, 2);
1773 Inventory *inv = getinv(L, ref);
1774 InventoryList *list = inv->getList(listname);
1776 inventory_set_list_from_lua(inv, listname, L, 3,
1779 inventory_set_list_from_lua(inv, listname, L, 3);
1780 reportInventoryChange(L, ref);
1784 // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1785 // Returns the leftover stack
1786 static int l_add_item(lua_State *L)
1788 InvRef *ref = checkobject(L, 1);
1789 const char *listname = luaL_checkstring(L, 2);
1790 ItemStack item = read_item(L, 3);
1791 InventoryList *list = getlist(L, ref, listname);
1793 ItemStack leftover = list->addItem(item);
1794 if(leftover.count != item.count)
1795 reportInventoryChange(L, ref);
1796 LuaItemStack::create(L, leftover);
1798 LuaItemStack::create(L, item);
1803 // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1804 // Returns true if the item completely fits into the list
1805 static int l_room_for_item(lua_State *L)
1807 InvRef *ref = checkobject(L, 1);
1808 const char *listname = luaL_checkstring(L, 2);
1809 ItemStack item = read_item(L, 3);
1810 InventoryList *list = getlist(L, ref, listname);
1812 lua_pushboolean(L, list->roomForItem(item));
1814 lua_pushboolean(L, false);
1819 // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
1820 // Returns true if the list contains the given count of the given item name
1821 static int l_contains_item(lua_State *L)
1823 InvRef *ref = checkobject(L, 1);
1824 const char *listname = luaL_checkstring(L, 2);
1825 ItemStack item = read_item(L, 3);
1826 InventoryList *list = getlist(L, ref, listname);
1828 lua_pushboolean(L, list->containsItem(item));
1830 lua_pushboolean(L, false);
1835 // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
1836 // Returns the items that were actually removed
1837 static int l_remove_item(lua_State *L)
1839 InvRef *ref = checkobject(L, 1);
1840 const char *listname = luaL_checkstring(L, 2);
1841 ItemStack item = read_item(L, 3);
1842 InventoryList *list = getlist(L, ref, listname);
1844 ItemStack removed = list->removeItem(item);
1845 if(!removed.empty())
1846 reportInventoryChange(L, ref);
1847 LuaItemStack::create(L, removed);
1849 LuaItemStack::create(L, ItemStack());
1855 InvRef(const InventoryLocation &loc):
1864 // Creates an InvRef and leaves it on top of stack
1865 // Not callable from Lua; all references are created on the C side.
1866 static void create(lua_State *L, const InventoryLocation &loc)
1868 InvRef *o = new InvRef(loc);
1869 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1870 luaL_getmetatable(L, className);
1871 lua_setmetatable(L, -2);
1873 static void createPlayer(lua_State *L, Player *player)
1875 InventoryLocation loc;
1876 loc.setPlayer(player->getName());
1879 static void createNodeMeta(lua_State *L, v3s16 p)
1881 InventoryLocation loc;
1886 static void Register(lua_State *L)
1889 int methodtable = lua_gettop(L);
1890 luaL_newmetatable(L, className);
1891 int metatable = lua_gettop(L);
1893 lua_pushliteral(L, "__metatable");
1894 lua_pushvalue(L, methodtable);
1895 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1897 lua_pushliteral(L, "__index");
1898 lua_pushvalue(L, methodtable);
1899 lua_settable(L, metatable);
1901 lua_pushliteral(L, "__gc");
1902 lua_pushcfunction(L, gc_object);
1903 lua_settable(L, metatable);
1905 lua_pop(L, 1); // drop metatable
1907 luaL_openlib(L, 0, methods, 0); // fill methodtable
1908 lua_pop(L, 1); // drop methodtable
1910 // Cannot be created from Lua
1911 //lua_register(L, className, create_object);
1914 const char InvRef::className[] = "InvRef";
1915 const luaL_reg InvRef::methods[] = {
1916 method(InvRef, get_size),
1917 method(InvRef, set_size),
1918 method(InvRef, get_stack),
1919 method(InvRef, set_stack),
1920 method(InvRef, get_list),
1921 method(InvRef, set_list),
1922 method(InvRef, add_item),
1923 method(InvRef, room_for_item),
1924 method(InvRef, contains_item),
1925 method(InvRef, remove_item),
1937 ServerEnvironment *m_env;
1939 static const char className[];
1940 static const luaL_reg methods[];
1942 static NodeMetaRef *checkobject(lua_State *L, int narg)
1944 luaL_checktype(L, narg, LUA_TUSERDATA);
1945 void *ud = luaL_checkudata(L, narg, className);
1946 if(!ud) luaL_typerror(L, narg, className);
1947 return *(NodeMetaRef**)ud; // unbox pointer
1950 static NodeMetadata* getmeta(NodeMetaRef *ref)
1952 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1956 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1958 NodeMetadata *meta = getmeta(ref);
1961 if(meta->typeId() != NODEMETA_GENERIC)
1963 return (IGenericNodeMetadata*)meta;
1966 static void reportMetadataChange(NodeMetaRef *ref)
1968 // Inform other things that the metadata has changed
1969 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1971 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1973 ref->m_env->getMap().dispatchEvent(&event);
1974 // Set the block to be saved
1975 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1977 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1978 "NodeMetaRef::reportMetadataChange");
1981 // Exported functions
1983 // garbage collector
1984 static int gc_object(lua_State *L) {
1985 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1991 static int l_get_type(lua_State *L)
1993 NodeMetaRef *ref = checkobject(L, 1);
1994 NodeMetadata *meta = getmeta(ref);
2000 lua_pushstring(L, meta->typeName());
2004 // allows_text_input(self)
2005 static int l_allows_text_input(lua_State *L)
2007 NodeMetaRef *ref = checkobject(L, 1);
2008 NodeMetadata *meta = getmeta(ref);
2009 if(meta == NULL) return 0;
2011 lua_pushboolean(L, meta->allowsTextInput());
2015 // set_text(self, text)
2016 static int l_set_text(lua_State *L)
2018 NodeMetaRef *ref = checkobject(L, 1);
2019 NodeMetadata *meta = getmeta(ref);
2020 if(meta == NULL) return 0;
2022 std::string text = luaL_checkstring(L, 2);
2023 meta->setText(text);
2024 reportMetadataChange(ref);
2029 static int l_get_text(lua_State *L)
2031 NodeMetaRef *ref = checkobject(L, 1);
2032 NodeMetadata *meta = getmeta(ref);
2033 if(meta == NULL) return 0;
2035 std::string text = meta->getText();
2036 lua_pushstring(L, text.c_str());
2041 static int l_get_owner(lua_State *L)
2043 NodeMetaRef *ref = checkobject(L, 1);
2044 NodeMetadata *meta = getmeta(ref);
2045 if(meta == NULL) return 0;
2047 std::string owner = meta->getOwner();
2048 lua_pushstring(L, owner.c_str());
2052 // set_owner(self, string)
2053 static int l_set_owner(lua_State *L)
2055 NodeMetaRef *ref = checkobject(L, 1);
2056 NodeMetadata *meta = getmeta(ref);
2057 if(meta == NULL) return 0;
2059 std::string owner = luaL_checkstring(L, 2);
2060 meta->setOwner(owner);
2061 reportMetadataChange(ref);
2065 // get_allow_removal(self)
2066 static int l_get_allow_removal(lua_State *L)
2068 NodeMetaRef *ref = checkobject(L, 1);
2069 NodeMetadata *meta = getmeta(ref);
2071 lua_pushboolean(L, true);
2075 lua_pushboolean(L, !meta->nodeRemovalDisabled());
2079 /* IGenericNodeMetadata interface */
2081 // set_infotext(self, text)
2082 static int l_set_infotext(lua_State *L)
2084 NodeMetaRef *ref = checkobject(L, 1);
2085 NodeMetadata *meta = getmeta(ref);
2086 if(meta == NULL) return 0;
2088 std::string text = luaL_checkstring(L, 2);
2089 meta->setInfoText(text);
2090 reportMetadataChange(ref);
2094 // get_inventory(self)
2095 static int l_get_inventory(lua_State *L)
2097 NodeMetaRef *ref = checkobject(L, 1);
2098 NodeMetadata *meta = getmeta(ref);
2099 if(meta == NULL) return 0;
2101 InvRef::createNodeMeta(L, ref->m_p);
2105 // set_inventory_draw_spec(self, text)
2106 static int l_set_inventory_draw_spec(lua_State *L)
2108 NodeMetaRef *ref = checkobject(L, 1);
2109 NodeMetadata *meta = getmeta(ref);
2110 if(meta == NULL) return 0;
2112 std::string text = luaL_checkstring(L, 2);
2113 meta->setInventoryDrawSpec(text);
2114 reportMetadataChange(ref);
2118 // set_allow_text_input(self, text)
2119 static int l_set_allow_text_input(lua_State *L)
2121 NodeMetaRef *ref = checkobject(L, 1);
2122 NodeMetadata *meta = getmeta(ref);
2123 if(meta == NULL) return 0;
2125 bool b = lua_toboolean(L, 2);
2126 meta->setAllowTextInput(b);
2127 reportMetadataChange(ref);
2131 // set_allow_removal(self, text)
2132 static int l_set_allow_removal(lua_State *L)
2134 NodeMetaRef *ref = checkobject(L, 1);
2135 NodeMetadata *meta = getmeta(ref);
2136 if(meta == NULL) return 0;
2138 bool b = lua_toboolean(L, 2);
2139 meta->setRemovalDisabled(!b);
2140 reportMetadataChange(ref);
2144 // set_enforce_owner(self, text)
2145 static int l_set_enforce_owner(lua_State *L)
2147 NodeMetaRef *ref = checkobject(L, 1);
2148 NodeMetadata *meta = getmeta(ref);
2149 if(meta == NULL) return 0;
2151 bool b = lua_toboolean(L, 2);
2152 meta->setEnforceOwner(b);
2153 reportMetadataChange(ref);
2157 // is_inventory_modified(self)
2158 static int l_is_inventory_modified(lua_State *L)
2160 NodeMetaRef *ref = checkobject(L, 1);
2161 NodeMetadata *meta = getmeta(ref);
2162 if(meta == NULL) return 0;
2164 lua_pushboolean(L, meta->isInventoryModified());
2168 // reset_inventory_modified(self)
2169 static int l_reset_inventory_modified(lua_State *L)
2171 NodeMetaRef *ref = checkobject(L, 1);
2172 NodeMetadata *meta = getmeta(ref);
2173 if(meta == NULL) return 0;
2175 meta->resetInventoryModified();
2176 reportMetadataChange(ref);
2180 // is_text_modified(self)
2181 static int l_is_text_modified(lua_State *L)
2183 NodeMetaRef *ref = checkobject(L, 1);
2184 NodeMetadata *meta = getmeta(ref);
2185 if(meta == NULL) return 0;
2187 lua_pushboolean(L, meta->isTextModified());
2191 // reset_text_modified(self)
2192 static int l_reset_text_modified(lua_State *L)
2194 NodeMetaRef *ref = checkobject(L, 1);
2195 NodeMetadata *meta = getmeta(ref);
2196 if(meta == NULL) return 0;
2198 meta->resetTextModified();
2199 reportMetadataChange(ref);
2203 // set_string(self, name, var)
2204 static int l_set_string(lua_State *L)
2206 NodeMetaRef *ref = checkobject(L, 1);
2207 NodeMetadata *meta = getmeta(ref);
2208 if(meta == NULL) return 0;
2210 std::string name = luaL_checkstring(L, 2);
2212 const char *s = lua_tolstring(L, 3, &len);
2213 std::string str(s, len);
2214 meta->setString(name, str);
2215 reportMetadataChange(ref);
2219 // get_string(self, name)
2220 static int l_get_string(lua_State *L)
2222 NodeMetaRef *ref = checkobject(L, 1);
2223 NodeMetadata *meta = getmeta(ref);
2224 if(meta == NULL) return 0;
2226 std::string name = luaL_checkstring(L, 2);
2227 std::string str = meta->getString(name);
2228 lua_pushlstring(L, str.c_str(), str.size());
2233 NodeMetaRef(v3s16 p, ServerEnvironment *env):
2243 // Creates an NodeMetaRef and leaves it on top of stack
2244 // Not callable from Lua; all references are created on the C side.
2245 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2247 NodeMetaRef *o = new NodeMetaRef(p, env);
2248 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2249 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2250 luaL_getmetatable(L, className);
2251 lua_setmetatable(L, -2);
2254 static void Register(lua_State *L)
2257 int methodtable = lua_gettop(L);
2258 luaL_newmetatable(L, className);
2259 int metatable = lua_gettop(L);
2261 lua_pushliteral(L, "__metatable");
2262 lua_pushvalue(L, methodtable);
2263 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2265 lua_pushliteral(L, "__index");
2266 lua_pushvalue(L, methodtable);
2267 lua_settable(L, metatable);
2269 lua_pushliteral(L, "__gc");
2270 lua_pushcfunction(L, gc_object);
2271 lua_settable(L, metatable);
2273 lua_pop(L, 1); // drop metatable
2275 luaL_openlib(L, 0, methods, 0); // fill methodtable
2276 lua_pop(L, 1); // drop methodtable
2278 // Cannot be created from Lua
2279 //lua_register(L, className, create_object);
2282 const char NodeMetaRef::className[] = "NodeMetaRef";
2283 const luaL_reg NodeMetaRef::methods[] = {
2284 method(NodeMetaRef, get_type),
2285 method(NodeMetaRef, allows_text_input),
2286 method(NodeMetaRef, set_text),
2287 method(NodeMetaRef, get_text),
2288 method(NodeMetaRef, get_owner),
2289 method(NodeMetaRef, set_owner),
2290 method(NodeMetaRef, get_allow_removal),
2291 method(NodeMetaRef, set_infotext),
2292 method(NodeMetaRef, get_inventory),
2293 method(NodeMetaRef, set_inventory_draw_spec),
2294 method(NodeMetaRef, set_allow_text_input),
2295 method(NodeMetaRef, set_allow_removal),
2296 method(NodeMetaRef, set_enforce_owner),
2297 method(NodeMetaRef, is_inventory_modified),
2298 method(NodeMetaRef, reset_inventory_modified),
2299 method(NodeMetaRef, is_text_modified),
2300 method(NodeMetaRef, reset_text_modified),
2301 method(NodeMetaRef, set_string),
2302 method(NodeMetaRef, get_string),
2313 ServerActiveObject *m_object;
2315 static const char className[];
2316 static const luaL_reg methods[];
2318 static ObjectRef *checkobject(lua_State *L, int narg)
2320 luaL_checktype(L, narg, LUA_TUSERDATA);
2321 void *ud = luaL_checkudata(L, narg, className);
2322 if(!ud) luaL_typerror(L, narg, className);
2323 return *(ObjectRef**)ud; // unbox pointer
2326 static ServerActiveObject* getobject(ObjectRef *ref)
2328 ServerActiveObject *co = ref->m_object;
2332 static LuaEntitySAO* getluaobject(ObjectRef *ref)
2334 ServerActiveObject *obj = getobject(ref);
2337 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2339 return (LuaEntitySAO*)obj;
2342 static PlayerSAO* getplayersao(ObjectRef *ref)
2344 ServerActiveObject *obj = getobject(ref);
2347 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2349 return (PlayerSAO*)obj;
2352 static Player* getplayer(ObjectRef *ref)
2354 PlayerSAO *playersao = getplayersao(ref);
2355 if(playersao == NULL)
2357 return playersao->getPlayer();
2360 // Exported functions
2362 // garbage collector
2363 static int gc_object(lua_State *L) {
2364 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2365 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2371 static int l_remove(lua_State *L)
2373 ObjectRef *ref = checkobject(L, 1);
2374 ServerActiveObject *co = getobject(ref);
2375 if(co == NULL) return 0;
2376 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2377 co->m_removed = true;
2382 // returns: {x=num, y=num, z=num}
2383 static int l_getpos(lua_State *L)
2385 ObjectRef *ref = checkobject(L, 1);
2386 ServerActiveObject *co = getobject(ref);
2387 if(co == NULL) return 0;
2388 v3f pos = co->getBasePosition() / BS;
2390 lua_pushnumber(L, pos.X);
2391 lua_setfield(L, -2, "x");
2392 lua_pushnumber(L, pos.Y);
2393 lua_setfield(L, -2, "y");
2394 lua_pushnumber(L, pos.Z);
2395 lua_setfield(L, -2, "z");
2399 // setpos(self, pos)
2400 static int l_setpos(lua_State *L)
2402 ObjectRef *ref = checkobject(L, 1);
2403 //LuaEntitySAO *co = getluaobject(ref);
2404 ServerActiveObject *co = getobject(ref);
2405 if(co == NULL) return 0;
2407 v3f pos = checkFloatPos(L, 2);
2413 // moveto(self, pos, continuous=false)
2414 static int l_moveto(lua_State *L)
2416 ObjectRef *ref = checkobject(L, 1);
2417 //LuaEntitySAO *co = getluaobject(ref);
2418 ServerActiveObject *co = getobject(ref);
2419 if(co == NULL) return 0;
2421 v3f pos = checkFloatPos(L, 2);
2423 bool continuous = lua_toboolean(L, 3);
2425 co->moveTo(pos, continuous);
2429 // punch(self, puncher, tool_capabilities, direction, time_from_last_punch)
2430 static int l_punch(lua_State *L)
2432 ObjectRef *ref = checkobject(L, 1);
2433 ObjectRef *puncher_ref = checkobject(L, 2);
2434 ServerActiveObject *co = getobject(ref);
2435 ServerActiveObject *puncher = getobject(puncher_ref);
2436 if(co == NULL) return 0;
2437 if(puncher == NULL) return 0;
2438 ToolCapabilities toolcap = read_tool_capabilities(L, 3);
2439 v3f dir = read_v3f(L, 4);
2440 float time_from_last_punch = 1000000;
2441 if(lua_isnumber(L, 5))
2442 time_from_last_punch = lua_tonumber(L, 5);
2444 puncher->punch(dir, &toolcap, puncher, time_from_last_punch);
2448 // right_click(self, clicker); clicker = an another ObjectRef
2449 static int l_right_click(lua_State *L)
2451 ObjectRef *ref = checkobject(L, 1);
2452 ObjectRef *ref2 = checkobject(L, 2);
2453 ServerActiveObject *co = getobject(ref);
2454 ServerActiveObject *co2 = getobject(ref2);
2455 if(co == NULL) return 0;
2456 if(co2 == NULL) return 0;
2458 co->rightClick(co2);
2463 // hp = number of hitpoints (2 * number of hearts)
2465 static int l_set_hp(lua_State *L)
2467 ObjectRef *ref = checkobject(L, 1);
2468 luaL_checknumber(L, 2);
2469 ServerActiveObject *co = getobject(ref);
2470 if(co == NULL) return 0;
2471 int hp = lua_tonumber(L, 2);
2472 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2473 <<" hp="<<hp<<std::endl;*/
2481 // returns: number of hitpoints (2 * number of hearts)
2482 // 0 if not applicable to this type of object
2483 static int l_get_hp(lua_State *L)
2485 ObjectRef *ref = checkobject(L, 1);
2486 ServerActiveObject *co = getobject(ref);
2487 if(co == NULL) return 0;
2488 int hp = co->getHP();
2489 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2490 <<" hp="<<hp<<std::endl;*/
2492 lua_pushnumber(L, hp);
2496 // get_inventory(self)
2497 static int l_get_inventory(lua_State *L)
2499 ObjectRef *ref = checkobject(L, 1);
2500 ServerActiveObject *co = getobject(ref);
2501 if(co == NULL) return 0;
2503 InventoryLocation loc = co->getInventoryLocation();
2504 if(get_server(L)->getInventory(loc) != NULL)
2505 InvRef::create(L, loc);
2511 // get_wield_list(self)
2512 static int l_get_wield_list(lua_State *L)
2514 ObjectRef *ref = checkobject(L, 1);
2515 ServerActiveObject *co = getobject(ref);
2516 if(co == NULL) return 0;
2518 lua_pushstring(L, co->getWieldList().c_str());
2522 // get_wield_index(self)
2523 static int l_get_wield_index(lua_State *L)
2525 ObjectRef *ref = checkobject(L, 1);
2526 ServerActiveObject *co = getobject(ref);
2527 if(co == NULL) return 0;
2529 lua_pushinteger(L, co->getWieldIndex() + 1);
2533 // get_wielded_item(self)
2534 static int l_get_wielded_item(lua_State *L)
2536 ObjectRef *ref = checkobject(L, 1);
2537 ServerActiveObject *co = getobject(ref);
2538 if(co == NULL) return 0;
2540 LuaItemStack::create(L, co->getWieldedItem());
2544 // set_wielded_item(self, itemstack or itemstring or table or nil)
2545 static int l_set_wielded_item(lua_State *L)
2547 ObjectRef *ref = checkobject(L, 1);
2548 ServerActiveObject *co = getobject(ref);
2549 if(co == NULL) return 0;
2551 ItemStack item = read_item(L, 2);
2552 bool success = co->setWieldedItem(item);
2553 lua_pushboolean(L, success);
2557 // set_armor_groups(self, groups)
2558 static int l_set_armor_groups(lua_State *L)
2560 ObjectRef *ref = checkobject(L, 1);
2561 ServerActiveObject *co = getobject(ref);
2562 if(co == NULL) return 0;
2564 ItemGroupList groups;
2565 read_groups(L, 2, groups);
2566 co->setArmorGroups(groups);
2570 // set_properties(self, properties)
2571 static int l_set_properties(lua_State *L)
2573 ObjectRef *ref = checkobject(L, 1);
2574 ServerActiveObject *co = getobject(ref);
2575 if(co == NULL) return 0;
2576 ObjectProperties *prop = co->accessObjectProperties();
2579 read_object_properties(L, 2, prop);
2580 co->notifyObjectPropertiesModified();
2584 /* LuaEntitySAO-only */
2586 // setvelocity(self, {x=num, y=num, z=num})
2587 static int l_setvelocity(lua_State *L)
2589 ObjectRef *ref = checkobject(L, 1);
2590 LuaEntitySAO *co = getluaobject(ref);
2591 if(co == NULL) return 0;
2592 v3f pos = checkFloatPos(L, 2);
2594 co->setVelocity(pos);
2598 // getvelocity(self)
2599 static int l_getvelocity(lua_State *L)
2601 ObjectRef *ref = checkobject(L, 1);
2602 LuaEntitySAO *co = getluaobject(ref);
2603 if(co == NULL) return 0;
2605 v3f v = co->getVelocity();
2610 // setacceleration(self, {x=num, y=num, z=num})
2611 static int l_setacceleration(lua_State *L)
2613 ObjectRef *ref = checkobject(L, 1);
2614 LuaEntitySAO *co = getluaobject(ref);
2615 if(co == NULL) return 0;
2617 v3f pos = checkFloatPos(L, 2);
2619 co->setAcceleration(pos);
2623 // getacceleration(self)
2624 static int l_getacceleration(lua_State *L)
2626 ObjectRef *ref = checkobject(L, 1);
2627 LuaEntitySAO *co = getluaobject(ref);
2628 if(co == NULL) return 0;
2630 v3f v = co->getAcceleration();
2635 // setyaw(self, radians)
2636 static int l_setyaw(lua_State *L)
2638 ObjectRef *ref = checkobject(L, 1);
2639 LuaEntitySAO *co = getluaobject(ref);
2640 if(co == NULL) return 0;
2641 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2648 static int l_getyaw(lua_State *L)
2650 ObjectRef *ref = checkobject(L, 1);
2651 LuaEntitySAO *co = getluaobject(ref);
2652 if(co == NULL) return 0;
2654 float yaw = co->getYaw() * core::DEGTORAD;
2655 lua_pushnumber(L, yaw);
2659 // settexturemod(self, mod)
2660 static int l_settexturemod(lua_State *L)
2662 ObjectRef *ref = checkobject(L, 1);
2663 LuaEntitySAO *co = getluaobject(ref);
2664 if(co == NULL) return 0;
2666 std::string mod = luaL_checkstring(L, 2);
2667 co->setTextureMod(mod);
2671 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2672 // select_horiz_by_yawpitch=false)
2673 static int l_setsprite(lua_State *L)
2675 ObjectRef *ref = checkobject(L, 1);
2676 LuaEntitySAO *co = getluaobject(ref);
2677 if(co == NULL) return 0;
2680 if(!lua_isnil(L, 2))
2681 p = read_v2s16(L, 2);
2683 if(!lua_isnil(L, 3))
2684 num_frames = lua_tonumber(L, 3);
2685 float framelength = 0.2;
2686 if(!lua_isnil(L, 4))
2687 framelength = lua_tonumber(L, 4);
2688 bool select_horiz_by_yawpitch = false;
2689 if(!lua_isnil(L, 5))
2690 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2691 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2696 // get_entity_name(self)
2697 static int l_get_entity_name(lua_State *L)
2699 ObjectRef *ref = checkobject(L, 1);
2700 LuaEntitySAO *co = getluaobject(ref);
2701 if(co == NULL) return 0;
2703 std::string name = co->getName();
2704 lua_pushstring(L, name.c_str());
2708 // get_luaentity(self)
2709 static int l_get_luaentity(lua_State *L)
2711 ObjectRef *ref = checkobject(L, 1);
2712 LuaEntitySAO *co = getluaobject(ref);
2713 if(co == NULL) return 0;
2715 luaentity_get(L, co->getId());
2721 // get_player_name(self)
2722 static int l_get_player_name(lua_State *L)
2724 ObjectRef *ref = checkobject(L, 1);
2725 Player *player = getplayer(ref);
2731 lua_pushstring(L, player->getName());
2735 // get_look_dir(self)
2736 static int l_get_look_dir(lua_State *L)
2738 ObjectRef *ref = checkobject(L, 1);
2739 Player *player = getplayer(ref);
2740 if(player == NULL) return 0;
2742 float pitch = player->getRadPitch();
2743 float yaw = player->getRadYaw();
2744 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
2749 // get_look_pitch(self)
2750 static int l_get_look_pitch(lua_State *L)
2752 ObjectRef *ref = checkobject(L, 1);
2753 Player *player = getplayer(ref);
2754 if(player == NULL) return 0;
2756 lua_pushnumber(L, player->getRadPitch());
2760 // get_look_yaw(self)
2761 static int l_get_look_yaw(lua_State *L)
2763 ObjectRef *ref = checkobject(L, 1);
2764 Player *player = getplayer(ref);
2765 if(player == NULL) return 0;
2767 lua_pushnumber(L, player->getRadYaw());
2772 ObjectRef(ServerActiveObject *object):
2775 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2781 infostream<<"ObjectRef destructing for id="
2782 <<m_object->getId()<<std::endl;
2784 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2787 // Creates an ObjectRef and leaves it on top of stack
2788 // Not callable from Lua; all references are created on the C side.
2789 static void create(lua_State *L, ServerActiveObject *object)
2791 ObjectRef *o = new ObjectRef(object);
2792 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2793 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2794 luaL_getmetatable(L, className);
2795 lua_setmetatable(L, -2);
2798 static void set_null(lua_State *L)
2800 ObjectRef *o = checkobject(L, -1);
2804 static void Register(lua_State *L)
2807 int methodtable = lua_gettop(L);
2808 luaL_newmetatable(L, className);
2809 int metatable = lua_gettop(L);
2811 lua_pushliteral(L, "__metatable");
2812 lua_pushvalue(L, methodtable);
2813 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2815 lua_pushliteral(L, "__index");
2816 lua_pushvalue(L, methodtable);
2817 lua_settable(L, metatable);
2819 lua_pushliteral(L, "__gc");
2820 lua_pushcfunction(L, gc_object);
2821 lua_settable(L, metatable);
2823 lua_pop(L, 1); // drop metatable
2825 luaL_openlib(L, 0, methods, 0); // fill methodtable
2826 lua_pop(L, 1); // drop methodtable
2828 // Cannot be created from Lua
2829 //lua_register(L, className, create_object);
2832 const char ObjectRef::className[] = "ObjectRef";
2833 const luaL_reg ObjectRef::methods[] = {
2834 // ServerActiveObject
2835 method(ObjectRef, remove),
2836 method(ObjectRef, getpos),
2837 method(ObjectRef, setpos),
2838 method(ObjectRef, moveto),
2839 method(ObjectRef, punch),
2840 method(ObjectRef, right_click),
2841 method(ObjectRef, set_hp),
2842 method(ObjectRef, get_hp),
2843 method(ObjectRef, get_inventory),
2844 method(ObjectRef, get_wield_list),
2845 method(ObjectRef, get_wield_index),
2846 method(ObjectRef, get_wielded_item),
2847 method(ObjectRef, set_wielded_item),
2848 method(ObjectRef, set_armor_groups),
2849 method(ObjectRef, set_properties),
2850 // LuaEntitySAO-only
2851 method(ObjectRef, setvelocity),
2852 method(ObjectRef, getvelocity),
2853 method(ObjectRef, setacceleration),
2854 method(ObjectRef, getacceleration),
2855 method(ObjectRef, setyaw),
2856 method(ObjectRef, getyaw),
2857 method(ObjectRef, settexturemod),
2858 method(ObjectRef, setsprite),
2859 method(ObjectRef, get_entity_name),
2860 method(ObjectRef, get_luaentity),
2862 method(ObjectRef, get_player_name),
2863 method(ObjectRef, get_look_dir),
2864 method(ObjectRef, get_look_pitch),
2865 method(ObjectRef, get_look_yaw),
2869 // Creates a new anonymous reference if id=0
2870 static void objectref_get_or_create(lua_State *L,
2871 ServerActiveObject *cobj)
2873 if(cobj->getId() == 0){
2874 ObjectRef::create(L, cobj);
2876 objectref_get(L, cobj->getId());
2885 class LuaPerlinNoise
2892 static const char className[];
2893 static const luaL_reg methods[];
2895 // Exported functions
2897 // garbage collector
2898 static int gc_object(lua_State *L)
2900 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
2905 static int l_get2d(lua_State *L)
2907 LuaPerlinNoise *o = checkobject(L, 1);
2908 v2f pos2d = read_v2f(L,2);
2909 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
2910 lua_pushnumber(L, val);
2913 static int l_get3d(lua_State *L)
2915 LuaPerlinNoise *o = checkobject(L, 1);
2916 v3f pos3d = read_v3f(L,2);
2917 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
2918 lua_pushnumber(L, val);
2923 LuaPerlinNoise(int a_seed, int a_octaves, double a_persistence,
2927 persistence(a_persistence),
2936 // LuaPerlinNoise(seed, octaves, persistence, scale)
2937 // Creates an LuaPerlinNoise and leaves it on top of stack
2938 static int create_object(lua_State *L)
2940 int seed = luaL_checkint(L, 1);
2941 int octaves = luaL_checkint(L, 2);
2942 double persistence = luaL_checknumber(L, 3);
2943 double scale = luaL_checknumber(L, 4);
2944 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
2945 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2946 luaL_getmetatable(L, className);
2947 lua_setmetatable(L, -2);
2951 static LuaPerlinNoise* checkobject(lua_State *L, int narg)
2953 luaL_checktype(L, narg, LUA_TUSERDATA);
2954 void *ud = luaL_checkudata(L, narg, className);
2955 if(!ud) luaL_typerror(L, narg, className);
2956 return *(LuaPerlinNoise**)ud; // unbox pointer
2959 static void Register(lua_State *L)
2962 int methodtable = lua_gettop(L);
2963 luaL_newmetatable(L, className);
2964 int metatable = lua_gettop(L);
2966 lua_pushliteral(L, "__metatable");
2967 lua_pushvalue(L, methodtable);
2968 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2970 lua_pushliteral(L, "__index");
2971 lua_pushvalue(L, methodtable);
2972 lua_settable(L, metatable);
2974 lua_pushliteral(L, "__gc");
2975 lua_pushcfunction(L, gc_object);
2976 lua_settable(L, metatable);
2978 lua_pop(L, 1); // drop metatable
2980 luaL_openlib(L, 0, methods, 0); // fill methodtable
2981 lua_pop(L, 1); // drop methodtable
2983 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
2984 lua_register(L, className, create_object);
2987 const char LuaPerlinNoise::className[] = "PerlinNoise";
2988 const luaL_reg LuaPerlinNoise::methods[] = {
2989 method(LuaPerlinNoise, get2d),
2990 method(LuaPerlinNoise, get3d),
3001 ServerEnvironment *m_env;
3003 static const char className[];
3004 static const luaL_reg methods[];
3006 static int gc_object(lua_State *L) {
3007 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3012 static EnvRef *checkobject(lua_State *L, int narg)
3014 luaL_checktype(L, narg, LUA_TUSERDATA);
3015 void *ud = luaL_checkudata(L, narg, className);
3016 if(!ud) luaL_typerror(L, narg, className);
3017 return *(EnvRef**)ud; // unbox pointer
3020 // Exported functions
3022 // EnvRef:set_node(pos, node)
3023 // pos = {x=num, y=num, z=num}
3024 static int l_set_node(lua_State *L)
3026 //infostream<<"EnvRef::l_set_node()"<<std::endl;
3027 EnvRef *o = checkobject(L, 1);
3028 ServerEnvironment *env = o->m_env;
3029 if(env == NULL) return 0;
3031 v3s16 pos = read_v3s16(L, 2);
3033 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3035 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
3036 lua_pushboolean(L, succeeded);
3040 static int l_add_node(lua_State *L)
3042 return l_set_node(L);
3045 // EnvRef:remove_node(pos)
3046 // pos = {x=num, y=num, z=num}
3047 static int l_remove_node(lua_State *L)
3049 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
3050 EnvRef *o = checkobject(L, 1);
3051 ServerEnvironment *env = o->m_env;
3052 if(env == NULL) return 0;
3054 v3s16 pos = read_v3s16(L, 2);
3056 bool succeeded = env->getMap().removeNodeWithEvent(pos);
3057 lua_pushboolean(L, succeeded);
3061 // EnvRef:get_node(pos)
3062 // pos = {x=num, y=num, z=num}
3063 static int l_get_node(lua_State *L)
3065 //infostream<<"EnvRef::l_get_node()"<<std::endl;
3066 EnvRef *o = checkobject(L, 1);
3067 ServerEnvironment *env = o->m_env;
3068 if(env == NULL) return 0;
3070 v3s16 pos = read_v3s16(L, 2);
3072 MapNode n = env->getMap().getNodeNoEx(pos);
3074 pushnode(L, n, env->getGameDef()->ndef());
3078 // EnvRef:get_node_or_nil(pos)
3079 // pos = {x=num, y=num, z=num}
3080 static int l_get_node_or_nil(lua_State *L)
3082 //infostream<<"EnvRef::l_get_node()"<<std::endl;
3083 EnvRef *o = checkobject(L, 1);
3084 ServerEnvironment *env = o->m_env;
3085 if(env == NULL) return 0;
3087 v3s16 pos = read_v3s16(L, 2);
3090 MapNode n = env->getMap().getNode(pos);
3092 pushnode(L, n, env->getGameDef()->ndef());
3094 } catch(InvalidPositionException &e)
3101 // EnvRef:get_node_light(pos, timeofday)
3102 // pos = {x=num, y=num, z=num}
3103 // timeofday: nil = current time, 0 = night, 0.5 = day
3104 static int l_get_node_light(lua_State *L)
3106 EnvRef *o = checkobject(L, 1);
3107 ServerEnvironment *env = o->m_env;
3108 if(env == NULL) return 0;
3110 v3s16 pos = read_v3s16(L, 2);
3111 u32 time_of_day = env->getTimeOfDay();
3112 if(lua_isnumber(L, 3))
3113 time_of_day = 24000.0 * lua_tonumber(L, 3);
3114 time_of_day %= 24000;
3115 u32 dnr = time_to_daynight_ratio(time_of_day);
3116 MapNode n = env->getMap().getNodeNoEx(pos);
3118 MapNode n = env->getMap().getNode(pos);
3119 INodeDefManager *ndef = env->getGameDef()->ndef();
3120 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3122 } catch(InvalidPositionException &e)
3129 // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3130 // pos = {x=num, y=num, z=num}
3131 static int l_add_entity(lua_State *L)
3133 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3134 EnvRef *o = checkobject(L, 1);
3135 ServerEnvironment *env = o->m_env;
3136 if(env == NULL) return 0;
3138 v3f pos = checkFloatPos(L, 2);
3140 const char *name = luaL_checkstring(L, 3);
3142 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3143 int objectid = env->addActiveObject(obj);
3144 // If failed to add, return nothing (reads as nil)
3148 objectref_get_or_create(L, obj);
3152 // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3153 // pos = {x=num, y=num, z=num}
3154 static int l_add_item(lua_State *L)
3156 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3157 EnvRef *o = checkobject(L, 1);
3158 ServerEnvironment *env = o->m_env;
3159 if(env == NULL) return 0;
3161 v3f pos = checkFloatPos(L, 2);
3163 ItemStack item = read_item(L, 3);
3164 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3166 // Use minetest.spawn_item to spawn a __builtin:item
3167 lua_getglobal(L, "minetest");
3168 lua_getfield(L, -1, "spawn_item");
3169 if(lua_isnil(L, -1))
3171 lua_pushvalue(L, 2);
3172 lua_pushstring(L, item.getItemString().c_str());
3173 if(lua_pcall(L, 2, 1, 0))
3174 script_error(L, "error: %s", lua_tostring(L, -1));
3176 /*lua_pushvalue(L, 1);
3177 lua_pushstring(L, "__builtin:item");
3178 lua_pushstring(L, item.getItemString().c_str());
3179 return l_add_entity(L);*/
3181 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3182 int objectid = env->addActiveObject(obj);
3183 // If failed to add, return nothing (reads as nil)
3187 objectref_get_or_create(L, obj);
3191 // EnvRef:add_rat(pos)
3192 // pos = {x=num, y=num, z=num}
3193 static int l_add_rat(lua_State *L)
3195 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3196 <<" Doing nothing."<<std::endl;
3200 // EnvRef:add_firefly(pos)
3201 // pos = {x=num, y=num, z=num}
3202 static int l_add_firefly(lua_State *L)
3204 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3205 <<" Doing nothing."<<std::endl;
3209 // EnvRef:get_meta(pos)
3210 static int l_get_meta(lua_State *L)
3212 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3213 EnvRef *o = checkobject(L, 1);
3214 ServerEnvironment *env = o->m_env;
3215 if(env == NULL) return 0;
3217 v3s16 p = read_v3s16(L, 2);
3218 NodeMetaRef::create(L, p, env);
3222 // EnvRef:get_player_by_name(name)
3223 static int l_get_player_by_name(lua_State *L)
3225 EnvRef *o = checkobject(L, 1);
3226 ServerEnvironment *env = o->m_env;
3227 if(env == NULL) return 0;
3229 const char *name = luaL_checkstring(L, 2);
3230 Player *player = env->getPlayer(name);
3235 PlayerSAO *sao = player->getPlayerSAO();
3240 // Put player on stack
3241 objectref_get_or_create(L, sao);
3245 // EnvRef:get_objects_inside_radius(pos, radius)
3246 static int l_get_objects_inside_radius(lua_State *L)
3248 // Get the table insert function
3249 lua_getglobal(L, "table");
3250 lua_getfield(L, -1, "insert");
3251 int table_insert = lua_gettop(L);
3253 EnvRef *o = checkobject(L, 1);
3254 ServerEnvironment *env = o->m_env;
3255 if(env == NULL) return 0;
3257 v3f pos = checkFloatPos(L, 2);
3258 float radius = luaL_checknumber(L, 3) * BS;
3259 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
3261 int table = lua_gettop(L);
3262 for(std::set<u16>::const_iterator
3263 i = ids.begin(); i != ids.end(); i++){
3264 ServerActiveObject *obj = env->getActiveObject(*i);
3265 // Insert object reference into table
3266 lua_pushvalue(L, table_insert);
3267 lua_pushvalue(L, table);
3268 objectref_get_or_create(L, obj);
3269 if(lua_pcall(L, 2, 0, 0))
3270 script_error(L, "error: %s", lua_tostring(L, -1));
3275 // EnvRef:set_timeofday(val)
3277 static int l_set_timeofday(lua_State *L)
3279 EnvRef *o = checkobject(L, 1);
3280 ServerEnvironment *env = o->m_env;
3281 if(env == NULL) return 0;
3283 float timeofday_f = luaL_checknumber(L, 2);
3284 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
3285 int timeofday_mh = (int)(timeofday_f * 24000.0);
3286 // This should be set directly in the environment but currently
3287 // such changes aren't immediately sent to the clients, so call
3288 // the server instead.
3289 //env->setTimeOfDay(timeofday_mh);
3290 get_server(L)->setTimeOfDay(timeofday_mh);
3294 // EnvRef:get_timeofday() -> 0...1
3295 static int l_get_timeofday(lua_State *L)
3297 EnvRef *o = checkobject(L, 1);
3298 ServerEnvironment *env = o->m_env;
3299 if(env == NULL) return 0;
3301 int timeofday_mh = env->getTimeOfDay();
3302 float timeofday_f = (float)timeofday_mh / 24000.0;
3303 lua_pushnumber(L, timeofday_f);
3308 // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
3309 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3310 static int l_find_node_near(lua_State *L)
3312 EnvRef *o = checkobject(L, 1);
3313 ServerEnvironment *env = o->m_env;
3314 if(env == NULL) return 0;
3315 INodeDefManager *ndef = get_server(L)->ndef();
3316 v3s16 pos = read_v3s16(L, 2);
3317 int radius = luaL_checkinteger(L, 3);
3318 std::set<content_t> filter;
3319 if(lua_istable(L, 4)){
3322 while(lua_next(L, table) != 0){
3323 // key at index -2 and value at index -1
3324 luaL_checktype(L, -1, LUA_TSTRING);
3325 ndef->getIds(lua_tostring(L, -1), filter);
3326 // removes value, keeps key for next iteration
3329 } else if(lua_isstring(L, 4)){
3330 ndef->getIds(lua_tostring(L, 4), filter);
3333 for(int d=1; d<=radius; d++){
3334 core::list<v3s16> list;
3335 getFacePositions(list, d);
3336 for(core::list<v3s16>::Iterator i = list.begin();
3337 i != list.end(); i++){
3338 v3s16 p = pos + (*i);
3339 content_t c = env->getMap().getNodeNoEx(p).getContent();
3340 if(filter.count(c) != 0){
3349 // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
3350 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
3351 static int l_find_nodes_in_area(lua_State *L)
3353 EnvRef *o = checkobject(L, 1);
3354 ServerEnvironment *env = o->m_env;
3355 if(env == NULL) return 0;
3356 INodeDefManager *ndef = get_server(L)->ndef();
3357 v3s16 minp = read_v3s16(L, 2);
3358 v3s16 maxp = read_v3s16(L, 3);
3359 std::set<content_t> filter;
3360 if(lua_istable(L, 4)){
3363 while(lua_next(L, table) != 0){
3364 // key at index -2 and value at index -1
3365 luaL_checktype(L, -1, LUA_TSTRING);
3366 ndef->getIds(lua_tostring(L, -1), filter);
3367 // removes value, keeps key for next iteration
3370 } else if(lua_isstring(L, 4)){
3371 ndef->getIds(lua_tostring(L, 4), filter);
3374 // Get the table insert function
3375 lua_getglobal(L, "table");
3376 lua_getfield(L, -1, "insert");
3377 int table_insert = lua_gettop(L);
3380 int table = lua_gettop(L);
3381 for(s16 x=minp.X; x<=maxp.X; x++)
3382 for(s16 y=minp.Y; y<=maxp.Y; y++)
3383 for(s16 z=minp.Z; z<=maxp.Z; z++)
3386 content_t c = env->getMap().getNodeNoEx(p).getContent();
3387 if(filter.count(c) != 0){
3388 lua_pushvalue(L, table_insert);
3389 lua_pushvalue(L, table);
3391 if(lua_pcall(L, 2, 0, 0))
3392 script_error(L, "error: %s", lua_tostring(L, -1));
3398 // EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
3399 // returns world-specific PerlinNoise
3400 static int l_get_perlin(lua_State *L)
3402 EnvRef *o = checkobject(L, 1);
3403 ServerEnvironment *env = o->m_env;
3404 if(env == NULL) return 0;
3406 int seeddiff = luaL_checkint(L, 2);
3407 int octaves = luaL_checkint(L, 3);
3408 double persistence = luaL_checknumber(L, 4);
3409 double scale = luaL_checknumber(L, 5);
3411 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
3412 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
3413 luaL_getmetatable(L, "PerlinNoise");
3414 lua_setmetatable(L, -2);
3419 EnvRef(ServerEnvironment *env):
3422 //infostream<<"EnvRef created"<<std::endl;
3427 //infostream<<"EnvRef destructing"<<std::endl;
3430 // Creates an EnvRef and leaves it on top of stack
3431 // Not callable from Lua; all references are created on the C side.
3432 static void create(lua_State *L, ServerEnvironment *env)
3434 EnvRef *o = new EnvRef(env);
3435 //infostream<<"EnvRef::create: o="<<o<<std::endl;
3436 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3437 luaL_getmetatable(L, className);
3438 lua_setmetatable(L, -2);
3441 static void set_null(lua_State *L)
3443 EnvRef *o = checkobject(L, -1);
3447 static void Register(lua_State *L)
3450 int methodtable = lua_gettop(L);
3451 luaL_newmetatable(L, className);
3452 int metatable = lua_gettop(L);
3454 lua_pushliteral(L, "__metatable");
3455 lua_pushvalue(L, methodtable);
3456 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3458 lua_pushliteral(L, "__index");
3459 lua_pushvalue(L, methodtable);
3460 lua_settable(L, metatable);
3462 lua_pushliteral(L, "__gc");
3463 lua_pushcfunction(L, gc_object);
3464 lua_settable(L, metatable);
3466 lua_pop(L, 1); // drop metatable
3468 luaL_openlib(L, 0, methods, 0); // fill methodtable
3469 lua_pop(L, 1); // drop methodtable
3471 // Cannot be created from Lua
3472 //lua_register(L, className, create_object);
3475 const char EnvRef::className[] = "EnvRef";
3476 const luaL_reg EnvRef::methods[] = {
3477 method(EnvRef, set_node),
3478 method(EnvRef, add_node),
3479 method(EnvRef, remove_node),
3480 method(EnvRef, get_node),
3481 method(EnvRef, get_node_or_nil),
3482 method(EnvRef, get_node_light),
3483 method(EnvRef, add_entity),
3484 method(EnvRef, add_item),
3485 method(EnvRef, add_rat),
3486 method(EnvRef, add_firefly),
3487 method(EnvRef, get_meta),
3488 method(EnvRef, get_player_by_name),
3489 method(EnvRef, get_objects_inside_radius),
3490 method(EnvRef, set_timeofday),
3491 method(EnvRef, get_timeofday),
3492 method(EnvRef, find_node_near),
3493 method(EnvRef, find_nodes_in_area),
3494 method(EnvRef, get_perlin),
3503 class LuaPseudoRandom
3506 PseudoRandom m_pseudo;
3508 static const char className[];
3509 static const luaL_reg methods[];
3511 // Exported functions
3513 // garbage collector
3514 static int gc_object(lua_State *L)
3516 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
3521 // next(self, min=0, max=32767) -> get next value
3522 static int l_next(lua_State *L)
3524 LuaPseudoRandom *o = checkobject(L, 1);
3527 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
3528 if(!lua_isnil(L, 2))
3529 min = luaL_checkinteger(L, 2);
3530 if(!lua_isnil(L, 3))
3531 max = luaL_checkinteger(L, 3);
3532 if(max - min != 32767 && max - min > 32767/5)
3533 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.");
3534 PseudoRandom &pseudo = o->m_pseudo;
3535 int val = pseudo.next();
3536 val = (val % (max-min+1)) + min;
3537 lua_pushinteger(L, val);
3542 LuaPseudoRandom(int seed):
3551 const PseudoRandom& getItem() const
3555 PseudoRandom& getItem()
3560 // LuaPseudoRandom(seed)
3561 // Creates an LuaPseudoRandom and leaves it on top of stack
3562 static int create_object(lua_State *L)
3564 int seed = luaL_checknumber(L, 1);
3565 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
3566 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3567 luaL_getmetatable(L, className);
3568 lua_setmetatable(L, -2);
3572 static LuaPseudoRandom* checkobject(lua_State *L, int narg)
3574 luaL_checktype(L, narg, LUA_TUSERDATA);
3575 void *ud = luaL_checkudata(L, narg, className);
3576 if(!ud) luaL_typerror(L, narg, className);
3577 return *(LuaPseudoRandom**)ud; // unbox pointer
3580 static void Register(lua_State *L)
3583 int methodtable = lua_gettop(L);
3584 luaL_newmetatable(L, className);
3585 int metatable = lua_gettop(L);
3587 lua_pushliteral(L, "__metatable");
3588 lua_pushvalue(L, methodtable);
3589 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
3591 lua_pushliteral(L, "__index");
3592 lua_pushvalue(L, methodtable);
3593 lua_settable(L, metatable);
3595 lua_pushliteral(L, "__gc");
3596 lua_pushcfunction(L, gc_object);
3597 lua_settable(L, metatable);
3599 lua_pop(L, 1); // drop metatable
3601 luaL_openlib(L, 0, methods, 0); // fill methodtable
3602 lua_pop(L, 1); // drop methodtable
3604 // Can be created from Lua (LuaPseudoRandom(seed))
3605 lua_register(L, className, create_object);
3608 const char LuaPseudoRandom::className[] = "PseudoRandom";
3609 const luaL_reg LuaPseudoRandom::methods[] = {
3610 method(LuaPseudoRandom, next),
3620 class LuaABM : public ActiveBlockModifier
3626 std::set<std::string> m_trigger_contents;
3627 std::set<std::string> m_required_neighbors;
3628 float m_trigger_interval;
3629 u32 m_trigger_chance;
3631 LuaABM(lua_State *L, int id,
3632 const std::set<std::string> &trigger_contents,
3633 const std::set<std::string> &required_neighbors,
3634 float trigger_interval, u32 trigger_chance):
3637 m_trigger_contents(trigger_contents),
3638 m_required_neighbors(required_neighbors),
3639 m_trigger_interval(trigger_interval),
3640 m_trigger_chance(trigger_chance)
3643 virtual std::set<std::string> getTriggerContents()
3645 return m_trigger_contents;
3647 virtual std::set<std::string> getRequiredNeighbors()
3649 return m_required_neighbors;
3651 virtual float getTriggerInterval()
3653 return m_trigger_interval;
3655 virtual u32 getTriggerChance()
3657 return m_trigger_chance;
3659 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
3660 u32 active_object_count, u32 active_object_count_wider)
3662 lua_State *L = m_lua;
3665 assert(lua_checkstack(L, 20));
3666 StackUnroller stack_unroller(L);
3668 // Get minetest.registered_abms
3669 lua_getglobal(L, "minetest");
3670 lua_getfield(L, -1, "registered_abms");
3671 luaL_checktype(L, -1, LUA_TTABLE);
3672 int registered_abms = lua_gettop(L);
3674 // Get minetest.registered_abms[m_id]
3675 lua_pushnumber(L, m_id);
3676 lua_gettable(L, registered_abms);
3677 if(lua_isnil(L, -1))
3681 luaL_checktype(L, -1, LUA_TTABLE);
3682 lua_getfield(L, -1, "action");
3683 luaL_checktype(L, -1, LUA_TFUNCTION);
3685 pushnode(L, n, env->getGameDef()->ndef());
3686 lua_pushnumber(L, active_object_count);
3687 lua_pushnumber(L, active_object_count_wider);
3688 if(lua_pcall(L, 4, 0, 0))
3689 script_error(L, "error: %s", lua_tostring(L, -1));
3697 static void read_server_sound_params(lua_State *L, int index,
3698 ServerSoundParams ¶ms)
3701 index = lua_gettop(L) + 1 + index;
3703 params = ServerSoundParams();
3704 if(lua_istable(L, index)){
3705 getfloatfield(L, index, "gain", params.gain);
3706 getstringfield(L, index, "to_player", params.to_player);
3707 lua_getfield(L, index, "pos");
3708 if(!lua_isnil(L, -1)){
3709 v3f p = read_v3f(L, -1)*BS;
3711 params.type = ServerSoundParams::SSP_POSITIONAL;
3714 lua_getfield(L, index, "object");
3715 if(!lua_isnil(L, -1)){
3716 ObjectRef *ref = ObjectRef::checkobject(L, -1);
3717 ServerActiveObject *sao = ObjectRef::getobject(ref);
3719 params.object = sao->getId();
3720 params.type = ServerSoundParams::SSP_OBJECT;
3724 params.max_hear_distance = BS*getfloatfield_default(L, index,
3725 "max_hear_distance", params.max_hear_distance/BS);
3726 getboolfield(L, index, "loop", params.loop);
3735 // Writes a line to dstream
3736 static int l_debug(lua_State *L)
3738 std::string text = lua_tostring(L, 1);
3739 dstream << text << std::endl;
3743 // log([level,] text)
3744 // Writes a line to the logger.
3745 // The one-argument version logs to infostream.
3746 // The two-argument version accept a log level: error, action, info, or verbose.
3747 static int l_log(lua_State *L)
3750 LogMessageLevel level = LMT_INFO;
3751 if(lua_isnone(L, 2))
3753 text = lua_tostring(L, 1);
3757 std::string levelname = lua_tostring(L, 1);
3758 text = lua_tostring(L, 2);
3759 if(levelname == "error")
3761 else if(levelname == "action")
3763 else if(levelname == "verbose")
3764 level = LMT_VERBOSE;
3766 log_printline(level, text);
3770 // register_item_raw({lots of stuff})
3771 static int l_register_item_raw(lua_State *L)
3773 luaL_checktype(L, 1, LUA_TTABLE);
3776 // Get the writable item and node definition managers from the server
3777 IWritableItemDefManager *idef =
3778 get_server(L)->getWritableItemDefManager();
3779 IWritableNodeDefManager *ndef =
3780 get_server(L)->getWritableNodeDefManager();
3782 // Check if name is defined
3783 lua_getfield(L, table, "name");
3784 if(lua_isstring(L, -1)){
3785 std::string name = lua_tostring(L, -1);
3786 verbosestream<<"register_item_raw: "<<name<<std::endl;
3788 throw LuaError(L, "register_item_raw: name is not defined or not a string");
3791 // Check if on_use is defined
3793 // Read the item definition and register it
3794 ItemDefinition def = read_item_definition(L, table);
3795 idef->registerItem(def);
3797 // Read the node definition (content features) and register it
3798 if(def.type == ITEM_NODE)
3800 ContentFeatures f = read_content_features(L, table);
3801 ndef->set(f.name, f);
3804 return 0; /* number of results */
3807 // register_alias_raw(name, convert_to_name)
3808 static int l_register_alias_raw(lua_State *L)
3810 std::string name = luaL_checkstring(L, 1);
3811 std::string convert_to = luaL_checkstring(L, 2);
3813 // Get the writable item definition manager from the server
3814 IWritableItemDefManager *idef =
3815 get_server(L)->getWritableItemDefManager();
3817 idef->registerAlias(name, convert_to);
3819 return 0; /* number of results */
3822 // helper for register_craft
3823 static bool read_craft_recipe_shaped(lua_State *L, int index,
3824 int &width, std::vector<std::string> &recipe)
3827 index = lua_gettop(L) + 1 + index;
3829 if(!lua_istable(L, index))
3834 while(lua_next(L, index) != 0){
3836 // key at index -2 and value at index -1
3837 if(!lua_istable(L, -1))
3839 int table2 = lua_gettop(L);
3841 while(lua_next(L, table2) != 0){
3842 // key at index -2 and value at index -1
3843 if(!lua_isstring(L, -1))
3845 recipe.push_back(lua_tostring(L, -1));
3846 // removes value, keeps key for next iteration
3853 if(colcount != width)
3856 // removes value, keeps key for next iteration
3863 // helper for register_craft
3864 static bool read_craft_recipe_shapeless(lua_State *L, int index,
3865 std::vector<std::string> &recipe)
3868 index = lua_gettop(L) + 1 + index;
3870 if(!lua_istable(L, index))
3874 while(lua_next(L, index) != 0){
3875 // key at index -2 and value at index -1
3876 if(!lua_isstring(L, -1))
3878 recipe.push_back(lua_tostring(L, -1));
3879 // removes value, keeps key for next iteration
3885 // helper for register_craft
3886 static bool read_craft_replacements(lua_State *L, int index,
3887 CraftReplacements &replacements)
3890 index = lua_gettop(L) + 1 + index;
3892 if(!lua_istable(L, index))
3896 while(lua_next(L, index) != 0){
3897 // key at index -2 and value at index -1
3898 if(!lua_istable(L, -1))
3900 lua_rawgeti(L, -1, 1);
3901 if(!lua_isstring(L, -1))
3903 std::string replace_from = lua_tostring(L, -1);
3905 lua_rawgeti(L, -1, 2);
3906 if(!lua_isstring(L, -1))
3908 std::string replace_to = lua_tostring(L, -1);
3910 replacements.pairs.push_back(
3911 std::make_pair(replace_from, replace_to));
3912 // removes value, keeps key for next iteration
3917 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
3918 static int l_register_craft(lua_State *L)
3920 //infostream<<"register_craft"<<std::endl;
3921 luaL_checktype(L, 1, LUA_TTABLE);
3924 // Get the writable craft definition manager from the server
3925 IWritableCraftDefManager *craftdef =
3926 get_server(L)->getWritableCraftDefManager();
3928 std::string type = getstringfield_default(L, table, "type", "shaped");
3931 CraftDefinitionShaped
3933 if(type == "shaped"){
3934 std::string output = getstringfield_default(L, table, "output", "");
3936 throw LuaError(L, "Crafting definition is missing an output");
3939 std::vector<std::string> recipe;
3940 lua_getfield(L, table, "recipe");
3941 if(lua_isnil(L, -1))
3942 throw LuaError(L, "Crafting definition is missing a recipe"
3943 " (output=\"" + output + "\")");
3944 if(!read_craft_recipe_shaped(L, -1, width, recipe))
3945 throw LuaError(L, "Invalid crafting recipe"
3946 " (output=\"" + output + "\")");
3948 CraftReplacements replacements;
3949 lua_getfield(L, table, "replacements");
3950 if(!lua_isnil(L, -1))
3952 if(!read_craft_replacements(L, -1, replacements))
3953 throw LuaError(L, "Invalid replacements"
3954 " (output=\"" + output + "\")");
3957 CraftDefinition *def = new CraftDefinitionShaped(
3958 output, width, recipe, replacements);
3959 craftdef->registerCraft(def);
3962 CraftDefinitionShapeless
3964 else if(type == "shapeless"){
3965 std::string output = getstringfield_default(L, table, "output", "");
3967 throw LuaError(L, "Crafting definition (shapeless)"
3968 " is missing an output");
3970 std::vector<std::string> recipe;
3971 lua_getfield(L, table, "recipe");
3972 if(lua_isnil(L, -1))
3973 throw LuaError(L, "Crafting definition (shapeless)"
3974 " is missing a recipe"
3975 " (output=\"" + output + "\")");
3976 if(!read_craft_recipe_shapeless(L, -1, recipe))
3977 throw LuaError(L, "Invalid crafting recipe"
3978 " (output=\"" + output + "\")");
3980 CraftReplacements replacements;
3981 lua_getfield(L, table, "replacements");
3982 if(!lua_isnil(L, -1))
3984 if(!read_craft_replacements(L, -1, replacements))
3985 throw LuaError(L, "Invalid replacements"
3986 " (output=\"" + output + "\")");
3989 CraftDefinition *def = new CraftDefinitionShapeless(
3990 output, recipe, replacements);
3991 craftdef->registerCraft(def);
3994 CraftDefinitionToolRepair
3996 else if(type == "toolrepair"){
3997 float additional_wear = getfloatfield_default(L, table,
3998 "additional_wear", 0.0);
4000 CraftDefinition *def = new CraftDefinitionToolRepair(
4002 craftdef->registerCraft(def);
4005 CraftDefinitionCooking
4007 else if(type == "cooking"){
4008 std::string output = getstringfield_default(L, table, "output", "");
4010 throw LuaError(L, "Crafting definition (cooking)"
4011 " is missing an output");
4013 std::string recipe = getstringfield_default(L, table, "recipe", "");
4015 throw LuaError(L, "Crafting definition (cooking)"
4016 " is missing a recipe"
4017 " (output=\"" + output + "\")");
4019 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4021 CraftDefinition *def = new CraftDefinitionCooking(
4022 output, recipe, cooktime);
4023 craftdef->registerCraft(def);
4028 else if(type == "fuel"){
4029 std::string recipe = getstringfield_default(L, table, "recipe", "");
4031 throw LuaError(L, "Crafting definition (fuel)"
4032 " is missing a recipe");
4034 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
4036 CraftDefinition *def = new CraftDefinitionFuel(
4038 craftdef->registerCraft(def);
4042 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
4046 return 0; /* number of results */
4049 // setting_set(name, value)
4050 static int l_setting_set(lua_State *L)
4052 const char *name = luaL_checkstring(L, 1);
4053 const char *value = luaL_checkstring(L, 2);
4054 g_settings->set(name, value);
4058 // setting_get(name)
4059 static int l_setting_get(lua_State *L)
4061 const char *name = luaL_checkstring(L, 1);
4063 std::string value = g_settings->get(name);
4064 lua_pushstring(L, value.c_str());
4065 } catch(SettingNotFoundException &e){
4071 // setting_getbool(name)
4072 static int l_setting_getbool(lua_State *L)
4074 const char *name = luaL_checkstring(L, 1);
4076 bool value = g_settings->getBool(name);
4077 lua_pushboolean(L, value);
4078 } catch(SettingNotFoundException &e){
4084 // chat_send_all(text)
4085 static int l_chat_send_all(lua_State *L)
4087 const char *text = luaL_checkstring(L, 1);
4088 // Get server from registry
4089 Server *server = get_server(L);
4091 server->notifyPlayers(narrow_to_wide(text));
4095 // chat_send_player(name, text)
4096 static int l_chat_send_player(lua_State *L)
4098 const char *name = luaL_checkstring(L, 1);
4099 const char *text = luaL_checkstring(L, 2);
4100 // Get server from registry
4101 Server *server = get_server(L);
4103 server->notifyPlayer(name, narrow_to_wide(text));
4107 // get_player_privs(name, text)
4108 static int l_get_player_privs(lua_State *L)
4110 const char *name = luaL_checkstring(L, 1);
4111 // Get server from registry
4112 Server *server = get_server(L);
4115 int table = lua_gettop(L);
4116 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
4117 for(std::set<std::string>::const_iterator
4118 i = privs_s.begin(); i != privs_s.end(); i++){
4119 lua_pushboolean(L, true);
4120 lua_setfield(L, table, i->c_str());
4122 lua_pushvalue(L, table);
4126 // get_inventory(location)
4127 static int l_get_inventory(lua_State *L)
4129 InventoryLocation loc;
4131 std::string type = checkstringfield(L, 1, "type");
4132 if(type == "player"){
4133 std::string name = checkstringfield(L, 1, "name");
4134 loc.setPlayer(name);
4135 } else if(type == "node"){
4136 lua_getfield(L, 1, "pos");
4137 v3s16 pos = check_v3s16(L, -1);
4138 loc.setNodeMeta(pos);
4141 if(get_server(L)->getInventory(loc) != NULL)
4142 InvRef::create(L, loc);
4148 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
4149 static int l_get_dig_params(lua_State *L)
4151 std::map<std::string, int> groups;
4152 read_groups(L, 1, groups);
4153 ToolCapabilities tp = read_tool_capabilities(L, 2);
4154 if(lua_isnoneornil(L, 3))
4155 push_dig_params(L, getDigParams(groups, &tp));
4157 push_dig_params(L, getDigParams(groups, &tp,
4158 luaL_checknumber(L, 3)));
4162 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
4163 static int l_get_hit_params(lua_State *L)
4165 std::map<std::string, int> groups;
4166 read_groups(L, 1, groups);
4167 ToolCapabilities tp = read_tool_capabilities(L, 2);
4168 if(lua_isnoneornil(L, 3))
4169 push_hit_params(L, getHitParams(groups, &tp));
4171 push_hit_params(L, getHitParams(groups, &tp,
4172 luaL_checknumber(L, 3)));
4176 // get_current_modname()
4177 static int l_get_current_modname(lua_State *L)
4179 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
4183 // get_modpath(modname)
4184 static int l_get_modpath(lua_State *L)
4186 std::string modname = luaL_checkstring(L, 1);
4188 if(modname == "__builtin"){
4189 std::string path = get_server(L)->getBuiltinLuaPath();
4190 lua_pushstring(L, path.c_str());
4193 const ModSpec *mod = get_server(L)->getModSpec(modname);
4198 lua_pushstring(L, mod->path.c_str());
4203 static int l_get_worldpath(lua_State *L)
4205 std::string worldpath = get_server(L)->getWorldPath();
4206 lua_pushstring(L, worldpath.c_str());
4210 // sound_play(spec, parameters)
4211 static int l_sound_play(lua_State *L)
4213 SimpleSoundSpec spec;
4214 read_soundspec(L, 1, spec);
4215 ServerSoundParams params;
4216 read_server_sound_params(L, 2, params);
4217 s32 handle = get_server(L)->playSound(spec, params);
4218 lua_pushinteger(L, handle);
4222 // sound_stop(handle)
4223 static int l_sound_stop(lua_State *L)
4225 int handle = luaL_checkinteger(L, 1);
4226 get_server(L)->stopSound(handle);
4230 // is_singleplayer()
4231 static int l_is_singleplayer(lua_State *L)
4233 lua_pushboolean(L, get_server(L)->isSingleplayer());
4237 // get_password_hash(name, raw_password)
4238 static int l_get_password_hash(lua_State *L)
4240 std::string name = luaL_checkstring(L, 1);
4241 std::string raw_password = luaL_checkstring(L, 2);
4242 std::string hash = translatePassword(name,
4243 narrow_to_wide(raw_password));
4244 lua_pushstring(L, hash.c_str());
4248 // notify_authentication_modified(name)
4249 static int l_notify_authentication_modified(lua_State *L)
4251 std::string name = "";
4252 if(lua_isstring(L, 1))
4253 name = lua_tostring(L, 1);
4254 get_server(L)->reportPrivsModified(name);
4258 static const struct luaL_Reg minetest_f [] = {
4261 {"register_item_raw", l_register_item_raw},
4262 {"register_alias_raw", l_register_alias_raw},
4263 {"register_craft", l_register_craft},
4264 {"setting_set", l_setting_set},
4265 {"setting_get", l_setting_get},
4266 {"setting_getbool", l_setting_getbool},
4267 {"chat_send_all", l_chat_send_all},
4268 {"chat_send_player", l_chat_send_player},
4269 {"get_player_privs", l_get_player_privs},
4270 {"get_inventory", l_get_inventory},
4271 {"get_dig_params", l_get_dig_params},
4272 {"get_hit_params", l_get_hit_params},
4273 {"get_current_modname", l_get_current_modname},
4274 {"get_modpath", l_get_modpath},
4275 {"get_worldpath", l_get_worldpath},
4276 {"sound_play", l_sound_play},
4277 {"sound_stop", l_sound_stop},
4278 {"is_singleplayer", l_is_singleplayer},
4279 {"get_password_hash", l_get_password_hash},
4280 {"notify_authentication_modified", l_notify_authentication_modified},
4285 Main export function
4288 void scriptapi_export(lua_State *L, Server *server)
4291 assert(lua_checkstack(L, 20));
4292 verbosestream<<"scriptapi_export()"<<std::endl;
4293 StackUnroller stack_unroller(L);
4295 // Store server as light userdata in registry
4296 lua_pushlightuserdata(L, server);
4297 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
4299 // Register global functions in table minetest
4301 luaL_register(L, NULL, minetest_f);
4302 lua_setglobal(L, "minetest");
4304 // Get the main minetest table
4305 lua_getglobal(L, "minetest");
4307 // Add tables to minetest
4310 lua_setfield(L, -2, "object_refs");
4312 lua_setfield(L, -2, "luaentities");
4314 // Register wrappers
4315 LuaItemStack::Register(L);
4316 InvRef::Register(L);
4317 NodeMetaRef::Register(L);
4318 ObjectRef::Register(L);
4319 EnvRef::Register(L);
4320 LuaPseudoRandom::Register(L);
4321 LuaPerlinNoise::Register(L);
4324 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
4325 const std::string &modname)
4327 ModNameStorer modnamestorer(L, modname);
4329 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
4331 errorstream<<"Error loading mod \""<<modname
4332 <<"\": modname does not follow naming conventions: "
4333 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
4337 bool success = false;
4340 success = script_load(L, scriptpath.c_str());
4343 errorstream<<"Error loading mod \""<<modname
4344 <<"\": "<<e.what()<<std::endl;
4350 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
4353 assert(lua_checkstack(L, 20));
4354 verbosestream<<"scriptapi_add_environment"<<std::endl;
4355 StackUnroller stack_unroller(L);
4357 // Create EnvRef on stack
4358 EnvRef::create(L, env);
4359 int envref = lua_gettop(L);
4361 // minetest.env = envref
4362 lua_getglobal(L, "minetest");
4363 luaL_checktype(L, -1, LUA_TTABLE);
4364 lua_pushvalue(L, envref);
4365 lua_setfield(L, -2, "env");
4367 // Store environment as light userdata in registry
4368 lua_pushlightuserdata(L, env);
4369 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
4372 Add ActiveBlockModifiers to environment
4375 // Get minetest.registered_abms
4376 lua_getglobal(L, "minetest");
4377 lua_getfield(L, -1, "registered_abms");
4378 luaL_checktype(L, -1, LUA_TTABLE);
4379 int registered_abms = lua_gettop(L);
4381 if(lua_istable(L, registered_abms)){
4382 int table = lua_gettop(L);
4384 while(lua_next(L, table) != 0){
4385 // key at index -2 and value at index -1
4386 int id = lua_tonumber(L, -2);
4387 int current_abm = lua_gettop(L);
4389 std::set<std::string> trigger_contents;
4390 lua_getfield(L, current_abm, "nodenames");
4391 if(lua_istable(L, -1)){
4392 int table = lua_gettop(L);
4394 while(lua_next(L, table) != 0){
4395 // key at index -2 and value at index -1
4396 luaL_checktype(L, -1, LUA_TSTRING);
4397 trigger_contents.insert(lua_tostring(L, -1));
4398 // removes value, keeps key for next iteration
4401 } else if(lua_isstring(L, -1)){
4402 trigger_contents.insert(lua_tostring(L, -1));
4406 std::set<std::string> required_neighbors;
4407 lua_getfield(L, current_abm, "neighbors");
4408 if(lua_istable(L, -1)){
4409 int table = lua_gettop(L);
4411 while(lua_next(L, table) != 0){
4412 // key at index -2 and value at index -1
4413 luaL_checktype(L, -1, LUA_TSTRING);
4414 required_neighbors.insert(lua_tostring(L, -1));
4415 // removes value, keeps key for next iteration
4418 } else if(lua_isstring(L, -1)){
4419 required_neighbors.insert(lua_tostring(L, -1));
4423 float trigger_interval = 10.0;
4424 getfloatfield(L, current_abm, "interval", trigger_interval);
4426 int trigger_chance = 50;
4427 getintfield(L, current_abm, "chance", trigger_chance);
4429 LuaABM *abm = new LuaABM(L, id, trigger_contents,
4430 required_neighbors, trigger_interval, trigger_chance);
4432 env->addActiveBlockModifier(abm);
4434 // removes value, keeps key for next iteration
4442 // Dump stack top with the dump2 function
4443 static void dump2(lua_State *L, const char *name)
4445 // Dump object (debug)
4446 lua_getglobal(L, "dump2");
4447 luaL_checktype(L, -1, LUA_TFUNCTION);
4448 lua_pushvalue(L, -2); // Get previous stack top as first parameter
4449 lua_pushstring(L, name);
4450 if(lua_pcall(L, 2, 0, 0))
4451 script_error(L, "error: %s", lua_tostring(L, -1));
4459 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
4462 assert(lua_checkstack(L, 20));
4463 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
4464 StackUnroller stack_unroller(L);
4466 // Create object on stack
4467 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
4468 int object = lua_gettop(L);
4470 // Get minetest.object_refs table
4471 lua_getglobal(L, "minetest");
4472 lua_getfield(L, -1, "object_refs");
4473 luaL_checktype(L, -1, LUA_TTABLE);
4474 int objectstable = lua_gettop(L);
4476 // object_refs[id] = object
4477 lua_pushnumber(L, cobj->getId()); // Push id
4478 lua_pushvalue(L, object); // Copy object to top of stack
4479 lua_settable(L, objectstable);
4482 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
4485 assert(lua_checkstack(L, 20));
4486 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
4487 StackUnroller stack_unroller(L);
4489 // Get minetest.object_refs table
4490 lua_getglobal(L, "minetest");
4491 lua_getfield(L, -1, "object_refs");
4492 luaL_checktype(L, -1, LUA_TTABLE);
4493 int objectstable = lua_gettop(L);
4495 // Get object_refs[id]
4496 lua_pushnumber(L, cobj->getId()); // Push id
4497 lua_gettable(L, objectstable);
4498 // Set object reference to NULL
4499 ObjectRef::set_null(L);
4500 lua_pop(L, 1); // pop object
4502 // Set object_refs[id] = nil
4503 lua_pushnumber(L, cobj->getId()); // Push id
4505 lua_settable(L, objectstable);
4512 // What scriptapi_run_callbacks does with the return values of callbacks.
4513 // Regardless of the mode, if only one callback is defined,
4514 // its return value is the total return value.
4515 // Modes only affect the case where 0 or >= 2 callbacks are defined.
4516 enum RunCallbacksMode
4518 // Returns the return value of the first callback
4519 // Returns nil if list of callbacks is empty
4520 RUN_CALLBACKS_MODE_FIRST,
4521 // Returns the return value of the last callback
4522 // Returns nil if list of callbacks is empty
4523 RUN_CALLBACKS_MODE_LAST,
4524 // If any callback returns a false value, the first such is returned
4525 // Otherwise, the first callback's return value (trueish) is returned
4526 // Returns true if list of callbacks is empty
4527 RUN_CALLBACKS_MODE_AND,
4528 // Like above, but stops calling callbacks (short circuit)
4529 // after seeing the first false value
4530 RUN_CALLBACKS_MODE_AND_SC,
4531 // If any callback returns a true value, the first such is returned
4532 // Otherwise, the first callback's return value (falseish) is returned
4533 // Returns false if list of callbacks is empty
4534 RUN_CALLBACKS_MODE_OR,
4535 // Like above, but stops calling callbacks (short circuit)
4536 // after seeing the first true value
4537 RUN_CALLBACKS_MODE_OR_SC,
4538 // Note: "a true value" and "a false value" refer to values that
4539 // are converted by lua_toboolean to true or false, respectively.
4542 // Push the list of callbacks (a lua table).
4543 // Then push nargs arguments.
4544 // Then call this function, which
4545 // - runs the callbacks
4546 // - removes the table and arguments from the lua stack
4547 // - pushes the return value, computed depending on mode
4548 static void scriptapi_run_callbacks(lua_State *L, int nargs,
4549 RunCallbacksMode mode)
4551 // Insert the return value into the lua stack, below the table
4552 assert(lua_gettop(L) >= nargs + 1);
4554 lua_insert(L, -(nargs + 1) - 1);
4555 // Stack now looks like this:
4556 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
4558 int rv = lua_gettop(L) - nargs - 1;
4560 int arg = table + 1;
4562 luaL_checktype(L, table, LUA_TTABLE);
4566 bool first_loop = true;
4567 while(lua_next(L, table) != 0){
4568 // key at index -2 and value at index -1
4569 luaL_checktype(L, -1, LUA_TFUNCTION);
4571 for(int i = 0; i < nargs; i++)
4572 lua_pushvalue(L, arg+i);
4573 if(lua_pcall(L, nargs, 1, 0))
4574 script_error(L, "error: %s", lua_tostring(L, -1));
4576 // Move return value to designated space in stack
4579 // Result of first callback is always moved
4583 // Otherwise, what happens depends on the mode
4584 if(mode == RUN_CALLBACKS_MODE_FIRST)
4586 else if(mode == RUN_CALLBACKS_MODE_LAST)
4588 else if(mode == RUN_CALLBACKS_MODE_AND ||
4589 mode == RUN_CALLBACKS_MODE_AND_SC){
4590 if(lua_toboolean(L, rv) == true &&
4591 lua_toboolean(L, -1) == false)
4596 else if(mode == RUN_CALLBACKS_MODE_OR ||
4597 mode == RUN_CALLBACKS_MODE_OR_SC){
4598 if(lua_toboolean(L, rv) == false &&
4599 lua_toboolean(L, -1) == true)
4608 // Handle short circuit modes
4609 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
4610 lua_toboolean(L, rv) == false)
4612 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
4613 lua_toboolean(L, rv) == true)
4616 // value removed, keep key for next iteration
4619 // Remove stuff from stack, leaving only the return value
4622 // Fix return value in case no callbacks were called
4624 if(mode == RUN_CALLBACKS_MODE_AND ||
4625 mode == RUN_CALLBACKS_MODE_AND_SC){
4627 lua_pushboolean(L, true);
4629 else if(mode == RUN_CALLBACKS_MODE_OR ||
4630 mode == RUN_CALLBACKS_MODE_OR_SC){
4632 lua_pushboolean(L, false);
4637 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
4638 const std::string &message)
4641 assert(lua_checkstack(L, 20));
4642 StackUnroller stack_unroller(L);
4644 // Get minetest.registered_on_chat_messages
4645 lua_getglobal(L, "minetest");
4646 lua_getfield(L, -1, "registered_on_chat_messages");
4648 lua_pushstring(L, name.c_str());
4649 lua_pushstring(L, message.c_str());
4650 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
4651 bool ate = lua_toboolean(L, -1);
4655 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
4658 assert(lua_checkstack(L, 20));
4659 StackUnroller stack_unroller(L);
4661 // Get minetest.registered_on_newplayers
4662 lua_getglobal(L, "minetest");
4663 lua_getfield(L, -1, "registered_on_newplayers");
4665 objectref_get_or_create(L, player);
4666 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4669 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
4672 assert(lua_checkstack(L, 20));
4673 StackUnroller stack_unroller(L);
4675 // Get minetest.registered_on_dieplayers
4676 lua_getglobal(L, "minetest");
4677 lua_getfield(L, -1, "registered_on_dieplayers");
4679 objectref_get_or_create(L, player);
4680 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4683 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
4686 assert(lua_checkstack(L, 20));
4687 StackUnroller stack_unroller(L);
4689 // Get minetest.registered_on_respawnplayers
4690 lua_getglobal(L, "minetest");
4691 lua_getfield(L, -1, "registered_on_respawnplayers");
4693 objectref_get_or_create(L, player);
4694 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
4695 bool positioning_handled_by_some = lua_toboolean(L, -1);
4696 return positioning_handled_by_some;
4699 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
4702 assert(lua_checkstack(L, 20));
4703 StackUnroller stack_unroller(L);
4705 // Get minetest.registered_on_joinplayers
4706 lua_getglobal(L, "minetest");
4707 lua_getfield(L, -1, "registered_on_joinplayers");
4709 objectref_get_or_create(L, player);
4710 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4713 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
4716 assert(lua_checkstack(L, 20));
4717 StackUnroller stack_unroller(L);
4719 // Get minetest.registered_on_leaveplayers
4720 lua_getglobal(L, "minetest");
4721 lua_getfield(L, -1, "registered_on_leaveplayers");
4723 objectref_get_or_create(L, player);
4724 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
4727 void scriptapi_get_creative_inventory(lua_State *L, ServerActiveObject *player)
4730 assert(lua_checkstack(L, 20));
4731 StackUnroller stack_unroller(L);
4733 Inventory *inv = player->getInventory();
4736 lua_getglobal(L, "minetest");
4737 lua_getfield(L, -1, "creative_inventory");
4738 luaL_checktype(L, -1, LUA_TTABLE);
4739 inventory_set_list_from_lua(inv, "main", L, -1, PLAYER_INVENTORY_SIZE);
4742 static void get_auth_handler(lua_State *L)
4744 lua_getglobal(L, "minetest");
4745 lua_getfield(L, -1, "registered_auth_handler");
4746 if(lua_isnil(L, -1)){
4748 lua_getfield(L, -1, "builtin_auth_handler");
4750 if(lua_type(L, -1) != LUA_TTABLE)
4751 throw LuaError(L, "Authentication handler table not valid");
4754 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
4755 std::string *dst_password, std::set<std::string> *dst_privs)
4758 assert(lua_checkstack(L, 20));
4759 StackUnroller stack_unroller(L);
4761 get_auth_handler(L);
4762 lua_getfield(L, -1, "get_auth");
4763 if(lua_type(L, -1) != LUA_TFUNCTION)
4764 throw LuaError(L, "Authentication handler missing get_auth");
4765 lua_pushstring(L, playername.c_str());
4766 if(lua_pcall(L, 1, 1, 0))
4767 script_error(L, "error: %s", lua_tostring(L, -1));
4769 // nil = login not allowed
4770 if(lua_isnil(L, -1))
4772 luaL_checktype(L, -1, LUA_TTABLE);
4774 std::string password;
4775 bool found = getstringfield(L, -1, "password", password);
4777 throw LuaError(L, "Authentication handler didn't return password");
4779 *dst_password = password;
4781 lua_getfield(L, -1, "privileges");
4782 if(!lua_istable(L, -1))
4784 "Authentication handler didn't return privilege table");
4786 read_privileges(L, -1, *dst_privs);
4792 void scriptapi_create_auth(lua_State *L, const std::string &playername,
4793 const std::string &password)
4796 assert(lua_checkstack(L, 20));
4797 StackUnroller stack_unroller(L);
4799 get_auth_handler(L);
4800 lua_getfield(L, -1, "create_auth");
4801 if(lua_type(L, -1) != LUA_TFUNCTION)
4802 throw LuaError(L, "Authentication handler missing create_auth");
4803 lua_pushstring(L, playername.c_str());
4804 lua_pushstring(L, password.c_str());
4805 if(lua_pcall(L, 2, 0, 0))
4806 script_error(L, "error: %s", lua_tostring(L, -1));
4809 bool scriptapi_set_password(lua_State *L, const std::string &playername,
4810 const std::string &password)
4813 assert(lua_checkstack(L, 20));
4814 StackUnroller stack_unroller(L);
4816 get_auth_handler(L);
4817 lua_getfield(L, -1, "set_password");
4818 if(lua_type(L, -1) != LUA_TFUNCTION)
4819 throw LuaError(L, "Authentication handler missing set_password");
4820 lua_pushstring(L, playername.c_str());
4821 lua_pushstring(L, password.c_str());
4822 if(lua_pcall(L, 2, 1, 0))
4823 script_error(L, "error: %s", lua_tostring(L, -1));
4824 return lua_toboolean(L, -1);
4828 item callbacks and node callbacks
4831 // Retrieves minetest.registered_items[name][callbackname]
4832 // If that is nil or on error, return false and stack is unchanged
4833 // If that is a function, returns true and pushes the
4834 // function onto the stack
4835 static bool get_item_callback(lua_State *L,
4836 const char *name, const char *callbackname)
4838 lua_getglobal(L, "minetest");
4839 lua_getfield(L, -1, "registered_items");
4841 luaL_checktype(L, -1, LUA_TTABLE);
4842 lua_getfield(L, -1, name);
4844 // Should be a table
4845 if(lua_type(L, -1) != LUA_TTABLE)
4847 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
4851 lua_getfield(L, -1, callbackname);
4853 // Should be a function or nil
4854 if(lua_type(L, -1) == LUA_TFUNCTION)
4858 else if(lua_isnil(L, -1))
4865 errorstream<<"Item \""<<name<<"\" callback \""
4866 <<callbackname<<" is not a function"<<std::endl;
4872 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
4873 ServerActiveObject *dropper, v3f pos)
4876 assert(lua_checkstack(L, 20));
4877 StackUnroller stack_unroller(L);
4879 // Push callback function on stack
4880 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
4884 LuaItemStack::create(L, item);
4885 objectref_get_or_create(L, dropper);
4886 pushFloatPos(L, pos);
4887 if(lua_pcall(L, 3, 1, 0))
4888 script_error(L, "error: %s", lua_tostring(L, -1));
4889 if(!lua_isnil(L, -1))
4890 item = read_item(L, -1);
4894 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
4895 ServerActiveObject *placer, const PointedThing &pointed)
4898 assert(lua_checkstack(L, 20));
4899 StackUnroller stack_unroller(L);
4901 // Push callback function on stack
4902 if(!get_item_callback(L, item.name.c_str(), "on_place"))
4906 LuaItemStack::create(L, item);
4907 objectref_get_or_create(L, placer);
4908 push_pointed_thing(L, pointed);
4909 if(lua_pcall(L, 3, 1, 0))
4910 script_error(L, "error: %s", lua_tostring(L, -1));
4911 if(!lua_isnil(L, -1))
4912 item = read_item(L, -1);
4916 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
4917 ServerActiveObject *user, const PointedThing &pointed)
4920 assert(lua_checkstack(L, 20));
4921 StackUnroller stack_unroller(L);
4923 // Push callback function on stack
4924 if(!get_item_callback(L, item.name.c_str(), "on_use"))
4928 LuaItemStack::create(L, item);
4929 objectref_get_or_create(L, user);
4930 push_pointed_thing(L, pointed);
4931 if(lua_pcall(L, 3, 1, 0))
4932 script_error(L, "error: %s", lua_tostring(L, -1));
4933 if(!lua_isnil(L, -1))
4934 item = read_item(L, -1);
4938 bool scriptapi_node_on_punch(lua_State *L, v3s16 pos, MapNode node,
4939 ServerActiveObject *puncher)
4942 assert(lua_checkstack(L, 20));
4943 StackUnroller stack_unroller(L);
4945 INodeDefManager *ndef = get_server(L)->ndef();
4947 // Push callback function on stack
4948 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
4953 pushnode(L, node, ndef);
4954 objectref_get_or_create(L, puncher);
4955 if(lua_pcall(L, 3, 0, 0))
4956 script_error(L, "error: %s", lua_tostring(L, -1));
4960 bool scriptapi_node_on_dig(lua_State *L, v3s16 pos, MapNode node,
4961 ServerActiveObject *digger)
4964 assert(lua_checkstack(L, 20));
4965 StackUnroller stack_unroller(L);
4967 INodeDefManager *ndef = get_server(L)->ndef();
4969 // Push callback function on stack
4970 if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
4975 pushnode(L, node, ndef);
4976 objectref_get_or_create(L, digger);
4977 if(lua_pcall(L, 3, 0, 0))
4978 script_error(L, "error: %s", lua_tostring(L, -1));
4986 void scriptapi_environment_step(lua_State *L, float dtime)
4989 assert(lua_checkstack(L, 20));
4990 //infostream<<"scriptapi_environment_step"<<std::endl;
4991 StackUnroller stack_unroller(L);
4993 // Get minetest.registered_globalsteps
4994 lua_getglobal(L, "minetest");
4995 lua_getfield(L, -1, "registered_globalsteps");
4997 lua_pushnumber(L, dtime);
4998 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5001 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
5005 assert(lua_checkstack(L, 20));
5006 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
5007 StackUnroller stack_unroller(L);
5009 // Get minetest.registered_on_generateds
5010 lua_getglobal(L, "minetest");
5011 lua_getfield(L, -1, "registered_on_generateds");
5013 push_v3s16(L, minp);
5014 push_v3s16(L, maxp);
5015 lua_pushnumber(L, blockseed);
5016 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
5023 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
5026 assert(lua_checkstack(L, 20));
5027 verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
5028 <<name<<"\""<<std::endl;
5029 StackUnroller stack_unroller(L);
5031 // Get minetest.registered_entities[name]
5032 lua_getglobal(L, "minetest");
5033 lua_getfield(L, -1, "registered_entities");
5034 luaL_checktype(L, -1, LUA_TTABLE);
5035 lua_pushstring(L, name);
5036 lua_gettable(L, -2);
5037 // Should be a table, which we will use as a prototype
5038 //luaL_checktype(L, -1, LUA_TTABLE);
5039 if(lua_type(L, -1) != LUA_TTABLE){
5040 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
5043 int prototype_table = lua_gettop(L);
5044 //dump2(L, "prototype_table");
5046 // Create entity object
5048 int object = lua_gettop(L);
5050 // Set object metatable
5051 lua_pushvalue(L, prototype_table);
5052 lua_setmetatable(L, -2);
5054 // Add object reference
5055 // This should be userdata with metatable ObjectRef
5056 objectref_get(L, id);
5057 luaL_checktype(L, -1, LUA_TUSERDATA);
5058 if(!luaL_checkudata(L, -1, "ObjectRef"))
5059 luaL_typerror(L, -1, "ObjectRef");
5060 lua_setfield(L, -2, "object");
5062 // minetest.luaentities[id] = object
5063 lua_getglobal(L, "minetest");
5064 lua_getfield(L, -1, "luaentities");
5065 luaL_checktype(L, -1, LUA_TTABLE);
5066 lua_pushnumber(L, id); // Push id
5067 lua_pushvalue(L, object); // Copy object to top of stack
5068 lua_settable(L, -3);
5073 void scriptapi_luaentity_activate(lua_State *L, u16 id,
5074 const std::string &staticdata)
5077 assert(lua_checkstack(L, 20));
5078 verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
5079 StackUnroller stack_unroller(L);
5081 // Get minetest.luaentities[id]
5082 luaentity_get(L, id);
5083 int object = lua_gettop(L);
5085 // Get on_activate function
5086 lua_pushvalue(L, object);
5087 lua_getfield(L, -1, "on_activate");
5088 if(!lua_isnil(L, -1)){
5089 luaL_checktype(L, -1, LUA_TFUNCTION);
5090 lua_pushvalue(L, object); // self
5091 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
5092 // Call with 2 arguments, 0 results
5093 if(lua_pcall(L, 2, 0, 0))
5094 script_error(L, "error running function on_activate: %s\n",
5095 lua_tostring(L, -1));
5099 void scriptapi_luaentity_rm(lua_State *L, u16 id)
5102 assert(lua_checkstack(L, 20));
5103 verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
5105 // Get minetest.luaentities table
5106 lua_getglobal(L, "minetest");
5107 lua_getfield(L, -1, "luaentities");
5108 luaL_checktype(L, -1, LUA_TTABLE);
5109 int objectstable = lua_gettop(L);
5111 // Set luaentities[id] = nil
5112 lua_pushnumber(L, id); // Push id
5114 lua_settable(L, objectstable);
5116 lua_pop(L, 2); // pop luaentities, minetest
5119 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
5122 assert(lua_checkstack(L, 20));
5123 //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
5124 StackUnroller stack_unroller(L);
5126 // Get minetest.luaentities[id]
5127 luaentity_get(L, id);
5128 int object = lua_gettop(L);
5130 // Get get_staticdata function
5131 lua_pushvalue(L, object);
5132 lua_getfield(L, -1, "get_staticdata");
5133 if(lua_isnil(L, -1))
5136 luaL_checktype(L, -1, LUA_TFUNCTION);
5137 lua_pushvalue(L, object); // self
5138 // Call with 1 arguments, 1 results
5139 if(lua_pcall(L, 1, 1, 0))
5140 script_error(L, "error running function get_staticdata: %s\n",
5141 lua_tostring(L, -1));
5144 const char *s = lua_tolstring(L, -1, &len);
5145 return std::string(s, len);
5148 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
5149 ObjectProperties *prop)
5152 assert(lua_checkstack(L, 20));
5153 //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
5154 StackUnroller stack_unroller(L);
5156 // Get minetest.luaentities[id]
5157 luaentity_get(L, id);
5158 //int object = lua_gettop(L);
5160 // Set default values that differ from ObjectProperties defaults
5163 // Deprecated: read object properties directly
5164 read_object_properties(L, -1, prop);
5166 // Read initial_properties
5167 lua_getfield(L, -1, "initial_properties");
5168 read_object_properties(L, -1, prop);
5172 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
5175 assert(lua_checkstack(L, 20));
5176 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5177 StackUnroller stack_unroller(L);
5179 // Get minetest.luaentities[id]
5180 luaentity_get(L, id);
5181 int object = lua_gettop(L);
5182 // State: object is at top of stack
5183 // Get step function
5184 lua_getfield(L, -1, "on_step");
5185 if(lua_isnil(L, -1))
5187 luaL_checktype(L, -1, LUA_TFUNCTION);
5188 lua_pushvalue(L, object); // self
5189 lua_pushnumber(L, dtime); // dtime
5190 // Call with 2 arguments, 0 results
5191 if(lua_pcall(L, 2, 0, 0))
5192 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
5195 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
5196 // tool_capabilities, direction)
5197 void scriptapi_luaentity_punch(lua_State *L, u16 id,
5198 ServerActiveObject *puncher, float time_from_last_punch,
5199 const ToolCapabilities *toolcap, v3f dir)
5202 assert(lua_checkstack(L, 20));
5203 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5204 StackUnroller stack_unroller(L);
5206 // Get minetest.luaentities[id]
5207 luaentity_get(L, id);
5208 int object = lua_gettop(L);
5209 // State: object is at top of stack
5211 lua_getfield(L, -1, "on_punch");
5212 if(lua_isnil(L, -1))
5214 luaL_checktype(L, -1, LUA_TFUNCTION);
5215 lua_pushvalue(L, object); // self
5216 objectref_get_or_create(L, puncher); // Clicker reference
5217 lua_pushnumber(L, time_from_last_punch);
5218 push_tool_capabilities(L, *toolcap);
5220 // Call with 5 arguments, 0 results
5221 if(lua_pcall(L, 5, 0, 0))
5222 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
5225 // Calls entity:on_rightclick(ObjectRef clicker)
5226 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
5227 ServerActiveObject *clicker)
5230 assert(lua_checkstack(L, 20));
5231 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
5232 StackUnroller stack_unroller(L);
5234 // Get minetest.luaentities[id]
5235 luaentity_get(L, id);
5236 int object = lua_gettop(L);
5237 // State: object is at top of stack
5239 lua_getfield(L, -1, "on_rightclick");
5240 if(lua_isnil(L, -1))
5242 luaL_checktype(L, -1, LUA_TFUNCTION);
5243 lua_pushvalue(L, object); // self
5244 objectref_get_or_create(L, clicker); // Clicker reference
5245 // Call with 2 arguments, 0 results
5246 if(lua_pcall(L, 2, 0, 0))
5247 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));