# Logic Machine Lua reference manual

## Basic Functions

### ipairs(t) top ↑

Returns three values: an iterator function, the table `t`, and 0, so that the construction

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

will iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the first integer key absent from the table

### pairs(t) top ↑

Returns three values: the `next` function, the table `t`, and `nil`, so that the construction

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

will iterate over all key-value pairs of table `t`.

The behavior is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields

### pcall(f, arg1, ...) top ↑

Calls function `f` with the given arguments in protected mode. This means that any error inside `f` is not propagated; instead, `pcall` catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, `pcall` also returns all results from the call, after this first result. In case of any error, `pcall` returns `false` plus the error message.

### require(modname) top ↑

If there is any error loading or running the module, or if it cannot find any loader for the module, then `require` signals an error.

### tonumber(e [, base]) top ↑

Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then `tonumber` returns this number; otherwise, it returns `nil`.

An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter '`A`' (in either upper or lower case) represents 10, '`B`' represents 11, and so forth, with '`Z`' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.

### tostring(e) top ↑

Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use `string.format`.

### type(v) top ↑

Returns the type of its only argument, coded as a string. The possible results of this function are `nil` (a string, not the value nil), `number`, `string`, `boolean`, `table`, `function`, `thread`, and `userdata`.

### unpack(list [, i [, j]]) top ↑

Returns the elements from the given table. This function is equivalent to

``````return list[i], list[i+1], ..., list[j]
``````

except that the above code can be written only for a fixed number of elements. By default, `i` is 1 and `j` is the length of the list, as defined by the length operator.

### toboolean(value) top ↑

Converts given value to boolean using following rules: `nil`, `false`, `0`, `empty string`, `'0' string` are treated as false, everything else as true.

### sleep(delay) top ↑

Delays script execution by the specified number of seconds (can be a fraction).

Adds a message to Alert list. This function behaves exactly as `string.format`.

### log(...) top ↑

Logs any number of variables in human-readable format.

## String Manipulation

### General information top ↑

This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.

The string library provides all its functions inside the table `string`. It also sets a metatable for strings where the `__index` field points to the `string` table. Therefore, you can use the string functions in object-oriented style. For instance, `string.byte(s, i)` can be written as `s:byte(i)`.

The string library assumes one-byte character encodings.

### string.byte(s [, i [, j]]) top ↑

Returns the internal numerical codes of the characters `s[i]`, `s[i+1]`, ..., `s[j]`. The default value for `i` is 1; the default value for `j` is `i`.

### string.char(...) top ↑

Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

### string.find(s, pattern [, init [, plain]]) top ↑

Looks for the first match of `pattern` in the string `s`. If it finds a match, then `find` returns the indices of `s` where this 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 a fourth, optional argument `plain` turns off the pattern matching facilities, so the function does 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.

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

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the `printf` family of standard C functions. The only differences are that the options/modifiers `*`, `l`, `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 Lua: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call

``````string.format('%q', 'a string with "quotes" and \n new line')
``````

will produce the string:

``````"a string with \"quotes\" and \
new line"
``````

The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and `x` all expect a number as argument, whereas `q` and `s` expect a string.

This function does not accept string values containing embedded zeros, except as arguments to the `q` option.

### string.gmatch(s, pattern) top ↑

Returns an iterator function that, each time it is called, returns the next captures from `pattern` over string `s`. If `pattern` specifies no captures, then the whole match is produced in each call.

As an example, the following loop

``````s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
``````

will iterate over all the words from string `s`, printing one per line. The next example collects all pairs `key=value` from the given string into a table:

``````t = {}
s = "from=world, to=Lua"

for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
``````

For this function, a '`^`' at the start of a pattern does not work as an anchor, as this would prevent the iteration.

### string.gsub(s, pattern, repl [, n]) top ↑

Returns a copy of `s` in which all (or the first `n`, if given) occurrences of the `pattern` have been replaced by a replacement string specified by `repl`, which can be a string, a table, or a function. `gsub` also returns, as its second value, the total number of matches that occurred.

If `repl` is a string, then its value is used for replacement. The character `%` works as an escape character: any sequence in `repl` of the form `%*n*`, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence `%0` stands for the whole match. The sequence `%%` stands for a single `%`.

If `repl` is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.

If `repl` is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

Here are some examples:

``````x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"

x = string.gsub("hello world", "%w+", "%0 %0", 1)
--> x="hello hello world"

x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"
``````

### string.len(s) top ↑

Receives a string and returns its length. The empty string `""` has length 0. Embedded zeros are counted, so `"a\000bc\000"` has length 5.

### string.lower(s) top ↑

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

### string.match(s, pattern [, init]) top ↑

Looks for the first match of `pattern` in the string `s`. If it finds one, then `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 value is 1 and can be negative.

