Lua

Reference ❯ Tables, Strings, Math and Time

Overview

For Loops Overview top ↑

You can use for loops in Lua to iterate over arrays and tables, performing tasks for each element.

This example simply iterates i over the values 1 to 10

-- Iterate from 1 to 10
for i = 1, 10 do
    print( i )
end

This example uses the ipairs function to sequentially iterate over a table. Note that ipairs only works on tables that have sequential elements beginning at 1.

-- Iterate over an array named 'arr'
arr = { 3, 2, 1 }

for i,v in ipairs(arr) do
    print( "arr["..i.."] = "..v )
end

-- Prints:
--  arr[1] = 3
--  arr[2] = 2
--  arr[3] = 1

This example uses pairs to iterate over all the key/value pairs in a table, unlike ipairs the keys do not have to be integral values, and can be anything.

-- Iterate over a table named 'tab'
tab = { x = 3, y = "string", z = 1 }

for key,value in pairs(tab) do
    print( "tab."..key.." = "..value )
end

-- Prints:
--  tab.y = string
--  tab.x = 3
--  tab.z = 1

Conditionals Overview top ↑

Use conditionals to test for a particular circumstance and then branch your code appropriately. See the examples below.

-- Check if x is equal to 10
if x == 10 then
    print( "x equals 10" )
end

-- else and elseif
if x == 10 then
    print( "x is 10" )
elseif x == 5 then
    print( "x is 5" )
else    
    print( "x is something else: "..x )
end

-- Checking multiple values
if x == 10 and y < 5 then
    print( "x is 10 and y is less than 5" )
elseif x == 5 or y == 3 then
    print( "x is 5 or y is 3" )
else
    print( "x is "..x.." and y is "..y )
end

Language

ipairs( table ) top ↑

Syntax

for i,v in ipairs( t ) do body end

-- This will iterate over the pairs:
--   (1,t[1]), (2,t[2]), ...    

ipairs can be used to iterate over a table sequentially, starting from the index 1 and continuing until the first integer key absent from the table. Returns three values: an iterator function, the table, and 0.

table

table to iterate over

Returns

Returns three values: an iterator function, the table, and 0

pairs( table ) top ↑

Syntax

for k,v in pairs( t ) do body end

-- This will iterate over all key-value
-- pairs in table t

pairs can be used to iterate over a tables key-value pairs. Returns three values: the next function, the table t, and nil.

table

table to iterate over

Returns

Returns three values: the next function, the table t, and nil

Tables

table.concat( table, sep ) top ↑

Syntax

table.concat( table )
table.concat( table, sep )
table.concat( table, sep, i )
table.concat( table, sep, i, j )

Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ... sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.

table

table to concatenate

sep

separator string

i

int, starting index to concatenate from

j

int, ending index

Returns

A string of the elements in table concatenated with each other, separated by sep

table.insert( table, pos, value ) top ↑

Syntax

table.insert( table, value )
table.insert( table, pos, value )

Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t.

table

table to insert into

pos

int, position to inset

value

value to insert

table.maxn( table ) top ↑

Syntax

table.maxn( table )

Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)

table

table to query

Returns

Largest positive numerical index of the given table

table.remove( table, pos ) top ↑

Syntax

table.remove( table )
table.remove( table, pos )

Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.

table

table to insert into

pos

int, position of value to remove

Returns

Value of the removed element

table.sort( table ) top ↑

Syntax

table.sort( table )
table.sort( table, comp )

Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

table

the table to sort

comp

a function that receives two table elements and returns true when the first is less than the second

Strings

string.find( s, pattern ) top ↑

Syntax

string.find( s, pattern )
string.find( s, pattern, init )
string.find( s, pattern, init, plain )

Looks for the first match of pattern in the string s. If it finds a match, then string.find() returns the indices of s where the occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search, its default value is 1 and can be negative. A value of true as the fourth optional argument plain turns off the pattern matching facilities so the function performs a plain "find substring" operation, with no characters in pattern being considered "magic." Note that if plain is given, then init must be given as well.

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

s

string to search in

pattern

pattern to look for

init

starting character in string to search from, default is 1

plain

boolean, perform a plain substring search

Returns

The start and end indices of the match, or nil if no match. If the pattern has captures then captured values are also returned after the indices

string.format( formatstring, ... ) top ↑

Syntax

string.format( formatstring, ... )

Returns a formatted version of its variable arguments following the description given in the first argument, which must be a string. The format string follows the same rules as the printf family of standard C functions. The only difference are that the options/modifiers *, 1, L, n, p and h are not supported and that there is an extra option q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter, for example all double quotes, newlines, embedded zeros and backslashes will be escaped when written.

formatstring

string defining the format

Examples

s = string.format("Number is %d", 5) print( s ) -- prints "Number is 5"

