Lua Api
Lua Api
8
========================================
More information at http://www.minetest.net/
Developer Wiki: http://dev.minetest.net/
Introduction
-------------
Content and functionality can be added to Minetest 0.4 by using Lua
scripting in run-time loaded mods.
Mods are contained and ran solely on the server side. Definitions and media
files are automatically transferred to the client.
If you see a deficiency in the API, feel free to attempt to add the
functionality in the engine and API. You can send such improvements as
source code patches to <celeron55@gmail.com>.
Programming in Lua
-------------------
If you have any difficulty in understanding this, please read:
http://www.lua.org/pil/
Startup
--------
Mods are loaded during server startup from the mod load paths by running
the init.lua scripts in a shared environment.
Paths
-----
RUN_IN_PLACE=1: (Windows release, local build)
$path_user: Linux: <build directory>
Windows: <build directory>
$path_share: Linux: <build directory>
Windows: <build directory>
Games
-----
Games are looked up from:
$path_share/games/gameid/
$path_user/games/gameid/
where gameid is unique to each game.
The game directory contains the file game.conf, which contains these fields:
name = <Human-readable full name of the game>
eg.
name = Minetest
The game directory can contain the file minetest.conf, which will be used
to set default settings when running the particular game.
Mod load path
-------------
Generic:
$path_share/games/gameid/mods/
$path_share/mods/
$path_user/games/gameid/mods/
$path_user/mods/ <-- User-installed mods
$worldpath/worldmods/
Modpack support
----------------
Mods can be put in a subdirectory, if the parent directory, which otherwise
should be a mod, contains a file named modpack.txt. This file shall be
empty, except for lines starting with #, which are comments.
modname:
The location of this directory can be fetched by using
minetest.get_modpath(modname)
depends.txt:
List of mods that have to be loaded before loading this mod.
A single line contains a single modname.
screenshot.png:
A screenshot shown in modmanager within mainmenu.
description.txt:
File containing desctiption to be shown within mainmenu.
optdepends.txt:
An alternative way of specifying optional dependencies.
Like depends.txt, a single line contains a single modname.
init.lua:
The main Lua script. Running this script should register everything it
wants to register. Subsequent execution depends on minetest calling the
registered callbacks.
Enforcement can be overridden by prefixing the name with ":". This can
be used for overriding the registrations of some other mod.
The ":" prefix can also be used for maintaining backwards compatibility.
Aliases
-------
Aliases can be added by using minetest.register_alias(name, convert_to)
This will make Minetest to convert things called name to things called
convert_to.
This can be used for maintaining backwards compatibility.
This can be also used for setting quick access names for things, eg. if
you have an item called epiclylongmodname:stuff, you could do
minetest.register_alias("stuff", "epiclylongmodname:stuff")
and be able to use "/giveme stuff".
Textures
--------
Mods should generally prefix their textures with modname_, eg. given
the mod name "foomod", a texture could be called
"foomod_foothing.png"
Sounds
-------
Only OGG files are supported.
Mods should generally prefix their sounds with modname_, eg. given
the mod name "foomod", a sound could be called
"foomod_foosound.ogg"
Sounds are referred to by their name with a dot, a single digit and the
file extension stripped out. When a sound is played, the actual sound file
is chosen randomly from the matching sounds.
SimpleSoundSpec:
eg. ""
eg. "default_place_node"
eg. {}
eg. {name="default_place_node"}
eg. {name="default_place_node", gain=1.0}
Note that in some cases you will stumble upon things that are not contained
in these tables (eg. when a mod has been removed). Always check for
existence before trying to access the fields.
Example: If you want to check the drawtype of a node, you could do:
Nodes
------
Nodes are the bulk data of the world: cubes and other things that take the
space of a cube. Huge amounts of them are handled efficiently, but they
are quite static.
param1 and param2 are 8 bit integers. The engine uses them for certain
automated functions. If you don't use these functions, you can use them to
store arbitrary values.
The functions of param1 and param2 are determined by certain fields in the
node definition:
param1 is reserved for the engine when paramtype != "none":
paramtype = "light"
^ The value stores light with and without sun in it's
upper and lower 4 bits.
param2 is reserved for the engine when any of these are used:
liquidtype == "flowing"
^ The level and some flags of the liquid is stored in param2
drawtype == "flowingliquid"
^ The drawn liquid level is read from param2
drawtype == "torchlike"
drawtype == "signlike"
paramtype2 == "wallmounted"
^ The rotation of the node is stored in param2. You can make this value
by using minetest.dir_to_wallmounted().
paramtype2 == "facedir"
^ The rotation of the node is stored in param2. Furnaces and chests are
rotated this way. Can be made by using minetest.dir_to_facedir().
Values range 0 - 23
facedir modulo 4 = axisdir
0 = y+ 1 = z+ 2 = z- 3 = x+ 4 = x- 5 = y-
facedir's two less significant bits are rotation around the axis
paramtype2 == "leveled"
^ The drawn node level is read from param2, like flowingliquid
Node drawtypes
---------------
There are a bunch of different looking node types. These are mostly just
copied from Minetest 0.3; more may be made in the future.
- normal
- airlike
- liquid
- flowingliquid
- glasslike
- glasslike_framed
- allfaces
- allfaces_optional
- torchlike
- signlike
- plantlike
- fencelike
- raillike
- nodebox -- See below. EXPERIMENTAL
Node boxes
-----------
Node selection boxes are defined using "node boxes"
Ore types
---------------
These tell in what manner the ore is generated.
All default ores are of the uniformly-distributed scatter type.
- scatter
Randomly chooses a location and generates a cluster of ore.
If noise_params is specified, the ore will be placed if the 3d perlin noise at
that point is greater than the noise_threshhold, giving the ability to create a
non-equal
distribution of ore.
- sheet
Creates a sheet of ore in a blob shape according to the 2d perlin noise
described by noise_params.
The relative height of the sheet can be controlled by the same perlin noise as
well, by specifying
a non-zero 'scale' parameter in noise_params. IMPORTANT: The noise is not
transformed by offset or
scale when comparing against the noise threshhold, but scale is used to
determine relative height.
The height of the blob is randomly scattered, with a maximum height of
clust_size.
clust_scarcity and clust_num_ores are ignored.
This is essentially an improved version of the so-called "stratus" ore seen in
some unofficial mods.
- claylike - NOT YET IMPLEMENTED
Places ore if there are no more than clust_scarcity number of specified nodes
within a Von Neumann
neighborhood of clust_size radius.
Ore attributes
-------------------
Currently supported flags: absheight
- absheight
Also produce this same ore between the height range of -height_max and -
height_min.
Useful for having ore in sky realms without having to duplicate ore entries.
Decoration types
-------------------
The varying types of decorations that can be placed.
The default value is simple, and is currently the only type supported.
- simple
Creates a 1xHx1 column of a specified node (or a random node from a list, if a
decoration
list is specified). Can specify a certain node it must spawn next to, such as
water or lava,
for example. Can also generate a decoration of random height between a
specified lower and
upper bound. This type of decoration is intended for placement of grass,
flowers, cacti,
papyrus, and so on.
- schematic
Copies a box of MapNodes from a specified schematic file (or raw description).
Can specify a
probability of a node randomly appearing when placed. This decoration type is
intended to be used
for multi-node sized discrete structures, such as trees, cave spikes, rocks,
and so on.
Schematic specifier
--------------------
A schematic specifier identifies a schematic by either a filename to a Minetest
Schematic file (.mts)
or through raw data supplied through Lua, in the form of a table. This table must
specify two fields:
- The 'size' field is a 3d vector containing the dimensions of the provided
schematic.
- The 'data' field is a flat table of MapNodes making up the schematic, in the
order of [z [y [x]]].
Important: The default value for param1 in MapNodes here is 255, which represents
"always place".
In the bulk MapNode data, param1, instead of the typical light values, instead
represents the
probability of that node appearing in the structure.
When passed to minetest.create_schematic, probability is an integer value ranging
from 0 to 255:
- A probability value of 0 means that node will never appear (0% chance).
- A probability value of 255 means the node will always appear (100% chance).
- If the probability value p is greater than 0, then there is a (p / 256 * 100)%
chance that node
will appear when the schematic is placed on the map.
Important note: Node aliases cannot be used for a raw schematic provided when
registering as a decoration.
Schematic attributes
---------------------
Currently supported flags: place_center_x, place_center_y, place_center_z
- place_center_x
Placement of this decoration is centered along the X axis.
- place_center_y
Placement of this decoration is centered along the Y axis.
- place_center_z
Placement of this decoration is centered along the Z axis.
Note: Future revisions to the HUD API may be incompatible; the HUD API is still in
the experimental stages.
- image
Displays an image on the HUD.
- scale: The scale of the image, with 1 being the original texture size.
Only the X coordinate scale is used (positive values)
Negative values represent that percentage of the screen it
should take; e.g. x=-100 means 100% (width)
- text: The name of the texture that is displayed.
- alignment: The alignment of the image.
- offset: offset in pixels from position.
- text
Displays text on the HUD.
- scale: Defines the bounding rectangle of the text.
A value such as {x=100, y=100} should work.
- text: The text to be displayed in the HUD element.
- number: An integer containing the RGB value of the color used to draw the
text.
Specify 0xFFFFFF for white text, 0xFF0000 for red, and so on.
- alignment: The alignment of the text.
- offset: offset in pixels from position.
- statbar
Displays a horizontal bar made up of half-images.
- text: The name of the texture that is used.
- number: The number of half-textures that are displayed.
If odd, will end with a vertically center-split texture.
- direction
- offset: offset in pixels from position.
- inventory
- text: The name of the inventory list to be displayed.
- number: Number of items in the inventory to be displayed.
- item: Position of item that is selected.
- direction
pointed_thing:
{type="nothing"}
{type="node", under=pos, above=pos}
{type="object", ref=ObjectRef}
Items
------
Node (register_node):
A node from the world
Tool (register_tool):
A tool/weapon that can dig and damage things according to tool_capabilities
Craftitem (register_craftitem):
A miscellaneous item
Table format:
eg. {name="default:dirt", count=5, wear=0, metadata=""}
^ 5 dirt nodes
eg. {name="default:pick_wood", count=1, wear=21323, metadata=""}
^ a wooden pick about 1/3 weared out
eg. {name="default:apple", count=1, wear=0, metadata=""}
^ an apple.
ItemStack:
C++ native format with many helper methods. Useful for converting between
formats. See the Class reference section for details.
Groups
-------
In a number of places, there is a group table. Groups define the
properties of a thing (item, node, armor of entity, capabilities of
tool) in such a way that the engine and other mods can can interact with
the thing without actually knowing what the thing is.
Usage:
- Groups are stored in a table, having the group names with keys and the
group ratings as values. For example:
groups = {crumbly=3, soil=1}
^ Default dirt
groups = {crumbly=2, soil=1, level=2, outerspace=1}
^ A more special dirt-kind of thing
- Groups always have a rating associated with them. If there is no
useful meaning for a rating for an enabled group, it shall be 1.
- When not defined, the rating of a group defaults to 0. Thus when you
read groups, you must interpret nil and 0 as the same value, 0.
You can read the rating of a group for an item or a node by using
minetest.get_item_group(itemname, groupname)
Groups of items
----------------
Groups of items can define what kind of an item it is (eg. wool).
Groups of nodes
----------------
In addition to the general item things, groups are used to define whether
a node is destroyable and how long it takes to destroy by a tool.
Groups of entities
-------------------
For entities, groups are, as of now, used only for calculating damage.
The rating is the percentage of damage caused by tools with this damage group.
See "Entity damage mechanism".
Groups of tools
----------------
Groups in tools define which groups of nodes and entities they are
effective towards.
Special groups
---------------
- immortal: Disables the group damage system for an entity
- level: Can be used to give an additional sense of progression in the game.
- A larger level will cause eg. a weapon of a lower level make much less
damage, and get weared out much faster, or not be able to get drops
from destroyed nodes.
- 0 is something that is directly accessible at the start of gameplay
- There is no upper limit
- dig_immediate: (player can always pick up node without tool wear)
- 2: node is removed without tool wear after 0.5 seconds or so
(rail, sign)
- 3: node is removed without tool wear immediately (torch)
- disable_jump: Player (and possibly other things) cannot jump from node
- fall_damage_add_percent: damage speed = speed * (1 + value/100)
- bouncy: value is bounce speed in percent
- falling_node: if there is no walkable block under the node it will fall
- attached_node: if the node under it is not a walkable block the node will be
dropped as an item. If the node is wallmounted the
wallmounted direction is checked.
- soil: saplings will grow on nodes in this group
- connect_to_raillike: makes nodes of raillike drawtype connect to
other group members with same drawtype
The **level** group is used to limit the toughness of nodes a tool can dig
and to scale the digging times / damage to a greater extent.
^ PLEASE DO UNDERSTAND THIS, otherwise you cannot use the system to it's
full potential.
**Tools define:**
* Full punch interval
* Maximum drop level
* For an arbitrary list of groups:
* Uses (until the tool breaks)
* Maximum level (usually 0, 1, 2 or 3)
* Digging times
* Damage groups
**Uses**
Determines how many uses the tool has when it is used for digging a node,
of this group, of the maximum level. For lower leveled nodes, the use count
is multiplied by 3^leveldiff.
- uses=10, leveldiff=0 -> actual uses: 10
- uses=10, leveldiff=1 -> actual uses: 30
- uses=10, leveldiff=2 -> actual uses: 90
**Maximum level**
Tells what is the maximum level of a node of this group that the tool will
be able to dig.
**Digging times**
List of digging times for different ratings of the group, for nodes of the
maximum level.
* For example, as a lua table, ''times={2=2.00, 3=0.70}''. This would
result in the tool to be able to dig nodes that have a rating of 2 or 3
for this group, and unable to dig the rating 1, which is the toughest.
Unless there is a matching group that enables digging otherwise.
**Damage groups**
List of damage for groups of entities. See "Entity damage mechanism".
This makes the tool be able to dig nodes that fullfill both of these:
- Have the **crumbly** group
- Have a **level** group less or equal to 2
level diff: 2 1 0 -1 -2
Notes:
- At crumbly=0, the node is not diggable.
- At crumbly=3, the level difference digging time divider kicks in and makes
easy nodes to be quickly breakable.
- At level > 2, the node is not diggable, because it's level > maxlevel
Node Metadata
-------------
The instance of a node in the world normally only contains the three values
mentioned in "Nodes". However, it is possible to insert extra data into a
node. It is called "node metadata"; See "NodeMetaRef".
Example stuff:
Spaces and newlines can be inserted between the blocks, as is used in the
examples.
Examples:
- Chest:
invsize[8,9;]
list[context;main;0,0;8,4;]
list[current_player;main;0,5;8,4;]
- Furnace:
invsize[8,9;]
list[context;fuel;2,3;1,1;]
list[context;src;2,1;1,1;]
list[context;dst;5,1;2,2;]
list[current_player;main;0,5;8,4;]
- Minecraft-like player inventory
invsize[8,7.5;]
image[1,0.6;1,2;player.png]
list[current_player;main;0,3.5;8,4;]
list[current_player;craft;3,0;3,3;]
list[current_player;craftpreview;7,1;1,1;]
Elements:
size[<W>,<H>]
^ Define the size of the menu in inventory slots
^ deprecated: invsize[<W>,<H>;]
listcolors[<slot_bg_normal>;<slot_bg_hover>]
^ Sets background color of slots in HEX-Color format
^ Sets background color of slots on mouse hovering
listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>]
^ Sets background color of slots in HEX-Color format
^ Sets background color of slots on mouse hovering
^ Sets color of slots border
listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>;<tooltip_bgcolor>;<toolti
p_fontcolor>]
^ Sets background color of slots in HEX-Color format
^ Sets background color of slots on mouse hovering
^ Sets color of slots border
^ Sets background color of tooltips
^ Sets font color of tooltips
image[<X>,<Y>;<W>,<H>;<texture name>]
^ Show an image
^ Position and size units are inventory slots
item_image[<X>,<Y>;<W>,<H>;<item name>]
^ Show an inventory image of registered item/node
^ Position and size units are inventory slots
bgcolor[<color>;<fullscreen>]
^ Sets background color of formspec in HEX-Color format
^ If true the background color is drawn fullscreen (does not effect the size of the
formspec)
background[<X>,<Y>;<W>,<H>;<texture name>]
^ Use a background. Inventory rectangles are not drawn then.
^ Position and size units are inventory slots
^ Example for formspec 8x4 in 16x resolution: image shall be sized 8*16px x 4*16px
background[<X>,<Y>;<W>,<H>;<texture name>;<auto_clip>]
^ Use a background. Inventory rectangles are not drawn then.
^ Position and size units are inventory slots
^ Example for formspec 8x4 in 16x resolution: image shall be sized 8*16px x 4*16px
^ If true the background is clipped to formspec size (x and y are used as offset
values, w and h are ignored)
pwdfield[<X>,<Y>;<W>,<H>;<name>;<label>]
^ Textual password style field; will be sent to server when a button is clicked
^ x and y position the field relative to the top left of the menu
^ w and h are the size of the field
^ fields are a set height, but will be vertically centred on h
^ Position and size units are inventory slots
^ name is the name of the field as returned in fields to on_receive_fields
^ label, if not blank, will be text printed on the top left above the field
field[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]
^ Textual field; will be sent to server when a button is clicked
^ x and y position the field relative to the top left of the menu
^ w and h are the size of the field
^ fields are a set height, but will be vertically centred on h
^ Position and size units are inventory slots
^ name is the name of the field as returned in fields to on_receive_fields
^ label, if not blank, will be text printed on the top left above the field
^ default is the default value of the field
^ default may contain variable references such as '${text}' which
will fill the value from the metadata value 'text'
^ Note: no extra text or more than a single variable is supported ATM.
field[<name>;<label>;<default>]
^ as above but without position/size units
^ special field for creating simple forms, such as sign text input
^ must be used without a size[] element
^ a 'Proceed' button will be added automatically
textarea[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]
^ same as fields above, but with multi-line input
label[<X>,<Y>;<label>]
^ x and y work as per field
^ label is the text on the label
^ Position and size units are inventory slots
vertlabel[<X>,<Y>;<label>]
^ Textual label drawn verticaly
^ x and y work as per field
^ label is the text on the label
^ Position and size units are inventory slots
button[<X>,<Y>;<W>,<H>;<name>;<label>]
^ Clickable button. When clicked, fields will be sent.
^ x, y and name work as per field
^ w and h are the size of the button
^ label is the text on the button
^ Position and size units are inventory slots
image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]
^ x, y, w, h, and name work as per button
^ texture name is the filename of an image
^ Position and size units are inventory slots
image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>;<noclip>;<drawborder>]
^ x, y, w, h, and name work as per button
^ texture name is the filename of an image
^ Position and size units are inventory slots
^ noclip true meand imagebutton doesn't need to be within specified formsize
^ drawborder draw button bodrer or not
image_button[<X>,<Y>;<W>,<H>;<texture
name>;<name>;<label>;<noclip>;<drawborder>;<pressed texture name>]
^ x, y, w, h, and name work as per button
^ texture name is the filename of an image
^ Position and size units are inventory slots
^ noclip true meand imagebutton doesn't need to be within specified formsize
^ drawborder draw button bodrer or not
^ pressed texture name is the filename of an image on pressed state
item_image_button[<X>,<Y>;<W>,<H>;<item name>;<name>;<label>]
^ x, y, w, h, name and label work as per button
^ item name is the registered name of an item/node,
tooltip will be made out of its descritption
^ Position and size units are inventory slots
button_exit[<X>,<Y>;<W>,<H>;<name>;<label>]
^ When clicked, fields will be sent and the form will quit.
image_button_exit[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]
^ When clicked, fields will be sent and the form will quit.
box[<X>,<Y>;<W>,<H>;<color>]
^ simple colored semitransparent box
^ x and y position the box relative to the top left of the menu
^ w and h are the size of box
^ color in HEX-Color format
checkbox[<X>,<Y>;<name>;<label>;<selected>]
^ show a checkbox
^ x and y position of checkbox
^ name fieldname data is transfered to lua
^ label to be shown left of checkbox
^ selected (optional) true/false
Note: do NOT use a element name starting with "key_" those names are reserved to
pass key press events to formspec!
Inventory location:
HEX-Color
---------
#RGB
^ defines a color in hexadecimal format
#RGBA
^ defines a color in hexadecimal format and alpha channel
#RRGGBB
^ defines a color in hexadecimal format
#RRGGBBAA
^ defines a color in hexadecimal format and alpha channel
Vector helpers
---------------
vector.new([x[, y, z]]) -> vector
^ x is a table or the x position.
vector.direction(p1, p2) -> vector
vector.distance(p1, p2) -> number
vector.length(v) -> number
vector.normalize(v) -> vector
vector.round(v) -> vector
vector.equals(v1, v2) -> bool
For the folowing x can be either a vector or a number.
vector.add(v, x) -> vector
vector.subtract(v, x) -> vector
vector.multiply(v, x) -> vector
vector.divide(v, x) -> vector
Helper functions
-----------------
dump2(obj, name="_", dumped={})
^ Return object serialized as a string, handles reference loops
dump(obj, dumped={})
^ Return object serialized as a string
math.hypot(x, y)
^ Get the hypotenuse of a triangle with legs x and y.
Usefull for distance calculation.
string:split(separator)
^ eg. string:split("a,b", ",") == {"a","b"}
string:trim()
^ eg. string.trim("\n \t\tfoo bar\t ") == "foo bar"
minetest.pos_to_string({x=X,y=Y,z=Z}) -> "(X,Y,Z)"
^ Convert position to a printable string
minetest.string_to_pos(string) -> position
^ Same but in reverse
^ escapes characters [ ] \ , ; that can not be used in formspecs
minetest.is_yes(arg)
^ returns whether arg can be interpreted as yes
Logging:
minetest.debug(line)
^ Always printed to stderr and logfile (print() is redirected here)
minetest.log(line)
minetest.log(loglevel, line)
^ loglevel one of "error", "action", "info", "verbose"
Registration functions: (Call these only at load time)
minetest.register_entity(name, prototype table)
minetest.register_abm(abm definition)
minetest.register_node(name, node definition)
minetest.register_tool(name, item definition)
minetest.register_craftitem(name, item definition)
minetest.register_alias(name, convert_to)
minetest.register_craft(recipe)
minetest.register_ore(ore definition)
minetest.register_decoration(decoration definition)
Setting-related:
minetest.setting_set(name, value)
minetest.setting_get(name) -> string or nil
minetest.setting_setbool(name, value)
minetest.setting_getbool(name) -> boolean value or nil
minetest.setting_get_pos(name) -> position or nil
minetest.setting_save() -> nil, save all settings to config file
Authentication:
minetest.notify_authentication_modified(name)
^ Should be called by the authentication handler if privileges change.
^ To report everybody, set name=nil.
minetest.get_password_hash(name, raw_password)
^ Convert a name-password pair to a password hash that minetest can use
minetest.string_to_privs(str) -> {priv1=true,...}
minetest.privs_to_string(privs) -> "priv1,priv2,..."
^ Convert between two privilege representations
minetest.set_player_password(name, password_hash)
minetest.set_player_privs(name, {priv1=true,...})
minetest.get_player_privs(name) -> {priv1=true,...}
minetest.auth_reload()
^ These call the authentication handler
minetest.check_player_privs(name, {priv1=true,...}) -> bool, missing_privs
^ A quickhand for checking privileges
minetest.get_player_ip(name) -> IP address string
Chat:
minetest.chat_send_all(text)
minetest.chat_send_player(name, text, prepend)
^ prepend: optional, if it is set to false "Server -!- " will not be prepended to
the message
Environment access:
minetest.set_node(pos, node)
minetest.add_node(pos, node): alias set_node(pos, node)
^ Set node at position (node = {name="foo", param1=0, param2=0})
minetest.remove_node(pos)
^ Equivalent to set_node(pos, "air")
minetest.get_node(pos)
^ Returns {name="ignore", ...} for unloaded area
minetest.get_node_or_nil(pos)
^ Returns nil for unloaded area
minetest.get_node_light(pos, timeofday) -> 0...15 or nil
^ timeofday: nil = current time, 0 = night, 0.5 = day
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
minetest.punch_node(pos)
^ Punch node with the same effects that a player would cause
Inventory:
minetest.get_inventory(location) -> InvRef
^ location = eg. {type="player", name="celeron55"}
{type="node", pos={x=, y=, z=}}
{type="detached", name="creative"}
minetest.create_detached_inventory(name, callbacks) -> InvRef
^ callbacks: See "Detached inventory callbacks"
^ Creates a detached inventory. If it already exists, it is cleared.
minetest.show_formspec(playername, formname, formspec)
^ playername: name of player to show formspec
^ formname: name passed to on_player_receive_fields callbacks
^ should follow "modname:<whatever>" naming convention
^ formspec: formspec to display
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)
^ Get position of a pointed_thing (that you can get from somewhere)
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.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) -> output, decremented_input
^ input.method = 'normal' or 'cooking' or 'fuel'
^ input.width = for example 3
^ input.items = for example { stack 1, stack 2, stack 3, stack 4,
stack 5, stack 6, stack 7, stack 8, stack 9 }
^ output.item = ItemStack, if unsuccessful: empty ItemStack
^ output.time = number, if unsuccessful: 0
^ decremented_input = like input
minetest.get_craft_recipe(output) -> 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 { stack 1, stack 2, stack 3, stack 4,
stack 5, stack 6, stack 7, stack 8, stack 9 }
^ input.items = nil if no recipe found
minetest.get_all_craft_recipes(query item) -> 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={type = "cooking", width = 3, output = "default:gold_ingot",
items = {1 = "default:gold_lump"}},
2={type = "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 (eg. dropping items on
ground)
Rollbacks:
minetest.rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
^ Find who has done something to a node, or near a node
^ actor: "player:<name>", also "liquid".
minetest.rollback_revert_actions_by(actor, seconds) -> bool, log messages
^ Revert latest actions of someone
^ actor: "player:<name>", also "liquid".
Sounds:
minetest.sound_play(spec, parameters) -> handle
^ spec = SimpleSoundSpec
^ parameters = sound parameter table
minetest.sound_stop(handle)
Timing:
minetest.after(time, func, ...)
^ Call function after time seconds
^ Optional: Variable number of arguments that are passed to func
Server:
minetest.request_shutdown() -> request for server shutdown
minetest.get_server_status() -> server status string
Bans:
minetest.get_ban_list() -> ban list (same as minetest.get_ban_description(""))
minetest.get_ban_description(ip_or_name) -> ban description (string)
minetest.ban_player(name) -> ban a player
minetest.unban_player_or_ip(name) -> unban player or IP address
Particles:
minetest.add_particle(pos, velocity, acceleration, expirationtime,
size, collisiondetection, texture, playername)
^ Spawn particle at pos with velocity and acceleration
^ Disappears after expirationtime seconds
^ collisiondetection: if true collides with physical objects
^ Uses texture (string)
^ Playername is optional, if specified spawns particle only on the player's client
minetest.add_particlespawner(amount, time,
minpos, maxpos,
minvel, maxvel,
minacc, maxacc,
minexptime, maxexptime,
minsize, maxsize,
collisiondetection, texture, playername)
^ Add a particlespawner, an object that spawns an amount of particles over time
seconds
^ The particle's properties are random values in between the boundings:
^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration),
^ minsize/maxsize, minexptime/maxexptime (expirationtime)
^ collisiondetection: if true uses collisiondetection
^ Uses texture (string)
^ Playername is optional, if specified spawns particle only on the player's client
^ If time is 0 has infinite lifespan and spawns the amount on a per-second base
^ Returns and id
minetest.delete_particlespawner(id, player)
^ Delete ParticleSpawner with id (return value from 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)
^ Create a schematic from the volume of map specified by the box formed by p1 and
p2.
^ Apply the specified probability values to the specified nodes in
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,
^ and prob is the integer value from 0 to 255 of the probability (see: Schematic
specifier).
^ If there are two or more entries with the same pos value, the last occuring in
the array is used.
^ If pos is not inside the box formed by p1 and p2, it is ignored.
^ If probability_list is nil, no probabilities are applied.
^ Saves schematic in the Minetest Schematic format to filename.
Random:
minetest.get_connected_players() -> list of ObjectRefs
minetest.hash_node_position({x=,y=,z=}) -> 48-bit integer
^ Gives a unique hash number for a node position (16+16+16=48bit)
minetest.get_item_group(name, group) -> rating
^ Get rating of a group of an item. (0 = not in group)
minetest.get_node_group(name, group) -> rating
^ Deprecated: An alias for the former.
minetest.get_content_id(name) -> integer
^ Gets the internal content ID of name
minetest.get_name_from_content_id(content_id) -> string
^ Gets the name of the content with that content ID
minetest.parse_json(string[, nullvalue]) -> 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}]") -> {[1] = 10, [2] = {a = false}}
minetest.serialize(table) -> string
^ Convert a table containing tables, strings, numbers, booleans and nils
into string form readable by minetest.deserialize
^ Example: serialize({foo='bar'}) -> 'return { ["foo"] = "bar" }'
minetest.deserialize(string) -> 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" }') -> {foo='bar'}
^ Example: deserialize('print("foo")') -> nil (function call fails)
^ error:[string "print("foo")"]:1: attempt to call global 'print' (a nil value)
minetest.is_protected(pos, name) -> bool
^ This function should be overriden by protection mods and should be used to
check if a player can interact at a position.
^ This function should call the old version of itself if the position is not
protected by the mod.
^ 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.rotate_and_place(itemstack, placer, pointed_thing, infinitestacks,
orient_flags)
^ 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). Stacks are handled normally if the infinitestacks
field is false or omitted (else, the itemstack is not changed). orient_flags
is an 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.
The above four options are mutually-exclusive; the last in the list takes
precedence over the first.
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:
minetest.registered_items
^ List of registered items, indexed by name
minetest.registered_nodes
^ List of registered node definitions, indexed by name
minetest.registered_craftitems
^ List of registered craft item definitions, indexed by name
minetest.registered_tools
^ List of registered tool definitions, indexed by name
minetest.registered_entities
^ List of registered entity prototypes, indexed by name
minetest.object_refs
^ List of object references, indexed by active object id
minetest.luaentities
^ List of lua entities, indexed by active object id
Class reference
----------------
NodeMetaRef: Node metadata - reference extra data and functionality stored
in a node
- Can be gotten via minetest.get_nodemeta(pos)
methods:
- set_string(name, value)
- get_string(name)
- set_int(name, value)
- get_int(name)
- set_float(name, value)
- get_float(name)
- get_inventory() -> InvRef
- to_table() -> nil or {fields = {...}, inventory = {list1 = {}, ...}}
- from_table(nil or {})
^ See "Node Metadata"
{jump=bool,right=bool,left=bool,LMB=bool,RMB=bool,sneak=bool,aux1=bool,down=bool,up
=bool}
- get_player_control_bits(): returns integer with bit packed player pressed keys
bit nr/meaning: 0/up ,1/down ,2/left ,3/right ,4/jump ,5/aux1 ,6/sneak
,7/LMB ,8/RMB
- set_physics_override(speed, jump, gravity)
modifies per-player walking speed, jump height, and gravity.
Values default to 1 and act as offsets to the physics settings
in minetest.conf. nil will keep the current setting.
- hud_add(hud definition): add a HUD element described by HUD def, returns ID
number on success
- hud_remove(id): remove the HUD element of the specified id
- hud_change(id, stat, value): change a value of a previously added HUD element
^ element stat values: position, name, scale, text, number, item, dir
- hud_get(id): gets the HUD element definition structure of the specified ID
- hud_set_flags(flags): sets specified HUD flags to true/false
^ flags: (is visible) hotbar, healthbar, crosshair, wielditem
^ pass a table containing a true/false value of each flag to be set or unset
^ if a flag is nil, the flag is not modified
- hud_set_hotbar_itemcount(count): sets number of items in builtin hotbar
^ count: number of items, must be between 1 and 23
- hud_set_hotbar_image(texturename)
^ sets background image for hotbar
- hud_set_hotbar_selected_image(texturename)
^ sets image for selected item of hotbar
Mapgen objects
---------------
A mapgen object is a construct used in map generation. Mapgen objects can be used
by an on_generate
callback to speed up operations by avoiding unnecessary recalculations; these can
be retrieved using the
minetest.get_mapgen_object() function. If the requested Mapgen object is
unavailable, or
get_mapgen_object() was called outside of an on_generate() callback, nil is
returned.
- voxelmanip
This returns three values; the VoxelManip object to be used, minimum and
maximum emerged position, in that
order. All mapgens support this object.
- heightmap
Returns an array containing the y coordinates of the ground levels of nodes in
the most recently
generated chunk by the current mapgen.
- biomemap
Returns an array containing the biome IDs of nodes in the most recently
generated chunk by the
current mapgen.
- heatmap
Returns an array containing the temperature values of nodes in the most
recently generated chunk by
the current mapgen.
- humiditymap
Returns an array containing the humidity values of nodes in the most recently
generated chunk by the
current mapgen.
Registered entities
--------------------
- Functions receive a "luaentity" as self:
- It has the member .name, which is the registered name ("mod:thing")
- It has the member .object, which is an ObjectRef pointing to the object
- The original prototype stuff is visible directly via a metatable
- Callbacks:
- on_activate(self, staticdata)
^ Called when the object is instantiated.
- on_step(self, dtime)
^ Called on every server tick (dtime is usually 0.1 seconds)
- on_punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
^ Called when somebody punches the object.
^ Note that you probably want to handle most punches using the
automatic armor group system.
^ puncher: ObjectRef (can be nil)
^ 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.
- on_rightclick(self, clicker)
- get_staticdata(self)
^ Should return a string that will be passed to on_activate when
the object is instantiated the next time.
L-system trees
---------------
treedef={
axiom, - string initial tree axiom
rules_a, - string rules set A
rules_b, - string rules set B
rules_c, - string rules set C
rules_d, - string rules set D
trunk, - string trunk node name
leaves, - string leaves node name
leaves2, - string secondary leaves node name
leaves2_chance,- num chance (0-100) to replace leaves with leaves2
angle, - num angle in deg
iterations, - num max # of iterations, usually 2 -5
random_level, - num factor to lower nr of iterations, usually 0 - 3
trunk_type, - string single/double/crossed) type of trunk: 1 node, 2x2 nodes
or 3x3 in cross shape
thin_branches, - boolean true -> use thin (1 node) branches
fruit, - string fruit node name
fruit_chance, - num chance (0-100) to replace leaves with fruit node
seed, - num random seed
}
Definition tables
------------------
Object Properties
{
hp_max = 1,
physical = true,
collide_with_objects = true, -- collide with other objects if physical=true
weight = 5,
collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5},
visual = "cube"/"sprite"/"upright_sprite"/"mesh",
visual_size = {x=1, y=1},
mesh = "model",
textures = {}, -- number of required textures depends on visual
colors = {}, -- number of required colors depends on visual
spritediv = {x=1, y=1},
initial_sprite_basepos = {x=0, y=0},
is_visible = true,
makes_footstep_sound = false,
automatic_rotate = false,
stepheight = 0,
automatic_face_movement_dir = 0.0,
^ automatically set yaw to movement direction; offset in degrees; false to
disable
}
Tile definition:
- "image.png"
- {name="image.png", animation={Tile Animation definition}}
- {name="image.png", backface_culling=bool}
^ backface culling only supported in special tiles
- deprecated still supported field names:
- image -> name
on_construct = func(pos),
^ Node constructor; always called after adding node
^ Can set up metadata and stuff like that
^ default: nil
on_destruct = func(pos),
^ Node destructor; always called before removing node
^ default: nil
after_destruct = func(pos, oldnode),
^ Node destructor; always called after removing node
^ default: nil
on_timer = function(pos,elapsed),
^ default: nil
^ called by NodeTimers, see minetest.get_node_timer and NodeTimerRef
^ elapsed is the total time passed since the timer was started
^ return true to run the timer for another cycle with the same timeout value