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"
37 #include "luaentity_common.h"
38 #include "content_sao.h" // For LuaEntitySAO
42 #include "craftitemdef.h"
43 #include "main.h" // For g_settings
44 #include "settings.h" // For accessing g_settings
45 #include "nodemetadata.h"
46 #include "mapblock.h" // For getNodeBlockPos
47 #include "content_nodemeta.h"
50 static void stackDump(lua_State *L, std::ostream &o)
53 int top = lua_gettop(L);
54 for (i = 1; i <= top; i++) { /* repeat for each level */
55 int t = lua_type(L, i);
58 case LUA_TSTRING: /* strings */
59 o<<"\""<<lua_tostring(L, i)<<"\"";
62 case LUA_TBOOLEAN: /* booleans */
63 o<<(lua_toboolean(L, i) ? "true" : "false");
66 case LUA_TNUMBER: /* numbers */ {
68 snprintf(buf, 10, "%g", lua_tonumber(L, i));
72 default: /* other values */
73 o<<lua_typename(L, t);
82 static void realitycheck(lua_State *L)
84 int top = lua_gettop(L);
86 dstream<<"Stack is over 30:"<<std::endl;
87 stackDump(L, dstream);
88 script_error(L, "Stack is over 30 (reality check)");
98 StackUnroller(lua_State *L):
102 m_original_top = lua_gettop(m_lua); // store stack height
106 lua_settop(m_lua, m_original_top); // restore stack height
110 static v3f readFloatPos(lua_State *L, int index)
113 luaL_checktype(L, index, LUA_TTABLE);
114 lua_getfield(L, index, "x");
115 pos.X = lua_tonumber(L, -1);
117 lua_getfield(L, index, "y");
118 pos.Y = lua_tonumber(L, -1);
120 lua_getfield(L, index, "z");
121 pos.Z = lua_tonumber(L, -1);
123 pos *= BS; // Scale to internal format
127 static void pushFloatPos(lua_State *L, v3f p)
131 lua_pushnumber(L, p.X);
132 lua_setfield(L, -2, "x");
133 lua_pushnumber(L, p.Y);
134 lua_setfield(L, -2, "y");
135 lua_pushnumber(L, p.Z);
136 lua_setfield(L, -2, "z");
139 static void pushpos(lua_State *L, v3s16 p)
142 lua_pushnumber(L, p.X);
143 lua_setfield(L, -2, "x");
144 lua_pushnumber(L, p.Y);
145 lua_setfield(L, -2, "y");
146 lua_pushnumber(L, p.Z);
147 lua_setfield(L, -2, "z");
150 static v3s16 readpos(lua_State *L, int index)
152 // Correct rounding at <0
153 v3f pf = readFloatPos(L, index);
154 return floatToInt(pf, BS);
157 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
160 lua_pushstring(L, ndef->get(n).name.c_str());
161 lua_setfield(L, -2, "name");
162 lua_pushnumber(L, n.getParam1());
163 lua_setfield(L, -2, "param1");
164 lua_pushnumber(L, n.getParam2());
165 lua_setfield(L, -2, "param2");
168 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
170 lua_getfield(L, index, "name");
171 const char *name = lua_tostring(L, -1);
174 lua_getfield(L, index, "param1");
178 param1 = lua_tonumber(L, -1);
181 lua_getfield(L, index, "param2");
185 param2 = lua_tonumber(L, -1);
187 return MapNode(ndef, name, param1, param2);
190 static video::SColor readARGB8(lua_State *L, int index)
193 luaL_checktype(L, index, LUA_TTABLE);
194 lua_getfield(L, index, "a");
195 if(lua_isnumber(L, -1))
196 color.setAlpha(lua_tonumber(L, -1));
198 lua_getfield(L, index, "r");
199 color.setRed(lua_tonumber(L, -1));
201 lua_getfield(L, index, "g");
202 color.setGreen(lua_tonumber(L, -1));
204 lua_getfield(L, index, "b");
205 color.setBlue(lua_tonumber(L, -1));
210 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
212 core::aabbox3d<f32> box;
213 if(lua_istable(L, -1)){
214 lua_rawgeti(L, -1, 1);
215 box.MinEdge.X = lua_tonumber(L, -1) * scale;
217 lua_rawgeti(L, -1, 2);
218 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
220 lua_rawgeti(L, -1, 3);
221 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
223 lua_rawgeti(L, -1, 4);
224 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
226 lua_rawgeti(L, -1, 5);
227 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
229 lua_rawgeti(L, -1, 6);
230 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
236 static v2s16 read_v2s16(lua_State *L, int index)
239 luaL_checktype(L, index, LUA_TTABLE);
240 lua_getfield(L, index, "x");
241 p.X = lua_tonumber(L, -1);
243 lua_getfield(L, index, "y");
244 p.Y = lua_tonumber(L, -1);
249 static v2f read_v2f(lua_State *L, int index)
252 luaL_checktype(L, index, LUA_TTABLE);
253 lua_getfield(L, index, "x");
254 p.X = lua_tonumber(L, -1);
256 lua_getfield(L, index, "y");
257 p.Y = lua_tonumber(L, -1);
262 static bool getstringfield(lua_State *L, int table,
263 const char *fieldname, std::string &result)
265 lua_getfield(L, table, fieldname);
267 if(lua_isstring(L, -1)){
268 result = lua_tostring(L, -1);
275 static bool getintfield(lua_State *L, int table,
276 const char *fieldname, int &result)
278 lua_getfield(L, table, fieldname);
280 if(lua_isnumber(L, -1)){
281 result = lua_tonumber(L, -1);
288 static bool getfloatfield(lua_State *L, int table,
289 const char *fieldname, float &result)
291 lua_getfield(L, table, fieldname);
293 if(lua_isnumber(L, -1)){
294 result = lua_tonumber(L, -1);
301 static bool getboolfield(lua_State *L, int table,
302 const char *fieldname, bool &result)
304 lua_getfield(L, table, fieldname);
306 if(lua_isboolean(L, -1)){
307 result = lua_toboolean(L, -1);
314 static std::string getstringfield_default(lua_State *L, int table,
315 const char *fieldname, const std::string &default_)
317 std::string result = default_;
318 getstringfield(L, table, fieldname, result);
322 static int getintfield_default(lua_State *L, int table,
323 const char *fieldname, int default_)
325 int result = default_;
326 getintfield(L, table, fieldname, result);
330 /*static float getfloatfield_default(lua_State *L, int table,
331 const char *fieldname, float default_)
333 float result = default_;
334 getfloatfield(L, table, fieldname, result);
338 static bool getboolfield_default(lua_State *L, int table,
339 const char *fieldname, bool default_)
341 bool result = default_;
342 getboolfield(L, table, fieldname, result);
352 static bool string_to_enum(const EnumString *spec, int &result,
353 const std::string &str)
355 const EnumString *esp = spec;
357 if(str == std::string(esp->str)){
366 /*static bool enum_to_string(const EnumString *spec, std::string &result,
369 const EnumString *esp = spec;
380 static int getenumfield(lua_State *L, int table,
381 const char *fieldname, const EnumString *spec, int default_)
383 int result = default_;
384 string_to_enum(spec, result,
385 getstringfield_default(L, table, fieldname, ""));
389 struct EnumString es_DrawType[] =
391 {NDT_NORMAL, "normal"},
392 {NDT_AIRLIKE, "airlike"},
393 {NDT_LIQUID, "liquid"},
394 {NDT_FLOWINGLIQUID, "flowingliquid"},
395 {NDT_GLASSLIKE, "glasslike"},
396 {NDT_ALLFACES, "allfaces"},
397 {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
398 {NDT_TORCHLIKE, "torchlike"},
399 {NDT_SIGNLIKE, "signlike"},
400 {NDT_PLANTLIKE, "plantlike"},
401 {NDT_FENCELIKE, "fencelike"},
402 {NDT_RAILLIKE, "raillike"},
406 struct EnumString es_ContentParamType[] =
409 {CPT_LIGHT, "light"},
410 {CPT_MINERAL, "mineral"},
411 {CPT_FACEDIR_SIMPLE, "facedir_simple"},
415 struct EnumString es_LiquidType[] =
417 {LIQUID_NONE, "none"},
418 {LIQUID_FLOWING, "flowing"},
419 {LIQUID_SOURCE, "source"},
423 struct EnumString es_NodeBoxType[] =
425 {NODEBOX_REGULAR, "regular"},
426 {NODEBOX_FIXED, "fixed"},
427 {NODEBOX_WALLMOUNTED, "wallmounted"},
431 struct EnumString es_Diggability[] =
433 {DIGGABLE_NOT, "not"},
434 {DIGGABLE_NORMAL, "normal"},
435 {DIGGABLE_CONSTANT, "constant"},
443 static int l_register_nodedef_defaults(lua_State *L)
445 luaL_checktype(L, 1, LUA_TTABLE);
447 lua_pushvalue(L, 1); // Explicitly put parameter 1 on top of stack
448 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_nodedef_default");
453 // Register new object prototype
454 // register_entity(name, prototype)
455 static int l_register_entity(lua_State *L)
457 const char *name = luaL_checkstring(L, 1);
458 infostream<<"register_entity: "<<name<<std::endl;
459 luaL_checktype(L, 2, LUA_TTABLE);
461 // Get minetest.registered_entities
462 lua_getglobal(L, "minetest");
463 lua_getfield(L, -1, "registered_entities");
464 luaL_checktype(L, -1, LUA_TTABLE);
465 int registered_entities = lua_gettop(L);
466 lua_pushvalue(L, 2); // Object = param 2 -> stack top
467 // registered_entities[name] = object
468 lua_setfield(L, registered_entities, name);
470 // Get registered object to top of stack
473 // Set __index to point to itself
474 lua_pushvalue(L, -1);
475 lua_setfield(L, -2, "__index");
477 // Set metatable.__index = metatable
478 luaL_getmetatable(L, "minetest.entity");
479 lua_pushvalue(L, -1); // duplicate metatable
480 lua_setfield(L, -2, "__index");
481 // Set object metatable
482 lua_setmetatable(L, -2);
484 return 0; /* number of results */
487 class LuaABM : public ActiveBlockModifier
493 std::set<std::string> m_trigger_contents;
494 float m_trigger_interval;
495 u32 m_trigger_chance;
497 LuaABM(lua_State *L, int id,
498 const std::set<std::string> &trigger_contents,
499 float trigger_interval, u32 trigger_chance):
502 m_trigger_contents(trigger_contents),
503 m_trigger_interval(trigger_interval),
504 m_trigger_chance(trigger_chance)
507 virtual std::set<std::string> getTriggerContents()
509 return m_trigger_contents;
511 virtual float getTriggerInterval()
513 return m_trigger_interval;
515 virtual u32 getTriggerChance()
517 return m_trigger_chance;
519 virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
520 u32 active_object_count, u32 active_object_count_wider)
522 lua_State *L = m_lua;
525 assert(lua_checkstack(L, 20));
526 StackUnroller stack_unroller(L);
528 // Get minetest.registered_abms
529 lua_getglobal(L, "minetest");
530 lua_getfield(L, -1, "registered_abms");
531 luaL_checktype(L, -1, LUA_TTABLE);
532 int registered_abms = lua_gettop(L);
534 // Get minetest.registered_abms[m_id]
535 lua_pushnumber(L, m_id);
536 lua_gettable(L, registered_abms);
541 luaL_checktype(L, -1, LUA_TTABLE);
542 lua_getfield(L, -1, "action");
543 luaL_checktype(L, -1, LUA_TFUNCTION);
545 pushnode(L, n, env->getGameDef()->ndef());
546 lua_pushnumber(L, active_object_count);
547 lua_pushnumber(L, active_object_count_wider);
548 if(lua_pcall(L, 4, 0, 0))
549 script_error(L, "error: %s\n", lua_tostring(L, -1));
553 // register_abm({...})
554 static int l_register_abm(lua_State *L)
556 infostream<<"register_abm"<<std::endl;
557 luaL_checktype(L, 1, LUA_TTABLE);
559 // Get minetest.registered_abms
560 lua_getglobal(L, "minetest");
561 lua_getfield(L, -1, "registered_abms");
562 luaL_checktype(L, -1, LUA_TTABLE);
563 int registered_abms = lua_gettop(L);
568 lua_pushnumber(L, id);
569 lua_gettable(L, registered_abms);
577 infostream<<"register_abm: id="<<id<<std::endl;
579 // registered_abms[id] = spec
580 lua_pushnumber(L, id);
582 lua_settable(L, registered_abms);
584 return 0; /* number of results */
587 // register_tool(name, {lots of stuff})
588 static int l_register_tool(lua_State *L)
590 const char *name = luaL_checkstring(L, 1);
591 infostream<<"register_tool: "<<name<<std::endl;
592 luaL_checktype(L, 2, LUA_TTABLE);
595 // Get server from registry
596 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
597 Server *server = (Server*)lua_touserdata(L, -1);
598 // And get the writable tool definition manager from the server
599 IWritableToolDefManager *tooldef =
600 server->getWritableToolDefManager();
604 getstringfield(L, table, "image", def.imagename);
605 getfloatfield(L, table, "basetime", def.properties.basetime);
606 getfloatfield(L, table, "dt_weight", def.properties.dt_weight);
607 getfloatfield(L, table, "dt_crackiness", def.properties.dt_crackiness);
608 getfloatfield(L, table, "dt_crumbliness", def.properties.dt_crumbliness);
609 getfloatfield(L, table, "dt_cuttability", def.properties.dt_cuttability);
610 getfloatfield(L, table, "basedurability", def.properties.basedurability);
611 getfloatfield(L, table, "dd_weight", def.properties.dd_weight);
612 getfloatfield(L, table, "dd_crackiness", def.properties.dd_crackiness);
613 getfloatfield(L, table, "dd_crumbliness", def.properties.dd_crumbliness);
614 getfloatfield(L, table, "dd_cuttability", def.properties.dd_cuttability);
616 tooldef->registerTool(name, def);
617 return 0; /* number of results */
620 // register_craftitem(name, {lots of stuff})
621 static int l_register_craftitem(lua_State *L)
623 const char *name = luaL_checkstring(L, 1);
624 infostream<<"register_craftitem: "<<name<<std::endl;
625 luaL_checktype(L, 2, LUA_TTABLE);
628 // Get server from registry
629 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
630 Server *server = (Server*)lua_touserdata(L, -1);
631 // And get the writable CraftItem definition manager from the server
632 IWritableCraftItemDefManager *craftitemdef =
633 server->getWritableCraftItemDefManager();
635 // Check if on_drop is defined
636 lua_getfield(L, table, "on_drop");
637 bool got_on_drop = !lua_isnil(L, -1);
640 // Check if on_use is defined
641 lua_getfield(L, table, "on_use");
642 bool got_on_use = !lua_isnil(L, -1);
645 CraftItemDefinition def;
647 getstringfield(L, table, "image", def.imagename);
648 getstringfield(L, table, "cookresult_item", def.cookresult_item);
649 getfloatfield(L, table, "furnace_cooktime", def.furnace_cooktime);
650 getfloatfield(L, table, "furnace_burntime", def.furnace_burntime);
651 def.usable = getboolfield_default(L, table, "usable", got_on_use);
652 getboolfield(L, table, "liquids_pointable", def.liquids_pointable);
653 def.dropcount = getintfield_default(L, table, "dropcount", def.dropcount);
654 def.stack_max = getintfield_default(L, table, "stack_max", def.stack_max);
656 // If an on_drop callback is defined, force dropcount to 1
661 craftitemdef->registerCraftItem(name, def);
663 lua_pushvalue(L, table);
664 scriptapi_add_craftitem(L, name);
666 return 0; /* number of results */
669 // register_node(name, {lots of stuff})
670 static int l_register_node(lua_State *L)
672 const char *name = luaL_checkstring(L, 1);
673 infostream<<"register_node: "<<name<<std::endl;
674 luaL_checktype(L, 2, LUA_TTABLE);
675 int nodedef_table = 2;
677 // Get server from registry
678 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
679 Server *server = (Server*)lua_touserdata(L, -1);
680 // And get the writable node definition manager from the server
681 IWritableNodeDefManager *nodedef =
682 server->getWritableNodeDefManager();
684 // Get default node definition from registry
685 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_nodedef_default");
686 int nodedef_default = lua_gettop(L);
689 Add to minetest.registered_nodes with default as metatable
692 // Get the node definition table given as parameter
693 lua_pushvalue(L, nodedef_table);
695 // Set __index to point to itself
696 lua_pushvalue(L, -1);
697 lua_setfield(L, -2, "__index");
699 // Set nodedef_default as metatable for the definition
700 lua_pushvalue(L, nodedef_default);
701 lua_setmetatable(L, nodedef_table);
703 // minetest.registered_nodes[name] = nodedef
704 lua_getglobal(L, "minetest");
705 lua_getfield(L, -1, "registered_nodes");
706 luaL_checktype(L, -1, LUA_TTABLE);
707 lua_pushstring(L, name);
708 lua_pushvalue(L, nodedef_table);
717 // Default to getting the corresponding NodeItem when dug
718 f.dug_item = std::string("NodeItem \"")+name+"\" 1";
720 // Default to unknown_block.png as all textures
721 f.setAllTextures("unknown_block.png");
724 Read definiton from Lua
729 /* Visual definition */
731 f.drawtype = (NodeDrawType)getenumfield(L, nodedef_table, "drawtype", es_DrawType,
733 getfloatfield(L, nodedef_table, "visual_scale", f.visual_scale);
735 lua_getfield(L, nodedef_table, "tile_images");
736 if(lua_istable(L, -1)){
737 int table = lua_gettop(L);
740 while(lua_next(L, table) != 0){
741 // key at index -2 and value at index -1
742 if(lua_isstring(L, -1))
743 f.tname_tiles[i] = lua_tostring(L, -1);
745 f.tname_tiles[i] = "";
746 // removes value, keeps key for next iteration
754 // Copy last value to all remaining textures
756 std::string lastname = f.tname_tiles[i-1];
758 f.tname_tiles[i] = lastname;
765 getstringfield(L, nodedef_table, "inventory_image", f.tname_inventory);
767 lua_getfield(L, nodedef_table, "special_materials");
768 if(lua_istable(L, -1)){
769 int table = lua_gettop(L);
772 while(lua_next(L, table) != 0){
773 // key at index -2 and value at index -1
774 int smtable = lua_gettop(L);
775 std::string tname = getstringfield_default(
776 L, smtable, "image", "");
777 bool backface_culling = getboolfield_default(
778 L, smtable, "backface_culling", true);
779 MaterialSpec mspec(tname, backface_culling);
780 f.setSpecialMaterial(i, mspec);
781 // removes value, keeps key for next iteration
792 f.alpha = getintfield_default(L, nodedef_table, "alpha", 255);
796 lua_getfield(L, nodedef_table, "post_effect_color");
797 if(!lua_isnil(L, -1))
798 f.post_effect_color = readARGB8(L, -1);
801 f.param_type = (ContentParamType)getenumfield(L, nodedef_table, "paramtype",
802 es_ContentParamType, CPT_NONE);
804 // True for all ground-like things like stone and mud, false for eg. trees
805 getboolfield(L, nodedef_table, "is_ground_content", f.is_ground_content);
806 getboolfield(L, nodedef_table, "light_propagates", f.light_propagates);
807 getboolfield(L, nodedef_table, "sunlight_propagates", f.sunlight_propagates);
808 // This is used for collision detection.
809 // Also for general solidness queries.
810 getboolfield(L, nodedef_table, "walkable", f.walkable);
811 // Player can point to these
812 getboolfield(L, nodedef_table, "pointable", f.pointable);
813 // Player can dig these
814 getboolfield(L, nodedef_table, "diggable", f.diggable);
815 // Player can climb these
816 getboolfield(L, nodedef_table, "climbable", f.climbable);
817 // Player can build on these
818 getboolfield(L, nodedef_table, "buildable_to", f.buildable_to);
819 // If true, param2 is set to direction when placed. Used for torches.
820 // NOTE: the direction format is quite inefficient and should be changed
821 getboolfield(L, nodedef_table, "wall_mounted", f.wall_mounted);
822 // Whether this content type often contains mineral.
823 // Used for texture atlas creation.
824 // Currently only enabled for CONTENT_STONE.
825 getboolfield(L, nodedef_table, "often_contains_mineral", f.often_contains_mineral);
826 // Inventory item string as which the node appears in inventory when dug.
827 // Mineral overrides this.
828 getstringfield(L, nodedef_table, "dug_item", f.dug_item);
829 // Extra dug item and its rarity
830 getstringfield(L, nodedef_table, "extra_dug_item", f.extra_dug_item);
831 // Usual get interval for extra dug item
832 getintfield(L, nodedef_table, "extra_dug_item_rarity", f.extra_dug_item_rarity);
833 // Metadata name of node (eg. "furnace")
834 getstringfield(L, nodedef_table, "metadata_name", f.metadata_name);
835 // Whether the node is non-liquid, source liquid or flowing liquid
836 f.liquid_type = (LiquidType)getenumfield(L, nodedef_table, "liquidtype",
837 es_LiquidType, LIQUID_NONE);
838 // If the content is liquid, this is the flowing version of the liquid.
839 getstringfield(L, nodedef_table, "liquid_alternative_flowing",
840 f.liquid_alternative_flowing);
841 // If the content is liquid, this is the source version of the liquid.
842 getstringfield(L, nodedef_table, "liquid_alternative_source",
843 f.liquid_alternative_source);
844 // Viscosity for fluid flow, ranging from 1 to 7, with
845 // 1 giving almost instantaneous propagation and 7 being
846 // the slowest possible
847 f.liquid_viscosity = getintfield_default(L, nodedef_table,
848 "liquid_viscosity", f.liquid_viscosity);
849 // Amount of light the node emits
850 f.light_source = getintfield_default(L, nodedef_table,
851 "light_source", f.light_source);
852 f.damage_per_second = getintfield_default(L, nodedef_table,
853 "damage_per_second", f.damage_per_second);
855 lua_getfield(L, nodedef_table, "selection_box");
856 if(lua_istable(L, -1)){
857 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
858 es_NodeBoxType, NODEBOX_REGULAR);
860 lua_getfield(L, -1, "fixed");
861 if(lua_istable(L, -1))
862 f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
865 lua_getfield(L, -1, "wall_top");
866 if(lua_istable(L, -1))
867 f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
870 lua_getfield(L, -1, "wall_bottom");
871 if(lua_istable(L, -1))
872 f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
875 lua_getfield(L, -1, "wall_side");
876 if(lua_istable(L, -1))
877 f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
882 lua_getfield(L, nodedef_table, "material");
883 if(lua_istable(L, -1)){
884 f.material.diggability = (Diggability)getenumfield(L, -1, "diggability",
885 es_Diggability, DIGGABLE_NORMAL);
887 getfloatfield(L, -1, "constant_time", f.material.constant_time);
888 getfloatfield(L, -1, "weight", f.material.weight);
889 getfloatfield(L, -1, "crackiness", f.material.crackiness);
890 getfloatfield(L, -1, "crumbliness", f.material.crumbliness);
891 getfloatfield(L, -1, "cuttability", f.material.cuttability);
892 getfloatfield(L, -1, "flammability", f.material.flammability);
896 getstringfield(L, nodedef_table, "cookresult_item", f.cookresult_item);
897 getfloatfield(L, nodedef_table, "furnace_cooktime", f.furnace_cooktime);
898 getfloatfield(L, nodedef_table, "furnace_burntime", f.furnace_burntime);
904 nodedef->set(name, f);
906 return 0; /* number of results */
909 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
910 static int l_register_craft(lua_State *L)
912 infostream<<"register_craft"<<std::endl;
913 luaL_checktype(L, 1, LUA_TTABLE);
916 // Get server from registry
917 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
918 Server *server = (Server*)lua_touserdata(L, -1);
919 // And get the writable craft definition manager from the server
920 IWritableCraftDefManager *craftdef =
921 server->getWritableCraftDefManager();
925 std::vector<std::string> input;
927 lua_getfield(L, table0, "output");
928 luaL_checktype(L, -1, LUA_TSTRING);
929 if(lua_isstring(L, -1))
930 output = lua_tostring(L, -1);
933 lua_getfield(L, table0, "recipe");
934 luaL_checktype(L, -1, LUA_TTABLE);
935 if(lua_istable(L, -1)){
936 int table1 = lua_gettop(L);
939 while(lua_next(L, table1) != 0){
941 // key at index -2 and value at index -1
942 luaL_checktype(L, -1, LUA_TTABLE);
943 if(lua_istable(L, -1)){
944 int table2 = lua_gettop(L);
946 while(lua_next(L, table2) != 0){
947 // key at index -2 and value at index -1
948 luaL_checktype(L, -1, LUA_TSTRING);
949 input.push_back(lua_tostring(L, -1));
950 // removes value, keeps key for next iteration
958 if(colcount != width){
959 script_error(L, "error: %s\n", "Invalid crafting recipe");
962 // removes value, keeps key for next iteration
969 CraftDefinition def(output, width, input);
970 craftdef->registerCraft(def);
972 return 0; /* number of results */
976 static int l_setting_get(lua_State *L)
978 const char *name = luaL_checkstring(L, 1);
980 std::string value = g_settings->get(name);
981 lua_pushstring(L, value.c_str());
982 } catch(SettingNotFoundException &e){
988 // setting_getbool(name)
989 static int l_setting_getbool(lua_State *L)
991 const char *name = luaL_checkstring(L, 1);
993 bool value = g_settings->getBool(name);
994 lua_pushboolean(L, value);
995 } catch(SettingNotFoundException &e){
1001 // chat_send_all(text)
1002 static int l_chat_send_all(lua_State *L)
1004 const char *text = luaL_checkstring(L, 1);
1005 // Get server from registry
1006 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
1007 Server *server = (Server*)lua_touserdata(L, -1);
1009 server->notifyPlayers(narrow_to_wide(text));
1013 // chat_send_player(name, text)
1014 static int l_chat_send_player(lua_State *L)
1016 const char *name = luaL_checkstring(L, 1);
1017 const char *text = luaL_checkstring(L, 2);
1018 // Get server from registry
1019 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
1020 Server *server = (Server*)lua_touserdata(L, -1);
1022 server->notifyPlayer(name, narrow_to_wide(text));
1026 static const struct luaL_Reg minetest_f [] = {
1027 {"register_nodedef_defaults", l_register_nodedef_defaults},
1028 {"register_entity", l_register_entity},
1029 {"register_tool", l_register_tool},
1030 {"register_craftitem", l_register_craftitem},
1031 {"register_node", l_register_node},
1032 {"register_craft", l_register_craft},
1033 {"register_abm", l_register_abm},
1034 {"setting_get", l_setting_get},
1035 {"setting_getbool", l_setting_getbool},
1036 {"chat_send_all", l_chat_send_all},
1037 {"chat_send_player", l_chat_send_player},
1045 static const struct luaL_Reg minetest_entity_m [] = {
1050 Getters for stuff in main tables
1053 static void objectref_get(lua_State *L, u16 id)
1055 // Get minetest.object_refs[i]
1056 lua_getglobal(L, "minetest");
1057 lua_getfield(L, -1, "object_refs");
1058 luaL_checktype(L, -1, LUA_TTABLE);
1059 lua_pushnumber(L, id);
1060 lua_gettable(L, -2);
1061 lua_remove(L, -2); // object_refs
1062 lua_remove(L, -2); // minetest
1065 static void luaentity_get(lua_State *L, u16 id)
1067 // Get minetest.luaentities[i]
1068 lua_getglobal(L, "minetest");
1069 lua_getfield(L, -1, "luaentities");
1070 luaL_checktype(L, -1, LUA_TTABLE);
1071 lua_pushnumber(L, id);
1072 lua_gettable(L, -2);
1073 lua_remove(L, -2); // luaentities
1074 lua_remove(L, -2); // minetest
1081 #define method(class, name) {#name, class::l_##name}
1091 ServerEnvironment *m_env;
1093 static const char className[];
1094 static const luaL_reg methods[];
1096 static NodeMetaRef *checkobject(lua_State *L, int narg)
1098 luaL_checktype(L, narg, LUA_TUSERDATA);
1099 void *ud = luaL_checkudata(L, narg, className);
1100 if(!ud) luaL_typerror(L, narg, className);
1101 return *(NodeMetaRef**)ud; // unbox pointer
1104 static NodeMetadata* getmeta(NodeMetaRef *ref)
1106 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1110 /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1112 NodeMetadata *meta = getmeta(ref);
1115 if(meta->typeId() != NODEMETA_GENERIC)
1117 return (IGenericNodeMetadata*)meta;
1120 static void reportMetadataChange(NodeMetaRef *ref)
1122 // Inform other things that the metadata has changed
1123 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1125 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1127 ref->m_env->getMap().dispatchEvent(&event);
1128 // Set the block to be saved
1129 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1131 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1132 "NodeMetaRef::reportMetadataChange");
1135 // Exported functions
1137 // garbage collector
1138 static int gc_object(lua_State *L) {
1139 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1145 static int l_get_type(lua_State *L)
1147 NodeMetaRef *ref = checkobject(L, 1);
1148 NodeMetadata *meta = getmeta(ref);
1154 lua_pushstring(L, meta->typeName());
1158 // allows_text_input(self)
1159 static int l_allows_text_input(lua_State *L)
1161 NodeMetaRef *ref = checkobject(L, 1);
1162 NodeMetadata *meta = getmeta(ref);
1163 if(meta == NULL) return 0;
1165 lua_pushboolean(L, meta->allowsTextInput());
1169 // set_text(self, text)
1170 static int l_set_text(lua_State *L)
1172 NodeMetaRef *ref = checkobject(L, 1);
1173 NodeMetadata *meta = getmeta(ref);
1174 if(meta == NULL) return 0;
1176 std::string text = lua_tostring(L, 2);
1177 meta->setText(text);
1178 reportMetadataChange(ref);
1183 static int l_get_text(lua_State *L)
1185 NodeMetaRef *ref = checkobject(L, 1);
1186 NodeMetadata *meta = getmeta(ref);
1187 if(meta == NULL) return 0;
1189 std::string text = meta->getText();
1190 lua_pushstring(L, text.c_str());
1195 static int l_get_owner(lua_State *L)
1197 NodeMetaRef *ref = checkobject(L, 1);
1198 NodeMetadata *meta = getmeta(ref);
1199 if(meta == NULL) return 0;
1201 std::string owner = meta->getOwner();
1202 lua_pushstring(L, owner.c_str());
1206 /* IGenericNodeMetadata interface */
1208 // set_infotext(self, text)
1209 static int l_set_infotext(lua_State *L)
1211 infostream<<__FUNCTION_NAME<<std::endl;
1212 NodeMetaRef *ref = checkobject(L, 1);
1213 NodeMetadata *meta = getmeta(ref);
1214 if(meta == NULL) return 0;
1216 std::string text = lua_tostring(L, 2);
1217 meta->setInfoText(text);
1218 reportMetadataChange(ref);
1222 // inventory_set_list(self, name, {item1, item2, ...})
1223 static int l_inventory_set_list(lua_State *L)
1225 NodeMetaRef *ref = checkobject(L, 1);
1226 NodeMetadata *meta = getmeta(ref);
1227 if(meta == NULL) return 0;
1229 Inventory *inv = meta->getInventory();
1230 std::string name = lua_tostring(L, 2);
1231 // If nil, delete list
1232 if(lua_isnil(L, 3)){
1233 inv->deleteList(name);
1236 // Otherwise set list
1237 std::list<std::string> items;
1238 luaL_checktype(L, 3, LUA_TTABLE);
1241 infostream<<"items: ";
1242 while(lua_next(L, table) != 0){
1243 // key at index -2 and value at index -1
1244 luaL_checktype(L, -1, LUA_TSTRING);
1245 std::string itemstring = lua_tostring(L, -1);
1246 infostream<<"\""<<itemstring<<"\" ";
1247 items.push_back(itemstring);
1248 // removes value, keeps key for next iteration
1251 infostream<<std::endl;
1252 InventoryList *invlist = inv->addList(name, items.size());
1254 for(std::list<std::string>::const_iterator
1255 i = items.begin(); i != items.end(); i++){
1256 const std::string &itemstring = *i;
1257 InventoryItem *newitem = NULL;
1258 if(itemstring != "")
1259 newitem = InventoryItem::deSerialize(itemstring,
1260 ref->m_env->getGameDef());
1261 InventoryItem *olditem = invlist->changeItem(index, newitem);
1265 reportMetadataChange(ref);
1269 // inventory_get_list(self, name)
1270 static int l_inventory_get_list(lua_State *L)
1272 NodeMetaRef *ref = checkobject(L, 1);
1273 NodeMetadata *meta = getmeta(ref);
1274 if(meta == NULL) return 0;
1276 Inventory *inv = meta->getInventory();
1277 std::string name = lua_tostring(L, 2);
1278 InventoryList *invlist = inv->getList(name);
1279 if(invlist == NULL){
1283 // Get the table insert function
1284 lua_getglobal(L, "table");
1285 lua_getfield(L, -1, "insert");
1286 int table_insert = lua_gettop(L);
1287 // Create and fill table
1289 int table = lua_gettop(L);
1290 for(u32 i=0; i<invlist->getSize(); i++){
1291 InventoryItem *item = invlist->getItem(i);
1292 lua_pushvalue(L, table_insert);
1293 lua_pushvalue(L, table);
1297 lua_pushstring(L, item->getItemString().c_str());
1299 if(lua_pcall(L, 2, 0, 0))
1300 script_error(L, "error: %s\n", lua_tostring(L, -1));
1305 // set_inventory_draw_spec(self, text)
1306 static int l_set_inventory_draw_spec(lua_State *L)
1308 NodeMetaRef *ref = checkobject(L, 1);
1309 NodeMetadata *meta = getmeta(ref);
1310 if(meta == NULL) return 0;
1312 std::string text = lua_tostring(L, 2);
1313 meta->setInventoryDrawSpec(text);
1314 reportMetadataChange(ref);
1318 // set_allow_text_input(self, text)
1319 static int l_set_allow_text_input(lua_State *L)
1321 NodeMetaRef *ref = checkobject(L, 1);
1322 NodeMetadata *meta = getmeta(ref);
1323 if(meta == NULL) return 0;
1325 bool b = lua_toboolean(L, 2);
1326 meta->setAllowTextInput(b);
1327 reportMetadataChange(ref);
1331 // set_allow_removal(self, text)
1332 static int l_set_allow_removal(lua_State *L)
1334 NodeMetaRef *ref = checkobject(L, 1);
1335 NodeMetadata *meta = getmeta(ref);
1336 if(meta == NULL) return 0;
1338 bool b = lua_toboolean(L, 2);
1339 meta->setRemovalDisabled(!b);
1340 reportMetadataChange(ref);
1344 // set_enforce_owner(self, text)
1345 static int l_set_enforce_owner(lua_State *L)
1347 NodeMetaRef *ref = checkobject(L, 1);
1348 NodeMetadata *meta = getmeta(ref);
1349 if(meta == NULL) return 0;
1351 bool b = lua_toboolean(L, 2);
1352 meta->setEnforceOwner(b);
1353 reportMetadataChange(ref);
1357 // is_inventory_modified(self)
1358 static int l_is_inventory_modified(lua_State *L)
1360 NodeMetaRef *ref = checkobject(L, 1);
1361 NodeMetadata *meta = getmeta(ref);
1362 if(meta == NULL) return 0;
1364 lua_pushboolean(L, meta->isInventoryModified());
1368 // reset_inventory_modified(self)
1369 static int l_reset_inventory_modified(lua_State *L)
1371 NodeMetaRef *ref = checkobject(L, 1);
1372 NodeMetadata *meta = getmeta(ref);
1373 if(meta == NULL) return 0;
1375 meta->resetInventoryModified();
1376 reportMetadataChange(ref);
1380 // is_text_modified(self)
1381 static int l_is_text_modified(lua_State *L)
1383 NodeMetaRef *ref = checkobject(L, 1);
1384 NodeMetadata *meta = getmeta(ref);
1385 if(meta == NULL) return 0;
1387 lua_pushboolean(L, meta->isTextModified());
1391 // reset_text_modified(self)
1392 static int l_reset_text_modified(lua_State *L)
1394 NodeMetaRef *ref = checkobject(L, 1);
1395 NodeMetadata *meta = getmeta(ref);
1396 if(meta == NULL) return 0;
1398 meta->resetTextModified();
1399 reportMetadataChange(ref);
1403 // set_string(self, name, var)
1404 static int l_set_string(lua_State *L)
1406 NodeMetaRef *ref = checkobject(L, 1);
1407 NodeMetadata *meta = getmeta(ref);
1408 if(meta == NULL) return 0;
1410 std::string name = lua_tostring(L, 2);
1412 const char *s = lua_tolstring(L, 3, &len);
1413 std::string str(s, len);
1414 meta->setString(name, str);
1415 reportMetadataChange(ref);
1419 // get_string(self, name)
1420 static int l_get_string(lua_State *L)
1422 NodeMetaRef *ref = checkobject(L, 1);
1423 NodeMetadata *meta = getmeta(ref);
1424 if(meta == NULL) return 0;
1426 std::string name = lua_tostring(L, 2);
1427 std::string str = meta->getString(name);
1428 lua_pushlstring(L, str.c_str(), str.size());
1433 NodeMetaRef(v3s16 p, ServerEnvironment *env):
1443 // Creates an NodeMetaRef and leaves it on top of stack
1444 // Not callable from Lua; all references are created on the C side.
1445 static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
1447 NodeMetaRef *o = new NodeMetaRef(p, env);
1448 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
1449 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1450 luaL_getmetatable(L, className);
1451 lua_setmetatable(L, -2);
1454 static void Register(lua_State *L)
1457 int methodtable = lua_gettop(L);
1458 luaL_newmetatable(L, className);
1459 int metatable = lua_gettop(L);
1461 lua_pushliteral(L, "__metatable");
1462 lua_pushvalue(L, methodtable);
1463 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1465 lua_pushliteral(L, "__index");
1466 lua_pushvalue(L, methodtable);
1467 lua_settable(L, metatable);
1469 lua_pushliteral(L, "__gc");
1470 lua_pushcfunction(L, gc_object);
1471 lua_settable(L, metatable);
1473 lua_pop(L, 1); // drop metatable
1475 luaL_openlib(L, 0, methods, 0); // fill methodtable
1476 lua_pop(L, 1); // drop methodtable
1478 // Cannot be created from Lua
1479 //lua_register(L, className, create_object);
1482 const char NodeMetaRef::className[] = "NodeMetaRef";
1483 const luaL_reg NodeMetaRef::methods[] = {
1484 method(NodeMetaRef, get_type),
1485 method(NodeMetaRef, allows_text_input),
1486 method(NodeMetaRef, set_text),
1487 method(NodeMetaRef, get_text),
1488 method(NodeMetaRef, get_owner),
1489 method(NodeMetaRef, set_infotext),
1490 method(NodeMetaRef, inventory_set_list),
1491 method(NodeMetaRef, inventory_get_list),
1492 method(NodeMetaRef, set_inventory_draw_spec),
1493 method(NodeMetaRef, set_allow_text_input),
1494 method(NodeMetaRef, set_allow_removal),
1495 method(NodeMetaRef, set_enforce_owner),
1496 method(NodeMetaRef, is_inventory_modified),
1497 method(NodeMetaRef, reset_inventory_modified),
1498 method(NodeMetaRef, is_text_modified),
1499 method(NodeMetaRef, reset_text_modified),
1500 method(NodeMetaRef, set_string),
1501 method(NodeMetaRef, get_string),
1512 ServerEnvironment *m_env;
1514 static const char className[];
1515 static const luaL_reg methods[];
1517 static EnvRef *checkobject(lua_State *L, int narg)
1519 luaL_checktype(L, narg, LUA_TUSERDATA);
1520 void *ud = luaL_checkudata(L, narg, className);
1521 if(!ud) luaL_typerror(L, narg, className);
1522 return *(EnvRef**)ud; // unbox pointer
1525 // Exported functions
1527 // EnvRef:add_node(pos, node)
1528 // pos = {x=num, y=num, z=num}
1529 static int l_add_node(lua_State *L)
1531 //infostream<<"EnvRef::l_add_node()"<<std::endl;
1532 EnvRef *o = checkobject(L, 1);
1533 ServerEnvironment *env = o->m_env;
1534 if(env == NULL) return 0;
1536 v3s16 pos = readpos(L, 2);
1538 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
1540 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
1541 lua_pushboolean(L, succeeded);
1545 // EnvRef:remove_node(pos)
1546 // pos = {x=num, y=num, z=num}
1547 static int l_remove_node(lua_State *L)
1549 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
1550 EnvRef *o = checkobject(L, 1);
1551 ServerEnvironment *env = o->m_env;
1552 if(env == NULL) return 0;
1554 v3s16 pos = readpos(L, 2);
1556 bool succeeded = env->getMap().removeNodeWithEvent(pos);
1557 lua_pushboolean(L, succeeded);
1561 // EnvRef:get_node(pos)
1562 // pos = {x=num, y=num, z=num}
1563 static int l_get_node(lua_State *L)
1565 //infostream<<"EnvRef::l_get_node()"<<std::endl;
1566 EnvRef *o = checkobject(L, 1);
1567 ServerEnvironment *env = o->m_env;
1568 if(env == NULL) return 0;
1570 v3s16 pos = readpos(L, 2);
1572 MapNode n = env->getMap().getNodeNoEx(pos);
1574 pushnode(L, n, env->getGameDef()->ndef());
1578 // EnvRef:add_luaentity(pos, entityname)
1579 // pos = {x=num, y=num, z=num}
1580 static int l_add_luaentity(lua_State *L)
1582 //infostream<<"EnvRef::l_add_luaentity()"<<std::endl;
1583 EnvRef *o = checkobject(L, 1);
1584 ServerEnvironment *env = o->m_env;
1585 if(env == NULL) return 0;
1587 v3f pos = readFloatPos(L, 2);
1589 const char *name = lua_tostring(L, 3);
1591 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
1592 env->addActiveObject(obj);
1596 // EnvRef:add_item(pos, inventorystring)
1597 // pos = {x=num, y=num, z=num}
1598 static int l_add_item(lua_State *L)
1600 infostream<<"EnvRef::l_add_item()"<<std::endl;
1601 EnvRef *o = checkobject(L, 1);
1602 ServerEnvironment *env = o->m_env;
1603 if(env == NULL) return 0;
1605 v3f pos = readFloatPos(L, 2);
1607 const char *inventorystring = lua_tostring(L, 3);
1609 ServerActiveObject *obj = new ItemSAO(env, pos, inventorystring);
1610 env->addActiveObject(obj);
1614 // EnvRef:add_rat(pos)
1615 // pos = {x=num, y=num, z=num}
1616 static int l_add_rat(lua_State *L)
1618 infostream<<"EnvRef::l_add_rat()"<<std::endl;
1619 EnvRef *o = checkobject(L, 1);
1620 ServerEnvironment *env = o->m_env;
1621 if(env == NULL) return 0;
1623 v3f pos = readFloatPos(L, 2);
1625 ServerActiveObject *obj = new RatSAO(env, pos);
1626 env->addActiveObject(obj);
1630 // EnvRef:add_firefly(pos)
1631 // pos = {x=num, y=num, z=num}
1632 static int l_add_firefly(lua_State *L)
1634 infostream<<"EnvRef::l_add_firefly()"<<std::endl;
1635 EnvRef *o = checkobject(L, 1);
1636 ServerEnvironment *env = o->m_env;
1637 if(env == NULL) return 0;
1639 v3f pos = readFloatPos(L, 2);
1641 ServerActiveObject *obj = new FireflySAO(env, pos);
1642 env->addActiveObject(obj);
1646 // EnvRef:get_meta(pos)
1647 static int l_get_meta(lua_State *L)
1649 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
1650 EnvRef *o = checkobject(L, 1);
1651 ServerEnvironment *env = o->m_env;
1652 if(env == NULL) return 0;
1654 v3s16 p = readpos(L, 2);
1655 NodeMetaRef::create(L, p, env);
1659 static int gc_object(lua_State *L) {
1660 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
1666 EnvRef(ServerEnvironment *env):
1669 infostream<<"EnvRef created"<<std::endl;
1674 infostream<<"EnvRef destructing"<<std::endl;
1677 // Creates an EnvRef and leaves it on top of stack
1678 // Not callable from Lua; all references are created on the C side.
1679 static void create(lua_State *L, ServerEnvironment *env)
1681 EnvRef *o = new EnvRef(env);
1682 //infostream<<"EnvRef::create: o="<<o<<std::endl;
1683 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1684 luaL_getmetatable(L, className);
1685 lua_setmetatable(L, -2);
1688 static void set_null(lua_State *L)
1690 EnvRef *o = checkobject(L, -1);
1694 static void Register(lua_State *L)
1697 int methodtable = lua_gettop(L);
1698 luaL_newmetatable(L, className);
1699 int metatable = lua_gettop(L);
1701 lua_pushliteral(L, "__metatable");
1702 lua_pushvalue(L, methodtable);
1703 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
1705 lua_pushliteral(L, "__index");
1706 lua_pushvalue(L, methodtable);
1707 lua_settable(L, metatable);
1709 lua_pushliteral(L, "__gc");
1710 lua_pushcfunction(L, gc_object);
1711 lua_settable(L, metatable);
1713 lua_pop(L, 1); // drop metatable
1715 luaL_openlib(L, 0, methods, 0); // fill methodtable
1716 lua_pop(L, 1); // drop methodtable
1718 // Cannot be created from Lua
1719 //lua_register(L, className, create_object);
1722 const char EnvRef::className[] = "EnvRef";
1723 const luaL_reg EnvRef::methods[] = {
1724 method(EnvRef, add_node),
1725 method(EnvRef, remove_node),
1726 method(EnvRef, get_node),
1727 method(EnvRef, add_luaentity),
1728 method(EnvRef, add_item),
1729 method(EnvRef, add_rat),
1730 method(EnvRef, add_firefly),
1731 method(EnvRef, get_meta),
1742 ServerActiveObject *m_object;
1744 static const char className[];
1745 static const luaL_reg methods[];
1747 static ObjectRef *checkobject(lua_State *L, int narg)
1749 luaL_checktype(L, narg, LUA_TUSERDATA);
1750 void *ud = luaL_checkudata(L, narg, className);
1751 if(!ud) luaL_typerror(L, narg, className);
1752 return *(ObjectRef**)ud; // unbox pointer
1755 static ServerActiveObject* getobject(ObjectRef *ref)
1757 ServerActiveObject *co = ref->m_object;
1761 static LuaEntitySAO* getluaobject(ObjectRef *ref)
1763 ServerActiveObject *obj = getobject(ref);
1766 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
1768 return (LuaEntitySAO*)obj;
1771 static ServerRemotePlayer* getplayer(ObjectRef *ref)
1773 ServerActiveObject *obj = getobject(ref);
1776 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
1778 return static_cast<ServerRemotePlayer*>(obj);
1781 // Exported functions
1783 // garbage collector
1784 static int gc_object(lua_State *L) {
1785 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
1786 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
1792 static int l_remove(lua_State *L)
1794 ObjectRef *ref = checkobject(L, 1);
1795 ServerActiveObject *co = getobject(ref);
1796 if(co == NULL) return 0;
1797 infostream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
1798 co->m_removed = true;
1803 // returns: {x=num, y=num, z=num}
1804 static int l_getpos(lua_State *L)
1806 ObjectRef *ref = checkobject(L, 1);
1807 ServerActiveObject *co = getobject(ref);
1808 if(co == NULL) return 0;
1809 v3f pos = co->getBasePosition() / BS;
1811 lua_pushnumber(L, pos.X);
1812 lua_setfield(L, -2, "x");
1813 lua_pushnumber(L, pos.Y);
1814 lua_setfield(L, -2, "y");
1815 lua_pushnumber(L, pos.Z);
1816 lua_setfield(L, -2, "z");
1820 // setpos(self, pos)
1821 static int l_setpos(lua_State *L)
1823 ObjectRef *ref = checkobject(L, 1);
1824 //LuaEntitySAO *co = getluaobject(ref);
1825 ServerActiveObject *co = getobject(ref);
1826 if(co == NULL) return 0;
1828 v3f pos = readFloatPos(L, 2);
1834 // moveto(self, pos, continuous=false)
1835 static int l_moveto(lua_State *L)
1837 ObjectRef *ref = checkobject(L, 1);
1838 //LuaEntitySAO *co = getluaobject(ref);
1839 ServerActiveObject *co = getobject(ref);
1840 if(co == NULL) return 0;
1842 v3f pos = readFloatPos(L, 2);
1844 bool continuous = lua_toboolean(L, 3);
1846 co->moveTo(pos, continuous);
1850 // setvelocity(self, velocity)
1851 static int l_setvelocity(lua_State *L)
1853 ObjectRef *ref = checkobject(L, 1);
1854 LuaEntitySAO *co = getluaobject(ref);
1855 if(co == NULL) return 0;
1857 v3f pos = readFloatPos(L, 2);
1859 co->setVelocity(pos);
1863 // setacceleration(self, acceleration)
1864 static int l_setacceleration(lua_State *L)
1866 ObjectRef *ref = checkobject(L, 1);
1867 LuaEntitySAO *co = getluaobject(ref);
1868 if(co == NULL) return 0;
1870 v3f pos = readFloatPos(L, 2);
1872 co->setAcceleration(pos);
1876 // getacceleration(self)
1877 static int l_getacceleration(lua_State *L)
1879 ObjectRef *ref = checkobject(L, 1);
1880 LuaEntitySAO *co = getluaobject(ref);
1881 if(co == NULL) return 0;
1883 v3f v = co->getAcceleration();
1888 // add_to_inventory(self, itemstring)
1889 // returns: true if item was added, false otherwise
1890 static int l_add_to_inventory(lua_State *L)
1892 ObjectRef *ref = checkobject(L, 1);
1893 luaL_checkstring(L, 2);
1894 ServerActiveObject *co = getobject(ref);
1895 if(co == NULL) return 0;
1897 const char *itemstring = lua_tostring(L, 2);
1898 infostream<<"ObjectRef::l_add_to_inventory(): id="<<co->getId()
1899 <<" itemstring=\""<<itemstring<<"\""<<std::endl;
1901 std::istringstream is(itemstring, std::ios::binary);
1902 ServerEnvironment *env = co->getEnv();
1904 IGameDef *gamedef = env->getGameDef();
1905 InventoryItem *item = InventoryItem::deSerialize(is, gamedef);
1906 infostream<<"item="<<env<<std::endl;
1907 bool fits = co->addToInventory(item);
1909 lua_pushboolean(L, fits);
1913 // add_to_inventory_later(self, itemstring)
1915 static int l_add_to_inventory_later(lua_State *L)
1917 ObjectRef *ref = checkobject(L, 1);
1918 luaL_checkstring(L, 2);
1919 ServerActiveObject *co = getobject(ref);
1920 if(co == NULL) return 0;
1922 const char *itemstring = lua_tostring(L, 2);
1923 infostream<<"ObjectRef::l_add_to_inventory_later(): id="<<co->getId()
1924 <<" itemstring=\""<<itemstring<<"\""<<std::endl;
1926 std::istringstream is(itemstring, std::ios::binary);
1927 ServerEnvironment *env = co->getEnv();
1929 IGameDef *gamedef = env->getGameDef();
1930 InventoryItem *item = InventoryItem::deSerialize(is, gamedef);
1931 infostream<<"item="<<env<<std::endl;
1932 co->addToInventoryLater(item);
1938 // returns: number of hitpoints (2 * number of hearts)
1939 // 0 if not applicable to this type of object
1940 static int l_get_hp(lua_State *L)
1942 ObjectRef *ref = checkobject(L, 1);
1943 ServerActiveObject *co = getobject(ref);
1944 if(co == NULL) return 0;
1945 int hp = co->getHP();
1946 infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
1947 <<" hp="<<hp<<std::endl;
1949 lua_pushnumber(L, hp);
1954 // hp = number of hitpoints (2 * number of hearts)
1956 static int l_set_hp(lua_State *L)
1958 ObjectRef *ref = checkobject(L, 1);
1959 luaL_checknumber(L, 2);
1960 ServerActiveObject *co = getobject(ref);
1961 if(co == NULL) return 0;
1962 int hp = lua_tonumber(L, 2);
1963 infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
1964 <<" hp="<<hp<<std::endl;
1971 // settexturemod(self, mod)
1972 static int l_settexturemod(lua_State *L)
1974 ObjectRef *ref = checkobject(L, 1);
1975 LuaEntitySAO *co = getluaobject(ref);
1976 if(co == NULL) return 0;
1978 std::string mod = lua_tostring(L, 2);
1979 co->setTextureMod(mod);
1983 // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
1984 // select_horiz_by_yawpitch=false)
1985 static int l_setsprite(lua_State *L)
1987 ObjectRef *ref = checkobject(L, 1);
1988 LuaEntitySAO *co = getluaobject(ref);
1989 if(co == NULL) return 0;
1992 if(!lua_isnil(L, 2))
1993 p = read_v2s16(L, 2);
1995 if(!lua_isnil(L, 3))
1996 num_frames = lua_tonumber(L, 3);
1997 float framelength = 0.2;
1998 if(!lua_isnil(L, 4))
1999 framelength = lua_tonumber(L, 4);
2000 bool select_horiz_by_yawpitch = false;
2001 if(!lua_isnil(L, 5))
2002 select_horiz_by_yawpitch = lua_toboolean(L, 5);
2003 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2008 ObjectRef(ServerActiveObject *object):
2011 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2017 infostream<<"ObjectRef destructing for id="
2018 <<m_object->getId()<<std::endl;
2020 infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2023 // Creates an ObjectRef and leaves it on top of stack
2024 // Not callable from Lua; all references are created on the C side.
2025 static void create(lua_State *L, ServerActiveObject *object)
2027 ObjectRef *o = new ObjectRef(object);
2028 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2029 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2030 luaL_getmetatable(L, className);
2031 lua_setmetatable(L, -2);
2034 static void set_null(lua_State *L)
2036 ObjectRef *o = checkobject(L, -1);
2040 static void Register(lua_State *L)
2043 int methodtable = lua_gettop(L);
2044 luaL_newmetatable(L, className);
2045 int metatable = lua_gettop(L);
2047 lua_pushliteral(L, "__metatable");
2048 lua_pushvalue(L, methodtable);
2049 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
2051 lua_pushliteral(L, "__index");
2052 lua_pushvalue(L, methodtable);
2053 lua_settable(L, metatable);
2055 lua_pushliteral(L, "__gc");
2056 lua_pushcfunction(L, gc_object);
2057 lua_settable(L, metatable);
2059 lua_pop(L, 1); // drop metatable
2061 luaL_openlib(L, 0, methods, 0); // fill methodtable
2062 lua_pop(L, 1); // drop methodtable
2064 // Cannot be created from Lua
2065 //lua_register(L, className, create_object);
2068 const char ObjectRef::className[] = "ObjectRef";
2069 const luaL_reg ObjectRef::methods[] = {
2070 method(ObjectRef, remove),
2071 method(ObjectRef, getpos),
2072 method(ObjectRef, setpos),
2073 method(ObjectRef, moveto),
2074 method(ObjectRef, setvelocity),
2075 method(ObjectRef, setacceleration),
2076 method(ObjectRef, add_to_inventory),
2077 method(ObjectRef, add_to_inventory_later),
2078 method(ObjectRef, get_hp),
2079 method(ObjectRef, set_hp),
2080 method(ObjectRef, settexturemod),
2081 method(ObjectRef, setsprite),
2085 // Creates a new anonymous reference if id=0
2086 static void objectref_get_or_create(lua_State *L,
2087 ServerActiveObject *cobj)
2089 if(cobj->getId() == 0){
2090 ObjectRef::create(L, cobj);
2092 objectref_get(L, cobj->getId());
2097 Main export function
2100 void scriptapi_export(lua_State *L, Server *server)
2103 assert(lua_checkstack(L, 20));
2104 infostream<<"scriptapi_export"<<std::endl;
2105 StackUnroller stack_unroller(L);
2107 // Store server as light userdata in registry
2108 lua_pushlightuserdata(L, server);
2109 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
2111 // Store nil as minetest_nodedef_defaults in registry
2113 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_nodedef_default");
2115 // Register global functions in table minetest
2117 luaL_register(L, NULL, minetest_f);
2118 lua_setglobal(L, "minetest");
2120 // Get the main minetest table
2121 lua_getglobal(L, "minetest");
2123 // Add tables to minetest
2126 lua_setfield(L, -2, "registered_nodes");
2128 lua_setfield(L, -2, "registered_entities");
2130 lua_setfield(L, -2, "registered_craftitems");
2132 lua_setfield(L, -2, "registered_abms");
2135 lua_setfield(L, -2, "object_refs");
2137 lua_setfield(L, -2, "luaentities");
2139 // Create entity prototype
2140 luaL_newmetatable(L, "minetest.entity");
2141 // metatable.__index = metatable
2142 lua_pushvalue(L, -1); // Duplicate metatable
2143 lua_setfield(L, -2, "__index");
2144 // Put functions in metatable
2145 luaL_register(L, NULL, minetest_entity_m);
2146 // Put other stuff in metatable
2148 // Register reference wrappers
2149 NodeMetaRef::Register(L);
2150 EnvRef::Register(L);
2151 ObjectRef::Register(L);
2154 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
2157 assert(lua_checkstack(L, 20));
2158 infostream<<"scriptapi_add_environment"<<std::endl;
2159 StackUnroller stack_unroller(L);
2161 // Create EnvRef on stack
2162 EnvRef::create(L, env);
2163 int envref = lua_gettop(L);
2165 // minetest.env = envref
2166 lua_getglobal(L, "minetest");
2167 luaL_checktype(L, -1, LUA_TTABLE);
2168 lua_pushvalue(L, envref);
2169 lua_setfield(L, -2, "env");
2171 // Store environment as light userdata in registry
2172 lua_pushlightuserdata(L, env);
2173 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
2175 /* Add ActiveBlockModifiers to environment */
2177 // Get minetest.registered_abms
2178 lua_getglobal(L, "minetest");
2179 lua_getfield(L, -1, "registered_abms");
2180 luaL_checktype(L, -1, LUA_TTABLE);
2181 int registered_abms = lua_gettop(L);
2183 if(lua_istable(L, registered_abms)){
2184 int table = lua_gettop(L);
2186 while(lua_next(L, table) != 0){
2187 // key at index -2 and value at index -1
2188 int id = lua_tonumber(L, -2);
2189 int current_abm = lua_gettop(L);
2191 std::set<std::string> trigger_contents;
2192 lua_getfield(L, current_abm, "nodenames");
2193 if(lua_istable(L, -1)){
2194 int table = lua_gettop(L);
2196 while(lua_next(L, table) != 0){
2197 // key at index -2 and value at index -1
2198 luaL_checktype(L, -1, LUA_TSTRING);
2199 trigger_contents.insert(lua_tostring(L, -1));
2200 // removes value, keeps key for next iteration
2206 float trigger_interval = 10.0;
2207 getfloatfield(L, current_abm, "interval", trigger_interval);
2209 int trigger_chance = 50;
2210 getintfield(L, current_abm, "chance", trigger_chance);
2212 LuaABM *abm = new LuaABM(L, id, trigger_contents,
2213 trigger_interval, trigger_chance);
2215 env->addActiveBlockModifier(abm);
2217 // removes value, keeps key for next iteration
2225 // Dump stack top with the dump2 function
2226 static void dump2(lua_State *L, const char *name)
2228 // Dump object (debug)
2229 lua_getglobal(L, "dump2");
2230 luaL_checktype(L, -1, LUA_TFUNCTION);
2231 lua_pushvalue(L, -2); // Get previous stack top as first parameter
2232 lua_pushstring(L, name);
2233 if(lua_pcall(L, 2, 0, 0))
2234 script_error(L, "error: %s\n", lua_tostring(L, -1));
2242 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
2245 assert(lua_checkstack(L, 20));
2246 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
2247 StackUnroller stack_unroller(L);
2249 // Create object on stack
2250 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
2251 int object = lua_gettop(L);
2253 // Get minetest.object_refs table
2254 lua_getglobal(L, "minetest");
2255 lua_getfield(L, -1, "object_refs");
2256 luaL_checktype(L, -1, LUA_TTABLE);
2257 int objectstable = lua_gettop(L);
2259 // object_refs[id] = object
2260 lua_pushnumber(L, cobj->getId()); // Push id
2261 lua_pushvalue(L, object); // Copy object to top of stack
2262 lua_settable(L, objectstable);
2265 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
2268 assert(lua_checkstack(L, 20));
2269 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
2270 StackUnroller stack_unroller(L);
2272 // Get minetest.object_refs table
2273 lua_getglobal(L, "minetest");
2274 lua_getfield(L, -1, "object_refs");
2275 luaL_checktype(L, -1, LUA_TTABLE);
2276 int objectstable = lua_gettop(L);
2278 // Get object_refs[id]
2279 lua_pushnumber(L, cobj->getId()); // Push id
2280 lua_gettable(L, objectstable);
2281 // Set object reference to NULL
2282 ObjectRef::set_null(L);
2283 lua_pop(L, 1); // pop object
2285 // Set object_refs[id] = nil
2286 lua_pushnumber(L, cobj->getId()); // Push id
2288 lua_settable(L, objectstable);
2291 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
2292 const std::string &message)
2295 assert(lua_checkstack(L, 20));
2296 StackUnroller stack_unroller(L);
2298 // Get minetest.registered_on_chat_messages
2299 lua_getglobal(L, "minetest");
2300 lua_getfield(L, -1, "registered_on_chat_messages");
2301 luaL_checktype(L, -1, LUA_TTABLE);
2302 int table = lua_gettop(L);
2305 while(lua_next(L, table) != 0){
2306 // key at index -2 and value at index -1
2307 luaL_checktype(L, -1, LUA_TFUNCTION);
2309 lua_pushstring(L, name.c_str());
2310 lua_pushstring(L, message.c_str());
2311 if(lua_pcall(L, 2, 1, 0))
2312 script_error(L, "error: %s\n", lua_tostring(L, -1));
2313 bool ate = lua_toboolean(L, -1);
2317 // value removed, keep key for next iteration
2326 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
2329 assert(lua_checkstack(L, 20));
2330 StackUnroller stack_unroller(L);
2332 // Get minetest.registered_on_newplayers
2333 lua_getglobal(L, "minetest");
2334 lua_getfield(L, -1, "registered_on_newplayers");
2335 luaL_checktype(L, -1, LUA_TTABLE);
2336 int table = lua_gettop(L);
2339 while(lua_next(L, table) != 0){
2340 // key at index -2 and value at index -1
2341 luaL_checktype(L, -1, LUA_TFUNCTION);
2343 objectref_get_or_create(L, player);
2344 if(lua_pcall(L, 1, 0, 0))
2345 script_error(L, "error: %s\n", lua_tostring(L, -1));
2346 // value removed, keep key for next iteration
2349 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
2352 assert(lua_checkstack(L, 20));
2353 StackUnroller stack_unroller(L);
2355 bool positioning_handled_by_some = false;
2357 // Get minetest.registered_on_respawnplayers
2358 lua_getglobal(L, "minetest");
2359 lua_getfield(L, -1, "registered_on_respawnplayers");
2360 luaL_checktype(L, -1, LUA_TTABLE);
2361 int table = lua_gettop(L);
2364 while(lua_next(L, table) != 0){
2365 // key at index -2 and value at index -1
2366 luaL_checktype(L, -1, LUA_TFUNCTION);
2368 objectref_get_or_create(L, player);
2369 if(lua_pcall(L, 1, 1, 0))
2370 script_error(L, "error: %s\n", lua_tostring(L, -1));
2371 bool positioning_handled = lua_toboolean(L, -1);
2373 if(positioning_handled)
2374 positioning_handled_by_some = true;
2375 // value removed, keep key for next iteration
2377 return positioning_handled_by_some;
2384 static void pushPointedThing(lua_State *L, const PointedThing& pointed)
2387 if(pointed.type == POINTEDTHING_NODE)
2389 lua_pushstring(L, "node");
2390 lua_setfield(L, -2, "type");
2391 pushpos(L, pointed.node_undersurface);
2392 lua_setfield(L, -2, "under");
2393 pushpos(L, pointed.node_abovesurface);
2394 lua_setfield(L, -2, "above");
2396 else if(pointed.type == POINTEDTHING_OBJECT)
2398 lua_pushstring(L, "object");
2399 lua_setfield(L, -2, "type");
2400 objectref_get(L, pointed.object_id);
2401 lua_setfield(L, -2, "ref");
2405 lua_pushstring(L, "nothing");
2406 lua_setfield(L, -2, "type");
2410 void scriptapi_add_craftitem(lua_State *L, const char *name)
2412 StackUnroller stack_unroller(L);
2413 assert(lua_gettop(L) > 0);
2415 // Set minetest.registered_craftitems[name] = table on top of stack
2416 lua_getglobal(L, "minetest");
2417 lua_getfield(L, -1, "registered_craftitems");
2418 luaL_checktype(L, -1, LUA_TTABLE);
2419 lua_pushvalue(L, -3); // push another reference to the table to be registered
2420 lua_setfield(L, -2, name); // set minetest.registered_craftitems[name]
2423 static bool get_craftitem_callback(lua_State *L, const char *name,
2424 const char *callbackname)
2426 // Get minetest.registered_craftitems[name][callbackname]
2427 // If that is nil or on error, return false and stack is unchanged
2428 // If that is a function, returns true and pushes the
2429 // function onto the stack
2431 lua_getglobal(L, "minetest");
2432 lua_getfield(L, -1, "registered_craftitems");
2434 luaL_checktype(L, -1, LUA_TTABLE);
2435 lua_getfield(L, -1, name);
2437 // Should be a table
2438 if(lua_type(L, -1) != LUA_TTABLE)
2440 errorstream<<"CraftItem name \""<<name<<"\" not defined"<<std::endl;
2444 lua_getfield(L, -1, callbackname);
2446 // Should be a function or nil
2447 if(lua_type(L, -1) == LUA_TFUNCTION)
2451 else if(lua_isnil(L, -1))
2458 errorstream<<"CraftItem name \""<<name<<"\" callback \""
2459 <<callbackname<<" is not a function"<<std::endl;
2465 bool scriptapi_craftitem_on_drop(lua_State *L, const char *name,
2466 ServerActiveObject *dropper, v3f pos,
2467 bool &callback_exists)
2470 assert(lua_checkstack(L, 20));
2471 //infostream<<"scriptapi_craftitem_on_drop"<<std::endl;
2472 StackUnroller stack_unroller(L);
2474 bool result = false;
2475 callback_exists = get_craftitem_callback(L, name, "on_drop");
2479 lua_pushstring(L, name);
2480 objectref_get_or_create(L, dropper);
2481 pushFloatPos(L, pos);
2482 if(lua_pcall(L, 3, 1, 0))
2483 script_error(L, "error: %s\n", lua_tostring(L, -1));
2484 result = lua_toboolean(L, -1);
2489 bool scriptapi_craftitem_on_place_on_ground(lua_State *L, const char *name,
2490 ServerActiveObject *placer, v3f pos,
2491 bool &callback_exists)
2494 assert(lua_checkstack(L, 20));
2495 //infostream<<"scriptapi_craftitem_on_place_on_ground"<<std::endl;
2496 StackUnroller stack_unroller(L);
2498 bool result = false;
2499 callback_exists = get_craftitem_callback(L, name, "on_place_on_ground");
2503 lua_pushstring(L, name);
2504 objectref_get_or_create(L, placer);
2505 pushFloatPos(L, pos);
2506 if(lua_pcall(L, 3, 1, 0))
2507 script_error(L, "error: %s\n", lua_tostring(L, -1));
2508 result = lua_toboolean(L, -1);
2513 bool scriptapi_craftitem_on_use(lua_State *L, const char *name,
2514 ServerActiveObject *user, const PointedThing& pointed,
2515 bool &callback_exists)
2518 assert(lua_checkstack(L, 20));
2519 //infostream<<"scriptapi_craftitem_on_use"<<std::endl;
2520 StackUnroller stack_unroller(L);
2522 bool result = false;
2523 callback_exists = get_craftitem_callback(L, name, "on_use");
2527 lua_pushstring(L, name);
2528 objectref_get_or_create(L, user);
2529 pushPointedThing(L, pointed);
2530 if(lua_pcall(L, 3, 1, 0))
2531 script_error(L, "error: %s\n", lua_tostring(L, -1));
2532 result = lua_toboolean(L, -1);
2541 void scriptapi_environment_step(lua_State *L, float dtime)
2544 assert(lua_checkstack(L, 20));
2545 //infostream<<"scriptapi_environment_step"<<std::endl;
2546 StackUnroller stack_unroller(L);
2548 // Get minetest.registered_globalsteps
2549 lua_getglobal(L, "minetest");
2550 lua_getfield(L, -1, "registered_globalsteps");
2551 luaL_checktype(L, -1, LUA_TTABLE);
2552 int table = lua_gettop(L);
2555 while(lua_next(L, table) != 0){
2556 // key at index -2 and value at index -1
2557 luaL_checktype(L, -1, LUA_TFUNCTION);
2559 lua_pushnumber(L, dtime);
2560 if(lua_pcall(L, 1, 0, 0))
2561 script_error(L, "error: %s\n", lua_tostring(L, -1));
2562 // value removed, keep key for next iteration
2566 void scriptapi_environment_on_placenode(lua_State *L, v3s16 p, MapNode newnode,
2567 ServerActiveObject *placer)
2570 assert(lua_checkstack(L, 20));
2571 //infostream<<"scriptapi_environment_on_placenode"<<std::endl;
2572 StackUnroller stack_unroller(L);
2574 // Get server from registry
2575 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
2576 Server *server = (Server*)lua_touserdata(L, -1);
2577 // And get the writable node definition manager from the server
2578 IWritableNodeDefManager *ndef =
2579 server->getWritableNodeDefManager();
2581 // Get minetest.registered_on_placenodes
2582 lua_getglobal(L, "minetest");
2583 lua_getfield(L, -1, "registered_on_placenodes");
2584 luaL_checktype(L, -1, LUA_TTABLE);
2585 int table = lua_gettop(L);
2588 while(lua_next(L, table) != 0){
2589 // key at index -2 and value at index -1
2590 luaL_checktype(L, -1, LUA_TFUNCTION);
2593 pushnode(L, newnode, ndef);
2594 objectref_get_or_create(L, placer);
2595 if(lua_pcall(L, 3, 0, 0))
2596 script_error(L, "error: %s\n", lua_tostring(L, -1));
2597 // value removed, keep key for next iteration
2601 void scriptapi_environment_on_dignode(lua_State *L, v3s16 p, MapNode oldnode,
2602 ServerActiveObject *digger)
2605 assert(lua_checkstack(L, 20));
2606 //infostream<<"scriptapi_environment_on_dignode"<<std::endl;
2607 StackUnroller stack_unroller(L);
2609 // Get server from registry
2610 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
2611 Server *server = (Server*)lua_touserdata(L, -1);
2612 // And get the writable node definition manager from the server
2613 IWritableNodeDefManager *ndef =
2614 server->getWritableNodeDefManager();
2616 // Get minetest.registered_on_dignodes
2617 lua_getglobal(L, "minetest");
2618 lua_getfield(L, -1, "registered_on_dignodes");
2619 luaL_checktype(L, -1, LUA_TTABLE);
2620 int table = lua_gettop(L);
2623 while(lua_next(L, table) != 0){
2624 // key at index -2 and value at index -1
2625 luaL_checktype(L, -1, LUA_TFUNCTION);
2628 pushnode(L, oldnode, ndef);
2629 objectref_get_or_create(L, digger);
2630 if(lua_pcall(L, 3, 0, 0))
2631 script_error(L, "error: %s\n", lua_tostring(L, -1));
2632 // value removed, keep key for next iteration
2636 void scriptapi_environment_on_punchnode(lua_State *L, v3s16 p, MapNode node,
2637 ServerActiveObject *puncher)
2640 assert(lua_checkstack(L, 20));
2641 //infostream<<"scriptapi_environment_on_punchnode"<<std::endl;
2642 StackUnroller stack_unroller(L);
2644 // Get server from registry
2645 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
2646 Server *server = (Server*)lua_touserdata(L, -1);
2647 // And get the writable node definition manager from the server
2648 IWritableNodeDefManager *ndef =
2649 server->getWritableNodeDefManager();
2651 // Get minetest.registered_on_punchnodes
2652 lua_getglobal(L, "minetest");
2653 lua_getfield(L, -1, "registered_on_punchnodes");
2654 luaL_checktype(L, -1, LUA_TTABLE);
2655 int table = lua_gettop(L);
2658 while(lua_next(L, table) != 0){
2659 // key at index -2 and value at index -1
2660 luaL_checktype(L, -1, LUA_TFUNCTION);
2663 pushnode(L, node, ndef);
2664 objectref_get_or_create(L, puncher);
2665 if(lua_pcall(L, 3, 0, 0))
2666 script_error(L, "error: %s\n", lua_tostring(L, -1));
2667 // value removed, keep key for next iteration
2671 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
2674 assert(lua_checkstack(L, 20));
2675 //infostream<<"scriptapi_environment_on_generated"<<std::endl;
2676 StackUnroller stack_unroller(L);
2678 // Get minetest.registered_on_generateds
2679 lua_getglobal(L, "minetest");
2680 lua_getfield(L, -1, "registered_on_generateds");
2681 luaL_checktype(L, -1, LUA_TTABLE);
2682 int table = lua_gettop(L);
2685 while(lua_next(L, table) != 0){
2686 // key at index -2 and value at index -1
2687 luaL_checktype(L, -1, LUA_TFUNCTION);
2691 if(lua_pcall(L, 2, 0, 0))
2692 script_error(L, "error: %s\n", lua_tostring(L, -1));
2693 // value removed, keep key for next iteration
2701 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name,
2702 const std::string &staticdata)
2705 assert(lua_checkstack(L, 20));
2706 infostream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
2707 <<name<<"\""<<std::endl;
2708 StackUnroller stack_unroller(L);
2710 // Get minetest.registered_entities[name]
2711 lua_getglobal(L, "minetest");
2712 lua_getfield(L, -1, "registered_entities");
2713 luaL_checktype(L, -1, LUA_TTABLE);
2714 lua_pushstring(L, name);
2715 lua_gettable(L, -2);
2716 // Should be a table, which we will use as a prototype
2717 //luaL_checktype(L, -1, LUA_TTABLE);
2718 if(lua_type(L, -1) != LUA_TTABLE){
2719 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
2722 int prototype_table = lua_gettop(L);
2723 //dump2(L, "prototype_table");
2725 // Create entity object
2727 int object = lua_gettop(L);
2729 // Set object metatable
2730 lua_pushvalue(L, prototype_table);
2731 lua_setmetatable(L, -2);
2733 // Add object reference
2734 // This should be userdata with metatable ObjectRef
2735 objectref_get(L, id);
2736 luaL_checktype(L, -1, LUA_TUSERDATA);
2737 if(!luaL_checkudata(L, -1, "ObjectRef"))
2738 luaL_typerror(L, -1, "ObjectRef");
2739 lua_setfield(L, -2, "object");
2741 // minetest.luaentities[id] = object
2742 lua_getglobal(L, "minetest");
2743 lua_getfield(L, -1, "luaentities");
2744 luaL_checktype(L, -1, LUA_TTABLE);
2745 lua_pushnumber(L, id); // Push id
2746 lua_pushvalue(L, object); // Copy object to top of stack
2747 lua_settable(L, -3);
2749 // Get on_activate function
2750 lua_pushvalue(L, object);
2751 lua_getfield(L, -1, "on_activate");
2752 if(!lua_isnil(L, -1)){
2753 luaL_checktype(L, -1, LUA_TFUNCTION);
2754 lua_pushvalue(L, object); // self
2755 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
2756 // Call with 2 arguments, 0 results
2757 if(lua_pcall(L, 2, 0, 0))
2758 script_error(L, "error running function %s:on_activate: %s\n",
2759 name, lua_tostring(L, -1));
2765 void scriptapi_luaentity_rm(lua_State *L, u16 id)
2768 assert(lua_checkstack(L, 20));
2769 infostream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
2771 // Get minetest.luaentities table
2772 lua_getglobal(L, "minetest");
2773 lua_getfield(L, -1, "luaentities");
2774 luaL_checktype(L, -1, LUA_TTABLE);
2775 int objectstable = lua_gettop(L);
2777 // Set luaentities[id] = nil
2778 lua_pushnumber(L, id); // Push id
2780 lua_settable(L, objectstable);
2782 lua_pop(L, 2); // pop luaentities, minetest
2785 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
2788 assert(lua_checkstack(L, 20));
2789 infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
2790 StackUnroller stack_unroller(L);
2792 // Get minetest.luaentities[id]
2793 luaentity_get(L, id);
2794 int object = lua_gettop(L);
2796 // Get get_staticdata function
2797 lua_pushvalue(L, object);
2798 lua_getfield(L, -1, "get_staticdata");
2799 if(lua_isnil(L, -1))
2802 luaL_checktype(L, -1, LUA_TFUNCTION);
2803 lua_pushvalue(L, object); // self
2804 // Call with 1 arguments, 1 results
2805 if(lua_pcall(L, 1, 1, 0))
2806 script_error(L, "error running function get_staticdata: %s\n",
2807 lua_tostring(L, -1));
2810 const char *s = lua_tolstring(L, -1, &len);
2811 return std::string(s, len);
2814 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
2815 LuaEntityProperties *prop)
2818 assert(lua_checkstack(L, 20));
2819 infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
2820 StackUnroller stack_unroller(L);
2822 // Get minetest.luaentities[id]
2823 luaentity_get(L, id);
2824 //int object = lua_gettop(L);
2828 getboolfield(L, -1, "physical", prop->physical);
2830 getfloatfield(L, -1, "weight", prop->weight);
2832 lua_getfield(L, -1, "collisionbox");
2833 if(lua_istable(L, -1))
2834 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
2837 getstringfield(L, -1, "visual", prop->visual);
2839 lua_getfield(L, -1, "visual_size");
2840 if(lua_istable(L, -1))
2841 prop->visual_size = read_v2f(L, -1);
2844 lua_getfield(L, -1, "textures");
2845 if(lua_istable(L, -1)){
2846 prop->textures.clear();
2847 int table = lua_gettop(L);
2849 while(lua_next(L, table) != 0){
2850 // key at index -2 and value at index -1
2851 if(lua_isstring(L, -1))
2852 prop->textures.push_back(lua_tostring(L, -1));
2854 prop->textures.push_back("");
2855 // removes value, keeps key for next iteration
2861 lua_getfield(L, -1, "spritediv");
2862 if(lua_istable(L, -1))
2863 prop->spritediv = read_v2s16(L, -1);
2866 lua_getfield(L, -1, "initial_sprite_basepos");
2867 if(lua_istable(L, -1))
2868 prop->initial_sprite_basepos = read_v2s16(L, -1);
2872 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
2875 assert(lua_checkstack(L, 20));
2876 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
2877 StackUnroller stack_unroller(L);
2879 // Get minetest.luaentities[id]
2880 luaentity_get(L, id);
2881 int object = lua_gettop(L);
2882 // State: object is at top of stack
2883 // Get step function
2884 lua_getfield(L, -1, "on_step");
2885 if(lua_isnil(L, -1))
2887 luaL_checktype(L, -1, LUA_TFUNCTION);
2888 lua_pushvalue(L, object); // self
2889 lua_pushnumber(L, dtime); // dtime
2890 // Call with 2 arguments, 0 results
2891 if(lua_pcall(L, 2, 0, 0))
2892 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
2895 // Calls entity:on_punch(ObjectRef puncher)
2896 void scriptapi_luaentity_punch(lua_State *L, u16 id,
2897 ServerActiveObject *puncher)
2900 assert(lua_checkstack(L, 20));
2901 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
2902 StackUnroller stack_unroller(L);
2904 // Get minetest.luaentities[id]
2905 luaentity_get(L, id);
2906 int object = lua_gettop(L);
2907 // State: object is at top of stack
2909 lua_getfield(L, -1, "on_punch");
2910 if(lua_isnil(L, -1))
2912 luaL_checktype(L, -1, LUA_TFUNCTION);
2913 lua_pushvalue(L, object); // self
2914 objectref_get_or_create(L, puncher); // Clicker reference
2915 // Call with 2 arguments, 0 results
2916 if(lua_pcall(L, 2, 0, 0))
2917 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
2920 // Calls entity:on_rightclick(ObjectRef clicker)
2921 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
2922 ServerActiveObject *clicker)
2925 assert(lua_checkstack(L, 20));
2926 //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
2927 StackUnroller stack_unroller(L);
2929 // Get minetest.luaentities[id]
2930 luaentity_get(L, id);
2931 int object = lua_gettop(L);
2932 // State: object is at top of stack
2934 lua_getfield(L, -1, "on_rightclick");
2935 if(lua_isnil(L, -1))
2937 luaL_checktype(L, -1, LUA_TFUNCTION);
2938 lua_pushvalue(L, object); // self
2939 objectref_get_or_create(L, clicker); // Clicker reference
2940 // Call with 2 arguments, 0 results
2941 if(lua_pcall(L, 2, 0, 0))
2942 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));