Lua Language

Lua is an interpreted language that is used for scripting in Total War. It's lightweight, fast, and easy to use.

Lua instructions are written in a text file, which is generally given a .lua file extension. The game looks to load certain script files when loading, and may be configured to load specific scripts when loading a particular campaign or battle.

Version 5.1 of lua is used in Total War scripting - the latest at time of writing is version 5.3.5.

Whitespace in lua is ignored, so scripts can be spaced out according to the scripters preference. Lua statements may optionally be terminated with a semicolon. Individual lines may be commented with -- - this causes the rest of the line to be ignored. Blocks of script of any size may be commented with --[[ script ]]. These blocks may not be nested, however.

Lua is case-sensitive, so variables named value, Value and VALUE are all different. This is a common source of bugs.

Example:

-- this line is commented
--[[
this line is also commented
]]
value = 6
print(value);        -- semicolon optional
print(Value)
6
nil
Relevant in Campaign Loaded in Campaign
Relevant in Battle Loaded in Battle
Relevant in Frontend Loaded in Frontend
Back to top

More Information

More information about lua can be found on the following sites:

https://www.lua.orgLua homepage.
https://www.lua.org/demo.htmlLua demo site - allows snippets of script to be tested outside of the game (very useful).
https://www.lua.org/manual/5.1/The lua manual.
http://lua-users.org/wiki/Lua wiki - contains useful information about supplied libraries.
https://www.tutorialspoint.com/lua/Lua tutorial - others are available.

Back to top

Lua Data Types

Lua supports only eight data types, six of which are documented further down this page:

Data TypeDescription
nilThe absence of a value.
booleantrue/false values.
numberFloating-point numeric values.
stringText values.
functionExecutable chunks of script.
tableDynamically-sized key/value lists, may be used to build complex data structures.
userdataObjects provided by the host program to lua, with an interface on which script may make function calls.
threadRepresents independent threads of execution - not supported in Total War scripting.

Back to top

Local and Global Variables

Variables created in lua are global by default, which means they are accessible across the entire scope of the script. Variables can optionally be declared with local scope, whereby they only persist for the lifetime of the block in which they are declared. It is strongly encouraged to declare variables with local scope unless there is a compelling reason to do otherwise, as it lessens the risk of them being accessed or overwritten by accident.

Example:

-- global and local variable declarations
g_var_one = 10
local l_var_one = 20

-- declarations within a block
if g_var_one then
    g_var_two = 20
    local l_var_two = 30    -- will fall out of scope as the block ends
end

print("g_var_one: " .. tostring(g_var_one))
print("l_var_one: " .. tostring(l_var_one))
print("g_var_two: " .. tostring(g_var_two))
print("l_var_two: " .. tostring(l_var_two))
g_var_one: 10
l_var_one: 20
g_var_two: 20
l_var_two: nil
Back to top

if statements

An if statement may be used to perform a logical test and, based on the boolean result of that test, execute different blocks of instruction. An if statement will execute a block of script specified by a mandatory then operator if the logical test evaluates to true, or a second optional block specified by an else operator if it doesn't. Each if statement must be terminated by the keyword end.

An else operator following another if statement may be combined into an elseif operator. Converting nested if statements to elseif operators in this way saves on having to terminate each if statement with end - see the example below.

Example:

t = true
f = false

if t == true then
    print("t is true")
end

if f == true then
    print("f is true")
else
    print("f is false")
end

n = 28

if n < 5 then
    print("n is less than 5")
elseif n < 10 then
    print("n is less than 10")
elseif n < 15 then
    print("n is less than 15")
elseif n < 20 then
    print("n is less than 20")
else
    print("n is greater than or equal to 20")
end
t is true
f is false
n is greater than or equal to 20
Back to top

Conditional Operators

Conditional tests may be performed by structures such as if statements, while loops and repeat loops to make decisions about what scripts to execute. Any values can be evaluated in a conditional test - non-boolean values may be evaluated in a boolean manner as follows:

  • false boolean values, and nil values, evaluate to false.
  • Any other value evaluates to true (including the number 0, which evaluates to false in C).

The logical operator not may be used to negate the result of a boolean - if passed a true value it returns false, and if passed a false value it returns true. The value returned by the not operator is always boolean, even if the value supplied was not. The statement x = not not x converts x to a boolean value, therefore.

The logical operators and and or may be used to assess multiple boolean conditions together. The and operator returns true if both of the expressions passed to it evaluate to true themselves. The or operator returns the second value passed to it if the first evaluates to false, otherwise the first value is returned. Unlike and, not and other comparison operators, therefore, or can return something other than a boolean value. This can be useful for setting default values for a variable - see the example below.

The lua interpreter reads forward when performing conditional tests, and will not evaluate expressions that it doesn't need to. For example, if the first expression passed to an and operator evaluates to false then the second is never evaluated. Likewise, if the first expression passed to an or operator evaluates to true then the second expression is never evaluated (and the first is returned). These constructs can both be useful in different ways - see the examples below.

The not operator has precedence (meaning it gets evaluated first), followed by the and operator and finally the or operator. Parenthesis () can be used to override the natural order of precedence.

Example - Relying on conversion to boolean to test existence of value:

num_value = 10

-- A number of any value evaluates to true.
-- This is akin to saying "if num_value has been set.."
if num_value then
    print("num_value evaluates to true")
end
num_value evaluates to true

Example - Using 'not' to convert to boolean:

num_value = 10

print("not num_value: " .. not num_value)
print("not not num_value: " .. not not num_value)
not num_value: false
not not num_value: true

Example - and/or operator examples:

t = true
f = false

if t and f then
    print("this should never get printed")
end

if t and not f then            -- "not f" evaluates to true
    print("this should get printed")
end

if t or f then
    print("either t or f is true")
end
this should get printed
either t or f is true

Example - Compound logical test of greater length, with parenthesis:

t = true
f = false

if not (t and (not f or not t)) then
    print("???")
else
    print("wha?")
end
wha?

Example - Using 'or' to set a default value during an assignment operation:

function returns_nothing()
    -- do nothing
end

-- returns_nothing() evaluates to nil/false,
-- so 'or' will return the second value here
value = returns_nothing() or 1
print("value is " .. tostring(value))
value is 1

Example - Using 'and' to test existence or type before value of variable, to prevent errors :

This example shows how the 'and' operator can be used in a serial to guard operations on values that might otherwise fail and cause script errors. Performing a numeric comparison such as > on a non-numeric value is illegal and would cause a script failure. This is prevented by the first expression which tests whether value is a number. If value is not a number, and the type check returns false, lua will not proceed on to evaluate the second expression (containing the numeric comparison) as the interpreter is smart enough to realise that it can't affect the final result.
function test_value(value)
    if type(value) == "number" and value > 10 then
        print("value " .. tostring(value) .. " is a number > 10")
    else
        print("value " .. tostring(value) .. " is not a number or a number <= 10")
    end
end

test_value(20)
test_value("hello")
test_value(false)
value 20 is a number > 10
value hello is not a number or a number <= 10
value false is not a number or a number <= 10
Back to top

Standard Functions

Lua provides a number of standard functions for various puposes, some of which are documented below.

print(... values to print)

Prints one or more supplied values to the standard output. In Total War games, the standard output is the game console, and optionally also a text file. Non-string values passed to the function are cast to string before printing.

Parameters:

1

...

values to print

Returns:

  1. nil

Example:

print("hello")        -- string
print(5, 3)        -- two numbers
print({})            -- a table
hello
5    3
table: 0xb805do

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 192

type(variable variable)

Returns the type of a specified value as a string.

Parameters:

1

variable

variable

Returns:

  1. string type

Example:

print(type(not_defined))
print(type("hello"))
print(type(5))
print(type({}))
nil
string
number
table

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 203

tostring(variable variable)

Returns the specified value cast to a string. The specified value is unaffected.

Parameters:

1

variable

variable

Returns:

  1. string variable cast to string

Example:

value = 6
value_as_string = tostring(value)
print(value, type(value))
print(value_as_string, type(value_as_string))
6    number
6    string

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 217

tonumber(variable variable)

Returns the specified string value cast to a number. This only works for string values that contain numeric characters (e.g. "65"). If the supplied value is a string that does not contain numeric characters, or is any other value other than a number then nil is returned.

Parameters:

1

variable

variable

Returns:

  1. number variable cast to number

Example:

numeric_str_value = "26"
non_numeric_str_value = "hello"
number_value = 18
boolean_value = true
table_value = {}
print(tonumber(numeric_str_value), tonumber(non_numeric_str_value), tonumber(number_value), tonumber(boolean_value), tonumber(table_value))
26    nil    18    nil    nil

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 229

loadstring(string lua string)

Returns an executable function created from a string. This string may be constructed manually, or generated by another function such as string.dump. When the returned function is executed the lua script contained within the specified string is run.
Use this function sparingly. See external documentation for more information.

