'minetest' namespace reference

Utilities

  • minetest.get_current_modname(): returns the currently loading mod's name, when loading a mod.
  • minetest.get_modpath(modname): returns e.g. "/home/user/.minetest/usermods/modname".
    • Useful for loading additional .lua modules or static data from mod
  • minetest.get_modnames(): returns a list of installed mods
    • Return a list of installed mods, sorted alphabetically
  • minetest.get_worldpath(): returns e.g. "/home/user/.minetest/world"
    • Useful for storing custom data
  • minetest.is_singleplayer()
  • minetest.features: Table containing API feature flags

    { glasslike_framed = true, -- 0.4.7 nodebox_as_selectionbox = true, -- 0.4.7 get_all_craft_recipes_works = true, -- 0.4.7 -- The transparency channel of textures can optionally be used on -- nodes (0.4.7) use_texture_alpha = true, -- Tree and grass ABMs are no longer done from C++ (0.4.8) no_legacy_abms = true, -- Texture grouping is possible using parentheses (0.4.11) texture_names_parens = true, -- Unique Area ID for AreaStore:insert_area (0.4.14) area_store_custom_ids = true, -- add_entity supports passing initial staticdata to on_activate -- (0.4.16) add_entity_with_staticdata = true, -- Chat messages are no longer predicted (0.4.16) no_chat_message_prediction = true, -- The transparency channel of textures can optionally be used on -- objects (ie: players and lua entities) (5.0.0) object_use_texture_alpha = true, -- Object selectionbox is settable independently from collisionbox -- (5.0.0) object_independent_selectionbox = true, -- Specifies whether binary data can be uploaded or downloaded using -- the HTTP API (5.1.0) httpfetch_binary_data = true, -- Whether formspec_version[] may be used (5.1.0) formspec_version_element = true, -- Whether AreaStore's IDs are kept on save/load (5.1.0) area_store_persistent_ids = true, }

  • minetest.has_feature(arg): returns boolean, missing_features

    • arg: string or table in format {foo=true, bar=true}
    • missing_features: {foo=true, bar=true}
  • minetest.get_player_information(player_name): Table containing information about a player. Example return value:

    { address = "127.0.0.1", -- IP address of client ip_version = 4, -- IPv4 / IPv6 min_rtt = 0.01, -- minimum round trip time max_rtt = 0.2, -- maximum round trip time avg_rtt = 0.02, -- average round trip time min_jitter = 0.01, -- minimum packet time jitter max_jitter = 0.5, -- maximum packet time jitter avg_jitter = 0.03, -- average packet time jitter connection_uptime = 200, -- seconds since client connected protocol_version = 32, -- protocol version used by client formspec_version = 2, -- supported formspec version -- following information is available on debug build only!!! -- DO NOT USE IN MODS --ser_vers = 26, -- serialization version used by client --major = 0, -- major version number --minor = 4, -- minor version number --patch = 10, -- patch version number --vers_string = "0.4.9-git", -- full version string --state = "Active" -- current client state }

  • minetest.mkdir(path): returns success.

    • Creates a directory specified by path, creating parent directories if they don't exist.
  • minetest.get_dir_list(path, [is_dir]): returns list of entry names
    • is_dir is one of:
      • nil: return all entries,
      • true: return only subdirectory names, or
      • false: return only file names.
  • minetest.safe_file_write(path, content): returns boolean indicating success
    • Replaces contents of file at path with new contents in a safe (atomic) way. Use this instead of below code when writing e.g. database files: local f = io.open(path, "wb"); f:write(content); f:close()
  • minetest.get_version(): returns a table containing components of the engine version. Components:
    • project: Name of the project, eg, "Minetest"
    • string: Simple version, eg, "1.2.3-dev"
    • hash: Full git version (only set if available), eg, "1.2.3-dev-01234567-dirty". Use this for informational purposes only. The information in the returned table does not represent the capabilities of the engine, nor is it reliable or verifiable. Compatible forks will have a different name and version entirely. To check for the presence of engine features, test whether the functions exported by the wanted features exist. For example: if minetest.check_for_falling then ... end.
  • minetest.sha1(data, [raw]): returns the sha1 hash of data
    • data: string of data to hash
    • raw: return raw bytes instead of hex digits, default: false

Logging

  • minetest.debug(...)
    • Equivalent to minetest.log(table.concat({...}, "\t"))
  • minetest.log([level,] text)
    • level is one of "none", "error", "warning", "action", "info", or "verbose". Default is "none".

Registration functions

Call these functions only at load time!

Environment

  • minetest.register_node(name, node definition)
  • minetest.register_craftitem(name, item definition)
  • minetest.register_tool(name, item definition)
  • minetest.override_item(name, redefinition)
    • Overrides fields of an item registered with register_node/tool/craftitem.
    • Note: Item must already be defined, (opt)depend on the mod defining it.
    • Example: minetest.override_item("default:mese", {light_source=minetest.LIGHT_MAX})
  • minetest.unregister_item(name)
    • Unregisters the item from the engine, and deletes the entry with key name from minetest.registered_items and from the associated item table according to its nature: minetest.registered_nodes, etc.
  • minetest.register_entity(name, entity definition)
  • minetest.register_abm(abm definition)
  • minetest.register_lbm(lbm definition)
  • minetest.register_alias(alias, original_name)
    • Also use this to set the 'mapgen aliases' needed in a game for the core mapgens. See [Mapgen aliases] section above.
  • minetest.register_alias_force(alias, original_name)
  • minetest.register_ore(ore definition)
    • Returns an integer object handle uniquely identifying the registered ore on success.
    • The order of ore registrations determines the order of ore generation.
  • minetest.register_biome(biome definition)
    • Returns an integer object handle uniquely identifying the registered biome on success. To get the biome ID, use minetest.get_biome_id.
  • minetest.unregister_biome(name)
    • Unregisters the biome from the engine, and deletes the entry with key name from minetest.registered_biomes.
  • minetest.register_decoration(decoration definition)
    • Returns an integer object handle uniquely identifying the registered decoration on success. To get the decoration ID, use minetest.get_decoration_id.
    • The order of decoration registrations determines the order of decoration generation.
  • minetest.register_schematic(schematic definition)
    • Returns an integer object handle uniquely identifying the registered schematic on success.
    • If the schematic is loaded from a file, the name field is set to the filename.
    • If the function is called when loading the mod, and name is a relative path, then the current mod path will be prepended to the schematic filename.
  • minetest.clear_registered_ores()
    • Clears all ores currently registered.
  • minetest.clear_registered_biomes()
    • Clears all biomes currently registered.
  • minetest.clear_registered_decorations()
    • Clears all decorations currently registered.
  • minetest.clear_registered_schematics()
    • Clears all schematics currently registered.

Gameplay

  • minetest.register_craft(recipe)
    • Check recipe table syntax for different types below.
  • minetest.clear_craft(recipe)
    • Will erase existing craft based either on output item or on input recipe.
    • Specify either output or input only. If you specify both, input will be ignored. For input use the same recipe table syntax as for minetest.register_craft(recipe). For output specify only the item, without a quantity.
    • Returns false if no erase candidate could be found, otherwise returns true.
    • Warning! The type field ("shaped", "cooking" or any other) will be ignored if the recipe contains output. Erasing is then done independently from the crafting method.
  • minetest.register_chatcommand(cmd, chatcommand definition)
  • minetest.override_chatcommand(name, redefinition)
    • Overrides fields of a chatcommand registered with register_chatcommand.
  • minetest.unregister_chatcommand(name)
    • Unregisters a chatcommands registered with register_chatcommand.
  • minetest.register_privilege(name, definition)
    • definition can be a description or a definition table (see [Privilege definition]).
    • If it is a description, the priv will be granted to singleplayer and admin by default.
    • To allow players with basic_privs to grant, see the basic_privs minetest.conf setting.
  • minetest.register_authentication_handler(authentication handler definition)
    • Registers an auth handler that overrides the builtin one.
    • This function can be called by a single mod once only.

Global callback registration functions

Call these functions only at load time!

  • minetest.register_globalstep(function(dtime))
    • Called every server step, usually interval of 0.1s
  • minetest.register_on_mods_loaded(function())
    • Called after mods have finished loading and before the media is cached or the aliases handled.
  • minetest.register_on_shutdown(function())
    • Called before server shutdown
    • Warning: If the server terminates abnormally (i.e. crashes), the registered callbacks will likely not be run. Data should be saved at semi-frequent intervals as well as on server shutdown.
  • minetest.register_on_placenode(function(pos, newnode, placer, oldnode, itemstack, pointed_thing))
    • Called when a node has been placed
    • If return true no item is taken from itemstack
    • placer may be any valid ObjectRef or nil.
    • Not recommended; use on_construct or after_place_node in node definition whenever possible.
  • minetest.register_on_dignode(function(pos, oldnode, digger))
    • Called when a node has been dug.
    • Not recommended; Use on_destruct or after_dig_node in node definition whenever possible.
  • minetest.register_on_punchnode(function(pos, node, puncher, pointed_thing))
    • Called when a node is punched
  • minetest.register_on_generated(function(minp, maxp, blockseed))
    • Called after generating a piece of world. Modifying nodes inside the area is a bit faster than usually.
  • minetest.register_on_newplayer(function(ObjectRef))
    • Called after a new player has been created
  • minetest.register_on_punchplayer(function(player, hitter, time_from_last_punch, tool_capabilities, dir, damage))
    • Called when a player is punched
    • Note: This callback is invoked even if the punched player is dead.
    • player: ObjectRef - Player that was punched
    • hitter: ObjectRef - Player that hit
    • time_from_last_punch: Meant for disallowing spamming of clicks (can be nil).
    • tool_capabilities: Capability table of used tool (can be nil)
    • dir: Unit vector of direction of punch. Always defined. Points from the puncher to the punched.
    • damage: Number that represents the damage calculated by the engine
    • should return true to prevent the default damage mechanism
  • minetest.register_on_player_hpchange(function(player, hp_change, reason), modifier)
    • Called when the player gets damaged or healed
    • player: ObjectRef of the player
    • hp_change: the amount of change. Negative when it is damage.
    • reason: a PlayerHPChangeReason table.
      • The type field will have one of the following values:
        • set_hp: A mod or the engine called set_hp without giving a type - use this for custom damage types.
        • punch: Was punched. reason.object will hold the puncher, or nil if none.
        • fall
        • node_damage: damage_per_second from a neighbouring node. reason.node will hold the node name or nil.
        • drown
        • respawn
      • Any of the above types may have additional fields from mods.
      • reason.from will be mod or engine.
    • modifier: when true, the function should return the actual hp_change. Note: modifiers only get a temporary hp_change that can be modified by later modifiers. Modifiers can return true as a second argument to stop the execution of further functions. Non-modifiers receive the final HP change calculated by the modifiers.
  • minetest.register_on_dieplayer(function(ObjectRef, reason))
    • Called when a player dies
    • reason: a PlayerHPChangeReason table, see register_on_player_hpchange
  • minetest.register_on_respawnplayer(function(ObjectRef))
    • Called when player is to be respawned
    • Called before repositioning of player occurs
    • return true in func to disable regular player placement
  • minetest.register_on_prejoinplayer(function(name, ip))
    • Called before a player joins the game
    • If it returns a string, the player is disconnected with that string as reason.
  • minetest.register_on_joinplayer(function(ObjectRef))
    • Called when a player joins the game
  • minetest.register_on_leaveplayer(function(ObjectRef, timed_out))
    • Called when a player leaves the game
    • timed_out: True for timeout, false for other reasons.
  • minetest.register_on_auth_fail(function(name, ip))
    • Called when a client attempts to log into an account but supplies the wrong password.
    • ip: The IP address of the client.
    • name: The account the client attempted to log into.
  • minetest.register_on_cheat(function(ObjectRef, cheat))
    • Called when a player cheats
    • cheat: {type=<cheat_type>}, where <cheat_type> is one of:
      • moved_too_fast
      • interacted_too_far
      • interacted_while_dead
      • finished_unknown_dig
      • dug_unbreakable
      • dug_too_fast
  • minetest.register_on_chat_message(function(name, message))
    • Called always when a player says something
    • Return true to mark the message as handled, which means that it will not be sent to other players.
  • minetest.register_on_player_receive_fields(function(player, formname, fields))
    • Called when the server received input from player in a formspec with the given formname. Specifically, this is called on any of the following events:
      • a button was pressed,
      • Enter was pressed while the focus was on a text field
      • a checkbox was toggled,
      • something was selecteed in a drop-down list,
      • a different tab was selected,
      • selection was changed in a textlist or table,
      • an entry was double-clicked in a textlist or table,
      • a scrollbar was moved, or
      • the form was actively closed by the player.
    • Fields are sent for formspec elements which define a field. fields is a table containing each formspecs element value (as string), with the name parameter as index for each. The value depends on the formspec element type:
      • button and variants: If pressed, contains the user-facing button text as value. If not pressed, is nil
      • field, textarea and variants: Text in the field
      • dropdown: Text of selected item
      • tabheader: Tab index, starting with "1" (only if tab changed)
      • checkbox: "true" if checked, "false" if unchecked
      • textlist: See minetest.explode_textlist_event
      • table: See minetest.explode_table_event
      • scrollbar: See minetest.explode_scrollbar_event
      • Special case: ["quit"]="true" is sent when the user actively closed the form by mouse click, keypress or through a button_exit[] element.
      • Special case: ["key_enter"]="true" is sent when the user pressed the Enter key and the focus was either nowhere (causing the formspec to be closed) or on a button. If the focus was on a text field, additionally, the index key_enter_field contains the name of the text field. See also: field_close_on_enter.
    • Newest functions are called first
    • If function returns true, remaining functions are not called
  • minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv))
    • Called when player crafts something
    • itemstack is the output
    • old_craft_grid contains the recipe (Note: the one in the inventory is cleared).
    • craft_inv is the inventory with the crafting grid
    • Return either an ItemStack, to replace the output, or nil, to not modify it.
  • minetest.register_craft_predict(function(itemstack, player, old_craft_grid, craft_inv))
    • The same as before, except that it is called before the player crafts, to make craft prediction, and it should not change anything.
  • minetest.register_allow_player_inventory_action(function(player, action, inventory, inventory_info))
    • Determinates how much of a stack may be taken, put or moved to a player inventory.
    • player (type ObjectRef) is the player who modified the inventory inventory (type InvRef).
    • List of possible action (string) values and their inventory_info (table) contents:
      • move: {from_list=string, to_list=string, from_index=number, to_index=number, count=number}
      • put: {listname=string, index=number, stack=ItemStack}
      • take: Same as put
    • Return a numeric value to limit the amount of items to be taken, put or moved. A value of -1 for take will make the source stack infinite.
  • minetest.register_on_player_inventory_action(function(player, action, inventory, inventory_info))
    • Called after a take, put or move event from/to/in a player inventory
    • Function arguments: see minetest.register_allow_player_inventory_action
    • Does not accept or handle any return value.
  • minetest.register_on_protection_violation(function(pos, name))
    • Called by builtin and mods when a player violates protection at a position (eg, digs a node or punches a protected entity).
    • The registered functions can be called using minetest.record_protection_violation.
    • The provided function should check that the position is protected by the mod calling this function before it prints a message, if it does, to allow for multiple protection mods.
  • minetest.register_on_item_eat(function(hp_change, replace_with_item, itemstack, user, pointed_thing))
    • Called when an item is eaten, by minetest.item_eat
    • Return itemstack to cancel the default item eat response (i.e.: hp increase).
  • minetest.register_on_priv_grant(function(name, granter, priv))
    • Called when granter grants the priv priv to name.
    • Note that the callback will be called twice if it's done by a player, once with granter being the player name, and again with granter being nil.
  • minetest.register_on_priv_revoke(function(name, revoker, priv))
    • Called when revoker revokes the priv priv from name.
    • Note that the callback will be called twice if it's done by a player, once with revoker being the player name, and again with revoker being nil.
  • minetest.register_can_bypass_userlimit(function(name, ip))
    • Called when name user connects with ip.
    • Return true to by pass the player limit
  • minetest.register_on_modchannel_message(function(channel_name, sender, message))
    • Called when an incoming mod channel message is received
    • You should have joined some channels to receive events.
    • If message comes from a server mod, sender field is an empty string.
  • minetest.settings: Settings object containing all of the settings from the main config file (minetest.conf).
  • minetest.setting_get_pos(name): Loads a setting from the main settings and parses it as a position (in the format (1,2,3)). Returns a position or nil.

