1
0
mirror of https://github.com/luanti-org/luanti.git synced 2025-10-19 19:25:18 +02:00

Refactor client_lua_api.md

This commit is contained in:
Bradley Pierce
2024-01-17 19:57:44 -05:00
parent 554fa34365
commit 8b3f6bc83f

View File

@@ -1,12 +1,11 @@
Minetest Lua Client Modding API Reference 5.9.0
================================================
* More information at <http://www.minetest.net/>
* Developer Wiki: <http://dev.minetest.net/>
# Minetest Lua Client Modding API Reference 5.9.0
Introduction
------------
* More information at <https://www.minetest.net/>
* Developer Wiki: <https://dev.minetest.net/>
** WARNING: The client API is currently unstable, and may break/change without warning. **
## Introduction
> **Warning**: The client API is currently unstable, and may break/change without warning.
Content and functionality can be added to Minetest by using Lua
scripting in run-time loaded mods.
@@ -20,28 +19,29 @@ 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 on GitHub (https://github.com/minetest/minetest).
Programming in Lua
------------------
## Programming in Lua
If you have any difficulty in understanding this, please read
[Programming in Lua](http://www.lua.org/pil/).
Startup
-------
## Startup
Mods are loaded during client startup from the mod load paths by running
the `init.lua` scripts in a shared environment.
In order to load client-side mods, the following conditions need to be satisfied:
1) `$path_user/minetest.conf` contains the setting `enable_client_modding = true`
2) The client-side mod located in `$path_user/clientmods/<modname>` is added to
1. `$path_user/minetest.conf` contains the setting `enable_client_modding = true`
2. The client-side mod located in `$path_user/clientmods/<modname>` is added to
`$path_user/clientmods/mods.conf` as `load_mod_<modname> = true`.
Note: Depending on the remote server's settings, client-side mods might not
> **Note**: Depending on the remote server's settings, client-side mods might not
be loaded or have limited functionality. See setting `csm_restriction_flags` for reference.
Paths
-----
# Paths
* `RUN_IN_PLACE=1` (Windows release, local build)
* `$path_user`: `<build directory>`
* `$path_share`: `<build directory>`
@@ -53,24 +53,23 @@ Paths
* Linux: `$HOME/.minetest`
* Windows: `C:/users/<user>/AppData/minetest` (maybe)
Mod load path
-------------
Generic:
## Mod Load Path
Generic:
aa
* `$path_share/clientmods/`
* `$path_user/clientmods/` (User-installed mods)
In a run-in-place version (e.g. the distributed windows version):
* `minetest/clientmods/` (User-installed mods)
* `minetest-0.4.x/clientmods/` (User-installed mods)
On an installed version on Linux:
* `/usr/share/minetest/clientmods/`
* `$HOME/.minetest/clientmods/` (User-installed mods)
Modpack support
----------------
## Modpack Support
Mods can be put in a subdirectory, if the parent directory, which otherwise
should be a mod, contains a file named `modpack.conf`.
@@ -85,15 +84,15 @@ Mod directory structure
clientmods
├── modname
   ├── mod.conf
   ├── init.lua