Parameters:

1

string

lua string

Returns:

  1. function lua function

Example:

function test_func()
    print("hello");
end;

local str_a = string.dump(test_func);
local str_b = "print(\"123\")";

func_a = loadstring(str_a);
func_b = loadstring(str_b);

func_a()
func_b()
hello
123

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 242


Nil

The data type nil represents the absence of a value in lua. nil is both the name of the type and also the only value that a variable of that type can take. All variables contain the value nil, and are of type nil, before they are declared. Assigning nil to a variable is the same as deleting it.

nil values resolve to false when considered in a logical expression.

Example:

print("no_value has a value of " .. tostring(no_value) .. " and is of type " .. type(no_value))

some_value = 6
some_value = nil     -- deleting
if not some_value then
    print("some_value is false or nil")
end
no_value has a value of nil and is of type nil
some_value is false or nil

Booleans

Boolean values may be either true or false. Boolean values are of most use when evaluated by language structures such as if statements and while loops that perform logical tests and take action based on the result. The logical operators and, or and not can be used to evaluate booleans.

See the section on Conditional Operators for more information.

Example:

t = true

-- must use tostring as the .. concatenation operator wont work with booleans
print("t is " .. tostring(t) .. " and of type " .. type(t))

f = 6 > 7        -- logical expression evaluates to false

print("f is " .. tostring(f))
print("not f is " .. tostring(not f))
print("f and t is " .. tostring(f or t))
if f or t then
    print("f or t must be true!")
end
t is true and of type boolean
f is false
not f is true
f and t is true
f or t must be true!

Numbers

Numeric values in lua are real, so they may contain decimal places. There is no integer numeric type. The default lua language specification sets numbers to be stored as double-precision floats. At time of writing, however, numbers in Total War's implementation of lua are stored as single-precision floats, which offer only about 7 digits of precision. Scripters should be aware of this limitation when planning scripts that may potentially have to deal with very large or precise numbers.

Number values can be added, subtracted, multiplied and divided with the +, -, * and / operators respectively. Exponents may be expressed with the ^ operator.

Example:

a = 5
b = a + 10
c = b * 2
d = c / 10
e = a ^ d
print(a, b, c, d, e)
5    15    30    3.0    125.0

Strings

Strings are variables containing representations of text. A string may be specified by enclosing a value in matching single or double quotes. A string can be zero, one or more characters long, with no upper limit beyond the amount of memory available.

Strings may be joined together using the concatenation operator, ...

Example:

str_a = "hello"
str_b = "world"
print(str_a .. " " .. str_b)
hello world
Back to top

String Patterns

Some of the string functions described in the next section make use of string patterns, a method of matching sequences of characters akin to regular expressions. More information about lua string patterns may be found on lua-users.org here.

Back to top

String Library

Lua provides a number of operations that can be performed on strings, listed below. More detailed information about these functions may be found on the dedicated page on lua-users.org here.

The functions may be called in the form string.<function>(<string>, <arguments>), or <string>:<function>(<arguments>) where appropriate.

string.byte([number first char], [number last char])

Returns the numerical code corresponding to the characters of a specified portion of the string. The portion of the string is specified by index positions of the start and end characters.

Parameters:

1

number

optional, default value=1

Position of first character in the substring. If this is not a valid character index for this string then nil is returned.

2

number

optional, default value=1

Position of last character in the substring. If the first character position is specified and this is not, then this is set to the value of the first character position (so that only one character is returned).

Returns:

  1. ... number character value(s)

Example:

print(string.byte("hello"))        -- prints first character by default
print(string.byte("hello", 4))        -- print single character
print(string.byte("hello", 1, 3))    -- prints range of characters
104
108
104    101    108

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 425

string.byte_compare(string first string to compare., string second string to compare.)

Compares two strings lexicographically byte by byte and returns the difference in the first byte that differs between the two, or zero if the two are equal. Hence a negative value if the first string precedes the second, a positive value if the second string precedes the first and zero if the two strings are equal.
This can be used to compare unicode strings encoded in UTF-8, as UTF-8 is designed in a way that allows for this. See https://en.wikipedia.org/wiki/UTF-8 section "Comparison with other encodings", subsection "Sorting order".

Parameters:

1

string

first string to compare.

2

string

second string to compare.

Returns:

  1. number comparison result

Example:

print(string.byte_compare("string2", "string1"))
1

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 438

string.byte_greater_than(string first string to compare., string second string to compare.)

Compares two strings lexicographically byte by byte and returns whether the second string precedes the first.
This can be used to compare unicode strings encoded in UTF-8, as UTF-8 is designed in a way that allows for this. See https://en.wikipedia.org/wiki/UTF-8 section "Comparison with other encodings", subsection "Sorting order".

Parameters:

1

string

first string to compare.

2

string

second string to compare.

Returns:

  1. boolean second string precedes first string

Example:

print(string.byte_greater_than("string2", "string1"))
true

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 467

string.byte_less_than(string first string to compare., string second string to compare.)

Compares two strings lexicographically byte by byte and returns whether the first string precedes the second.
This can be used to compare unicode strings encoded in UTF-8, as UTF-8 is designed in a way that allows for this. See https://en.wikipedia.org/wiki/UTF-8 section "Comparison with other encodings", subsection "Sorting order".

Parameters:

1

string

first string to compare.

2

string

second string to compare.

Returns:

  1. boolean first string precedes second string

Example:

print(string.byte_less_than("string2", "string1"))
false

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 480

string.char(... character values)

Returns a string constructed from the specified numeric character values. Number character values can be obtained with string.byte.

Parameters:

1

...

Vararg of number character values.

Returns:

  1. nil

Example:

print(string.char(104, 101, 108, 108, 111))
hello

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 493

string.dump(function function)

Returns a string representation of a supplied function, which can later be passed to the loadstring function to be reconstituted as an executable function.

Parameters:

1

function

function

Returns:

  1. string string representation

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 500

string.ends_with(string subject string, string substring)

Returns true if the subject string ends with the supplied substring, or false othewise.

Parameters:

1

string

subject string

2

string

substring

Returns:

  1. nil

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 506

string.find(string string, string substring, [number start index], [boolean disable pattern matching])

Returns the position of the first occurrence of a supplied substring within the subject string. If the supplied substring is found within the subject string then the start and end character positions of the substring are returned. nil is returned if the substring is not found.
This is a modified version of the original lua language implementation of find, which does not support utf8 strings but which does support pattern matching. See the lua wiki for more information about lua patterns. See also string.find_utf8 for an implementation that supports utf8 strings, but does not support pattern matching.
However, please note: in our library implementation, pattern-matching is disabled by default. Supply false as the fourth boolean argument to turn it on. Alternatively, use string.find_lua instead - this is the default string.find provided by the lua language.

Parameters:

1

string

Subject string.

2

string

String pattern to search for.

3

number

optional, default value=1

Position of character at which to start the search. Supply a negative number to specify a character from the end of the string, counting back.

4

boolean

optional, default value=true

Disables pattern matching if set to true. Unlike the default lua library implementation, this is true by default. Supply false here to enable pattern matching.

Returns:

  1. number first character index
  2. number last character index

Example:

local str = "This is a test string"
print(string.find(str, "is"));
3    4

Example - Example using pattern matching:

local str = "This is a test string"
print(string.find(str, "%s", nil, false));            -- find first space
5    5

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 515

string.find_lua(string string, string substring, [number start index], [boolean disable pattern matching])

Direct exposure of the lua-provided string.find function, which returns the position of the first occurrence of a supplied substring within the subject string. If the supplied substring is found within the subject string then the start and end character positions of the substring are returned. nil is returned if the substring is not found.
This is the original lua language implementation of find, unaltered. This function does not support utf8 strings, but does support pattern matching, and unlike our implementation of string.find pattern-matching is turned on by default. See the lua wiki for more information about lua patterns.
This function directly exposes the lua-language implementation of string.find. It's provided mainly for performance, as calling string.find goes through a wrapper redirect function.

Parameters:

1

string

Subject string.

2

string

String pattern to search for.

3

number

optional, default value=1

Position of character at which to start the search. Supply a negative number to specify a character from the end of the string, counting back.

4

boolean

optional, default value=false

Disables pattern matching if set to true.

Returns:

  1. number first character index
  2. number last character index

Example - Pattern matching enabled by default:

local str = "This is a test string"
print(string.find(str, "%s"));                        -- find first space
5    5

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 538

string.find_utf8(string string, string substring, [number start index])

Returns the position of the first occurrence of a supplied substring in the subject string. If the supplied substring is found within the subject string then the start and end character positions of the substring are returned. nil is returned if the substring is not found.
This implementation of len is provided by our game code to support utf8 strings. It does not support pattern matching - see string.find for the original language implementation which does.

Parameters:

1

string

Subject string.

2

string

String pattern to search for.

3

number

optional, default value=1