Authentication

  • minetest.string_to_privs(str): returns {priv1=true,...}
  • minetest.privs_to_string(privs): returns "priv1,priv2,..."
    • Convert between two privilege representations
  • minetest.get_player_privs(name) -> {priv1=true,...}
  • minetest.check_player_privs(player_or_name, ...): returns bool, missing_privs

    • A quickhand for checking privileges.
    • player_or_name: Either a Player object or the name of a player.
    • ... is either a list of strings, e.g. "priva", "privb" or a table, e.g. { priva = true, privb = true }.
  • minetest.check_password_entry(name, entry, password)

    • Returns true if the "password entry" for a player with name matches given password, false otherwise.
    • The "password entry" is the password representation generated by the engine as returned as part of a get_auth() call on the auth handler.
    • Only use this function for making it possible to log in via password from external protocols such as IRC, other uses are frowned upon.
  • minetest.get_password_hash(name, raw_password)
    • Convert a name-password pair to a password hash that Minetest can use.
    • The returned value alone is not a good basis for password checks based on comparing the password hash in the database with the password hash from the function, with an externally provided password, as the hash in the db might use the new SRP verifier format.
    • For this purpose, use minetest.check_password_entry instead.
  • minetest.get_player_ip(name): returns an IP address string for the player name.

    • The player needs to be online for this to be successful.
  • minetest.get_auth_handler(): Return the currently active auth handler

    • See the [Authentication handler definition]
    • Use this to e.g. get the authentication data for a player: local auth_data = minetest.get_auth_handler().get_auth(playername)
  • minetest.notify_authentication_modified(name)
    • Must be called by the authentication handler for privilege changes.
    • name: string; if omitted, all auth data should be considered modified
  • minetest.set_player_password(name, password_hash): Set password hash of player name.
  • minetest.set_player_privs(name, {priv1=true,...}): Set privileges of player name.
  • minetest.auth_reload()
    • See reload() in authentication handler definition