### string.rep(s, n) top ↑

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

### string.reverse(s) top ↑

Returns a string that is the string `s` reversed.

### string.split(str, sep) top ↑

Splits string by given separator `string`. Returns Lua `table`.

### string.sub(s, i [, j]) top ↑

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`.

### string.trim(str) top ↑

Trims leading and trailing spaces off a given string.

### string.upper(s) top ↑

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

### Patterns top ↑

#### Character Class:

A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:

• x: (where x is not one of the magic characters `^\$()%.[]*+-?`) represents the character x itself.
• `.`: (a dot) represents all characters.
• `%a`: represents all letters.
• `%c`: represents all control characters.
• `%d`: represents all digits.
• `%l`: represents all lowercase letters.
• `%p`: represents all punctuation characters.
• `%s`: represents all space characters.
• `%u`: represents all uppercase letters.
• `%w`: represents all alphanumeric characters.
• `%x`: represents all hexadecimal digits.
• `%z`: represents the character with representation 0.
• `%*x*`: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a '`%`' when used to represent itself in a pattern.
• `[*set*]`: represents the class which is the union of all characters in set. A range of characters can be specified by separating the end characters of the range with a '`-`'. All classes `%`x described above can also be used as components in set. All ther characters in set represent themselves. For example, `[%w_]` (or `[_%w]`) represents all alphanumeric characters plus the underscore, `[0-7]` represents the octal digits, and `[0-7%l%-]` represents the octal digits plus the lowercase letters plus the '`-`' character.

The interaction between ranges and classes is not defined. Therefore, patterns like `[%a-z]` or `[a-%%]` have no meaning.

• `[^*set*]`: represents the complement of set, where set is interpreted as above.

For all classes represented by single letters (`%a`, `%c`, etc.), the corresponding uppercase letter represents the complement of the class. For instance, `%S` represents all non-space characters.

The definitions of letter, space, and other character groups depend on the current locale. In particular, the class `[a-z]` may not be equivalent to `%l`.

#### Pattern Item:

A pattern item can be

• a single character class, which matches any single character in the class;
• a single character class followed by '`*`', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
• a single character class followed by '`+`', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
• a single character class followed by '`-`', which also matches 0 or more repetitions of characters in the class. Unlike '`*`', these repetition items will always match the shortest possible sequence;
• a single character class followed by '`?`', which matches 0 or 1 occurrence of a character in the class;
• `%*n*`, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);
• `%b*xy*`, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y* where the count reaches 0. For instance, the item `%b()` matches expressions with balanced parentheses.

#### Pattern:

A pattern is a sequence of pattern items. A '`^`' at the beginning of a pattern anchors the match at the beginning of the subject string. A '`\$`' at the end of a pattern anchors the match at the end of the subject string. At other positions, '`^`' and '`\$`' have no special meaning and represent themselves.

#### Captures:

A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern `"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored as the first capture (and therefore has number 1); the character matching "`.`" is captured with number 2, and the part matching "`%s*`" has number 3.

As a special case, the empty capture `()` captures the current string position (a number). For instance, if we apply the pattern `"()aa()"` on the string `"flaaap"`, there will be two captures: 3 and 5.

A pattern cannot contain embedded zeros. Use `%z` instead.

## Table Manipulation

### table.concat(table [, sep [, i [, j]]]) top ↑

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.insert(table, [pos,] value) top ↑

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.maxn(table) top ↑

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.remove(table [, pos]) top ↑

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.sort(table [, comp]) top ↑

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.

## Mathematical Functions

### math.abs(x) top ↑

