mdbtxt1
mdbtxt2
Proceed to Safety

Minetest Documentation and Fixes    


Where the *%$& are the screenshots?

On MacOS versions of minetest, the F12 button puts the screen shot in a folder deep within the minetest application itself. On my sytem, the screenshots are saved to:

/Applications/minetest.app/Contents/Resources/screenshot_176447873.png

(but with different numbers in place of the '176447873' shown here)


Bugs

In bin/builtin/common/serialize.lua is the following line:

error("Can't serialize data of type "..t)

which causes the lua virtual machine to die with the errors

WARNING: Undeclared global variable ''t'' accessed
attempt to concatenate global 't' (a nil value)

whenever an attempt is made to minetest.serialize something containing a lua userdata type data block (for example, a player object as returned by minetest.get_player_by_name will do this). To fix it, "t" should be changed to "tp":

error("Can't serialize data of type "..tp)

This bug is present in minetest 0.4.11 and was fixed on 2015 Jan 15 by kaeza (see file history at github.com/minetest/minetest/blob/master/builtin/common/serialize.lua )


If you install a mod then remove it, or try to rename a mod's directory, minetest will usually display useless errors at startup referring to the old name of the renamed or removed mod:

The following mods could not be found: "old_mod_name"

To fix this, edit worlds/WORLD-NAME/world.mt and find and remove the line that says

load_mod_old_mod_name = true


Using ffmpeg to change the audio volume of the sheep bleat sound:

The sound made by the sheep in the mobs (simple mods) mod by PilzAdam is way too loud.


If you see error messages like these in "

Irrlicht log: Could not open file of texture: character.png Irrlicht log: Could not open file of texture: mobs_sheep.png Irrlicht log: Could not open file of texture: UV_rat.png

It might be caused by un-needed TextureFilename lines in the ".x" files used to define the 3-D appearance of mobs. For example, the error ending in "mobs_sheep.png" was caused by the following section of MINETEST_FOLDER/mods/mobs/models/mobs_sheep.x :

Material Material { 0.800000; 0.800000; 0.800000; 1.000000;; 96.078431; 0.000000; 0.000000; 0.000000;; 0.000000; 0.000000; 0.000000;; TextureFilename {"mobs_sheep.png";} }

to remove the bogus error messages all I had to do was comment out the "TextureFilename" line (by adding "//" in front of it).




Pages from the Wiki

I have colleceted some useful pages here and added to some.


Time of day

A day in Minetest (uses other world times than in the "Important times of day" section)

Time of day determines the position of the sun, moon and stars in the day-night cycle. It is represented as a number which is between 0 and 24000 (24000 excluded), this range represents a full day. This number resembles the 24-hour system, where the full hours are multiplied by 1000. So, for example 12:00 would correspond to 12000 time of day (think of it only as a guide to get an idea how it works).

The world time can be set with the /time command by players who have the "settime" privilege. It takes the desired time of day as it's only parameter. Refer the the "Important times of day" section as a guide.

/time 6000 - sets the time of day to morning (corresponds to 6:00)

/time 12000 - sets the time of day to midday (corresponds to 12:00)

The following world times were taken from a case study. The numbers in brackets denote the brightness level compared to moonlight (higher is brighter, this number is only used for this article).

In the world files in env_meta.txt, the time of day is stored as "time_of_day".

Mods like the beds mod change the time of day with an API call like "minetest.set_timeofday(0.23)" (documented below)




minetest API reference

Following are a few pages of reference material on minetest programming, that I want to keep all in one place (becaue the Wikis are terrible)


add_entity

minetest.add_entity(pos, "name")

Spawns Lua entitiy at pos. Returns ObjectRef or nil if failed.

   pos: List of 3 vertices (x, y, z)

   "name": Entity name

Example

local obj = minetest.add_entity({x=0, y=10, z=0}, "mobs:sheep") if obj then obj:setacceleration({x=0, y=-10, z=0}) end


chat_send_all

minetest.chat_send_all("text")

Send a chat message to all players.

Example:

minetest.chat_send_all("Hello World!")


get_timeofday

minetest.get_timeofday()

Returns time of day on a scale of 0.0 to 1.0. Note that the console /time command uses a scale of 0 to 24000, so this example prints the time on that scale:

print(minetest.get_timeofday() * 24000)


LuaEntitySAO

These are non-player moving things in the game. It inherits all the properties of ObjectRef.

New entity types are registered using minetest.register_entity(...) and the prototype definitions indexed using minetest.registered_entities["name"]. Instances are created using minetest.add_entity(...) and may be indexed using minetest.luaentities[objectID]

Methods

   getacceleration() — {x=num, y=num, z=num}

   getvelocity() — {x=num, y=num, z=num}

   getyaw() — returns yaw in radians

   get_entity_name() DEPRECATED: Will be removed in a future version

      In place of this, use object.get_luaentity().name

   get_luaentity()

   setacceleration({x=num, y=num, z=num})

   setsprite(p={x=0,y=0}, num_frames=1, framelength=0.2, select_horiz_by_yawpitch=false) — Select sprite from spritesheet with optional animation and DM-style texture selection based on yaw relative to camera

   settexturemod(mod)

   setvelocity({x=num, y=num, z=num})

   setyaw(radians)

Inherited from ObjectRef

   getpos() — returns {x=num, y=num, z=num}.

   get_armor_groups() - Returns {group1=rating, group2=rating, ...})

      Note: Documented in lua_api.txt but not yet implemented as of version 0.4.4

   get_hp() — returns number of hitpoints (2 * number of hearts).

   get_inventory() — returns the InvRef of the object.

   get_wielded_item() — returns the wielded item (ItemStack). This is essentially just a pseudonym for object:get_inventory():get_stack(object:get_wield_list(), object:get_wield_index()) so please note the caveats for inventory manipulation (changes will need to be "committed" by calling object:set_wielded_item(modifiedStack) after modifying the stack unless they are done in the context of a callback that implicitly modifies the stack; see minetest.register_node#on_use).

   get_wield_index() — returns the index of the wielded item

   get_wield_list() — returns the name of the inventory list the wielded item is in

   moveto(pos, continuous=false) — interpolated move

   punch(puncher, time_from_last_punch, tool_capabilities, direction)

      puncher — an another ObjectRef

      time_from_last_punch — time since last punch action of the puncher

      direction: can be nil

   remove() — remove object (after returning from Lua)

   right_click(clicker)

      clicker — another ObjectRef

   setpos(pos) — "teleport"

      pos — position

   set_armor_groups({group1=rating, group2=rating, ...})

   set_hp(hp) — set number of hitpoints (2 * number of hearts)

   set_properties({object property table})

   set_wielded_item(item) — replaces the wielded item, returns true if successful

   set_animation({x=1,y=1}, frame_speed=15, frame_blend=0)

   set_attach(parent, "", {x=0,y=0,z=0}, {x=0,y=0,z=0})

   set_detach()

   set_bone_position("", {x=0,y=0,z=0}, {x=0,y=0,z=0})

Lua Entity

Each LuaEntitySAO object is backed by a Lua entity copied from the prototype definition given to minetest.register_entity(...). This Lua entity is the place where a mod should store the data and methods it uses to implement custom entities.

The Lua entity's properties are initialized from the prototype's properties. In addition it has the following added properties:

   name — The registered name passed to minetest.register_entity(...).

   object — Reference back to the LuaEntitySAO object.

The Lua entity object may be obtained from the LuaEntitySAO using get_luaentity().

Lua Entity Properties

User code may include arbitrary fields and methods in the Lua entity by adding them to the prototype. Runtime values may then be set for each instance individually inside the on_activate(self, staticdata) callback (see below) or by the code causing the entity to be spawned. The following properties are treated specially by the engine if included:

   initial_properties — Initial values for the ObjectRef properties (hp_max, physical, collisionbox, etc.).

   on_activate(self, staticdata) — Callback method called by the engine when a new entity is instantiated (spawned) using minetest.add_entity(...) or re-instantiated after the object is deactivated.

      staticdata — String obtained from get_staticdata() when the entity is saved for later re-instantiation. For a newly created entity (i.e. created using minetest.add_entity(...)), this is the empty string (not nil).

   on_step(self, dtime) — Callback method called every server tick.

      dtime — time since last call (usually 0.05 seconds)

   on_punch(self, puncher, time_from_last_punch, tool_capabilities, dir) — Called by the engine when somebody punches the object. Note that you probably want to handle most punches using the automatic armor group system (See Entity Damage below).

      puncher — An ObjectRef or nil.

      time_from_last_punch — Can be used to calculate damage. Can be nil.

      tool_capabilities — Capability table of used tool. Can be nil.

      dir — Unit vector in the direction of the punch. Points from the puncher to the entity, and is always defined.

   on_rightclick(self, clicker) — Callback method called when entity is right-clicked by player.

   get_staticdata(self) — Used to serialize the entity state when the entity is being deactivated. It must return a string, and this string will be passed to on_activate(self, staticdata) when the entity is re-instantiated.

Entity Damage

By default damage to entities is handled automatically by the engine in a way that is designed to be generic enough to mix use of tools both to dig nodes and act as weapons against entities. This relies heavily on the Groups mechanism. For a tool to damage an entity, the tool's capabilities must specify that it can damage things belonging to a group that the entity has a rating for (the armor_groups field). For example, in the default game living things usually have a rating from 1 to 3 in the "fleshy" group, and a weapon will specify that it can damage "fleshy" things, whereas a shovel can only dig/damage "crumbly" things.

The way the amount of damage is actually determined is by calculating how many nodes with the matching group the tool could dig in the time between swings (with the initial and maximum time being the tool's "full punch interval"), and applying this directly as hit point loss (TODO: figure out what happens when MULTIPLE groups match; is the best one taken, or are results added, or...?). This calculation is done based on the entity's rating in the matching group, with lower values representing the toughest/least damaged nodes/entities. It is also influenced by some special group ratings for the entity:

To punch an entity or object programmatically, call ObjectRef:punch(...). This ties in with the automatic damage mechanism and entity on_punch(...) callback, whereas a simple HP adjustment using ObjectRef:set_hp(...) does not.

For details about the automatic damage and dig time calculations, see the "lua_api.txt" file included with the game's documentation.

For example Lua entity code see the "item_entity.lua" file included with the game. This file implements the "__builtin:item" entity type, which is used by the game for items dropped on the ground (e.g. when leaves drop saplings or a player drops an item instead of using it to build a node).


ObjectRef

Moving things in the game are generally these (basically reference to a C++ ServerActiveObject).

Note that all ObjectRefs except player are actually LuaEntitySAO.

Methods

   getpos() — returns {x=num, y=num, z=num}.

   get_armor_groups() - Returns {group1=rating, group2=rating, ...})

      Note: Documented in lua_api.txt but not yet implemented as of version 0.4.4

   get_hp() — returns number of hitpoints (2 * number of hearts).

   get_inventory() — returns the InvRef of the object.

   get_wielded_item() — returns the wielded item (ItemStack). This is essentially just a pseudonym for object:get_inventory():get_stack(object:get_wield_list(), object:get_wield_index()) so please note the caveats for inventory manipulation (changes will need to be "committed" by calling object:set_wielded_item(modifiedStack) after modifying the stack unless they are done in the context of a callback that implicitly modifies the stack; see minetest.register_node#on_use).

   get_wield_index() — returns the index of the wielded item

   get_wield_list() — returns the name of the inventory list the wielded item is in

   moveto(pos, continuous=false) — interpolated move

   punch(puncher, time_from_last_punch, tool_capabilities, direction)

      puncher — an another ObjectRef

      time_from_last_punch — time since last punch action of the puncher

      direction: can be nil

   remove() — remove object (after returning from Lua)

   right_click(clicker)

      clicker — another ObjectRef

   setpos(pos)

      pos — position

   set_armor_groups({group1=rating, group2=rating, ...})

   set_hp(hp) — set number of hitpoints (2 * number of hearts)

   set_properties({object property table})

   set_wielded_item(item) — replaces the wielded item, returns true if successful

   set_animation({x=1,y=1}, frame_speed=15, frame_blend=0)

   set_attach(parent, "", {x=0,y=0,z=0}, {x=0,y=0,z=0})

   set_detach()

   set_bone_position("", {x=0,y=0,z=0}, {x=0,y=0,z=0})

Object property table

{ hp_max = 1, physical = true, weight = 5, collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5}, visual = "cube"/"sprite"/"upright_sprite"/"mesh"/"wielditem", 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, }

"cube"/"sprite"/"upright_sprite"/"mesh"/"wielditem":

   cube:

      a simple cube, like a default node.

   sprite:

      - Flat texture

      - Always looks at you (like the dropped items in 0.4.9)

   upright_sprite:

      - Used for 2D-characters,

      - You can go around it like a normal player

      - Looks like a standing paper

   mesh:

      - Visuals are defined with a mesh(-file)

   wielditem

      similar to a wielded or dropped item; is like upright_sprite, but extruded.

This article is incomplete.


override_item

minetest.override_item(name, redefinition)

(Available in 0.4.10+)

Overrides fields of an item registered with minetest.register_node / minetest.register_tool / minetest.register_craftitem. Item must already be defined, (opt)depend on the mod defining it.

Example

minetest.override_item("default:mese", { light_source = LIGHT_MAX, groups = {unbreakable=1}, })


register_abm

minetest.register_abm(abm_defintion_table)

The Active Block Modifier consists of a function that is executed at a specific interval for single nodes.

abm_defintion_table is a table which can contain following fields: nodenames, neighbors, interval, chance, action

   nodenames is a list of the nodenames that should execute the function. "group:groupname" is also possible.

   neighbors is a list of nodenames. At least one of these nodes has to be near node that executes the function (can be nil). "group:groupname" is also possible.

   interval is the interval in seconds that specifies when the function is executed. Minimuim is 1.0.

   chance is the inverted chance for each node to execute the function.

   action is the function that is executed. The parameters are (pos, node, active_object_count, active_object_count_wider) The object counts are useful for preventing overcrowding of spawned entities.

      pos is the position of the node

      node is the node

      active_object_count is the amount of objects inside the node

      active_object_count is the amount of objects inside the node and its neighbours

abms only work in active chunks. When a player enters an old chunk, abm functions are called at once, though farming plants grow a lot slower if seldom someone enters the chunk because the plant only grows one time/abm function call

Example

minetest.register_abm({ nodenames = {"group:lava"}, neighbors = {"group:water"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name = "default:cobblestone"}) end, })


register_entity

minetest.register_entity(entity_name, entity_definition)

Registers a LuaEntity that can be spawned as a LuaEntitySAO using mineteset.env:add_entity(...).

   entity_name — The registered name of the entity, used as the hash key for minetest.regsitered_entities and as the name property of each instantiated LuaEntity.

   entity_definition — A table of LuaEntity properties.

This article is incomplete. This article is missing examples, feel free to add them.

Object property table

{ hp_max = 1, physical = true, weight = 5, collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5}, visual = "cube"/"sprite"/"upright_sprite"/"mesh"/"wielditem", 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, }


register_node

minetest.register_node("name", {node definition})

Registers a new node named "name". The node properties are specified in the Node definition (see below).

Note that the node is not "created" immediately; it is stored in the minetest.registered_nodes list to be processed when all the mods have been loaded.

The node definition is a regular Lua table:

minetest.registered_nodes[""].

Valid fields include:

   drawtype — Specifies how the game engine is to draw the node. See Node Drawtypes for more information.

   visual_scale — Specifies the scale at which the item is drawn when it is wielded. Default is 1.0 (normal scale). 2.0 is double, 0.5 is half, and so on.

   tiles — Specifies the textures used for the node's faces. It's an array (table) of either one or six elements. If only one texture is needed, it can be specified directly as a string instead of a table. The textures are specified as strings as either "texturename.png" or "texturename". The order of the textures is +Y, -Y, +X, -X, +Z, -Z. In English: top, bottom, right, left, front, back.

   special_tiles — Specifies certain textures used in things like texture animations. [This text needs further expansion]

   use_texture_alpha — Set this to true for the texture's alpha channel to be used.

   alpha — Alpha value (transparency) of the node, with 255 being fully opaque and 0 being fully transparent. Values in-between specify partial transparency. This only has an effect on liquid nodes.

   post_effect_color — Whenever a player is "inside" the node, the screen is tinted using this color. It is specified as a table with fields 'r', 'g', 'b', and 'a', which represent the Red, Green, and Blue components, and the effect transparency (Alpha). For example: { r=255, g=0, b=0, a=128 }.

   inventory_image — This texture will be used for every state except when placed in the world (i.e. it will be used in inventory and when dropped). If undefined (nil) an image will be automatically constructed from tiles.

   wield_image — The texture to display in place of the hand texture when the node is wielded. If undefined (nil), the inventory image will be used.

   paramtype — Specifies what the node's param1 should hold. Possible values are:

      none — The engine does not use the param1 field, and it is free to be used for other purposes.

      light — The value stored in param1 is the light level with and without sun in it's upper and lower 4 bits respectively.

   paramtype2 — Specifies what the node's param2 should hold. Possible values are:

      wallmounted — param2 field contains the wall to which this node is "mounted". See minetest.dir_to_wallmounted(dir).

      facedir — param2 field contains the node's facing direction. Required to be able to orient nodes depending on the direction the player is facing. minetest.dir_to_facedir(dir).

   is_ground_content — If true, caves will carve through this

   sunlight_propagates — If true, sunlight will go infinitely through this

   walkable — If true, objects collide with node

   pointable — If true, can be pointed at

   diggable — If false, can never be dug

   climbable — If true, can be climbed on (ladder)

   buildable_to — If true, placed nodes can replace this node

   drop — alternatively drop = { max_items = ..., items = { ... } }

   liquidtype — "none"/"source"/"flowing"

   liquid_alternative_flowing — Flowing version of source liquid

   liquid_alternative_source — Source version of flowing liquid

   liquid_viscosity — Higher viscosity means slower flow (max. 7)

   liquid_renewable — If true, when placing two or more sources so that there's air between them, a new liquid source will be created.

   light_source — Amount of light emitted by node, where 0 is no light, and 14 is sunlight-like light.

   damage_per_second — If player is inside node, this damage is caused. This is used for example, by lava.

   node_box — See Node boxes

   selection_box — See Node boxes

   collision_box

   legacy_facedir_simple — Support maps made in and before January 2012

   legacy_wallmounted — Support maps made in and before January 2012

   sounds — A table that specifies which sound to play when some events occur. See SimpleSoundSpec for details. The following events are defined for nodes:

      footstep — Played when a player walks on the node.

      dig — Played while the player is digging the node. If it is "__group" is specified as value, it uses the group-based sound. [This text needs further expansion]

   dug — Played when the player finishes digging the node.

Wield Image Transparency

When an inventory image or explicit wield image is selected by the engine to display in first-person view on the client, some processing is done to actually display it on the screen. The game takes the rightmost pixels in the image that are not 100% transparent (alpha=0) and duplicates them several times to the right to give the image a "3D" appearance. This can cause artifacts if those right-most pixels are partially transparent, or if anti-aliasing results in some of the pixels being partially transparent.

However, you can use a trick to effectively turn this feature off: add some pixels of your own to the right of all "real" pixels in your image, and make them very close to fully transparent (alpha=1 when alpha ranges from 0 to 255, or alpha=0.005 when alpha ranges from 0.0 to 1.0, or alpha = 0.5% when alpha ranges from 0% to 100%; alpha and opacity are generally interchangeable terms in image editors, so setting the opacity of a layer in GIMP to 0.5% accomplishes this for all fully opaque pixels in the layer). This will cause these buffer pixels, which are generally invisible to the eye, to be duplicated instead of the "real" pixels of your image. This will allow you to have full control over the wielded item images and even use anti-aliasing for them.

Use Texture Alpha Channel

Must be used with a drawtype that does not perform backface culling.

There are currently two known, difficult-to-solve issues with this feature.

With shaders enabled, the faces of other transparent nodes are sometimes not drawn, depending on viewing angle. This is most noticable when a liquid is behind a node that uses the texture's alpha channel.

With shaders disabled, transparent objects farther away from the camera that should be occluded will be drawn over the node with this attribute. This is caused by the lack of transparency sorting, and is also the cause of water being drawn in front of clouds.

Primary Callbacks

When the following methods are defined in the node definition, the core engine will call them as callback methods as a result of direct events in the game such as a player punching the node or the node being added to the environment. Much of the default behavior of the game, such as adding a node to the environment when it is "placed", or adding an entity for an item when it is "dropped" can be replaced by overriding these callback methods. See src/scriptapi.cpp for more info.