minetest.set_player_password, minetest_set_player_privs, minetest_get_player_privs and minetest.auth_reload call the authentication handler.

Chat

  • minetest.chat_send_all(text)
  • minetest.chat_send_player(name, text)
  • minetest.format_chat_message(name, message)
    • Used by the server to format a chat message, based on the setting chat_message_format. Refer to the documentation of the setting for a list of valid placeholders.
    • Takes player name and message, and returns the formatted string to be sent to players.
    • Can be redefined by mods if required, for things like colored names or messages.
    • Only the first occurrence of each placeholder will be replaced.

Environment access

  • minetest.set_node(pos, node)
  • minetest.add_node(pos, node): alias to minetest.set_node
    • Set node at position pos
    • node: table {name=string, param1=number, param2=number}
    • If param1 or param2 is omitted, it's set to 0.
    • e.g. minetest.set_node({x=0, y=10, z=0}, {name="default:wood"})
  • minetest.bulk_set_node({pos1, pos2, pos3, ...}, node)
    • Set node on all positions set in the first argument.
    • e.g. minetest.bulk_set_node({{x=0, y=1, z=1}, {x=1, y=2, z=2}}, {name="default:stone"})
    • For node specification or position syntax see minetest.set_node call
    • Faster than set_node due to single call, but still considerably slower than Lua Voxel Manipulators (LVM) for large numbers of nodes. Unlike LVMs, this will call node callbacks. It also allows setting nodes in spread out positions which would cause LVMs to waste memory. For setting a cube, this is 1.3x faster than set_node whereas LVM is 20 times faster.
  • minetest.swap_node(pos, node)
    • Set node at position, but don't remove metadata
  • minetest.remove_node(pos)
    • By default it does the same as minetest.set_node(pos, {name="air"})
  • minetest.get_node(pos)
    • Returns the node at the given position as table in the format {name="node_name", param1=0, param2=0}, returns {name="ignore", param1=0, param2=0} for unloaded areas.
  • minetest.get_node_or_nil(pos)
    • Same as get_node but returns nil for unloaded areas.
  • minetest.get_node_light(pos, timeofday)
    • Gets the light value at the given position. Note that the light value "inside" the node at the given position is returned, so you usually want to get the light value of a neighbor.
    • pos: The position where to measure the light.
    • timeofday: nil for current time, 0 for night, 0.5 for day
    • Returns a number between 0 and 15 or nil
  • minetest.place_node(pos, node)
    • Place node with the same effects that a player would cause
  • minetest.dig_node(pos)
    • Dig node with the same effects that a player would cause
    • Returns true if successful, false on failure (e.g. protected location)
  • minetest.punch_node(pos)
    • Punch node with the same effects that a player would cause
  • minetest.spawn_falling_node(pos)

    • Change node into falling node
    • Returns true if successful, false on failure
  • minetest.find_nodes_with_meta(pos1, pos2)

    • Get a table of positions of nodes that have metadata within a region {pos1, pos2}.
  • minetest.get_meta(pos)
    • Get a NodeMetaRef at that position
  • minetest.get_node_timer(pos)

    • Get NodeTimerRef
  • minetest.add_entity(pos, name, [staticdata]): Spawn Lua-defined entity at position.

    • Returns ObjectRef, or nil if failed
  • minetest.add_item(pos, item): Spawn item
    • Returns ObjectRef, or nil if failed
  • minetest.get_player_by_name(name): Get an ObjectRef to a player
  • minetest.get_objects_inside_radius(pos, radius): returns a list of ObjectRefs.
    • radius: using an euclidean metric
  • minetest.set_timeofday(val)
    • val is between 0 and 1; 0 for midnight, 0.5 for midday
  • minetest.get_timeofday()
  • minetest.get_gametime(): returns the time, in seconds, since the world was created.
  • minetest.get_day_count(): returns number days elapsed since world was created.
    • accounts for time changes.
  • minetest.find_node_near(pos, radius, nodenames, [search_center]): returns pos or nil.
    • radius: using a maximum metric
    • nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
    • search_center is an optional boolean (default: false) If true pos is also checked for the nodes
  • minetest.find_nodes_in_area(pos1, pos2, nodenames): returns a list of positions.
    • nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
    • First return value: Table with all node positions
    • Second return value: Table with the count of each node with the node name as index.
    • Area volume is limited to 4,096,000 nodes
  • minetest.find_nodes_in_area_under_air(pos1, pos2, nodenames): returns a list of positions.
    • nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
    • Return value: Table with all node positions with a node air above
    • Area volume is limited to 4,096,000 nodes
  • minetest.get_perlin(noiseparams)
  • minetest.get_perlin(seeddiff, octaves, persistence, spread)
    • Return world-specific perlin noise (int(worldseed)+seeddiff)
  • minetest.get_voxel_manip([pos1, pos2])
    • Return voxel manipulator object.
    • Loads the manipulator from the map if positions are passed.
  • minetest.set_gen_notify(flags, {deco_ids})
    • Set the types of on-generate notifications that should be collected.
    • flags is a flag field with the available flags:
      • dungeon
      • temple
      • cave_begin
      • cave_end
      • large_cave_begin
      • large_cave_end
      • decoration
    • The second parameter is a list of IDs of decorations which notification is requested for.
  • minetest.get_gen_notify()
    • Returns a flagstring and a table with the deco_ids.
  • minetest.get_decoration_id(decoration_name)
    • Returns the decoration ID number for the provided decoration name string, or nil on failure.
  • minetest.get_mapgen_object(objectname)
    • Return requested mapgen object if available (see [Mapgen objects])
  • minetest.get_heat(pos)
    • Returns the heat at the position, or nil on failure.
  • minetest.get_humidity(pos)
    • Returns the humidity at the position, or nil on failure.
  • minetest.get_biome_data(pos)
    • Returns a table containing:
      • biome the biome id of the biome at that position
      • heat the heat at the position
      • humidity the humidity at the position
    • Or returns nil on failure.
  • minetest.get_biome_id(biome_name)
    • Returns the biome id, as used in the biomemap Mapgen object and returned by minetest.get_biome_data(pos), for a given biome_name string.
  • minetest.get_biome_name(biome_id)
    • Returns the biome name string for the provided biome id, or nil on failure.
    • If no biomes have been registered, such as in mgv6, returns default.
  • minetest.get_mapgen_params()
    • Deprecated: use minetest.get_mapgen_setting(name) instead.
    • Returns a table containing:
      • mgname
      • seed
      • chunksize
      • water_level
      • flags
  • minetest.set_mapgen_params(MapgenParams)
    • Deprecated: use minetest.set_mapgen_setting(name, value, override) instead.
    • Set map generation parameters.
    • Function cannot be called after the registration period; only initialization and on_mapgen_init.
    • Takes a table as an argument with the fields:
      • mgname
      • seed
      • chunksize
      • water_level
      • flags
    • Leave field unset to leave that parameter unchanged.
    • flags contains a comma-delimited string of flags to set, or if the prefix "no" is attached, clears instead.
    • flags is in the same format and has the same options as mg_flags in minetest.conf.
  • minetest.get_mapgen_setting(name)
    • Gets the active mapgen setting (or nil if none exists) in string format with the following order of precedence: 1) Settings loaded from map_meta.txt or overrides set during mod execution. 2) Settings set by mods without a metafile override 3) Settings explicitly set in the user config file, minetest.conf 4) Settings set as the user config default
  • minetest.get_mapgen_setting_noiseparams(name)
    • Same as above, but returns the value as a NoiseParams table if the setting name exists and is a valid NoiseParams.
  • minetest.set_mapgen_setting(name, value, [override_meta])
    • Sets a mapgen param to value, and will take effect if the corresponding mapgen setting is not already present in map_meta.txt.
    • override_meta is an optional boolean (default: false). If this is set to true, the setting will become the active setting regardless of the map metafile contents.
    • Note: to set the seed, use "seed", not "fixed_map_seed".
  • minetest.set_mapgen_setting_noiseparams(name, value, [override_meta])
    • Same as above, except value is a NoiseParams table.
  • minetest.set_noiseparams(name, noiseparams, set_default)
    • Sets the noiseparams setting of name to the noiseparams table specified in noiseparams.
    • set_default is an optional boolean (default: true) that specifies whether the setting should be applied to the default config or current active config.
  • minetest.get_noiseparams(name)
    • Returns a table of the noiseparams for name.
  • minetest.generate_ores(vm, pos1, pos2)
    • Generate all registered ores within the VoxelManip vm and in the area from pos1 to pos2.
    • pos1 and pos2 are optional and default to mapchunk minp and maxp.
  • minetest.generate_decorations(vm, pos1, pos2)
    • Generate all registered decorations within the VoxelManip vm and in the area from pos1 to pos2.
    • pos1 and pos2 are optional and default to mapchunk minp and maxp.
  • minetest.clear_objects([options])
    • Clear all objects in the environment
    • Takes an optional table as an argument with the field mode.
      • mode = "full" : Load and go through every mapblock, clearing objects (default).
      • mode = "quick": Clear objects immediately in loaded mapblocks, clear objects in unloaded mapblocks only when the mapblocks are next activated.
  • minetest.load_area(pos1[, pos2])
    • Load the mapblocks containing the area from pos1 to pos2. pos2 defaults to pos1 if not specified.
    • This function does not trigger map generation.
  • minetest.emerge_area(pos1, pos2, [callback], [param])
    • Queue all blocks in the area from pos1 to pos2, inclusive, to be asynchronously fetched from memory, loaded from disk, or if inexistent, generates them.
    • If callback is a valid Lua function, this will be called for each block emerged.
    • The function signature of callback is: function EmergeAreaCallback(blockpos, action, calls_remaining, param)
      • blockpos is the block coordinates of the block that had been emerged.
      • action could be one of the following constant values:
        • minetest.EMERGE_CANCELLED
        • minetest.EMERGE_ERRORED
        • minetest.EMERGE_FROM_MEMORY
        • minetest.EMERGE_FROM_DISK
        • minetest.EMERGE_GENERATED
      • calls_remaining is the number of callbacks to be expected after this one.
      • param is the user-defined parameter passed to emerge_area (or nil if the parameter was absent).
  • minetest.delete_area(pos1, pos2)
    • delete all mapblocks in the area from pos1 to pos2, inclusive
  • minetest.line_of_sight(pos1, pos2): returns boolean, pos
    • Checks if there is anything other than air between pos1 and pos2.
    • Returns false if something is blocking the sight.
    • Returns the position of the blocking node when false
    • pos1: First position
    • pos2: Second position
  • minetest.raycast(pos1, pos2, objects, liquids): returns Raycast
    • Creates a Raycast object.
    • pos1: start of the ray
    • pos2: end of the ray
    • objects: if false, only nodes will be returned. Default is true.
    • liquids: if false, liquid nodes won't be returned. Default is false.
  • minetest.find_path(pos1,pos2,searchdistance,max_jump,max_drop,algorithm)
    • returns table containing path
    • returns a table of 3D points representing a path from pos1 to pos2 or nil.
    • pos1: start position
    • pos2: end position
    • searchdistance: number of blocks to search in each direction using a maximum metric.
    • max_jump: maximum height difference to consider walkable
    • max_drop: maximum height difference to consider droppable
    • algorithm: One of "A*_noprefetch" (default), "A*", "Dijkstra"
  • minetest.spawn_tree (pos, {treedef})
    • spawns L-system tree at given pos with definition in treedef table
  • minetest.transforming_liquid_add(pos)
    • add node to liquid update queue
  • minetest.get_node_max_level(pos)
    • get max available level for leveled node
  • minetest.get_node_level(pos)
    • get level of leveled node (water, snow)
  • minetest.set_node_level(pos, level)
    • set level of leveled node, default level equals 1
    • if totallevel > maxlevel, returns rest (total-max).
  • minetest.add_node_level(pos, level)
    • increase level of leveled node by level, default level equals 1
    • if totallevel > maxlevel, returns rest (total-max)
    • can be negative for decreasing
  • minetest.fix_light(pos1, pos2): returns true/false
    • resets the light in a cuboid-shaped part of the map and removes lighting bugs.
    • Loads the area if it is not loaded.
    • pos1 is the corner of the cuboid with the least coordinates (in node coordinates), inclusive.
    • pos2 is the opposite corner of the cuboid, inclusive.
    • The actual updated cuboid might be larger than the specified one, because only whole map blocks can be updated. The actual updated area consists of those map blocks that intersect with the given cuboid.
    • However, the neighborhood of the updated area might change as well, as light can spread out of the cuboid, also light might be removed.
    • returns false if the area is not fully generated, true otherwise
  • minetest.check_single_for_falling(pos)
    • causes an unsupported group:falling_node node to fall and causes an unattached group:attached_node node to fall.
    • does not spread these updates to neighbours.
  • minetest.check_for_falling(pos)
    • causes an unsupported group:falling_node node to fall and causes an unattached group:attached_node node to fall.
    • spread these updates to neighbours and can cause a cascade of nodes to fall.
  • minetest.get_spawn_level(x, z)
    • Returns a player spawn y co-ordinate for the provided (x, z) co-ordinates, or nil for an unsuitable spawn point.
    • For most mapgens a 'suitable spawn point' is one with y between water_level and water_level + 16, and in mgv7 well away from rivers, so nil will be returned for many (x, z) co-ordinates.
    • The spawn level returned is for a player spawn in unmodified terrain.
    • The spawn level is intentionally above terrain level to cope with full-node biome 'dust' nodes.