Returns the absolute value of `x`.

### math.acos(x) top ↑

Returns the arc cosine of `x` (in radians).

### math.asin(x) top ↑

Returns the arc sine of `x` (in radians).

### math.atan(x) top ↑

Returns the arc tangent of `x` (in radians).

### math.atan2(y, x) top ↑

Returns the arc tangent of `y/x` (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of `x` being zero.)

### math.ceil(x) top ↑

Returns the smallest integer larger than or equal to `x`.

### math.cos(x) top ↑

Returns the cosine of `x` (assumed to be in radians).

### math.cosh(x) top ↑

Returns the hyperbolic cosine of `x`.

### math.deg(x) top ↑

Returns the angle `x` (given in radians) in degrees.

### math.exp(x) top ↑

Returns the value ex.

### math.floor(x) top ↑

Returns the largest integer smaller than or equal to `x`.

### math.fmod(x, y) top ↑

Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero.

### math.frexp(x) top ↑

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

### math.huge top ↑

The value `HUGE_VAL`, a value larger than or equal to any other numerical value.

### math.ldexp(m, e) top ↑

Returns m2e (`e` should be an integer).

### math.log(x) top ↑

Returns the natural logarithm of `x`.

### math.log10(x) top ↑

Returns the base-10 logarithm of `x`.

### math.max(x, ...) top ↑

Returns the maximum value among its arguments.

### math.min(x, ...) top ↑

Returns the minimum value among its arguments.

### math.modf(x) top ↑

Returns two numbers, the integral part of `x` and the fractional part of `x`.

The value of pi.

### math.pow(x, y) top ↑

Returns xy. (You can also use the expression `x^y` to compute this value.)

Returns the angle `x` (given in degrees) in radians.

### math.random([m [, n]]) top ↑

This function is an interface to the simple pseudo-random generator function `rand` provided by ANSI C. (No guarantees can be given for its statistical properties.)

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

### math.randomseed(x) top ↑

Sets `x` as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.

### math.round(x [, precision]) top ↑

Returns the rounded value of `x` to specified `precision` (number of digits after the decimal point, value between 0 and 10, defaults to 0).

### math.sin(x) top ↑

Returns the sine of `x` (assumed to be in radians).

### math.sinh(x) top ↑

Returns the hyperbolic sine of `x`.

### math.sqrt(x) top ↑

Returns the square root of `x`. (You can also use the expression `x^0.5` to compute this value.)

### math.tan(x) top ↑

Returns the tangent of `x` (assumed to be in radians).

### math.tanh(x) top ↑

Returns the hyperbolic tangent of `x`.

## Input and Output Facilities

### General information top ↑

Some `io` functions are omitted from this documentation, for full library reference please see Lua 5.1 Reference Manual.

Reads whole file contents, returns `string` on success, or `nil` when file cannot be read.

Executes a process returns process output as a `string` on success, or `nil` when process cannot be executed.

### io.writefile(file, data) top ↑

Overwrites `file` with the given `string` contents, returns `true` on success, or `nil` when file cannot be written.

### io.exists(path) top ↑

Returns `true` when the given path (file or directory) exists, `false` otherwise.

### io.ls(directory) top ↑

Returns `table` with unsorted directory contents, or `nil` when directory is not readable.

### io.stat(path) top ↑

Returns size and modification timestamp of the given path (file or directory). Size and timestamp will be zero when path does not exist.

## Operating System and Date / Time functions

### os.clock() top ↑

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

### os.date([format [, time]]) top ↑

Returns a string or a table containing 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")`).

### os.execute([command]) top ↑

This function is equivalent to the C function `system`. It passes `command` to be executed by an operating system shell. It returns a status code, which is system-dependent. If `command` is absent, then it returns nonzero if a shell is available and zero otherwise.

### os.time([table]) top ↑

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 of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970

### os.microtime() top ↑

Returns two values: current timestamp in seconds and timestamp fraction in microseconds.

### os.udifftime(sec, usec) top ↑

Returns time difference as a floating point value between current timestamp and timestamp components passed to it (seconds, microseconds).

### os.sleep(delay) top ↑

Delays script execution by the specified number of seconds (can be a fraction).