├── mod.conf
├── init.lua
└── another
### modname
### `modname`
The location of this directory.
### mod.conf
### `mod.conf`
An (optional) settings file that provides meta information about the mod.
@@ -112,12 +111,14 @@ The main Lua script. Running this script should register everything it
wants to register. Subsequent execution depends on minetest calling the
registered callbacks.
**NOTE**: Client mods currently can't provide textures, sounds, or models by
> **Note**: Client mods currently can't provide textures, sounds, or models by
themselves. Any media referenced in function calls must already be loaded
(provided by mods that exist on the server).
Naming convention for registered textual names
----------------------------------------------
# Naming Convention For Registered Textual Names
Registered names should generally be in this format:
"modname:<whatever>" (<whatever> can have characters a-zA-Z0-9_)
@@ -125,7 +126,8 @@ Registered names should generally be in this format:
This is to prevent conflicting names from corrupting maps and is
enforced by the mod loader.
### Example
## Example
In the mod `experimental`, there is the ideal item/node/entity name `tnt`.
So the name should be `experimental:tnt`.
@@ -141,9 +143,11 @@ when registering it.
The `:` prefix can also be used for maintaining backwards compatibility.
Sounds
------
**NOTE: Connecting sounds to objects is not implemented.**
# Sounds
> **Note**: Connecting sounds to objects is not implemented.
Only Ogg Vorbis files are supported.
@@ -185,21 +189,29 @@ Examples of sound parameter tables:
pos = {x = 1, y = 2, z = 3},
gain = 1.0, -- default
}
-- Play connected to an object, looped
{
object = <an ObjectRef>,
gain = 1.0, -- default
loop = true,
}
```
Looped sounds must be played locationless.
### SimpleSoundSpec
## `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}`
Representations of simple things
--------------------------------
### Position/vector
# Representations of Simple Things
## Position/Vector
```lua
{x=num, y=num, z=num}
@@ -207,30 +219,36 @@ Representations of simple things
For helper functions see "Vector helpers".
### pointed_thing
## `pointed_thing`
* `{type="nothing"}`
* `{type="node", under=pos, above=pos}`
* `{type="object", id=ObjectID}`
Flag Specifier Format
---------------------
# Flag Specifier Format
Refer to `lua_api.md`.
Formspec
--------
# Formspec
Formspec defines a menu. It is a string, with a somewhat strange format.
For details, refer to `lua_api.md`.
Spatial Vectors
---------------
# Spatial Vectors
Refer to `lua_api.md`.
Helper functions
----------------
# Helper Functions
* `dump2(obj, name="_", dumped={})`
* Return object serialized as a string, handles reference loops
* `dump(obj, dumped={})`
@@ -264,10 +282,11 @@ Helper functions
* `table.copy(table)`: returns a table
* returns a deep copy of `table`
Minetest namespace reference
------------------------------
### Utilities
# Minetest Namespace Reference
## Utilities
* `minetest.get_current_modname()`: returns the currently loading mod's name, when we are loading a mod
* `minetest.get_modpath(modname)`: returns virtual path of given mod including
@@ -303,14 +322,16 @@ Minetest namespace reference
percent sign followed by two hex digits. See
[RFC 3986, section 2.3](https://datatracker.ietf.org/doc/html/rfc3986#section-2.3).
### Logging
## Logging
* `minetest.debug(...)`
* Equivalent to `minetest.log(table.concat({...}, "\t"))`
* `minetest.log([level,] text)`
* `level` is one of `"none"`, `"error"`, `"warning"`, `"action"`,
`"info"`, or `"verbose"`. Default is `"none"`.
### Global callback registration functions
## Global Callback Registration Functions
Call these functions only at load time!
* `minetest.register_globalstep(function(dtime))`
@@ -319,7 +340,7 @@ Call these functions only at load time!
* Called just after mods have finished loading.
* `minetest.register_on_shutdown(function())`
* Called before client shutdown
* **Warning**: If the client terminates abnormally (i.e. crashes), the registered
> **Warning**: If the client 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_receiving_chat_message(function(message))`
@@ -368,19 +389,21 @@ Call these functions only at load time!
* If message comes from a server mod, `sender` field is an empty string.
* `minetest.register_on_modchannel_signal(function(channel_name, signal))`
* Called when a valid incoming mod channel signal is received
* Signal id permit to react to server mod channel events
* Signal ID permit to react to server mod channel events
* Possible values are:
0: join_ok
1: join_failed
2: leave_ok
3: leave_failed
4: event_on_not_joined_channel
5: state_changed
0: `join_ok`
1: `join_failed`
2: `leave_ok`
3: `leave_failed`
4: `event_on_not_joined_channel`
5: `state_changed`
* `minetest.register_on_inventory_open(function(inventory))`
* Called when the local player open inventory
* Newest functions are called first
* If any function returns true, inventory doesn't open
### Sounds
## Sounds
* `minetest.sound_play(spec, parameters)`: returns a handle
* `spec` is a `SimpleSoundSpec`
* `parameters` is a sound parameter table
@@ -393,20 +416,18 @@ Call these functions only at load time!
the sound volume.
* `gain` the target gain for the fade.
### Timing
## Timing
* `minetest.after(time, func, ...)`
* Call the function `func` after `time` seconds, may be fractional
* Optional: Variable number of arguments that are passed to `func`
* Jobs set for earlier times are executed earlier. If multiple jobs expire
at exactly the same time, then they expire in the order in which they were
registered. This basically just applies to jobs registered on the same
step with the exact same delay.
* `minetest.get_us_time()`
* Returns time with microsecond precision. May not return wall time.
* `minetest.get_timeofday()`
* Returns the time of day: `0` for midnight, `0.5` for midday
### Map
## Map
* `minetest.get_node_or_nil(pos)`
* Returns the node at the given position as table in the format
`{name="node_name", param1=0, param2=0}`, returns `nil`
@@ -461,7 +482,8 @@ Call these functions only at load time!
* `minetest.get_node_max_level(pos)`
* get max available level for leveled node
### Player
## Player
* `minetest.send_chat_message(message)`
* Act as if `message` was typed by the player into the terminal.
* `minetest.run_server_chatcommand(cmd, param)`
@@ -471,14 +493,16 @@ Call these functions only at load time!
* `minetest.localplayer`
* Reference to the LocalPlayer object. See [`LocalPlayer`](#localplayer) class reference for methods.
### Privileges
## Privileges
* `minetest.get_privilege_list()`
* Returns a list of privileges the current player has in the format `{priv1=true,...}`
* `minetest.string_to_privs(str)`: returns `{priv1=true,...}`
* `minetest.privs_to_string(privs)`: returns `"priv1,priv2,..."`
* Convert between two privilege representations
### Client Environment
## Client Environment
* `minetest.get_player_names()`
* Returns list of player names on server (nil if CSM_RF_READ_PLAYERINFO is enabled by server)
* `minetest.disconnect()`
@@ -489,20 +513,24 @@ Call these functions only at load time!
* `minetest.send_respawn()`
* Sends a respawn request to the server.
### Storage API
## Storage API
* `minetest.get_mod_storage()`:
* returns reference to mod private `StorageRef`
* must be called during mod load time
### Mod channels
## Mod Channels
![Mod channels communication scheme](docs/mod channels.png)
* `minetest.mod_channel_join(channel_name)`
* Client joins channel `channel_name`, and creates it, if necessary. You
should listen from incoming messages with `minetest.register_on_modchannel_message`
call to receive incoming messages. Warning, this function is asynchronous.
call to receive incoming messages.
> **Warning**: This function is asynchronous.
## Particles
### Particles
* `minetest.add_particle(particle definition)`
* `minetest.add_particlespawner(particlespawner definition)`
@@ -512,7 +540,8 @@ Call these functions only at load time!
* `minetest.delete_particlespawner(id)`
* Delete `ParticleSpawner` with `id` (return value from `minetest.add_particlespawner`)
### Misc.
## Misc.
* `minetest.parse_json(string[, nullvalue])`: returns something
* Convert a string containing JSON data into the Lua equivalent
* `nullvalue`: returned in place of the JSON null; defaults to `nil`
@@ -523,10 +552,10 @@ Call these functions only at load time!
* 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 cannot mix string and integer keys.
This is due to the fact that JSON has two distinct array and object values.
> **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 cannot mix string and integer keys. This is due to the fact that JSON has
> two distinct array and object values.
* Example: `write_json({10, {a = false}})`, returns `"[10, {\"a\": false}]"`
* `minetest.serialize(table)`: returns a string
* Convert a table containing tables, strings, numbers, booleans and `nil`s
@@ -578,7 +607,8 @@ Call these functions only at load time!
* `minetest.global_exists(name)`
* Checks if a global variable has been set, without triggering a warning.
### UI
## UI
* `minetest.ui.minimap`
* Reference to the minimap object. See [`Minimap`](#minimap) class reference for methods.
* If client disabled minimap (using enable_minimap setting) this reference will be nil.
@@ -589,22 +619,25 @@ Call these functions only at load time!
* `minetest.display_chat_message(message)` returns true on success
* Shows a chat message to the current player.
Setting-related
---------------
# Setting-Related
* `minetest.settings`: Settings object containing all of the settings from the
main config file (`minetest.conf`). Check lua_api.md for class reference.
main config file (`minetest.conf`). Check `lua_api.md` for class reference.
* `minetest.setting_get_pos(name)`: Loads a setting from the main settings and
parses it as a position (in the format `(1,2,3)`). Returns a position or nil.
Class reference
---------------
### ModChannel
# Class Reference
## `ModChannel`
An interface to use mod channels on client and server
#### Methods
### Methods
* `leave()`: leave the mod channel.
* Client leaves channel `channel_name`.
* No more incoming or outgoing messages can be sent to this channel from client mods.
@@ -615,10 +648,12 @@ An interface to use mod channels on client and server
* If mod channel is not writable or invalid, message will be dropped.
* Message size is limited to 65535 characters by protocol.
### Minimap
## Minimap
An interface to manipulate minimap on client UI
#### Methods
### Methods
* `show()`: shows the minimap (if not disabled by server)
* `hide()`: hides the minimap
* `set_pos(pos)`: sets the minimap position on screen
@@ -630,11 +665,13 @@ An interface to manipulate minimap on client UI
* `set_shape(shape)`: Sets the minimap shape. (0 = square, 1 = round)
* `get_shape()`: Gets the minimap shape. (0 = square, 1 = round)
### Camera
## Camera
An interface to get or set information about the camera and camera-node.
Please do not try to access the reference until the camera is initialized, otherwise the reference will be nil.
#### Methods
### Methods
* `set_camera_mode(mode)`
* Pass `0` for first-person, `1` for third person, and `2` for third person front
* `get_camera_mode()`
@@ -664,7 +701,7 @@ Please do not try to access the reference until the camera is initialized, other
* `get_aspect_ratio()`
* Returns aspect ratio of screen
### LocalPlayer
## `LocalPlayer`
An interface to retrieve information about the player.
This object will only be available after the client is initialized. Earlier accesses will yield a `nil` value.
@@ -698,7 +735,6 @@ Methods:
* returns true if player is swimming in vertical
* `get_physics_override()`
* returns:
```lua
{
speed = float,
@@ -709,7 +745,6 @@ Methods:
new_move = boolean,
}
```
* `get_override_pos()`
* returns override position
* `get_last_pos()`
@@ -720,7 +755,6 @@ Methods:
* returns the player's breath
* `get_movement_acceleration()`
* returns acceleration of the player in different environments:
```lua
{
fast = float,
@@ -728,10 +762,8 @@ Methods:
default = float,
}
```
* `get_movement_speed()`
* returns player's speed in different environments:
```lua
{
walk = float,
@@ -741,10 +773,8 @@ Methods:
climb = float,
}
```
* `get_movement()`
* returns player's movement in different environments:
```lua
{
liquid_fluidity = float,
@@ -753,14 +783,12 @@ Methods:
gravity = float,
}
```
* `get_last_look_horizontal()`:
* returns last look horizontal angle
* `get_last_look_vertical()`:
* returns last look vertical angle
* `get_control()`:
* returns pressed player controls
```lua
{
up = boolean,
@@ -775,7 +803,6 @@ Methods:
place = boolean,
}
```
* `get_armor_groups()`
* returns a table with the armor group ratings
* `hud_add(definition)`
@@ -783,23 +810,20 @@ Methods:
* See [`HUD definition`](#hud-definition-hud_add-hud_get)
* `hud_get(id)`
* returns the [`definition`](#hud-definition-hud_add-hud_get) of the HUD with that ID number or `nil`, if non-existent.
* `hud_get_all()`:
* Returns a table in the form `{ [id] = HUD definition, [id] = ... }`.
* A mod should keep track of its introduced IDs and only use this to access foreign elements.
* It is discouraged to change foreign HUD elements.
* `hud_remove(id)`
* remove the HUD element of the specified id, returns `true` on success
* remove the HUD element of the specified ID, returns `true` on success
* `hud_change(id, stat, value)`
* change a value of a previously added HUD element
* element `stat` values: `position`, `name`, `scale`, `text`, `number`, `item`, `dir`
* Returns `true` on success, otherwise returns `nil`
### Settings
## `Settings`
An interface to read config files in the format of `minetest.conf`.
It can be created via `Settings(filename)`.
#### Methods
### Methods
* `get(key)`: returns a value
* `get_bool(key)`: returns a boolean
* `set(key, value)`
@@ -809,11 +833,12 @@ It can be created via `Settings(filename)`.
* write changes to file
* `to_table()`: returns `{[key1]=value1,...}`
### NodeMetaRef
## `NodeMetaRef`
Node metadata: reference extra data and functionality stored in a node.
Can be obtained via `minetest.get_meta(pos)`.
#### Methods
### Methods
* `get_string(name)`
* `get_int(name)`
* `get_float(name)`
@@ -821,7 +846,7 @@ Can be obtained via `minetest.get_meta(pos)`.
* `fields`: key-value storage
* `inventory`: `{list1 = {}, ...}}`
### `Raycast`
## `Raycast`
A raycast on the map. It works with selection boxes.
Can be used as an iterator in a for loop as:
@@ -844,19 +869,19 @@ It can be created via `Raycast(pos1, pos2, objects, liquids)` or
* `objects`: if false, only nodes will be returned. Default is true.
* `liquids`: if false, liquid nodes won't be returned. Default is false.
#### Methods
### Methods
* `next()`: returns a `pointed_thing` with exact pointing location
* Returns the next thing pointed by the ray or nil.
-----------------
### Definitions
# Definitions
* `minetest.get_node_def(nodename)`
* Returns [node definition](#node-definition) table of `nodename`
* `minetest.get_item_def(itemstring)`
* Returns item definition table of `itemstring`
#### Node Definition
## Node Definition
```lua
{
@@ -918,7 +943,7 @@ It can be created via `Raycast(pos1, pos2, objects, liquids)` or
}
```
#### Item Definition
## Item Definition
```lua
{
@@ -940,9 +965,8 @@ It can be created via `Raycast(pos1, pos2, objects, liquids)` or
node_placement_prediction = string -- Node placed in client until server catches up
}
```
-----------------
### Chat command definition (`register_chatcommand`)
## Chat Command Definition (`register_chatcommand`)
```lua
{
@@ -953,7 +977,7 @@ It can be created via `Raycast(pos1, pos2, objects, liquids)` or
}
```
### Server info
## Server Information
```lua
{
@@ -964,12 +988,14 @@ It can be created via `Raycast(pos1, pos2, objects, liquids)` or
}
```
### HUD Definition (`hud_add`, `hud_get`)
## HUD Definition (`hud_add`, `hud_get`)
Refer to `lua_api.md`.
Escape sequences
----------------
# Escape Sequences
Most text can contain escape sequences that can for example color the text.
There are a few exceptions: tab headers, dropdowns and vertical labels can't.
The following functions provide escape sequences:
@@ -992,19 +1018,25 @@ The following functions provide escape sequences:
* `minetest.strip_colors(str)`
* Removes all color escape sequences.
`ColorString`
-------------
# `ColorString`
Refer to `lua_api.md`.
`Color`
-------------
# `Color`
`{a = alpha, r = red, g = green, b = blue}` defines an ARGB8 color.
### Particle definition (`add_particle`)
As documented in `lua_api.md`, except for obvious reasons, the `playername` field is not supported.
As documented in `lua_api.md`, except the `playername` field is not supported.
### `ParticleSpawner` definition (`add_particlespawner`)
As documented in `lua_api.md`, except for obvious reasons, the `playername` field is not supported.
As documented in `lua_api.md`, except the `playername` field is not supported.