Mod channels

You can find mod channels communication scheme in doc/mod_channels.png.

  • minetest.mod_channel_join(channel_name)
    • Server joins channel channel_name, and creates it if necessary. You should listen for incoming messages with minetest.register_on_modchannel_message

Inventory

minetest.get_inventory(location): returns an InvRef

  • location = e.g.
    • {type="player", name="celeron55"}
    • {type="node", pos={x=, y=, z=}}
    • {type="detached", name="creative"}
  • minetest.create_detached_inventory(name, callbacks, [player_name]): returns an InvRef.
    • callbacks: See [Detached inventory callbacks]
    • player_name: Make detached inventory available to one player exclusively, by default they will be sent to every player (even if not used). Note that this parameter is mostly just a workaround and will be removed in future releases.
    • Creates a detached inventory. If it already exists, it is cleared.
  • minetest.remove_detached_inventory(name)
    • Returns a boolean indicating whether the removal succeeded.
  • minetest.do_item_eat(hp_change, replace_with_item, itemstack, user, pointed_thing): returns left over ItemStack.
    • See minetest.item_eat and minetest.register_on_item_eat

Formspec

  • minetest.show_formspec(playername, formname, formspec)
    • playername: name of player to show formspec
    • formname: name passed to on_player_receive_fields callbacks. It should follow the "modname:<whatever>" naming convention
    • formspec: formspec to display
  • minetest.close_formspec(playername, formname)
    • playername: name of player to close formspec
    • formname: has to exactly match the one given in show_formspec, or the formspec will not close.
    • calling show_formspec(playername, formname, "") is equal to this expression.
    • to close a formspec regardless of the formname, call minetest.close_formspec(playername, ""). USE THIS ONLY WHEN ABSOLUTELY NECESSARY!
  • minetest.formspec_escape(string): returns a string
    • escapes the characters "[", "]", "\", "," and ";", which can not be used in formspecs.
  • minetest.explode_table_event(string): returns a table
    • returns e.g. {type="CHG", row=1, column=2}
    • type is one of:
      • "INV": no row selected
      • "CHG": selected
      • "DCL": double-click
  • minetest.explode_textlist_event(string): returns a table
    • returns e.g. {type="CHG", index=1}
    • type is one of:
      • "INV": no row selected
      • "CHG": selected
      • "DCL": double-click
  • minetest.explode_scrollbar_event(string): returns a table
    • returns e.g. {type="CHG", value=500}
    • type is one of:
      • "INV": something failed
      • "CHG": has been changed
      • "VAL": not changed

