Difference between revisions of "LuaAPI/wesnoth"
m (→wesnoth.wml_conditionals: Fix an arrow) |
(→wesnoth.game_config: Document game_config.palettes and game_config.xx_scale[_text]) |
||
(80 intermediate revisions by 5 users not shown) | |||
Line 1: | Line 1: | ||
+ | <div class="tright"> __TOC__ </div> | ||
+ | |||
The <tt>wesnoth</tt> module contains most of the core Wesnoth API. It is always loaded and available. | The <tt>wesnoth</tt> module contains most of the core Wesnoth API. It is always loaded and available. | ||
+ | |||
+ | == Functions == | ||
=== wesnoth.dofile === | === wesnoth.dofile === | ||
− | * '''wesnoth.dofile'''(''file_path'' [ | + | * '''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 <tt>...</tt> variable), and '''dofile''' returns all the values returned by the script. | 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 <tt>...</tt> variable), and '''dofile''' returns all the values returned by the script. | ||
Line 13: | Line 17: | ||
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. | 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.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.textdomain === | === wesnoth.textdomain === | ||
Line 40: | Line 32: | ||
The full syntax for using the result of this function is: | The full syntax for using the result of this function is: | ||
− | * ''textdomain_constructor''(''string'' [ | + | * ''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. | + | 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. This plural syntax returns a form of the string that's grammatically suitable for the indicated number, but doesn't actually substitute the number in – you need to do that yourself with either '''string.format''' or '''stringx.vformat'''. |
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. | 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. | + | === wesnoth.log === |
+ | |||
+ | * '''wesnoth.log'''([''logger''], ''message'', ''in_chat'') | ||
+ | |||
+ | Logs a message to the console. These messages are normally not visible unless Wesnoth is run from the command-line or (in Windows) with the --wconsole switch. The in_chat argument, however, can be set to true to also echo the message to the in-game chat area. | ||
+ | |||
+ | ''logger'' is the log level. | ||
+ | |||
+ | In any context, ''logger'' can be the standard log levels of '''info''', '''debug''', '''warning''', or '''error'''. Various abbreviations of the standard four are also recognised. The default logger is '''info'''. | ||
+ | |||
+ | In the game context, you can also set the ''logger'' to '''wml'''. The '''wml''' log level is special and is intended for WML errors; it always goes to chat, so the in_chat argument is ignored and can be omitted. | ||
+ | |||
+ | The logdomain to enable these logs depends on the context. In the game context, they are written to the '''wml''' logdomain. In other contexts, the logdomain is '''scripting/lua/user'''. | ||
+ | |||
+ | === wesnoth.as_text === | ||
+ | |||
+ | {{DevFeature1.15|10}} | ||
+ | |||
+ | * {{LuaGameOnly}} '''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. | ||
+ | |||
+ | {{DevFeature1.17|0}} This is now available in all contexts. | ||
+ | |||
+ | === wesnoth.simulate_combat === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.simulate_combat'''(''attacker'', [''attacker_weapon_index''], ''defender'', [''defender_weapon_index'']) → ''attacker stats evaluation'', ''defender stats evaluation'', ''attacker weapon evaluation'', ''defender weapon evaluation'' | ||
+ | |||
+ | Computes the hitpoint distribution and status chance after a combat between two units. The first unit is the attacker. The attacker does not have to be on the map, but its location should be meaningful - that is, it can be a private-to-Lua clone of a unit with the '''x''' and '''y''' values changed, but whatever it is it has to have '''x''' and '''y''' values that allow attacking the defender (with '''max_range''' of the attack set appropriately it's possible to simulate attacking non-adjacent units). The second unit is the defender; it has to be on the map. | ||
+ | |||
+ | Optional integers can be passed after each unit to select a particular weapon, otherwise the "best" one is selected. When giving the weapon, the parameter is the weapon number (integer, starting at 1) and not the attack definition. | ||
+ | |||
+ | The function returns four tables describing the evaluation of the combat. The first two contain an evaluation of the combatant's stats over the course of the fight, while the second two contains more detailed information on their weapons. | ||
+ | |||
+ | The stats evaluation tables contain the following keys: | ||
+ | |||
+ | * ''stats''.'''poisoned''' → ''probability'' | ||
+ | * ''stats''.'''slowed''' → ''probability'' | ||
+ | * ''stats''.'''untouched''' → ''probability'' | ||
+ | |||
+ | The probability that the unit will be poisoned or slowed, or that it will survive with no damage taken. (A scenario where the unit's hitpoints increase counts as untouched.) | ||
+ | |||
+ | * ''stats''.'''average_hp''' → ''number'' | ||
+ | |||
+ | The expected value of the unit's hitpoints after the fight. | ||
+ | |||
+ | * ''stats''.'''hp_chance''' → ''mapping of hp to probability'' | ||
+ | |||
+ | The probability that the unit's hitpoints will be at a specific value after the fight. Though it looks almost like an array, it begins at index 0 unlike a typical Lua array. Thus, it's better understood as an associated mapping from the resulting hitpoints value to the probability of ending the combat with that value. Therefore, the value at index 0 represents the chance that the unit will die. | ||
+ | |||
+ | The weapon evaluation tables contain the following keys: | ||
+ | |||
+ | num_blows, damage, chance_to_hit, poisons, slows, petrifies, plagues, plague_type, backstabs, rounds, firststrike, drains, drain_constant, drain_percent, attack_num, name | ||
+ | |||
+ | <syntaxhighlight lang='lua'> | ||
+ | local function display_stats(n, t) | ||
+ | wesnoth.interface.add_chat_message(string.format( | ||
+ | "Chance for the %s\n to be slowed: %f,\n to be poisoned: %f,\n to die: %f.\nAverage HP: %f.", | ||
+ | n, t.slowed, t.poisoned, t.hp_chance[0], t.average_hp)) | ||
+ | end | ||
+ | local att_stats, def_stats = wesnoth.simulate_combat(att, att_weapon, def, def_weapon) | ||
+ | display_stats("attacker", att_stats) | ||
+ | display_stats("defender", def_stats) | ||
+ | |||
+ | local att_stats, def_stats, att_weapon, def_weapon = wesnoth.simulate_combat(attacker, att_weapon_number, defender) | ||
+ | wesnoth.interface.add_chat_message(string.format( | ||
+ | "The attack %s should be countered with %s, which does %d damage, has %d%% chance to hit and forces %d attack rounds due to its berserk ability.", | ||
+ | att_weapon.name, def_weapon.name or "no weapon", def_weapon.damage, def_weapon.chance_to_hit, def_weapon.rounds)) | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === wesnoth.name_generator === | ||
+ | |||
+ | * '''wesnoth.name_generator'''('''"markov"''', ''definition'', [''chain_size'', [''max_length'']]) → ''generator function'' | ||
+ | * '''wesnoth.name_generator'''('''"cfg"''', ''definition'') → ''generator function'' | ||
+ | * ''generator function''() → ''random name'' | ||
+ | |||
+ | Constructs a name generator for use in generating names using either the Markov chain algorithm used in older versions of Wesnoth or the context-free grammar generator used since 1.13.5. The type parameter indicates which algorithm to use (either markov or cfg). The definition can be a string, just like it would be in a config file, or it can be formatted as a table. Additional parameters may be passed, depending on the type of generator. The function returns a callable userdata, which will return a new name each time it is called (with no parameters). | ||
+ | |||
+ | * '''Markov chain''': A Markov chain generator works by analyzing a list of input names and noticing tendencies in the way the letters are strung together. It can then apply those tendencies to produce new similar names that were not in the original list. Longer lists give better results. The definition is a list of names, formatted either as a comma-separated string or as an array-like table. The Markov generator can take two additional parameters. | ||
+ | ** ''chain_size'': A value greater than 1 for the ''chain_size'' causes the analyzer to consider the words in chunks, which is similar to analyzing them syllable by syllable instead of letter by letter. The default chain size is 2, meaning that the analyzer treats words as consisting of 2-character syllables. | ||
+ | ** ''max_length'': Places a cap on the total length of the name. The default value is 12 characters. | ||
+ | <syntaxhighlight lang=lua> | ||
+ | local markov_names = wesnoth.name_generator('markov', {'Kaasa', 'Kayya', 'Keyya', 'Kiira', 'Korra'}, 1) | ||
+ | print(markov_names(), markov_names(), markov_names()) | ||
+ | </syntaxhighlight> | ||
+ | * '''Context-free grammar''': A [[context-free grammar]] is a way of specifying how strings can be constructed. The definition may be specified as a multi-line string, just as described in the preceding link, or it can be formatted as a table where the keys are non-terminals and the values are what they expand to. The expansion of each non-terminal can be formatted either as a |-separated list as described in the preceding link, or as an array-like table. (Mixing the two forms is permissible too.) The context-free generator has no additional parameters. | ||
+ | <syntaxhighlight lang=lua> | ||
+ | local cfg_names = wesnoth.name_generator('cfg', { | ||
+ | main = {'{prefix}{suffix}', '{prefix}{centre}{suffix}'}, | ||
+ | prefix = 'Kaa|Ka|Ke|Kuu|Ko', | ||
+ | suffix = 'sa|yya|ra|rra', | ||
+ | centre = 'err|aash|eez|azz' | ||
+ | }) | ||
+ | print(cfg_names(), cfg_names(), cfg_names()) | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | '''Note''': If you want to generate a name using any of the default generators, you can use the predefined generators in the [[LuaAPI/types#race|race]] instead of constructing one with this function. | ||
+ | |||
+ | === wesnoth.compile_formula === | ||
+ | |||
+ | * '''wesnoth.compile_formula'''(''formula'') → ''compiled formula'' | ||
+ | |||
+ | Compiles a [[Wesnoth Formula Language]] formula into a Lua callable userdata. A compiled formula can be converted back to valid code using the built-in <code>tostring</code> function. | ||
+ | |||
+ | === wesnoth.eval_formula === | ||
+ | |||
+ | * '''wesnoth.eval_formula'''(''formula'', [''variables'']) → ''result'' | ||
+ | * ''compiled formula''([''variables'']) → ''result'' | ||
+ | |||
+ | Evaluate a [[Wesnoth Formula Language]] formula and return the result it computed (which can be '''nil'''). | ||
+ | |||
+ | The passed in variables can be an arbitrary Lua table, which defines variables available to the formula. Unlike with WML tables, there is no restriction on the format of this table. The formula can access the variables as a list using the special WFL variable '''__list''', or as a map using the special WFL variable '''__map'''. Directly accessing keys on the table is also possible. | ||
+ | |||
+ | It is also possible to pass a unit proxy as the variables, which evaluates the formula in that unit's context just as if it had been used in a [[StandardUnitFilter]]. | ||
+ | |||
+ | When calling '''wesnoth.eval_formula''', the first argument may either be an already-compiled formula or a string, in which case it will be automatically compiled on the fly. | ||
+ | |||
+ | <syntaxhighlight lang=lua> | ||
+ | local f = wesnoth.compile_formula('if(x > y, x - y, x + y)') | ||
+ | |||
+ | print(f{x=1,y=2}) -- prints 3.0 | ||
+ | print(f{x=1,y=3}) -- prints 4.0 | ||
+ | print(f{x=2,y=3}) -- prints 5.0 | ||
+ | print(f{x=1,y=1}) -- prints 2.0 | ||
+ | print(f{x=3,y=1}) -- prints 2.0 | ||
+ | print(f{x=3,y=2}) -- prints 1.0 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === wesnoth.version === | ||
+ | |||
+ | * '''wesnoth.version'''(''version string'') → ''version'' | ||
+ | * '''wesnoth.version'''(''major'', [''minor'', [''patch'']], [''suffix'')) → ''version'' | ||
+ | |||
+ | Creates a version object, either by parsing a string or by building it from its component parts. The resulting version object can be compared with other version objects using the standard Lua comparison operators, which follows the same rules as the [[PreprocessorRef#.23ifver_and_.23ifnver|#ifver]] preprocessor statement. It can also be decomposed by accessing the following keys on the object: | ||
+ | |||
+ | * ''integer'': Grab any integer version component by index. A non-canonical version may have more than three components. | ||
+ | * '''major''': The major version number (index 1). | ||
+ | * '''minor''': The minor version number (index 2). | ||
+ | * '''revision''': The patch revision number (index 3). | ||
+ | * '''is_canonical''': True if the version has at most three components (plus an optional suffix). | ||
+ | * '''sep''': The character that separates the version components from the suffix (usually either + or nil). | ||
+ | * '''special''': The version suffix, for example the "dev" in "1.15.14+dev". | ||
+ | |||
+ | The version can be converted to a string using the built-in '''tostring''' function. | ||
+ | |||
+ | <syntaxhighlight lang=lua> | ||
+ | local function version_is_sufficient(required) | ||
+ | return wesnoth.current_version() >= required | ||
+ | end | ||
+ | local required = wesnoth.version "1.9.6" | ||
+ | if not version_is_sufficient(required) then | ||
+ | gui.alert(string.format("Your BfW version is insufficient, please get BfW %s or greater!", tostring(required))) | ||
+ | end | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === wesnoth.current_version === | ||
+ | |||
+ | * '''wesnoth.current_version'''() → ''current version'' | ||
+ | |||
+ | Returns the current version of Wesnoth as a version object. | ||
+ | |||
+ | === wesnoth.ms_since_init === | ||
+ | |||
+ | * '''wesnoth.ms_since_init'''() → ''milliseconds'' | ||
+ | |||
+ | This function returns the amount of milliseconds that have passed since Wesnoth started up the current session. Its only use is to track the passage of real time. | ||
+ | |||
+ | '''WARNING:''' this function uses the same code as [set_variable] time=stamp, and so it is MP-unsafe. It is provided only for benchmark purposes and AI development, although it should work inside wesnoth.synchronize_choice() as well. | ||
+ | |||
+ | === wesnoth.deprecated_message === | ||
+ | |||
+ | * '''wesnoth.deprecated_message'''(''element_name'', ''level'', ''version'', ''detail_message'') | ||
+ | |||
+ | Displays a deprecation warning in the Lua console. The level is an integer from 1 to 4 inclusive (see [[CompatibilityStandards#Deprecation_levels_-_When_to_remove_deprecated_features|deprecation levels]]), and the version can be left nil for levels 1 and 4. Otherwise it must be a version ''string'' (not a version object from [[#wesnoth.version|wesnoth.version]]). | ||
+ | |||
+ | === wesnoth.deprecate_api === | ||
+ | |||
+ | * '''wesnoth.deprecate_api'''(''original_name'', ''new_name'', ''level'', ''version'', ''element'', ''detail_message'') → ''deprecated wrapper'' | ||
+ | |||
+ | Creates a deprecated wrapper for a function or table. A deprecated function will raise the deprecated message the first time it's called, and then suppress it thereafter. A deprecated table will raise the deprecated message the first time a key is read or assigned, and then suppress it thereafter. | ||
+ | |||
+ | The ''element'' is the function or table to wrap. It can be the original function or the new function (which may happen if the function was renamed without any interface changes), or a wrapper function that calls the new function while providing the interface of the old function. The ''level'' and ''version'' are as in [[#wesnoth.deprecated_message|wesnoth.deprecated_message]]. | ||
+ | |||
+ | If ''level'' is 4, then the ''element'' is ignored (you can pass '''nil''') and a generic deprecated wrapper is returned that does nothing but raises the deprecated message the first time you call it, assign a key, or read a key, and suppresses it thereafter. This is intended for a function that was removed without deprecation, to leave behind a more informative message if someone still attempts to use it. | ||
+ | |||
+ | If Wesnoth is run with the <tt>--strict-lua</tt> command-line option, this function will return '''nil''' instead of the deprecated wrapper. Since the normal use-case of this function is to assign the deprecated wrapper to the original name, this has the effect of erasing any deprecated functions from the API. | ||
+ | |||
+ | The result of this function always contains a '''__deprecated''' attribute set to true, which can allow identifying if something is deprecated. | ||
+ | |||
+ | === wesnoth.type === | ||
+ | |||
+ | {{DevFeature1.17|?}} | ||
+ | |||
+ | * '''wesnoth.type'''(''value'') → ''type name'' | ||
+ | |||
+ | Returns a string describing the value's type. This is the same as the built-in type function, except that it returns a more specific string in the case of userdata or tables, based on the metatable. For example, it would return 'unit' if called on a unit. | ||
+ | |||
+ | === wesnoth.named_tuple === | ||
+ | |||
+ | {{DevFeature1.17|?}} | ||
+ | |||
+ | * '''wesnoth.named_tuple'''(''array'', ''names'') → ''named tuple'' | ||
+ | |||
+ | Decorates a numeric based array so that the indices can be accessed by name instead of by index. This function is used internally for a number of things, most notably map locations and WML tags. Most end-users will not need to use it, but it could be useful if you wish to build a Lua API that returns locations (or similar data) in the engine-standard format. | ||
+ | |||
+ | For example: | ||
+ | |||
+ | <syntaxhighlight lang=lua> | ||
+ | local t = wesnoth.named_tuple({42,21,36}, {'x', 'y', 'z'}) | ||
+ | |||
+ | print(t[1]) -- prints 42 | ||
+ | print(t[2]) -- prints 21 | ||
+ | print(t[3]) -- prints 36 | ||
+ | print(t.x) -- prints 42 | ||
+ | print(t.y) -- prints 21 | ||
+ | print(t.z) -- prints 36 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === wesnoth.get_language === | ||
+ | |||
+ | * '''wesnoth.get_language'''() → ''string'' | ||
+ | |||
+ | Gets the language the UI is currently set to. Note that this may return an empty string if using the system default language. | ||
+ | |||
+ | === wesnoth.print_attributes === | ||
+ | |||
+ | * '''wesnoth.print_attributes'''(''object'', [''function'']) | ||
+ | |||
+ | Prints out a list of attributes that can be accessed on the object, excluding deprecated functionality. The function defaults to '''print''', and receives a formatted line usually containing multiple attributes. They are annotated by type – ƒ for a function, † for a table, ! if there was an error attempting to determine the type (which includes write-only attributes). Other types are unannotated. | ||
+ | |||
+ | For tables, by default this iterates the table using '''pairs''' to discover the attributes available, walking the metatable hierarchy if there is an '''__index''' table and filtering out anything that contains a '''__deprecated''' attribute set to '''true'''. However, if finds a function as the '''__index''', and the table's metatable also has a member '''__dir''', it will be used instead. The '''__dir''' can either be an array of strings, or a function that returns an array of strings. It will automatically be sorted and have any duplicates filtered out. | ||
+ | |||
+ | For custom objects defined by the engine, there is special handling so that this function shows the correct result. For example, if used on a GUI2 widget object, it will show the attributes available for that type of widget, as well as the IDs of any sub-widgets that can be accessed by name. | ||
+ | |||
+ | In the Lua console only, this function can also be referenced by a shorter alias, '''dir'''. | ||
+ | |||
+ | == Hooks == | ||
+ | |||
+ | === wesnoth.persistent_tags === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.persistent_tags'''.''action''.'''read''' ↔ '''function'''(''wml content'') | ||
+ | * {{LuaGameOnly}} '''wesnoth.persistent_tags'''.''action''.'''write''' ↔ '''function'''(''add_tag_function'') | ||
+ | |||
+ | 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 <tt>on_load</tt> and passed a function as a parameter which takes a WML table and adds it to 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: | ||
+ | |||
+ | <syntaxhighlight lang=lua> | ||
+ | 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 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Notice that you don't need to create <tt>wesnoth.persistent_tags.inventory</tt> as an empty table first; you can simply define the read and write functions. | ||
+ | |||
+ | === wesnoth.wml_actions === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.wml_actions'''.''action'' ↔ '''function'''(''wml parameters table'') | ||
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. | 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. | ||
Line 82: | Line 336: | ||
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. | 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 === | |
− | * | + | * {{LuaGameOnly}} '''wesnoth.wml_conditionals'''.''action'' ↔ '''function'''(''wml parameters table'') → ''boolean result'' |
− | |||
− | This is a hook table like wesnoth.wml_actions. You can use it to define new | + | 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: | ||
Line 113: | Line 366: | ||
[/if] | [/if] | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | Note that the basic logic tags of ConditionalWML (true, false, and, or, not) do not pass through this table and cannot be overridden. | ||
+ | |||
+ | === wesnoth.effects === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.effects'''.''name'' ↔ '''function'''(''unit'', ''wml table'') | ||
+ | * {{LuaGameOnly}} '''wesnoth.effects'''.''name''.'''__descr''' ↔ ''description'' | ||
+ | * {{LuaGameOnly}} '''wesnoth.effects'''.''name''.'''__descr''' ↔ '''function'''(''unit'', ''wml table'') → ''description'' | ||
+ | |||
+ | This table contains the implementation of [[EffectWML|[effect]]]s. Each value is a callable value that takes a unit and the effect config. It can be a function or a callable table. If it is a callable table, its metatable may have a '''__descr''' field which is either a string or a function. Built-in effects are present in this table, and you may register your own custom effects too. | ||
+ | |||
+ | <syntaxhighlight lang='lua'> | ||
+ | function wesnoth.effects.min_resistance(u, cfg) | ||
+ | local resistance_new = {} | ||
+ | local resistance_old = wml.parsed(wml.get_child(cfg, "resistance")) | ||
+ | for k,v in pairs(resistance_old) do | ||
+ | if type(k) == "string" and type(v) == "number" and u:resistance_to(k) >= v then | ||
+ | resistance_new[k] = v | ||
+ | end | ||
+ | end | ||
+ | wesnoth.effects.resistance(u, { | ||
+ | apply_to = "resistance", | ||
+ | replace = true, | ||
+ | T.resistance (resistance_new), | ||
+ | }) | ||
+ | end | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | The code above adds a new <code>min_resistance</code> effect that will set the resistances to specific values if they are currently below that value. It can then be used like this (for example, in [[DirectActionsWML#.5Bobject.5D|[object]]]): | ||
+ | |||
+ | <syntaxhighlight lang='wml'> | ||
+ | [effect] | ||
+ | apply_to=min_resistance | ||
+ | [resistance] | ||
+ | cold=50 | ||
+ | [/resistance] | ||
+ | [/effect] | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Note that in order work properly, effects must be registered before any units are created. This means it must be placed into a global or scenario level [lua] tag. In particular, the preload event is too late. | ||
+ | |||
+ | You can also specify description modifiers, which will be used if a custom effect is placed in a <code>[trait]</code> tag. Instead of setting a function as the effect, you set a table with a <code>__call</code> metafunction which does what the function would have done. The table can then have an additional <code>__descr</code> metafunction which updates descriptions as necessary. The built-in effects all use this structure. This metafunction takes the same arguments as the regular effect function, but should not modify the unit. Instead, it returns a string to be appended to the trait's effect description. | ||
+ | |||
+ | === wesnoth.micro_ais === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.micro_ais'''.''ai_name'' ↔ ''function''(''cfg'') → ''required'', ''optional'', ''ca_params'' | ||
+ | |||
+ | Registers a new [[Micro_AIs#Custom_Micro_AIs|MicroAI]] with '''ai_type'''=''ai_name''. The function will be called by the [micro_ai] tag to set up the AI. See the link for more details on how this works. | ||
+ | |||
+ | === wesnoth.custom_synced_commands === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.custom_synced_commands'''.''command_name'' ↔ ''function''(''cfg'') | ||
+ | |||
+ | Registers a custom synced command, which can be invoked by AI to enable unusual behaviour. The command can do basically anything, and is guaranteed to run on all clients. The WML table passed to the callback is the same table passed to [[LuaAPI/wesnoth/sync#wesnoth.sync.invoke_command|wesnoth.sync.invoke_command]]. | ||
+ | |||
+ | == Data == | ||
+ | |||
+ | Access to most of the game data is available via various tables in the <tt>wesnoth</tt> module. | ||
+ | |||
+ | === wesnoth.colors === | ||
+ | |||
+ | {{DevFeature1.15|4}} | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.colors'''.''color_name'' → ''color info'' | ||
+ | |||
+ | Access defined [[GameConfigWML#Color_Palettes|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''' - {{DevFeature1.15|13}} 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. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.side''' → ''side number'' | ||
+ | |||
+ | The number of the currently active side. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.turn''' → ''turn number'' | ||
+ | |||
+ | The current turn number. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.synced_state''' → ''state'' | ||
+ | |||
+ | 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 [[LuaAPI/wesnoth/interface#wesnoth.interface.game_display|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 [[#wesnoth.synchronize_choice|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'''. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.user_can_invoke_commands''' → ''boolean'' | ||
+ | |||
+ | Indicates whether the player is currently able to take actions in the game. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.map''' → ''map userdata'' | ||
+ | |||
+ | The current active game map. See [[LuaAPI/types/map]] and [[LuaAPI/wesnoth/map]] for information on how this data can be used. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.schedule''' → ''schedule userdata'' | ||
+ | |||
+ | The current global time schedule. This is a special object with the following properties: | ||
+ | |||
+ | :* #''schedule'' | ||
+ | :The Lua length operator will return the number of turns in the schedule. | ||
+ | |||
+ | :* ''schedule''[''index''] ↔ ''time of day info'' | ||
+ | :Get the information for a particular time of day, or replace it with new info. | ||
+ | |||
+ | :* ''schedule''.'''time_of_day''' ↔ ''id'' | ||
+ | :Get the ID of the current active time of day, or switch to a new one. If the time of day occurs more than once in the schedule, the time will be set to the first occurrence. | ||
+ | |||
+ | :* ''schedule''.'''liminal_bonus''' ↔ ''bonus'' | ||
+ | :Get the maximum bonus for liminal units in the current schedule. You can also override the default by assigning a different value, or revert to the default by assigning nil. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.current.event_context''' → ''WML table'' | ||
+ | |||
+ | 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 to the event, if any. This is the same as '''x1''', '''y1''' in most cases. Currently the only exceptions are enter and exit hex events. | ||
+ | :* '''data''' - {{DevFeature1.17|6}} The event data. Can contain anything at all if the event was fired by [[LuaAPI/wesnoth/game_events#wesnoth.game_events.fire|wesnoth.game_events.fire]]. In a village capture event, '''owner_side''' will contain the former owner of the village. | ||
+ | |||
+ | === 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_income''' ↔ ''integer'' | ||
+ | * '''wesnoth.game_config.village_income''' ↔ ''integer'' | ||
+ | * '''wesnoth.game_config.village_support''' ↔ ''integer'' | ||
+ | * '''wesnoth.game_config.poison_amount''' ↔ ''integer'' | ||
+ | * '''wesnoth.game_config.rest_heal_amount''' ↔ ''integer' | ||
+ | * '''wesnoth.game_config.recall_cost''' ↔ ''integer'' | ||
+ | * '''wesnoth.game_config.combat_experience''' ↔ ''integer'' | ||
+ | * '''wesnoth.game_config.kill_experience''' ↔ ''integer'' | ||
+ | |||
+ | Values of various game settings. | ||
+ | |||
+ | * '''wesnoth.game_config.global_traits'''[''trait id''] → | ||
+ | |||
+ | A table with named fields (trait id strings) holding the wml tables defining the traits. This contains all global traits the engine knows about, but race-specific traits are not included. The known fields and subtags of each element are the ones which were given in the wml definition of the [[SingleUnitWML|trait]]. | ||
+ | |||
+ | <syntaxhighlight lang=lua> | ||
+ | print(wesnoth.game_config.global_traits.strong.male_name) | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.game_config.do_healing''' ↔ ''boolean'' | ||
+ | |||
+ | Whether healing will occur at the beginning of each side's turn. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.game_config.theme''' ↔ ''theme id'' | ||
+ | |||
+ | The currently active in-game theme. | ||
+ | |||
+ | * '''wesnoth.game_config.debug''' → ''boolean'' | ||
+ | |||
+ | 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_lua''' → ''boolean'' | ||
+ | |||
+ | 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_debug''' → ''boolean'' | ||
+ | |||
+ | 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_lua''' → ''boolean'' | ||
+ | |||
+ | 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. | ||
+ | |||
+ | * {{DevFeature1.19|4}} '''wesnoth.game_config.palettes'''.''palette'' → ''list of colors'' | ||
+ | |||
+ | Returns the color palette with the given name, as defined by a '''[color_palette]''' tag in the [[GameConfigWML#Color_Palettes|game config]]. | ||
+ | |||
+ | * {{DevFeature1.19|4}} '''wesnoth.game_config.red_green_scale''' → ''list of colors'' | ||
+ | |||
+ | Returns the gradient used for health bars. | ||
+ | |||
+ | * {{DevFeature1.19|4}} '''wesnoth.game_config.red_green_scale_text''' → ''list of colors'' | ||
+ | |||
+ | Returns the gradient used for health numbers. | ||
+ | |||
+ | * {{DevFeature1.19|4}} '''wesnoth.game_config.blue_white_scale''' → ''list of colors'' | ||
+ | |||
+ | Returns the gradient used for experience bars. | ||
+ | |||
+ | * {{DevFeature1.19|4}} '''wesnoth.game_config.blue_white_scale_text''' → ''list of colors'' | ||
+ | |||
+ | Returns the gradient used for experience numbers. | ||
+ | |||
+ | === wesnoth.races === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.races'''.''id'' → ''race info'' | ||
+ | |||
+ | Access defined [[UnitsWML#.5Brace.5D|races]]. Returns a [[LuaAPI/types#Race|race userdata]]. | ||
+ | |||
+ | === wesnoth.scenario === | ||
+ | |||
+ | Contains information about the current scenario | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.turns''' ↔ ''turn limit'' | ||
+ | |||
+ | The current turn limit of the scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.next''' ↔ ''scenario id'' | ||
+ | |||
+ | The ID of the scenario to transition to when this scenario ends. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.id''' → ''scenario id'' | ||
+ | |||
+ | The ID of the current scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.name''' → | ||
+ | |||
+ | The name of the current scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.defeat_music''' ↔ ''list of music tracks'' | ||
+ | |||
+ | The music to play if you lose this scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.victory_music''' ↔ ''list of music tracks'' | ||
+ | |||
+ | The music to play if you win this scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.show_credits''' ↔ ''boolean'' | ||
+ | |||
+ | Whether credits should be shown when this scenario ends. Only relevant if '''wesnoth.scenario.next''' is nil. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.end_text''' ↔ ''text'' | ||
+ | |||
+ | The end text to show when the scenario ends. Only relevant if '''wesnoth.scenario.next''' is nil. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.end_text_duration''' ↔ ''duration'' | ||
+ | |||
+ | How long to show the end text for when the scenario ends. Only relevant if '''wesnoth.scenario.next''' is nil. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.difficulty''' → ''difficult'' | ||
+ | |||
+ | The difficulty level this scenario is being played on. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.type''' → ''tag name'' | ||
+ | |||
+ | The type of this scenario. One of the strings '''scenario''', '''multiplayer''', or '''test'''. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.era''' → ''era tag'' | ||
+ | |||
+ | The [era] tag active in this scenario. Accessing this will throw an error in single-player games. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.campaign''' → ''campaign 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. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.resources''' → ''list of resource tags'' | ||
+ | |||
+ | A list of [resource] tags active in this scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.modifications''' → ''list of modification tags'' | ||
+ | |||
+ | A list of [modification] tags active in this scenario. | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.scenario.mp_settings''' → ''table'' | ||
+ | |||
+ | 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 === | ||
+ | |||
+ | {{DevFeature1.15|12}} | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.terrain_types'''[''code''] → ''terrain info'' | ||
+ | |||
+ | Access defined [[TerrainWML|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 === | ||
+ | |||
+ | * {{LuaGameOnly}} '''wesnoth.unit_types'''[''id''] → ''unit type info'' | ||
+ | |||
+ | Access defined [[UnitTypeWML|unit types]] by their ID. Returns a [[LuaAPI/types#Unit_Type|unit type userdata]]. | ||
+ | |||
+ | == Submodules == | ||
+ | |||
+ | The <tt>wesnoth</tt> module also contains a number of submodules for working with particular aspects of the game. | ||
+ | |||
+ | === wesnoth.audio === | ||
+ | |||
+ | A [[LuaAPI/wesnoth/audio|submodule]] containing functions for playing music and sound effects. | ||
+ | |||
+ | === wesnoth.achievements === | ||
+ | |||
+ | A [[LuaAPI/wesnoth/achievements|submodule]] containing functions for working with in-game achievements. | ||
+ | |||
+ | === wesnoth.game_events === | ||
+ | |||
+ | A [[LuaAPI/wesnoth/game_events|submodule]] containing functions for working with event handlers. | ||
+ | |||
+ | === wesnoth.map === | ||
+ | |||
+ | {{DevFeature1.15|11}} | ||
+ | |||
+ | A [[LuaAPI/wesnoth/map|submodule]] containing functions for querying and manipulating the game map. | ||
=== wesnoth.interface === | === wesnoth.interface === | ||
Line 119: | Line 730: | ||
A [[LuaAPI/wesnoth/interface|submodule]] containing functions pertaining to the in-game UI. | A [[LuaAPI/wesnoth/interface|submodule]] containing functions pertaining to the in-game UI. | ||
+ | |||
+ | === wesnoth.paths === | ||
+ | |||
+ | {{DevFeature1.15|0}} | ||
+ | |||
+ | A [[LuaAPI/wesnoth/paths|submodule]] containing functions related to pathfinding. | ||
+ | |||
+ | === wesnoth.schedule === | ||
+ | |||
+ | {{DevFeature1.15|14}} | ||
+ | |||
+ | A [[LuaAPI/wesnoth/schedule|submodule]] containing functions to manipulate the time of day schedule. | ||
+ | |||
+ | === wesnoth.sides === | ||
+ | |||
+ | {{DevFeature1.15|3}} | ||
+ | |||
+ | A [[LuaAPI/wesnoth/sides|submodule]] containing functions for manipulating the sides of a scenario. | ||
+ | |||
+ | === wesnoth.sync === | ||
+ | |||
+ | {{DevFeature1.15|14}} | ||
+ | |||
+ | A [[LuaAPI/wesnoth/sync|submodule]] containing functions to deal with multiplayer synchronization. | ||
=== wesnoth.units === | === wesnoth.units === | ||
Line 127: | Line 762: | ||
[[Category: Lua Reference]] | [[Category: Lua Reference]] | ||
+ | |||
+ | == Unsupported Functions == | ||
+ | |||
+ | The following functions exist in the '''wesnoth''' module but are not intended to be used: | ||
+ | |||
+ | * wesnoth.allow_undo | ||
+ | * wesnoth.cancel_action | ||
+ | * wesnoth.clear_menu_item | ||
+ | * wesnoth.set_menu_item | ||
+ | * wesnoth.kernel_type | ||
+ | * wesnoth.log_replay | ||
+ | * wesnoth.print | ||
+ | * wesnoth.redraw | ||
+ | * wesnoth.add_known_unit | ||
+ | * wesnoth.get_era | ||
+ | * wesnoth.get_resource | ||
+ | |||
+ | Some of these have WML equivalents, so if you need the functionality you should call the WML action directly (via [[#wesnoth.wml_actions|wml_actions]] or [[LuaAPI/wml#wml.fire|wml.fire]]). Others are internal functionality used in core Lua scripts, which are not intended for general use. These functions ''may'' be removed or changed without warning or going through a deprecation cycle. | ||
+ | |||
+ | Examination of the '''wesnoth''' module will also reveal two additional subtables - the '''package''' table, which is where packages loaded by [[#wesnoth.require|wesnoth.require]] persist (meaning you can force '''wesnoth.require''' to reload a file by nulling out its entry in this table), and the '''experimental''' module, which contains functions that are available for use but without warranty - they may change without warning or going through a deprecation cycle. Use of both of these tables is unsupported. |
Latest revision as of 17:53, 21 September 2024
Contents
- 1 Functions
- 1.1 wesnoth.dofile
- 1.2 wesnoth.require
- 1.3 wesnoth.textdomain
- 1.4 wesnoth.log
- 1.5 wesnoth.as_text
- 1.6 wesnoth.simulate_combat
- 1.7 wesnoth.name_generator
- 1.8 wesnoth.compile_formula
- 1.9 wesnoth.eval_formula
- 1.10 wesnoth.version
- 1.11 wesnoth.current_version
- 1.12 wesnoth.ms_since_init
- 1.13 wesnoth.deprecated_message
- 1.14 wesnoth.deprecate_api
- 1.15 wesnoth.type
- 1.16 wesnoth.named_tuple
- 1.17 wesnoth.get_language
- 1.18 wesnoth.print_attributes
- 2 Hooks
- 3 Data
- 4 Submodules
- 5 Unsupported Functions
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.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. This plural syntax returns a form of the string that's grammatically suitable for the indicated number, but doesn't actually substitute the number in – you need to do that yourself with either string.format or stringx.vformat.
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.log
- wesnoth.log([logger], message, in_chat)
Logs a message to the console. These messages are normally not visible unless Wesnoth is run from the command-line or (in Windows) with the --wconsole switch. The in_chat argument, however, can be set to true to also echo the message to the in-game chat area.
logger is the log level.
In any context, logger can be the standard log levels of info, debug, warning, or error. Various abbreviations of the standard four are also recognised. The default logger is info.
In the game context, you can also set the logger to wml. The wml log level is special and is intended for WML errors; it always goes to chat, so the in_chat argument is ignored and can be omitted.
The logdomain to enable these logs depends on the context. In the game context, they are written to the wml logdomain. In other contexts, the logdomain is scripting/lua/user.
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.
(Version 1.17.0 and later only) This is now available in all contexts.
wesnoth.simulate_combat
- ♟ wesnoth.simulate_combat(attacker, [attacker_weapon_index], defender, [defender_weapon_index]) → attacker stats evaluation, defender stats evaluation, attacker weapon evaluation, defender weapon evaluation
Computes the hitpoint distribution and status chance after a combat between two units. The first unit is the attacker. The attacker does not have to be on the map, but its location should be meaningful - that is, it can be a private-to-Lua clone of a unit with the x and y values changed, but whatever it is it has to have x and y values that allow attacking the defender (with max_range of the attack set appropriately it's possible to simulate attacking non-adjacent units). The second unit is the defender; it has to be on the map.
Optional integers can be passed after each unit to select a particular weapon, otherwise the "best" one is selected. When giving the weapon, the parameter is the weapon number (integer, starting at 1) and not the attack definition.
The function returns four tables describing the evaluation of the combat. The first two contain an evaluation of the combatant's stats over the course of the fight, while the second two contains more detailed information on their weapons.
The stats evaluation tables contain the following keys:
- stats.poisoned → probability
- stats.slowed → probability
- stats.untouched → probability
The probability that the unit will be poisoned or slowed, or that it will survive with no damage taken. (A scenario where the unit's hitpoints increase counts as untouched.)
- stats.average_hp → number
The expected value of the unit's hitpoints after the fight.
- stats.hp_chance → mapping of hp to probability
The probability that the unit's hitpoints will be at a specific value after the fight. Though it looks almost like an array, it begins at index 0 unlike a typical Lua array. Thus, it's better understood as an associated mapping from the resulting hitpoints value to the probability of ending the combat with that value. Therefore, the value at index 0 represents the chance that the unit will die.
The weapon evaluation tables contain the following keys:
num_blows, damage, chance_to_hit, poisons, slows, petrifies, plagues, plague_type, backstabs, rounds, firststrike, drains, drain_constant, drain_percent, attack_num, name
local function display_stats(n, t)
wesnoth.interface.add_chat_message(string.format(
"Chance for the %s\n to be slowed: %f,\n to be poisoned: %f,\n to die: %f.\nAverage HP: %f.",
n, t.slowed, t.poisoned, t.hp_chance[0], t.average_hp))
end
local att_stats, def_stats = wesnoth.simulate_combat(att, att_weapon, def, def_weapon)
display_stats("attacker", att_stats)
display_stats("defender", def_stats)
local att_stats, def_stats, att_weapon, def_weapon = wesnoth.simulate_combat(attacker, att_weapon_number, defender)
wesnoth.interface.add_chat_message(string.format(
"The attack %s should be countered with %s, which does %d damage, has %d%% chance to hit and forces %d attack rounds due to its berserk ability.",
att_weapon.name, def_weapon.name or "no weapon", def_weapon.damage, def_weapon.chance_to_hit, def_weapon.rounds))
wesnoth.name_generator
- wesnoth.name_generator("markov", definition, [chain_size, [max_length]]) → generator function
- wesnoth.name_generator("cfg", definition) → generator function
- generator function() → random name
Constructs a name generator for use in generating names using either the Markov chain algorithm used in older versions of Wesnoth or the context-free grammar generator used since 1.13.5. The type parameter indicates which algorithm to use (either markov or cfg). The definition can be a string, just like it would be in a config file, or it can be formatted as a table. Additional parameters may be passed, depending on the type of generator. The function returns a callable userdata, which will return a new name each time it is called (with no parameters).
- Markov chain: A Markov chain generator works by analyzing a list of input names and noticing tendencies in the way the letters are strung together. It can then apply those tendencies to produce new similar names that were not in the original list. Longer lists give better results. The definition is a list of names, formatted either as a comma-separated string or as an array-like table. The Markov generator can take two additional parameters.
- chain_size: A value greater than 1 for the chain_size causes the analyzer to consider the words in chunks, which is similar to analyzing them syllable by syllable instead of letter by letter. The default chain size is 2, meaning that the analyzer treats words as consisting of 2-character syllables.
- max_length: Places a cap on the total length of the name. The default value is 12 characters.
local markov_names = wesnoth.name_generator('markov', {'Kaasa', 'Kayya', 'Keyya', 'Kiira', 'Korra'}, 1)
print(markov_names(), markov_names(), markov_names())
- Context-free grammar: A context-free grammar is a way of specifying how strings can be constructed. The definition may be specified as a multi-line string, just as described in the preceding link, or it can be formatted as a table where the keys are non-terminals and the values are what they expand to. The expansion of each non-terminal can be formatted either as a |-separated list as described in the preceding link, or as an array-like table. (Mixing the two forms is permissible too.) The context-free generator has no additional parameters.
local cfg_names = wesnoth.name_generator('cfg', {
main = {'{prefix}{suffix}', '{prefix}{centre}{suffix}'},
prefix = 'Kaa|Ka|Ke|Kuu|Ko',
suffix = 'sa|yya|ra|rra',
centre = 'err|aash|eez|azz'
})
print(cfg_names(), cfg_names(), cfg_names())
Note: If you want to generate a name using any of the default generators, you can use the predefined generators in the race instead of constructing one with this function.
wesnoth.compile_formula
- wesnoth.compile_formula(formula) → compiled formula
Compiles a Wesnoth Formula Language formula into a Lua callable userdata. A compiled formula can be converted back to valid code using the built-in tostring
function.
wesnoth.eval_formula
- wesnoth.eval_formula(formula, [variables]) → result
- compiled formula([variables]) → result
Evaluate a Wesnoth Formula Language formula and return the result it computed (which can be nil).
The passed in variables can be an arbitrary Lua table, which defines variables available to the formula. Unlike with WML tables, there is no restriction on the format of this table. The formula can access the variables as a list using the special WFL variable __list, or as a map using the special WFL variable __map. Directly accessing keys on the table is also possible.
It is also possible to pass a unit proxy as the variables, which evaluates the formula in that unit's context just as if it had been used in a StandardUnitFilter.
When calling wesnoth.eval_formula, the first argument may either be an already-compiled formula or a string, in which case it will be automatically compiled on the fly.
local f = wesnoth.compile_formula('if(x > y, x - y, x + y)')
print(f{x=1,y=2}) -- prints 3.0
print(f{x=1,y=3}) -- prints 4.0
print(f{x=2,y=3}) -- prints 5.0
print(f{x=1,y=1}) -- prints 2.0
print(f{x=3,y=1}) -- prints 2.0
print(f{x=3,y=2}) -- prints 1.0
wesnoth.version
- wesnoth.version(version string) → version
- wesnoth.version(major, [minor, [patch]], [suffix)) → version
Creates a version object, either by parsing a string or by building it from its component parts. The resulting version object can be compared with other version objects using the standard Lua comparison operators, which follows the same rules as the #ifver preprocessor statement. It can also be decomposed by accessing the following keys on the object:
- integer: Grab any integer version component by index. A non-canonical version may have more than three components.
- major: The major version number (index 1).
- minor: The minor version number (index 2).
- revision: The patch revision number (index 3).
- is_canonical: True if the version has at most three components (plus an optional suffix).
- sep: The character that separates the version components from the suffix (usually either + or nil).
- special: The version suffix, for example the "dev" in "1.15.14+dev".
The version can be converted to a string using the built-in tostring function.
local function version_is_sufficient(required)
return wesnoth.current_version() >= required
end
local required = wesnoth.version "1.9.6"
if not version_is_sufficient(required) then
gui.alert(string.format("Your BfW version is insufficient, please get BfW %s or greater!", tostring(required)))
end
wesnoth.current_version
- wesnoth.current_version() → current version
Returns the current version of Wesnoth as a version object.
wesnoth.ms_since_init
- wesnoth.ms_since_init() → milliseconds
This function returns the amount of milliseconds that have passed since Wesnoth started up the current session. Its only use is to track the passage of real time.
WARNING: this function uses the same code as [set_variable] time=stamp, and so it is MP-unsafe. It is provided only for benchmark purposes and AI development, although it should work inside wesnoth.synchronize_choice() as well.
wesnoth.deprecated_message
- wesnoth.deprecated_message(element_name, level, version, detail_message)
Displays a deprecation warning in the Lua console. The level is an integer from 1 to 4 inclusive (see deprecation levels), and the version can be left nil for levels 1 and 4. Otherwise it must be a version string (not a version object from wesnoth.version).
wesnoth.deprecate_api
- wesnoth.deprecate_api(original_name, new_name, level, version, element, detail_message) → deprecated wrapper
Creates a deprecated wrapper for a function or table. A deprecated function will raise the deprecated message the first time it's called, and then suppress it thereafter. A deprecated table will raise the deprecated message the first time a key is read or assigned, and then suppress it thereafter.
The element is the function or table to wrap. It can be the original function or the new function (which may happen if the function was renamed without any interface changes), or a wrapper function that calls the new function while providing the interface of the old function. The level and version are as in wesnoth.deprecated_message.
If level is 4, then the element is ignored (you can pass nil) and a generic deprecated wrapper is returned that does nothing but raises the deprecated message the first time you call it, assign a key, or read a key, and suppresses it thereafter. This is intended for a function that was removed without deprecation, to leave behind a more informative message if someone still attempts to use it.
If Wesnoth is run with the --strict-lua command-line option, this function will return nil instead of the deprecated wrapper. Since the normal use-case of this function is to assign the deprecated wrapper to the original name, this has the effect of erasing any deprecated functions from the API.
The result of this function always contains a __deprecated attribute set to true, which can allow identifying if something is deprecated.
wesnoth.type
(Version 1.17.? and later only)
- wesnoth.type(value) → type name
Returns a string describing the value's type. This is the same as the built-in type function, except that it returns a more specific string in the case of userdata or tables, based on the metatable. For example, it would return 'unit' if called on a unit.
wesnoth.named_tuple
(Version 1.17.? and later only)
- wesnoth.named_tuple(array, names) → named tuple
Decorates a numeric based array so that the indices can be accessed by name instead of by index. This function is used internally for a number of things, most notably map locations and WML tags. Most end-users will not need to use it, but it could be useful if you wish to build a Lua API that returns locations (or similar data) in the engine-standard format.
For example:
local t = wesnoth.named_tuple({42,21,36}, {'x', 'y', 'z'})
print(t[1]) -- prints 42
print(t[2]) -- prints 21
print(t[3]) -- prints 36
print(t.x) -- prints 42
print(t.y) -- prints 21
print(t.z) -- prints 36
wesnoth.get_language
- wesnoth.get_language() → string
Gets the language the UI is currently set to. Note that this may return an empty string if using the system default language.
wesnoth.print_attributes
- wesnoth.print_attributes(object, [function])
Prints out a list of attributes that can be accessed on the object, excluding deprecated functionality. The function defaults to print, and receives a formatted line usually containing multiple attributes. They are annotated by type – ƒ for a function, † for a table, ! if there was an error attempting to determine the type (which includes write-only attributes). Other types are unannotated.
For tables, by default this iterates the table using pairs to discover the attributes available, walking the metatable hierarchy if there is an __index table and filtering out anything that contains a __deprecated attribute set to true. However, if finds a function as the __index, and the table's metatable also has a member __dir, it will be used instead. The __dir can either be an array of strings, or a function that returns an array of strings. It will automatically be sorted and have any duplicates filtered out.
For custom objects defined by the engine, there is special handling so that this function shows the correct result. For example, if used on a GUI2 widget object, it will show the attributes available for that type of widget, as well as the IDs of any sub-widgets that can be accessed by name.
In the Lua console only, this function can also be referenced by a shorter alias, dir.
Hooks
wesnoth.persistent_tags
- ♟ wesnoth.persistent_tags.action.read ↔ function(wml content)
- ♟ wesnoth.persistent_tags.action.write ↔ function(add_tag_function)
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 to 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
- ♟ wesnoth.wml_actions.action ↔ function(wml parameters table)
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
- ♟ wesnoth.wml_conditionals.action ↔ function(wml parameters table) → boolean result
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.
wesnoth.effects
- ♟ wesnoth.effects.name ↔ function(unit, wml table)
- ♟ wesnoth.effects.name.__descr ↔ description
- ♟ wesnoth.effects.name.__descr ↔ function(unit, wml table) → description
This table contains the implementation of [effect]s. Each value is a callable value that takes a unit and the effect config. It can be a function or a callable table. If it is a callable table, its metatable may have a __descr field which is either a string or a function. Built-in effects are present in this table, and you may register your own custom effects too.
function wesnoth.effects.min_resistance(u, cfg)
local resistance_new = {}
local resistance_old = wml.parsed(wml.get_child(cfg, "resistance"))
for k,v in pairs(resistance_old) do
if type(k) == "string" and type(v) == "number" and u:resistance_to(k) >= v then
resistance_new[k] = v
end
end
wesnoth.effects.resistance(u, {
apply_to = "resistance",
replace = true,
T.resistance (resistance_new),
})
end
The code above adds a new min_resistance
effect that will set the resistances to specific values if they are currently below that value. It can then be used like this (for example, in [object]):
[effect]
apply_to=min_resistance
[resistance]
cold=50
[/resistance]
[/effect]
Note that in order work properly, effects must be registered before any units are created. This means it must be placed into a global or scenario level [lua] tag. In particular, the preload event is too late.
You can also specify description modifiers, which will be used if a custom effect is placed in a [trait]
tag. Instead of setting a function as the effect, you set a table with a __call
metafunction which does what the function would have done. The table can then have an additional __descr
metafunction which updates descriptions as necessary. The built-in effects all use this structure. This metafunction takes the same arguments as the regular effect function, but should not modify the unit. Instead, it returns a string to be appended to the trait's effect description.
wesnoth.micro_ais
- ♟ wesnoth.micro_ais.ai_name ↔ function(cfg) → required, optional, ca_params
Registers a new MicroAI with ai_type=ai_name. The function will be called by the [micro_ai] tag to set up the AI. See the link for more details on how this works.
wesnoth.custom_synced_commands
- ♟ wesnoth.custom_synced_commands.command_name ↔ function(cfg)
Registers a custom synced command, which can be invoked by AI to enable unusual behaviour. The command can do basically anything, and is guaranteed to run on all clients. The WML table passed to the callback is the same table passed to wesnoth.sync.invoke_command.
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_name → color 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.side → side number
The number of the currently active side.
- ♟ wesnoth.current.turn → turn number
The current turn number.
- ♟ wesnoth.current.synced_state → state
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.current.user_can_invoke_commands → boolean
Indicates whether the player is currently able to take actions in the game.
- ♟ wesnoth.current.map → map userdata
The current active game map. See LuaAPI/types/map and LuaAPI/wesnoth/map for information on how this data can be used.
- ♟ wesnoth.current.schedule → schedule userdata
The current global time schedule. This is a special object with the following properties:
- #schedule
- The Lua length operator will return the number of turns in the schedule.
- schedule[index] ↔ time of day info
- Get the information for a particular time of day, or replace it with new info.
- schedule.time_of_day ↔ id
- Get the ID of the current active time of day, or switch to a new one. If the time of day occurs more than once in the schedule, the time will be set to the first occurrence.
- schedule.liminal_bonus ↔ bonus
- Get the maximum bonus for liminal units in the current schedule. You can also override the default by assigning a different value, or revert to the default by assigning nil.
- ♟ wesnoth.current.event_context → WML table
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 to the event, if any. This is the same as x1, y1 in most cases. Currently the only exceptions are enter and exit hex events.
- data - (Version 1.17.6 and later only) The event data. Can contain anything at all if the event was fired by wesnoth.game_events.fire. In a village capture event, owner_side will contain the former owner of the village.
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_income ↔ integer
- wesnoth.game_config.village_income ↔ integer
- wesnoth.game_config.village_support ↔ integer
- wesnoth.game_config.poison_amount ↔ integer
- wesnoth.game_config.rest_heal_amount ↔ integer'
- wesnoth.game_config.recall_cost ↔ integer
- wesnoth.game_config.combat_experience ↔ integer
- wesnoth.game_config.kill_experience ↔ integer
Values of various game settings.
- wesnoth.game_config.global_traits[trait id] →
A table with named fields (trait id strings) holding the wml tables defining the traits. This contains all global traits the engine knows about, but race-specific traits are not included. The known fields and subtags of each element are the ones which were given in the wml definition of the trait.
print(wesnoth.game_config.global_traits.strong.male_name)
- ♟ wesnoth.game_config.do_healing ↔ boolean
Whether healing will occur at the beginning of each side's turn.
- ♟ wesnoth.game_config.theme ↔ theme id
The currently active in-game theme.
- wesnoth.game_config.debug → boolean
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_lua → boolean
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_debug → boolean
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_lua → boolean
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.
- (Version 1.19.4 and later only) wesnoth.game_config.palettes.palette → list of colors
Returns the color palette with the given name, as defined by a [color_palette] tag in the game config.
- (Version 1.19.4 and later only) wesnoth.game_config.red_green_scale → list of colors
Returns the gradient used for health bars.
- (Version 1.19.4 and later only) wesnoth.game_config.red_green_scale_text → list of colors
Returns the gradient used for health numbers.
- (Version 1.19.4 and later only) wesnoth.game_config.blue_white_scale → list of colors
Returns the gradient used for experience bars.
- (Version 1.19.4 and later only) wesnoth.game_config.blue_white_scale_text → list of colors
Returns the gradient used for experience numbers.
wesnoth.races
- ♟ wesnoth.races.id → race info
Access defined races. Returns a race userdata.
wesnoth.scenario
Contains information about the current scenario
- ♟ wesnoth.scenario.turns ↔ turn limit
The current turn limit of the scenario.
- ♟ wesnoth.scenario.next ↔ scenario id
The ID of the scenario to transition to when this scenario ends.
- ♟ wesnoth.scenario.id → scenario id
The ID of the current scenario.
- ♟ wesnoth.scenario.name →
The name of the current scenario.
- ♟ wesnoth.scenario.defeat_music ↔ list of music tracks
The music to play if you lose this scenario.
- ♟ wesnoth.scenario.victory_music ↔ list 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_text ↔ text
The end text to show when the scenario ends. Only relevant if wesnoth.scenario.next is nil.
- ♟ wesnoth.scenario.end_text_duration ↔ duration
How long to show the end text for when the scenario ends. Only relevant if wesnoth.scenario.next is nil.
- ♟ wesnoth.scenario.difficulty → difficult
The difficulty level this scenario is being played on.
- ♟ wesnoth.scenario.type → tag name
The type of this scenario. One of the strings scenario, multiplayer, or test.
- ♟ wesnoth.scenario.era → era tag
The [era] tag active in this scenario. Accessing this will throw an error in single-player games.
- ♟ wesnoth.scenario.campaign → campaign 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.resources → list of resource tags
A list of [resource] tags active in this scenario.
- ♟ wesnoth.scenario.modifications → list of modification tags
A list of [modification] tags active in this scenario.
- ♟ wesnoth.scenario.mp_settings → table
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.audio
A submodule containing functions for playing music and sound effects.
wesnoth.achievements
A submodule containing functions for working with in-game achievements.
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.paths
(Version 1.15.0 and later only)
A submodule containing functions related to pathfinding.
wesnoth.schedule
(Version 1.15.14 and later only)
A submodule containing functions to manipulate the time of day schedule.
wesnoth.sides
(Version 1.15.3 and later only)
A submodule containing functions for manipulating the sides of a scenario.
wesnoth.sync
(Version 1.15.14 and later only)
A submodule containing functions to deal with multiplayer synchronization.
wesnoth.units
(Version 1.15.0 and later only)
A submodule containing functions to manipulate units on the map.
Unsupported Functions
The following functions exist in the wesnoth module but are not intended to be used:
- wesnoth.allow_undo
- wesnoth.cancel_action
- wesnoth.clear_menu_item
- wesnoth.set_menu_item
- wesnoth.kernel_type
- wesnoth.log_replay
- wesnoth.print
- wesnoth.redraw
- wesnoth.add_known_unit
- wesnoth.get_era
- wesnoth.get_resource
Some of these have WML equivalents, so if you need the functionality you should call the WML action directly (via wml_actions or wml.fire). Others are internal functionality used in core Lua scripts, which are not intended for general use. These functions may be removed or changed without warning or going through a deprecation cycle.
Examination of the wesnoth module will also reveal two additional subtables - the package table, which is where packages loaded by wesnoth.require persist (meaning you can force wesnoth.require to reload a file by nulling out its entry in this table), and the experimental module, which contains functions that are available for use but without warranty - they may change without warning or going through a deprecation cycle. Use of both of these tables is unsupported.