Returns

A formatted string

string.len( s ) top ↑

Syntax

string.len( s )

Receives a string and returns its length. The empty string "" has length 0.

s

get the length of this string

Returns

Length of string s

string.lower( s ) top ↑

Syntax

string.lower( s )

Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged.

s

get a lowercase version of this string

Returns

Lowercase version of string s

string.upper( s ) top ↑

Syntax

string.upper( s )

Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged.

s

get an uppercase version of this string

Returns

Uppercase version of string s

string.match( s, pattern ) top ↑

Syntax

string.match( s, pattern )
string.match( s, pattern, init )

Looks for the first match of pattern in the string s. If it finds one then string.match() returns the captures from the pattern, otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third optional numerical argument init specifies where to start the search. Its default is 1 and can be negative.

s

string to search

pattern

pattern to match

init

starting location in string

Returns

Captures from the first match of pattern in string s, or nil if none were found

string.rep( s, n ) top ↑

Syntax

string.rep( s, n )

Returns a string that is the concatenation of n copies of the string s.

s

string to replicate

n

int, number of times to replicate the string

Returns

n concatenations of string s

string.sub( s, i, j ) top ↑

Syntax

string.sub( s, i )
string.sub( s, i, j )

Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

s

find substring of this string

i

int, starting index

j

int, ending index

Returns

Substring of string s

Math

math.abs( value ) top ↑

Syntax

math.abs( value )

This function returns the absolute value of value. For example, math.abs(-5) returns 5.

value

int or float, the number to get the absolute value of

Returns

The absolute value of value

math.acos( value ) top ↑

Syntax

math.acos( value )

This function returns the arc cosine of value in radians

value

int or float, compute the arc cosine of this number

Returns

The arc cosine of value in radians

math.asin( value ) top ↑

Syntax

math.asin( value )

This function returns the arc sine of value in radians

value

int or float, compute the arc sine of this number

Returns

The arc sine of value in radians

math.atan( value ) top ↑

Syntax

math.atan( value )

This function returns the arc tangent of value in radians

value

int or float, compute the arc tangent of this number

Returns

The arc tangent of value in radians

math.atan2( y, x ) top ↑

Syntax

math.atan2( y, x )

This function returns the arc tangent of y/x in radians, but uses the sign of both parameters to find the quadrant of the result. It also handles correctly the case of x being zero.

x

int or float, denominator for arc tangent

y

int or float, numerator for arc tangent

Returns

The arc tangent of y/x in radians

math.ceil( value ) top ↑

Syntax

math.ceil( value )

This function returns the smallest integer larger than or equal to value. This rounds a number up to the nearest integer. For example, math.ceil(5.2) returns 6.

value

int or float, compute the smallest integer larger than or equal to this number

Returns

The smallest integer larger than or equal to value

math.cos( value ) top ↑

Syntax

math.cos( value )

This function returns the cosine of value (assumed to be in radians).

value

int or float, compute the cosine of this number

Returns

Cosine of value

math.cosh( value ) top ↑

Syntax

math.cosh( value )

This function returns hyperbolic cosine of value.

value

int or float, compute the hyperbolic cosine of this number

Returns

Hyperbolic cosine of value

math.deg( value ) top ↑

Syntax

math.deg( value )

This function returns the angle specified by value (given in radians) in degrees.

value

int or float, angle in radians to convert to degrees

Returns

Angle specified by value (in radians) in degrees

math.rad( value ) top ↑

Syntax

math.rad( value )

This function returns the angle specified by value (given in degrees) in radians.

value

int or float, angle in degrees to convert to radians

Returns

Angle specified by value (in degrees) in radians

math.exp( value ) top ↑

Syntax

math.exp( value )

This function returns e raised to value

value

int or float, exponent of e

Returns

e raised to the power of value

math.floor( value ) top ↑

Syntax

math.floor( value )

This function returns the largest integer smaller than or equal to value. This rounds a number down to the nearest integer. For example, math.floorTh(5.7) returns 5.

value

int or float, compute the largest integer smaller than or equal to this number

Returns

The largest integer smaller than or equal to value

math.fmod( x, y ) top ↑

Syntax

math.fmod( x, y )

This function returns the remainder of the division of x by y that rounds the quotient towards zero.

x

int or float

y

int or float

Returns

The remainder of the division of x by y

math.frexp( value ) top ↑

Syntax

math.frexp( value )

This function returns m and e such that value = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).

value

int or float

Returns

m and e such that value = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).

math.ldexp( m, e ) top ↑

Syntax

math.ldexp( m, e )

This function returns m2^e (e should be an integer)

m

int or float

e

int

Returns

m2^e

math.log( value ) top ↑

Syntax

math.log( value )

This function returns the natural logarithm of value

value

int or float, compute the natural logarithm of this value