Position of character at which to start the search. Supply a negative number to specify a character from the end of the string, counting back.

Returns:

  1. number first character index
  2. number last character index

Example:

local str = "This is a test string"
print(string.find_utf8(str, "test"))
11    14

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 558

string.format(string container string, ... values to insert)

Returns a formatted string from the formatting string and then arguments provided, in a similar style to the C function printf. The formatting string may contain the following special characters:

CharacterData TypeDescription
%cnumber (character code)The supplied numerical character code (see string.byte) will be converted into its string representation.
%dnumber (integer)The supplied integer, to be preceded by up to up to seven leading zeroes, the number of which may optionally be specified alongside the special character e.g. %04d. If no number is specified then the integer is included in the returned string as it was given.
%enumberThe supplied number will be formatted as an exponent, with the output in lower-case.
%EnumberThe supplied number will be formatted as an exponent, with the output in upper-case.
%fnumberThe specified number will be formated as a floating-point value. A specific format for the number may optionally be specified alongside the special character e.g. %4.1f would specify that the floating point number should be formatted with four digits preceding the decimal point and one digit following it.
%gnumberThe specified number will be formated as a compact floating-point value, or as an exponent (if too many digits) in lower-case.
%GnumberThe specified number will be formated as a compact floating-point value, or as an exponent (if too many digits) in upper-case.
%inumber (integer)The supplied integer value will be formatted as a signed integer.
%onumber (integer)The supplied integer value will be formatted as an octal value.
%qstringThe supplied string will be enclosed in strings (as a quotation) when returned.
%sstringA string value.
%unumber (integer)The supplied value will be formatted as an unsigned integer.
%xnumber (integer)The supplied value will be formatted as a hexadecimal integer in lower-case.
%Xnumber (integer)The supplied value will be formatted as a hexadecimal integer in upper-case.
The function will throw an error if it's unable to convert the number specified into an integer value (should one be expected).

Parameters:

1

string

String containing special characters to insert values into.

2

...

One or more values to insert into the container string, in the order that the special characters are found.

Returns:

  1. string result

Example - Inserting character codes with %c:

local str = string.format("hello %c %c %c, pleased to meet you", 65, 66, 67)
print(str)
hello A B C, pleased to meet you

Example - Specifying the string length of an integer with %d:

local str = string.format("These integers will be displayed with at least 5 digits: %05d %05d %05d", 12, 1234, 123456)
print(str)
These integers will be displayed with at least 5 digits: 00012 01234 123456

Example - Lower/Upper-case exponents with %e and %E:

local str = string.format("Exponents: %e %E", 1234.56, 1234.56)
print(str)
Exponents: 1.234560e+03 1.234560E+03

Example - Floating point values with %f:

local str = string.format("Floating point values: %f %3.1f", 123456.78, 123456.78)
print(str)
Floating point values: 123456.780000 123456.8

Example - Compact floating point values with %g and %G:

local str = string.format("Compact floating point values: %g %g %G", 123456, 12345678, 12345678)
print(str)
Compact floating point values: 123456 1.23457e+07 1.23457E+07

Example - Signed, Unsigned, Octal and Hexadecimal integers:

local str = string.format("Signed: %i, Unsigned: %u, Octal: %o, Hex: %x", -100, -100, -100, -100)
print(str)
Signed: -100, Unsigned: 4294967196, Octal: 37777777634, Hex: ffffff9c

Example - Strings:

local str = string.format("Unquoted: %s, quoted: %q", "test", "test")
print(str)
Unquoted: test, quoted: "test"

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 571

string.gmatch(string subject string, string pattern)

Returns a pattern-finding iterator. More information about iterators and lua string patterns may be found externally - see String Patterns.

Parameters:

1

string

subject string

2

string

pattern

Returns:

  1. iterator

Example:

local str = "This is a test string"
local wordcount = 0
for word in string.gmatch(str, "%a+") do
wordcount = wordcount + 1
end
print(string.format("%q contains %d words", str, wordcount))
"This is a test string" contains 5 words

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 622

string.gsub(string subject, string pattern, string replacement, [number count])

This function takes a subject string, a pattern string and a replacement string, and performs a search based on the pattern string within the subject string. Should any parts of the pattern match, those parts of the subject string are replaced with the replacement string. The resulting string is then returned. An optional count argument may also be specified to limit the number of pattern replacements that may be performed.

Parameters:

1

string

Subject string.

2

string

Pattern string. More information about lua patterns may be found here: String Patterns

3

string

Replacement string.

4

number

optional, default value=nil

Maximum number of times the replacement can be performed. If left unset, then no maximum is applied.

Returns:

  1. string result

Example:

-- replace all spaces with underscores
result = string.gsub("this is a test string", " ", "_")
print(result)
this_is_a_test_string

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 636

string.len(string input)

Returns the number of characters in the supplied string. This is the original lua language implementation of len, which does not support utf8 strings.

Parameters:

1

string

input

Returns:

  1. number length

Example:

str = "hello"
print(string.len(str))
5

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 649

string.len_utf8(string input)

Returns the number of characters in the supplied string. This implementation of len is provided by our game code and supports utf8 strings, see string.len for the original language implementation.

Parameters:

1

string

input

Returns:

  1. number length

Example:

str = "hi"
print(string.len_utf8(str))
2

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 658

string.lower(string input)

Returns the supplied string, converted to lowercase.

Parameters:

1

string

input

Returns:

  1. string converted string

Example:

str = "A Test String"
print(string.lower(str))
a test string

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 667

string.match(string subject, string pattern, [number start character])

Returns a substring of the supplied string, by a supplied pattern. An optional index may also be used to specify a character at which the search should be started.
More information about patterns may be found here: String Patterns.

Parameters:

1

string

Subject string to search.

2

string

Search pattern.

3

number

optional, default value=1

Start character within the subject string.

Returns:

  1. string matching string

Example:

str = "THIS WORD here IS LOWERCASE"
print(string.match(str, "%l+"))
here

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 676

string.rep(string source, number count)

Generates and returns a string which is a supplied number of copies of the supplied string, all concatenated together.

Parameters:

1

string

source

2

number

count

Returns:

  1. string result

Example:

print(string.rep("test", 3))
testtesttest

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 688

string.reverse(string input)

Returns the supplied string with the character order reversed.

Parameters:

1

string

input

Returns:

  1. string reversed string

Example:

print(string.reverse("forward"))
drawrof

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 697

string.starts_with(string subject string, string substring)

Returns true if the subject string starts with the supplied substring, or false othewise.

Parameters:

1

string

subject string

2

string

substring

Returns:

  1. nil

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 705

string.sub(string input, number start index, [number end index])

Returns a section of the supplied string, specified by start and (optionally) end character positions. The substring will include the characters specified by the start and end positions.
This is the original lua language implementation of sub, which does not support utf8 strings. See string.sub_utf8 for an implementation that does.

Parameters:

1

string

Subject string.

2

number

Position of the starting character of the substring. If a negative number is specified then the function counts back from the end of the string.

3

number

optional, default value=nil

Position of the end character of the desired substring. If omitted, then the end of the supplied string is used as the end of the substring. If a negative number is specified then the function counts back from the end of the string to find this character.

Returns:

  1. nil

Example - From character 11 until the end:

str = "this is a test string"
print(string.sub(str, 11))
test string

Example - From characters 11 through to 14 :

str = "this is a test string"
print(string.sub(str, 11, 14))
test

Example - From 13 characters from the end, onwards:

str = "this is a test string"
print(string.sub(str, -13))
a test string

Example - From 13 characters from the end until 9 from the start:

str = "this is a test string"
print(string.sub(str, -13, 9))
a

Example - From 13 characters from the end until 8 from the end:

str = "this is a test string"
print(string.sub(str, -13, -8))
a test

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 714

string.sub_utf8(string input, number start index, [number end index])

Returns a section of the supplied string, specified by start and (optionally) end character positions. The substring will include the characters specified by the start and end positions.
This implementation of sub is provided by our game code, see string.sub for the original language implementation. This function is slightly slower than string.sub.

Parameters:

1

string

Subject string.

2

number

Position of the starting character of the substring. If a negative number is specified then the function counts back from the end of the string.

3

number

optional, default value=nil

Position of the end character of the desired substring. If omitted, then the end of the supplied string is used as the end of the substring. If a negative number is specified then the function counts back from the end of the string to find this character.

Returns:

  1. nil

Example - From character 11 until the end:

str = "this is a test string"
print(string.sub(str, 11))
test string

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 742

string.split(string subject_str, string split_str)

Returns a list representing the specified subject_str split up by occurances of split_str, not including those occurances.
An empty table is returned if no occurances of split_str are found.

Parameters:

1

string

The string to be split.

2

string

The character or string to split the subject string at.

Returns:

  1. nil

Example - Splitting a string by spaces:

string.split("The quick brown fox", ' ')
{ "The", "quick", "brown", "fox" }