Item handling

  • minetest.inventorycube(img1, img2, img3)
    • Returns a string for making an image of a cube (useful as an item image)
  • minetest.get_pointed_thing_position(pointed_thing, above)
    • Returns the position of a pointed_thing or nil if the pointed_thing does not refer to a node or entity.
    • If the optional above parameter is true and the pointed_thing refers to a node, then it will return the above position of the pointed_thing.
  • minetest.dir_to_facedir(dir, is6d)
    • Convert a vector to a facedir value, used in param2 for paramtype2="facedir".
    • passing something non-nil/false for the optional second parameter causes it to take the y component into account.
  • minetest.facedir_to_dir(facedir)
    • Convert a facedir back into a vector aimed directly out the "back" of a node.
  • minetest.dir_to_wallmounted(dir)
    • Convert a vector to a wallmounted value, used for paramtype2="wallmounted".
  • minetest.wallmounted_to_dir(wallmounted)
    • Convert a wallmounted value back into a vector aimed directly out the "back" of a node.
  • minetest.dir_to_yaw(dir)
    • Convert a vector into a yaw (angle)
  • minetest.yaw_to_dir(yaw)
    • Convert yaw (angle) to a vector
  • minetest.is_colored_paramtype(ptype)
    • Returns a boolean. Returns true if the given paramtype2 contains color information (color, colorwallmounted or colorfacedir).
  • minetest.strip_param2_color(param2, paramtype2)
    • Removes everything but the color information from the given param2 value.
    • Returns nil if the given paramtype2 does not contain color information.
  • minetest.get_node_drops(nodename, toolname)
    • Returns list of item names.
    • Note: This will be removed or modified in a future version.
  • minetest.get_craft_result(input): returns output, decremented_input
    • input.method = "normal" or "cooking" or "fuel"
    • input.width = for example 3
    • input.items = for example {stack1, stack2, stack3, stack4, stack 5, stack 6, stack 7, stack 8, stack 9}
    • output.item = ItemStack, if unsuccessful: empty ItemStack
    • output.time = a number, if unsuccessful: 0
    • output.replacements = list of ItemStacks that couldn't be placed in decremented_input.items
    • decremented_input = like input
  • minetest.get_craft_recipe(output): returns input
    • returns last registered recipe for output item (node)
    • output is a node or item type such as "default:torch"
    • input.method = "normal" or "cooking" or "fuel"
    • input.width = for example 3
    • input.items = for example {stack1, stack2, stack3, stack4, stack 5, stack 6, stack 7, stack 8, stack 9}
      • input.items = nil if no recipe found
  • minetest.get_all_craft_recipes(query item): returns a table or nil
    • returns indexed table with all registered recipes for query item (node) or nil if no recipe was found.
    • recipe entry table:
      • method: 'normal' or 'cooking' or 'fuel'
      • width: 0-3, 0 means shapeless recipe
      • items: indexed [1-9] table with recipe items
      • output: string with item name and quantity
    • Example query for "default:gold_ingot" will return table:

      { [1]={method = "cooking", width = 3, output = "default:gold_ingot", items = {1 = "default:gold_lump"}}, [2]={method = "normal", width = 1, output = "default:gold_ingot 9", items = {1 = "default:goldblock"}} } * minetest.handle_node_drops(pos, drops, digger) * drops: list of itemstrings * Handles drops from nodes after digging: Default action is to put them into digger's inventory. * Can be overridden to get different functionality (e.g. dropping items on ground) * minetest.itemstring_with_palette(item, palette_index): returns an item string. * Creates an item string which contains palette index information for hardware colorization. You can use the returned string as an output in a craft recipe. * item: the item stack which becomes colored. Can be in string, table and native form. * palette_index: this index is added to the item stack * minetest.itemstring_with_color(item, colorstring): returns an item string * Creates an item string which contains static color information for hardware colorization. Use this method if you wish to colorize an item that does not own a palette. You can use the returned string as an output in a craft recipe. * item: the item stack which becomes colored. Can be in string, table and native form. * colorstring: the new color of the item stack

