This page describes the functions native to LuaXP--those that are implemented within LuaXP itself. LuaXP permits user-defined functions to be defined as well. See the LuaXP Overview page for a description of that process.

## Arithmetic Functions

### abs( n )

The abs() function returns the absolute value of its argument.

### sgn( n )

The sgn() function takes a single numeric argument, and returns -1 if it is negative, 0 if it is 0, or 1 if it is positive.

### floor( n )

The floor() function takes a single numeric argument and returns the largest previous following integer. For example, floor( 1.2 ) returns 1, floor( 3.8 ) returns 3, and floor( -1.5 ) returns -2.

### ceil( n )

The ceil() function is the complement of floor(), and returns the smallest following integer. For example, ceil( 1.2 ) return 2, ceil( 3.8 ) return 4, and ceil( -1.5 ) returns -1.

### round( n, prec )

The round() function takes a numeric argument and a number of digits precision. It returns a number rounded to that number of digits. For example, round( 1.2, 0 ) returns 1.0, round( 1.5, 0 ) returns 2.0, round( 1.77, 1 ) returns 1.8, round( 3.14159, 2 ) returns 3.14, and round( 3.14159, 4 ) returns 3.1416.

### cos( n ), sin( n ), tan( n ), asin( n ), acos( n ), atan( n )

These functions perform their respective trigonometric functions on a single argument. The cos, sin, and tan functions take their arguments in radians.

### rad( d ), deg( r )

These functions convert degrees to radians or radians to degrees, respectively.

### log ( n ), exp( n )

The log() function returns the base *e* logarithm of its argument. The exp() function is its complement, returning *e* to the power of the function argument. In other words, log(exp(7)) = 7, because exp(7) = e^{7}, and log( e^{7} ) = 7.

### pow( b, n )

The pow() function raises a base *b* to the power *n*. So pow( 10, 3 ) = 10^{3} = 1000.

### sqrt( n )

The sqrt() function simply returns the square root of its argument.

### min( ... ), max( ... )

The min() and max() functions return the smallest or largest, respectively, numeric argument. Any argument may be an array, in which case the contents of the array is scanned. Several arrays, or a mix of arrays and numbers, are permitted. At least one argument or array element must be numeric, otherwise the function will return **null**.

### random( [[min,] max] )

The random() function, if given no arguments, will return a random real number between 0.0 and 1.0. With a single argument, the number returned will be a random integer in the range of 1 to the argument value (inclusive). With two arguments, the number returned will be a random integer between the first argument and the last.

### randomseed( value )

The randomseed() function seeds the random number generator. If not seeded, the random number generator will generate the same sequence of random numbers upon each run of the containing program. Using randomseed() therefore improves the quality of random numbers generated by altering this predictable behavior. The most common seed is the current time in seconds, like this: randomseed( time() )

## String Functions

### len( s )

The len() function returns the length of its string argument. The empty string ("") has length 0.

### sub( s, i, j )

The sub() function returns a substring of s from its *i*th character to its *j*th, inclusive.

### find( s, m )

The find() function returns the position of the first occurrence of the string *m* in string *s*. For example, find( "iron man", "man" ) returns 6. Zero is returned if the string is not found.

### replace( s, m, r )

The replace() function replaces all occurrences of string *m* with string *r* throughout string *s*. For example, replace( "Float your boat", "oat", "ic" ) returns "Flic your bic".

### upper( s ), lower( s )

The upper() and lower() functions convert a string to all uppercase or lowercase, respectively.

### trim( s ), ltrim( s ), rtrim( s )

The ltrim() function removes leading spaces from its string argument. The rtrim() function removes trailing spaces. The trim() function removes both leading and trailing spaces.

### tostring( a )

The tostring() function converts its argument to a string. Boolean values are converted to the strings "true" or "false" as need be.

### tonumber( a [, b] )

The tonumber() function converts its argument to a number, if possible. It returns the null value if the value could not be converted. The optional *b* argument is the base to be used in conversion. For example, tonumber("c1", 16) returns 193.

### format( s, ... )

The format() function is a direct pass-through to the Lua string.format() function, which itself is largely handled by C sprintf() in many implementations. See the Lua string.format() documentation in the Lua Reference for more information.

### split( s [, separator] )

The split() function takes a string, splits it at the separator pattern (comma "," by default), and returns an array of the substrings. For example, split( "A/B/C", "/" ) results in an array of three elements ([ 'A', 'B', 'C']). An empty string ("") returns a zero-length array. A string that has no occurrences of the separator returns an array of one element that contains the entire string.

Note that separator is a Lua pattern, so splitting certain characters that have special meaning in Lua patterns (like plus "+" which means one or more occurrences of the previous pattern character) must be escaped using the pattern escape character ("%"). For example, to split on a plus ("+") sign, use "%+"; to split on a percent sign, the separator must be given as "%%".

### Time/Date Functions

### time( [ s ] )

The time() function, with no arguments, returns the current time and date expressed as a Unix timestamp.

If a string is passed, time() attempts to convert the string to a date/time. If no date components are given, the current year, month, and day are assumed. If no time components are given, midnight (00:00:00) is assumed. Conversion is done to the runtime's current timezone, unless a timezone offset is given in the string. The time parser, like LuaXP itself, is intended to be simple, and will not parse every imaginable form a user might come up, or even may commonly be used in other system. For example, it does not understand the words "today" or "tomorrow". But it will handle the most common forms of ISO 8601 dates (2017-10-11T12:44:00-0500), as well as common forms like "July 4, 1776", "4-Jul", and "8/1/2015". Where the order of month and day may be ambiguous internationally (is 8/1/2015 August 1st or January 8th?), the parser will attempt to use the semantics of the runtime's locale to determine which to use.

