Difference between revisions of "LuaAPI"

From The Battle for Wesnoth Wiki
(Wesnoth Modules: Add filesystem and paths modules)
(Include Lua_Functions)
 
(31 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 +
{{Lua_Functions}}
 +
__NOTOC__
 +
All Lua API functionality is available in one of several global module tables, as well as some global functions which form the basic Lua API. Wesnoth uses [http://www.lua.org/manual/5.4/manual.html Lua 5.4] which is documented in detail on the Lua website.
  
'''''Note: This page is is a work-in-progress and only reflects the current stable version. For more complete documentation for 1.14, see [[LuaWML#Interface_to_the_engine_and_helper_functions|here]]. For information on what has changed since 1.14, see [[/UpdatingFrom14|here]].'''''
+
This page documents the modules, functions, and other APIs available for use when writing Lua for Wesnoth. For information on how to tell the engine about your Lua code, see [[LuaWML]].
  
All Lua API functionality is available in one of several global module tables, as well as some global functions which form the basic Lua API. The following core Lua modules are available and are documented on the Lua website:
+
== Conventions used in this manual ==
  
* [http://www.lua.org/manual/5.3/manual.html#6.1 basic] — except <tt>dofile</tt>, <tt>require</tt>, and <tt>loadfile</tt>; also note that <tt>print</tt> redirects to the Lua console interface rather than standard output; you can use <tt>std_print</tt> if you need the default Lua behavior. Starting from 1.15, <tt>loadstring</tt> (deprecated in Lua in favor of <tt>load</tt>) isn't available either.
+
On this page and any page linked from it, variable values will be shown in italic type, while literal names will be shown in bold type. Variable values may be parameters, self values, indexes, or field names on a table. Return values will be indicated by a right arrow (&rarr;) followed by a list of names in italics. The arrow will be omitted for a function that returns nothing. Optional portions will be enclosed in square brackets. The commas for optional parameters will not be included in the brackets, even though they must be omitted if the optional parameter is omitted.
* [http://www.lua.org/manual/5.3/manual.html#6.2 coroutine]
 
* [http://www.lua.org/manual/5.3/manual.html#6.4 string]
 
* [http://www.lua.org/manual/5.3/manual.html#6.5 utf8]
 
* [http://www.lua.org/manual/5.3/manual.html#6.6 table]
 
* [http://www.lua.org/manual/5.3/manual.html#6.7 math] — note that <tt>math.random</tt> is unsafe for MP usage; wesnoth provides a separate MP-safe random function
 
* [http://www.lua.org/manual/5.3/manual.html#6.9 os] — only the <tt>clock</tt>, <tt>date</tt>, <tt>time</tt>, and <tt>difftime</tt> functions are available (but keep in mind that they are not MP safe)
 
* [http://www.lua.org/manual/5.3/manual.html#6.10 debug] — only the <tt>traceback</tt> function is available
 
  
Wesnoth also provides several modules of its own, some of which are loaded by default while others require you to load them as needed.
+
===== Functions =====
  
=== Conventions used in this manual ===
+
For example, the following line would be seen in the documentation of a function that returns two values and has an optional parameter:
  
On this page and any page linked from it, parameters will be shown in italic type, while literal names will be shown in bold type. Return values will be indicated by a right arrow (&rarr;) followed by a list of names in italics. Optional portions will be enclosed in square brackets.
+
* '''wesnoth.some_function'''(''some_parameter'', [''some_optional_parameter'']) &rarr; ''first_return_value'', ''second_return_value''
  
For example, consider the following hypothetical definitions:
+
===== Methods =====
 +
 
 +
The following example documents a function that can be called as a method on a ''some_value'', taking one additional parameter and returning one value.
  
* '''wesnoth.some_function'''(''some_parameter'' [, ''some_optional_parameter'']) &rarr; ''first_return_value'', ''second_return_value''
 
This is a function that returns multiple values and has optional parameters
 
 
* ''some_value'':'''some_method'''(''some_parameter'') &rarr; ''some_new_value''
 
* ''some_value'':'''some_method'''(''some_parameter'') &rarr; ''some_new_value''
* ''some_value''.'''some_member''' &rarr; ''result''
 
  
For member variables, the right arrow may be replaced with a left arrow (&larr;) if it is write-only, or a double-ended arrow (&harr;) if it is read-write.
+
===== Variadic Functions =====
 +
 
 +
Functions that take a variable number of parameters or return a variable number of values where the specific meaning of the parameters is unspecified will use the string "..." to indicate this. For example:
 +
 
 +
* '''wesnoth.variadic_function'''(''required_param'', [...])
 +
* '''wesnoth.get_several_values'''(''param'') &rarr; ...
 +
 
 +
The first of these takes a variable number of parameters, but requires at least one parameter. The second takes one parameter and returns a variable number of values.
 +
 
 +
===== Member Variables =====
 +
 
 +
Not all documented APIs are functions. When documenting userdata types, as well as some complex tables returned by API functions, the following syntax is used for member variables. The right arrow may be replaced with a left arrow (&larr;) if it is write-only, or a double-ended arrow (&harr;) if it is read-write. Read-only members may return multiple values. The following examples document a read-write member, a read-only member that returns two values, and a write-only member respectively.
 +
 
 +
* ''some_value''.'''some_member''' &harr; ''result''
 +
* ''some_value''.'''read_only_member''' &rarr; ''first_result'', ''second_result''
 +
* ''some_value''.'''write_only_member''' &larr; ''input''
 +
 
 +
===== Operators =====
 +
 
 +
Custom types in Lua can overload operators with new functionality. Some examples of how these would be documented:
 +
 
 +
* #'''wesnoth.list_like_object''' &rarr; ''number of somethings''
 +
* '''wesnoth.list_like_object'''[''index''] &harr; ''a something definition table''
 +
* ''comparable_value'' == ''comparable_value'' &rarr; ''whether they are equal''
 +
* ''operable_value'' + ''operable_value'' &rarr; ''result''
 +
 
 +
The first example documents that you can get the length of that object. The same format would be used for other unary operators as well.
 +
 
 +
The second example documents that you can index the object with arbitrary values. Whether the index needs to be a number would usually be mentioned in the detailed description, although the placeholder name may also make it clear. This example could also use a single-directional arrow to indicate that it is read-only or write-only.
 +
 
 +
The third example documents that you can compare two values of that type with the equality operator, and the fourth example documents that you can add two values of that type together with the addition operator.
 +
 
 +
===== Iterators =====
 +
 
 +
For functions that return an iterator, a double arrow indicates the values yielded when you use the iterator in a for loop. The following example documents a function returning an iterator that yields three values.
 +
 
 +
* '''wesnoth.some_function'''() &rarr; ''iterator'' &rArr; ''a'', ''b'', ''c''
 +
 
 +
===== Hooks =====
 +
 
 +
Some parts of the API are so-called ''hooks'', meaning that you define a function in a special location and it has some effect on the game. The following example documents a hook which takes one parameter and returns a value. Usually the double-ended arrow is used for hooks, but some may be write-only.
 +
 
 +
* '''wesnoth.some_table'''.''name'' &harr; '''function'''(''parameter'') &rarr; ''expected return value''
 +
 
 +
===== Context Specifiers =====
 +
 
 +
Many functions and variables are only available in certain contexts. Currently, there are three possible contexts - plugins, map generators, and the game. Most Lua will run in the game kernel. If a function is only available in certain contexts, that will be indicated with an icon at the beginning of the definition. For example:
 +
 
 +
* {{LuaGameOnly}} '''wesnoth.game_exclusive_function'''(''parameter'') &rarr; ''result''
  
Many functions and variables are only available in certain contexts. Currently, there are three possible contexts - plugins, map generators, and the game. Most Lua will run in the game kernel. If a function is only available in certain contexts, that will be indicated in parentheses at the beginning of the definition. For example:
+
The possible icons are:
  
* (game only) '''wesnoth.game_exclusive_function'''(''parameter'') &rarr; ''result''
+
* {{LuaGameOnly}} Available in the game context. Most Lua in Wesnoth runs in the game context, which is initialized when a game begins and destroyed upon victory or loss.
 +
* {{LuaMapOnly}} Available in the map generation context. This context is created at the game creation screen, generally to generate a map for a scenario.
 +
* {{LuaPluginOnly}} Available in the plugins context. There is only one plugins context, which is initialized when Wesnoth launches and remains valid until it shuts down. A plugin is a Lua script loaded via the command-line option <tt>--plugin</tt> that runs as a coroutine in parallel with the game UI. It can automatically connect to a server and host or join a game. This API is documented at [[LuaPluginAPI]].
  
<!-- TODO: Consider implementing image icons for these? -->
+
== Built-in Modules ==
  
Functions that take a variable number of parameters or return a variable number of values where the specific meaning of the parameters is unspecified will use the string "..." to indicate this. For example:
+
The following built-in Lua modules are available:
 +
 
 +
* [http://www.lua.org/manual/5.4/manual.html#6.1 basic] — except <tt>dofile</tt>, <tt>require</tt>, and <tt>loadfile</tt>; also note that <tt>print</tt> redirects to the Lua console interface rather than standard output; you can use <tt>std_print</tt> if you need the default Lua behavior.
 +
* [http://www.lua.org/manual/5.4/manual.html#6.2 coroutine]
 +
* [http://www.lua.org/manual/5.4/manual.html#6.4 string]
 +
* [http://www.lua.org/manual/5.4/manual.html#6.5 utf8]
 +
* [http://www.lua.org/manual/5.4/manual.html#6.6 table]
 +
* [http://www.lua.org/manual/5.4/manual.html#6.7 math] — note that <tt>math.random</tt> is unsafe for MP usage; wesnoth provides a separate MP-safe random function
 +
* [http://www.lua.org/manual/5.4/manual.html#6.9 os] — only the <tt>clock</tt>, <tt>date</tt>, <tt>time</tt>, and <tt>difftime</tt> functions are available (but keep in mind that they are not MP safe)
 +
* [http://www.lua.org/manual/5.4/manual.html#6.10 debug] — only the <tt>traceback</tt> function is available
  
* '''wesnoth.variadic_function'''(''required_param'' [, ...])
+
== Wesnoth Modules ==
* '''wesnoth.get_several_values'''(''param'') &rarr; ...
 
  
=== Wesnoth Modules ===
+
Wesnoth also provides several modules of its own, some of which are loaded by default while others require you to load them as needed. Note: APIs named '''wesnoth.something''', for example [[LuaAPI/wesnoth#wesnoth.scenario|wesnoth.scenario]], might be part of Core and not a separate module.
  
 
* [[LuaAPI/wesnoth|wesnoth]] (Core) - The <tt>wesnoth</tt> module contains most of the core Wesnoth API. It is always loaded and available.
 
* [[LuaAPI/wesnoth|wesnoth]] (Core) - The <tt>wesnoth</tt> module contains most of the core Wesnoth API. It is always loaded and available.
Line 50: Line 103:
 
** [[LuaAPI/wesnoth/audio|wesnoth.audio]] (Audio) - {{DevFeature1.15|13}} The <tt>audio</tt> submodule contains functions for playing music and sound effects.
 
** [[LuaAPI/wesnoth/audio|wesnoth.audio]] (Audio) - {{DevFeature1.15|13}} The <tt>audio</tt> submodule contains functions for playing music and sound effects.
 
** [[LuaAPI/wesnoth/paths|wesnoth.paths]] (Pathfinding) - {{DevFeature1.15|14}} The <tt>paths</tt> submodule contains functions related to pathfinding.
 
** [[LuaAPI/wesnoth/paths|wesnoth.paths]] (Pathfinding) - {{DevFeature1.15|14}} The <tt>paths</tt> submodule contains functions related to pathfinding.
 +
** [[LuaAPI/wesnoth/game_events|wesnoth.game_events]] (Event Handling) - The <tt>game_events</tt> submodule contains functions and hooks related to event handling.
 +
** [[LuaAPI/wesnoth/achievements|wesnoth.achievements]] (Achievements Support) - {{DevFeature1.17|13}} The <tt>achievements</tt> submodule contains functions for checking and setting achievements.
 
* [[LuaAPI/gui|gui]] (User Interface) - {{DevFeature1.15|0}} The <tt>gui</tt> module contains routines for showing dialogs on the screen. It does ''not'' contain anything for manipulating the in-game UI, however.
 
* [[LuaAPI/gui|gui]] (User Interface) - {{DevFeature1.15|0}} The <tt>gui</tt> module contains routines for showing dialogs on the screen. It does ''not'' contain anything for manipulating the in-game UI, however.
 
** [[LuaAPI/gui/widget|gui.widget]] (GUI Widget Support) - {{DevFeature1.15|6}} The <tt>widget</tt> submodule contains routines for operating on dialog widgets. Since they take a widget reference an argument, they can only be called while a dialog is onscreen.
 
** [[LuaAPI/gui/widget|gui.widget]] (GUI Widget Support) - {{DevFeature1.15|6}} The <tt>widget</tt> submodule contains routines for operating on dialog widgets. Since they take a widget reference an argument, they can only be called while a dialog is onscreen.
Line 55: Line 110:
 
* [[LuaAPI/location_set|location_set]] (Location Sets) - A module for working with sets of locations, optionally associating data to each location. Not loaded by default.
 
* [[LuaAPI/location_set|location_set]] (Location Sets) - A module for working with sets of locations, optionally associating data to each location. Not loaded by default.
 
* [[LuaAPI/functional|functional]] - Higher-order functions module. Not loaded by default.
 
* [[LuaAPI/functional|functional]] - Higher-order functions module. Not loaded by default.
* [[LuaAPI/filesystem|filesystem]] - Functions for dealing with files and assets.
 
 
* [[LuaAPI/stringx|stringx]] - Additional string support functions, to augment the built-in string module.
 
* [[LuaAPI/stringx|stringx]] - Additional string support functions, to augment the built-in string module.
 
* [[LuaAPI/mathx|mathx]] - {{DevFeature1.15|13}} Additional math and randomization support functions, to augment the built-in math module.
 
* [[LuaAPI/mathx|mathx]] - {{DevFeature1.15|13}} Additional math and randomization support functions, to augment the built-in math module.
 
* [[LuaAPI/filesystem|filesystem]] - {{DevFeature1.15|13}} Functions that allow read-only access to arbitrary files in the data folder.
 
* [[LuaAPI/filesystem|filesystem]] - {{DevFeature1.15|13}} Functions that allow read-only access to arbitrary files in the data folder.
 
* [[LuaAPI/ai|ai]] - Functions that instruct the AI on how to move.
 
* [[LuaAPI/ai|ai]] - Functions that instruct the AI on how to move.
 +
* [[LuaAPI/wml-utils|wml-utils]] - Useful functions for implementing custom WML tags.
 +
* [[LuaAPI/unit_test|unit_test]] - Functions that can be used to write unit tests; only available in [test] scenarios.
  
=== Wesnoth Types ===
+
== Wesnoth Types ==
  
 
Wesnoth defines a large number of ''userdata'' types, some of which are quite common and complex. Most of them are documented alongside the function that creates them, but some of the most common or complex ones are listed below.
 
Wesnoth defines a large number of ''userdata'' types, some of which are quite common and complex. Most of them are documented alongside the function that creates them, but some of the most common or complex ones are listed below.
Line 76: Line 132:
 
* [[LuaAPI/types/hex|hex]] - represents a single hex on the map.
 
* [[LuaAPI/types/hex|hex]] - represents a single hex on the map.
  
[[Category:Lua Reference]]
+
== See Also ==
 +
* [[LuaAPI/UpdatingFrom14]]
 +
* [[LuaAPI/old]] - The reference for the 1.14 Lua API, which may be useful if porting older add-ons
 +
 
 +
[[Category:Lua Reference|*]]

Latest revision as of 20:41, 23 April 2024

[edit]Lua Functions

wesnoth

wesnoth.as_text
wesnoth.colors
wesnoth.compile_formula
wesnoth.current
wesnoth.current_version
wesnoth.custom_synced_commands
wesnoth.deprecate_api
wesnoth.deprecated_message
wesnoth.dofile
wesnoth.effects
wesnoth.eval_formula
wesnoth.game_config
wesnoth.get_language
wesnoth.log
wesnoth.micro_ais
wesnoth.ms_since_init
wesnoth.name_generator
wesnoth.named_tuple
wesnoth.persistent_tags
wesnoth.print_attributes
wesnoth.races
wesnoth.require
wesnoth.scenario
wesnoth.simulate_combat
wesnoth.terrain_types
wesnoth.textdomain
wesnoth.type
wesnoth.unit_types
wesnoth.version
wesnoth.wml_actions
wesnoth.wml_conditionals

wesnoth.achievements

wesnoth.achievements.get
wesnoth.achievements.has
wesnoth.achievements.has_sub_achievement
wesnoth.achievements.progress
wesnoth.achievements.set
wesnoth.achievements.set_sub_achievement

wesnoth.audio

wesnoth.audio.music_list
wesnoth.audio.music_list.add
wesnoth.audio.music_list.all
wesnoth.audio.music_list.clear
wesnoth.audio.music_list.current
wesnoth.audio.music_list.next
wesnoth.audio.music_list.play
wesnoth.audio.music_list.previous
wesnoth.audio.music_list.remove
wesnoth.audio.music_list.volume
wesnoth.audio.play
wesnoth.audio.sources
wesnoth.audio.volume

wesnoth.game_events

wesnoth.game_events.add
wesnoth.game_events.add_menu
wesnoth.game_events.add_repeating
wesnoth.game_events.add_wml
wesnoth.game_events.fire
wesnoth.game_events.fire_by_id
wesnoth.game_events.on_event
wesnoth.game_events.on_load
wesnoth.game_events.on_mouse_action
wesnoth.game_events.on_mouse_button
wesnoth.game_events.on_mouse_move
wesnoth.game_events.on_save
wesnoth.game_events.remove

wesnoth.interface

wesnoth.interface.add_chat_message
wesnoth.interface.add_hex_overlay
wesnoth.interface.add_item_halo
wesnoth.interface.add_item_image
wesnoth.interface.add_overlay_text
wesnoth.interface.allow_end_turn
wesnoth.interface.clear_chat_messages
wesnoth.interface.color_adjust
wesnoth.interface.delay
wesnoth.interface.deselect_hex
wesnoth.interface.end_turn
wesnoth.interface.float_label
wesnoth.interface.get_displayed_unit
wesnoth.interface.get_hovered_hex
wesnoth.interface.get_items
wesnoth.interface.get_selected_hex
wesnoth.interface.get_viewing_side
wesnoth.interface.handle_user_interact
wesnoth.interface.highlight_hex
wesnoth.interface.is_locked
wesnoth.interface.is_skipping_messages
wesnoth.interface.lock
wesnoth.interface.remove_hex_overlay
wesnoth.interface.remove_item
wesnoth.interface.scroll
wesnoth.interface.scroll_to_hex
wesnoth.interface.select_unit
wesnoth.interface.skip_messages
wesnoth.interface.zoom

wesnoth.map

wesnoth.map.add_label
wesnoth.map.are_hexes_adjacent
wesnoth.map.create
wesnoth.map.distance_between
wesnoth.map.find
wesnoth.map.generate
wesnoth.map.generate_height_map
wesnoth.map.get
wesnoth.map.get_adjacent_hexes
wesnoth.map.get_area
wesnoth.map.get_direction
wesnoth.map.get_hexes_in_radius
wesnoth.map.get_label
wesnoth.map.get_owner
wesnoth.map.get_relative_dir
wesnoth.map.iter
wesnoth.map.make_bitmap
wesnoth.map.matches
wesnoth.map.on_board
wesnoth.map.on_border
wesnoth.map.parse_bitmap
wesnoth.map.place_area
wesnoth.map.read_location
wesnoth.map.remove_area
wesnoth.map.remove_label
wesnoth.map.rotate_right_around_center
wesnoth.map.set_owner
wesnoth.map.split_terrain_code
wesnoth.map.terrain_mask

wesnoth.paths

wesnoth.paths.find_cost_map
wesnoth.paths.find_path
wesnoth.paths.find_reach
wesnoth.paths.find_vacant_hex
wesnoth.paths.find_vision_range

wesnoth.schedule

wesnoth.schedule.get_illumination
wesnoth.schedule.get_time_of_day
wesnoth.schedule.replace

wesnoth.sides

wesnoth.sides.add_ai_component
wesnoth.sides.append_ai
wesnoth.sides.change_ai_component
wesnoth.sides.create
wesnoth.sides.debug_ai
wesnoth.sides.delete_ai_component
wesnoth.sides.find
wesnoth.sides.get
wesnoth.sides.is_enemy
wesnoth.sides.is_fogged
wesnoth.sides.is_shrouded
wesnoth.sides.iter
wesnoth.sides.matches
wesnoth.sides.override_shroud
wesnoth.sides.place_fog
wesnoth.sides.place_shroud
wesnoth.sides.remove_fog
wesnoth.sides.remove_shroud
wesnoth.sides.set_id
wesnoth.sides.switch_ai

wesnoth.sync

wesnoth.sync.evaluate_multiple
wesnoth.sync.evaluate_single
wesnoth.sync.invoke_command
wesnoth.sync.run_unsynced

wesnoth.units

wesnoth.unit.resistance_against
wesnoth.units.ability
wesnoth.units.add_modification
wesnoth.units.advance
wesnoth.units.chance_to_be_hit
wesnoth.units.clone
wesnoth.units.create
wesnoth.units.create_animator
wesnoth.units.defense_on
wesnoth.units.erase
wesnoth.units.extract
wesnoth.units.find
wesnoth.units.find_attack
wesnoth.units.find_on_map
wesnoth.units.find_on_recall
wesnoth.units.get
wesnoth.units.get_hovered
wesnoth.units.jamming_on
wesnoth.units.matches
wesnoth.units.movement_on
wesnoth.units.remove_modifications
wesnoth.units.scroll_to
wesnoth.units.select
wesnoth.units.to_map
wesnoth.units.to_recall
wesnoth.units.transform
wesnoth.units.vision_on

ai

ai.aspects
ai.attack
ai.check_attack
ai.check_move
ai.check_recall
ai.check_recruit
ai.check_stopunit
ai.fallback_human
ai.get_attacks
ai.get_targets
ai.move
ai.move_full
ai.read_only
ai.recall
ai.recruit
ai.side
ai.stopunit_all
ai.stopunit_attacks
ai.stopunit_moves
ai.suitable_keep

filesystem

filesystem.canonical_path
filesystem.have_asset
filesystem.have_file
filesystem.image_size
filesystem.read_file
filesystem.resolve_asset

functional

functional.choose
functional.choose_map
functional.filter
functional.filter_map
functional.find
functional.find_map
functional.map
functional.map_array
functional.reduce
functional.take_while
functional.zip

gui

gui.add_widget_definition
gui.get_user_choice
gui.show_dialog
gui.show_help
gui.show_inspector
gui.show_lua_console
gui.show_menu
gui.show_narration
gui.show_popup
gui.show_prompt
gui.show_story
gui.widget

location_set

location_set.clear
location_set.clone
location_set.create
location_set.diff
location_set.empty
location_set.filter
location_set.get
location_set.insert
location_set.inter
location_set.inter_merge
location_set.invert
location_set.iter
location_set.of_map
location_set.of_pairs
location_set.of_raw
location_set.of_shroud_data
location_set.of_triples
location_set.of_wml_var
location_set.random
location_set.remove
location_set.size
location_set.stable_iter
location_set.symm
location_set.to_map
location_set.to_pairs
location_set.to_shroud_data
location_set.to_stable_pairs
location_set.to_triples
location_set.to_wml_var
location_set.union
location_set.union_merge

mathx

mathx.clamp
mathx.lerp
mathx.random
mathx.random_choice
mathx.round
mathx.shuffle

stringx

stringx.anim_split
stringx.escaped_split
stringx.format_conjunct_list
stringx.format_disjunct_list
stringx.iter_range
stringx.iter_ranges
stringx.join
stringx.join_map
stringx.map_split
stringx.parenthetical_split
stringx.parse_range
stringx.quoted_split
stringx.split
stringx.trim
stringx.vformat

unit_test

unit_test.assert
unit_test.assert_approx_equal
unit_test.assert_contains
unit_test.assert_equal
unit_test.assert_greater
unit_test.assert_greater_equal
unit_test.assert_in_range
unit_test.assert_less
unit_test.assert_less_equal
unit_test.assert_not_equal
unit_test.assert_nothrow
unit_test.assert_throws
unit_test.assert_throws_with
unit_test.fail
unit_test.finish
unit_test.fire_wml_menu_item
unit_test.log
unit_test.succeed
unit_test.tostring

wml

wml.all_variables
wml.array_access.get
wml.array_access.get_proxy
wml.array_access.set
wml.array_variables
wml.attribute_count
wml.child_array
wml.child_count
wml.child_range
wml.clone
wml.diff
wml.equal
wml.error
wml.eval_conditional
wml.find_child
wml.fire
wml.get_child
wml.get_nth_child
wml.interpolate
wml.literal
wml.load
wml.matches_filter
wml.merge
wml.parse
wml.parsed
wml.patch
wml.remove_child
wml.remove_children
wml.shallow_literal
wml.shallow_parsed
wml.tag
wml.tostring
wml.tovconfig
wml.valid
wml.variables
wml.variables_proxy

wml-utils

utils.check_key
utils.get_sides
utils.handle_event_commands
utils.optional_side_filter
utils.scoped_var
utils.set_exiting
utils.vwriter

All Lua API functionality is available in one of several global module tables, as well as some global functions which form the basic Lua API. Wesnoth uses Lua 5.4 which is documented in detail on the Lua website.

This page documents the modules, functions, and other APIs available for use when writing Lua for Wesnoth. For information on how to tell the engine about your Lua code, see LuaWML.

Conventions used in this manual

On this page and any page linked from it, variable values will be shown in italic type, while literal names will be shown in bold type. Variable values may be parameters, self values, indexes, or field names on a table. Return values will be indicated by a right arrow (→) followed by a list of names in italics. The arrow will be omitted for a function that returns nothing. Optional portions will be enclosed in square brackets. The commas for optional parameters will not be included in the brackets, even though they must be omitted if the optional parameter is omitted.

Functions

For example, the following line would be seen in the documentation of a function that returns two values and has an optional parameter:

  • wesnoth.some_function(some_parameter, [some_optional_parameter]) → first_return_value, second_return_value
Methods

The following example documents a function that can be called as a method on a some_value, taking one additional parameter and returning one value.

  • some_value:some_method(some_parameter) → some_new_value
Variadic Functions

Functions that take a variable number of parameters or return a variable number of values where the specific meaning of the parameters is unspecified will use the string "..." to indicate this. For example:

  • wesnoth.variadic_function(required_param, [...])
  • wesnoth.get_several_values(param) → ...

The first of these takes a variable number of parameters, but requires at least one parameter. The second takes one parameter and returns a variable number of values.

Member Variables

Not all documented APIs are functions. When documenting userdata types, as well as some complex tables returned by API functions, the following syntax is used for member variables. The right arrow may be replaced with a left arrow (←) if it is write-only, or a double-ended arrow (↔) if it is read-write. Read-only members may return multiple values. The following examples document a read-write member, a read-only member that returns two values, and a write-only member respectively.

  • some_value.some_memberresult
  • some_value.read_only_memberfirst_result, second_result
  • some_value.write_only_memberinput
Operators

Custom types in Lua can overload operators with new functionality. Some examples of how these would be documented:

  • #wesnoth.list_like_objectnumber of somethings
  • wesnoth.list_like_object[index] ↔ a something definition table
  • comparable_value == comparable_valuewhether they are equal
  • operable_value + operable_valueresult

The first example documents that you can get the length of that object. The same format would be used for other unary operators as well.

The second example documents that you can index the object with arbitrary values. Whether the index needs to be a number would usually be mentioned in the detailed description, although the placeholder name may also make it clear. This example could also use a single-directional arrow to indicate that it is read-only or write-only.

The third example documents that you can compare two values of that type with the equality operator, and the fourth example documents that you can add two values of that type together with the addition operator.

Iterators

For functions that return an iterator, a double arrow indicates the values yielded when you use the iterator in a for loop. The following example documents a function returning an iterator that yields three values.

  • wesnoth.some_function() → iteratora, b, c
Hooks

Some parts of the API are so-called hooks, meaning that you define a function in a special location and it has some effect on the game. The following example documents a hook which takes one parameter and returns a value. Usually the double-ended arrow is used for hooks, but some may be write-only.

  • wesnoth.some_table.namefunction(parameter) → expected return value
Context Specifiers

Many functions and variables are only available in certain contexts. Currently, there are three possible contexts - plugins, map generators, and the game. Most Lua will run in the game kernel. If a function is only available in certain contexts, that will be indicated with an icon at the beginning of the definition. For example:

  • wesnoth.game_exclusive_function(parameter) → result

The possible icons are:

  • Available in the game context. Most Lua in Wesnoth runs in the game context, which is initialized when a game begins and destroyed upon victory or loss.
  • Available in the map generation context. This context is created at the game creation screen, generally to generate a map for a scenario.
  • 🔌 Available in the plugins context. There is only one plugins context, which is initialized when Wesnoth launches and remains valid until it shuts down. A plugin is a Lua script loaded via the command-line option --plugin that runs as a coroutine in parallel with the game UI. It can automatically connect to a server and host or join a game. This API is documented at LuaPluginAPI.

Built-in Modules

The following built-in Lua modules are available:

  • basic — except dofile, require, and loadfile; also note that print redirects to the Lua console interface rather than standard output; you can use std_print if you need the default Lua behavior.
  • coroutine
  • string
  • utf8
  • table
  • math — note that math.random is unsafe for MP usage; wesnoth provides a separate MP-safe random function
  • os — only the clock, date, time, and difftime functions are available (but keep in mind that they are not MP safe)
  • debug — only the traceback function is available

Wesnoth Modules

Wesnoth also provides several modules of its own, some of which are loaded by default while others require you to load them as needed. Note: APIs named wesnoth.something, for example wesnoth.scenario, might be part of Core and not a separate module.

Wesnoth Types

Wesnoth defines a large number of userdata types, some of which are quite common and complex. Most of them are documented alongside the function that creates them, but some of the most common or complex ones are listed below.

  • translatable strings - a string that will be translated by the engine.
  • vconfig - a WML object that automatically substitutes variables on the fly.
  • unit - represents a reference to Wesnoth unit on the map, on the recall list, or private to Lua.
  • weapon - represents a unit's weapon.
  • race - represents a unit's race.
  • unit type - represents a unit's type.
  • side - represents a single side (player) in the game.
  • widget - represents a GUI2 widget.
  • map - represents the game map.
  • hex - represents a single hex on the map.

See Also

This page was last edited on 23 April 2024, at 20:41.