Example - Splitting a string with another string (note that the pattern matches at its earliest possible location):

string.split("Bananas: Price ----- £1.50", '---')
{ "Bananas: Price ", "-- £150" }

Example - Trimming the start and end occurances of spaces:

string.split("NoSpacesHere", ' ')
{ "NoSpacesHere" }

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 754

string.upper(string input)

Returns the supplied string, converted to uppercase.

Parameters:

1

string

input

Returns:

  1. string converted string

Example:

str = "A Test String"
print(string.upper(str))
A TEST STRING

defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 787


Functions

Functions are chunks of script that, when executed, perform one or more operations and then return control to the script that called them. Function declarations begin with the function keyword, and end with a corresponding end keyword. They are useful for encapsulating tasks that need to be performed repeatedly.

Functions can optionally take one or more argument values from the calling script. This allows a single function to produce different results when run repeatedly, based on its input values. Functions may also optionally return one or more values to the script that called them.

Functions in lua are first-class values, which means that they may be assigned and re-assigned to variables in exactly the same manner as number values, string values and so on. As with other variables types in lua it's possible for functions to be anonymous, where they are created without a name.

Once declared, a function can be called and executed in script by appending open and close parenthesis characters to its name in the form <function_name>(arg1, arg2). See the examples below.

Example - Simple function declaration and execution:

-- declare a function variable called test_function that takes no arguments
function test_function()
    print("test_function() called");
end

-- call test_function, after it has been declared
test_function()
test_function() called

Example - Alternative form of function declaration:

This alternative form of function declaration is identical to the previous example. It better illustrates the nature of functions as just another type of variable, created by assignment like a string or number.
-- declare a function variable called test_function that takes no arguments
test_function = function()
    print("test_function() called");
end

-- call test_function, after it has been declared
test_function()
test_function() called

Example - Function taking two arguments:

Arguments can be specified in the function specification as follows. The arguments will be accessible as local variables throughout the lifetime of the function.
-- declare a function that takes two arguments called 'first' and 'second'
f = function(first, second)
    print("f() called");
    print("\tfirst is " .. tostring(first));
    print("\tsecond is " .. tostring(second));
end

-- call f
f("hello", "goodbye")
f("lonely")            -- deliberately not supplying a second arg
f(nil, "lonely")        -- deliberately not supplying a first arg
f() called
    first is hello
    second is goodbye
f() called
    first is lonely
    second is nil        -- value of unsupplied arguments is nil
f() called
    first is nil
    second is lonely

Example - Function returning two values:

function get_1080p_screen_resolution()
    return 1920, 1080;
end

local x, y = get_1080p_screen_resolution()
print("1080p screen resolution is [" .. x .. ", " .. y .. "]")
1080p screen resolution is [1920, 1080]

Example - Example of passing functions as arguments to another function:

This includes an example of an anonymous function.
-- this function takes an argument and prints whether it's a function or not
function is_function(name, obj)
    if type(obj) == "function" then
        print(name .. " is a function");
    else
        print(name .. " is not a function");
    end
end

a_number = 5
a_function = function() print("hello!") end

-- make calls to is_function. First arg is string name, second arg is value to test
is_function("a_number", a_number)
is_function("a_function", a_function)

-- pass through an anonymous function
is_function("anonymous_function", function() print("this is an anonymous function!") end)

-- pass is_function itself into is_function...
is_function("is_function", is_function)
a_number is not a function
a_function is a function
anonymous_function is a function
is_function is a function
Back to top

Varargs

A function can also take a variable number of arguments in a vararg structure. Using varargs, an unlimited number of arguments can be supplied to a function, which accesses them as elements in a table created within the function block called arg. The number of arguments can be accessed at the special element n within the arg table. See the examples below.

Example:

-- the ... argument in the function declaration specifies that the function takes a vararg
function print_all(...)
    for i = 1, arg.n do
        print("arg " .. i .. " is " .. tostring(arg[i]))
    end
end

-- call print_all() with as many arguments as we like
print_all("hello", "goodbye", 1, 2, 3)
arg 1 is hello
arg 2 is goodbye
arg 3 is 1
arg 4 is 2
arg 5 is 3

Tables

Tables are the only data type in lua that can be used to contain other data. As such, they are the only mechanism available for building complex data structures.

Lua tables are associative arrays, which means they store sets of key/value pairs. A value in a table is stored in a record corresponding to a key, and that value may later accessed or modified using that same key.

An example representation of a table:

KeyValue
1"first"
2"second place"
3"third place"
4"also ran"
5"also ran"

If a value is written to a table at a key which is already associated with a value, then that previous value is overwritten, just like normal variables.

Table keys are most commonly or usefully number or string values, but may be of any data type other than nil. Values stored at keys within a table can be of any type, including function or table (allowing tables to be nested). If a value of nil is stored at a particular key, then that is equivalent to deleting that key/value combination. If a key is looked up in a table at which no value has been stored, then nil is returned.

Values in a table may be accessed using [] square brackets, or by using the . accessor if the key is a string that contains no spaces, and where the first character of that string is not a numeric character. See the examples below:

Example:

-- Create an empty table
example_table = {}

-- Assign a string value to table t at a numeric key
example_table[5] = "5"

-- Assign a string value to table t at a numeric key
example_table[5] = "5"

-- Assign a number value to table t at a string key
example_table["10"] = 10

-- Assign a string value to table t at a string key
example_table["five"] = "five"

-- Also assign a string value to table t at a string key, using the shorthand method of accessing string keys
example_table.ten = "ten"

-- Function to access and print data from the table
function print_key_and_value(t, key)
    print("key is " .. tostring(key) .. " of type " .. type(key) .. ", corresponding value is " .. tostring(t[key]) .. " of type " .. type(t[key]))
end

print_key_and_value(example_table, 5)
print_key_and_value(example_table, "5")        -- doesn't exist - no value corresponding to the string key "5" was written - value will be nil
print_key_and_value(example_table, 10)            -- doesn't exist - no value corresponding to the number key 10 was written - value will be nil
print_key_and_value(example_table, "five")
print_key_and_value(example_table, "ten")

-- This use of shorthand accessors will work, as the keys "five" and "ten" are strings
print(example_table.five)
print(example_table.ten)

-- This, however, is illegal, as while the key "10" is a string, it starts with a numeric char
print(example_table.10)
key is 5 of type number, corresponding value is 5 of type string
key is 5 of type string, corresponding value is nil of type nil
key is 10 of type number, corresponding value is nil of type nil
key is five of type string, corresponding value is five of type string
key is ten of type string, corresponding value is ten of type string
five
ten

Example:

t = {}

-- Assign a number value at a string key
t["age"] = 25

-- Alternative shorthand method for assigning a value to a string key within a table.
-- Here, the string value "Peter" is stored at the string key "name".
t.name = "Peter"

-- The alternative shorthand method of accessing table elements cannot be used for keys that are not strings, however.
t.false = "warning!"            -- The value "warning!" will be stored at the string key "false", not the boolean key false
t.2 = "error!"                    -- This attempt to use table assignment shorthand is illegal and will generate a syntax error
t["2"] = "okay"                -- The proper method of accessing an element with a string key that starts with a number char

-- Assign a value to a key, but where we evaluate the key from another variable.
-- The string value "brown" will be stored at the string key "hair_colour"
key_name = "hair_colour"
t[key_name] = "brown"

-- Access elements in the table (using a variety of methods)
print(t["name"] .. " is " .. t.age .. " years old, his hair colour is " .. t.hair_colour)
Peter is 25 years old, his hair colour is brown
Back to top

Table Construction

Before a table can be used it must be created with a table constructor, which is a pair of {} braces. Values, or key/value pairs, can be included within the constructor so that they are stored in the table from creation.

Within the {} braces which denote the new table, key/value combinations that specify data to add to the table on construction can be given in a variety of formats:

  1. Keys can be explictly given by enclosing them in square brackets [].
  2. If a key name is given but not enclosed within square brackets, it is assumed to be a string.
  3. If the key is omitted altogether, then the first ascending free integer is used as the key. This shorthand is useful for creating Indexed Tables.

Example - Create an empty table:

t_empty = {}

Example - Create an indexed table with data values by omitting the keys:

If data values are supplied without keys, separated by commas, then each value is inserted into the table at the first available integer key, starting at 1. See the section on Indexed Tables below.
t_indexed = {
    "first",        -- The string value "first" is stored with a numeric key 1
    "second",        -- The string value "second" is stored with a numeric key 2
    "third",        -- The string value "third" is stored with a numeric key 3
    "fourth"        -- The string value "fourth" is stored with a numeric key 4
}

Example - Create a table with explicit key/values:

t_explicit_keys = { [10] = "ten", [20] = "twenty", [30] = "thirty", ["40"] = "a trap" }        -- observe that ["40"] is actually a string key, rather than a number

Example - Shorthand way of creating string keys during construction:

t_string_keys = {
    monday = "first",                    -- string key "monday", string value "first"
    tuesday = "second",                    -- string key "tuesday", string value "second"
    ["wednesday"] = "third",            -- the 'longhand' way of specifying string key "wednesday", string value "third"
    [thursday] = "fourth",                -- probably an error! This is not specifying a string key, but will evaluate the expression thursday and substitute the result
    1st_january = "new_year",            -- this is illegal - when using the shorthand method of creating a string key, the first character must be a letter
    ["1st_january"] = "new_year",        -- legal version, using the longhand form of key specification - generally, it's recommended to avoid string table keys starting with number chars
    25th december = "christmas",        -- also illegal - when using shorthand methods of specifying a string key, they may not contain spaces
    ["25th december"] = "christmas"     -- legal version, using the longhand form of string key specification
}

Example - Create a table with key/values, but where the key is evaluated:

key_name = "title"
t = { [key_name] = "doctor" }
print(t.title)                -- print the value corresponding to the string key "title"
doctor
Back to top

Tables and Memory

Tables are always assigned by reference, and passed by reference if supplied as function arguments. Multiple references to the same table can exist at the same time. When no more references to a table exist, the lua garbage collector will eventually delete it and reclaim the memory it uses.

Example:

-- Declare function to modify table
function modify_table(t)
    print("modify_table() called, table is " .. tostring(t))
    print("\tadding table.parting")
    t.parting = "goodbye"
end

-- Declare table
example_table = { greeting = "hello" }
print("example_table created, memory address is " .. tostring(example_table))

modify_table(example_table)

print("example_table.greeting is " .. example_table.greeting .. ", example_table.parting is " .. example_table.parting)

example_table_2 = example_table

example_table = "not a table any more"

print("example_table is " .. tostring(example_table))
print("example_table_2 is " .. tostring(example_table_2))

example_table_2 = 5
example_table created, memory address is table: 0x75cd70
modify_table() called, table is table: 0x75cd70
    adding table.parting
example_table.greeting is hello, example_table.parting is goodbye
example_table is not a table any more
example_table_2 is table: 0x75cd70
Back to top

Indexed Tables

Tables are commonly used in one of two manners. Our internal nomenclature for these is Indexed vs Lookup Tables. There is no difference in the manner of creation between the two, and indeed one table can work in both modes at once, although this is rarely done.

Indexed tables, as we call them, contain elements stored at keys in an ascending numerical sequence, starting from 1. Tables arranged in this manner are easy to create, easy to iterate over in sequence, and many functions within the table library and elsewhere require tables to be arranged in an indexed manner in order to work. Additionally, the sizeof operator # will only produce accurate results for an indexed table.

Indexed tables can be iterated-over with a manual for-loop (see the section on Standard Traversal), or with the ipairs iterator. The pairs iterator can also be used, but the order of iteration will not be predictable or deterministic.

It is advantageous to create an indexed table when the problem being solved would benefit from storing and working with data in a listed, fixed order. If the relative order in which elements are stored in the table is important, especially if iterating over the table, or if the table's use case demands that the data within it will be accessed via iteration more than directly by key, then chances are it should be set up as an indexed table. Examples include stacks, queues, trees or other data structure where the order of elements needs to be preserved.

Example - Indexed table creation:

If no keys are given during table creation, then the table is indexed by default.
-- First value is stored at numeric key 1
days_of_week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

for i = 1, #days_of_week do
    print(days_of_week[i])
end

