Difference between revisions of "LuaAPI/wesnoth"

From The Battle for Wesnoth Wiki
(Data: Document wesnoth.scenario)
(wesnoth.wml_conditionals: Correct and link '''eval_conditional''')
Line 126: Line 126:
 
* (game only) '''wesnoth.wml_conditionals'''.''action'' ↔ ''function''
 
* (game only) '''wesnoth.wml_conditionals'''.''action'' ↔ ''function''
  
This is a hook table like wesnoth.wml_actions. You can use it to define new ConditionalWML tags that will be recognized in WML when using [if], [show_if], [while], etc., or more generally when '''wesnoth.eval_conditional''' is run.
+
This is a hook table like wesnoth.wml_actions. You can use it to define new ConditionalWML tags that will be recognized in WML when using [if], [show_if], [while], etc., or more generally when [[../wml#wml.eval_conditional|'''wml.eval_conditional''']] is run.
  
 
Use it like this:
 
Use it like this:

Revision as of 02:03, 22 June 2021

The wesnoth module contains most of the core Wesnoth API. It is always loaded and available.

Functions

wesnoth.dofile

  • wesnoth.dofile(file_path [, ...]) → ...

Loads and executes a file. The rules for locating the files are the same as for WML files, except that they require a .lua extension instead of .cfg. Any extra parameters to dofile are forwarded to the script (which can access them via the special ... variable), and dofile returns all the values returned by the script.

wesnoth.require

  • wesnoth.require(module) → module_contents

Returns the contents of the specified module, loading it if necessary. The module can either be a simple name or a file path similar to that used by wesnoth.dofile. In addition, the .lua extension will automatically be appended if necessary. The module script is invoked with no arguments, and wesnoth.require then passes back its first return value, discarding any additional ones. If the module is a directory, then all lua files are loaded, and a table containing the resulting modules is returned, with the keys being the filenames minus the .lua extension.

wesnoth.require returns nil on failure, for example if it could not locate the module. If it did locate the module, but the module did not return anything (or returned nil), then wesnoth.require returns an empty table with a metatable that raises an error on any attempt to access it.

wesnoth.read_file

  • wesnoth.read_file(file_path) → file_contents

Loads a file into memory and returns it as a string. The rules for locating the files are the same as for WML files, but with no requirements on file extension. If the path points to a directory, it instead returns a table containing a list of directory entries, sorted alphabetically with directories grouped at the beginning. In this case, there is also an ndirs member which contains the number of entries that are directories, allowing you to easily skip the directories if you wish.

wesnoth.have_file

  • wesnoth.have_file(file_path[, only_as_regular_file]) → boolean

Checks if a file exists. The rules for locating the files are the same as for WML files. Using the second parameter, you can distinguish regular files from directories.

wesnoth.textdomain

  • wesnoth.textdomain(domain) → textdomain_constructor

Returns a callable userdata that can be used to construct translatable strings. A typical use is:

local _ = wesnoth.textdomain "example"
wesnoth.alert(_ "This is an example translated string!")

The full syntax for using the result of this function is:

  • textdomain_constructor(string [, string_plural, number]) → translatable_string

By passing the optional arguments, you can vary the string based on a number that will be substituted into it. As with all Lua functions, the parentheses are optional when passing a single string argument, as in the above example.

The returned translatable string can be treated in many ways like a regular string. Translatable strings can be compared with other translatable strings or concatenated with each other or with regular strings or integers. The length operator also works, though it should be noted that its value may change if the language is changed. If you need to pass a translatable string to a function that doesn't understand them, it can be converted to a regular string with tostring.

wesnoth.as_text

(Version 1.15.10 and later only)

  • wesnoth.as_text(value1, value2, ...)

Accept one or more values as arguments and returns them as a string. This is intended for use as an easy way to view the contents of lua tables. Using the returned string for any other purpose is not supported.

Hooks

wesnoth.persistent_tags

  • (game only) wesnoth.persistent_tags.action.read(wml content)
  • (game only) wesnoth.persistent_tags.action.readfunction
  • (game only) wesnoth.persistent_tags.action.write(add_tag)
  • (game only) wesnoth.persistent_tags.action.writefunction

This is an associative table defining tags that should be persisted in saved games. Each tag is itself a table containing two functions, read and write. The write function is called in on_load and passed a function as a parameter which takes a WML table and adds it the saved game under the specified tag; the read function is called once per matching tag found in the saved game, and is passed a WML table of its contents. Note the asymmetry here: if you're saving an array, the write function is responsible for saving the entire array (and is only called once), while the read function is only responsible for loading one item (and is called several times).

Example:

local inventory = {}

function wesnoth.persistent_tags.inventory.read(cfg)
    inventory[cfg.side] = cfg
end

function wesnoth.persistent_tags.inventory.write(add)
    for i = 1, #wesnoth.sides do
        add(inventory[i])
    end
end

Notice that you don't need to create wesnoth.persistent_tags.inventory as an empty table first; you can simply define the read and write functions.

wesnoth.wml_actions

  • (game only) wesnoth.wml_actions.action(wml parameters)
  • (game only) wesnoth.wml_actions.actionfunction

This is a hook table that exposes and defines WML actions. Each function in this table corresponds to a single ActionWML tag, allowing you to invoke tags, define custom tags, and even modify the behavior of built-in tags. The single argument to these functions is a WML table, the content of the tag.

function wesnoth.wml_actions.freeze_unit(cfg)
    local unit_id = cfg.id or wml.error "[freeze_unit] expects an id= attribute."
    local unit = wesnoth.units.get(unit_id)
    if unit then unit.moves = 0 end
    wesnoth.units.modify({ id = unit_id }, { moves = 0 })
end

The new tag can now be used in plain WML code.

[freeze_unit]
    id=Delfador
[/freeze_unit]

You can override functions already assigned to the table. This is useful if you need to extend functionality of core tags. For instance, the following script overrides the [print] tag so that messages are displayed with a bigger font.

function wesnoth.wml_actions.print(cfg)
    local modified_cfg = setmetatable({}, {__index = cfg})
    modified_cfg.size = (cfg.size or 12) + 10
    wesnoth.wml_actions.print(modified_cfg)
end

An action handler should be able to handle being called with either a WML table or a WML vconfig userdata. It is recommended to pass the argument through wml.tovconfig before doing anything with it, both in the action's definition and when calling it directly (in case its definition did not do that). The engine always passes a vconfig when calling a WML action.

wesnoth.wml_conditionals

  • (game only) wesnoth.wml_conditionals.action(wml parameters) → boolean result
  • (game only) wesnoth.wml_conditionals.actionfunction

This is a hook table like wesnoth.wml_actions. You can use it to define new ConditionalWML tags that will be recognized in WML when using [if], [show_if], [while], etc., or more generally when wml.eval_conditional is run.

Use it like this:

function wesnoth.wml_conditionals.foo(cfg)
    local bar = cfg.bar or wml.error("[foo] tag did not have 'bar' attribute")

    return (bar == "baz")
end

If this lua code is executed, it would make the following syntax be valid WML in your add-on:

[if]
   [foo]
      bar = $X
   [/foo]
   [then]
      [message]
         # ...
      [/message]
   [/then]
[/if]

Note that the basic logic tags of ConditionalWML (true, false, and, or, not) do not pass through this table and cannot be overridden.

Data

Access to most of the game data is available via various tables in the wesnoth module.

wesnoth.colors

(Version 1.15.4 and later only)

  • wesnoth.colors.color_namecolor info

Access defined color ranges. This can be used to translate the color name available from wesnoth.sides[n].color to RGB values.

Each color info table contains the following keys:

  • mid - average shade for recoloring with the team color
  • min - minimum shade for recoloring with the team color (this is likely to be black)
  • max - maximum shade for recoloring with the team color (this is likely to be almost white)
  • minimap - representative color to use on the mini-map
  • pango_color - (Version 1.15.13 and later only) a hex string such as #ff0000 suitable for use in formatted text

Each of mid, min, max and minimap have the following keys:

  • r - red component of that color
  • g - green component of that color
  • b - blue component of that color
  • a - alpha component of that color (probably fully opaque)

Reference usage in mainline: see data/multiplayer/eras.lua

wesnoth.current

Contains various information about the current game and event state.

  • wesnoth.current.sideside number

The number of the currently active side.

  • wesnoth.current.turnturn number

The current turn number.

  • wesnoth.current.synced_statestate

Allows you to determine whether the current code runs in a synced context. Returns one of the following strings:

  • synced - The current code runs on all mp clients. This is the normal context, in which all gamestate changing actions should take place.
  • unsynced - The current code runs only on the local machine, so changing the gamestate here will cause out-of-sync errors. For example, during select events or during the calculation of a game_display hook. Typical things to do here are UI related things, or entering the synced state via [do_command].
  • local_choice - The current code was invoked by synchronize_choice and runs only on one local client to calculate the return value for the choice. You cannot enter the synced context with [do_command] now.
  • preload - We are currently running a preload event or an even earlier event. This behaves similar to local_choice.
  • wesnoth.user_can_invoke_commandsboolean

Indicates whether the player is currently able to take actions in the game.

  • wesnoth.current.mapmap userdata

The current active game map.

  • wesnoth.current.event_contexttable

Contains information on the current active event. Returns a table with the following keys:

  • name - The event name. This is the actual event that fired, not the name in the [event] tag, so it never contains commas or variables.
  • id - The event's unique ID, if it has one.
  • weapon - The first weapon relevant to the event, if any.
  • second_weapon - The second weapon relevant to the event, if any.
  • damage_inflicted - The damage inflicted in the event, if applicable.
  • x1, y1 - The first location relevant to the event, if any.
  • x2, y2 - The second location relevant to the event, if any.
  • unit_x, unit_y - The location of the first unit relevant t the event, if any. This is the same as x1, y1 in most cases. Currently the only exceptions are enter and exit hex events.

wesnoth.game_config

Contains static global information about the game. Some of this information can also be modified on the fly, but only in the game context, not in the plugin or map generator context.

  • wesnoth.game_config.base_incomeinteger
  • wesnoth.game_config.village_incomeinteger
  • wesnoth.game_config.village_supportinteger
  • wesnoth.game_config.poison_amountinteger
  • wesnoth.game_config.rest_heal_amountinteger'
  • wesnoth.game_config.recall_costinteger
  • wesnoth.game_config.combat_experienceinteger
  • wesnoth.game_config.kill_experienceinteger

Values of various game settings.

  • (game only) wesnoth.game_config.do_healingboolean

Whether healing will occur at the beginning of each side's turn.

  • (game_only) wesnoth.game_config.themetheme id

The currently active in-game theme.

  • wesnoth.game_config.debugboolean

Whether debug mode is currently active. Debug mode is activated by the --debug command-line parameter or the :debug in-game command.

  • wesnoth.game_config.debug_luaboolean

Whether Lua debug is enabled. Lua debug is activated by the --debug-lua command-line parameter. This does not seem to do anything by default.

  • wesnoth.game_config.mp_debugboolean

Whether MP debug is enabled. MP debug is activated in the same way as debug mode, but is only active in multiplayer games.

  • wesnoth.game_config.strict_luaboolean

Whether strict Lua mode is enabled. Strict Lua mode is activated by the --strict-lua command-line parameter and causes all deprecated Lua APIs to be completely removed from the engine.

wesnoth.races

  • wesnoth.races.idrace info

Access defined races. Returns a race userdata.

wesnoth.scenario

Contains information about the current scenario

  • wesnoth.scenario.turnsturn limit

The current turn limit of the scenario.

  • wesnoth.scenario.nextscenario id

The ID of the scenario to transition to when this scenario ends.

  • wesnoth.scenario.idscenario id

The ID of the current scenario.

  • wesnoth.scenario.defeat_musiclist of music tracks

The music to play if you lose this scenario.

  • wesnoth.scenario.victory_musiclist of music tracks

The music to play if you win this scenario.

  • wesnoth.scenario.show_credits'boolean

Whether credits should be shown when this scenario ends. Only relevant if wesnoth.scenario.next is nil.

  • wesnoth.scenario.end_texttext

The end text to show when the scenario ends. Only relevant if wesnoth.scenario.next is nil.

  • wesnoth.scenario.end_text_durationduration

How long to show the end text for when the scenario ends. Only relevant if wesnoth.scenario.next is nil.

  • wesnoth.scenario.difficultydifficult

The difficulty level this scenario is being played on.

  • wesnoth.scenario.typetag name

The type of this scenario. One of the strings scenario, multiplayer, or test.

  • wesnoth.scenario.eraera tag

The [era] tag active in this scenario. Accessing this will throw an error in single-player games.

  • wesnoth.scenario.campaigncampaign tag

The [campaign] tag active in this scenario. Accessing this will throw an error in multiplayer or test games, so be sure to check wesnoth.scenario.type first in generic code.

  • wesnoth.scenario.resourceslist of resource tags

A list of [resource] tags active in this scenario.

  • wesnoth.scenario.modificationslist of modification tags

A list of [modification] tags active in this scenario.

  • wesnoth.scenario.mp_settingstable

In a multiplayer game, this is a proxy table which gives read only access to all MP-only configuration options which appear as attributes of [multiplayer] tag in a save game file. This allows accessing basically everything that can be set in the create game screen. The following keys exist in the returned table:

  • active_mods - A list of all active modification IDs
  • hash - A hash of mp data
  • mp_campaign - Name of mp campaign
  • mp_scenario - ID of this mp scenario
  • mp_scenario_name - Name of this mp scenario
  • scenario - MP lobby title
  • difficulty_define - The campaign difficulty string for an mp campaign
  • mp_village_gold
  • mp_village_support
  • mp_num_turns
  • mp_era - The id of the chosen era
  • mp_eras - A list of all era ids
  • mp_fog
  • mp_shroud
  • mp_random_start_time
  • experience_modifier
  • mp_use_map_settings
  • mp_countdown - Whether the timer is enabled
  • mp_countdown_action_bonus
  • mp_countdown_init_time
  • mp_countdown_reservoir_time
  • mp_countdown_turn_bonus
  • observer
  • shuffle_sides
  • savegame - Whether this is a reloaded game
  • side_users - List of how sides are assigned to users (at game start)

wesnoth.terrain_types

(Version 1.15.12 and later only)

  • wesnoth.terrain_types[code] → terrain info

Access defined terrain types by their terrain code. Returns a table with the following keys:

  • id
  • name
  • editor_name
  • description
  • icon
  • editor_image
  • light
  • village
  • castle
  • keep
  • healing

wesnoth.unit_types

  • wesnoth.unit_types[id] → unit type info

Access defined unit types by their ID. Returns a unit type userdata.

Submodules

The wesnoth module also contains a number of submodules for working with particular aspects of the game.

wesnoth.game_events

A submodule containing functions for working with event handlers.

wesnoth.map

(Version 1.15.11 and later only)

A submodule containing functions for querying and manipulating the game map.

wesnoth.interface

(Version 1.15.0 and later only)

A submodule containing functions pertaining to the in-game UI.

wesnoth.sides

(Version 1.15.3 and later only)

A submodule containing functions for manipulating the sides of a scenario.

wesnoth.units

(Version 1.15.0 and later only)

A submodule containing functions to manipulate units on the map.