on_construct

on_construct = function(pos)

Node Constructor. This function is called after putting the node in the world. It can be used to set up the node's metadata.

pos — Position of the new node

on_destruct

on_destruct = function(pos)

Node destructor. This function is called before removing the node.

pos — Position of the node being destroyed.

after_destruct

after_destruct = function(pos, oldnode)

Node destructor. This function is called after removing the node.

   pos — Position the destroyed node occupied.

   oldnode — A reference to the node that has been removed (TODO: verify this from C++ source; no documentation or examples are evident).

on_place

on_place = function(itemstack, placer, pointed_thing)

Called when a player places a node in-world. Returns itemstack modified according to the logic of the method (e.g. with one node removed from the count).

Default: Reference to minetest.item_place which:

   1. Checks whether the destination can be built to (contains no node or one with the buildable_to flag turned on).

   2. Sets param2 for "facedir" or "wallmounted" type nodes.

   3. Adds the node to the environment using minetest.add_node(...).

   4. Calls the after_place_node(...) and game-wide on_placement (see minetest.register_on_placenode) callbacks.

   5. Returns itemstack with one node removed.

Parameters are:

   itemstack — The ItemStack that contains the node being placed.

   placer — The Player object for the player placing the node.

   pointed_thing — The pointed_thing acting as a reference for where to place the node (i.e. what the player's crosshair is pointing at).

on_drop

on_drop = function(itemstack, dropper, pos)

Called when a player drops a node item (as in drops its stack on the ground--with the Q button by default--not placing it in-world as a node). Returns itemstack modified according to the logic of the method (e.g. emptied of all contents).

Default: Reference to minetest.item_drop which calculates a point 1m in front of the camera, places an item entity (type "__builtin:item") there using minetest.add_item(...), and gives it a small "push" away from the camera using LuaEntitySAO.setvelocity(...).

   itemstack — The ItemStack that contains the node being dropped.

   dropper — The Player object for the player dropping the node.

   pos — The position of the player dropping the node item. Note that this is not the place where the item is dropped in-world; it is up to this method to calculate that based on factors like which way the player is looking.

on_use

on_use = function(itemstack, user, pointed_thing)

Called when player wields and uses the node item. Returns itemstack modified according to the logic of the method, or nil if no item is to be removed from inventory.

Default: nil (not called)

   itemstack — The ItemStack that contains the node being used.

   user — The Player object for the player using the node item.

   pointed_thing — The pointed_thing acting as a reference for where the player's crosshair is pointing.

on_punch

on_punch = function(pos, node, puncher, pointed_thing)

Called when node is punched by player or using minetest.punch_node(...).

Default: Reference to minetest.node_punch(pos, node, puncher, pointed_thing), which calls minetest.register_on_punchnode() callbacks.

   pos — Position of the node being punched.

   node — Copy of the node being punched.

   puncher — Reference to an object indicating who or what is punching the node.

   pointed_thing — Copy of pointed_thing (only in 0.4.10+).

on_dig

on_dig = function(pos, node, digger)

Called when node is dug by player or using minetest.dig_node(...).

Default: Reference to minetest.node_dig(pos, node, digger), which:

   1. Checks node.diggable and calls can_dig(pos, digger) (if defined).

   2. Adds wear to the digger's wielded item, if any.

   3. Handles node drops.

   4. Removes the node from the environment with minetest.remove_node(pos).

   5. Calls after_dig_node (if defined) and game-wide on_dignodes (see minetest.register_on_dignode) callbacks.

Parameters are:

   pos — Position of the node being punched.

   node — Reference to the node being dug.

   digger — Reference to an ObjectRef indicating who or what doing the digging.

on_timer

on_timer = function(pos, elapsed)

Called by node timers. Should return a boolean indicating whether to run the timer for another cycle using the same timeout value.

   pos — Position of the node for which the timer has elapsed.

   elapsed — Total time that has passed since the timer was started.

on_receive_fields

on_receive_fields = function(pos, formname, fields, sender)

Called when a UI form on a node (e.g. sign text input) returns data. See formspec and NodeMetaRef.

   pos — Position of the node whose form fields are submitted.

   formname — (TODO: Check meaning and use, because its only used by minetest.show_formspec(playername, formname, formspec) and minetest.register_on_player_receive_fields(func(player, formname, fields)))

   fields — The names and values of the form's fields, as a table: {name1 = value1, name2 = value2, ...}

   sender — Reference to a Player object indicating who submitted the form.

allow_metadata_inventory_move

allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)

Called when a player attempts to move an item or items from one inventory slot to another within the node's inventory. Should return the actual number of items allowed to move from 0 (if the move is not allowed) to count (if all items may be moved), inclusive.

Example: Used by locked chests to ensure only the owner can modify them.

   pos — The position of the node whose inventory is being modified.

   from_list — The inventory list from which the item or items are being moved (e.g. "fuel", "dst", or "src" for a furnace in the default game).

   from_index — The index of the slot from which the item or items are being moved within from_list.

   to_list — The inventory list to which the item or items are being moved (e.g. "fuel", "dst", or "src" for a furnace in the default game).

   to_index — The index of the slot to which the item or items are being moved within to_list.

   count — The number of items the player is attempting to move.

   player — The player attempting to modify the node inventory.

allow_metadata_inventory_put

allow_metadata_inventory_put = function(pos, listname, index, stack, player)

Called when a player attempts to move an item or items into the node's inventory from another inventory (e.g. the player's own inventory). Should return either -1 to allow all items to be moved but leave the node inventory unchanged, or the actual number of items allowed to move from 0 (if the move is not allowed) to count (if all items may be moved), inclusive.

Example: Used by locked chests to ensure only the owner can modify them.

   pos — The position of the node whose inventory is being modified.

   listname — The inventory list to which the item or items are being moved (e.g. "fuel", "dst", or "src" for a furnace in the default game).

   index — The index of the slot to which the item or items are being moved within listname.

   stack — Reference to an ItemStack describing what player is attempting to move.

   player — The player attempting to modify the node inventory.

allow_metadata_inventory_take

allow_metadata_inventory_take = function(pos, listname, index, stack, player)

Called when a player attempts to move an item or items out of the node's inventory to another inventory (e.g. the player's own inventory). Should return either -1 to allow all items to be moved but leave the node inventory unchanged (copy items out), or the actual number of items allowed to move from 0 (if the move is not allowed) to count (if all items may be moved), inclusive.

Example: Used by locked chests to ensure only the owner can modify them.

   pos — The position of the node whose inventory is being modified.

   listname — The inventory list from which the item or items are being moved (e.g. "fuel", "dst", or "src" for a furnace in the default game).

   index — The index of the slot from which the item or items are being moved within listname.

   stack — Reference to an ItemStack describing what player is attempting to move.

   player — The player attempting to modify the node inventory.

on_metadata_inventory_move

on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)

Callback called after a player has moved an item or items from one inventory slot to another within the node's inventory. Called after allow_metadata_inventory_move(pos, from_list, from_index, to_list, to_index, count, player) if the inventory move is allowed, with identical arguments except for a count updated to reflect the actual allowed number of items.

on_metadata_inventory_put

on_metadata_inventory_put = function(pos, listname, index, stack, player)

Callback called after a player has moved an item or items into the node's inventory from another inventory (e.g. the player's own inventory). Called after allow_metadata_inventory_put(pos, listname, index, stack, player) if the inventory move is allowed, with identical arguments except for a stack updated to reflect the actual allowed number of items.

on_metadata_inventory_take

on_metadata_inventory_take = function(pos, listname, index, stack, player)

Callback called after a player has moved an item or items out of the node's inventory to another inventory (e.g. the player's own inventory). Called after allow_metadata_inventory_take(pos, listname, index, stack, player) if the inventory move is allowed, with identical arguments except for a stack updated to reflect the actual allowed number of items.

Secondary Callbacks

Rather than being used by the core game engine itself the following callbacks are called indirectly by the default implementations of the above primary callbacks, so installing a callback for the primary events may result in these methods not being called. For example, if you implement on_place with a custom event handler callback, then after_place_node will not be called unless you explicitly call it, since it is the default on_place callback (minetest.item_place) that calls after_place_node. The default implementation of these secondary callbacks for a new node type does nothing (though several node types used by the default game mods do install behavior; e.g. chests). This means overriding them for your custom node simply adds new behavior instead of replacing existing default behavior. See builtin/item.lua for more info.

after_place_node

after_place_node = function(pos, placer, itemstack, pointed_thing)

Called after constructing node when node was placed using minetest.item_place_node(...) / minetest.place_node(...) (for example, locked chests use this to determine the owner).

Return a true value to indicate modification of itemstack (if any) has been handled by the callback. Otherwise (return nothing, false, or nil) the caller will remove one item from itemstack. Note that it is not generally possible for one global on_placenode callback to know what values were returned by others or by this callback (one should thus be careful to avoid double-removal of items).

   pos — Position of the new node.

   placer — Reference to an object.

   itemstack — Reference to wielded ItemStack.

   pointed_thing — Copy of the pointed_thing (only in 0.4.10+).

can_dig

can_dig = function(pos, player)

Called by minetest.node_dig(...) / minetest.node_dig(...) to determine if player can dig the node in its current state. Returns a boolean (true if node can be dug).

Example: Chests and furnaces use this to allow digging only if they are empty.

   pos — Position of the node to be dug.

   player — Reference to an object indicating who or what is trying to dig the node.

after_dig_node

after_dig_node = function(pos, oldnode, oldmetadata, digger)

Called after node is destroyed as a result of minetest.node_dig(...) / minetest.node_dig(...).

   pos — Position of node that was dug.

   oldnode — Copy of old node

   oldmetadata — Copy of old metadata in table format.

   digger — Reference to an object.

on_rightclick

on_rightclick = function(pos, node, player, itemstack, pointed_thing)

When defined (not nil), this method is called by minetest.on_place(...) instead of minetest.item_place_node(...). Returns itemstack modified according to the logic of the method (e.g. with one node removed from the count). (New in 0.4.5)

Default: nil (not defined; try to place a node instead)

   pos — Position of the node that was right-clicked on.

   node — Node that was right-clicked on.

   player — Reference to the Player who right-clicked on the node.

   itemstack — The item (stack) wielded by the player when right-clicking.

   pointed_thing pointed_thing. Can be nil if called by a mod (only in 0.4.10+).

Unclassified Callbacks

These callbacks have been mentioned very briefly in the game documentation (e.g. in lua_api.txt), but few details are available other than a hint at their design and purpose, so it is unknown where they fit in the scheme of engine vs. mod code.

on_blast

on_blast = function(pos, intensity)

If defined, called when an explosion touches the node, instead of removing the node. It does not have any use in the engine yet, but should be used by mods.

   pos — The position of the node being affected the the explosion.

   intensity — Describes the intensity of the blast affecting the node. According the lua_api.txt: 1.0 = mid range of regular TNT

Example

minetest.register_node("default:stone", { description = "Stone", tiles = {"default_stone.png"}, is_ground_content = true, groups = {cracky=3, stone=1}, drop = 'default:cobble', legacy_mineral = true, sounds = default.node_sound_stone_defaults(), })

This article is incomplete.


register_tool

minetest.register_tool(name, tool_definition)

   name The name of the tool, for example: tutorial:decowood_pick.

   tool_definition A table of values defining the tool.

Registers a tool, examples are picks, axes, swords, and shovels.

Example:

minetest.register_tool("tutorial:decowood_pick", { description = "Decowood Pickaxe", inventory_image = "tutorial_decowood_pick.png", tool_capabilities = { max_drop_level=3, groupcaps= { cracky={times={[1]=4.00, [2]=1.50, [3]=1.00}, uses=70, maxlevel=1} } } })


sound_play

minetest.sound_play(SimpleSoundSpec, SoundParameters)

Plays a sound.

Only OGG files are supported. For positional playing of sounds, only single-channel (mono) files are supported. Otherwise OpenAL will play them non-positionally.

SimpleSoundSpec can be a string with the filename (without the file extention) or a table with the fields name="name" and gain=float.

SoundParameters is a table with the following fields:

gain = float: the gain. default = 1.0

max_hear_distance = int: the maximum hear distance. default = 32

loop = bool: Sound is looped. Only sounds connected to objects can be looped. default = false

The location can be specified with one of the following fields in the SoundParameters (if none is used, its played locationless to all players):

to_player = "playername": Sound is played locationless to the player

pos = position: Sound is played at this position

object = ObjectRef: Sound is played connected to the object

The function returns a sound handle that can be passed to minetest.sound_stop(handle) to stop the sound.

You can play random sound using filename convention modname_soundname.N.ogg (see examples)

Examples

To play the sound "testmod_testsound.ogg" at position 0,0,0:

minetest.sound_play("testmod_testsound", { pos = {x=0, y=0, z=0}, max_hear_distance = 100, gain = 10.0, })

To play the sound "testmod_foobar.ogg" to player "foo":

minetest.sound_play("testmod_foobar", { to_player = "foo", gain = 2.0, })

To play a sound selected at random from the files with basename "testmod_foobar":

-- testmod/sounds listing: -- /testmod_foobar.1.ogg -- /testmod_foobar.2.ogg -- /testmod_foobar.3.ogg minetest.sound_play("testmod_foobar")




Minetest Lua Modding API Reference 0.4.11

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.

A mod is a self-contained bunch of scripts, textures and other related things that is loaded by and interfaces with Minetest.

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 .

Programming in Lua

If you have any difficulty in understanding this, please read:

http://rubenwardy.com/minetest_modding_book/lua_api.html

http://dev.minetest.net/Modding_Book/Lua_Scripts

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:

Windows:

$path_share: Linux:

Windows:

RUN_IN_PLACE=0: (Linux release)

$path_share: Linux: /usr/share/minetest

Windows: /minetest-0.4.x

$path_user: Linux: ~/.minetest

Windows: C:/users//AppData/minetest (maybe)

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 = e.g.

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/

In a run-in-place version (e.g. the distributed windows version):

minetest-0.4.x/games/gameid/mods/

minetest-0.4.x/mods/ <-- User-installed mods

minetest-0.4.x/worlds/worldname/worldmods/

On an installed version on Linux:

/usr/share/minetest/games/gameid/mods/

~/.minetest/mods/ <-- User-installed mods

~/.minetest/worlds/worldname/worldmods

Mod load path for world-specific games

It is possible to include a game in a world; in this case, no mods or games are loaded or checked from anywhere else.

This is useful for e.g. adventure worlds.

This happens if the following directory exists:

$world/game/

Mods should be then be placed in:

$world/game/mods/

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.

Mod directory structure

mods |-- modname -- depends.txt -- screenshot.png -- description.txt -- init.lua -- models -- textures | -- modname_stuff.png
-- modname_something_else.png -- sounds -- media |
--
-- another

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.

Optional dependencies can be defined by appending a question mark to a single modname. Their meaning is that if the specified mod is missing, that does not prevent this mod from being loaded.

screenshot.png:

A screenshot shown in modmanager within mainmenu.

description.txt:

File containing description to be shown within mainmenu.

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.

minetest.setting_get(name) and minetest.setting_getbool(name) can be used to read custom or existing settings at load time, if necessary.

models:

Models for entities or meshnodes.

textures, sounds, media:

Media files (textures, sounds, whatever) that will be transferred to the

client and will be available for use by the mod.

Naming convention for registered textual names

Registered names should generally be in this format:

"modname:" ( can have characters a-zA-Z0-9_)

This is to prevent conflicting names from corrupting maps and is enforced by the mod loader.

Example: mod "experimental", ideal item/node/entity name "tnt":

-> the name should be "experimental:tnt".

Enforcement can be overridden by prefixing the name with ":". This can be used for overriding the registrations of some other mod.

Example: Any mod can redefine experimental:tnt by using the name

":experimental:tnt" when registering it. (also that mod is required to have "experimental" as a dependency)

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, e.g. 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_, e.g. given the mod name "foomod", a texture could be called

"foomod_foothing.png"

Textures are referred to by their complete name, or alternatively by stripping out the file extension:

e.g. foomod_foothing.png

e.g. foomod_foothing

Texture modifiers

There are various texture modifiers that can be used to generate textures on-the-fly.

Texture overlaying:

Textures can be overlaid by putting a ^ between them.

Example: default_dirt.png^default_grass_side.png

default_grass_side.png is overlayed over default_dirt.png

Texture grouping:

Textures can be grouped together by enclosing them in ( and ).

Example: cobble.png^(thing1.png^thing2.png)

A texture for 'thing1.png^thing2.png' is created and the resulting

texture is overlaid over cobble.png.

Advanced texture modifiers:

[crack:n:p

n = animation frame count, p = current animation frame

Draw a step of the crack animation on the texture.

Example: default_cobble.png^[crack:10:1

[combine:WxH:x1,y1=file1:x2,y2=file2 W = width, x is a literal character 'x', H = height, x1/x2 = x position, y1/y1 = y position, file1/file2 = texture to combine Create a texture of size w * h and blit file1 to (x1,y1) and blit file2 to (x2,y2). Example: [combine:16x32:0,0=default_cobble.png:0,16=default_wood.png

[brighten Brightens the texture. Example: tnt_tnt_side.png^[brighten

[noalpha Makes the texture completely opaque. Example: default_leaves.png^[noalpha

[makealpha:r,g,b Convert one color to transparency. Example: default_cobble.png^[makealpha:128,128,128

[transformt t = transformation(s) to apply Rotates and/or flips the image. t can be a number (between 0 and 7) or a transform name. Rotations are counter-clockwise. 0 I identity 1 R90 rotate by 90 degrees 2 R180 rotate by 180 degrees 3 R270 rotate by 270 degrees 4 FX flip X 5 FXR90 flip X then rotate by 90 degrees 6 FY flip Y 7 FYR90 flip Y then rotate by 90 degrees Example: default_stone.png^[transformFXR90

[inventorycube{top{left{right '^' is replaced by '&' in texture names Create an inventory cube texture using the side textures. Example: [inventorycube{grass.png{dirt.png

grass_side.png{dirt.png

grass_side.png Creates an inventorycube with 'grass.png', 'dirt.png^grass_side.png' and 'dirt.png^grass_side.png' textures

[lowpart:percent:file Blit the lower percent% part of file on the texture: Example: base.png^[lowpart:25:overlay.png

[verticalframe:t:n t = animation frame count, n = current animation frame Crops the texture to a frame of a vertical animation. Example: default_torch_animated.png^[verticalframe:16:8

[mask:file Apply a mask to the base image. The mask is applied using binary AND.

[colorize:color Colorize the textures with given color color as ColorString

Sounds ~~~~~~

Only OGG Vorbis files are supported.

For positional playing of sounds, only single-channel (mono) files are supported. Otherwise OpenAL will play them non-positionally.

Mods should generally prefix their sounds with modname_, e.g. 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.

When playing the sound "foomod_foosound", the sound is chosen randomly from the available ones of the following files:

foomod_foosound.ogg

foomod_foosound.0.ogg

foomod_foosound.1.ogg

...

foomod_foosound.9.ogg

Examples of sound parameter tables: — Play location-less on all clients {

gain = 1.0, — default } — Play location-less to a player {

to_player = name,

gain = 1.0, — default } — Play in a location {

pos = {x=1,y=2,z=3},

gain = 1.0, — default

max_hear_distance = 32, — default } — Play connected to an object, looped {

object = ,

gain = 1.0, — default

max_hear_distance = 32, — default

loop = true, — only sounds connected to objects can be looped }

SimpleSoundSpec: e.g. "" e.g. "default_place_node" e.g. {} e.g. {name="default_place_node"} e.g. {name="default_place_node", gain=1.0}

Registered definitions of stuff

Anything added using certain minetest.register_* functions get added to the global minetest.registered_* tables.

minetest.register_entity(name, prototype table)

-> minetest.registered_entities[name]

minetest.register_node(name, node definition)

-> minetest.registered_items[name]

-> minetest.registered_nodes[name]

minetest.register_tool(name, item definition)

-> minetest.registered_items[name]

minetest.register_craftitem(name, item definition)

-> minetest.registered_items[name]

Note that in some cases you will stumble upon things that are not contained in these tables (e.g. 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:

local function get_nodedef_field(nodename, fieldname)

if not minetest.registered_nodes[nodename] then

return nil

end

return minetest.registered_nodes[nodename][fieldname] end local drawtype = get_nodedef_field(nodename, "drawtype")

Example: minetest.get_item_group(name, group) has been implemented as:

function minetest.get_item_group(name, group)

if not minetest.registered_items[name] or not

minetest.registered_items[name].groups[group] then

return 0

end

return minetest.registered_items[name].groups[group] end

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.

The definition of a node is stored and can be accessed by name in

minetest.registered_nodes[node.name] See "Registered definitions of stuff".

Nodes are passed by value between Lua and the engine. They are represented by a table:

{name="name", param1=num, param2=num}

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"

collision_box = {

type = "fixed",

fixed = {

{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},

},

},

^ defines list of collision boxes for the node. If empty, collision boxes

will be the same as nodeboxes, in case of any other nodes will be full cube

as in the example above.

Nodes can also contain extra data. See "Node Metadata".

Node drawtypes

There are a bunch of different looking node types.

Look for examples in games/minimal or games/minetest_game.

- normal - airlike - liquid - flowingliquid - glasslike - glasslike_framed - glasslike_framed_optional - allfaces - allfaces_optional - torchlike - signlike - plantlike - firelike - fencelike - raillike - nodebox — See below. EXPERIMENTAL - mesh — use models for nodes

*_optional drawtypes need less rendering time if deactivated (always client side)

Node boxes

Node selection boxes are defined using "node boxes"

The "nodebox" node drawtype allows defining visual of nodes consisting of arbitrary number of boxes. It allows defining stuff like stairs. Only the "fixed" and "leveled" box type is supported for these. ^ Please note that this is still experimental, and may be incompatibly

changed in the future.

A nodebox is defined as any of: {

— A normal cube; the default in most things

type = "regular" } {

— A fixed box (facedir param2 is used, if applicable)

type = "fixed",

fixed = box OR {box1, box2, ...} } {

— A box like the selection box for torches

— (wallmounted param2 is used, if applicable)

type = "wallmounted",

wall_top = box,

wall_bottom = box,

wall_side = box }

A box is defined as:

{x1, y1, z1, x2, y2, z2} A box of a regular node would look like:

{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},

type = "leveled" is same as "fixed", but y2 will be automatically set to level from param2

Meshes

If drawtype "mesh" is used tiles should hold model materials textures.

Only static meshes are implemented.

For supported model formats see Irrlicht engine documentation.

Noise Parameters

Noise Parameters, or commonly called NoiseParams, define the properties of perlin noise.

- offset

Offset that the noise is translated by (i.e. added) after calculation.

- scale

Factor that the noise is scaled by (i.e. multiplied) after calculation.

- spread

Vector containing values by which each coordinate is divided by before calculation.

Higher spread values result in larger noise features.

A value of {x=250, y=250, z=250} is common.

- seed

Random seed for the noise. Add the world seed to a seed offset for world-unique noise.

In the case of minetest.get_perlin(), this value has the world seed automatically added.

- octaves

Number of times the noise gradient is accumulated into the noise.

Increase this number to increase the amount of detail in the resulting noise.

A value of 6 is common.

- persistence

Factor by which the effect of the noise gradient function changes with each successive octave.

Values less than 1 make the details of successive octaves' noise diminish, while values

greater than 1 make successive octaves stronger.

A value of 0.6 is common.

- lacunarity

Factor by which the noise feature sizes change with each successive octave.

A value of 2.0 is common.

- flags

Leave this field unset for no special handling.

Currently supported are:

- defaults

Specify this if you would like to keep auto-selection of eased/not-eased while specifying

some other flags.

- eased

Maps noise gradient values onto a quintic S-curve before performing interpolation.

This results in smooth, rolling noise. Disable this ("noeased") for sharp-looking noise.

If no flags are specified (or defaults is), 2D noise is eased and 3D noise is not eased.

- absvalue

Accumulates the absolute value of each noise gradient result.

Noise parameters format example for 2D or 3D perlin noise or perlin noise maps:

np_terrain = {

offset = 0,

scale = 1,

spread = {x=500, y=500, z=500},

seed = 571347,

octaves = 5,

persist = 0.63,

lacunarity = 2.0,

flags = "defaults, absvalue"

}

^ A single noise parameter table can be used to get 2D or 3D noise,

when getting 2D noise spread.z is ignored.

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_threshold, 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 threshold, 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

See section Flag Specifier Format. 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

See section Flag Specifier Format. 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.

HUD element types

The position field is used for all element types. To account for differing resolutions, the position coordinates are the percentage of the screen, ranging in value from 0 to 1. The name field is not yet used, but should contain a description of what the HUD element represents. The direction field is the direction in which something is drawn. 0 draws from left to right, 1 draws from right to left, 2 draws from top to bottom, and 3 draws from bottom to top. The alignment field specifies how the item will be aligned. It ranges from -1 to 1, with 0 being the center, -1 is moved to the left/up, and 1 is to the right/down. Fractional values can be used. The offset field specifies a pixel offset from the position. Contrary to position, the offset is not scaled to screen size. This allows for some precisely-positioned items in the HUD. Note offset WILL adapt to screen dpi as well as user defined scaling factor! Below are the specific uses for fields in each type; fields not listed for that type are ignored.

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.

- size: If used will force full-image size to this value (override texture pack image size) - 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 - waypoint

Displays distance to selected world position.

- name: The name of the waypoint.

- text: Distance suffix. Can be blank.

- number: An integer containing the RGB value of the color used to draw the text.

- world_pos: World position of the waypoint.

Representations of simple things

Position/vector:

{x=num, y=num, z=num} For helper functions see "Vector helpers".

pointed_thing:

{type="nothing"}

{type="node", under=pos, above=pos}

{type="object", ref=ObjectRef}

Flag Specifier Format

Flags using the standardized flag specifier format can be specified in either of two ways, by string or table. The string format is a comma-delimited set of flag names; whitespace and unrecognized flag fields are ignored. Specifying a flag in the string sets the flag, and specifying a flag prefixed by the string "no" explicitly clears the flag from whatever the default may be. In addition to the standard string flag format, the schematic flags field can also be a table of flag names to boolean values representing whether or not the flag is set. Additionally, if a field with the flag name prefixed with "no" is present, mapped to a boolean of any value, the specified flag is unset.

e.g. A flag field of value

{place_center_x = true, place_center_y=false, place_center_z=true} is equivalent to

{place_center_x = true, noplace_center_y=true, place_center_z=true} which is equivalent to

"place_center_x, noplace_center_y, place_center_z" or even

"place_center_x, place_center_z" since, by default, no schematic attributes are set.

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

Items and item stacks can exist in three formats:

Serialized; This is called stackstring or itemstring: e.g. 'default:dirt 5' e.g. 'default:pick_wood 21323' e.g. 'default:apple'

Table format: e.g. {name="default:dirt", count=5, wear=0, metadata=""}

^ 5 dirt nodes e.g. {name="default:pick_wood", count=1, wear=21323, metadata=""}

^ a wooden pick about 1/3 worn out e.g. {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.

When an item must be passed to a function, it can usually be in any of these formats.

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 (e.g. 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".

object.get_armor_groups() -> a group-rating table (e.g. {fleshy=100}) object.set_armor_groups({fleshy=30, cracky=80})

Groups of tools

Groups in tools define which groups of nodes and entities they are effective towards.

Groups in crafting recipes

An example: Make meat soup from any meat, any water and any bowl {

output = 'food:meat_soup_raw',

recipe = {

{'group:meat'},

{'group:water'},

{'group:bowl'},

},

— preserve = {'group:bowl'}, — Not implemented yet (TODO) } An another example: Make red wool from white wool and red dye {

type = 'shapeless',

output = 'wool:red',

recipe = {'wool:white', 'group:dye,basecolor_red'}, }

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 e.g. a weapon of a lower level make much less

damage, and get worn 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

Known damage and digging time defining groups

- crumbly: dirt, sand - cracky: tough but crackable stuff like stone. - snappy: something that can be cut using fine tools; e.g. leaves, small

plants, wire, sheets of metal - choppy: something that can be cut using force; e.g. trees, wooden planks - fleshy: Living things like animals and the player. This could imply

some blood effects when hitting. - explody: Especially prone to explosions - oddly_breakable_by_hand:

Can be added to nodes that shouldn't logically be breakable by the

hand but are. Somewhat similar to dig_immediate, but times are more

like {[1]=3.50,[2]=2.00,[3]=0.70} and this does not override the

speed of a tool if the tool can dig at a faster speed than this

suggests for the hand.

Examples of custom groups

Item groups are often used for defining, well, //groups of items//. - meat: any meat-kind of a thing (rating might define the size or healing

ability or be irrelevant - it is not defined as of yet) - eatable: anything that can be eaten. Rating might define HP gain in half

hearts. - flammable: can be set on fire. Rating might define the intensity of the

fire, affecting e.g. the speed of the spreading of an open fire. - wool: any wool (any origin, any color) - metal: any metal - weapon: any weapon - heavy: anything considerably heavy

Digging time calculation specifics

Groups such as crumbly, cracky and snappy are used for this purpose. Rating is 1, 2 or 3. A higher rating for such a group implies faster digging time.

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 their properties by a list of parameters for groups. They cannot dig other groups; thus it is important to use a standard bunch of groups to enable interaction with tools.

Tools define:

Full punch interval: When used as a weapon, the tool will do full damage if this time is spent between punches. If e.g. half the time is spent, the tool will do half damage.

Maximum drop level Suggests the maximum level of node, when dug with the tool, that will drop it's useful item. (e.g. iron ore to drop a lump of iron). - This is not automated; it is the responsibility of the node definition

to implement this

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.

Damage groups List of damage for groups of entities. See "Entity damage mechanism".

Example definition of the capabilities of a tool

tool_capabilities = { full_punch_interval=1.5, max_drop_level=1, groupcaps={ crumbly={maxlevel=2, uses=20, times={[1]=1.60, [2]=1.20, [3]=0.80}} } damage_groups = {fleshy=2}, }

This makes the tool be able to dig nodes that fulfil both of these: - Have the crumbly group - Have a level group less or equal to 2

Table of resulting digging times: crumbly 0 1 2 3 4 <- level

-> 0 - - - - -

1 0.80 1.60 1.60 - -

2 0.60 1.20 1.20 - -

3 0.40 0.80 0.80 - -

level diff: 2 1 0 -1 -2

Table of resulting tool uses:

-> 0 - - - - -

1 180 60 20 - -

2 180 60 20 - -

3 180 60 20 - -

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

Entity damage mechanism

Damage calculation: damage = 0 foreach group in cap.damage_groups:

damage += cap.damage_groups[group] * limit(actual_interval / cap.full_punch_interval, 0.0, 1.0)

* (object.armor_groups[group] / 100.0)

— Where object.armor_groups[group] is 0 for inexistent values return damage

Client predicts damage based on damage groups. Because of this, it is able to give an immediate response when an entity is damaged or dies; the response is pre-defined somehow (e.g. by defining a sprite animation) (not implemented; TODO). - Currently a smoke puff will appear when an entity dies.

The group immortal completely disables normal damage.

Entities can define a special armor group, which is punch__operable. This group disables the regular damage mechanism for players punching it by hand or a non-tool item, so that it can do something else than take damage.

On the Lua side, every punch calls ''entity:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)''. This should never be called directly, because damage is usually not handled by the entity itself.

To punch an entity/object in Lua, call ''object:punch(puncher, time_from_last_punch, tool_capabilities, direction)''. 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".

Metadata contains two things: - A key-value store - An inventory

Some of the values in the key-value store are handled specially: - formspec: Defines a right-click inventory menu. See "Formspec". - infotext: Text shown on the screen when the node is pointed at

Example stuff:

local meta = minetest.get_meta(pos) meta:set_string("formspec",

"size[8,9]"..

"list[context;main;0,0;8,4;]"..

"list[current_player;main;0,5;8,4;]") meta:set_string("infotext", "Chest"); local inv = meta:get_inventory() inv:set_size("main", 8*4) print(dump(meta:to_table())) meta:from_table({

inventory = {

main = {[1] = "default:dirt", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "default:cobble", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "default:cobble", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "", [31] = "", [32] = ""}

},

fields = {

formspec = "size[8,9]list[context;main;0,0;8,4;]list[current_player;main;0,5;8,4;]",

infotext = "Chest"

} })

Formspec

Formspec defines a menu. Currently not much else than inventories are supported. It is a string, with a somewhat strange format.

Spaces and newlines can be inserted between the blocks, as is used in the examples.

Examples: - Chest:

size[8,9]

list[context;main;0,0;8,4;]

list[current_player;main;0,5;8,4;] - Furnace:

size[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

size[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[,,] ^ Define the size of the menu in inventory slots ^ fixed_size true/false (optional) ^ deprecated: invsize[,;]

list[;;,;,;] list[;;,;,;] ^ Show an inventory list

listcolors[;] ^ Sets background color of slots as ColorString ^ Sets background color of slots on mouse hovering

listcolors[;;] ^ Sets background color of slots as ColorString ^ Sets background color of slots on mouse hovering ^ Sets color of slots border

listcolors[;;;;] ^ Sets background color of slots as ColorString ^ Sets background color of slots on mouse hovering ^ Sets color of slots border ^ Sets default background color of tooltips ^ Sets default font color of tooltips

tooltip[;;,] ^ Adds tooltip for an element ^ tooltip background color as ColorString (optional) ^ tooltip font color as ColorString (optional)

image[,;,;] ^ Show an image ^ Position and size units are inventory slots

item_image[,;,;] ^ Show an inventory image of registered item/node ^ Position and size units are inventory slots

bgcolor[;] ^ Sets background color of formspec as ColorString ^ If true the background color is drawn fullscreen (does not effect the size of the formspec)

background[,;,;] ^ 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[,;,;;] ^ 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[,;,;;

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[;

textarea[,;,;;

label[,;

vertlabel[,;

button[,;,;;

image_button[,;,;;;

image_button[,;,;;;

item_image_button[,;,;;;

tooltip will be made out of its description

to override it use tooltip element ^ Position and size units are inventory slots

button_exit[,;,;;

image_button_exit[,;,;;;

textlist[,;,;;,,...,] ^ Scrollable item list showing arbitrary text elements ^ x and y position the itemlist relative to the top left of the menu ^ w and h are the size of the itemlist ^ name fieldname sent to server on doubleclick value is current selected element ^ listelements can be prepended by #color in hexadecimal format RRGGBB (only), ^ if you want a listelement to start with # write #

textlist[,;,;;,,...,;;] ^ Scrollable itemlist showing arbitrary text elements ^ x and y position the itemlist relative to the top left of the menu ^ w and h are the size of the itemlist ^ name fieldname sent to server on doubleclick value is current selected element ^ listelements can be prepended by #RRGGBB (only) in hexadecimal format ^ if you want a listelement to start with # write # ^ index to be selected within textlist ^ true/false draw transparent background ^ see also minetest.explode_textlist_event (main menu: engine.explode_textlist_event)

tabheader[,;;,,...,;;;] ^ show a tabHEADER at specific position (ignores formsize) ^ x and y position the itemlist relative to the top left of the menu ^ name fieldname data is transferred to Lua ^ caption 1... name shown on top of tab ^ current_tab index of selected tab 1... ^ transparent (optional) show transparent ^ draw_border (optional) draw border

box[,;,;] ^ 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 as ColorString

dropdown[,;;;,, ...,;] ^ show a dropdown field ^ IMPORTANT NOTE: There are two different operation modes: ^ 1) handle directly on change (only changed dropdown is submitted) ^ 2) read the value on pressing a button (all dropdown values are available) ^ x and y position of dropdown ^ width of dropdown ^ fieldname data is transferred to Lua ^ items to be shown in dropdown ^ index of currently selected dropdown item

checkbox[,;;

scrollbar[,;,;;;] ^ show a scrollbar ^ there are two ways to use it: ^ 1) handle the changed event (only changed scrollbar is available) ^ 2) read the value on pressing a button (all scrollbars are available) ^ x and y position of trackbar ^ width and height ^ orientation vertical/horizontal ^ fieldname data is transferred to lua ^ value this trackbar is set to (0-1000) ^ see also minetest.explode_scrollbar_event (main menu: engine.explode_scrollbar_event)

table[,;,;;,,...,;] ^ show scrollable table using options defined by the previous tableoptions[] ^ displays cells as defined by the previous tablecolumns[] ^ x and y position the itemlist relative to the top left of the menu ^ w and h are the size of the itemlist ^ name fieldname sent to server on row select or doubleclick ^ cell 1...n cell contents given in row-major order ^ selected idx: index of row to be selected within table (first row = 1) ^ see also minetest.explode_table_event (main menu: engine.explode_table_event)

tableoptions[;;...] ^ sets options for table[]: ^ color=#RRGGBB ^^ default text color (ColorString), defaults to #FFFFFF ^ background=#RRGGBB ^^ table background color (ColorString), defaults to #000000 ^ border= ^^ should the table be drawn with a border? (default true) ^ highlight=#RRGGBB ^^ highlight background color (ColorString), defaults to #466432 ^ highlight_text=#RRGGBB ^^ highlight text color (ColorString), defaults to #FFFFFF ^ opendepth= ^^ all subtrees up to depth < value are open (default value = 0) ^^ only useful when there is a column of type "tree"

tablecolumns[,,,...;,,;...] ^ sets columns for table[]: ^ types: text, image, color, indent, tree ^^ text: show cell contents as text ^^ image: cell contents are an image index, use column options to define images ^^ color: cell contents are a ColorString and define color of following cell ^^ indent: cell contents are a number and define indentation of following cell ^^ tree: same as indent, but user can open and close subtrees (treeview-like) ^ column options: ^^ align= for "text" and "image": content alignment within cells ^^ available values: left (default), center, right, inline ^^ width= for "text" and "image": minimum width in em (default 0) ^^ for "indent" and "tree": indent width in em (default 1.5) ^^ padding= padding left of the column, in em (default 0.5) ^^ exception: defaults to 0 for indent columns ^^ tooltip= tooltip text (default empty) ^ "image" column options: ^^ 0= sets image for image index 0 ^^ 1= sets image for image index 1 ^^ 2= sets image for image index 2 ^^ and so on; defined indices need not be contiguous ^^ empty or non-numeric cells are treated as 0 ^ "color" column options: ^^ span= number of following columns to affect (default infinite)

Note: do NOT use a element name starting with "key_" those names are reserved to pass key press events to formspec!

Inventory location:

- "context": Selected node metadata (deprecated: "current_name") - "current_player": Player to whom the menu is shown - "player:": Any player - "nodemeta:,,": Any node metadata - "detached:": A detached inventory

ColorString

#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

Named colors are also supported and are equivalent to "CSS Color Module Level 4" (http://dev.w3.org/csswg/css-color/#named-colors). To specify the value of the alpha channel, append AA to the end of the color name (e.g. colorname08). For named colors the hexadecimal string representing the alpha value must (always) be two hexadecimal digits.

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.apply(v, func) -> vector vector.equals(v1, v2) -> bool For the following functions 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.

Useful for distance calculation. math.sign(x, tolerance) ^ Get the sign of a number

Optional: Also returns 0 when the absolute value is within the tolerance (default 0) string:split(separator) ^ e.g. string:split("a,b", ",") = {"a","b"} string:trim() ^ e.g. 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. Returns nil if the string can't be parsed to a position. minetest.formspec_escape(string) -> string ^ escapes characters [ ] \ , ; that can not be used in formspecs minetest.is_yes(arg) ^ returns whether arg can be interpreted as yes minetest.get_us_time() ^ returns time with microsecond precision table.copy(table) -> table ^ returns a deep copy of a table

minetest namespace reference

Utilities: minetest.get_current_modname() -> string minetest.get_modpath(modname) -> e.g. "/home/user/.minetest/usermods/modname" ^ Useful for loading additional .lua modules or static data from mod minetest.get_modnames() -> list of installed mods ^ Return a list of installed mods, sorted alphabetically minetest.get_worldpath() -> e.g. "/home/user/.minetest/world" ^ Useful for storing custom data minetest.is_singleplayer() minetest.features ^ table containing API feature flags: {foo=true, bar=true} minetest.has_feature(arg) -> bool, missing_features ^ arg: string or table in format {foo=true, bar=true} ^ missing_features: {foo=true, bar=true} minetest.get_player_information(playername) ^ table containing information about player peer: { 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    -- following information is available on debug build only!!! -- DO NOT USE IN MODS --ser_vers = 26, -- serialization version used by client --prot_vers = 23, -- protocol 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 }

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) 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=LIGHT_MAX})

Global callback registration functions: (Call these only at load time) minetest.register_globalstep(func(dtime)) ^ Called every server step, usually interval of 0.1s minetest.register_on_shutdown(func()) ^ 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(func(pos, newnode, placer, oldnode, itemstack, pointed_thing)) ^ Called when a node has been placed ^ If return true no item is taken from itemstack ^ Not recommended; use on_construct or after_place_node in node definition ^ whenever possible minetest.register_on_dignode(func(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(func(pos, node, puncher, pointed_thing)) ^ Called when a node is punched minetest.register_on_generated(func(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(func(ObjectRef)) ^ Called after a new player has been created minetest.register_on_dieplayer(func(ObjectRef)) ^ Called when a player dies minetest.register_on_respawnplayer(func(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(func(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(func(ObjectRef)) ^ Called when a player joins the game minetest.register_on_leaveplayer(func(ObjectRef)) ^ Called when a player leaves the game minetest.register_on_cheat(func(ObjectRef, cheat)) ^ Called when a player cheats ^ cheat: {type="moved_too_fast"/"interacted_too_far"/"finished_unknown_dig"/"dug_unbreakable"/"dug_too_fast"} minetest.register_on_chat_message(func(name, message)) ^ Called always when a player says something minetest.register_on_player_receive_fields(func(player, formname, fields)) ^ Called when a button is pressed in player's inventory form ^ Newest functions are called first ^ If function returns true, remaining functions are not called minetest.register_on_mapgen_init(func(MapgenParams)) ^ Called just before the map generator is initialized but before the environment is initialized ^ MapgenParams consists of a table with the fields mgname, seed, water_level, and flags minetest.register_on_craft(func(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(func(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_on_protection_violation(func(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(func(hp_change, replace_with_item, itemstack, user, pointed_thing)) ^ Called when an item is eaten, by minetest.item_eat ^ Return true or itemstack to cancel the default item eat response (ie: hp increase)

Other registration functions: minetest.register_chatcommand(cmd, chatcommand definition) minetest.register_privilege(name, definition) ^ definition: "description text" ^ definition: {

description = "description text",

give_to_singleplayer = boolean, — default: true

} minetest.register_authentication_handler(handler) ^ See minetest.builtin_auth_handler in builtin.lua for reference

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)

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.swap_node(pos, node) ^ Set node at position, but don't remove metadata 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

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.get_meta(pos) — Get a NodeMetaRef at that position minetest.get_node_timer(pos) — Get NodeTimerRef

minetest.add_entity(pos, name): 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) minetest.set_timeofday(val): val: 0...1; 0 = midnight, 0.5 = midday minetest.get_timeofday() minetest.get_gametime(): returns the time, in seconds, since the world was created minetest.find_node_near(pos, radius, nodenames) -> pos or nil ^ nodenames: e.g. {"ignore", "group:tree"} or "default:dirt" minetest.find_nodes_in_area(minp, maxp, nodenames) -> list of positions ^ nodenames: e.g. {"ignore", "group:tree"} or "default:dirt" minetest.get_perlin(noiseparams) minetest.get_perlin(seeddiff, octaves, persistence, scale) ^ Return world-specific perlin noise (int(worldseed)+seeddiff) minetest.get_voxel_manip() ^ Return voxel manipulator object 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_mapgen_object(objectname) ^ Return requested mapgen object if available (see Mapgen objects) minetest.set_mapgen_params(MapgenParams) ^ 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, water_level, and 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.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 of true) that specifies whether the setting ^ should be applied to the default config or current active config minetest.clear_objects() ^ clear all objects in the environments minetest.line_of_sight(pos1, pos2, stepsize) -> true/false, pos ^ Check if there is a direct line of sight between pos1 and pos2 ^ Returns the position of the blocking node when false ^ pos1 First position ^ pos2 Second position ^ stepsize smaller gives more accurate results but requires more computing

time. Default is 1. minetest.find_path(pos1,pos2,searchdistance,max_jump,max_drop,algorithm) ^ -> 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 ^ max_jump: maximum height difference to consider walkable ^ max_drop: maximum height difference to consider droppable ^ algorithm: 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 = 1, if totallevel > maxlevel returns rest (total-max). minetest.add_node_level(pos, level) ^ increase level of leveled node by level, default level = 1, if totallevel > maxlevel returns rest (total-max). can be negative for decreasing

Inventory: minetest.get_inventory(location) -> InvRef ^ location = e.g. {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.

Formspec: 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:" naming convention ^ formspec: formspec to display minetest.formspec_escape(string) -> string ^ escapes characters [ ] \ , ; that can not be used in formspecs minetest.explode_table_event(string) -> table ^ returns e.g. {type="CHG", row=1, column=2} ^ type: "INV" (no row selected), "CHG" (selected) or "DCL" (double-click) minetest.explode_textlist_event(string) -> table ^ returns e.g. {type="CHG", index=1} ^ type: "INV" (no row selected), "CHG" (selected) or "DCL" (double-click) minetest.explode_scrollbar_event(string) -> table ^ returns e.g. {type="CHG", value=500} ^ type: "INV" (something failed), "CHG" (has been changed) or "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) ^ 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 (e.g. dropping items on

ground)

Rollback: minetest.rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, newnode}, ...} ^ Find who has done something to a node, or near a node ^ actor: "player:", also "liquid". minetest.rollback_revert_actions_by(actor, seconds) -> bool, log messages ^ Revert latest actions of someone ^ actor: "player:", also "liquid".

Defaults for the on_* item definition functions: (These return the leftover itemstack) minetest.item_place_node(itemstack, placer, pointed_thing, param2) ^ Place item as a node ^ param2 overrides facedir and wallmounted param2 ^ 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 can be nil.

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) -> 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 minetest.kick_player(name, [reason]) -> disconnect a player with a optional reason

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 ^ 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 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 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 entry 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.

^ Slice probability works in the same manner, except takes a field called ypos instead which indicates

^ the y position of the slice with a probability applied.

^ If slice probability list is nil, no slice probabilities are applied. ^ Saves schematic in the Minetest Schematic format to filename.

minetest.place_schematic(pos, schematic, rotation, replacements, force_placement) ^ Place the schematic specified by schematic (see: Schematic specifier) at pos. ^ Rotation can be "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

Misc.: 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_position_from_hash(hash) -> position ^ Inverse transform of minetest.hash_node_position 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}]") -> {10, {a = false}} minetest.write_json(data[, styled]) -> string or nil and 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 are saved as null. ^ 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}}) -> "[10, {\"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.compress(data, method, ...) -> 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, ...) -> data ^ Decompress a string of data (using ZLib). ^ See documentation on minetest.compress() for supported compression methods. ^ currently supported. ^
...
indicates method-specific arguments. Currently, no methods use this. minetest.is_protected(pos, name) -> bool ^ This function should be overridden 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.

force_facedir: if true, forcefully reset the facedir to north when placing on the floor or ceiling

minetest.rotate_node(itemstack, placer, pointed_thing) ^ calls rotate_and_place() with infinitestacks set according to the state of

the creative mode setting, and checks for "sneak" to set the invert_wall

parameter.

minetest.forceload_block(pos) ^ forceloads the position pos. ^ returns true if area could be forceloaded

minetest.forceload_free_block(pos) ^ stops forceloading the position pos.

Please note that forceloaded areas are saved when the server restarts.

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_meta(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"

NodeTimerRef: Node Timers - a high resolution persistent per-node timer - Can be gotten via minetest.get_node_timer(pos) methods: - set(timeout,elapsed)

^ set a timer's state

^ timeout is in seconds, and supports fractional values (0.1 etc)

^ elapsed is in seconds, and supports fractional values (0.1 etc)

^ will trigger the node's on_timer function after timeout-elapsed seconds - start(timeout)

^ start a timer

^ equivalent to set(timeout,0) - stop()

^ stops the timer - get_timeout() -> current timeout in seconds

^ if timeout is 0, timer is inactive - get_elapsed() -> current elapsed time in seconds

^ the node's on_timer function will be called after timeout-elapsed seconds - is_started() -> boolean state of timer

^ returns true if timer is started, otherwise false

ObjectRef: Moving things in the game are generally these (basically reference to a C++ ServerActiveObject) methods: - remove(): remove object (after returning from Lua) - getpos() -> {x=num, y=num, z=num} - setpos(pos); pos={x=num, y=num, z=num} - moveto(pos, continuous=false): interpolated move - punch(puncher, time_from_last_punch, tool_capabilities, direction)

^ puncher = an another ObjectRef,

^ time_from_last_punch = time since last punch action of the puncher

^ direction: can be nil - right_click(clicker); clicker = an another ObjectRef - get_hp(): returns number of hitpoints (2 * number of hearts) - set_hp(hp): set number of hitpoints (2 * number of hearts) - get_inventory() -> InvRef - get_wield_list(): returns the name of the inventory list the wielded item is in - get_wield_index(): returns the index of the wielded item - get_wielded_item() -> ItemStack - set_wielded_item(item): replaces the wielded item, returns true if successful - set_armor_groups({group1=rating, group2=rating, ...}) - set_animation({x=1,y=1}, frame_speed=15, frame_blend=0) - set_attach(parent, bone, position, rotation)

^ bone = string

^ position = {x=num, y=num, z=num} (relative)

^ rotation = {x=num, y=num, z=num} - set_detach() - set_bone_position(bone, position, rotation)

^ bone = string

^ position = {x=num, y=num, z=num} (relative)

^ rotation = {x=num, y=num, z=num} - set_properties(object property table) LuaEntitySAO-only: (no-op for other objects) - setvelocity({x=num, y=num, z=num}) - getvelocity() -> {x=num, y=num, z=num} - setacceleration({x=num, y=num, z=num}) - getacceleration() -> {x=num, y=num, z=num} - setyaw(radians) - getyaw() -> radians - settexturemod(mod) - setsprite(p={x=0,y=0}, num_frames=1, framelength=0.2, - select_horiz_by_yawpitch=false)

^ Select sprite from spritesheet with optional animation and DM-style

texture selection based on yaw relative to camera - get_entity_name() (DEPRECATED: Will be removed in a future version)

      In place of this, use object.get_luaentity().name - get_luaentity() Player-only: (no-op for other objects) - is_player(): true for players, false for others - get_player_name(): returns "" if is not a player - get_look_dir(): get camera direction as a unit vector - get_look_pitch(): pitch in radians - get_look_yaw(): yaw in radians (wraps around pretty randomly as of now) - set_look_pitch(radians): sets look pitch - set_look_yaw(radians): sets look yaw - get_breath() : returns players breath - set_breath(value) : sets players breath

values: 0 player is drowning,

1-10 number of bubbles remain,

11 bubbles bar is not shown - set_inventory_formspec(formspec)

^ Redefine player's inventory form

^ Should usually be called in on_joinplayer - get_inventory_formspec() -> formspec string - get_player_control(): returns table with player pressed keys

{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 = 1.0, — multiplier to default value

jump = 1.0, — multiplier to default value

gravity = 1.0, — multiplier to default value

sneak = true, — whether player can sneak

sneak_glitch = true, — whether player can use the sneak glitch

}) - 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_get_flags(): returns a table containing status of hud flags

^ returns { hotbar=true, healthbar=true, crosshair=true, wielditem=true, breathbar=true } - 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 - hud_replace_builtin(name, hud definition)

^ replace definition of a builtin hud element

^ name: "breath" or "health"

^ hud definition: definition to replace builtin definition - set_sky(bgcolor, type, {texture names})

^ bgcolor: {r=0...255, g=0...255, b=0...255} or nil, defaults to white

^ Available types:

- "regular": Uses 0 textures, bgcolor ignored

- "skybox": Uses 6 textures, bgcolor used

- "plain": Uses 0 textures, bgcolor used

^ Note: currently does not work directly in on_joinplayer; use

minetest.after(0) in there. - override_day_night_ratio(ratio or nil)

^ 0...1: Overrides day-night ratio, controlling sunlight to a specific amount

^ nil: Disables override, defaulting to sunlight based on day-night cycle - set_local_animation({x=0, y=79}, {x=168, y=187}, {x=189, y=198}, {x=200, y=219}, frame_speed=30): set animation for player model in third person view

^ stand/idle animation key frames

^ walk animation key frames

^ dig animation key frames

^ walk+dig animation key frames

^ animation frame speed - set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0}): defines offset value for camera per player

^ in first person view

^ in third person view (max. values {x=-10/10,y=-10,15,z=-5/5})

InvRef: Reference to an inventory methods: - is_empty(listname): return true if list is empty - get_size(listname): get size of a list - set_size(listname, size): set size of a list

^ returns false on error (e.g. invalid listname or listsize) - get_width(listname): get width of a list - set_width(listname, width): set width of list; currently used for crafting - get_stack(listname, i): get a copy of stack index i in list - set_stack(listname, i, stack): copy stack to index i in list - get_list(listname): return full list - set_list(listname, list): set full list (size will not change) - get_lists(): returns list of inventory lists - set_lists(lists): sets inventory lists (size will not change) - add_item(listname, stack): add item somewhere in list, returns leftover ItemStack - room_for_item(listname, stack): returns true if the stack of items

can be fully added to the list - contains_item(listname, stack): returns true if the stack of items

can be fully taken from the list - remove_item(listname, stack): take as many items as specified from the list,

returns the items that were actually removed (as an ItemStack) - note that

any item metadata is ignored, so attempting to remove a specific unique

item this way will likely remove the wrong one - to do that use set_stack

with an empty ItemStack - get_location() -> location compatible to minetest.get_inventory(location)

-> {type="undefined"} in case location is not known

ItemStack: A stack of items. - Can be created via ItemStack(itemstack or itemstring or table or nil) methods: - is_empty(): return true if stack is empty - get_name(): returns item name (e.g. "default:stone") - set_name(itemname) - get_count(): returns number of items on the stack - set_count(count) - get_wear(): returns tool wear (0-65535), 0 for non-tools - set_wear(wear) - get_metadata(): returns metadata (a string attached to an item stack) - set_metadata(metadata) - clear(): removes all items from the stack, making it empty - replace(item): replace the contents of this stack (item can also

be an itemstring or table) - to_string(): returns the stack in itemstring form - to_table(): returns the stack in Lua table form - get_stack_max(): returns the maximum size of the stack (depends on the item) - get_free_space(): returns get_stack_max() - get_count() - is_known(): returns true if the item name refers to a defined item type - get_definition(): returns the item definition table - get_tool_capabilities(): returns the digging properties of the item,

^ or those of the hand if none are defined for this item type - add_wear(amount): increases wear by amount if the item is a tool - add_item(item): put some item or stack onto this stack,

^ returns leftover ItemStack - item_fits(item): returns true if item or stack can be fully added to this one - take_item(n): take (and remove) up to n items from this stack

^ returns taken ItemStack

^ if n is omitted, n=1 is used - peek_item(n): copy (don't remove) up to n items from this stack

^ returns copied ItemStack

^ if n is omitted, n=1 is used

PseudoRandom: A pseudorandom number generator - Can be created via PseudoRandom(seed) methods: - next(): return next integer random number [0...32767] - next(min, max): return next integer random number [min...max]

(max - min) must be 32767 or <= 6553 due to the simple

implementation making bad distribution otherwise.

PerlinNoise: A perlin noise generator - Can be created via PerlinNoise(seed, octaves, persistence, scale) or PerlinNoise(noiseparams) - Also minetest.get_perlin(seeddiff, octaves, persistence, scale) or minetest.get_perlin(noiseparams) methods: - get2d(pos) -> 2d noise value at pos={x=,y=} - get3d(pos) -> 3d noise value at pos={x=,y=,z=}

PerlinNoiseMap: A fast, bulk perlin noise generator - Can be created via PerlinNoiseMap(noiseparams, size) - Also minetest.get_perlin_map(noiseparams, size) - Format of 'size' for 3D perlin maps: {x=dimx, y=dimy, z=dimz} - Format of 'size' for 2D perlin maps: {x=dimx, y=dimy}

^ where dimx, dimy, dimz are the array dimensions

^ for 3D perlin maps the z component of 'size' must be larger than 1 otherwise 'nil' is returned methods: - get2dMap(pos) -> X 2d array of 2d noise values starting at pos={x=,y=} - get3dMap(pos) -> XX 3d array of 3d noise values starting at pos={x=,y=,z=} - get2dMap_flat(pos) -> Flat element array of 2d noise values starting at pos={x=,y=} - get3dMap_flat(pos) -> Same as get2dMap_flat, but 3d noise

VoxelManip: An interface to the MapVoxelManipulator for Lua - Can be created via VoxelManip() - Also minetest.get_voxel_manip() methods: - read_from_map(p1, p2): Reads a chunk of map from the map containing the region formed by p1 and p2.

^ returns actual emerged pmin, actual emerged pmax - write_to_map(): Writes the data loaded from the VoxelManip back to the map.

^ important: data must be set using VoxelManip:set_data before calling this - get_node_at(pos): Returns a MapNode table of the node currently loaded in the VoxelManip at that position - set_node_at(pos, node): Sets a specific MapNode in the VoxelManip at that position - get_data(): Gets the data read into the VoxelManip object

^ returns raw node data is in the form of an array of node content ids - set_data(data): Sets the data contents of the VoxelManip object - update_map(): Update map after writing chunk back to map.

^ To be used only by VoxelManip objects created by the mod itself; not a VoxelManip that was

^ retrieved from minetest.get_mapgen_object - set_lighting(light, p1, p2): Set the lighting within the VoxelManip to a uniform value

^ light is a table, {day=<0...15>, night=<0...15>}

^ To be used only by a VoxelManip object from minetest.get_mapgen_object

^ (p1, p2) is the area in which lighting is set; defaults to the whole area if left out - get_light_data(): Gets the light data read into the VoxelManip object

^ Returns an array (indices 1 to volume) of integers ranging from 0 to 255

^ Each value is the bitwise combination of day and night light values (0..15 each)

^ light = day + (night * 16) - set_light_data(light_data): Sets the param1 (light) contents of each node in the VoxelManip

^ expects lighting data in the same format that get_light_data() returns - get_param2_data(): Gets the raw param2 data read into the VoxelManip object - set_param2_data(param2_data): Sets the param2 contents of each node in the VoxelManip - calc_lighting(p1, p2): Calculate lighting within the VoxelManip

^ To be used only by a VoxelManip object from minetest.get_mapgen_object

^ (p1, p2) is the area in which lighting is set; defaults to the whole area if left out - update_liquids(): Update liquid flow - was_modified(): Returns true or false if the data in the voxel manipulator had been modified since

the last read from map, due to a call to minetest.set_data() on the loaded area elsewhere

VoxelArea: A helper class for voxel areas - Can be created via VoxelArea:new{MinEdge=pmin, MaxEdge=pmax} - Coordinates are inclusive, like most other things in Minetest methods: - getExtent(): returns a 3d vector containing the size of the area formed by MinEdge and MaxEdge - getVolume(): returns the volume of the area formed by MinEdge and MaxEdge - index(x, y, z): returns the index of an absolute position in a flat array starting at 1

^ useful for things like VoxelManip, raw Schematic specifiers, PerlinNoiseMap:get2d/3dMap, and so on - indexp(p): same as above, except takes a vector - position(i): returns the absolute position vector corresponding to index i - contains(x, y, z): check if (x,y,z) is inside area formed by MinEdge and MaxEdge - containsp(p): same as above, except takes a vector - containsi(i): same as above, except takes an index - iter(minx, miny, minz, maxx, maxy, maxz): returns an iterator that returns indices

^ from (minx,miny,minz) to (maxx,maxy,maxz) in the order of [z [y [x]]] - iterp(minp, maxp): same as above, except takes a vector

Settings: An interface to read config files in the format of minetest.conf - Can be created via Settings(filename) methods: - get(key) -> value - get_bool(key) -> boolean - set(key, value) - remove(key) -> success - get_names() -> {key1,...} - write() -> success

^ write changes to file - to_table() -> {[key1]=value1,...}

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.

The following Mapgen objects are currently available:

- 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.

- gennotify

Returns a table mapping requested generation notification types to arrays of positions at which the corresponding generated structures are located at within the current chunk. To set the capture of positions of interest to be recorded on generate, use minetest.set_gen_notify(). Possible fields of the table returned are:

dungeon, temple, cave_begin, cave_end, large_cave_begin, large_cave_end, decoration Decorations have a key in the format of "decoration#id", where id is the numeric unique decoration ID.

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, after movement and collision processing.

dtime is usually 0.1 seconds, as per the dedicated_server_step setting

in minetest.conf.

- 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; if no seed is provided, the engine will create one

}

Key for Special L-System Symbols used in Axioms

G - move forward one unit with the pen up

F - move forward one unit with the pen down drawing trunks and branches

f - move forward one unit with the pen down drawing leaves (100% chance)

T - move forward one unit with the pen down drawing trunks only

R - move forward one unit with the pen down placing fruit

A - replace with rules set A

B - replace with rules set B

C - replace with rules set C

D - replace with rules set D

a - replace with rules set A, chance 90%

b - replace with rules set B, chance 80%

c - replace with rules set C, chance 70%

d - replace with rules set D, chance 60%

+ - yaw the turtle right by angle parameter

- - yaw the turtle left by angle parameter

& - pitch the turtle down by angle parameter

^ - pitch the turtle up by angle parameter

/ - roll the turtle to the right by angle parameter

* - roll the turtle to the left by angle parameter

[ - save in stack current state info

] - recover from stack state info

Example usage: spawn small apple tree apple_tree={

axiom="FFFFFAFFBF",

rules_a="[&&FFFFF&FFFF][&

++++FFFFF&FFFF][&

----FFFFF&FFFF]",

rules_b="[&&++FFFFF&FFFF][&

--FFFFF&FFFF][&

------FFFFF&FFFF]",

trunk="default:tree",

leaves="default:leaves",

angle=30,

iterations=2,

random_level=0,

trunk_type="single",

thin_branches=true,

fruit_chance=10,

fruit="default:apple"

} minetest.spawn_tree(pos,apple_tree)

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"/"wielditem",

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 }

Entity definition (register_entity) {

(Deprecated: Everything in object properties is read directly from here)

initial_properties = ,

on_activate = function(self, staticdata, dtime_s), on_step = function(self, dtime), on_punch = function(self, hitter), on_rightclick = function(self, clicker), get_staticdata = function(self), ^ Called sometimes; the string returned is passed to on_activate when the entity is re-activated from static state

# Also you can define arbitrary member variables here myvariable = whatever,

}

ABM (ActiveBlockModifier) definition (register_abm) {

— In the following two fields, also group:groupname will work.

nodenames = {"default:lava_source"},

neighbors = {"default:water_source", "default:water_flowing"}, — (any of these)

^ If left out or empty, any neighbor will do

interval = 1.0, — (operation interval)

chance = 1, — (chance of trigger is 1.0/this)

action = func(pos, node, active_object_count, active_object_count_wider), }

Item definition (register_node, register_craftitem, register_tool) {

description = "Steel Axe",

groups = {}, — key=name, value=rating; rating=1..3.

if rating not applicable, use 1.

e.g. {wool=1, fluffy=3}

{soil=2, outerspace=1, crumbly=1}

{bendy=2, snappy=1},

{hard=1, metal=1, spikes=1}

inventory_image = "default_tool_steelaxe.png",

wield_image = "",

wield_scale = {x=1,y=1,z=1},

stack_max = 99,

range = 4.0,

liquids_pointable = false,

tool_capabilities = {

full_punch_interval = 1.0,

max_drop_level=0,

groupcaps={

— For example:

snappy={times={[2]=0.80, [3]=0.40}, maxwear=0.05, maxlevel=1},

choppy={times={[3]=0.90}, maxwear=0.05, maxlevel=0}

},

damage_groups = {groupname=damage},

}

node_placement_prediction = nil,

^ If nil and item is node, prediction is made automatically

^ If nil and item is not a node, no prediction is made

^ If "" and item is anything, no prediction is made

^ Otherwise should be name of node which the client immediately places

on ground when the player places the item. Server will always update

actual result to client in a short moment.

sound = {

place = ,

}

on_place = func(itemstack, placer, pointed_thing), ^ Shall place item and return the leftover itemstack ^ default: minetest.item_place on_drop = func(itemstack, dropper, pos), ^ Shall drop item and return the leftover itemstack ^ default: minetest.item_drop on_use = func(itemstack, user, pointed_thing), ^ default: nil ^ Function must return either nil if no item shall be removed from inventory, or an itemstack to replace the original itemstack. e.g. itemstack:take_item(); return itemstack ^ Otherwise, the function is free to do what it wants. ^ The default functions handle regular use cases. after_use = func(itemstack, user, node, digparams), ^ default: nil ^ If defined, should return an itemstack and will be called instead of wearing out the tool. If returns nil, does nothing. If after_use doesn't exist, it is the same as: function(itemstack, user, node, digparams) itemstack:add_wear(digparams.wear) return itemstack end

}

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

Tile animation definition: - {type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}

Node definition (register_node) {

,

drawtype = "normal", — See "Node drawtypes" visual_scale = 1.0, ^ Supported for drawtypes "plantlike", "signlike", "torchlike", "mesh". ^ For plantlike, the image will start at the bottom of the node; for the ^ other drawtypes, the image will be centered on the node. ^ Note that positioning for "torchlike" may still change. tiles = {tile definition 1, def2, def3, def4, def5, def6}, ^ Textures of node; +Y, -Y, +X, -X, +Z, -Z (old field name: tile_images) ^ List can be shortened to needed length special_tiles = {tile definition 1, Tile definition 2}, ^ Special textures of node; used rarely (old field name: special_materials) ^ List can be shortened to needed length alpha = 255, use_texture_alpha = false, — Use texture's alpha channel post_effect_color = {a=0, r=0, g=0, b=0}, — If player is inside node paramtype = "none", — See "Nodes" paramtype2 = "none", — See "Nodes" is_ground_content = true, — If false, the cave generator will not carve through this sunlight_propagates = false, — If true, sunlight will go infinitely through this walkable = true, — If true, objects collide with node pointable = true, — If true, can be pointed at diggable = true, — If false, can never be dug climbable = false, — If true, can be climbed on (ladder) buildable_to = false, — If true, placed nodes can replace this node liquidtype = "none", — "none"/"source"/"flowing" liquid_alternative_flowing = "", — Flowing version of source liquid liquid_alternative_source = "", — Source version of flowing liquid liquid_viscosity = 0, — Higher viscosity = slower flow (max. 7) liquid_renewable = true, — Can new liquid source be created by placing two or more sources nearby? freezemelt = "", — water for snow/ice, ice/snow for water leveled = 0, — Block contain level in param2. value - default level, used for snow. Don't forget use "leveled" type nodebox liquid_range = 8, — number of flowing nodes around source (max. 8) drowning = 0, — Player will take this amount of damage if no bubbles are left light_source = 0, — Amount of light emitted by node damage_per_second = 0, — If player is inside node, this damage is caused node_box = {type="regular"}, — See "Node boxes" mesh = "model", selection_box = {type="regular"}, — See "Node boxes" ^ If drawtype "nodebox" is used and selection_box is nil, then node_box is used legacy_facedir_simple = false, — Support maps made in and before January 2012 legacy_wallmounted = false, — Support maps made in and before January 2012 sounds = { footstep = , dig = , — "__group" = group-based sound (default) dug = , place = , }, drop = "", — Name of dropped node when dug. Default is the node itself. — Alternatively: drop = { max_items = 1, — Maximum number of items to drop. items = { — Choose max_items randomly from this list. { items = {"foo:bar", "baz:frob"}, — Choose one item randomly from this list. rarity = 1, — Probability of getting is 1 / rarity. }, }, },

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

after_place_node = func(pos, placer, itemstack, pointed_thing) ^ Called after constructing node when node was placed using minetest.item_place_node / minetest.place_node ^ If return true no item is taken from itemstack ^ default: nil after_dig_node = func(pos, oldnode, oldmetadata, digger), ^ oldmetadata is in table format ^ Called after destructing node when node was dug using minetest.node_dig / minetest.dig_node ^ default: nil can_dig = function(pos,player) ^ returns true if node can be dug, or false if not ^ default: nil

on_punch = func(pos, node, puncher, pointed_thing), ^ default: minetest.node_punch ^ By default: Calls minetest.register_on_punchnode callbacks on_rightclick = func(pos, node, clicker, itemstack, pointed_thing), ^ default: nil ^ if defined, itemstack will hold clicker's wielded item ^ Shall return the leftover itemstack ^ Note: pointed_thing can be nil, if a mod calls this function

on_dig = func(pos, node, digger), ^ default: minetest.node_dig ^ By default: checks privileges, wears out tool and removes node

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

on_receive_fields = func(pos, formname, fields, sender), ^ fields = {name1 = value1, name2 = value2, ...} ^ Called when an UI form (e.g. sign text input) returns data ^ default: nil

allow_metadata_inventory_move = func(pos, from_list, from_index, to_list, to_index, count, player), ^ Called when a player wants to move items inside the inventory ^ Return value: number of items allowed to move

allow_metadata_inventory_put = func(pos, listname, index, stack, player), ^ Called when a player wants to put something into the inventory ^ Return value: number of items allowed to put ^ Return value: -1: Allow and don't modify item count in inventory

allow_metadata_inventory_take = func(pos, listname, index, stack, player), ^ Called when a player wants to take something out of the inventory ^ Return value: number of items allowed to take ^ Return value: -1: Allow and don't modify item count in inventory

on_metadata_inventory_move = func(pos, from_list, from_index, to_list, to_index, count, player), on_metadata_inventory_put = func(pos, listname, index, stack, player), on_metadata_inventory_take = func(pos, listname, index, stack, player), ^ Called after the actual action has happened, according to what was allowed. ^ No return value

on_blast = func(pos, intensity), ^ intensity: 1.0 = mid range of regular TNT ^ If defined, called when an explosion touches the node, instead of removing the node

}

Recipe for register_craft: (shaped) {

output = 'default:pick_stone',

recipe = {

{'default:cobble', 'default:cobble', 'default:cobble'},

{'', 'default:stick', ''},

{'', 'default:stick', ''}, — Also groups; e.g. 'group:crumbly'

},

replacements =

replace one input item with another item on crafting> }

Recipe for register_craft (shapeless) {

type = "shapeless",

output = 'mushrooms:mushroom_stew',

recipe = {

"mushrooms:bowl",

"mushrooms:mushroom_brown",

"mushrooms:mushroom_red",

},

replacements =

replace one input item with another item on crafting> }

Recipe for register_craft (tool repair) {

type = "toolrepair",

additional_wear = -0.02, }

Recipe for register_craft (cooking) {

type = "cooking",

output = "default:glass",

recipe = "default:sand",

cooktime = 3, }

Recipe for register_craft (furnace fuel) {

type = "fuel",

recipe = "default:leaves",

burntime = 1, }

Ore definition (register_ore) {

ore_type = "scatter", — See "Ore types"

ore = "default:stone_with_coal",

wherein = "default:stone",

^ a list of nodenames is supported too

clust_scarcity = 8*8*8,

^ Ore has a 1 out of clust_scarcity chance of spawning in a node

^ This value should be MUCH higher than your intuition might tell you!

clust_num_ores = 8,

^ Number of ores in a cluster

clust_size = 3,

^ Size of the bounding box of the cluster

^ In this example, there is a 3x3x3 cluster where 8 out of the 27 nodes are coal ore

height_min = -31000,

height_max = 64,

flags = "",

^ Attributes for this ore generation

noise_threshhold = 0.5,

^ If noise is above this threshold, ore is placed. Not needed for a uniform distribution

noise_params = {offset=0, scale=1, spread={x=100, y=100, z=100}, seed=23, octaves=3, persist=0.70}

^ NoiseParams structure describing the perlin noise used for ore distribution.

^ Needed for sheet ore_type. Omit from scatter ore_type for a uniform ore distribution }

Decoration definition (register_decoration) {

deco_type = "simple", — See "Decoration types"

place_on = "default:dirt_with_grass",

^ Node that decoration can be placed on

sidelen = 8,

^ Size of divisions made in the chunk being generated.

^ If the chunk size is not evenly divisible by sidelen, sidelen is made equal to the chunk size.

fill_ratio = 0.02,

^ Ratio of the area to be uniformly filled by the decoration.

^ Used only if noise_params is not specified.

noise_params = {offset=0, scale=.45, spread={x=100, y=100, z=100}, seed=354, octaves=3, persist=0.7},

^ NoiseParams structure describing the perlin noise used for decoration distribution.

^ The result of this is multiplied by the 2d area of the division being decorated.

biomes = {"Oceanside", "Hills", "Plains"},

^ List of biomes in which this decoration occurs. Occurs in all biomes if this is omitted,

^ and ignored if the Mapgen being used does not support biomes.

----- Simple-type parameters decoration = "default:grass", ^ The node name used as the decoration. ^ If instead a list of strings, a randomly selected node from the list is placed as the decoration. height = 1, ^ Number of nodes high the decoration is made. ^ If height_max is not 0, this is the lower bound of the randomly selected height. height_max = 0, ^ Number of nodes the decoration can be at maximum. ^ If absent, the parameter 'height' is used as a constant. spawn_by = "default:water", ^ Node that the decoration only spawns next to, in a 1-node square radius. num_spawn_by = 1, ^ Number of spawn_by nodes that must be surrounding the decoration position to occur. ^ If absent or -1, decorations occur next to any nodes.

----- Schematic-type parameters schematic = "foobar.mts", ^ If schematic is a string, it is the filepath relative to the current working directory of the ^ specified Minetest schematic file. ^ - OR -, could instead be a table containing two mandatory fields, size and data, ^ and an optional table yslice_prob: schematic = { size = {x=4, y=6, z=4}, data = { {name="cobble", param1=255, param2=0}, {name="dirt_with_grass", param1=255, param2=0}, ... }, yslice_prob = { {ypos=2, prob=128}, {ypos=5, prob=64}, ... }, }, ^ See 'Schematic specifier' for details. replacements = {["oldname"] = "convert_to", ...}, flags = "place_center_x, place_center_z", ^ Flags for schematic decorations. See 'Schematic attributes'. rotation = "90" — rotate schematic 90 degrees on placement ^ Rotation can be "0", "90", "180", "270", or "random".

}

Chatcommand definition (register_chatcommand) {

params = " ", — Short parameter description

description = "Remove privilege from player", — Full description

privs = {privs=true}, — Require the "privs" privilege to run

func = function(name, param), — Called when command is run.

— Returns boolean success and text output. }

Detached inventory callbacks {

allow_move = func(inv, from_list, from_index, to_list, to_index, count, player),

^ Called when a player wants to move items inside the inventory

^ Return value: number of items allowed to move

allow_put = func(inv, listname, index, stack, player), ^ Called when a player wants to put something into the inventory ^ Return value: number of items allowed to put ^ Return value: -1: Allow and don't modify item count in inventory

allow_take = func(inv, listname, index, stack, player), ^ Called when a player wants to take something out of the inventory ^ Return value: number of items allowed to take ^ Return value: -1: Allow and don't modify item count in inventory

on_move = func(inv, from_list, from_index, to_list, to_index, count, player), on_put = func(inv, listname, index, stack, player), on_take = func(inv, listname, index, stack, player), ^ Called after the actual action has happened, according to what was allowed. ^ No return value

}

HUD Definition (hud_add, hud_get) {

hud_elem_type = "image", — see HUD element types

^ type of HUD element, can be either of "image", "text", "statbar", or "inventory"

position = {x=0.5, y=0.5},

^ Left corner position of element

name = "",

scale = {x=2, y=2},

text = "",

number = 2,

item = 3,

^ Selected item in inventory. 0 for no item selected.

direction = 0,

^ Direction: 0: left-right, 1: right-left, 2: top-bottom, 3: bottom-top

alignment = {x=0, y=0},

^ See "HUD Element Types"

offset = {x=0, y=0},

^ See "HUD Element Types"

size = { x=100, y=100 },

^ Size of element in pixels }

Particle definition (add_particle) {

pos = {x=0, y=0, z=0},

velocity = {x=0, y=0, z=0},

acceleration = {x=0, y=0, z=0},

^ Spawn particle at pos with velocity and acceleration

expirationtime = 1,

^ Disappears after expirationtime seconds

size = 1,

collisiondetection = false,

^ collisiondetection: if true collides with physical objects

vertical = false,

^ vertical: if true faces player using y axis only

texture = "image.png",

^ Uses texture (string)

playername = "singleplayer"

^ optional, if specified spawns particle only on the player's client }

ParticleSpawner definition (add_particlespawner) {

amount = 1,

time = 1,

^ If time is 0 has infinite lifespan and spawns the amount on a per-second base

minpos = {x=0, y=0, z=0},

maxpos = {x=0, y=0, z=0},

minvel = {x=0, y=0, z=0},

maxvel = {x=0, y=0, z=0},

minacc = {x=0, y=0, z=0},

maxacc = {x=0, y=0, z=0},

minexptime = 1,

maxexptime = 1,

minsize = 1,

maxsize = 1,

^ The particle's properties are random values in between the bounds:

^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration),

^ minsize/maxsize, minexptime/maxexptime (expirationtime)

collisiondetection = false,

^ collisiondetection: if true uses collision detection

vertical = false,

^ vertical: if true faces player using y axis only

texture = "image.png",

^ Uses texture (string)

playername = "singleplayer"

^ Playername is optional, if specified spawns particle only on the player's client }




Source: home.metrocast.net/~minetestmoddingtutorial/beginnerEN.html

Minetest-c55: Beginners Guide to Modding in Lua

Introduction

Minetest-c55 is a Minecraft clone, developed by the Finnish programmer 'celeron55' and contributors.

Minetest has been built with the intention of making it easy for anyone to program Mods (Modifications), extending its features and adding new items.

In this tutorial we'll show you how to get started writing Mods for Minetest using Lua. Along the way you'll start learning how to write programs in Lua.

If you already know a programming language like Java, Javascript, Python, etc., then you should find it reasonably easy to get started in Lua. If you are new to programming, don't worry. We'll go slowly and show you exactly what to do. If you would like to learn more about programming in Lua there are lots of places on the web that can help. We've put a list of suggested programming resources at the end of this tutorial.

Chapter 1 - Modding basics

Why Would You Want to Write a Mod?

The computer program that runs Minetest is split into two main parts. First, there is the "Engine". This looks after drawing the world on the screen, keeping track of players and objects in the game, all the communications in a multiplayer game, etc. Second, there are the "Mods". Mods decide what things in the game look like and how they work. Mods deal with all the crafting. Mods define what happens when you hit things. Without the Mods the game would run, but it wouldn't be very interesting.

The people who wrote Minetest have made it really easy for you to change how the game works by writing your own Mods. This means that with a little bit of knowledge of how to write small bits of computer programs you can change Minetest to work in any way that you can imagine. Really. You want trees to fly? No problem. You want to have a working farm? Someone's already done that one. You want chests to send tweets to Twitter whenever someone takes something out of them? That one will take a little work.

Writing Your First Mod

To get ourselves started, let's write a simple Mod. What we'll do is change the game so that when you hit a brick block it complains at the injustice you have just caused it.

Set Up

Follow these steps to get yourself started:

In order to write computer programs, you are going to need to use a text editor. If you already know what a text editor is, then you probably have a favourite one ready to go. If you don't know what a text editor is and you are using Windows, then Notepad++ is a good choice. You can download and install a copy from http://notepad-plus-plus.org/.

Finding Where to Put Your Mods

The next bit can be a bit fiddly. If you get stuck ask someone for some help. You need to find the folder where you installed Minetest. I unpacked my Minetest on my "C:\" folder on Windows. If I open the "Computer" folder in Windows and click on "Local Disk (C:)", I can find a folder called "minetest-0.4.6". This is the where I installed Minetest. Make sure you can find the folder where you installed Minetest as this is the place you need to go to write your Mods. If you are stuck, ask someone for help.

Writing Your First Mod

Now that you have found the folder where you installed Minetest, let's write our first Mod. This will be a simple, but polite, Mod that will say hello to us as we start the game. Inside the folder where you installed Minetest double click to open the folder called "mods". Double click again to open the folder called "minetest". We now need to make a new folder in this minetest directory for our new Mod. In Windows right-click the empty space in the folder and choose "New => Folder". Change the name of the folder to "chatty_bricks".

So far so good. We've created a folder to hold our new Mod. Now we actually need to write some code. Open up your text editor (Notepad++ or your favorite) and tell it to create a new blank text document. Type the following lines into the new text document:

print("++++++++ Hello from me +++++++++")

Now you need to save the document. Save it in the "chatty_bricks" folder that you just made. Call the document "init.lua". Be careful not to save it as "init.lua.txt" by mistake.

We have reached the moment of truth. Go and fire up Minetest. As you start the program you should see a console window pop up behind the main Minetest window. Move the windows around so that you can see the console window. Keep one eye on the console window as you double click to open a single player world. Did you see your hello line appear? If you did, perform a celebratory dance of your own choosing. If you didn't, ask the person sitting next to you to see if they can help you figure out what went wrong.

Challenge: Try changing your program to make it say something different. Be polite!!!

Making the Mod More Interesting

While I was impressed by that, I've a feeling your friends may be somewhat underwhelmed if you brought them round specially to show them your new Minetest Mod. Let's improve on it a bit. Open up your editor again and edit the init.lua file. After the print statement you created in the previous step, on a new line add the following:

minetest.after(5, function(params) minetest.chat_send_all("BEWARE THIS GAME HAS BEEN MOD'ED!") end )

Save your init.lua. Close your single player world in Minetest and then reopen it. Five seconds after you start the game you should get the message appear as a chat in the main game.

Challenge:The number 5 in the code tells Minetest how many seconds to wait before sending the message. Add some more "after" functions so that Minetest does a count-down from 10 to 1.

Now For Those Chatty Bricks

We're nearly there. The last thing for us to do is add some code to our Mod that makes bricks complain when you hit them. We've already seen the chat_send_all function that sends a message. What we need to use now is register_on_punchnode function to tell the game what to do when someone hits a brick.

Add this to your init.lua file:

minetest.register_on_punchnode( function(pos, node, puncher) if node.name == "default:brick" then minetest.chat_send_all("Hey!! Stop it!! That hurts") end end )

Challenge: Add some more code to do make a different type of block say something.

Challenge: Change the message so that the brick uses the name of the person who punched it.

Challenge (Tricky!): See if you can use the minetest.sound_play function to make the brick make a noise when you hit it.

Apendix

Where to Look for More Help

List of all the minetest._____ functions: http://dev.minetest.net/Global_Minetest_object

Another Minetest tutorial: http://dev.minetest.net/Intro

Credits and Afterword

This is page is adapted from Jeija's Modding tutorial by Dave Potts (davegoopot on GitHub).




Source: home.metrocast.net/~minetestmoddingtutorial/englishEN.html

Minetest-c55: Modding in Lua

Download Resources CONTENTS

   The Basics

   Introduction

   Chapter 1 - Modding Basics and Required understanding

   Part One: Declaring and Crafting Nodes

      Chapter 2 - Defining a node

      Chapter 3 - Setting up a craft recipe

   Part Two: ABMs

      Chapter 4 - ABM Basics and the Position Variable

      more comming soon

   Part Three: Lua Files and Debuging

      Chapter # - Including LUA Files

      Chapter # - Exceptions, Bugs, and the print function

The Basics

Introduction

Minetest-c55 is a Minecraft clone, developed by the Finnish programmer 'celeron55' and contributors.

Minetest has a ScriptAPI (Applictation Programming Interface), which is used to program Mods (Modifications) for the game, extending its features and adding new items.

This ScriptAPI is accessed using an easy-to-use programming langauge called Lua.

Requirements

Basic Programming Knowledge, ideally in the Lua Language (learn)

Chapter 1 - Modding basics

Types of objects in Minetest

Here are the three types of items you can define in Minetest:

The type of the object is important as it plays a part in the properties of that object.

Mod packs and item names

In minetest, each node, tool and item needs a unique name to identify it in the api. The name's format is like this:

modname:itemname

In this case, the mod is called 'modname' (name is preset by the folder name) and the block is called 'itemname', so it's tutorial:decowood. so for example, default:dirt is the unique name for dirt.

Creating a mod

1) Create a new folder with the name of your mod in the mod folder

Linux Systemwide: ~/.minetest*/usermods/

Windows + Linux Run-in-place: minetest*/mods/minetest

minetest* The place where minetest was installed/extracted to.

2) In the new folder, create a file called 'init.lua'. This is the file that will contain the source code for the mod.

To do this on Windows, use WordPad.

Click file>save as, dropdown to all files, and type 'init.lua' in the file name box.

Or you can use a lua compatible editor, a few examples: 'Context', 'luaedit', 'Geany (linux)', 'Bluefish (linux)'

WARNING: DO NOT USE NOTEPAD

3) Next make another sub folder called 'textures'. This is where you will place the textures

Part One: Declaring and Crafting Nodes

Chapter 2: Defining a node

We are going to make a mod that adds a special kind of wood that can only be used for decoration. For this, create a new mod called 'tutorial' using the method described in Chapter 0.

Registering the decowood node

1) copy-paste this into 'init.lua':

minetest.register_node("tutorial:decowood", { tile_images = {"tutorial_decowood.png"}, groups={choppy}, })

2) Copy the file 'tutorial_decowood.png' supplied with this Document to the textures folder in the mod.

Try it) Launch the game now, and notice that the mods are automatically loaded and compiled. This means when changing the code you simply have to 'Exit to Menu' and 'Start Game/Connect' again to try out the changes.

Let's try out our first mod! Open the chat window ingame (press t) and enter "/giveme tutorial:decowood 99" (Without "" of course). This will add 99 blocks of the decorative wood to your inventory!

The "give" privilage is required for the /giveme command to work

To grant yourself the "give" privilage, go to worlds/gamename/auth.txt and open it. Add ",give" after "shout,interact" to make it "shout,interact,give"

Let's have a look at the source code:

The function minetest.register_node(name, table) is responsible for adding new blocks to the game (node=block, but also torches, rails, ...)

It takes 2 Parameters: The name of the new block ("tutorial:decowood", the string before : MUST be the name of the mod folder) and a table with several properties of the block.

In this case we use 2 properties:

Chapter 3 - Crafting

What is crafting?

Crafting does not only play an important role in Minecraft, Minetest also uses different crafting recipes. Therefore it is important to know what crafting means and how to code it!

Crafting means to creating Tools, Blocks and Other Objects. In minetest you have a 3x3 crafting area by default with a 1x1 output field.

For example, a stone pickaxe can be made out of 2 Sticks and 3 Cobblestones:

[image] The craft recipe for a stone pick-axe

S=Stick C=Cobblestone; Looks quite logic, doesn't it?

Lets make a recipe for our decowood mod

So let's make a crafting recipe for the decorative wood of Chapter 0!

Just append (add) this to your init.lua file:

minetest.register_craft({ output = '"tutorial:decowood" 2', recipe = { {'default:wood', 'default:wood', ''}, {'default:wood', 'default:wood', ''}, {'', '', ''}, } })

The function minetest.register_craft() registers a crafting process, it defines the recipe for something.

It takes 1 parameter which is a table that contains 2 properties: (and an optional third)

1, output - which sets the outcome of the crafting process and recipe which is the actual recipe for the output.

2. recipe must be a table with other tables inside. Every of the 3 tables defines another row of the crafting field. Every row contains 3 columns. In this case The crafting recipe is like this:


   [image] The craft recipe for our decowood

3. [optional] type - if you want to make it a furnace craft add type="cook" before the "output" property

Easy, isn't it? You may also try out some other combinations!

What is the mod "default"?

So what is default? 'default' is the most important "mod" of minetest, in fact minetest itself is more like just a game engine, all the contents, materials, and other stuff are in several mods, like 'default' (standard tools/blocks), 'bucket' (Buckets: Lava/Water),...

If you want to find out more about these mods and maybe use features they contain, just have a look in their init.lua!

For Windows & Linux run-in-place these mods are in minetest/games/minetest_game/

For Linux systemwide installation, these mods are in /usr/share/minetest/games/minetest_game

Chapter 4: ABMs

ABMs stands for "Active Block Modifiers" and they add actions to blocks. For instance, the tutorial-wood could become normal wood after a few seconds.

Append this code to your init.lua:

minetest.register_abm( {nodenames = {"tutorial:decowood"}, interval = 30, chance = 1, action = function(pos) minetest.env:add_node(pos, {name="default:wood"}) end, })

Try it out! It's really annoying to see all your decowood creations destroyed after 30 seconds, they simply become normal wood.

But how does this work?

The function minetest.register_abm registers an action for each block of the same type.

nodenames = {"tutorial:decowood'} means that the action is processed for each decowood block.

You could also try "default:stone" instead of that to turn all stone blocks into wood.

interval = 30 means that the action is performed every 30 seconds. It starts counting at the beginning of the game. After 30 seconds all actions are processed, it doesn't matter when the block was placed.

This is not a per-block timer!

chance = 1 means that the probability of the action is 1:1, it happens in every case. A higher value means that it's less probable.

action = function(pos) is the function that is actually performed.

It contains the command minetest.env:add_node. More about it in the next section

minetest.env:add_node

This is a function that is used to add/replace a node the given place

minetest.env:add_node has 2 parameters.

In this case the name is enough to define what block you can see.

So let's assume we want to create a mod that makes junglegrass grow above every dirt-with-grass block. This should be a slow process, one dirt-with-grass block after the other should be grown over. This is what we do:

minetest.register_abm( {nodenames = {"default:dirt_with_grass"}, interval = 1, chance = 100, action = function(pos) pos.y=pos.y+1 minetest.env:add_node(pos, {name="default:junglegrass"}) end, })

You should already know everything else but the line "pos.y=pos.y+1".

The Position Variable

To understand the position variable, you need to know that in 3d space, positions are determind by three co-ordinates: x,y,z The player usually spawns near 0,0,0.

The line pos.y=pos.y+1 manipulates the position to 1 Block above the dirt-with-grass node.

There are some small other differences to our first abm.

The interval is 1 in this case, but the chance (probability) is 100.Therefore the function is executed every second, but only in 1 of 100 cases.

This makes your minetest garden slowly been overgrown by junglegrass.

Part Three - Lua Files and Debugging

Chapter # - Including Files

The dofile function

Sometimes you have so much code, a single init.lua file is too hard to maintain.

But there is a solution! dofile(minetest.get_modpath("tutorial").."/anotherfile.lua") will tell Minetest to look for anotherfile.lua in the same folder as init.lua, and load its contents.

Chapter # - Debugging

Types of errors and Bugs

As with most programming, when you develop you tend to get what are called "bugs" and errors, which are basically human mistakes.

There are three types of bugs/errors

Avoiding Syntax Mistakes

To help avoid syntax mistakes, make sure your code is easy to read.

Which one of these codes is easier to read?

minetest.register_abm( {nodenames = {"default:dirt_with_grass"}, interval = 1, chance = 100, action = function(pos) pos.y=pos.y+1 minetest.env:add_node(pos, {name="default:junglegrass"}) end, })    -or-    minetest.register_abm({nodenames = {"default:dirt_with_grass"},interval = 1,chance = 100, action = function(pos) pos.y=pos.y+1 minetest.env:add_node(pos, {name="default:junglegrass"}) end, })

Also you should check your work and put comments in

pos.y=pos.y+1 --This line increases the position's y axis by 1

Avoiding Runtime Mistakes

The Console is the black window with writing in that appears when Minetest runs.

LUA has a function called "print" and it displays a message to the console.

print("message to send")

You should the print function so you know how far Minetest gets in a program.

Why use print

For example, you have a mistake in the code:

check_something(1)    function check_something(value) if value=0 then print("it ends up here") else print("but you are certern that value=1") end end

The aboves Runtime bug was caused by a single "=" instead of double "=", and so instead of checking if value was equal to 0, it set it to 0 resulting in true And so having print helps point out your mistake.

Appendix

Learn to code

Don't have any knowledge? Use the following to learn:

Codecademy -Learn the basics of programming (it is Javascript (not Java) but still helps)

Internet Search (google,yahoo) lua tutorials

Credits and Afterword

This is Jeija's modding tutorial Version 20120823,

Updated, Rewriten and Reformated for english by "Rubenwardy".

Html coded by Rubenwardy.

Check for new version at GitHub.

See InfinityProject's Moddinghelper

For more advanced (and often cryptic) information about minetest modding have a look at this reference: Lua_api.txt

For generic modding questions or specific questions, feel free to ask in the minetest forum: minetest.net/forum

For questions about this tutorial, ask in the thread for this tutorial: minetest.net/forum/...

Thanks you for reading! Good luck in creating your amazing dream mod!




Source: rubenwardy.com/minetest_modding_book/index.html

Introduction

Welcome

Minetest uses Lua scripts to provide modding support. This online book aims to teach you how to create your own mods, starting from the basics.

What you will need

So, go on then.

Start reading. Use the navigation bar on the left (or on the top on mobiles) to open a chapter.

GitHub.

Download for offline use.

Forum Topic.

About this Book

Noticed a mistake, or want to give feedback? Tell us about it using one of these methods:

You can contribute to this project on GitHub.

Read the contribution README.

Written by rubenwardy.

License: CC-BY-SA 3.0

Feedback

Nickname (optional):

Contact method (email or forum name, optional):

Feedback:


Folder Structure

Introduction

In this chapter we will learn the basic structure of a mod's folder. This is an essential skill when creating mods.

Mod Folders

[image: Find the mod's folder]

Each mod has its own folder, where all its Lua code, textures, models and sounds are placed. These folders need to be placed in a mod location, such as minetest/mods. Mods can be grouped into mod packs, which are explained below.

A "mod name" is used to refer to a mod. Each mod should have a unique mod name, which you can choose - a good mod name can describes what the mod does. Mod names can be make up of letters, numbers or underscores. The folder a mod is in needs to be called the same as the mod name.

Mod Folder Structure

Mod name (eg: "mymod") - init.lua - the main scripting code file, which is run when the game loads. - (optional) depends.txt - a list of mod names that needs to be loaded before this mod. - (optional) textures/ - place images here, commonly in the format modname__itemname.png - (optional) sounds/ - place sounds in here - (optional) models/ - place 3d models in here ...and any other lua files to be included by init.lua

Only the init.lua file is required in a mod for it to run on game load, however the other items are needed by some mods to perform their functionality.

Dependencies

The depends text file allows you to specify what mods this mod requires to run, and what needs to be loaded before this mod.

depends.txt

modone modtwo modthree?

As you can see, each modname is on its own line.

Mod names with a question mark following them are optional dependencies. If an optional dependency is installed, it is loaded before the mod. However, if the dependency is not installed, the mod still loads. This is in contrast to normal dependencies, which will cause the current mod not to work if the dependency is not installed.

Mod Packs

Modpacks allow multiple mods to be packaged together, and move together. They are useful if you want to supply multiple mods to a player but don't want to make them download each one individually.

Mod Pack Folder Structure

modpackfolder/ - modone/ - modtwo/ - modthree/ - modfour/ - modpack.txt - signals that this is a mod pack, content does not matter

Example Time

Are you confused? Don't worry, here is an example putting all of this together.

Mod Folder

mymod/ - textures/ - - mymod_node.png - init.lua - depends.txt

depends.txt

default

init.lua

print("This file will be run at load time!") minetest.register_node("mymod:node", { description = "This is a node", tiles = { "mymod_node.png", "mymod_node.png", "mymod_node.png", "mymod_node.png", "mymod_node.png", "mymod_node.png" }, groups = {cracky = 1} })

Our mod has a name of "mymod". It has two text files: init.lua and depends.txt.

The script prints a message and then registers a node - which will be explained in the next chapter.

The depends text file adds a dependency to the default mod, which is in minetest_game.

There is also a texture in textures/ for the node.


Lua Scripts

Introduction

In this chapter we will talk about scripting in Lua, the tools required, and go over some techniques which you will probably find useful.

   Tools       Recommended Editors       Integrated Programming Environments    Coding in Lua       Selection    Programming    Local and Global    Including other Lua Scripts

Tools

A text editor with code highlighting is sufficient for writing scripts in Lua. Code highlighting gives different colors to different words and characters depending on what they mean. This allows you to spot mistakes.

function ctf.post(team,msg) if not ctf.team(team) then return false end if not ctf.team(team).log then ctf.team(team).log = {} end    table.insert(ctf.team(team).log,1,msg) ctf.save()    return true end

For example, keywords in the above snippet are highlighted, such as if, then, end, return. table.insert is a function which comes with Lua by default.

Recommended Editors

Other editors are available, of course.

Integrated Programming Environments

IDEs allow you to debug code like a native application. These are harder to set up than just a text editor.

One such IDE is Eclipse with the Koneki Lua plugin:

Coding in Lua

This section is a Work in Progress. May be unclear.

Programs are a series of commands that run one after another. We call these commands "statements."

Program flow is important, it allows you to direct or skip over statements. There are three main types of flow:

So, what do statements in Lua look like?

local a = 2 -- Set 'a' to 2 local b = 2 -- Set 'b' to 2 local result = a + b -- Set 'result' to a + b, which is 4 a = a + 10 print("Sum is "..result)

Woah, what happened there? a, b and result are variables. They're like what you get in mathematics, A = w * h. The equals signs are assignments, so "result" is set to a + b. Variable names can be longer than one character unlike in maths, as seen with the "result" variable. Lua is case sensitive. A is a different variable to a.

The word "local" before they are first used means that they have local scope, I'll discuss that shortly.

Variable Types

Type Description Example    Integer Whole number local A = 4    Float Decimal local B = 3.2, local C = 5 / 2    String A piece of text local D = "one two three"    Boolean True or False local is_true = false, local E = (1 == 1)    Table Lists Explained below    Function Can run. May require inputs and may return a value local result = func(1, 2, 3)

Not an exhaustive list. Doesn't contain every possible type.

Arithmetic Operators

Symbol Purpose Example    A + B Addition 2 + 2 = 4    A - B Subtraction 2 - 10 = -8    A * B Multiplication 2 * 2 = 4    A / B Division 100 / 50 = 2    A ^ B Powers 2 ^ 2 = 22 = 4    A .. B Join strings "foo" .. "bar" = "foobar"

A string in programming terms is a piece of text.

Not an exhaustive list. Doesn't contain every possible operator.

Selection

The most basic selection is the if statement. It looks like this:

local random_number = math.random(1, 100) -- Between 1 and 100.    if random_number > 50 then print("Woohoo!") else print("No!") end

That example generates a random number between 1 and 100. It then prints "Woohoo!" if that number is bigger than 50, otherwise it prints "No!". What else can you get apart from '>'?

Logical Operators

Symbol Purpose Example    A == B Equals 1 == 1 (true), 1 == 2 (false)    A ~= B Doesn't equal 1 ~= 1 (false), 1 ~= 2 (true)    A > B Greater than 5 > 2 (true), 1 > 2 (false), 1 > 1 (false)    A < B Less than 1 < 3 (true), 3 < 1 (false), 1 < 1 (false)    A >= B Greater than or equals 5 >= 5 (true), 5 >= 3 (true), 5 >= 6 (false)    A <= B Less than or equals 3 <= 6 (true), 3 <= 3 (true)    A and B And (both must be correct) (2 > 1) and (1 == 1) (true), (2 > 3) and (1 == 1) (false)    A or B either or. One or both must be true. (2 > 1) or (1 == 2) (true), (2 > 4) or (1 == 3) (false)    not A not true not (1 == 2) (true), not (1 == 1) (false)

Flow Control: Conditionals

if not A and B then print("Yay!") end

Which prints "Yay!" if A is false and B is true.

Logical and arithmetic operators work exactly the same, they both accept inputs and return a value which can be stored.

local A = 5 local is_equal = (A == 5)    if is_equal then print("Is equal!") end

Flow Control: Loops

Each of the following loops do the same thing (printing out the numbers from 0 to 10 inclusive)

i = 0; while i < 10 do print i i = i + 1 end    i = 0 repeat print i i = i + 1 until i > 10    -- "numeric loop" for i = 0, 10, 1 do print i end    -- "generic loop" list = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for _,i in pairs(list) do print i end

The last two ("numeric" and "generic") types of loop share two properties: The loop variables are local to the loop body and you should not assign any value to the loop variables within the loop. (This is different from some languages where you could, for example, do "if (i = 7) then i = 11" to make it exit a numeric loop early)

Programming

Programming is the action of talking a problem, such as sorting a list of items, and then turning it into steps that a computer can understand.

Teaching you the logical process of programming is beyond the scope of this book, however the following websites are quite useful in developing this:

Codecademy

Codecademy is one of the best resources for learning to 'code', it provides an interactive tutorial experience.

Scratch

Scratch is a good resource when starting from absolute basics, learning the problem solving techniques required to program.

Scratch is designed to teach children how to program, it isn't a serious programming language.

Local and Global

Whether a variable is local or global determines where it can be written to or read to. A local variable is only accessible from where it is defined. Here are some examples:

-- Accessible from within this script file local one = 1    function myfunc() -- Accessible from within this function local two = one + one    if two == one then -- Accessible from within this if statement local three = one + two end end

Whereas global variables can be accessed from anywhere in the script file, and from any other mod.

my_global_variable = "blah"    function one() my_global_variable = "three" end    print(my_global_variable) -- Output: "blah" one() print(my_global_variable) -- Output: "three"

Locals should be used as much as possible

Lua is global by default (unlike most other programming languages). Local variables must be identified as such.

function one() foo = "bar" end    function two() print(dump(foo)) -- Output: "bar" end    one() two()

dump() is a function that can turn any variable into a string so the programmer can see what it is. The foo variable will be printed as "bar", including the quotes which show it is a string.

This is sloppy coding, and Minetest will in fact warn you about this:

[WARNING] Assigment to undeclared global 'foo' inside function at init.lua:2

To correct this, use "local":

function one() local foo = "bar" end    function two() print(dump(foo)) -- Output: nil end    one() two()

Nil means not initalised. The variable hasn't been assigned a variable yet, doesn't exist or has been uninitialised (ie: set to nil)

The same goes for functions. Functions are variables of a special type. You should make functions as local as much as possible, as other mods could have functions of the same name.

local function foo(bar) return bar * 2 end

If you want your functions to be accessible from other scripts or mods, it is recommended that you add them all into a table with the same name as the mod:

mymod = {} function mymod.foo(bar) return "foo" .. bar end    -- In another mod, or script: mymod.foo("foobar")

Including other Lua Scripts

You can include Lua scripts from your mod, or another mod like this:

dofile(minetest.get_modpath("modname") .. "/script.lua")

"local" variables declared outside of any functions in a script file will be local to that script. You won't be able to access them from any other scripts.

As for how you divide code up into files, it doesn't matter that much. The most important thing is your code is easy to read and edit. You won't need to use it for smaller projects.


Nodes, Items and Crafting

Introduction

In this chapter we will learn how to register a new node or craftitem, and create craft recipes.

   Item Strings

   Textures

   Registering a Craftitem

   Foods

   Registering a basic Node

   Crafting

   Groups

Item Strings

Each item, whether that be a node, craftitem, tool or entity, has an item string.

This is sometimes referred to as registered name or just name. A string in programming terms is a piece of text.

modname:itemname

The modname is the name of the folder your mod is in. You may call the itemname any thing you like, however it should be relevant to what the item is, and it can't already be registered.

Overriding

Overriding allows you to:

To override, you prefix the item string with a colon, :. Declaring an item as :default:dirt will override the default:dirt in the default mod.

Textures

Textures are usually 16 by 16 pixels. They can be any resolution, but it is recommended that they are in the order of 2 (eg, 16, 32, 64, 128, etc), as other resolutions may not be supported correctly on older devices.

Textures should be placed in textures/. Their name should match modname_itemname.png.

JPEGs are supported, but they do not support transparency and are generally bad quality at low resolutions.

Registering a Craftitem

Craftitems are the simplest items in Minetest. Craftitems cannot be placed in the world. They are used in recipes to create other items, or they can be used be the player, such as food.

minetest.register_craftitem("mymod:diamond_fragments", { description = "Alien Diamond Fragments", inventory_image = "mymod_diamond_fragments.png" })

Item definitions like seen above are usually made up of an unique item string and a definition table. The definition table contains attributes which affect the behaviour of the item.

Foods

Foods are items that cure health. To create a food item, you need to define the on_use property like this:

minetest.register_craftitem("mymod:mudpie", { description = "Alien Mud Pie", inventory_image = "myfood_mudpie.png", on_use = minetest.item_eat(20) })

The number supplied to the minetest.item_eat function is the number of hit points that are healed by this food. Two hit points make one heart, and because there are 10 hearts there are 20 hitpoints. Hitpoints don't have to be integers (whole numbers), they can be decimals.

Sometimes you may want a food to be replaced with another item when being eaten, for example smaller pieces of cake or bones after eating meat. To do this, use:

minetest.item_eat(hp, replace_with_item)

Where replace_with_item is an item string.

Foods, extended

How about if you want to do more than just eat the item, such as send a message to the player?

minetest.register_craftitem("mymod:mudpie", { description = "Alien Mud Pie", inventory_image = "myfood_mudpie.png", on_use = function(itemstack, user, pointed_thing) hp_change = 20 replace_with_item = nil    minetest.chat_send_player(user:get_player_name(), "You ate an alien mud pie!")    -- Support for hunger mods using minetest.register_on_item_eat for _ , callback in pairs(minetest.registered_on_item_eats) do local result = callback(hp_change, replace_with_item, itemstack, user, pointed_thing) if result then return result end end    if itemstack:take_item() ~= nil then user:set_hp(user:get_hp() + hp_change) end return itemstack end })

If you are creating a hunger mod, or if you are affecting foods outside of your mod, you should consider using minetest.register_on_item_eat

Registering a basic node

In Minetest, a node is an item that you can place. Most nodes are 1m x 1m x 1m cubes, however the shape doesn't have to be a cube - as we will explore later.

Let's get onto it. A node's definition table is very similar to a craftitem's definition table, however you need to set the textures for the faces of the cube.

minetest.register_node("mymod:diamond", { description = "Alien Diamond", tiles = {"mymod_diamond.png"}, is_ground_content = true, groups = {cracky=3, stone=1} })

Let's ignore groups for now, and take a look at the tiles. The tiles property is a table of texture names the node will use. When there is only one texture, this texture is used on every side.

What if you would like a different texture for each side? Well, you give a table of 6 texture names, in this order:

up (+Y), down (-Y), right (+X), left (-X), back (+Z), front (-Z). (+Y, -Y, +X, -X, +Z, -Z)

Remember: +Y is upwards in Minetest, along with most video games. A plus direction means that it is facing positive co-ordinates, a negative direction means that it is facing negative co-ordinates.

minetest.register_node("mymod:diamond", { description = "Alien Diamond", tiles = { "mymod_diamond_up.png", "mymod_diamond_down.png", "mymod_diamond_right.png", "mymod_diamond_left.png", "mymod_diamond_back.png", "mymod_diamond_front.png" }, is_ground_content = true, groups = {cracky = 3}, drop = "mymod:diamond_fragments" -- ^ Rather than dropping diamond, drop mymod:diamond_fragments })

The is_ground_content attribute allows caves to be generated over the stone.

Crafting

There are several different types of crafting, identified by the type property.

   shaped - Ingredients must be in the correct position.

   shapeless - It doesn't matter where the ingredients are, just that there is the right amount.

   cooking - Recipes for the furnace to use.

      fuel - Defines items which can be burned in furnaces.

   tool_repair - Used to allow the repairing of tools.

Craft recipes do not use Item Strings to uniquely identify themselves.

Shaped

Shaped recipes are the normal recipes - the ingredients have to be in the right place. For example, when you are making a pickaxe the ingredients have to be in the right place for it to work.

minetest.register_craft({ output = "mymod:diamond_chair 99", recipe = { {"mymod:diamond_fragments", "", ""}, {"mymod:diamond_fragments", "mymod:diamond_fragments", ""}, {"mymod:diamond_fragments", "mymod:diamond_fragments", ""} } })

This is pretty self-explanatory. You don't need to define the type, as shaped crafts are default. The 99 after the itemname in output makes the craft create 99 chairs rather than one.

If you notice, there is a blank column at the far end. This means that the craft must always be exactly that. In most cases, such as the door recipe, you don't care if the ingredients are always in an exact place, you just want them correct relative to each other. In order to do this, delete any empty rows and columns. In the above case, there is an empty last column, which, when removed, allows the recipe to be crafted if it was all moved one place to the right.

minetest.register_craft({ output = "mymod:diamond_chair", recipe = { {"mymod:diamond_fragments", ""}, {"mymod:diamond_fragments", "mymod:diamond_fragments"}, {"mymod:diamond_fragments", "mymod:diamond_fragments"} } })

Shapeless

Shapeless recipes are a type of recipe which is used when it doesn't matter where the ingredients are placed, just that they're there. For example, when you craft a bronze ingot, the steel and the copper do not need to be in any specific place for it to work.

minetest.register_craft({ type = "shapeless", output = "mymod:diamond", recipe = { {"mymod:diamond_fragments" "mymod:diamond_fragments", "mymod:diamond_fragments"} } })

When you are crafting the diamond, the three diamond fragments can be anywhere in the grid.

Note: You can still use options like the number after the result, as mentioned earlier.

Cooking

Recipes with the type "cooking" are not made in the crafting grid, but are cooked in furnaces, or other cooking tools that might be found in mods. For example, you use a cooking recipe to turn ores into bars.

minetest.register_craft({ type = "cooking", output = "mymod:diamond_fragments", recipe = "default:coalblock", cooktime = 10, })

As you can see from this example, the only real difference in the code is that the recipe is just a single item, compared to being in a table (between braces). They also have an optional "cooktime" parameter, which defines how long the item takes to cook. If this is not set it defaults to 3.

The recipe above works when the coal block is in the input slot, with some form of a fuel below it. It creates diamond fragments after 10 seconds!

Fuel

This type is an accompaniment to the cooking type, as it defines what can be burned in furnaces and other cooking tools from mods.

minetest.register_craft({ type = "fuel", recipe = "mymod:diamond", burntime = 300, })

They don't have an output like other recipes, but they have a burn time which defines how long they will last as fuel, in seconds. So, the diamond is good as fuel for 300 seconds!

Groups

Items can be members of many groups, and groups can have many members. Groups are usually identified using group:group_name There are several reason you use groups.

Groups can be used in crafting recipes to allow interchangeability of ingredients. For example, you may use group:wood to allow any wood item to be used in the recipe.

Dig types

Let's look at our above mymod:diamond definition. You'll notice this line:

groups = {cracky = 3}

Cracky is a digtype. Dig types specify what type of the material the node is physically, and what tools are best to destroy it.

Group Description

crumbly dirt, sand

cracky tough but crackable stuff like stone.

snappy something that can be cut using fine tools; e.g. leaves, smallplants, wire, sheets of metal

choppy something that can be cut using force; e.g. trees, wooden planks

fleshy Living things like animals and the player. This could imply some blood effects when hitting.

explody Especially prone to explosions

oddly_breakable_by_hand Torches, etc, quick to dig


Creating Textures

Introduction

In this chapter we will learn how to create and optimise textures for Minetest. We will use techniques relevant for pixel art.

   Resources

   Editors

   Common Mistakes

Resources

16x16 Pixel Art Tutorial

About MS Paint

You need to be aware that MS Paint does not support transparency. This won't matter if you're making textures for the side of nodes, but generally you need transparency for craft items, etc.

Editing in GIMP

IMP is commonly used in the Minetest community. It has quite a high learning curve as lots of its features are hidden away.

Use the pencil tool to edit individual pixels

Pencil in GIMP

Set the rubber to hard edge

Rubber in GIMP

Common Mistakes

Blurred textures through usage of incorrect tools

For the most part, you want to manipulate pixels on an individual basis. The tool for this in most editors is the pencil tool.


Node Drawtypes

This chapter is incomplete

Some drawtypes have not been explained yet, and placeholder images are being used.

Introduction

In this chapter we explain all the different types of node drawtypes there are.

First of all, what is a drawtype? A drawtype defines how the node is to be drawn. A torch looks different to water, water looks different to stone.

The string you use to determine the drawtype in the node definition is the same as the title of the sections, except in lower case.

   Normal

   Airlike

   Liquid

      FlowingLiquid

   Glasslike

   Glasslike_Framed

      Glasslike_Framed_Optional

   Allfaces

      Allfaces_Optional

   Torchlike

   Nodebox

This article is not complete yet. These drawtypes are missing:

Normal

This is, well, the normal drawtypes. Nodes that use this will be cubes with textures for each side, simple-as.

Here is the example from the Nodes, Items and Crafting chapter. Notice how you don't need to declare the drawtype.

minetest.register_node("mymod:diamond", { description = "Alien Diamond", tiles = { "mymod_diamond_up.png", "mymod_diamond_down.png", "mymod_diamond_right.png", "mymod_diamond_left.png", "mymod_diamond_back.png", "mymod_diamond_front.png" }, is_ground_content = true, groups = {cracky = 3}, drop = "mymod:diamond_fragments" })

Airlike

These nodes are see through, and thus have no textures.

minetest.register_node("myair:air", { description = "MyAir (you hacker you!)", drawtype = "airlike",    paramtype = "light", -- ^ Allows light to propagate through the node with the -- light value falling by 1 per node.    sunlight_propagates = true, -- Sunlight shines through walkable = false, -- Would make the player collide with the air node pointable = false, -- You can't select the node diggable = false, -- You can't dig the node buildable_to = true, -- Nodes can be replace this node. -- (you can place a node and remove the air node -- that used to be there)    air_equivalent = true, drop = "", groups = {not_in_creative_inventory=1} })

Liquid

These nodes are complete liquid nodes, the liquid flows outwards from position using the flowing liquid drawtype. For each liquid node you should also have a flowing liquid node.

-- Some properties have been removed as they are beyond the scope of this chapter. minetest.register_node("default:water_source", { drawtype = "liquid", paramtype = "light",    inventory_image = minetest.inventorycube("default_water.png"), -- ^ this is required to stop the inventory image from being animated    tiles = { { name = "default_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0 } } },    special_tiles = { -- New-style water source material (mostly unused) { name = "default_water_source_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0}, backface_culling = false, } },    -- -- Behavior -- walkable = false, -- The player falls through pointable = false, -- The player can't highlight it diggable = false, -- The player can't dig it buildable_to = true, -- Nodes can be replace this node    alpha = 160,    -- -- Liquid Properties -- drowning = 1, liquidtype = "source",    liquid_alternative_flowing = "default:water_flowing", -- ^ when the liquid is flowing    liquid_alternative_source = "default:water_source", -- ^ when the liquid is a source    liquid_viscosity = WATER_VISC, -- ^ how fast    liquid_range = 8, -- ^ how far    post_effect_color = {a=64, r=100, g=100, b=200}, -- ^ color of screen when the player is submerged })

FlowingLiquid

See default:water_flowing in the default mod in minetest_game, it is mostly the same as the above example

Glasslike

When you place multiple glasslike nodes together, you'll notice that the internal edges are hidden, like this:

Glasslike's Edges

minetest.register_node("default:obsidian_glass", { description = "Obsidian Glass", drawtype = "glasslike", tiles = {"default_obsidian_glass.png"}, paramtype = "light", is_ground_content = false, sunlight_propagates = true, sounds = default.node_sound_glass_defaults(), groups = {cracky=3,oddly_breakable_by_hand=3}, })

Glasslike_Framed

This makes the node's edge go around the whole thing with a 3D effect, rather than individual nodes, like the following:

Glasslike_Framed's Edges

minetest.register_node("default:glass", { description = "Glass", drawtype = "glasslike_framed",    tiles = {"default_glass.png", "default_glass_detail.png"}, inventory_image = minetest.inventorycube("default_glass.png"),    paramtype = "light", sunlight_propagates = true, -- Sunlight can shine through block is_ground_content = false, -- Stops caves from being generated over this node.    groups = {cracky = 3, oddly_breakable_by_hand = 3}, sounds = default.node_sound_glass_defaults() })

Glasslike_Framed_Optional

"optional" drawtypes need less rendering time if deactivated on the client's side.

Allfaces

Allfaces nodes are partially transparent nodes - they have holes on the faces - which show every single face of the cube, even if sides are up against another node (which would normally be hidden). Leaves in vanilla minetest_game use this drawtype.

minetest.register_node("default:leaves", { description = "Leaves", drawtype = "allfaces_optional", tiles = {"default_leaves.png"} })

Allfaces_Optional

Allows clients to disable it using new_style_leaves = 0, requiring less rendering time.

TorchLike

TorchLike nodes are 2D nodes which allow you to have different textures depending on whether they are placed against a wall, on the floor or on the ceiling.

TorchLike nodes are not restricted to torches, you could use the for switches or other items which need to have different textures depending on where they are placed.

minetest.register_node("foobar:torch", { description = "Foobar Torch", drawtype = "torchlike", tiles = { {"foobar_torch_floor.png"}, {"foobar_torch_ceiling.png"}, {"foobar_torch_wall.png"} }, inventory_image = "foobar_torch_floor.png", wield_image = "default_torch_floor.png", light_source = LIGHT_MAX-1,    -- Determines how the torch is selected, ie: the wire box around it. -- each value is { x1, y1, z1, x2, y2, z2 } -- (x1, y1, y1) is the bottom front left corner -- (x2, y2, y2) is the opposite - top back right. -- Similar to the nodebox format. selection_box = { type = "wallmounted", wall_top = {-0.1, 0.5-0.6, -0.1, 0.1, 0.5, 0.1}, wall_bottom = {-0.1, -0.5, -0.1, 0.1, -0.5+0.6, 0.1}, wall_side = {-0.5, -0.3, -0.1, -0.5+0.3, 0.3, 0.1}, } })

Nodebox

Nodeboxes allow you to create a node which is not cubic, but is instead made out of as many cuboids as you like.

minetest.register_node("stairs:stair_stone", { drawtype = "nodebox", paramtype = "light", node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, } })

The most important part is the nodebox table:

{-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}

Each row is a cubiod which are joined to make a single node. The first three numbers are the co-ordinates, from -0.5 to 0.5 inclusive, of the bottom front left most corner, the last three numbers are the opposite corner. They are in the form X, Y, Z, where Y is up.

You can use the NodeBoxEditor to create node boxes by dragging the edges, it is more visual than doing it by hand.

Wallmounted Nodebox

Sometimes you want different nodeboxes for when it is place on the floor, wall and ceiling, like with torches.

minetest.register_node("default:sign_wall", { drawtype = "nodebox", node_box = { type = "wallmounted",    -- Ceiling wall_top = { {-0.4375, 0.4375, -0.3125, 0.4375, 0.5, 0.3125} },    -- Floor wall_bottom = { {-0.4375, -0.5, -0.3125, 0.4375, -0.4375, 0.3125} },    -- Wall wall_side = { {-0.5, -0.3125, -0.4375, -0.4375, 0.3125, 0.4375} } }, })


Node Metadata

Introduction

In this chapter you will learn how to manipulate a node's metadata.

   What is Node Metadata?

   Getting a Metadata Object

   Reading Metadata

   Setting Metadata

   Lua Tables

   Infotext

   Your Turn

What is Node Metadata?

Metadata is data about data. So Node Metadata is data about a node.

You may use metadata to store:

The node's type, light levels and orientation are not stored in the metadata, but are rather part of the data itself.

Metadata is stored in a key value relationship.

Key Value

foo bar

owner player1

counter 5

Getting a Metadata Object

Once you have a position of a node, you can do this:

local meta = minetest.get_meta(pos) -- where pos = { x = 1, y = 5, z = 7 }

Reading Metadata

local value = meta:get_string("key")    if value then print(value) else -- value == nil -- metadata of key "key" does not exist print(value) end

Here are all the get functions you can use, as of writing:

In order to do booleans, you should use get_string and minetest.is_yes:

local value = minetest.is_yes(meta:get_string("key"))    if value then print("is yes") else print("is no") end

Setting Metadata

Setting meta data works pretty much exactly the same way.

local value = "one" meta:set_string("key", value)    meta:set_string("foo", "bar")

Here are all the set functions you can use, as of writing:

Lua Tables

You can convert to and from lua tables using to_table and from_table:

local tmp = meta:to_table() tmp.foo = "bar" meta:from_table(tmp)

Infotext

The Minetest Engine reads the field infotext in order to make text appear on mouse-over. This is used by furnaces to show progress and signs to show their text.

meta:set_string("infotext", "Here is some text that will appear on mouse over!")

Your Turn

Make a block which disappears after it has been punched 5 times. (use on_punch in the node def and minetest.set_node)


Active Block Modifiers

Introduction

In this chapter we will learn how to create an Active Block Modifier (ABM). An active block modifier allows you to run code on certain nodes at certain intervals. Please be warned, ABMs which are too frequent or act on too many nodes cause massive amounts of lag. Use them lightly.

   Special Growing Grass

   Your Turn

Special Growing Grass

We are now going to make a mod (yay!). It will add a type of grass called alien grass - it grows near water on grassy blocks.

minetest.register_node("aliens:grass", { description = "Alien Grass", light_source = 3, -- The node radiates light. Values can be from 1 to 15 tiles = {"aliens_grass.png"}, groups = {choppy=1}, on_use = minetest.item_eat(20) })    minetest.register_abm({ nodenames = {"default:dirt_with_grass"}, neighbors = {"default:water_source", "default:water_flowing"}, interval = 10.0, -- Run every 10 seconds chance = 50, -- Select every 1 in 50 nodes action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node({x = pos.x, y = pos.y + 1, z = pos.z}, {name = "aliens:grass"}) end })

Every ten seconds the ABM is run. Each node which has the correct nodename and the correct neighbors then has a 1 in 5 chance of being run. If a node is run on, an alien grass block is placed above it. Please be warned, that will delete any blocks above grass blocks - you should check there is space by doing minetest.get_node.

That's really all there is to ABMs. Specifying a neighbor is optional, so is chance.

Your Turn


Chat and Commands

Introduction

In this chapter we will learn how to interact with player chat, including sending messages, intercepting messages and registering chat commands.

   Send a message to all players.

   Send a message to a certain player.

   Chat commands.

   Intercepting messages.

Send a message to all players

It's as simple as calling the chat_send_all function, as so:

minetest.chat_send_all("This is a chat message to all players")

Here is an example of how it would appear ingame (there are other messages around it).

<player1> Look at this entrance This is a chat message to all players <player2> What about it?

Send a message to a certain player

It's as simple as calling the chat_send_player function, as so:

minetest.chat_send_player("player1", "This is a chat message for player1")

Only player1 can see this message, and it's displayed the same as above.

Older mods

Occasionally you'll see mods with code like this:

minetest.chat_send_player("player1", "This is a server message", true) minetest.chat_send_player("player1", "This is a server message", false)

The boolean at the end was documented thus:

minetest.chat_send_player(name, text, prepend) -^ prepend: optional, if it is set to false "Server -!- " will not be prepended to the message

It has been depreciated so the third parameter is now ignored and has no effect.

Chat commands

In order to register a chat command, such as /foo, use register_chatcommand:

minetest.register_chatcommand("foo", { privs = { interact = true }, func = function(name, param) return true, "You said " .. param .. "!" end })

Calling /foo bar will result in You said bar! in the chat console.

Let's do a break down:

privs = { interact = true },

This makes it so that only players with the interact privilege can run the command. Other players will see an error message informing them which privilege they're missing.

return true, "You said " .. param .. "!"

This returns two values, firstly a boolean which says that the command succeeded and secondly the chat message to send to the player.

Intercepting messages

You can use register_on_chat_message, like so:

minetest.register_on_chat_message(function(name, message) print(name .. " said " .. message) return false end)

By returning false, we're allowing the chat message to be sent by the default handler. You can actually miss out the line return false, and it would still work the same.

WARNING: CHAT COMMANDS ARE ALSO INTERCEPTED. If you only want to catch player messages, you need to do this:

minetest.register_on_chat_message(function(name, message) if message:sub(1, 1) == "/" then print(name .. " ran chat command") return false end    print(name .. " said " .. message) return false end)


Player Physics

Introduction

Player physics can be modified using physics overrides. Physics overrides can set the walking speed, jump speed and gravity constants. Physics overrides are set on a player by player basis, and are multipliers - a value of 2 for gravity would make gravity twice as strong.

   Basic Interface

   Your Turn

Basic Interface

Here is an example which adds an antigravity command, which puts the caller in low G:

minetest.register_chatcommand("antigravity", func = function(name, param) local player = minetest.get_player_by_name(name) player:set_physics_override({ gravity = 0.1 -- set gravity to 10% of its original value -- (0.1 * 9.81) }) end })

Possible Overrides

player:set_physics_override() is given a table of overrides.

According to lua_api.txt, these can be:

The sneak glitch allows the player to climb an 'elevator' made out of a certain placement of blocks by sneaking (pressing shift) and pressing space to ascend. It was originally a bug in Minetest, but was kept as it is used on many servers to get to higher levels. They added the option above so you can disable it.

Multiple mods

Please be warned that mods that override the physics of a player tend to be incompatible with each other. When setting an override, it overwrites and override that has been set before, by your or anyone else's mod.

Your Turn


Formspecs

Introduction

[image: Screenshot of furnace formspec, labelled.]

In this chapter we will learn how to create a formspec and display it to the user. A formspec is the specification code for a form. In Minetest, forms are windows like the Inventory which allow you to move your mouse and enter information. You should consider using Heads Up Display (HUD) elements if you do not need to get user input - notifications, for example - as unexpected windows tend to disrupt game play.

   Formspec syntax

   Displaying Forms

   Callbacks

   Contexts

   Node Meta Formspecs

Formspec Syntax

Formspecs have a rather weird syntax. They consist of a series of tags which are in the following form:

element_type[param1;param2;...]

Firstly the element type is declared, and then the attributes are given in square brackets.

(An element is an item such as a text box or button, or it is meta data such as size or background).

Here are two elements, of types foo and bar.

foo[param1]bar[param1]

Size[w, h]

Nearly all forms have a size tag. They are used to declare the size of the window required. Forms don't use pixels as co-ordinates, they use a grid, based on inventories. A size of (1, 1) means the form is big enough to host a 1x1 inventory. The reason this is used is because it is independent on screen resolution - The form should work just as well on large screens as small screens. You can use decimals in sizes and co-ordinates.

size[5,2]

Co-ordinates and sizes only use one attribute. The x and y values are separated by a comma, as you can see above.

Field[x, y; w, h; name; label; default]

This is a textbox element. Most other elements have a similar style of attributes. The "name" attribute is used in callbacks to get the submitted information. The others are pretty self-explaintary.

field[1,1;3,1;firstname;Firstname;]

It is perfectly valid to not define an attribute, like above.

Other Elements

You should look in lua_api.txt for a list of all possible elements, just search for "Formspec". It is near line 1019, at time of writing.

Displaying Formspecs

Here is a generalized way to show a formspec

minetest.show_formspec(playername, formname, formspec)

Formnames should be itemnames, however that is not enforced. There is no need to override a formspec here, formspecs are not registered like nodes and items are, instead the formspec code is sent to the player's client for them to see, along with the formname. Formnames are used in callbacks to identify which form has been submitted, and see if the callback is relevant.

Example

-- Show form when the /formspec command is used. minetest.register_chatcommand("formspec", { func = function(name, param) minetest.show_formspec(name, "mymod:form", "size[4,3]" .. "label[0,0;Hello, " .. name .. "]" .. "field[1,1.5;3,1;name;Name;]" .. "button_exit[1,2;2,1;exit;Save]") end })

The above example shows a formspec to a player when they use the /formspec command.

Note: the .. is used to join two strings together. The following two lines are equivalent:

"foobar" "foo" .. "bar"

Callbacks

Let's expand on the above example.

-- Show form when the /formspec command is used. minetest.register_chatcommand("formspec", { func = function(name, param) minetest.show_formspec(name, "mymod:form", "size[4,3]" .. "label[0,0;Hello, " .. name .. "]" .. "field[1,1.5;3,1;name;Name;]" .. "button_exit[1,2;2,1;exit;Save]") end })    -- Register callback minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "mymod:form" then -- Formname is not mymod:form, -- exit callback. return false end    -- Send message to player. minetest.chat_send_player(player:get_player_name(), "You said: " .. fields.name .. "!")    -- Return true to stop other minetest.register_on_player_receive_fields -- from receiving this submission. return true end)

The function given in minetest.register_on_player_receive_fields is called everytime a user submits a form. Most callbacks will check the formname given to the function, and exit if it is not the right form. However, some callbacks may need to work on multiple forms, or all forms - it depends on what you want to do.

Fields

The fields parameter to the function is a table, index by string, of the values submitted by the user. You can access values in the table by doing fields.name, where 'name' is the name of the element.

As well as having the values of each element, you can also get which button was clicked. In this case, the button called 'exit' was clicked, so fields.exit will be true.

Some elements can submit the form without the user having to click a button, such as a check box. You can detect for these cases by looking for a clicked button.

-- An example of what fields could contain, -- using the above code { name = "Foo Bar", exit = true }

Contexts

In quite a lot of cases you want your minetest.show_formspec to give information to the callback which you don't want to have to send to the client. Information such as what a chat command was called with, or what the dialog is about.

Let's say you are making a form to handle land protection information.

-- -- Step 1) set context when player requests the formspec --    -- land_formspec_context[playername] gives the player's context. local land_formspec_context = {}    minetest.register_chatcommand("land", { func = function(name, param) if param == "" then minetest.chat_send_player(name, "Incorrect parameters - supply a land ID") return end    -- Save information land_formspec_context[name] = {id = param}    minetest.show_formspec(name, "mylandowner:edit", "size[4,4]" .. "field[1,1;3,1;plot;Plot Name;]" .. "field[1,2;3,1;owner;Owner;]" .. "button_exit[1,3;2,1;exit;Save]") end })    -- -- Step 2) retrieve context when player submits the form -- minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "mylandowner:edit" then return false end    -- Load information local context = land_formspec_context[player:get_player_name()]    if context then minetest.chat_send_player(player:get_player_name(), "Id " .. context.id .. " is now called " .. fields.plot .. " and owned by " .. fields.owner)    -- Delete context if it is no longer going to be used land_formspec_context[player:get_player_name()] = nil    return true else -- Fail gracefully if the context does not exist. minetest.chat_send_player(player:get_player_name(), "Something went wrong, try again.") end end)

Node Meta Formspecs

minetest.show_formspec is not the only way to show a formspec, you can also add formspecs to a node's meta data. This is used on nodes such as chests to allow for faster opening times - you don't need to wait for the server to send the player the chest formspec.

minetest.register_node("mymod:rightclick", { description = "Rightclick me!", tiles = {"mymod_rightclick.png"}, groups = {cracky = 1}, after_place_node = function(pos, placer) -- This function is run when the chest node is placed. -- The following code sets the formspec for chest. -- Meta is a way of storing data onto a node.    local meta = minetest.get_meta(pos) meta:set_string("formspec", "size[5,5]".. "label[1,1;This is shown on right click]".. "field[1,2;2,1;x;x;]") end, on_receive_fields = function(pos, formname, fields, player) if(fields.quit) then return end print(fields.x) end })

Formspecs set this way do not trigger the same callback. In order to receive form input for meta formspecs, you must include an on_receive_fields entry when registering the node.

This style of callback can trigger the callback when you press enter in a field, which is impossible with minetest.show_formspec, however, this kind of form can only be shown by right-clicking on a node. It cannot be triggered programmatically.


HUD

Experimental Feature

The HUD feature will probably be rewritten in an upcoming Minetest release. Be aware that you may need to update your mods if the API is changed.

Introduction

Heads Up Display (HUD) elements allow you to show text, images, and other graphical elements.

HUD doesn't accept user input. For that, you should use a Formspec.

   Basic Interface

   Positioning

   Text Elements

   Image Elements

   Other Elements

Basic Interface

HUD elements are created using a player object. You can get the player object from a username like this:

local player = minetest.get_player_by_name("username")

Once you have the player object, you can create an element:

local idx = player:hud_add({ hud_elem_type = "text", position = {x = 1, y = 0}, offset = {x=-100, y = 20}, scale = {x = 100, y = 100}, text = "My Text" })

This attributes in the above table and what they do vary depending on the hud_elem_type.

A number is returned by the hud_add function which is needed to identify the HUD element at a later time, if you wanted to change or delete it.

You can change an attribute after creating a HUD element, such as what the text says:

player:hud_change(idx, "text", "New Text")

You can also delete the element:

player:hud_remove(idx)

Positioning

Screens come in different sizes, and HUD elements need to work well on all sizes. You locate an element using a combination of a position and an offset.

The position is a co-ordinate between (0, 0) and (1, 1) which determines where, relative to the screen width and height, the element goes. For example, an element with a position of (0.5, 0.5) will be in the center of the screen.

The offset applies a pixel offset to the position.

An element with a position of (0, 0) and an offset of (10, 10) will end up at the screen co-ordinates (0 * width + 10, 0 * height + 10).

Please note that offset scales to DPI and a user defined factor.

Text Elements

A text element is the simplest form of a HUD element.

Here is our earlier example, but with comments to explain each part:

local idx = player:hud_add({ hud_elem_type = "text", -- This is a text element position = {x = 1, y = 0}, offset = {x=-100, y = 20}, scale = {x = 100, y = 100}, -- Maximum size of text, crops off any out of these bounds text = "My Text" -- The actual text shown })

Colors

You can apply colors to the text, using the number attribute. Colors are in Hexadecimal form.

local idx = player:hud_add({ hud_elem_type = "text", position = {x = 1, y = 0}, offset = {x=-100, y = 20}, scale = {x = 100, y = 100}, text = "My Text", number = 0xFF0000 -- Red })

Image Elements

Displays an image on the HUD.

The X co-ordinate of the scale attribute is the scale of the image, with 1 being the original texture size. Negative values represent that percentage of the screen it should take; e.g. x=-100 means 100% (width).

Use text to specify the name of the texture.

Other Elements

Have a look at lua_api.txt for a complete list of HUD elements.


ItemStack

Introduction

In this chapter you will learn how to use ItemStacks.

   Creating ItemStacks

   Name and Count

   Adding and Taking Items

   Wear

   Lua Tables

   Metadata

   More Methods

Creating ItemStacks

An item stack is a... stack of items. It's basically just an item type with a count of items in the stack.

You can create a stack like so:

local items = ItemStack("default:dirt") local items = ItemStack("default:stone 99")

You could alternatively create a blank ItemStack and fill it using methods:

local items = ItemStack() if items:set_name("default:dirt") then items:set_count(99) else print("An error occured!") end

And you can copy stacks like this:

local items2 = ItemStack(items)

Name and Count

local items = ItemStack("default:stone") print(items:get_name()) -- default:stone print(items:get_count()) -- 1    items:set_count(99) print(items:get_name()) -- default:stone print(items:get_count()) -- 99    if items:set_name("default:dirt") then print(items:get_name()) -- default:dirt print(items:get_count()) -- 99 else error("This shouldn't happen") end

Adding and Taking Items

Adding

Use add_item to add items to an ItemStack. An ItemStack of the items that could not be added is returned.

local items = ItemStack("default:stone 50") local to_add = ItemStack("default:stone 100") local leftovers = items:add_item(to_add)    print("Could not add" .. leftovers:get_count() .. " of the items.") -- ^ will be 51

Taking

The following code takes up to 100. If there aren't enough items in the stack, it will take as much as it can.

local taken = items:take_item(100) -- taken is the ItemStack taken from the main ItemStack    print("Took " .. taken:get_count() .. " items")

Wear

ItemStacks also have wear on them. Wear is a number out of 65535, the higher is more warn.

You use add_wear(), get_wear() and set_wear(wear).

local items = ItemStack("default:dirt") local max_uses = 10    -- This is done automatically when you use a tool that digs things -- It increases the wear of an item by one use. items:add_wear(65535 / (max_uses - 1))

When digging a node, the amount of wear a tool gets may depends on the node being dug. So max_uses varies depending on what is being dug.

Lua Tables

local data = items:to_table() local items2 = ItemStack(data)

Metadata

ItemStacks can also have a single field of metadata attached to them.

local meta = items:get_metadata() print(dump(meta)) meta = meta .. " ha!" items:set_metadata(meta) -- if ran multiple times, would give " ha! ha! ha!"

More Methods

Have a look at the list of methods for an ItemStack. There are a lot more available than talked about here.


Releasing a Mod

Introduction

In this chapter we will find out how to publish a mod so that other users can use it.

   License Choices

   Packaging

   Uploading

   Forum Topic

Before you release your mod, there are some things to think about:

License Choices

You need to specify a license for your mod. Public domain is not a valid licence, as the definition varies in different countries.

First thing you need to note is that your code and your art need different things from the license they use. Creative Commons licenses shouldn't be used with source code, but rather with artistic works such as images, text and meshes.

You are allowed any license, however mods which disallow derivatives are banned from the forum. (Other developers must be able to take your mod, modify it, and release it again.)

LGPL and CC-BY-SA

This is a common license combination in the Minetest community, as it is what Minetest and minetest_game use. You license your code under LGPL 2.1 and your art under CC-BY-SA.

Add this copyright notice to your README.txt, or as a new file called LICENSE.txt

License for Code ~~~~~~~~~~~~~~~~    Copyright (C) 2010-2013 Your Name <emailaddress>    This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.    You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.    License for Textures, Models and Sounds ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    CC-BY-SA 3.0 UNPORTED. Created by Your Name

WTFPL or CC0

These licenses allows anyone to do what they want with your mod. Modify, redistribute, sell, leave out attribution. They can be used for both code and art.

Packaging

There are some files that we recommend you include in your mod when you release it.

README.txt

You should provide a readme file. This should state:

Example:

My Super Special Mod =~=~=~=~=~=~=~=~=~==    Adds magic, rainbows and other special things.    Version: 1.1 License: LGPL 2.1 or later    Dependencies: default mod (found in minetest_game)    Report bugs or request help on the forum topic.    Installation ~~~~~~~~~~~~    Unzip the archive, rename the folder to to modfoldername and place it in minetest/mods/minetest/    ( GNU/Linux: If you use a system-wide installation place it in ~/.minetest/mods/minetest/. )    ( If you only want this to be used in a single world, place the folder in worldmods/ in your worlddirectory. )    For further information or help see: http://wiki.minetest.com/wiki/Installing_Mods

description.txt

Write a sentence or two explaining what your mod does. Be concise without being too vague. This is displayed in the mod store.

For example:

GOOD: Adds soups, cakes, bakes and juices. The food mod which supports the most ingredients. BAD: The food mod for Minetest.

screenshot.png

Screenshots should have 4 pixels of width for every 3 pixels of height, and be at least 200 by 150. This is displayed in the mod store.

Uploading

In order for a potential user to download your mod, you need to upload it to somewhere which is publicly accessible.

I will outline several methods you can use, but really you should use the one that works best for you, as long as it mets these requirements:

(and any other requirements which may be added by forum moderators)

Github, or another VCS

It is recommended that you use a Version Control System for the following reasons:

However, such systems may be hard to understand when you first start out.

The majority of Minetest developers use GitHub as a website to host their code, however that doesn't matter that much.

Using Git - Basic concepts. Using the command line.

GitHub for Windows - Use a graphical interface on Windows to upload your code.

Forum Attachments

You could use forum attachments instead. This is done when creating a mod's topic - covered below.

First, you need to zip the files into a single file. This varies from operating system to operating system.

On Windows, go to the mod's folder. Select all the files. Right click, Send To > Compressed (zipped) folder. Rename the resulting zip file to the name of your modfolder.

On the create a topic page, see below, go to the "Upload Attachment" tab at the bottom. Click browse and select the zipped file. I suggest that you enter the version of your mod in the comment field.

[image: Uploading an aAttachment on a phpBB forum]

Forum Topic

You can now create a forum topic. You should create it in the "WIP Mods" (Work In Progress) forum.

When you consider your mod no longer a work in progress, you can request that it be moved to "Mod Releases."

Content

The requirements of a forum topic are mostly the same as what is recommended for a README.txt

You should also include screenshots of your mod in action, if relevant.

Here is an example. The Minetest forum uses bbcode for formating.

Adds magic, rainbows and other special things.    See download attached.    [b]Version:[/b] 1.1 [b]License:[/b] LGPL 2.1 or later    Dependencies: default mod (found in minetest_game)    Report bugs or request help on the forum topic.    [h]Installation[/h]    Unzip the archive, rename the folder to to modfoldername and place it in minetest/mods/minetest/    ( GNU/Linux: If you use a system-wide installation place it in ~/.minetest/mods/minetest/. )    ( If you only want this to be used in a single world, place the folder in worldmods/ in your worlddirectory. )    For further information or help see: [url]http://wiki.minetest.com/wiki/Installing_Mods[/url]

If you modify the above example for your mod topic, remember to change "modfldername" to the name of the folder your mod should be in.

Title

Subject of topic must be in one of these formats:

eg: [Mod] More Blox [0.1] [moreblox]

Profit


Read More

List of Resources

After you’ve read this book, take a look at the following

Minetest Modding

Minetest’s Lua API Reference

HTML version: rubenwardy.com/minetest_modding_book/lua_api.html

Text version: github.com/minetest/minetest/blob/master/doc/lua_api.txt

Explore the Developer Wiki: dev.minetest.net/Main_Page

Look at existing mods: forum.minetest.net/viewforum.php?f=11

Lua Programming

Programming in Lua (PIL): www.lua.org/pil/

Lua Crash Course: luatut.com/crash_course.html

3D Modelling

Blender 3D: Noob to pro: en.wikibooks.org/wiki/Blender_3D:_Noob_to_Pro

Using Blender with Minetest: wiki.minetest.net/Using_Blender



Robert Munafo's home pages on AWS    © 1996-2024 Robert P. Munafo.    about    contact
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. Details here.

This page was written in the "embarrassingly readable" markup language RHTF, and was last updated on 2022 Sep 11. s.27