-- sizeof operator # only works with indexed tables
print("There are " .. #days_of_week .. " days of the week")

-- table.concat(t, spacer) is an example of a table library function that requires an indexed table in order to work
str = table.concat(days_of_week, ", ")
print(str)

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
There are 7 days of the week
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
Back to top

Lookup Tables

Tables containing keys that are not defined in an ascending integer sequence tend to be used as lookup tables. Data in a lookup table is more commonly looked up directly by key, rather than by iteration. If data within the table is accessed more commonly by iteration, or if it's important to maintain an order between the records stored in the table, then consider creating an indexed table with ascending numeric keys instead.

Lookup tables are most useful for flat data sets with no order of precedence or operation between the data records. Data sets akin to database tables are ideal for storing in lookup tables.

Lookup tables cannot be iterated over with the ipairs iterator - instead, the pairs iterator may be used. The downside to pairs is that order of iteration cannot be relied on to be the same on different machines running the same script, or even on the same machine running the same script multiple times.

Example - Lookup table example, showing nested tables:

months = {
    January = {                    -- within months table: string key "January", value is a table
        max_temp = 8.19,        -- within January table: string key "max_temp", value is number 8.19
        min_temp = 2.37
    },
    February = { max_temp = 8.37, min_temp = 2.25 },
    March = { max_temp = 10.48, min_temp = 3.56 },
    April = { max_temp = 13.12, min_temp = 5.15 },
    May = { max_temp = 16.31, min_temp = 8.11 },
    June = { max_temp = 19.08, min_temp = 10.95 },
    July = { max_temp = 20.94, min_temp = 13.02 },
    August = { max_temp = 21.03, min_temp = 13.06 },
    September = { max_temp = 18.92, min_temp = 10.92 },
    October = { max_temp = 15.49, min_temp = 8.38 },
    November = { max_temp = 11.61, min_temp = 5.21 },
    December = { max_temp = 8.87, min_temp = 2.81 }
}

flowers = {
    Sunflowers = { colour = "yellow", peak_month = "August" },
    Roses = { colour = "red", peak_month = "July" },
    Daffodils = { colour = "yellow", peak_month = "April" },
    Chrysanthemums = { colour = "pink", peak_month = "September" },
    Snowdrops = { colour = "white", peak_month = "February" }
}

function print_flower_info(flower_key)
    local flower_record = flowers[flower_key]            -- look up flower sub-table within flowers table, based on the key
    if flower_record then
        local month_key = flower_record.peak_month
        local month_record = months[month_key]            -- look up month sub-table within months table
        if month_record then
            local colour = flower_record.colour            -- look up colour value from the relevant flower record

            -- look up min_temp and max_temp values from the relevant month record
            local min_temp = month_record.min_temp
            local max_temp = month_record.max_temp
            print(flower_key .. " are " .. colour .. " and are best seen in " .. month_key .. ", when the temperature varies between " .. min_temp .. " and " .. max_temp .. " celcius")
        end
    end
end

print_flower_info("Daffodils")
print_flower_info("Chrysanthemums")
Daffodils are yellow and are best seen in April, when the temperature varies between 5.15 and 13.12 celcius
Chrysanthemums are pink and are best seen in September, when the temperature varies between 10.92 and 18.92 celcius
Back to top

Standard Traversal

Tables are commonly traversed/iterated over with a for-loop with manually-defined limits and steps. This is possible if the table keys are arranged in a suitable numeric order - usually an ascending integer sequence (see the section on Indexed Tables).

The size of a table where values are assigned at ascending numeric integer keys can be accessed with the # operator. This reports the first integer key n for which no value is stored at key n + 1.

Example - Examples of #t:

t1 = { "yes", "no", "maybe", "sometimes", "rarely" }                                 -- values are stored at ascending keys
t2 = { [1] = "hello", [2] = "bonjour", [3] = "gutentag", [5] = "salut" }             -- missing value stored at key 4
print("size of t1: " .. #t1)
print("size of t2: " .. #t2)
size of t1: 5
size of t2: 3

Example - Traversal by numeric sequence:

t = { "my", "enormous", "green", "boots", "dont", "fit" }
for i = 1, #t do
    print("\tkey: " .. i .. ", value: " .. t[i])
end
key: 1, value: my
key: 2, value: enormous
key: 3, value: green
key: 4, value: boots
key: 5, value: dont
key: 6, value: fit
Back to top

Table Iterators

The lua language provides the iterator functions ipairs and pairs for iterating over tables where Standard Traversal may not be possible or desirable.

The ipairs iterator behaves much the same as traversing over a table in ascending numeric sequence. Like other iterator functions, ipairs automatically creates local variables for the key and (optionally) the value for each table element it traverses. The ipairs iterator starts at the table element corresponding to a numeric key value of 1, increments the key by 1 for each loop iteration, and stops at the first integer key it finds for which a value is not assigned.

Unlike ipairs and numeric traversal, the pairs iterator allows traversal over all elements in a table, regardless of key type or any 'gaps' in the data. The main caveat to usage is that the order of traversal is not deterministic, either between machines or on the same machine making multiple passes over the same table. As such, the pairs iterator is unsafe to use in multiplayer scripts as two different machines will traverse the same table in different orders.

Also provided within the scripting libraries are:

  • dpairs, which is a deterministic version of pairs. This eliminates the problem of not being able to use pairs in multiplayer, but is written in lua and is quite computationally slow, so use this sparingly.
  • ipairs_reverse is an equivalent to ipairs which iterates in reverse order.
    • See also the section on Game Object Iterators, for iterators that work on non-table game objects.

      ipairs(table subject table)

      Iterates over a numerically indexed table. An indexed table is one containing keys in an ascending numeric sequence, starting from 1. The iterator will query the key/value pair where the key is 1, and then 2, 3 and so on, until it finds a key/pair that doesn't exist, at which point the iterator will terminate.
      The ipairs function returns three values - an iterator function, the table to iterate over, and the control variable. When used with a for loop the iterator can be used to get the key/value of each element in the table in sequence. See the examples below for more information on usage.
      Unlike the pairs iterator, ipairs disregards values stored at non-numeric keys, but the order in which values are returned is deterministic, meaning ipairs is safe to use in multiplayer mode.
      The ipairs iterator is interchangeable with using the size of table operator # to manually control the loop iteration.

      Parameters:

      1

      table

      subject table

      Returns:

      1. function iterator function
      2. table subject table
      3. number control variable

      Example - Standard ipairs example:

      t = {"january", "february", "march", "april", "may" }         -- table created with ascending numeric keys
      for key, value in ipairs(t) do
          -- local variables called 'key' and 'value' are automatically created each loop cycle
          print("key: " .. key .. ", value: " .. value);
      end
      key: 1, value: january
      key: 2, value: febraury
      key: 3, value: march
      key: 4, value: april
      key: 5, value: may

      Example - Ipairs example with gap in numeric sequence:

      t = { [1] = "first", [2] = "second", [3] = "third", [5] = "fifth" }         -- gap at 4
      for key, value in ipairs(t) do
          -- local variables called 'key' and 'value' are automatically created each loop cycle
          print("key: " .. key .. ", value: " .. value);
      end
      key: 1, value: first
      key: 2, value: second
      key: 3, value: third

      Example - Ipairs example with table containing non-numeric keys:

      t = {
          ["fruit"] = "apples",
          [4] = "fourth",
          ["animal"] = "cat",
          [2] = "second",
          [1] = "first",
          ["month"] = "september"
      }

      for key, value in ipairs(t) do
          -- loop will continue until it fails to find a value corresponding to key 3, and then stop
          print("key: " .. key .. ", value: " .. value);
      end
      key: 1, value: first
      key: 2, value: second

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1208

      pairs(table subject table)

      Iterates over any table returning key/value pairs in a non-deterministic order. The pairs iterator function is the main way to query each record in a table that is not numerically indexed. However, the order of iteration is not guaranteed, so the pairs iterator should be used with caution in multiplayer games where a different order of modifications to the model between clients can cause the game to desync.
      The pairs function returns three values - an iterator function, the table to iterate over, and the control variable. When used with a for loop the iterator can be used to get the key/value of each element in the table in sequence. See the examples below for more information on usage.

      Parameters:

      1

      table

      subject table

      Returns:

      1. function iterator function
      2. table subject table
      3. number control variable

      Example - pairs example:

      Note how the order of the output is arbitrary.
      -- table with keys of lots of different types - impossible to traverse with #t or ipairs
      t = {
          [1] = "first",
      ["greeting"] = "hello",
      [5] = "fifth",
      [10] = "tenth",
      [true] = "this has a boolean key",
          [function() print("hello") end] = "This has a function key! Weird but possible"
      }
      for key, value in pairs(t) do
          print("key: " .. tostring(key) .. ", value: " .. tostring(value));
      end
      key: 1, value: first
      key: greeting, value: hello
      key: function: 0x2194d10, value: This has a function key! Weird but possible
      key: 5, value: fifth
      key: true, value: this has a boolean key
      key: 10, value: tenth

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1259

      ipairs_reverse(table table)

      Iterator function that allows Indexed Tables to be iterated over in reverse order. This function can be used effectively with a for-loop to traverse backwards over an indexed table - see the example below.

      Parameters:

      1

      table

      table

      Returns:

      1. function iterator function
      2. table table
      3. number initial search key

      Example:

      local t = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
      for index, day in ipairs_reverse(t) do
          print("Day " .. index .. " is " .. day);
      end;
      Day 7 is sunday
      Day 6 is saturday
      Day 5 is friday
      Day 4 is thursday
      Day 3 is wednesday
      Day 2 is tuesday
      Day 1 is monday

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1300

      dpairs(table subject table)

      An iterator function, a deterministic equivalent of pairs. It is used in the same way, but it iterates over the table in a deterministic way, which makes it safe for use in multiplayer.
      Note that iteration using this function would be slower, so don't use it with large tables in performance-critical code! However, for the general usage in gameplay model or UI code with not many entries, it should be fine. Still, be mindful of the perfomance.
      It works by first iterating over all keys of the given table (using pairs), compiling the keys of the same type in separate tables. Then it sorts those tables and finally going through their contents (keys), table by table.
      dpairs requires that all keys within the table are number or string values.

      Parameters:

      1

      table

      subject table

      Returns:

      1. function iterator function
      2. table subject table
      3. nil starting index value

      Example - dpairs example:

      Note how the order of the output is not arbitrary, numerical keys before string keys.
      t = { 3, 2, 1, colour = "black", monster = "dragons", {}, "dragons", index = 5 }
      t[11] = 6
      t[12] = 7
      for k, v in dpairs(t) do
          print(tostring(k) .. " " .. tostring(v))
      end
      1 3
      2 2
      3 1
      4 table: 0x85bc50
      5 dragons
      11 6
      12 7
      colour black
      index 5
      monster dragons

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1324

      Lua provides a library of operations that can be performed on tables, listed below. More detailed information about these functions may be found on the dedicated page on lua-users.org here.

      The functions may be called in the form table.<function>(<t>, <arguments>).

      table.concat(table table, [string separator], [number start element], [number end element])

      Concatenates the values in the supplied table into a string, with optional separator characters, and returns that string. This can be a memory-efficient way of concatenating large amounts of strings together.

      Parameters:

      1

      table

      Table to concatenate.

      2

      string

      optional, default value=""

      Separator string to insert between elements from the table.

      3

      number

      optional, default value=1

      Table element at which to start concatenating.

      4

      number

      optional, default value=<table_size>

      Table element at which to finish concatenating.

      Returns:

      1. nil

      Example:

      t = {"first", "second", "third", "fourth", "fifth"}
      print(table.concat(t))
      print(table.concat(t, " ", 2, 4))
      firstsecondthirdfourthfifth
      second third fourth

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1415

      table.insert(table table, [number position], obj value)

      Inserts a value into the supplied table. The index at which to insert the value may optionally be specified - note that this can change the sequence of arguments.
      If no position argument is specified then the first available integer key in ascending order is chosen, starting from 1.

      Parameters:

      1

      table

      Table to insert element in to.

      2

      number

      optional, default value=<table_size>

      Position at which to insert value. Note that this may be omitted, in which case the value to insert should be specified as the second argument. In this case the first available integer key is chosen, ascending from 1.

      3

      obj

      Value to insert. If a third argument is omitted, the second is taken as the value to insert.

      Returns:

      1. nil

      Example:

      t = {1, 2, 3}
      table.insert(t, "hello")            -- insert "hello" as the last element in the table
      table.insert(t, 3, "goodbye")        -- insert "goodbye" as the third element in the table
      print(table.concat(t, " "))
      1 2 goodbye 3 hello

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1428

      table.maxn(table table)

      Returns the largest positive numeric index within the supplied table at which a value is assigned. Unlike the # operator, this will not stop counting if a gap in the integer sequence is found.

      Parameters:

      1

      table

      table

      Returns:

      1. number highest index

      Example:

      t = {}
      t[1] = "goodbye"
      t[2] = "adios"
      t[4] = "auf"
      -- no t[5]
      t[6] = "la revedere"
      t["8"] = "au revoir"        -- not counted as the key is a string
      print("table.maxn(t) is " .. table.maxn(t))
      print("#t is " .. #t)
      table.maxn(t) is 6
      #t is 4

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1441

      table.remove(table table, [number position])

      Removes the element from the supplied table at the supplied numeric index.

      Parameters:

      1

      table

      Table.

      2

      number

      optional, default value=<table_size>

      Position within table of element to remove.

      Returns:

      1. nil

      Example:

      t = {1, 2, 3, 4, 5}
      table.remove(t)        -- remove element at the end of the table
      table.remove(t, 2)        -- remove second element from the table
      print(table.concat(t))
      134

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1458

      table.sort(table table, [function comparison])

      Sorts the elements in the supplied table into a new order. A comparison function may be supplied, which should take two table elements as arguments and return true if the first of these elements should appear in the final sorted order before the second, or false if the opposite is desired. The table is sorted into ascending numerical order by default, which is the equivalent of supplying the sort function function(a, b) return a < b end.

      Parameters:

      1

      table

      Table to sort.

      2

      function

      optional, default value=<ascending_sort_order>

      Comparison function.

      Returns:

      1. nil

      Example - Default ascending sort order:

      t = {4, 5, 3, 1, 8, 10}
      table.sort(t)
      print(table.concat(t, " "))
      1 3 4 5 8 10

      Example - Reverse sort order:

      t = {4, 5, 3, 1, 8, 10}
      table.sort(t, function(a, b) return a > b end)
      print(table.concat(t, " "))
      10 8 5 4 3 1

      Example - Sorting a table of strings into length order:

      t = {"very_long", "short", "longer", "really_really_long"}
      table.sort(t, function(a, b) return string.len(a) < string.len(b) end)
      print(table.concat(t, "..."))
      short...longer...very_long...really_really_long

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1469

      table.tostring(table table, boolean for campaign savegame, [number max depth], [number tab level])

      Converts a table into a string representation of that table for debug output. Note that this function is not provided with lua but is provided by Total War's script libraries.

      Parameters:

      1

      table

      Subject table.

      2

      boolean

      Set to true if the string is intended for saving into a campaign savegame. This discards values that are not boolean, number, strings or tables.

      3

      number

      optional, default value=3

      Maximum depth. This is the maximum depth of tables-within-tables to which the function will descend. Supply -1 to set no maximum depth, which makes an infinite loop a possibility.

      4

      number

      optional, default value=0

      Starting tab level. This number of tabs will be prepended to the start of each new line in the output.

      Returns:

      1. string table to string

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1493

      table.contains(table table, value value)

      Reports if the supplied table contains the supplied value. If the table does contain the supplied value, the corresponding key at which it may be found is returned, otherwise false is returned.

      Parameters:

      1

      table

      table

      2

      value

      value

      Returns:

      1. value key corresponding to value

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1600

      table.binary_search(table table, value value, [function comparison function])

      Searches for a given value in the supplied sorted indexed table using binary search (which has log2 complexity).

      Parameters:

      1

      table

      The table to search the value in. It must be indexed table already sorted using the comparison function.

      2

      value

      The value to search the table for.

      3

      function

      optional, default value=less-than-comparison

      Comparison function used also for the sorting. If not provided operator less-than is used.

      Returns:

      1. boolean is the given value present in the table
      2. number index of an occurence of the value if it is present (not necessary the first one, if more than one are present), or where the value should be inserted in order to keep the table sorted

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1619

      table.binary_search_interval(
        
      table table,
        number
      first subinterval index,
        number
      last subinterval index,
        value
      value,
        function
      comparison function
      )

      Searches for a given value in a subinterval of the supplied sorted indexed table using binary search (which has log2 complexity).

      Parameters:

      1

      table

      table

      2

      number

      first subinterval index

      3

      number

      last subinterval index

      4

      value

      value

      5

      function

      Comparison function used also for the sorting.

      Returns:

      1. boolean is the given value present in the table
      2. number index of an occurence of the value if it is present in the given interval (not necessary the first one, if more than one are present), or where the value should be inserted in order to keep the table sorted

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1637

      table.is_empty(table table)

      Returns whether the supplied table is empty.

      Parameters:

      1

      table

      Subject table.

      Returns:

      1. boolean is empty

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1668

      table.copy(table table)

      Returns a deep copy of the supplied table. All subtables are copied. Metatables are not copied. Cyclical references are preserved.

      Parameters:

      1

      table

      Subject table

      Returns:

      1. table copy

      Example - Loading faction script:

      This script snippet requires the path to the campaign faction folder, then loads the "faction_script_loader" script file, when the game is created.
      my_table = { fruit = "apple", topping = { flavour = "cinnamon" } }
      copied_table = table.copy(my_table)
      copied_table.fruit = "banana"
      copied_table.topping.flavour = "chocolate"
      print(my_table.fruit .. " topped with " .. my_table.topping.flavour)
      print(copied_table.fruit .. " topped with " .. copied_table.topping.flavour)
      apple topped with cinnamon
      banana topped with chocolate

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1681

      table.mem_address(table object, [boolean leave punctuation])

      Returns the memory address portion of the result of calling tostring() with a table argument. The function will fail if the supplied table has a metatable that's write-protected.
      If the leave punctuation flag is set then the memory address is supplied back still with its leading colon and space characters.

      Parameters:

      1

      table

      object

      2

      boolean

      optional, default value=false

      leave punctuation

      Returns:

      1. string address string

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1727

      table.indexed_to_lookup(table indexed table)

      Returns another table containing all records in the supplied indexed table, except with the values set to keys. The values in the returned table will be true for all records.

      Parameters:

      1

      table

      indexed table

      Returns:

      1. table lookup table

      Example:

      indexed_t = {"oranges", "apples", "strawberries"}
      lookup_t = table.indexed_to_lookup(indexed_t)
      for key, value in pairs(lookup_t) do
      print(key, value)
      end
      strawberries    true
      oranges            true
      apples            true

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1768

      table.compile_tables(table table_list, [table merge_rules])

      Given a list of tables, sorts all tables by an optional load_order and then merges each one onto the previous successively. Can be used to merge and override data tables for mod compatibility.

      Parameters:

      1

      table

      The list of tables to be merged, indexed numerically.

      2

      table

      optional, default value=default rules (fully recursive, allow overrides)

      A table describing the rules for merging, including recursion_levels and allow_overrides.

      Returns:

      1. table Returns the fully compiled table (a new table reference).

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1833

      table.merge_tables(table merge_to, table merge_from, table merge_rules, [number recursion_level])

      Merge two tables given a set of merge rules, implanting the data from merge_from into merge_to.

      Parameters:

      1

      table

      The table to which data will be merged. The return value is this table, following the merge.

      2

      table

      The table from which data will be merged.

      3

      table

      A table describing the rules for merging, including recursion_levels and allow_overrides.

      4

      number

      optional, default value=1

      The number of recursions this function call is at, i.e. the number of table layers into the original table that the merge has reached. If unspecified, this begins at 1.

      Returns:

      1. table Returns the original merge_to table, but with the contents of merge_from incoorporated into it.

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1862


      Userdata

      Userdata is an area of memory accessible to lua but created by the host program. In our case, the host program is the game executable. It allows the host program to package up code functionality in a black box that can be used in fixed ways script.

      The interface objects supplied to script by the game in campaign and battle are typically userdata. It's not possible for script to meaningfully modify or query userdata objects in ways that weren't specifically set up by the creating code.


      Math

      The math library provides mathematical functions and values in a table that be called from within lua.

      The math libraries provides the following constants that can be looked up:

      math.abs(number value)

      Returns the absolute of the supplied value, converting it to a positive value if negative.

      Parameters:

      1

      number

      value

      Returns:

      1. number absolute value

      Example:

      print(math.abs(-4))
      4

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1944

      math.acos(number value)

      Returns the arc cosine of the supplied value, in radians. The supplied value should be between -1 and 1.

      Parameters:

      1

      number

      value

      Returns:

      1. number acos value in radians

      Example:

      print(math.acos(0.5))
      1.0471975511966

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1952

      math.asin(number value)

      Returns the arc sine of the supplied value, in radians. The supplied value should be between -1 and 1.

      Parameters:

      1

      number

      value

      Returns:

      1. number asin value in radians

      Example:

      print(math.asin(0.5))
      0.5235987755983

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1960

      math.atan(number value)

      Returns the arc tangent of the supplied value, in radians.

      Parameters:

      1

      number

      value

      Returns:

      1. number atan value in radians

      Example:

      print(math.atan2(1))
      0.64350110879328

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1968

      math.atan2(number opposite, number adjacent)

      Returns the arc tangent of the supplied opposite value divided by the supplied adjacent value, in radians. The sign of both arguments is used to find the quadrant of the result.

      Parameters:

      1

      number

      opposite

      2

      number

      adjacent

      Returns:

      1. number atan value in radians

      Example:

      print(math.atan2(5, 5))
      print(math.atan2(-5, 5))
      0.78539816339745
      -0.78539816339745

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1976

      math.ceil(number value)

      Returns the smallest integer that is larger than or equal to the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number ceil value

      Example:

      print(math.ceil(2.2))
      3

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1987

      math.ceil_to(number subject value, [number multiple value])

      Returns the smallest multiple of the supplied multiple value, which is larger than the supplied subject value.

      Parameters:

      1

      number

      subject value

      2

      number

      optional, default value=10

      multiple value

      Returns:

      1. number ceiling value

      Example:

      -- print the smallest multiple of 50 that is larger than 128
      print(math.ceil_to(128, 50))
      150

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 1995

      math.clamp(number value, number min, number max)

      Clamps the supplied numeric value to be between the supplied min and max values. The clamped value is returned.

      Parameters:

      1

      number

      value

      2

      number

      min

      3

      number

      max

      Returns:

      1. number clamped value

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2009

      math.cos(number value)

      Returns the cosine of the supplied radian value.

      Parameters:

      1

      number

      value

      Returns:

      1. number cosine value

      Example:

      print(math.cos(1.0471975511966))
      0.5

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2026

      math.cosh(number value)

      Returns the hyperbolic cosine of the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number hyperbolic cosine value

      Example:

      print(math.cosh(1))
      1.5430806348152

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2034

      math.deg(number radian value)

      Converts the supplied radian value into an angle in degrees. See also math.rad.

      Parameters:

      1

      number

      radian value

      Returns:

      1. number value in degrees

      Example:

      print(math.deg(math.pi))
      180.0

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2042

      math.exp(number exponent)

      Returns the numerical constant e to the power of the supplied value. Supply a value of 1 to just return e.

      Parameters:

      1

      number

      exponent

      Returns:

      1. number e ^ exponent

      Example:

      print(math.exp(1))
      2.718281828459

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2050

      math.floor(number value)

      Returns the largest integer that is smaller than or equal to the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number floor value

      Example:

      print(math.floor(2.2))
      2

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2058

      math.floor_to(number subject value, [number multiple value])

      Returns the largest multiple of the supplied multiple value, which is smaller than the supplied subject value.

      Parameters:

      1

      number

      subject value

      2

      number

      optional, default value=10

      multiple value

      Returns:

      1. number ceiling value

      Example:

      -- print the largest multiple of 50 that is smaller than 128
      print(math.floor_to(128, 50))
      100

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2066

      math.fmod(number dividend, number divisor)

      Returns remainder of the division of the first supplied value by the second supplied value.

      Parameters:

      1

      number

      dividend

      2

      number

      divisor

      Returns:

      1. number floor value

      Example:

      -- 5 * 4 is 20, leaving a remainder of 3 to reach 23
      print(math.fmod(23, 5))
      3

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2080

      math.frexp(number x value)

      Returns the values of m and exp in the expression x = m * 2 ^ exp, where x is the value supplied to the function. exp is an integer and the absolute value of the mantissa m is in the range 0.5 - 1 (or zero when x is zero).

      Parameters:

      1

      number

      x value

      Returns:

      1. number mantissa m value
      2. number exponent e value

      Example:

      print(math.frexp(10)))
      0.625    4

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2090

      math.ldexp(number m, number exp)

      Returns m * 2 ^ exp, where the mantissa m and exponent exp are values supplied to the function. exp should be an integer value.

      Parameters:

      1

      number

      m

      2

      number

      exp

      Returns:

      1. number m * 2 ^ exp

      Example:

      print(math.ldexp(2, 4))
      32.0

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2099

      math.log(number value)

      Returns the natural logarithm of the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number log value

      Example:

      print(math.log(10))
      2.302585092994

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2108

      math.log10(number value)

      Returns the base-10 logarithm of the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number log value

      Example:

      print(math.log(10))
      1.0

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2116

      math.map_range(
        
      number input value,
        number
      input range start,
        number
      input range end,
        number
      output range start,
        number
      output range end
      )

      Map a numeric value from one given range of numbers to another. The returned value will be the same relative to the output range, as the input number is to the specified input range. Negative numbers, input values outside of the input range, and ranges that run backwards are all supported.

      Parameters:

      1

      number

      input value

      2

      number

      input range start

      3

      number

      input range end

      4

      number

      output range start

      5

      number

      output range end

      Returns:

      1. number output value

      Example - Simple map_range example:

      For an input range between 0 to 10, and an input value of 1 (i.e. 10% of the difference between 0 and 10), show the value mapped on to the output range 50 to 60
      print(math.map_range(1, 0, 10, 50, 60))
      51.0

      Example - Further map_range example:

      For an input range between 20 to 30, and an input value of 25 (50% of the difference between 20 and 30), show the value mapped on to the output range 50 to 100
      print(math.map_range(25, 20, 30, 50, 100))
      75.0

      Example - Negative numbers:

      For an input range between -100 to -50, and an input value of -25, show the value mapped on to the output range 50 to 100
      print(math.map_range(-25, -100, -50, 50, 100))
      125.0

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2124

      math.max(... values)

      Returns the maximum numeric value amongst the arguments given.

      Parameters:

      1

      ...

      Varargs of number values

      Returns:

      1. number max value

      Example:

      print(math.max(12, 10, 14, 3, 8, 13))
      14

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2150

      math.min(... values)

      Returns the minimum numeric value amongst the arguments given.

      Parameters:

      1

      ...

      Varargs of number values

      Returns:

      1. number min value

      Example:

      print(math.min(12, 10, 14, 3, 8, 13))
      3

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2158

      math.modf(number input value)

      Returns the integral part of the supplied value and the fractional part of the supplied value.

      Parameters:

      1

      number

      input value

      Returns:

      1. number integral value
      2. number fractional value

      Example:

      print(math.modf(5))
      print(math.modf(5.4))
      5    0.0
      5    0.4

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2166

      math.normalize(number value, [number minimum], [number maximum])

      Scales a supplied value to between supplied minimum and maximum values.

      Parameters:

      1

      number

      value

      2

      number

      optional, default value=0

      minimum

      3

      number

      optional, default value=1

      maximum

      Returns:

      1. number normalized value

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2177

      math.pow(number x, number y)

      Returns the first supplied number value to the power of the second supplied number value.

      Parameters:

      1

      number

      x

      2

      number

      y

      Returns:

      1. number x ^ y

      Example:

      print(math.pow(2, 4))
      16.0

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2190

      math.rad(number degree value)

      Converts the supplied angle in degrees into an angle in radians. See also math.deg.

      Parameters:

      1

      number

      degree value

      Returns:

      1. number value in radians

      Example:

      print(math.rad(180))
      3.1415926535898

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2199

      math.random([number first limit], [number second limit])

      Provides an interface to the pseudo-random number generator provided by ANSI C. This function returns a random number between two optionally-supplied limits. If no arguments are supplied, those limits are 0 and 1. If one argument a is supplied, those limits are 1 and a. If two arguments a and b are supplied then those limits are a and b.
      If no arguments are supplied the returned value is real, whereas if any arguments are supplied the returned value is an integer.
      Note that use of this function is discouraged, as it will generate different results on different clients in a multiplayer game. Acting upon the result of this function in multiplayer scripts will likely cause desyncs.

      Parameters:

      1

      number

      optional, default value=nil

      first limit

      2

      number

      optional, default value=nil

      second limit

      Returns:

      1. number random number

      Example:

      print(math.random())        -- returned value will be 0..1
      print(math.random(10))        -- returned value will be 1..10
      print(math.random(5, 10))        -- returned value will be 5..10
      0.84018771676347
      4
      9

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2207

      math.randomseed(number seed)

      Sets the supplied value as the seed for the random number system.

      Parameters:

      1

      number

      seed

      Returns:

      1. nil

      Example:

      math.randomseed(os.clock()))        -- use os clock as random seed

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2222

      math.round(number input)

      Returns the nearest integer value to the supplied number.

      Parameters:

      1

      number

      input

      Returns:

      1. number rounded output

      Example:

      print(math.round(10.49))
      print(math.round(10.51))
      print(math.round(-10.49))
      print(math.round(-10.51))
      10
      11
      -10
      -11

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2228

      math.sin(number value)

      Returns the sine of the supplied radian value.

      Parameters:

      1

      number

      value

      Returns:

      1. number sine value

      Example:

      print(math.sin(0.5235987755983))
      0.5

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2245

      math.sinh(number value)

      Returns the hyperbolic sine of the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number hyperbolic sine value

      Example:

      print(math.sinh(0.5235987755983))
      0.54785347388804

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2253

      math.sqrt(number value)

      Returns the square root of the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number square root value

      Example:

      print(math.sqrt(4))
      2.0

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2261

      math.tan(number value)

      Returns the tangent of the supplied radian value.

      Parameters:

      1

      number

      value

      Returns:

      1. number tan value

      Example:

      print(math.tan(0.64350110879328))
      0.74999999999999

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2269

      math.tanh(number value)

      Returns the hyperbolic tangent of the supplied value.

      Parameters:

      1

      number

      value

      Returns:

      1. number hyperbolic tan value

      Example:

      print(math.tanh(0.64350110879328))
      0.56727870240097

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2277

      math.to_bool(value data)

      Converts the given data to a boolean. Only "nil" and "false" will return false.

      Parameters:

      1

      value

      data

      Returns:

      1. boolean true or false

      Example:

      to_bool(nil)
      to_bool(false)
      to_bool(1)
      to_bool(0)
      to_bool({5})
      to_bool({})
      to_bool("string")
      to_bool("")
      false
      false
      true
      true
      true
      true
      true
      true

      defined in ../../Warhammer/working_data/script/_lib/lib_lua_extensions.lua, line 2284

      Variables in this section:

      These variables may be accessed via <interface>.<variable_name>:

      pi number Value of Pi.
      huge number The value HUGE_VAL, a value equal to or larger than any other numerical value.
Last updated 8/23/2024 4:55:16 PM