Rollback

  • minetest.rollback_get_node_actions(pos, range, seconds, limit): returns {{actor, pos, time, oldnode, newnode}, ...}
    • Find who has done something to a node, or near a node
    • actor: "player:<name>", also "liquid".
  • minetest.rollback_revert_actions_by(actor, seconds): returns boolean, log_messages.
    • Revert latest actions of someone
    • actor: "player:<name>", also "liquid".

Defaults for the on_* item definition functions

These functions return the leftover itemstack.

  • minetest.item_place_node(itemstack, placer, pointed_thing[, param2, prevent_after_place])
    • Place item as a node
    • param2 overrides facedir and wallmounted param2
    • prevent_after_place: if set to true, after_place_node is not called for the newly placed node to prevent a callback and placement loop
    • returns itemstack, success
  • minetest.item_place_object(itemstack, placer, pointed_thing)
    • Place item as-is
  • minetest.item_place(itemstack, placer, pointed_thing, param2)
    • Use one of the above based on what the item is.
    • Calls on_rightclick of pointed_thing.under if defined instead
    • Note: is not called when wielded item overrides on_place
    • param2 overrides facedir and wallmounted param2
    • returns itemstack, success
  • minetest.item_drop(itemstack, dropper, pos)
    • Drop the item
  • minetest.item_eat(hp_change, replace_with_item)
    • Eat the item.
    • replace_with_item is the itemstring which is added to the inventory. If the player is eating a stack, then replace_with_item goes to a different spot. Can be nil
    • See minetest.do_item_eat

Defaults for the on_punch and on_dig node definition callbacks

  • minetest.node_punch(pos, node, puncher, pointed_thing)
    • Calls functions registered by minetest.register_on_punchnode()
  • minetest.node_dig(pos, node, digger)
    • Checks if node can be dug, puts item into inventory, removes node
    • Calls functions registered by minetest.registered_on_dignodes()

Sounds

  • minetest.sound_play(spec, parameters): returns a handle
    • spec is a SimpleSoundSpec
    • parameters is a sound parameter table
  • minetest.sound_stop(handle)
  • minetest.sound_fade(handle, step, gain)
    • handle is a handle returned by minetest.sound_play
    • step determines how fast a sound will fade. Negative step will lower the sound volume, positive step will increase the sound volume.
    • gain the target gain for the fade.

Timing

  • minetest.after(time, func, ...)
    • Call the function func after time seconds, may be fractional
    • Optional: Variable number of arguments that are passed to func

Server

  • minetest.request_shutdown([message],[reconnect],[delay]): request for server shutdown. Will display message to clients.
    • reconnect == true displays a reconnect button
    • delay adds an optional delay (in seconds) before shutdown. Negative delay cancels the current active shutdown. Zero delay triggers an immediate shutdown.
  • minetest.cancel_shutdown_requests(): cancel current delayed shutdown
  • minetest.get_server_status(name, joined)
    • Returns the server status string when a player joins or when the command /status is called. Returns nil or an empty string when the message is disabled.
    • joined: Boolean value, indicates whether the function was called when a player joined.
    • This function may be overwritten by mods to customize the status message.
  • minetest.get_server_uptime(): returns the server uptime in seconds
  • minetest.remove_player(name): remove player from database (if they are not connected).
    • As auth data is not removed, minetest.player_exists will continue to return true. Call the below method as well if you want to remove auth data too.
    • Returns a code (0: successful, 1: no such player, 2: player is connected)
  • minetest.remove_player_auth(name): remove player authentication data
    • Returns boolean indicating success (false if player nonexistant)

Bans

  • minetest.get_ban_list(): returns a list of all bans formatted as string
  • minetest.get_ban_description(ip_or_name): returns list of bans matching IP address or name formatted as string
  • minetest.ban_player(name): ban the IP of a currently connected player
    • Returns boolean indicating success
  • minetest.unban_player_or_ip(ip_or_name): remove ban record matching IP address or name
  • minetest.kick_player(name, [reason]): disconnect a player with an optional reason.
    • Returns boolean indicating success (false if player nonexistant)

Particles

  • minetest.add_particle(particle definition)

    • Deprecated: minetest.add_particle(pos, velocity, acceleration, expirationtime, size, collisiondetection, texture, playername)
  • minetest.add_particlespawner(particlespawner definition)

    • Add a ParticleSpawner, an object that spawns an amount of particles over time seconds.
    • Returns an id, and -1 if adding didn't succeed
    • Deprecated: minetest.add_particlespawner(amount, time, minpos, maxpos, minvel, maxvel, minacc, maxacc, minexptime, maxexptime, minsize, maxsize, collisiondetection, texture, playername)
  • minetest.delete_particlespawner(id, player)

    • Delete ParticleSpawner with id (return value from minetest.add_particlespawner).
    • If playername is specified, only deletes on the player's client, otherwise on all clients.