Returns

The natural logarithm of value

math.log10( value ) top ↑

Syntax

math.log10( value )

This function returns the base-10 logarithm of value

value

int or float, compute the base-10 logarithm of this value

Returns

The base-10 logarithm of value

math.max( value, ... ) top ↑

Syntax

math.max( value, ... )

This function returns maximum value among its arguments.

value

any comparable value

Returns

The maximum value among its arguments

math.min( value, ... ) top ↑

Syntax

math.min( value, ... )

This function returns minimum value among its arguments.

value

any comparable value

Returns

The minimum value among its arguments

math.modf( value ) top ↑

Syntax

math.modf( value )

This function returns two numbers, the integral part of value and the fractional part of value.

value

int or float

Returns

Two numbers, the integral part of value and the fractional part of value

math.pow( x, y ) top ↑

Syntax

math.pow( x, y )

This function returns x raised to y. Equivalent to the expression x^y.

x

int or float

y

int or float

Returns

x raised to y

math.random() top ↑

Syntax

math.random()
math.random( maximum )
math.random( minimum, maximum )

When called without arguments, math.random() returns a uniform pseudo-random real number in the range [0, 1). When called with an integer number maximum, math.random() returns a uniform pseudo-random integer in the range [1, maximum]. When called with two integer numbers, minimum and maximum, math.random() returns a uniform pseudo-random integer in the range [minimum, maximum].

minimum

int, minimum value of returned pseudo-random number

maximum

int, maximum value of returned pseudo-random number

Returns

A uniform pseudo-random real number or integer (depending on parameters)

math.randomseed( value ) top ↑

Syntax

math.randomseed( value )

Sets value as the "seed" for the pseudo-random number generator. Equal seeds produce equal sequences of numbers.

value

int, seed of the pseudo-random number generator

Returns

A uniform pseudo-random real number or integer (depending on parameters)

math.sin( value ) top ↑

Syntax

math.sin( value )

This function returns the sine of value (assumed to be in radians).

value

int or float, compute the sine of this number

Returns

Sine of value

math.sinh( value ) top ↑

Syntax

math.sinh( value )

This function returns hyperbolic sine of value.

value

int or float, compute the hyperbolic sine of this number

Returns

Hyperbolic sine of value

math.tan( value ) top ↑

Syntax

math.tan( value )

This function returns the tangent of value (assumed to be in radians).

value

int or float, compute the tangent of this number

Returns

Tangent of value

math.tanh( value ) top ↑

Syntax

math.tanh( value )

This function returns hyperbolic tangent of value.

value

int or float, compute the hyperbolic tangent of this number

Returns

Hyperbolic tangent of value

math.sqrt( value ) top ↑

Syntax

math.sqrt( value )

This function computes the square root of value. You can also use the expression value^0.5 to compute this value.

value

int or float, compute the square root of this number

Returns

Square root of value

math.huge top ↑

Syntax

math.huge

A value larger than or equal to any other numerical value.

Returns

A value larger than or equal to any other numerical value

math.pi top ↑

Syntax

math.pi

The value of pi.

Returns

Value of pi

Date and Time

os.clock() top ↑

Syntax

os.clock()

Returns an approximation of the amount in seconds of CPU time used by the program.

Returns

Approximation of the amount in seconds of CPU time used by the program.

os.difftime( t2, t1 ) top ↑

Syntax

os.difftime( t2, t1 )

Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1.

t2

Ending time

t1

Starting time

Returns

Number of seconds from time t1 to time t2.

os.date( format ) top ↑

Syntax

os.date()
os.date( format )
os.date( format, time )

Returns a string or a table containing the date and time, formatted according to the given string format.

If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time.

If format starts with '!', then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string '*t', then date returns a table with the following fields: year (four digits), month (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving flag, a boolean).

If format is not '*t', then date returns the date as a string, formatted according to the same rules as the C function strftime.

When called without arguments, date returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date() is equivalent to os.date('%c')).

format

String used to format the returned date

time

If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value).

Returns

A string or a table containing the date and time.

os.setlocale( locale ) top ↑

Syntax

os.setlocale( locale )
os.setlocale( locale, category )

Sets the current locale of the program. locale is a string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or nil if the request cannot be honored.

If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string "C", the current locale is set to the standard C locale.

When called with nil as the first argument, this function only returns the name of the current locale for the given category.

locale

String specifying a locale, can be nil or the empty string.

category

String specifying a category to set, can be "all", "collate", "ctype", "monetary", "numeric", or "time"

Returns

When called with nil for the first argument, returns the name of the current locale for the given category.

os.time() top ↑

Syntax

os.time()
os.time( table )

Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst (for a description of these fields, see the os.date function).

The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to date and difftime.

table

This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst

Returns

A number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to date and difftime.