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