Schematics

  • minetest.create_schematic(p1, p2, probability_list, filename, slice_prob_list)

    • Create a schematic from the volume of map specified by the box formed by p1 and p2.
    • Apply the specified probability and per-node force-place to the specified nodes according to the probability_list.
      • probability_list is an array of tables containing two fields, pos and prob.
        • pos is the 3D vector specifying the absolute coordinates of the node being modified,
        • prob is an integer value from 0 to 255 that encodes probability and per-node force-place. Probability has levels 0-127, then 128 may be added to encode per-node force-place. For probability stated as 0-255, divide by 2 and round down to get values 0-127, then add 128 to apply per-node force-place.
        • If there are two or more entries with the same pos value, the last entry is used.
        • If pos is not inside the box formed by p1 and p2, it is ignored.
        • If probability_list equals nil, no probabilities are applied.
    • Apply the specified probability to the specified horizontal slices according to the slice_prob_list.
      • slice_prob_list is an array of tables containing two fields, ypos and prob.
        • ypos indicates the y position of the slice with a probability applied, the lowest slice being ypos = 0.
        • If slice probability list equals nil, no slice probabilities are applied.
    • Saves schematic in the Minetest Schematic format to filename.
  • minetest.place_schematic(pos, schematic, rotation, replacements, force_placement, flags)

    • Place the schematic specified by schematic (see [Schematic specifier]) at pos.
    • rotation can equal "0", "90", "180", "270", or "random".
    • If the rotation parameter is omitted, the schematic is not rotated.
    • replacements = {["old_name"] = "convert_to", ...}
    • force_placement is a boolean indicating whether nodes other than air and ignore are replaced by the schematic.
    • Returns nil if the schematic could not be loaded.
    • Warning: Once you have loaded a schematic from a file, it will be cached. Future calls will always use the cached version and the replacement list defined for it, regardless of whether the file or the replacement list parameter have changed. The only way to load the file anew is to restart the server.
    • flags is a flag field with the available flags:
      • place_center_x
      • place_center_y
      • place_center_z
  • minetest.place_schematic_on_vmanip(vmanip, pos, schematic, rotation, replacement, force_placement, flags):

    • This function is analogous to minetest.place_schematic, but places a schematic onto the specified VoxelManip object vmanip instead of the map.
    • Returns false if any part of the schematic was cut-off due to the VoxelManip not containing the full area required, and true if the whole schematic was able to fit.
    • Returns nil if the schematic could not be loaded.
    • After execution, any external copies of the VoxelManip contents are invalidated.
    • flags is a flag field with the available flags:
      • place_center_x
      • place_center_y
      • place_center_z
  • minetest.serialize_schematic(schematic, format, options)

    • Return the serialized schematic specified by schematic (see [Schematic specifier])
    • in the format of either "mts" or "lua".
    • "mts" - a string containing the binary MTS data used in the MTS file format.
    • "lua" - a string containing Lua code representing the schematic in table format.
    • options is a table containing the following optional parameters:
      • If lua_use_comments is true and format is "lua", the Lua code generated will have (X, Z) position comments for every X row generated in the schematic data for easier reading.
      • If lua_num_indent_spaces is a nonzero number and format is "lua", the Lua code generated will use that number of spaces as indentation instead of a tab character.
  • minetest.read_schematic(schematic, options)

    • Returns a Lua table representing the schematic (see: [Schematic specifier])
    • schematic is the schematic to read (see: [Schematic specifier])
    • options is a table containing the following optional parameters:
      • write_yslice_prob: string value:
        • none: no write_yslice_prob table is inserted,
        • low: only probabilities that are not 254 or 255 are written in the write_ylisce_prob table,
        • all: write all probabilities to the write_yslice_prob table.
        • The default for this option is all.
        • Any invalid value will be interpreted as all.

HTTP Requests

  • minetest.request_http_api():
    • returns HTTPApiTable containing http functions if the calling mod has been granted access by being listed in the secure.http_mods or secure.trusted_mods setting, otherwise returns nil.
    • The returned table contains the functions fetch, fetch_async and fetch_async_get described below.
    • Only works at init time and must be called from the mod's main scope (not from a function).
    • Function only exists if minetest server was built with cURL support.
    • DO NOT ALLOW ANY OTHER MODS TO ACCESS THE RETURNED TABLE, STORE IT IN A LOCAL VARIABLE!
  • HTTPApiTable.fetch(HTTPRequest req, callback)
    • Performs given request asynchronously and calls callback upon completion
    • callback: function(HTTPRequestResult res)
    • Use this HTTP function if you are unsure, the others are for advanced use
  • HTTPApiTable.fetch_async(HTTPRequest req): returns handle
    • Performs given request asynchronously and returns handle for HTTPApiTable.fetch_async_get
  • HTTPApiTable.fetch_async_get(handle): returns HTTPRequestResult
    • Return response data for given asynchronous HTTP request

Storage API

  • minetest.get_mod_storage():
    • returns reference to mod private StorageRef
    • must be called during mod load time

