Integrated Libraries
This category specifies protocols imported from the outside libraries.
WORK IN PROGRESS: This manual is currently being updated and may not contain all the necessary information.
Introduction
The following libraries were implemented:
- eLua bit module - provides basic bit operations
- some functions borrowed from Lua BitOp
- eLua pack module - packing of data into Lua strings and unpacking data from Lua strings
- standard Lua Math library - mathematical functions
- standard Lua Debug library - debugging
- standard Lua String library - functions working with text
- standard Lua Base library functions
Beware, that linked documentation is not always complete and the article tries to link these for cross-reference purposes
Beware, that while the aforementioned libraries are implemented, not all the functions may be enabled. Consult the rest of the article for further details.
eLua Bit Module library
Since Lua doesn't have (yet) built-in capabilities for bit operations, the bit module was added to eLua to fill this gap. It is based on the bitlib library written by Reuben Thomas (slightly adapted to eLua) and provides basic bit operations (like setting and clearing bits) and bitwise operations.
Overview
Function | Short Description | Note |
---|---|---|
bit.bnot | bitwise negation | |
bit.band | bitwise AND | |
bit.bor | bitwise OR | |
bit.bxor | exclusive bitwise OR | |
bit.lshift | logical bitwise left shift | |
bit.rshift | logical bitwise right shift | |
bit.arshift | arithmetic bitwise right shift | |
bit.bit | generate a bit number | |
bit.set | set bits in a number | |
bit.clear | set bits in a number | |
bit.isset | check if the value in bits is set | |
bit.isclear | check if the value in bits is clear |
- Overview
- Arguments
- Returns
- Examples
Bitwise negation, equivalent to ~value in C.
Argument 1: value
- the bitwise to negate
Returns: integer
- the bitwise negated value of the number
Example
print(bit.bnot(0)) --> -1
print(bit.bnot(-1)) --> 0
print(bit.bnot(0xffffffff)) --> 0
- Overview
- Arguments
- Returns
- Examples
Returns bitwise AND of all of its arguments. Note that more than two arguments are allowed.
Argument 1: value 1
Argument 2: value 2
Argument 3(optional): value 3
Argument 4(optional)...
Returns: integer
- the bitwise AND of all the arguments
Example
print(bit.band(1, 2, 4, 8)) --> 0
print(bit.band(0x12345678, 0xff)) --> 120
Lua Script Example
bb=bit.band
function rcntr() local r = bb(g(2)+1) sv(2, r) return b(r) end
- Overview
- Arguments
- Returns
- Examples
Returns bitwise OR of all of its arguments. Note that more than two arguments are allowed.
Argument 1: value 1
Argument 2: value 2
Argument 3(optional): value 3
Argument 4(optional)...
Returns: integer
- the bitwise OR of all the arguments
Example
print(bit.bor(1, 2, 4, 8)) --> 15
print(bit.bor(0x12345678, 0xff)) --> 305420031
Lua Script Example
if nextWR == 1 then
sendFrames(true)
f = b(0xF4) .. rcntr()
i = 1
k = 0
jj = 1
while k == 0 do
B = 0
for j = 0, 7 do
if i > FLen then
k = 1
jj = j
break
end
B = bit.bor(B, bit.lshift(tbi(i), j))
i = i + 1
end
if jj ~= 0 then
f = f .. b(B)
end
end
- Overview
- Arguments
- Returns
- Examples
Returns exclusive bitwise OR of all of its arguments. Note that more than two arguments are allowed.
Argument 1: value 1
Argument 2: value 2
Argument 3(optional): value 3
Argument 4(optional)...
Returns: integer
- the exclusive bitwise OR of all the arguments
Example
print(bit.bxor(1, 2, 4, 8)) --> 15
print(bit.bxor(0x12345678, 0xff)) --> 305419911
Lua Script Example
elseif cmd == 5 then
len = wf("show-length")
idchs = 0
for i=1,len do
_,tmp=pu(wf("show-index", i), "<I")
idchs = bit.bxor(idchs, tmp)
end
- Overview
- Arguments
- Returns
- Examples
Returns the bitwise logical left-shift of its first argument by the number of bits given by the second argument.
Logical shifts treat the first argument as an unsigned number and shift in 0-bits.
Argument 1: value
- the value to be shifted to left
Argument 1: value
- the position we want to shift it to
Returns: integer
- the number shifted left
Example
print(bit.lshift(1, 0)) --> 1
print(bit.lshift(1, 8)) --> 256
print(bit.lshift(1, 40)) --> 256
print(bit.lshift(0x87654321, 12)) --> 1412567040
Lua Script Example
if nextWR == 1 then
sendFrames(true)
f = b(0xF4) .. rcntr()
i = 1
k = 0
jj = 1
while k == 0 do
B = 0
for j = 0, 7 do
if i > FLen then
k = 1
jj = j
break
end
B = bit.bor(B, bit.lshift(tbi(i), j))
i = i + 1
end
if jj ~= 0 then
f = f .. b(B)
end
end
- Overview
- Arguments
- Returns
- Examples
Returns the bitwise logical right-shift of its first argument by the number of bits given by the second argument.
Logical shifts treat the first argument as an unsigned number and shift in 0-bits.
Argument 1: value
- the value to be shifted right
Argument 1: value
- the position we want to shift it to
Returns: integer
- the number shifted right
Example
print(bit.rshift(256, 8)) --> 1
print(bit.rshift(-256, 8)) --> 16777215
print(bit.rshift(0x87654321, 12)) --> 554580
- Overview
- Arguments
- Returns
- Examples
Returns the bitwise arithmetic right-shift of its first argument by the number of bits given by the second argument.
Arithmetic right-shift treats the most-significant bit as a sign bit and replicates it.
Argument 1: value
- the value to be shifted right
Argument 1: value
- the position we want to shift it to
Returns: integer
- the number shifted right
Example
print(bit.arshift(256, 8)) --> 1
print(bit.arshift(-256, 8)) --> -1
print(bit.arshift(0x87654321, 12)) --> 554580
- Overview
- Arguments
- Returns
- Examples
Generate a number with a 1 bit (used for mask generation), Equivalent to 1 << position in C.
Argument: position
- position of the bit that will be set to 1
Returns: integer
- a number with only one 1 bit at position (the rest are set to 0)
Example
print(bit.bit(4)) --> 16
- Overview
- Arguments
- Returns
- Examples
Sets bits in a number.
Argument1:
- the base number
Argument2:
- position of the first bit to set
- note, that the indexing starts at 1 in Lua
Argument3(optional):
- position of the second bit to set
- note, that the indexing starts at 1 in Lua
Argument4...
Returns: integer
- the number with the bit(s) set in the given position(s)
Example
print(bit.set(100,1)) --> 102
print(bit.set(100,1,2,3)) --> 110
Lua Script Example
function makeHeader(finalFlag,messageNum)
local header = getIMEI()
header = header .. framecounter("h")
framecounter("i")
header = header .. pack.pack('b',plport)
header = header .. getSignal()
if(finalFlag == 1)
then
messageNum = bit.set(messageNum,6)
end
header = header .. pack.pack('>b2',0x10,messageNum)
return header
end
- Overview
- Arguments
- Returns
- Examples
Clears bits in a number.
Argument1:
- the base number
Argument2:
- position of the first bit to clear
- note, that the indexing starts at 1 in Lua
Argument3(optional):
- position of the second bit to clear
- note, that the indexing starts at 1 in Lua
Argument4...
Returns: integer
- the number with the bit(s) cleared in the given position(s)
Example
print(bit.clear(100,10,5,1)) --> 68
- Overview
- Arguments
- Returns
- Examples
Tests if a given bit is set - basically opposite of bit.isclear().
Argument 1: value
- the value to test
Argument 2: value
- bit position to test
- note, that the indexing starts at 1 in Lua
Returns: boolean
true
if the bit at the given position is 1, othewisefalse
Example
print(bit.isset(2,0)) --> false
print(bit.isset(1,1111)) --> true
- Overview
- Arguments
- Returns
- Examples
Tests if a given bit is cleared - basically opposite of bit.isset().
Argument 1: value
- the value to test
Argument 2: value
- bit position to test
- note, that the indexing starts at 1 in Lua
Returns: boolean
true
if the bit at the given position is 0, othewisefalse
Example
print(bit.isclear(2,0)) --> true
print(bit.isclear(1,1111)) --> false
Lua BitOp
Lua BitOp is a C extension module for Lua 5.1/5.2 which adds bitwise operations on numbers.
Overview
Function | Short Description | Note |
---|---|---|
bit.tohex | hex string conversion | |
bit.rol | bitwise left rotation | |
bit.ror | bitwise right rotation |
- Overview
- Arguments
- Returns
- Examples
Converts its first argument to a hex string.
The number of hex digits is given by the absolute value of the optional second argument. Positive numbers between 1 and 8 generate lowercase hex digits. Negative numbers generate uppercase hex digits. Only the least-significant 4*|n| bits are used.
The default is to generate 8 lowercase hex digits.
Argument 1: value
- the value that is converted to a hex string
Argument 2(optional): value
- number of hex digits: from -8 to 8
- positive number generates lowercase hex digits
- negative number generates highercase hex digits
Returns: hex string
Example
print(bit.tohex(1)) --> 00000001
print(bit.tohex(-1)) --> ffffffff
print(bit.tohex(0xffffffff)) --> ffffffff
print(bit.tohex(-1, -8)) --> FFFFFFFF
print(bit.tohex(0x21, 4)) --> 0021
print(bit.tohex(0x87654321, 4)) --> 4321
- Overview
- Arguments
- Returns
- Examples
Returns the bitwise left rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side.
Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).
Argument 1: value
- the value that is modified
Argument 2: value
- the number of bits to shift it to the left side
Returns: number
- bitwise left rotation
Example
print(bit.rol(0x12345678, 12)) --> 1164411171
- Overview
- Arguments
- Returns
- Examples
Returns the bitwise right rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side.
Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).
Argument 1: value
- the value that is modified
Argument 2: value
- the number of bits to shift it to the right side
Returns: number
- bitwise right rotation
Example
printx(bit.ror(0x12345678, 12)) --> 1736516421
eLua Pack Module library
This Lua module contains two methods pack.pack for serialization and pack.unpack for deserialization. Both of them use a "format" string to describe how to pack/unpack the data. The format string contains one or more data specifiers, each data specifier is applied to a single variable that must be packed/unpacked. The data specifier has the following general format:
[endianness]<format specifier>[count]
endianness can be chosen based on following table:
Endiannes symbol | Meaning |
---|---|
'<' | little endian |
'>' | big endian |
'=' | native endian (the platform's endian order, default). |
Format can be choosen based on following table:
Format specifier | Corresponding variable type |
---|---|
'z' | zero-terminated string |
'p' | string preceded by length byte |
'P' | string preceded by length word |
'a' | string preceded by length size_t |
'A' | string |
'f' | float |
'd' | double |
'n' | Lua number |
'c' | char |
'b' | byte = unsigned char |
'h' | short |
'H' | unsigned short |
'i' | int |
'I' | unsigned int |
'l' | long |
'L' | unsigned long |
Deserialization
Deserialization can be used for example when you receive data over LoRaWAN/NB and need to separate each byte to proccess the value. This function will extract each byte into separate variable.
nextpos, val1, val2, ..., valn = pack.unpack( string, format, [ init ] )
--string - the string to unpack.
--format - format specifier.
--init - (optional) marks where in string the unpacking should start (1 if not specified).
Lets say, we sent a simple command to the device using 1B, for example 0x01
(send ID) or 0x02
(send current data). We throw away first byte, as it contains value for nextpos and load cmd variable with received command.
received = "02"
--received data as string
toSend = 0
-- Example of an ID
-- instead you can use function to read ID
id = 0x92198717
-- received one byte
_, cmd = pack.unpack(received, "b", 1)
--first byte thrown away, loaded cmd
api.dumpArray(cmd)
--result 02
--show received cmd in console
Serialization
Serialization can be used to send data over LoRa or NB. It will pack multiple variables into single string.
packed = pack.pack( format, val1, val2, ..., valn )
--format - format specifier.
--val1 - first variable to pack.
--val2 - second variable to pack.
--valn - nth variable to pack.
Example of packing six 1B variables into one string in little endian.
-- Example of data
t_hour = 9
t_min = 30
d1 = 0xA1
d2 = 0xC2
d3 = 0xE3
checksum = 0x22
print("Send current data")
toSend = pack.pack("<b6", t_hour, t_min, d1, d2, d3, checksum)
-- at this point, toSend = 0x091EA1C2E322 with format of little endiean byte
api.nbSend(ip, port, toSend, 1000, proto)
api.dumpArray(toSend)
Example of packing mutltiple different data formats into single string
t_hour = 9
t_min = 30
str = "test"
size_t = string.len (str)
d1 = 0xD1 --integer value
d2 = 0x4143eb85 --12.32 in IEEE-754 Floating Point format with big endian
d3 = 0xE3 --integer value
checksum = 22
print("Send current data")
toSend = pack.pack("<b3 <A1 <b1 >f <b1 <b1", t_hour, t_min, size_t, str, d1, d2, d3, checksum)
-- at this point, toSend = \x09\x1E\x04\x74\x65\x73\x74\xD1\xB8\x1E\x45\x41\xE3\x16 with format of little endiean byte
api.dumpArray(toSend)
print(toSend)
Unpacking previous data with python script
from construct import *
input_data = Struct(
"t_hour" / Int8ul,
"t_min" / Int8ul,
"str" / PascalString(VarInt,"utf8"),
"d1" / Int8ul,
"d2" / Float32b,
"d3" / Int8ul,
"checksum" / Int8ul,
)
result = input_data.parse(b'\x09\x1E\x04\x74\x65\x73\x74\xD1\xB8\x1E\x45\x41\xE3\x16')
>>> result.t_hour
9
>>> result.t_min
30
>>> result.str
'test'
>>> result.d1
209
>>> result.d2
12.319999694824219
>>> result.d3
227
>>> result.checksum
22
Lua Math Library
Library used mainly for pre-determined mathematical functions.
Note, that the converters use only integers for mathematical functions, therefore only some of them are available to use.
Overview
Function | Short Description | Note |
---|---|---|
math.abs | absolute value | |
math.huge | returns maximum numerical value | |
math.max | pick the highest value | |
math.min | pick the lowest value | |
math.pow | power | |
math.random | random number | |
math.random | random number with bottom ceiling | |
math.randomseed | seed randomization | |
math.sqrt | square root |
- Overview
- Arguments
- Returns
- Examples
The abs() function in Lua’s math library returns the absolute value of a given number.
Argument: integer
Returns: integer
- the absolute value of the argument
Example
var value = -5
var absValue = math.abs(value)
print(absValue) --> 5
Lua Script Example
function GetTimestamp()
local sign, zone, Y, m, d, H, M, S, z = "", "", api.getTimeDate(1)
if z then
sign, z = z < 0 and "-" or "+", math.abs(z)
- Overview
- Returns
- Examples
This creates a maximum possible number, in our case, a maximum value of an integer.
Returns: integer(2147483647)
Example
var intMax = math.huge
print(intMax) --> 2147483647
- Overview
- Arguments
- Returns
- Examples
The max() function picks a highest value from the individual values specified in the arguments.
Argument 1: integer
Argument 2(optional): integer
Argument 3(optional)...
Returns: integer
- the higherst value of the arguments
Example
var n1 = 54
var n2 = 15
var n3 = 78
print(math.max(n1, n2, n3)) --> 78
Lua Script Example
function Validate(name) return math.max(var[name].min, math.min(var[name].max, api.getVar(var[name].id) or -1)) end
- Overview
- Arguments
- Returns
- Examples
The min() function picks a lowest value from the individual values specified in the arguments.
Argument 1: integer
Argument 2(Optional): integer
Argument 3(Optional)...
Returns: integer
Example
var n1 = 54
var n2 = 15
var n3 = 78
print(math.min(n1, n2, n3)) --> 15
Lua Script Example
function Validate(name) return math.max(var[name].min, math.min(var[name].max, api.getVar(var[name].id) or -1)) end
- Overview
- Arguments
- Returns
- Examples
A number(x) in the first argument raised to the power of a number(y) in the second argument (you can also use x ^ y).
Argument 1: integer Argument 2: integer
Returns: integer
- a number raised to a certain power
Example
var n1 = 54
var n2 = 15
var n3 = 78
print(math.pow(n1, n2, n3))
- Overview
- Arguments
- Returns
- Examples
Creates a random value with the argument being the maximum value and starting at 1 by default.
Note, that api.randInt() is commonly used and ideal to generate random numbers, but this function is also possible.
This api.randInt() is not available on NB-IoT devices, so there you would use this one.
Argument 1: integer
- maximum value the random number can have
Returns: integer
- a random number
Example
print(math.random(10)) --> 1 to 10
- Overview
- Arguments
- Returns
- Examples
Creates a random value, with the arguments being the minimum and maximum value.
Note, that api.randInt() is commonly used and ideal to generate random numbers, but this function is also possible.
This api.randInt() is not available on NB-IoT devices, so there you would use this one.
Argument 1: integer
- minimal value the number can have
Argument 2: integer
- maximal value the number can have
Returns: integer
- a random number
Example
print(math.random(10,120)) --> 10 to 120
- Overview
- Arguments
- Examples
Seeds the random number generator with an integer.
Argument 1: integer
Seeding with os.time() is not possible on our devices.
Example
math.randomseed(44)
print(math.random(10)) --> 1 to 10 based on the seed
- Overview
- Arguments
- Returns
- Examples
Calculates the square root of a number, but converted to an integer.
Argument 1: integer
- a number we want a square root of
Returns: integer
- a square root of a number converted to integer
print(math.sqrt(25)) --> 5
Lua Debug Library
debug.debug()
Enters an interactive mode with the user, creating a breakpoint running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont
finishes this function, so that the caller continues its execution.
Note that commands for debug.debug are not lexically nested within any function and so have no direct access to local variables.
Example
debug.debug()
at("ON_TAU_EVENT",1)
print("on_tau_event turned on")
debug.debug()
at("SLEEP_MONITOR",1)
print("sleep monitor turned on")
Note, that using this function in the interactive mode causes the device to reboot.
- Overview
- Arguments
- Returns
- Examples
Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the debug.sethook function).
Argument 1: table
- The thread we want the settings of.
Returns: values
- the current hook function, the current hook mask, and the current hook count
Example
- Overview
- Arguments
- Returns
- Examples
Returns a table with information about a function. You can give the function directly, or you can give a number as the value of function, which means the function running at level function of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo; and so on. If function is a number larger than the number of active functions, then getinfo returns nil. The returned table can contain all the fields returned by lua_getinfo, with the string what describing which fields to fill in. The default for what is to get all information available, except the table of valid lines. If present, the option 'f' adds a field named func with the function itself. If present, the option 'L' adds a field named activelines with the table of valid lines. For instance, the expression debug.getinfo(1,"n").name returns a table with a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information about the print function.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
This function returns the name and the value of the local variable with index local of the function at level level of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo to check whether the level is valid.) Variable names starting with '(' (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
Returns the registry table.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
Returns the metatable of the given object or nil if it does not have a metatable.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
This function returns the name and the value of the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
Sets the given function as a hook. The string mask and the number count describe when the hook will be called. The string mask may have the following characters, with the given meaning:
"c" the hook is called every time Lua calls a function; "r" the hook is called every time Lua returns from a function; "l" the hook is called every time Lua enters a new line of code.
With a count different from zero, the hook is called after every count instructions. When called without arguments, debug.sethook turns off the hook. When the hook is called, its first parameter is a string describing the event that has triggered its call: "call", "return" (or "tail return", when simulating a return from a tail call), "line", and "count". For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo with level 2 to get more information about the running function (level 0 is the getinfo function, and level 1 is the hook function), unless the event is "tail return". In this case, Lua is only simulating the return, and a call to getinfo will return invalid data.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
This function assigns the value value to the local variable with index local of the function at level level of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call getinfo to check whether the level is valid.) Otherwise, it returns the name of the local variable.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
Sets the metatable for the given object to the given table (which can be nil).
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
This function assigns the value value to the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Returns
- Examples
Returns a string with a traceback of the call stack. An optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback (default is 1, the function calling traceback).
Argument 1: **
- text
Returns: **
- text
Example
Lua String Library
This library enables additional possibilities for working with text - strings and characters.
Overview
Function | Short Description | Note |
---|---|---|
string.byte | character numerical code | |
string.byte | character numerical code | |
string.find | string pattern search | |
string.format | creating formatted strings | |
string.gmatch | ||
string.gsub | replacing substring with a substring | |
string.len | measuring string length | |
string.lower | lowercase conversion | |
string.upper | uppercase conversion | |
string.match | ||
string.rep | repeating a string | |
string.reverse | reversing a string | |
string.sub | extracting a substring | |
string.index |
- Overview
- Arguments
- Returns
- Examples
Returns the numerical code of the first character of the string.
Argument 1: string or character
Returns: integer
- a numerical value of the first character in the argument
Example
print(string.byte('a')) --> 97
- Overview
- Arguments
- Returns
- Examples
Returns the numerical code of the character in the string on a specific position.
Argument 1: string
- string, from which we want to extract a character code
Argument 2: integer
- position of said character
- there is a way to index the character from either side, see examples for details
- note, that the indexing starts at 1 in Lua
Returns: integer
- a numerical value of the character
Example
-- third character
print(string.byte("Lua123",3)) --> 97
-- first character from last
print(string.byte("Lua123",-1)) --> 51
-- second character
print(string.byte("Lua123",2)) --> 117
-- second character from last
print(string.byte("Lua123",-2)) --> 50
Lua Script Example
temper = string.byte(answer, 4)*256+string.byte(answer,5)
humid = string.byte(answer, 6)*256+string.byte(answer,7)
- Overview
- Arguments
- Returns
- Examples
- Patterns
Searches for a specific string or character in a string and returns its position if found.
Argument 1: string
- string I am searching through
Argument 2: string or character
- string or char I am searching for
Argument 3(optional): integer
- the position I want to start the search at
- note, that the indexing starts at 1 in Lua
- deafult is 1
Argument 4(optional): boolean
- whether we want to use pattern matching or not
- default is false
Returns: integer - starting index of the string we search for OR nil if there are no search results
Note, that Lua indexing starts at 1.
That means that index of position e.g. 5 is indeed on fifth position, unlike in most languages, where it would be sixth.
Example
local sentence = 'hello world'
local search1 = string.find(sentence, "hello")
print(search1) --> 1
search1 = string.find(sentence, "world")
print(search1) --> 7
Patterns
. --- (a dot) represents all characters.
%a --- all letters.
%c --- all control characters.
%d --- all digits.
%l --- all lowercase letters.
%p --- all punctuation characters.
%s --- all space characters.
%u --- all uppercase letters.
%w --- all alphanumeric characters.
%x --- all hexadecimal digits.
%z --- the character with hex representation 0x00 (null).
%% --- a single '%' character.
%1 --- captured pattern 1.
%2 --- captured pattern 2 (and so on).
%f[s] transition from not in set 's' to in set 's'.
%b() balanced nested pair ( ... ( ... ) ... )
- Overview
- Arguments
- Returns
- Examples
- Directives
The .format() function is used to create formatted strings by replacing placeholders with specified values.
Argument 1: string
- specification of the string which has dynamic values to be replaced
Argument 2: string, char, integer...
- element to be placed in the first position
Argument 3(optional): string, char, integer...
- element to be placed in the first position
Argument 4(optional)...
Returns: string
- final string with all the values inserted
local name = "Angel"
local height = 5.587
local age = 20
local formatted = string.format("Hello, my name is %s, I am %.1f ft tall and I am %d years old.", name, height, age)
print(formatted) --> Hello, my name is Angel, I am 5.6 ft tall and I am 20 years old.
Lua Script Example
local function ps(id, r, op) p(string.format("%08X",id),op.." @",r) end
Directives can be:
%c
- convert a number to a single character (like string.char)
string.format ("%c", 65) --> A
%d
and%i
- output as an integer number
string.format ("%i", 123.456) --> 123
%o
- convert to octal
string.format ("%o", 16) --> 20
%u
- convert to an unsigned number
Negative numbers will be converted to 4294967296 (2^32) minus the number.
string.format ("%u", 1234.566) --> 1234
string.format ("%u", -1234) --> 4294966062
%x
- hex (lower-case)
string.format ("%x", 86543) --> 1520f
%X
- hex (upper-case)
string.format ("%X", 86543) --> 1520F
%e
- scientific notation, "e" in lower case:
string.format ("%e", 15) --> 1.500000e+001
%E
- scientific notation, "E" in upper case:
string.format ("%E", 15) --> 1.500000E+001
%q
- formats a string in such a way Lua can read it back in (eg. as Lua source).
It puts a backslash in front of the double quote character (hex 22), backslash itself (hex 5C), and newline (hex 0A).
The nul character (hex 00) becomes \000
Carriage return (hex 0D) becomes \r
The string itself is surrounded by double quotes.
For example:
print (string.format ("%q", 'a cat called "Puss"')) --> "a cat called \"Puss\""
%s - output a string (or something that can be converted to a string, such as a number).
%% - output a single % character
- Overview
- Arguments
- Returns
- Examples
Returns an iterator function for returning the next capture from a pattern over a string. If there is no capture, the whole match is produced.
Argument 1: string
- string which you want to match
Argument 2:
Returns:
Example
for word in string.gmatch("Hello Lua user", "%a+") do print(word) end
--> Hello
--> Lua
--> user
Lua Script Example
imsi = ""
function tx(d, tout, rp)
if withIMSI then
if imsi == "" then
local r = at("IMSI?", 5000)
for val in string.gmatch(r, "([0-9]+)") do
imsi = val
end
end
end
- Overview
- Arguments
- Returns
- Examples
Modifies a part of string by replacing it with another string.
Argument 1: string
- string, that needs to have part of it replaced
Argument 2: string
- part of the string, that we want to replace
Argument 3: string
- what we are going to replace it with
Returns: string
- returns a modified string
Example
string = "Lua Tutorial"
-- replacing strings
newstring = string.gsub(string,"Tutorial","Language")
print("The new string is "..newstring) --> The new string is Lua Language
Lua Script Example
local c = string.gsub(str, ".*apiexec:\"([^\"]+)\".*", "%1")
- Overview
- Arguments
- Returns
- Examples
Returns a length of the string in an integer representing the amount of characters it contains.
Argument 1: string
- a string we want to measure
Returns: integer
- how long the string is
Example
local length = string.len("five")
print(length) --> 4
Lua Script Example
function getbytelen(payload) -- generates payload length
local len = string.len(payload)
local lenv = pack.pack('>H', len) -- 'H' stand for unsigned short
return lenv
end
- Overview
- Arguments
- Returns
- Examples
Converts a string to lowercase.
Argument 1: string
- a string we want to convert to lowercase
Returns: string
- a lowercase string
Example
print(string.lower("HELLO")) --> hello
- Overview
- Arguments
- Returns
- Examples
Converts a string to uppercase.
Argument 1: string
- a string we want to convert to uppercase
Returns: string
- an uppercase string
Example
print(string.upper("hello")) --> HELLO
- Overview
- Arguments
- Returns
- Examples
Duplicates and concatenates a string indicated the number of times.
Argument 1: string
- a string to repeat
Argument 2: integer
- the amount of times to repeat Argument 1
Returns: string
- string concatenated the amount of times it was repeated
Example
print(string.rep("hi",3)) --> hihihi
Lua Script Example
function padString(str, length, paddingChar)
local padding = length - #str
if padding > 0 then
return str .. string.rep(paddingChar, padding)
else
return str
end
end
- Overview
- Arguments
- Returns
- Examples
Reverses a string.
Argument 1: string
- a string we want to reverse
Returns: string
- reversed string
Example
print(string.reverse("string")) --> gnirts
- Overview
- Arguments
- Returns
- Examples
Extract a substring from a string.
Argument 1: string
- a string we want to create a substring from
Argument 2: integer
- at what index we want to start cutting the substring
- note, that the indexing starts at 1 in Lua
Argument 3(optional): integer
- at what index we want to end cutting the substring
- note, that the indexing starts at 1 in Lua
- by default, if this argument is not used, the substring is ends the same point as the original
Returns: string
- a cut out string from the original string
Example
print(string.sub("this is a string",8)) --> a string
print(string.sub("this is a string",3,7)) --> is is
Lua Script Example
cnt, req = api.stdin("readuntil", 100) -- maximum 100 characters, read until '\n'
req = string.sub(req,1, -2) -- drop last character - newline
if req == "r" then
print("reset...")
api.nbAT("AT", 2)
elseif req == "w" then
print("wake up...")
api.nbAT("AT", 1)
else
print("> " .. req)
api.nbAT(req)
end
end
Standard Lua Functions
These are the standard Lua functions available on our devices. Unlike the rest of the libraries, they do not require a prefix.
Overview
Function | Short Description | Note |
---|---|---|
assert | specific error trigger | |
collectgarbage | manual garbage collecting | |
error | custom error message | |
gcinfo | current memory use | |
getfenv | current environment table | |
getmetatable | metatable of an object | |
setmetatable | ||
loadstring | compile a piece of code | |
next | key value pair in a table | |
pcall | protected function calling | |
print a string | ||
rawequal | compare two values | |
rawget | get a table value | |
rawset | set a table value | |
select | return an indexed value | |
select | return the argument count | |
setfenv | set environment | |
tonumber | convert to number | |
tostring | convert to string | |
type | return a data type | |
unpack | unpack table | |
xpcall | function with an error handler |
- Overview
- Arguments
- Returns
- Examples
A method that triggers a custom error message when specific condition is met.
Argument 1: boolean
- if this condition is false (or nil), then the error message displays
Argument 2: string
- the error message that gets displayed
Returns: bool
- if false, error message is triggered
Example
n = io.read()
assert(tonumber(n),
"invalid input: " .. n .. " is not a number")
- Overview
- Arguments
- Examples
Allows for manual control of (otherwise automatic) garbage collecting.
Argument 1(optional): string
- by default (no argument), triggers "collect" - one complete cycle of garbage collection
- allows to trigger specific actions based on specific string commands
collectgarbage("collect") -- Runs one complete cycle of garbage collection.
collectgarbage("count") -- Returns the amount of memory currently used by the program in Kilobytes.
collectgarbage("restart") -- If the garbage collector has been stopped, it restarts it.
collectgarbage("setpause") -- Sets the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above.
collectgarbage("setstepmul") -- Sets the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above.
collectgarbage("step") -- Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle.
collectgarbage("stop") -- Stops the garbage collector if its running.
Example
local table = {4,5,5,45}
collectgarbage() -- table is not affected
print(table) --> 4 5 5 45
table = nil
collectgarbage() -- manual disposal of table
- Overview
- Arguments
- Examples
Triggers an error with a custom message.
Argument 1: string
- a message we want to display when the error triggers
Example
var wallet = 10
var withdraw = -11
if withdraw > wallet then
error("You do not have sufficient funds in your wallet, your current credit is "..wallet) -- this error message pops up
end
- Overview
- Returns
- Examples
Returns a value of Kb that are currently in dynamic memory use. Basically the same functionality as collectgarbage("count")
.
Returns: integer
- value in Kb of used dynamic memory
Example
print(gcinfo().." Kb are currently in use") --> 103 Kb are currently in use
- Overview
- Arguments
- Returns
- Examples
Returns the current environment table.
Argument 1(optional): integer
- the default value is 1
- 1 would be the currently running function, 2 is its parent and so on...
Returns: table
- returns the current environment table
- the environment is where "global" variables are stored
Example
funcTable = getfenv(func)
print(funcTable) --> table: 02072780
- Overview
- Arguments
- Returns
- Examples
Returns the metatable for the object.
Argument 1: object
- the metatable of an object
Returns:
- nil if no metatable
- the value of the __metatable field of the metatable, if any
- the metatable of the object
Example
getmetatable(_G) --> nil
- Overview
- Arguments
- Returns
- Examples
Compiles a string of Lua code.
Argument 1: string
- a string to be compiled
Returns: function
- parses the string and returns the compiled chunk as a function, does not execute it
- can be executed by adding
()
after the variable we store the string into
Example
f = loadstring("print 'hello, world'")
f() --> hello, world
- Overview
- Arguments
- Returns
- Examples
Returns next key / value pair in a table.
Argument 1: table
- the table we want ot work with
Argument 2(optional): integer
- if we want to start at a specific index, we specify it here
- note, that the indexing starts at 1 in Lua
Returns: integer and value
- returns the next index
- if index is nil (the default), returns the first pair
- when called with the last index of the table (or with an index of nil for an empty table) it does not return anything
Example
words = { "hello", "world" }
for i, word in next, words do
print (i, word)
end
-->
--[[
1 hello
2 world
]]--
- Overview
- Arguments
- Returns
- Examples
Calls a function in protected mode. Especially useful, if we want the script to keep running despite the potential errors.
Argument 1: **
- text
Returns: **
- text
Example
- Overview
- Arguments
- Prints
- Examples
Prints its arguments to a string, primarily used for feedback.
Argument 1: anything
- prints out argument 1
Argument 2(optional): anything
- prints out argument 2
Argument 3...
Prints: string
- prints all the values as text
- when multiple arguments are passed in, there will we be space between them
Example
print ("Hello", "world", 123, assert) --> Hello world 123 function: 02071C00
Lua Script Example
function onStartup()
buf,err,ack,wake = api.getGUIContext()
print("Starting up LUA interface...")
- Overview
- Arguments
- Returns
- Examples
Compares two values and determines, whether they are equal and returns true
or false
.
Argument 1: value
- first value to be compared with the second one
Argument 2: value
- second value to be compared with the second one
Returns: boolean
- true if the values are equal, else false
Example
print(rawequal(1,0x01)) --> true
Lua Script Example
function onStartup()
buf,err,ack,wake = api.getGUIContext()
print("Starting up LUA interface...")
- Overview
- Arguments
- Returns
- Examples
Gets the value of a table item without invoking metamethods.
Argument 1: table
- the table we want to get the value from
Argument 2: integer
- the index of the value we are trying to get
- note, that the indexing starts at 1 in Lua
Returns: value
- value of a table item without invoking metamethods
Example
local tab = {"hi", "hello", "oi"}
print(rawget(tab,2)) --> hello
- Overview
- Arguments
- Examples
Gets the value of a table item without invoking metamethods.
Argument 1: table
- the table we want to set the value in
Argument 2: integer
- the index of the value we are trying to set
- note, that the indexing starts at 1 in Lua
Argument 3: value
- the new value we are trying to set
Example
local tab = {"hi", "hello", "oi"}
rawset(tab,2,"holla") --> changing hello to holla
print(rawget(tab,2)) --> holla
- Overview
- Arguments
- Returns
- Examples
Returns all the values starting with a specific index.
If I have 4 arguments with value, it would return 2 arguments if I use index of 3.
Argument 1: integer
- at what index does the selection start
- note, that the indexing starts at 1 in Lua
Argument 2: value Argument 3(optional): value Argument 4...
Returns: arguments
- returns all the values starting with the index
- the index can be negative, in such case, it starts with the last value and ends with the first
Example
print(select(1,2,"hi",{4,5,2})) --> 2 hi table: 0x200052c4
print(select(-2,"a","b","c","d")) --> c d
- Overview
- Arguments
- Returns
- Examples
Returns the amount of arguments passed after the operator.
If I have 4 arguments with value, it would return 4.
Argument 1: "#"
- makes the function count the amount of values in the following argument
Argument 2: value Argument 3(optional): value Argument 4...
Returns: integer
- returns the amount of arguments used except the argument 1
Example
print(select("#",2,"hi",{4,5,2})) --> 3
print(select("#","a","b","c","d")) --> 4
- Overview
- Arguments
- Examples
Sets the current environment to be used by f, which can be a function, userdata, thread or stack level. Level 1 is the current function. Level 0 is the global environment of the current thread. The "env" argument is a table, which effectively becomes the "root" for the environment.
Argument 1: function
- can be a function, userdata, thread or stack level
Argument 2: table
- the environment
Example
function f (v)
test = v -- assign to global variable test
end -- function f
local myenv = {} -- my local environment table
setfenv (f, myenv) -- change environment for function f
f (42) -- call f with new environment
print (test) --> nil (global test was not changed)
print (myenv.test) --> 42 (test inside myenv was changed)
- Overview
- Arguments
- Returns
- Examples
Converts the value provided to it into a number.
If this argument is a number or a convertible string, the tonumber() function returns the converted number.
If it is not a number or a convertible string, it will return nil.
Argument 1: value
- the value, we want to attempt to convert to a number
Returns: integer or nil
- returns an integer, when successful, nil when not
Example
mynumber1 = 400
mystring1 = " This is a noncontible string"
mystring2 = "4839"
nilvlaue = nil
tableValue = {2,3,5,"49"};
--will return the original number
print(tonumber(mynumber1)) --> 400
--will return nil because this is inconvertible string
print(tonumber(mystring1)) --> nil
--will return the number equivalent of this string
print(tonumber(mystring2)) --> 4839
--returns nill, because data type nil can't convert
print(tonumber(nilvlaue)) --> nil
--converting the whole of the table will fail
print(tonumber(tableValue)) --> nil
--converting a particular convertible element works
print(tonumber(tableValue[4])) --> 49
- Overview
- Arguments
- Returns
- Examples
Converts a value, usually number, to string.
Argument 1: value
- this is going to get converted to a string data type
Returns: string
- argument 1 turned into a string
Example
a = 45
print(tostring(a))
Lua Script Example
version = 16*tonumber(ver:sub(1,1))+tonumber(ver:sub(-1))
- Overview
- Arguments
- Returns
- Examples
Returns the data type of the argument.
Argument 1: variable or a value
- what we want to find the data type of
Returns: data type
-
returns what data type is the argument:
- nil
- boolean
- number
- string
- function
- table
Example
local tab = {45, "fortyfive", true}
local val = tab[2] --> placing the second value from the table in val variable
print(type(val)) --> string
- Overview
- Arguments
- Returns
- Examples
Unpacks a table into individual values.
Argument 1: table
- the table we want to extract the individual values from
Returns: value
- returns all elements from the given list (table) as individual values
Example
t = { "the", "quick", "brown" }
print (unpack (t)) --> the quick brown
- Overview
- Arguments
- Returns
- Examples
Calls a function with a custom error handler.
If an error occurs in function it is caught and the error-handler is called. Then xpcall returns false, and whatever the error handler returned.
Argument 1: function
- the function we want to call
Argument 2: function
- what we want to happen if the error is caught
Returns: boolean and what the error-handler returned
- when the error is caught, it returns false and whatever it is that error-handler returns
Example
Note that the supplied error function is called before the stack is unwound (in case of error) so this is a good time to find what functions were on the stack leading up to the error. In the example below we use the debug.traceback function, which shows a stack trace as at the time of the error.
function f ()
return "a" + 2 -- will cause error
end -- f
function err (x)
print ("err called", x)
return "oh no!"
end -- err
print (xpcall (f, err))
-->
err called [string "Immediate"]:2: attempt to perform arithmetic on a string value
false oh no!
function f2 ()
return 2 + 2
end -- f
print (xpcall (f, err)) --> true 4
function f ()
return "a" + 2
end -- f
print (xpcall (f, debug.traceback))
-->
false stdin:2: attempt to perform arithmetic on a string value
stack traceback:
stdin:2: in function `f'
[C]: in function `xpcall'
stdin:1: in main chunk
[C]: ?