## Object access and control

### General information top ↑

Most functions use alias parameter - either object group address or object name. (e.g. `'1/1/1'` or `'My object'`).

Data types:

• dt.bool - 1-bit boolean
• dt.bit2 - 1-bit controlled number
• dt.bit4 - 3-bit controlled number
• dt.char - 1-byte ASCII character string
• dt.uint8 - 1-byte unsigned integer
• dt.scale - 1-byte unsigned integer [0..100]
• dt.angle - 1-byte unsigned integer [0..360]
• dt.int8 - 1-byte signed integer
• dt.uint16 - 2-byte unsigned integer
• dt.int16 - 2-byte signed integer
• dt.uint24 - 3-byte unsigned integer
• dt.rgb - RGB color, alias of dt.uint24
• dt.float16 - 2-byte floating point number
• dt.time - 3-byte time / day, table with the following fields:
• day - number [0..7]
• hour - number [0..23]
• minute - number [0..59]
• second - number [0..59]
• dt.date - 3-byte date, table with the following fields:
• day - number [1..31]
• month - number [1..12]
• year - number [1990-2089]
• dt.uint32 - 4-byte unsigned integer number
• dt.int32 - 4-byte signed integer number
• dt.float32 - 4-byte unsigned integer number
• dt.int64 - 8-byte signed integer number
• dt.string - 14-byte ASCII string, null characters `'\0'` are discarded during decoding
• dt.text - 250-byte string, cannot be sent to TP bus

### grp.find(alias) top ↑

Returns single object for the given alias. Object value will be decoded if data type is set.

Returns `nil` when object cannot be found, otherwise it returns `table` with the following fields:

• updatetime - latest update time in UNIX timestamp format. Use os.date() to convert to readable date formats
• name - unique object name
• datatype - object data type
• decoded - set to true when decoded value is available
• value - decoded object value

### grp.tag(tags [, mode]) top ↑

Returns `table` containing objects with the given tag. Tags parameter can be either a `table` or a `string`. Mode parameter can be either `'or'` (default — returns objects that have any of given tags) or `'and'` (return objects that have all of given tags). You can use object functions on the returned table.

### grp.dpt(dpt, [strict]) top ↑

Find all objects with matching data type. Dpt can be either a string ("bool", "scale", "uint32" etc) or a field from `dt` table (dt.bool, dt.scale, dt.uint32).

Example: if `dpt` is set to `dt.uint8`: in normal mode all sub-datatypes like `dt.scale` and `dt.angle` will be included. If exact data type match is required, set `strict` to `true`.

### grp.all() top ↑

Returns `table` with all known objects.

### grp.alias(alias) top ↑

Converts group address to object name or name to address. Returns `nil` when object cannot be found.

### grp.getvalue(alias) top ↑

Returns value for the given alias or `nil` when object cannot be found.

### grp.write(alias, value [, datatype]) top ↑

Sends group write request to the given alias. Data type is taken from the database if not specified as the third parameter. Returns boolean as the result.

### grp.response(alias, value [, datatype]) top ↑

Similar to `grp.write`. Sends group response request to the given alias.

Sends group read request to the given alias. Note: this function returns immediately and cannot be used to return the result of read request. Use event-based script instead.

Sends group read request to the given alias or multiple aliases (if `alias` is a Lua table) and waits for a reply. Returns decoded value for a single alias or a Lua table with values for multiple aliases in case of a successful read. Otherwise returns nil plus error message. Default `timeout` is 3 seconds.

### grp.update(alias, value [, datatype]) top ↑

Similar to `grp.write`, but does not send new value to TP bus. Useful for objects that are used only in visualization.

### grp.checkwrite(alias, value [, delta [, status]]) top ↑

Sends group write request to the given alias only when difference between current value and new value is more or equal to the specified delta (non-numeric values use exact comparison, default integer delta 1, default floating point delta is 0.1). Status object value is used for comparison when status object alias is set.

### grp.checkupdate(alias, value [, delta [, status]]) top ↑

Similar to `grp.checkwrite`, but uses `grp.update` for sending.

### grp.checkresponse(alias, value [, delta [, status]]) top ↑