Misc.

  • minetest.get_connected_players(): returns list of ObjectRefs
  • minetest.is_player(obj): boolean, whether obj is a player
  • minetest.player_exists(name): boolean, whether player exists (regardless of online status)
  • minetest.hud_replace_builtin(name, hud_definition)
    • Replaces definition of a builtin hud element
    • name: "breath" or "health"
    • hud_definition: definition to replace builtin definition
  • minetest.send_join_message(player_name)
    • This function can be overridden by mods to change the join message.
  • minetest.send_leave_message(player_name, timed_out)
    • This function can be overridden by mods to change the leave message.
  • minetest.hash_node_position(pos): returns an 48-bit integer
    • pos: table {x=number, y=number, z=number},
    • Gives a unique hash number for a node position (16+16+16=48bit)
  • minetest.get_position_from_hash(hash): returns a position
    • Inverse transform of minetest.hash_node_position
  • minetest.get_item_group(name, group): returns a rating
    • Get rating of a group of an item. (0 means: not in group)
  • minetest.get_node_group(name, group): returns a rating
    • Deprecated: An alias for the former.
  • minetest.raillike_group(name): returns a rating
    • Returns rating of the connect_to_raillike group corresponding to name
    • If name is not yet the name of a connect_to_raillike group, a new group id is created, with that name.
  • minetest.get_content_id(name): returns an integer
    • Gets the internal content ID of name
  • minetest.get_name_from_content_id(content_id): returns a string
    • Gets the name of the content with that content ID
  • minetest.parse_json(string[, nullvalue]): returns something
    • Convert a string containing JSON data into the Lua equivalent
    • nullvalue: returned in place of the JSON null; defaults to nil
    • On success returns a table, a string, a number, a boolean or nullvalue
    • On failure outputs an error message and returns nil
    • Example: parse_json("[10, {\"a\":false}]"), returns {10, {a = false}}
  • minetest.write_json(data[, styled]): returns a string or nil and an error message.
    • Convert a Lua table into a JSON string
    • styled: Outputs in a human-readable format if this is set, defaults to false.
    • Unserializable things like functions and userdata will cause an error.
    • Warning: JSON is more strict than the Lua table format.
      1. You can only use strings and positive integers of at least one as keys.
      2. You can not mix string and integer keys. This is due to the fact that JSON has two distinct array and object values.
    • Example: write_json({10, {a = false}}), returns "[10, {\"a\": false}]"
  • minetest.serialize(table): returns a string
    • Convert a table containing tables, strings, numbers, booleans and nils into string form readable by minetest.deserialize
    • Example: serialize({foo='bar'}), returns 'return { ["foo"] = "bar" }'
  • minetest.deserialize(string): returns a table
    • Convert a string returned by minetest.deserialize into a table
    • string is loaded in an empty sandbox environment.
    • Will load functions, but they cannot access the global environment.
    • Example: deserialize('return { ["foo"] = "bar" }'), returns {foo='bar'}
    • Example: deserialize('print("foo")'), returns nil (function call fails), returns error:[string "print("foo")"]:1: attempt to call global 'print' (a nil value)
  • minetest.compress(data, method, ...): returns compressed_data
    • Compress a string of data.
    • method is a string identifying the compression method to be used.
    • Supported compression methods:
      • Deflate (zlib): "deflate"
    • ... indicates method-specific arguments. Currently defined arguments are:
      • Deflate: level - Compression level, 0-9 or nil.
  • minetest.decompress(compressed_data, method, ...): returns data
    • Decompress a string of data (using ZLib).
    • See documentation on minetest.compress() for supported compression methods.
    • ... indicates method-specific arguments. Currently, no methods use this
  • minetest.rgba(red, green, blue[, alpha]): returns a string
    • Each argument is a 8 Bit unsigned integer
    • Returns the ColorString from rgb or rgba values
    • Example: minetest.rgba(10, 20, 30, 40), returns "#0A141E28"
  • minetest.encode_base64(string): returns string encoded in base64
    • Encodes a string in base64.
  • minetest.decode_base64(string): returns string
    • Decodes a string encoded in base64.
  • minetest.is_protected(pos, name): returns boolean

    • Returning true restricts the player name from modifying (i.e. digging, placing) the node at position pos.
    • name will be "" for non-players or unknown players.
    • This function should be overridden by protection mods. It is highly recommended to grant access to players with the protection_bypass privilege.
    • Cache and call the old version of this function if the position is not protected by the mod. This will allow using multiple protection mods.
    • Example:

      local old_is_protected = minetest.is_protected function minetest.is_protected(pos, name) if mymod:position_protected_from(pos, name) then return true end return old_is_protected(pos, name) end * minetest.record_protection_violation(pos, name) * This function calls functions registered with minetest.register_on_protection_violation. * minetest.is_area_protected(pos1, pos2, player_name, interval) * Returns the position of the first node that player_name may not modify in the specified cuboid between pos1 and pos2. * Returns false if no protections were found. * Applies is_protected() to a 3D lattice of points in the defined volume. The points are spaced evenly throughout the volume and have a spacing similar to, but no larger than, interval. * All corners and edges of the defined volume are checked. * interval defaults to 4. * interval should be carefully chosen and maximised to avoid an excessive number of points being checked. * Like minetest.is_protected, this function may be extended or overwritten by mods to provide a faster implementation to check the cuboid for intersections. * minetest.rotate_and_place(itemstack, placer, pointed_thing[, infinitestacks, orient_flags, prevent_after_place]) * Attempt to predict the desired orientation of the facedir-capable node defined by itemstack, and place it accordingly (on-wall, on the floor, or hanging from the ceiling). * infinitestacks: if true, the itemstack is not changed. Otherwise the stacks are handled normally. * orient_flags: Optional table containing extra tweaks to the placement code: * invert_wall: if true, place wall-orientation on the ground and ground-orientation on the wall. * force_wall : if true, always place the node in wall orientation. * force_ceiling: if true, always place on the ceiling. * force_floor: if true, always place the node on the floor. * force_facedir: if true, forcefully reset the facedir to north when placing on the floor or ceiling. * The first four options are mutually-exclusive; the last in the list takes precedence over the first. * prevent_after_place is directly passed to minetest.item_place_node * Returns the new itemstack after placement * minetest.rotate_node(itemstack, placer, pointed_thing) * calls rotate_and_place() with infinitestacks set according to the state of the creative mode setting, checks for "sneak" to set the invert_wall parameter and prevent_after_place set to true.

  • minetest.calculate_knockback(player, hitter, time_from_last_punch, tool_capabilities, dir, distance, damage)

    • Returns the amount of knockback applied on the punched player.
    • Arguments are equivalent to register_on_punchplayer, except the following:
      • distance: distance between puncher and punched player
    • This function can be overriden by mods that wish to modify this behaviour.
    • You may want to cache and call the old function to allow multiple mods to change knockback behaviour.
  • minetest.forceload_block(pos[, transient])

    • forceloads the position pos.
    • returns true if area could be forceloaded
    • If transient is false or absent, the forceload will be persistent (saved between server runs). If true, the forceload will be transient (not saved between server runs).
  • minetest.forceload_free_block(pos[, transient])

    • stops forceloading the position pos
    • If transient is false or absent, frees a persistent forceload. If true, frees a transient forceload.
  • minetest.request_insecure_environment(): returns an environment containing insecure functions if the calling mod has been listed as trusted in the secure.trusted_mods setting or security is disabled, otherwise returns nil.

    • Only works at init time and must be called from the mod's main scope (not from a function).
    • DO NOT ALLOW ANY OTHER MODS TO ACCESS THE RETURNED ENVIRONMENT, STORE IT IN A LOCAL VARIABLE!
  • minetest.global_exists(name)

    • Checks if a global variable has been set, without triggering a warning.

Global objects

  • minetest.env: EnvRef of the server environment and world.
    • Any function in the minetest namespace can be called using the syntax minetest.env:somefunction(somearguments) instead of minetest.somefunction(somearguments)
    • Deprecated, but support is not to be dropped soon

Global tables

Registered definition tables

  • minetest.registered_items
    • Map of registered items, indexed by name
  • minetest.registered_nodes
    • Map of registered node definitions, indexed by name
  • minetest.registered_craftitems
    • Map of registered craft item definitions, indexed by name
  • minetest.registered_tools
    • Map of registered tool definitions, indexed by name
  • minetest.registered_entities
    • Map of registered entity prototypes, indexed by name
  • minetest.object_refs
    • Map of object references, indexed by active object id
  • minetest.luaentities
    • Map of Lua entities, indexed by active object id
  • minetest.registered_abms
    • List of ABM definitions
  • minetest.registered_lbms
    • List of LBM definitions
  • minetest.registered_aliases
    • Map of registered aliases, indexed by name
  • minetest.registered_ores
    • Map of registered ore definitions, indexed by the name field.
    • If name is nil, the key is the object handle returned by minetest.register_ore.
  • minetest.registered_biomes
    • Map of registered biome definitions, indexed by the name field.
    • If name is nil, the key is the object handle returned by minetest.register_biome.
  • minetest.registered_decorations
    • Map of registered decoration definitions, indexed by the name field.
    • If name is nil, the key is the object handle returned by minetest.register_decoration.
  • minetest.registered_schematics
    • Map of registered schematic definitions, indexed by the name field.
    • If name is nil, the key is the object handle returned by minetest.register_schematic.
  • minetest.registered_chatcommands
    • Map of registered chat command definitions, indexed by name
  • minetest.registered_privileges
    • Map of registered privilege definitions, indexed by name

Registered callback tables

All callbacks registered with [Global callback registration functions] are added to corresponding minetest.registered_* tables.