The string may end with a relative time offset (not a timezone offset, but an offset provided over and above the timezone semantics) in the form [+|-][[[days:]HH:]MM:]SS, separated from the rest of the date string by a leading space, to offset the specified number of seconds, with optional minutes, hours, or days. For example, +1:00:00:00 would advance the parsed time 1 day. There are no limits to any component, so an offset of one hour could be written as 3600 or 60:00 or 1:00:00.

### date( [ year [, month [, day [, hours [, mins [, secs ] ] ] ] ] ] )

The date() function constructs a date and time (as a Unix timestamp; see time() above) from the current date and time (in the system's local time zone), replacing any specified part. For example, date( 2099 ) would return the Unix timestamp for the current month, day, and time of day in the year 2099. Midnight of the current day would be retrieved by date( null, null, null, 0, 0, 0 ).

### dateadd( d, sec[, min[, hours[, days[, months[, years]]]]] )

The dateadd() function modifies a specified date/time *d* by the amount passed in the remaining parameters. Only the *sec* parameter is required; the remainder are optional. The offsets of each parameter occur in the units corresponding to their name/place. Their effective is cumulative, and each may be independently positive or negative, and their range is not bound by "calendar limits" (that is, *hours* need not be 0 to 23, *month*s need not be 1 to 12). It is therefore possible to, for example, advance a date by two days by specifying *hours* as 24 and *days* as 1.

### datediff( d1, d2 )

The datediff() function returns the difference, in seconds, between two timestamps. While this could be done by simple subtraction, that would first require the user to make sure both operands are timestamps. The datediff() function accepts timestamps or date/time strings, and provides conversion as needed.

### timepart( [ time, [ utc ] ] )

This function returns a table with keys year, month, day, hour, min, sec and isdst (i.e. the table returned by Lua's os.date() function) for the given time, which is optional (current time is used, if not specified). If the utc argument (boolean, optional) is true, the time parts will be for UTC; otherwise, they are in the system locale's timezone.

### strftime( format[ , timestamp] )

The strftime() function formats a timestamp (or the current time if the *timestamp* argument is not passed). The formatting rules are exactly those provided by Lua os.date(). Refer to the Lua reference for details.

## Miscellaneous Functions

### if( condexp, truexp[, falsexp ] )

The if() function examines the result of the expression condexp, and if *true*, the function evaluates and returns the result of truexp, and otherwise the result of falsexp, or *null *if falsexp is not provided. For example, if( weather.tempunit=="C", weather.temp*9/5+32, weather.temp ) returns a temperature in Fahrenheit degrees, whether it is given in Fahrenheit or Celsius in the source data. That is, if the unit of temperature is C, return the conversion from C to F; otherwise return the temperature as given.

An important feature of this function is that truexp is only run if the result of condexp is *true*, and falsexp is only run if condexp is *false *(aka short-circuit evaluation).

### choose( index, default, v1[, ... ] )

The choose() function will return the *index*th value from the argument list. If *index* is less than 1 or more than the number of values passed, the *default* value is returned. This is useful for mapping numeric values in data to strings, for example.

### select( table, key, keyval )

The select() function returns the first value in *table* having a *key* with value *keyval*. It is equivalent to the jQuery $("[attribute=value]") selector. Consider this JSON fragment:

{ "rooms": [ { "id": 29, "name": "Family Room", "alt": "Great Room" }, { "id": 17, "name": "Kitchen", "alt": "Kueche" } }

By providing this (parsed) data in the passed context, we could locate the Kitchen object using select( rooms, "name", "Kitchen" ). The select function will return the first matching object where name=="Kitchen".

### keys( table )

The keys() function returns an array of the keys in *table*.

### iterate( table, expr [, ename] )

The iterate() function iterates over all of the top-level elements of table, and applies expr (an expression) to each. If the ename (string) argument is given, the current table element will be available by that name in the expression. If it is not given, the current element is available in the default identifier "_". The return value of the iterate() function is an array of the result values of the evaluated expressions. For example, iterate( list( 1, 2, 3 ), i*2, "i" ) will return an array containing 2, 4, 6. The same result could be achieved by writing iterate( list( 1, 2, 3 ), _*2 ) (ename not given).

The expr argument may be an expression (as shown in the above examples), or a string containing an expression. The latter (string) is the old way, and still works, but has the disadvantage of deferring parsing and syntax-checking of the expression, so errors in syntax may not be reported when the enclosing expression that uses iterate() is "compiled"--they'll be reported when iterate() runs. The direct syntax as shown in the above examples is therefore now preferred.

### void( expr )

The void() function returns **null** no matter its argument. It is a utility function intended to be used with iterate(), to discard the function values if they are not needed.

### first( array ), last( array )

The first() and last() functions return the first and last elements of an *array*, respectively. The array is not modified. If the array is empty, they return **null**. They are roughly equivalent to array[1] and array[#array], except that these expressions would throw an error if the array was empty (i.e. contained no elements), where first() and last() do not.

### list( [ arg1 [ , ... ] ] )

The list() function returns an array of its arguments. If given no arguments, it will return an empty list.

### join( array [, separator ] )

The join() function converts the *array *to a string. For example, join( list( 1,2,3), ":" ) results in the string "1:2:3". If the separator is not given, comma is used. See also split() (string function).

### indexof( array, item [, startpos ] )

The indexof() function searches an array for the item, and returns its index in the array. The optional startpos argument allows the search to commence from an array element other than the first.