Similar to `grp.checkwrite`, but uses `grp.response` for sending.

### grp.gettags(alias) top ↑

Returns `table` with all tags that are set for the given alias.

Adds single or multiple tags to the given alias. `Tags` parameter can be either a `string` (single tag) or a `table` consisting of strings (multiple tags).

### grp.removetags(alias, tags) top ↑

Removes single or multiple tags to the given alias. `Tags` parameter can be either a `string` (single tag) or a `table` consisting of strings (multiple tags).

### grp.removealltags(alias) top ↑

Removes all tags for given alias.

### grp.settags(alias, tags) top ↑

Overwrites all tags for the given alias. `Tags` parameter can be either a `string` (single tag) or a `table` consisting of strings (multiple tags).

### grp.create(config) top ↑

Creates a new or overwrites an existing object based on provided config, which must be a Lua `table`. Returns object address (`string`) on success, nil plus error message otherwise.

Config fields:

• datatype - object data type. Can be either a string ("bool", "scale", "uint32" etc) or a field from `dt` table (dt.bool, dt.scale, dt.uint32)
• name - unique object name (`string`)
• address - object address (`string` or `number`), when not set the next free address in the range will be used
• virtual - when `address` is not set select which address range to use (`boolean`: `true` to use virtual range, `false` to use standard range)
• tags - object tags, either a `string` (single tag) or a `table` consisting of strings (multiple tags). Overwrites tags for existing objects
• visparams - visualization parameters (`table` or JSON `string`)
• enums - custom values (`table` or JSON `string`)
• forcename - set to `true` to overwrite a name for an existing object
• log - logging policy (`boolean`), default policy is used when not set
• comment - object comments (`string`)
• covincr - BACnet change-of-value increment (`number`), only applicable to numeric data types
• readoninit - send read request on system start (`boolean`), does not apply to virtual objects
• export - export flag (`boolean`)
• pollinterval - poll interval in seconds (`number`), does not apply to virtual objects
• units - object units (`string`)

If an object with the same group address already exists all provided properties except for the object name will be updated. To update the name for an existing object set `forcename` property to `true`.

#### Examples

```-- create new object with known address
datatype = dt.float16,
name = 'My first object',
comment = 'This is my new object',
units = 'W',
tags = { 'My tag A', 'My tag B' },
})
```
```-- create new object with automatic address assignment
datatype = dt.bool,
name = 'My second object',
})
```

## JSON

### General information top ↑

JSON library is not loaded by default, use `require('json')` before calling any functions from this library.

### json.encode(value) top ↑

Converts Lua variable to JSON string. Script execution is stopped in case of an error.

### json.decode(value) top ↑

Converts JSON string to Lua variable. Script execution is stopped in case of an error.

### json.pdecode(value) top ↑

Converts JSON string to Lua variable in protected mode, returns `nil` on error.

## Script control

### script.set(name, status) top ↑

Sets new status (enabled/disabled) for the given script name. You can use `_SCRIPTNAME` variable for scripts that need to disable themselves.

### script.enable(name) top ↑

Enables script, shortcut for `script.set(name, true)`.

### script.disable(name) top ↑

Disables script, shortcut for `script.set(name, false)`.

### script.status(name) top ↑

Returns status (enabled/disabled) for the given script name, or `nil` when script is not found.

### script.categorystatus(category) top ↑

Returns two values: number of enabled and disabled scripts in the given category.

### script.categoryset(category, status) top ↑

Sets new status (enabled/disabled) for all scripts in the given category.

### script.categoryenable(category) top ↑

Enables all scripts in the given category, shortcut for `script.categoryset(category, true)`.

### script.categorydisable(category) top ↑

Disables all scripts in the given category, shortcut for `script.categoryset(category, false)`.

## Script data storage

### General information top ↑

Storage object provides persistent key-value data storage for user scripts. Only the following Lua data types are supported: `boolean`, `number`, `string`, `table`.

### storage.set(key, value) top ↑

Sets new value for the given key. Old value is overwritten. Returns boolean as the result and an optional error string.

### storage.get(key [, default]) top ↑

Gets value for the given key or returns default value (`nil` if not specified) if key is not found.

### storage.delete(key) top ↑

