]> git.lizzy.rs Git - minetest.git/blob - doc/menu_lua_api.txt
Add keybind to swap items between hands
[minetest.git] / doc / menu_lua_api.txt
1 Minetest Lua Mainmenu API Reference 5.7.0
2 =========================================
3
4 Introduction
5 -------------
6
7 The main menu is defined as a formspec by Lua in `builtin/mainmenu/`
8 Description of formspec language to show your menu is in `lua_api.txt`
9
10
11 Callbacks
12 ---------
13
14 * `core.button_handler(fields)`: called when a button is pressed.
15   * `fields` = `{name1 = value1, name2 = value2, ...}`
16 * `core.event_handler(event)`
17   * `event`: `"MenuQuit"`, `"KeyEnter"`, `"ExitButton"` or `"EditBoxEnter"`
18
19
20 Gamedata
21 --------
22
23 The "gamedata" table is read when calling `core.start()`. It should contain:
24
25     {
26         playername     = <name>,
27         password       = <password>,
28         address        = <IP/address>,
29         port           = <port>,
30         selected_world = <index>, -- 0 for client mode
31         singleplayer   = <true/false>,
32     }
33
34
35 Functions
36 ---------
37
38 * `core.start()`
39 * `core.close()`
40 * `core.get_min_supp_proto()`
41   * returns the minimum supported network protocol version
42 * `core.get_max_supp_proto()`
43   * returns the maximum supported network protocol version
44 * `core.open_url(url)`
45   * opens the URL in a web browser, returns false on failure.
46   * Must begin with http:// or https://
47 * `core.open_dir(path)`
48   * opens the path in the system file browser/explorer, returns false on failure.
49   * Must be an existing directory.
50 * `core.share_file(path)`
51   * Android only. Shares file using the share popup
52 * `core.get_version()` (possible in async calls)
53   * returns current core version
54
55
56
57 Filesystem
58 ----------
59
60 * `core.get_builtin_path()`
61   * returns path to builtin root
62 * `core.create_dir(absolute_path)` (possible in async calls)
63   * `absolute_path` to directory to create (needs to be absolute)
64   * returns true/false
65 * `core.delete_dir(absolute_path)` (possible in async calls)
66   * `absolute_path` to directory to delete (needs to be absolute)
67   * returns true/false
68 * `core.copy_dir(source,destination,keep_source)` (possible in async calls)
69   * `source` folder
70   * `destination` folder
71   * `keep_source` DEFAULT true --> if set to false `source` is deleted after copying
72   * returns true/false
73 * `core.is_dir(path)` (possible in async calls)
74   * returns true if `path` is a valid dir
75 * `core.extract_zip(zipfile,destination)` [unzip within path required]
76   * `zipfile` to extract
77   * `destination` folder to extract to
78   * returns true/false
79 * `core.sound_play(spec, looped)` -> handle
80   * `spec` = `SimpleSoundSpec` (see `lua_api.txt`)
81   * `looped` = bool
82 * `core.sound_stop(handle)`
83 * `core.get_video_drivers()`
84   * get list of video drivers supported by engine (not all modes are guaranteed to work)
85   * returns list of available video drivers' settings name and 'friendly' display name
86     e.g. `{ {name="opengl", friendly_name="OpenGL"}, {name="software", friendly_name="Software Renderer"} }`
87   * first element of returned list is guaranteed to be the NULL driver
88 * `core.get_mapgen_names([include_hidden=false])` -> table of map generator algorithms
89     registered in the core (possible in async calls)
90 * `core.get_cache_path()` -> path of cache
91 * `core.get_temp_path([param])` (possible in async calls)
92   * `param`=true: returns path to a temporary file
93     otherwise: returns path to the temporary folder
94
95
96 HTTP Requests
97 -------------
98
99 * `core.download_file(url, target)` (possible in async calls)
100     * `url` to download, and `target` to store to
101     * returns true/false
102 * `minetest.get_http_api()` (possible in async calls)
103     * returns `HTTPApiTable` containing http functions.
104     * The returned table contains the functions `fetch_sync`, `fetch_async` and
105       `fetch_async_get` described below.
106     * Function only exists if minetest server was built with cURL support.
107 * `HTTPApiTable.fetch_sync(HTTPRequest req)`: returns HTTPRequestResult
108     * Performs given request synchronously
109 * `HTTPApiTable.fetch_async(HTTPRequest req)`: returns handle
110     * Performs given request asynchronously and returns handle for
111       `HTTPApiTable.fetch_async_get`
112 * `HTTPApiTable.fetch_async_get(handle)`: returns `HTTPRequestResult`
113     * Return response data for given asynchronous HTTP request
114
115 ### `HTTPRequest` definition
116
117 Used by `HTTPApiTable.fetch` and `HTTPApiTable.fetch_async`.
118
119     {
120         url = "http://example.org",
121
122         timeout = 10,
123         -- Timeout for connection in seconds. Default is 3 seconds.
124
125         post_data = "Raw POST request data string" OR {field1 = "data1", field2 = "data2"},
126         -- Optional, if specified a POST request with post_data is performed.
127         -- Accepts both a string and a table. If a table is specified, encodes
128         -- table as x-www-form-urlencoded key-value pairs.
129         -- If post_data is not specified, a GET request is performed instead.
130
131         user_agent = "ExampleUserAgent",
132         -- Optional, if specified replaces the default minetest user agent with
133         -- given string
134
135         extra_headers = { "Accept-Language: en-us", "Accept-Charset: utf-8" },
136         -- Optional, if specified adds additional headers to the HTTP request.
137         -- You must make sure that the header strings follow HTTP specification
138         -- ("Key: Value").
139
140         multipart = boolean
141         -- Optional, if true performs a multipart HTTP request.
142         -- Default is false.
143     }
144
145 ### `HTTPRequestResult` definition
146
147 Passed to `HTTPApiTable.fetch` callback. Returned by
148 `HTTPApiTable.fetch_async_get`.
149
150     {
151         completed = true,
152         -- If true, the request has finished (either succeeded, failed or timed
153         -- out)
154
155         succeeded = true,
156         -- If true, the request was successful
157
158         timeout = false,
159         -- If true, the request timed out
160
161         code = 200,
162         -- HTTP status code
163
164         data = "response"
165     }
166
167
168 Formspec
169 --------
170
171 * `core.update_formspec(formspec)`
172 * `core.get_table_index(tablename)` -> index
173   * can also handle textlists
174 * `core.formspec_escape(string)` -> string
175   * escapes characters [ ] \ , ; that cannot be used in formspecs
176 * `core.explode_table_event(string)` -> table
177   * returns e.g. `{type="CHG", row=1, column=2}`
178   * `type`: "INV" (no row selected), "CHG" (selected) or "DCL" (double-click)
179 * `core.explode_textlist_event(string)` -> table
180   * returns e.g. `{type="CHG", index=1}`
181   * `type`: "INV" (no row selected), "CHG" (selected) or "DCL" (double-click)
182 * `core.set_formspec_prepend(formspec)`
183   * `formspec`: string to be added to every mainmenu formspec, to be used for theming.
184
185
186 GUI
187 ---
188
189 * `core.set_background(type,texturepath,[tile],[minsize])`
190   * `type`: "background", "overlay", "header" or "footer"
191   * `tile`: tile the image instead of scaling (background only)
192   * `minsize`: minimum tile size, images are scaled to at least this size prior
193    doing tiling (background only)
194 * `core.set_clouds(<true/false>)`
195 * `core.set_topleft_text(text)`
196 * `core.show_keys_menu()`
197 * `core.show_path_select_dialog(formname, caption, is_file_select)`
198   * shows a path select dialog
199   * `formname` is base name of dialog response returned in fields
200      - if dialog was accepted `"_accepted"`
201         will be added to fieldname containing the path
202      - if dialog was canceled `"_cancelled"`
203         will be added to fieldname value is set to formname itself
204   * if `is_file_select` is `true`, a file and not a folder will be selected
205   * returns nil or selected file/folder
206 * `core.get_active_renderer()`: Ex: "OpenGL 4.6".
207 * `core.get_window_info()`: Same as server-side `get_player_window_information` API.
208
209       -- Note that none of these things are constant, they are likely to change
210       -- as the player resizes the window and moves it between monitors
211       --
212       -- real_gui_scaling and real_hud_scaling can be used instead of DPI.
213       -- OSes don't necessarily give the physical DPI, as they may allow user configuration.
214       -- real_*_scaling is just OS DPI / 96 but with another level of user configuration.
215       {
216           -- Current size of the in-game render target.
217           --
218           -- This is usually the window size, but may be smaller in certain situations,
219           -- such as side-by-side mode.
220           size = {
221               x = 1308,
222               y = 577,
223           },
224
225           -- Estimated maximum formspec size before Minetest will start shrinking the
226           -- formspec to fit. For a fullscreen formspec, use a size 10-20% larger than
227           -- this and `padding[-0.01,-0.01]`.
228           max_formspec_size = {
229               x = 20,
230               y = 11.25
231           },
232
233           -- GUI Scaling multiplier
234           -- Equal to the setting `gui_scaling` multiplied by `dpi / 96`
235           real_gui_scaling = 1,
236
237           -- HUD Scaling multiplier
238           -- Equal to the setting `hud_scaling` multiplied by `dpi / 96`
239           real_hud_scaling = 1,
240       }
241
242
243
244 Content and Packages
245 --------------------
246
247 Content - an installed mod, modpack, game, or texture pack (txt)
248 Package - content which is downloadable from the content db, may or may not be installed.
249
250 * `core.get_user_path()` (possible in async calls)
251     * returns path to global user data,
252       the directory that contains user-provided mods, worlds, games, and texture packs.
253 * `core.get_modpath()` (possible in async calls)
254     * returns path to global modpath in the user path, where mods can be installed
255 * `core.get_modpaths()` (possible in async calls)
256     * returns table of virtual path to global modpaths, where mods have been installed
257       The difference with `core.get_modpath` is that no mods should be installed in these
258       directories by Minetest -- they might be read-only.
259
260       Ex:
261
262       ```
263       {
264           mods = "/home/user/.minetest/mods",
265           share = "/usr/share/minetest/mods",
266
267           -- Custom dirs can be specified by the MINETEST_MOD_DIR env variable
268           ["/path/to/custom/dir"] = "/path/to/custom/dir",
269       }
270       ```
271
272 * `core.get_clientmodpath()` (possible in async calls)
273     * returns path to global client-side modpath
274 * `core.get_gamepath()` (possible in async calls)
275     * returns path to global gamepath
276 * `core.get_texturepath()` (possible in async calls)
277     * returns path to default textures
278 * `core.get_games()` -> table of all games (possible in async calls)
279     * `name` in return value is deprecated, use `title` instead.
280     * returns a table (ipairs) with values:
281
282           {
283               id               = <id>,
284               path             = <full path to game>,
285               gamemods_path    = <path>,
286               title            = <title of game>,
287               menuicon_path    = <full path to menuicon>,
288               author           = "author",
289               DEPRECATED:
290               addon_mods_paths = {[1] = <path>,},
291           }
292 * `core.get_content_info(path)`
293     * returns
294
295           {
296               name             = "technical_id",
297               type             = "mod" or "modpack" or "game" or "txp",
298               title            = "Human readable title",
299               description      = "description",
300               author           = "author",
301               path             = "path/to/content",
302               depends          = {"mod", "names"}, -- mods only
303               optional_depends = {"mod", "names"}, -- mods only
304           }
305 * `core.check_mod_configuration(world_path, mod_paths)`
306     * Checks whether configuration is valid.
307     * `world_path`: path to the world
308     * `mod_paths`: list of enabled mod paths
309     * returns:
310
311           {
312               is_consistent = true,  -- true is consistent, false otherwise
313               unsatisfied_mods = {},  -- list of mod specs
314               satisfied_mods = {}, -- list of mod specs
315               error_message = "",  -- message or nil
316           }
317
318 Logging
319 -------
320
321 * `core.debug(line)` (possible in async calls)
322   * Always printed to `stderr` and logfile (`print()` is redirected here)
323 * `core.log(line)` (possible in async calls)
324 * `core.log(loglevel, line)` (possible in async calls)
325   * `loglevel` one of "error", "action", "info", "verbose"
326
327
328 Settings
329 --------
330
331 * `core.settings:set(name, value)`
332 * `core.settings:get(name)` -> string or nil (possible in async calls)
333 * `core.settings:set_bool(name, value)`
334 * `core.settings:get_bool(name)` -> bool or nil (possible in async calls)
335 * `core.settings:save()` -> nil, save all settings to config file
336
337 For a complete list of methods of the `Settings` object see
338 [lua_api.txt](https://github.com/minetest/minetest/blob/master/doc/lua_api.txt)
339
340
341 Worlds
342 ------
343
344 * `core.get_worlds()` -> list of worlds (possible in async calls)
345   * returns
346
347         {
348            [1] = {
349            path   = <full path to world>,
350            name   = <name of world>,
351            gameid = <gameid of world>,
352            },
353         }
354 * `core.create_world(worldname, gameid, init_settings)`
355 * `core.delete_world(index)`
356
357
358 Helpers
359 -------
360
361 * `core.get_us_time()`
362   * returns time with microsecond precision
363 * `core.gettext(string)` -> string
364   * look up the translation of a string in the gettext message catalog
365 * `fgettext_ne(string, ...)`
366   * call `core.gettext(string)`, replace "$1"..."$9" with the given
367   extra arguments and return the result
368 * `fgettext(string, ...)` -> string
369   * same as `fgettext_ne()`, but calls `core.formspec_escape` before returning result
370 * `core.parse_json(string[, nullvalue])` -> something (possible in async calls)
371   * see `core.parse_json` (`lua_api.txt`)
372 * `dump(obj, dumped={})`
373   * Return object serialized as a string
374 * `string:split(separator)`
375   * eg. `string:split("a,b", ",")` == `{"a","b"}`
376 * `string:trim()`
377   * eg. `string.trim("\n \t\tfoo bar\t ")` == `"foo bar"`
378 * `core.is_yes(arg)` (possible in async calls)
379   * returns whether `arg` can be interpreted as yes
380 * `minetest.encode_base64(string)` (possible in async calls)
381   * Encodes a string in base64.
382 * `minetest.decode_base64(string)` (possible in async calls)
383   * Decodes a string encoded in base64.
384
385
386 Async
387 -----
388
389 * `core.handle_async(async_job,parameters,finished)`
390   * execute a function asynchronously
391   * `async_job` is a function receiving one parameter and returning one parameter
392   * `parameters` parameter table passed to `async_job`
393   * `finished` function to be called once `async_job` has finished
394     the result of `async_job` is passed to this function
395
396 ### Limitations of Async operations
397  * No access to global lua variables, don't even try
398  * Limited set of available functions
399     e.g. No access to functions modifying menu like `core.start`, `core.close`,
400     `core.show_path_select_dialog`
401
402
403 Background music
404 ----------------
405
406 The main menu supports background music.
407 It looks for a `main_menu` sound in `$USER_PATH/sounds`. The same naming
408 conventions as for normal sounds apply.
409 This means the player can add a custom sound.
410 It will be played in the main menu (gain = 1.0), looped.