Deletes the given storage key. Returns boolean as the result.

## Scenes

### scene.run(name) top ↑

Run scene by the given name.

### scene.savelive(name) top ↑

Save live values for the given scene name.

### scene.set(name, active) top ↑

Enable/disable scene, this will only disable running the scene by sending a specified value to trigger object. Scene can be still executed via `scene.run()` no matter if it is enabled or not.

### scene.enable(name) top ↑

Shortcut for `scene.set(name, true)`

### scene.disable(name) top ↑

Shortcut for `scene.set(name, false)`

### scene.status(name) top ↑

Returns `true` when scene is enabled, `false` otherwise.

### scene.tagrun(tag) top ↑

Run all scenes having the given tag.

### scene.tagsavelive(tag) top ↑

Save live values for all scenes having the given tag.

### scene.tagset(tag, active) top ↑

Enable/disable all scenes having the given tag.

### scene.tagenable(tag) top ↑

Shortcut for `scene.tagset(tag, true)`

### scene.tagdisable(tag) top ↑

Shortcut for `scene.tagset(tag, false)`

### scene.tagstatus(tag) top ↑

Returns two values: number of enabled and disabled scenes for the given tag.

## Bit operators

### General information top ↑

Bit operation library is built-in and loaded by default. For examples and complete documentation please see Lua Bit Operations Module Functions.

Binary not.

### bit.band(x1 [, x2...]) top ↑

Binary and between any number of variables.

### bit.bor(x1 [, x2...]) top ↑

Binary or between any number of variables.

### bit.bxor(x1 [, x2...]) top ↑

Binary xor between any number of variables.

### bit.lshift(value, shift) top ↑

Left binary shift.

### bit.rshift(value, shift) top ↑

Right binary shift.

## Serial library

### General information top ↑

`require('serial')`

Include library before calling serial functions.

#### Example

```-- RS-485 echo test as a resident script

-- open port on first call
if not port then
require('serial')
port = serial.open('/dev/RS485-1', {
baudrate = 9600,
parity = 'even',
duplex = 'half'
})
port:flush()
end

if port then

-- send back if read succeeded
if char then
port:write(char)
end
end
```

### serial.open(device, parameters) top ↑

`port, err = serial.open(device, parameters)`

Opens given port, returns: port handle, or, in case of error, `nil` plus error message.

Parameters must be a Lua table, default values (in bold) are used when field is not present:

 baudrate 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400 parity "none", "even", "odd" databits 5, 6, 7, 8 stopbits 1, 2 duplex "full", "half" ("half" is required for RS-485)

### serial.write(str) top ↑

`res, err = port:write(str)`

Writes the specified string to the serial port. Returns number of bytes written, or, in case of error, nil plus error message.

`res, err = port:read(bytes, timeout)`

Reads until timeout occurs or the specified number of bytes is received, whichever happens first. Returns data plus number of bytes read, or, in case of error, `nil` plus error message.

### serial.flush() top ↑

`res = port:flush()`

Flushes any read/unsent bytes, returns flush operation result.

### serial.drain() top ↑

`res = port:drain()`

Waits until all output has been transmitted, returns drain operation result.

### serial.close() top ↑

`port:close()`

Closes serial port, no other port functions may be called afterwards.

## Encoding / Decoding library

### General information top ↑

EncDec library is not loaded by default, use `require('encdec')` before calling any functions from this library.

### encdec.md5(str[, raw]) top ↑

Returns md5 hash value of the given string as 32-character hex string or raw binary string if `raw` parameter is `true`.

### encdec.sha1(str[, raw]) top ↑

Returns sha1 hash value of the given string as 40-character hex string or raw binary string if `raw` parameter is `true`.

### encdec.sha256(str[, raw]) top ↑

Returns sha256 hash value of the given string as 64-character hex string or raw binary string if `raw` parameter is `true`.

### encdec.base64enc(str) top ↑

Returns the given string encoded in base64 format.

### encdec.base64dec(str) top ↑

Returns the given string decoded from base64 format, or nothing if string cannot be decoded.

## TCP/UDP socket library

### General information top ↑

For examples and documentation please see LuaSocket: Network support for the Lua language.