Library Functions

Index

The following describes the library functions available for Lua scripts. The functions that cannot be used for the Yamaha router, even though they are available for the standard Lua language, are not included here.

The portion enclosed in a dotted frame in each form can be omitted.

assert
collectgarbage
dofile
each
error
getfenv
getmetatable
ipairs
load
loadfile
loadstring
module
next
pairs
pcall
print
rawequal
rawget
rawset
require
select
setfenv
setmetatable
tonumber
tostring
type
unpack
xpcall
_G
_VERSION
_RT_LUA_VERSION
_RT_LUA_VERSION_NUM
_RT_FIRM_REVISION
_RT_MATH_RANDOM_STATE
arg
string.byte
string.char
string.dump
string.find
string.format
string.gmatch
string.gsub
string.len
string.lower
string.match
string.regexp
string.rep
string.reverse
string.split
string.sub
string.upper

table.concat
table.insert
table.maxn
table.remove
table.sort

math.abs
math.fmod
math.max
math.min
math.random
math.randomseed
io.close
io.flush
io.input
io.lines
io.open
io.output
io.read
io.type
io.write

file:close
file:flush
file:lines
file:read
file:write

bit.band
bit.btest
bit.bor
bit.bxor
bit.bnot
bit.bshift
bit.brotate
rt.command
rt.mail
rt.sleep
rt.syslog
rt.syslogwatch

rt.hw.open
hwd:close
hwd:tone
hwd:on
hwd:blink
hwd:off
hwd:read
hwd:getc
hwd:getchar
hwd:gets

rt.httprequest

rt.socket.tcp
rt.socket.udp
rt.socket.select
rt.socket.dns.toip
rt.socket.dns.tohostname
rt.socket.dns.gethostname
rt.socket.sleep
rt.socket.gettime
rt.socket.newtry
rt.socket.protect
rt.socket.skip
rt.socket._VERSION

tcp:accept
tcp:bind
tcp:listen
tcp:close
tcp:connect
tcp:getpeername
tcp:getsockname
tcp:getstats
tcp:receive
tcp:send
tcp:setoption
tcp:setstats
tcp:settimeout
tcp:shutdown
udp:close
udp:getpeername
udp:getsockname
udp:receive
udp:receivefrom
udp:send
udp:sendto
udp:setpeername
udp:setsockname
udp:settimeout

rt.mime.b64
rt.mime.dot
rt.mime.eol
rt.mime.qp
rt.mime.qpwrp
rt.mime.unb64
rt.mime.unqp
rt.mime.wrp

os.clock
os.date
os.difftime
os.exit
os.getenv
os.remove
os.rename
os.time

package.seeall

coroutine.create
coroutine.resume
coroutine.running
coroutine.status
coroutine.wrap
coroutine.yield

Basic Functions

assert(value , message)

  • value ... Optional type
  • message ... String type

If value is false, that is nil or false, the function issues an error and then stops executing the script. In the other cases, the function returns all the arguments as the return values, and continue executing the script. message is the string displayed in the case of an error. If omitted, the string, "assertion failed!", is displayed.

function f(x,y)
  assert(type(x) == "string") -- Check that the argument is the string type.
  assert(y > 0 and y < 100, "y is out of range") -- Check the value range of the argument. 
  ...
end

collectgarbage(opt , arg)

  • opt ... String type
  • arg ... Numeric type (FIXNUM)

This function controls the garbage collection operation. The following operation is performed according to the string given to the opt.

  • "stop": Stops the garbage collection.
  • "restart": Restarts the stopped garbage collection.
  • "collect": Executes the full garbage collection.
  • "count": Returns the size of the memory used by Lua in kilobytes.
  • "step": Executes only the arg step of the garbage collection. When the garbage collection is completed, true is returned as the return value.
  • "setpause": Sets the pause parameter of the garbage collection. As the return value, the value of the old pause parameter is returned.
  • "setstepmul": Sets the step multiplier parameter of the garbage collection. As the return value, the value of the old step multiplier parameter is returned.

dofile(filename)

  • filename ... String type

Reads the file specified by filename and executes it as a Lua script.

Unlike the standard Lua script, the filename cannot be omitted.


each(arg...)

  • arg ... Optional type

The standard Lua language does not include this function. This function can be used in the firmware with _RT_LUA_VERSION of "1.03" or later.

By using this function together with the generic for statement in a function that returns the iterator function as a return value, you can iterate the arguments.

In a particular case where there is only one argument of the table type, the argument is treated as an array and the elements are iterated in order from the top.

for v in each(1, 2, "a", "b") do
  print(v)
end
t = {1, 2, "a", "b"}
for v in each(t) do
  print(v)
end

error(message , level)

  • message ... String type
  • level ... Numeric type (FIXNUM)

Displays message as an error message and stops executing the Lua script. This function does not return to the caller.

With level, you can control the line number to display as the error location. If you omit the level or assign 1 to the argument, the line where the error function is called is considered the location where the error occurred. If you assign 2 to the argument, the line that called the function calling the error function is considered the error location. Likewise, as the value increases (3, 4, ...), the function call nesting gets deeper. When 0 is assigned, the line of error location is not displayed.

function f1(x) f2(x) end
function f2(x) f3(x) end
function f3(x) f4(x) end
function f4(x)
  if x == 1 then 
    error("", 1) -- error in f4()
  elseif x == 2 then
    error("", 2) -- error in f3()
  elseif x == 3 then
    error("", 3) -- error in f2()
  elseif x == 4 then
    error("", 4) -- error in f1()
  else
    error("", 5) -- error at the top level
  end
end

getfenv(func)

  • func ... Function type or number type (FIXNUM)

If the func is a function, the environment of the function is returned.

If the func is a numerical value, the value is considered the stack level, and the function that returns the environment is specified. This can be summarized as follows:

  • func is 1 ... function calling getfenv
  • func is 2 ... function calling the function calling getfenv
  • func is 3 ... function calling the function calling the function calling getfenv

When the func is 0, the global environment is returned. When the func is omitted, 1 is assumed to be given.


getmetatable(object)

  • object ... Optional type

If the object has not meta table, this function returns nil. If the object has a meta table containing an element having "_metateble" as the key, this function returns the value of the element. In other cases, the meta table of the object is returned.


ipairs(table)

  • table ... Table type

This function returns a set of three items (iterator function, table, 0) as a return value. By using this function with a generic for statement, you can iterate the elements having a numerical value (FIXNUM) as a key in the table.

The following example uses print to display the numerical value keys and their values, (1, t[1]), (2, t[2]), and so on in table t.

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

ipairs is a function for an array, so it cannot retrieve an element having anything other than a numerical value (FIXNUM), such as a string, as the key. This function also cannot retrieve an element having 0 or a negative value as the key. To retrieve all the elements, use the pairs function.


load(func , chunkname)

  • func ... Function type
  • chunkname ... String type

This function uses the func function to load a chunk. The func function returns a string every time it is called. If the func returns an empty string, nil, or nothing, the chunk is considered ended, and the function that is compiled the concatenated all returned strings is returned as the return value of the load. If an error occurs when the chunk is compiled, nil and the string of an error message are returned.

chunkname, as the name of the chuck, is used for an error message and debugging information. When omitted, "=(load)" is used.


loadfile(filename)

  • filename ... String type

This function reads a chunk from the file filename, and returns a function. The return value or other information are the same as those of load.

In the standard Lua language, you can omit filename, but in Lua language implemented in the Yamaha router, you cannot omit filename.


loadstring(string , chunkname)

  • string ... String type

This function handles the string string as a chunk, and returns a function. The meaning or other information of the return value and chunkname are the same as those of load.

The following example shows a typical expression when loading and executing the chunk given by a string.

assert(loadstring(str))()

The string, str, is compiled by loadstring(str) to be made into a function. The reason the assert is used is to capture an error if it occurs in str. With the last parentheses, (), the compiled function is executed.


next(table , key)

  • table ... Table type
  • key ... Optional type

This function returns the key and value of the element next to the element having key as the key in the table table. If the key is omitted or given nil, this function returns the key and value of the first element. If the element having key as the key is the last element in the table, nil is returned.

If next(t) == nil, the table, t, contains no element. This is a useful technique to check if a table is empty or not.

The order of the elements in a table is not defined. Even if the key is a numerical value, the iteration order for next is also not defined. Therefore, you cannot predict in which order the elements are returned by next. To access the keys having numerical values in the order of the numerical values, use ipairs.

When adding a new element to the table while calling next in order, the next behavior of next becomes indefinite. No problem will occur when changing the value of an existing element. Also, there is no problem with the deletion of an element.


pairs(table)

  • table ... Table type

By using this function together with the generic for statement in a function that returns a set of three values (next, table, nil) as a return value, you can iterate the elements in the table.

The following example uses print to display all the elements and keys in the table t.

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

For the notes on changing the table while calling pairs, see next.


pcall(func, ...)

  • func ... Function type

This function calls the function, func, in the protected mode. The rest of the arguments are used for calling f.

In the protected mode, even if an error occurs while func is being executed, the script does not stop executing, and the function notifies the status of the error as the return value of pcall.
(In the normal mode, if an error occurs during the execution of a function, the entire script stops executing.)

If the first return value of pcall is true, no error has occurred during the execution of the func. The pcall returns the return value of the func as the remaining return values.

If the first return value of pcall is false, an error has occurred during the execution of the func. The second return value is an error message.


print(...)

This function receives a user-defined number of arguments and output them to the console, and then breaks a line at the end. The arguments are converted into string representation by the tostring function.

There is no method of controlling the output format of the print function. To output the arguments while controlling the format, combine the string.format function and the io.write function.


rawequal(value1, value2)

  • value1 ... Optional type
  • value2 ... Optional type

This function compares value1 with value2 without using the meta method. The function returns true or false.


rawget(table, key)

  • table ... Table type
  • key ... Optional type

This function returns, without using the meta method, the value (table[key]) of the element having the key of the table, table, as the key.


rawset(table, key, value)

  • table ... Table type
  • key ... Optional type other than nil
  • value ... Optional type

This function assigns, without using the meta method, the value, value, to the element (table[key]) having the key of the table, table, as the key. The return value of the function is table.


select(num, ...)

  • num ... 1 or more in the number type (FIXNUM), or string "#".

For the numerical value N whose num is 1 or more, this function returns the Nth argument from the top of the remaining arguments and all the subsequent ones. If num is the string "#", this function returns the rest of the arguments.

select(3, "a", "b", "c", "d")    => "c", "d"
select("#", "a", "b", "c", "d")  => 4

select is useful when handling a varying number of arguments of a function. The following example passes one by one the arguments of the function f having a varying number of arguments as the arguments of the function g.

function f(...)
  for i = 1, select("#", ...) do
    g((select(i, ...)))
  end
end

setfenv(func, table)

  • func ... Function type or number type (FIXNUM)
  • table ... Table type

If the func is a function, the table is set as the environment of the function.

If the func is a numerical value, the value is considered the stack level, and the function that returns the environment is specified. This can be summarized as follows:

  • func is 1 ... function calling setfenv
  • func is 2 ... function calling the function calling setfenv
  • func is 3 ... function calling the function calling the function calling setfenv

When the func is 0, the global environment is set. When the func is omitted, 1 is assumed to have been assigned.

The return value of setfenv is a function with an environment set. When the global environment is set, no value is returned.


setmetatable(table, metatable)

  • table ... Table type
  • metatable ... Table type

This function sets the meta table, metatable, in the table, table. If metatable is nil, the meta table is deleted from the table. In any case, when the table, table, originally has the meta table and the meta table has the __metatable element, an error occurs.


tonumber(value , base)

  • value ... Optional type
  • base ... Numerical type (2 - 36)

This function converts value to a numerical value. If value is the number type, the value itself is returned. If value is the string type and can be considered the string representation of a numerical value, the numerical value is returned. For the other cases, nil is returned.

base is the base number used for converting a string to a numerical value, and can be specified with anything between 2 and 36. For example, if base is 2, the string is treated as a binary value, if 10 as a decimal, and if 16 as a hexadecimal. If base is omitted, the base number is assumed to be 10.

If a value other than 10 or 16 is specified for base, the return value of the function must fall between -2147483648 and 2147483647. If base is omitted or 10 or 16 is specified, the function can return an optional numerical value that can be represented in the number type.

If a string starts with "0x", it is specially treated. In this case, even if the base number is 10, the string following "0x" is considered hexadecimal. Similarly, when the base number is 16, the portion except for "0x" is considered hexadecimal. When the base number is anything other than 10 or 16, the "0x" at the top of a string is not considered the symbol for representing hexadecimal. Therefore, if the base number is less than 34 and the character "x" does not represent a numerical value, "0x" is not considered a numerical value and thus nil is returned.

a = tonumber(11)       --- a = 11
a = tonumber("11")     --- a = 11
a = tonumber("11", 2)  --- a = 3
a = tonumber("11", 16) --- a = 17
a = tonumber("0x11")   --- a = 17

tostring(value)

  • value ... Optional type

This function converts value into a string in the respective format.

a = tostring(11)  --- a = "11"
a = tostring(true) --- a = "true"
a = tostring(false) --- a = "false"
a = tostring(nil) --- a = "nil"
a = tostring({}) --- a = "table: 00907590"

type(value)

  • value ... Optional type

This function returns the type of value in string representation. The string to be returned for each type is as follows:

  • Number type (FIXNUM) ... "number"
  • Number type (BIGNUM) ... "number", "bignum"
  • String type ... "string"
  • Logical type ... "boolean"
  • nil type ... "nil"
  • Table type ... "table"
  • Function type ... "function"
  • Thread type ... "thread"
  • Userdata type ... "userdata"

unpack(table , i , j)

  • table ... Table type
  • i, j ... Number type (FIXNUM)

This function returns the values, as plural values, of the key elements from i to j in the table table. If i is larger than j, no value is returned. If no value is found for the key, nil is returned.

If i is omitted, 1 is assumed; if j is omitted, a number of elements of a table defined by the length operator # is assumed.

a = { 1, 2, 3 }
print(unpack(a)) --- 1, 2, 3
print(unpack(a, 1, 3)) --- 1, 2, 3
print(unpack(a, 2, 3)) --- 2, 3
print(unpack(a, 3, 3)) --- 3
print(unpack(a, 3, 2)) --- Nothing is displayed.
print(unpack(a, -1, 2)) --- nil, nil, 1, 2

xpcall(func, handler)

  • func ... Function type
  • handler ... Function type

xpcall is similar to pcall. The only difference is that this function can specify an error processing function.

xpcall calls the func function in the protection mode by using handler as an error processing function. If an error occurs during the execution of func, handler is called.

If the first return value of xpcall is true, no error has occurred during the execution of the func. The return value of the func is returned as the second or later returned value of the xpcall.

If the first return value of xpcall is false, an error had occurred during the execution of the func and handler has been called. The second or later returned value of the xpcall is the return value of the handler.


Global Variables

The following table lists the defined global variables.

Variable nameDescriptionExamples of values
_G The copy of the global environment is saved. The Lua itself does not use this variable, and thus operating this function does not affect the environment at all. To change the environment, use setfenv. Copy of the global environment (Table type)
_VERSION String representing the version number of the Lua language. "Lua 5.1"
_RT_LUA_VERSION String representing the version number of the Lua script function for the Yamaha router. "1.0"
_RT_LUA_VERSION_NUM Numerical value representation of _RT_LUA_VERSION. 100
_RT_FIRM_REVISION String representing the firmware revision of the Yamaha router. "RTX1200 Rev.10.01.12 (Fri Jul 31 17:52:51 2009)"
_RT_MATH_RANDOM_STATE User data to show the internal state for the math.random() function. This is defined in the firmware with _RT_LUA_VERSION of "1.01" or later.
arg Table for storing the strings of arguments passed by Lua commands.

String Operation

string.byte(str, i, j)

  • str ... String type
  • i, j ... Number type (FIXNUM)

This function converts the ith through jth characters of the string str into the numerical values of the corresponding internal character codes, and returns the values as plural values.

The beginning of the string is the first character, and if i is omitted, 1 is assumed. If j is omitted, the same value as i is assumed, which means that the return value is only the ith character.

The Lua scripts for the Yamaha router uses ASCII and Shift JIS internal codes for strings.

a, b = string.byte("ab", 1, 2) -- a=97, b=98
a, b = string.byte("ab")       -- a=97, b=nil
a, b = string.byte("ab", 2)    -- a=98, b=nil

string.char(...)

This function returns the string whose length is the same as the number of given arguments and whose internal code is the same as the value of the arguments. The argument must be numeric (FIXNUM), and the number of arguments can be greater than or equal to 0. If the number of arguments is 0, a 0-length string is returned.

The Lua scripts for the Yamaha router uses ASCII and Shift JIS internal codes for strings.

s = string.char(97, 98)   -- s = "ab"
s = string.char()         -- s = ""

string.dump(func)

  • func ... Function type

This function returns a string including the binary representation of the given function. This string can be given as the argument of loadstring, and in that case, the copy of the function can be obtained. The function must be the Lua function that does not have an upper level value.


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

  • str ... String type
  • pattern ... string type or regular expression object
  • init ... Number type (FIXNUM)
  • plain ... Boolean type

This function searches the string, str, from the beginning of the string for part that matches the pattern pattern. When the matched part is found, the function returns two numerical values: the positions of the first and last character of the matched part in the case where the top of the string is 1. If no part matched is found, nil is returned.

If pattern has capture, the captured string is returned as the return value following the two values indicating the positions.

By specifying the third argument, init, you can start searching for the pattern pattern from the initth character, not from the beginning of the string. A negative value can also be specified for init. In that case, the specified character is counted from the end.

If true is specified for the fourth argument plain, pattern is considered a string, not pattern. Therefore, this function searches for a part that matches pattern.

If pattern is a regular expression object, and plain is true, nil is returned.

a, b = string.find("ABCDE", "BC")        -- a=2, b=3
a, b = string.find("ABCDE", "%a*")       -- a=1, b=5
a, b = string.find("ABCDE", /\a*/)       -- a=1, b=5
a, b, c = string.find("ABCDE", "B(.)D")  -- a=2, b=4, c="C"

string.format(format, ...)

  • format ... String type

This function returns a string formatted from the value of the argument according to the instruction of the string format. This function is similar to the sprintf function of the C language.

The format is the string that includes the conversion instruction phrase to convert the remaining arguments to strings. The conversion instruction phrase starts with the percentage mark, %, and ends with the conversion indicator (d, x, X, c, s, q, %, z). The string output by the conversion instruction phrase is called a field. Between the percentage mark and the conversion indicator, a flag, field width, and accuracy can be put in this order.

string.format generates a field by following the instruction while reading format. The strings other than the conversion instruction phrase are output as they are.

If format includes a conversion instruction phrase, this function reads the arguments in order and outputs strings converted as instructed. The conversion instruction phrase requires the arguments of each particular types. If any argument other than these is given, an error occurs.

The flag specifies how to convert arguments. The following flags are available.

  • #
    For 0 conversion, 0 is supplied to the top as needed so that the output result always starts with 0. For x, X conversion, if the value is not 0, 0x or 0X is supplied to the top.
  • 0
    For conversion of a numerical value (d, x, X), fill the left-hand side of the converted value with 0, not with space characters. If the flag 0 and flag - are simultaneously specified, the flag 0 is ignored.
  • -
    The converted string is left-aligned in the field. If this flag is not specified, the string is right-aligned.

Specify a decimal value for the minimum width for the field where the converted string is to be output. If the length of a converted string is shorter than the field width, the left-hand side (right-hand side if the flag - is specified) of the string is filled with space characters or 0. If the length of a string is longer than the field width, the string is output without being truncated.

Specify the accuracy in the format of the period (.) followed by a decimal number. For the conversion of a numerical value (d, x, X), specify the minimum number of digits to be output. For string conversion (s), specify the maximum number of characters to be output from the string.

The conversion indicator includes the following types.

  • d
    This converts a numerical value-type argument into decimal notation.
    In the case of a negative value, add the minus sign, -, to the top.
  • x, X
    This converts a numerical value-type argument into hexadecimal notation.
    or x, use abcdef, and for X, use ABCDEF.
    In the case of a negative value, display the value as a positive value with 4294967296 (decimal) added.
  • c
    This converts a numerical value-type argument into a string having the internal code of the remainder of the argument divided by 256.
  • s
    This outputs a string-type argument from the beginning to the end of the string. If the accuracy is specified, the specified number of characters are output.
  • q
    This outputs a string-type argument from the beginning to the end of the string. At this time, double quotations, line break, NUL characters, and backslashes are appropriately escaped so that the interpreter of the Lua language can read the string.
  • %
    This outputs the character, %. There is no argument to be converted. No flag, field width, or accuracy must be specified. The entire conversion instruction phrase is always in the format of %%.
s = string.format("%d, %x", 10, 10)                    -- s="10, a"
s = string.format("%dab%d", 10, 20)                    -- s="10ab20"
s = string.format("[%4d], [%-4d], [%04d]", 10, 10, 10) -- s="[  10], [10  ], [0010]"

string.gmatch(str, pattern)

  • str ... String type
  • pattern ... string type or regular expression object

For the string str, this function returns the iterator function that returns the capture of the pattern pattern in order every time it is called. If the pattern does not include capture, the return value of the iterator function is the entire string that matches the pattern.

By using string.gmatch with a generic for statement, you can extract and process the portions that match the condition one by one from the string.

The following example extracts words from the string and displays the words, one per line.

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

The following example searches for the strings in the key=value format, and sets them in the table, t.

t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  t[k] = v
end

string.gsub(str, pattern, repl, n)

  • str ... String type
  • pattern ... string type or regular expression object
  • repl ... Any of the string type, table type, and function type
  • n ... Number type (FIXNUM)

For the string str, this function returns new strings that are converted from the portions matching the pattern pattern as instructed by the repl argument, and the number of pattern found. The string str is not changed at all.

If the fourth argument n is specified, only the first n portions found are converted. If omitted, all the portions found are converted.

If repl is the string type, the repl itself is the string to be converted. The following characters in repl have special meanings.

  • %0
    Represents the entire part that matches the pattern.
  • %1~%9
    Represents the string that matches capture in the specified order in the pattern.
  • %%
    Represents the percentage mark itself.

If repl is the table type, the value of the element of repl having the first capture in pattern as the key will be the converted string. If pattern does not include capture, the entire part that matches the pattern is the key.

If repl is the function type, this function calls the repl by using all the captures in pattern as the arguments, and the return value will be the converted string. If pattern does not include capture, the entire part that matches the pattern is the argument.

If repl is the table type or function type, and if the values of the elements in the table or the return value of the function are the string type, the value itself will be the converted string. In the case of the number type (FIXNUM), the value converted into a string will be the converted string.

If the value of the elements in the table or the return value of the function is false or nil, conversion is not performed and the original string remains. Any value other than the above causes an error.

x, y = string.gsub("HELLO world", /o/i, "o")
-- x = "HELLo world", y = 2

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

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

t = { name = "lua", version = "5.1" }
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
-- x = "lua-5.1.tar.gz"

function f(s)
  if s == "hello" then
    return "bye"
  elseif s == "world" then
    return "universe"
  else
    return "unknown"
  end
end
x = string.gsub("hello world", "(%w+)", f) -- x = "bye universe"

string.len(str)

  • str ... String type

This function returns the length of the string str. The "length of a string" is expressed in bytes in the Lua language. The length of an empty string "" is 0.

x = string.len("ABCDE")      -- x = 5
x = string.len("")           -- x = 0

string.lower(str)

  • str ... String type

This function newly creates and returns a string where the upper-case characters in the str string have been converted into lower-case ones. The string, str, itself is not changed at all.

Only the upper-case characters in ASCII are converted. The upper-case characters in Shift JIS are not converted.

x = string.lower("AB01CD")     -- x = "ab01cd"
x = string.lower("AB01CD") -- x = "AB01CD"

string.match(str, pattern, n)

  • str ... String type
  • pattern ... string type or regular expression object
  • n ... Number type (FIXNUM)

This function searches the string, str, from the top for the portion that matches the pattern, pattern. If found any, the function returns all the captures in the pattern. If capture does not exist in the pattern, this function returns the string of the whole part that matches the pattern. If no part is found that matches the pattern, nil is returned.

When the third argument, n, is specified, the function searches for the pattern from the nth character of the str. If omitted, it starts searching from the first character. A negative value can also be specified for n. In that case, the specified character is counted from the end.

If pattern is a regular expression object and if g is specified as the option, this function returns all the non-duplicated matched parts found in the string. In the other cases, only the first matched part is returned.

x = string.match("hello world", "%w+")    -- x = "hello"
x = string.match("hello world", " (%w+)") -- x = "world"
x = string.match("hello world", "%w+", 2) -- x = "ello"
x,y,z,w = string.match("hello world", /\w\w/g) -- x = "he", y = "ll", z = "wo", w = "rl"
x = {string.match("hello world", /\w\w/g)} -- x = { "he", "ll", "wo", "rl" }

string.regexp(str, option)

  • str ... String type
  • option ... String type

This function can be used in the firmware with _RT_LUA_VERSION of "1.03" or later.

This function considers the string, str, as a regular expression, and returns the corresponding regular expression object. The regular expression object can be used as the pattern of the string.find, string.match, string.gmatch, string.gsub, string.split, or rt.syslogwatch function.

If there is a regular expression error in a string, this function returns nil and the string containing the error.

For the string, option, specify the compile option of the regular expression. For the option, specify the combination of any of the following characters.

  • i ... Case-insensitive
  • s ... "." matches the one immediately after the line feed character.
  • x ... Spaces and a portion between "#" and line break in the regular expression are ignored.
  • m ... "^" and "$" matches ones before and after a line feed character in a string.
  • U ... The length specification symbols, such as "*" and "+", try to match the shortest string, while "*?" and "+?" try to match the longest string.

Any character other than above in option will be the option when a regular expression object is used.

You can call the string.regexp function also by writing it as regular expression syntactic sugar.

x = string.regexp("hello", "i")
x = /hello/i

string.rep(str, n)

  • str ... String type
  • n ... Number type (FIXNUM)

This function returns the string consisting of n str strings.

x = string.rep("ab", 5) -- x = "ababababab"

string.reverse(str)

  • str ... String type

This function returns the string of the reversed string, str. Note that a character string in Shift JIS cannot be specified.

x = string.reverse("hello world") -- x = "dlrow olleh"

string.split(str, pattern, n)

  • str ... String type
  • pattern ... string type or regular expression object
  • n ... Number type (FIXNUM)

This function can be used in the firmware with _RT_LUA_VERSION of "1.03" or later.

This function returns the string, str, that is divided at the portion that matches the pattern pattern. The returned string group does not include the portion that matches the pattern.

If the fourth argument, n, is specified, the division is performed the only the first n times. If omitted, all the divisions found are performed.

x = { string.split("hello world", /\s+/) } -- x = { "hello", "world" }

str = "hello world"
for w in each(str:split(/\s+/)) do
    print(w)
end

string.sub(str, i, j)

  • str ... String type
  • i, j ... Number type (FIXNUM)

This function returns the partial string from the ith character to the jth character of the string, str. A negative value can also be specified for i and j. In that case, the specified characters are counted from the end. If j is omitted, -1, which means the end of the str, is assumed.

x = string.sub("ABCDE", 2, 4)  -- x = "BCD"
x = string.sub("ABCDE", 3)     -- x = "CDE"
x = string.sub("ABCDE", 2, -2) -- x = "BCD"
x = string.sub("ABCDE", -2)    -- x = "DE"

string.upper

  • str ... String type

This function newly creates and returns a string where the lower-case characters in the str string have been converted into upper-case ones. The string, str, itself is not changed at all.

Only the lower-case characters in ASCII are converted. The lower-case characters in Shift JIS are not converted.

x = string.upper("ab01cd")     -- x = "AB01CD"
x = string.upper("ab01cd") -- x = "ab01cd"

Pattern

You can use patterns in the string.match or other functions to search for strings. The pattern unique to the Lua language and the regular expression are available.

The regular expression can be used in the firmware with _RT_LUA_VERSION of "1.03" or later.

A pattern consists of a special character having a special meaning and a normal character other than that. A normal character matches the character itself. For example, a matches a itself. For a pattern that does not include special characters, the string itself is searched for in the string searched.

The following shows the special characters used for the patterns.

Lua patternRegular expressionDescriptionSupplemental information
^\A Matches the beginning of a string.
^ Matches the beginning of a string. When the m option is specified, this matches the character immediately after a line feed character.
$\z Matches the end of a string.
$ Matches the end of a string. If the end of a string is a line feed character, this matches the one immediately before it. When the m option is specified, this matches the character immediately before a line feed character in the string.
\Z Matches the end of a string. If the end of a string is a line feed character, this matches the one immediately before it.
\b Matches the boundary of a word.
\B Matches anything other than the boundary of a word.
\G Matches anything that the pattern first matched.
\K The search result obtained before this character appears are not included in the search result that is finally reported.
.
%a
. Matches any one character.
*
-
*
*+
*?
Matches a string with the character immediately before it repeats 0 or more times. *, +, and ? in Lua always match as long a string as possible. - always matches as short a string as possible.
If nothing follows a recursive symbol in the regular expression, this matches as long a string as possible by default, but with the U option specified, as short a string as possible.
If + follows the symbol, this always matches as long a string as possible.
If ? follows the symbol, this matches as short a string as possible by default, but with the U option specified, as long a string as possible.
++
++
+?
Matches a string with the character immediately before it repeats 1 or more times.
??
?+
??
Matches a string with the character immediately before it appears 0 times or once.
{N} Matches a string with the character immediately before it appears exactly N times.
{N,M}
{N,M}+
{N,M}?
Matches a string with the character immediately before it appears N to M times.
{N,}
{N,}+
{N,}?
Matches a string with the character immediately before it appears N or more times.
| Matches a string that matches the pattern of either before or after |.
[...][...] This is a character set consisting of the characters enclosed by square brackets, and matches any one character included in the character set. In the square brackets, you can specify the range of characters by using a minus sign (-) to connect the first character with the last one. To do this, the first and the last characters must be the same type (numerical numbers, uppercase, lowercase).
If the caret (^) is immediately after the opening bracket ([), this matches a character not included in the character set, not one included in it. Therefore, to include a caret (^) in a character set, do not place it at the beginning of the character set.
To include a closing square bracket (]), make sure to place it immediately after the first opening bracket. An opening bracket can be placed anywhere.
For the regular expression, you can also use POSIX character set.
%d\d Matches a numerical value (0-9).
\D Matches anything other than a numerical value (0-9).
%u Matches an uppercase character (A-Z).
%l Matches a lowercase character (a-z).
%w Matches an alphanumeric character (A-Z, a-z, 0-9).
\w Matches an alphanumeric character (A-Z, a-z, 0-9) and an underscore (_).
\W Matches a character other than an alphanumeric character (A-Z, a-z, 0-9) and an underscore (_).
%s Matches a space character (In ASCII code, 0x09 (Horizontal Tab), 0x0a (line break), 0x0b (Vertical Tab), 0x0c (page break), 0x0d (return), 0x20 (space)).
\s Matches a space character (In ASCII code, 0x09 (Horizontal Tab), 0x0a (line break), 0x0c (page break), 0x0d (return), 0x20 (space)).
\S Matches anything other than a space character (In ASCII code, 0x09 (Horizontal Tab), 0x0a (line break), 0x0c (page break), and 0x0d (return), 0x20 (space)).
\h Matches a horizontal space character ((In ASCII code, 0x09 (Horizontal Tab), 0x20 (space)).
\H Matches anything other than a horizontal space character ((In ASCII code, 0x09 (Horizontal Tab), 0x20 (space)).
\v Matches a vertical space character (In ASCII code, 0x0a (line break), 0x0b (Vertical Tab), 0x0c (page break), 0x0d (return)).
\V Matches anything other than a vertical space character (In ASCII code, 0x0a (line break), 0x0b (Vertical Tab), 0x0c (page break), 0x0d (return)).
%x Matches a numerical number (0-9) or an alphabet among A-F and a-z.
%c Matches a control character (In ASCII code, 0x00 - 0x1f, or 0xff).
%p Matches a delimiter (!, ", #, $, %, &, ', (, ), *, +, ,, -, , , ., /, :, ;, >, =, <, ?, @, [, \, ], ^, _, `, {, |, }).
%z Matches a NULL character (In ASCII code, 0x00).
%X, where X is other than an alphanumeric character \X, where X is other than an alphanumeric character Matches the character X itself.
\a Matches an alarm character (0x07).
\cX Matches the control character produced by XOR between the ASCII code of the character X (After being converted to uppercase if X is an alphabet) and 0xC0.
\e Matches the escape character (0x1b).
\f Matches a page break character (0x0c).
\n Matches a line break character (0x0a).
\r Matches a return character (0x0d).
\t Matches a horizontal tab character (0x09).
\DD
\DDD
Matches DD or DDDH in decimal in ASCII code.
\xHH
\x{HH}
Matches HH in hexadecimal in ASCII code.
\R Matches a line break character. This is the same as the following pattern.
(?>\r\n|\n|\x0b|\f|\r|\x85)

%bXY, where X and Y are independent characters. Matches a partial string starting with X and ending with Y. For example, %b() matches a partial string enclosed by parentheses.
(...)(...) Handles the string enclosed by the parentheses as a group. For example, the pattern "(abc)+" matches a string wh22ere the string "abc" repeats once or more times, such as "abcabc" and "abcabcabc". The parentheses can be used as a capture.
%1~%9\1~\9
\gN
\g{N}
Matches a partial string captured. The numerical number represents the number of the capture counted from the beginning of the regular expression.
For the regular expression, N is 1 to 32 or -1 to -32. If N is a positive value, it represents, like in the case of \1, the number of the capture counted from the beginning. If N is a negative value, it represents the relative number of the capture counted from the location in the direction going back toward the front.
To write a capture in the substitute string of the string.gsub function, use %1-%9 even for the regular expression. Reference by \1~\9, \gN, \g{N}, or a name is the representation used only in the regular expression.
(?<NAME>...)
(?'NAME'...)
(?P<NAME>...)
Add a name (NAME) to a partial string to be captured. NAME consists of up to 32 characters including alphanumeric characters and underscores. The name can be used to refer to a capture. You can also specify the number to refer to a named capture.
\k<NAME>
\k'NAME'
\k{NAME}
\g{NAME}
(?P=NAME)
Refers to a named (NAME) capture.
() Captures the location of the string of the place.
(?#...) Treats the contents in the parentheses as a comment.
(?:...) The contents in the parentheses are grouped but not captured.
(?|...) The contents in the parentheses are grouped but not captured. Reset the capture number for each selection (|) in the parentheses.
(?>...) The contents in the parentheses are grouped but not captured. The string that once matched the pattern in the parentheses is not shortened to search for a new matching pattern even if the string does not match other patterns. For example, the string "aab" matches the regular expression, /a*ab/, but not match the regular expression, /(?>a*)ab/.
Usually, even if a* matches "aa", it does not match the remaining regular expression, ab, so the pattern is shortened to "a" to match a* and re-execute matching. However, for /(?>a*), the pattern is not shortened like this.
(?=...) Checks if strings in the forward direction from the searching position matches the pattern in the parentheses. The search is successful only when a match is found. The search result does not include the contents in the parentheses. This is not captured.
(?!...) Checks if strings in the forward direction from the searching position matches the pattern in the parentheses. The search is successful only when no match is found.
(?<=...) Checks if strings in the backward direction from the searching position matches the pattern in the parentheses. The search is successful only when a match is found.
(?<!...) Checks if strings in the backward direction from the searching position matches the pattern in the parentheses. The search is successful only when no match is found.
(?...) By writing an option character between (? and ), this enables the option after the position. Note that after a hyphen (-), if any, the option after the position is disabled. The following shows the available options.
  • i ... Case-insensitive
  • s ... "." matches the one immediately after the line feed character.
  • x ... Spaces and a portion between "#" and line break in the regular expression are ignored.
  • m ... "^" and "$" matches ones before and after a line feed character in a string.
  • U ... The length specification symbols, such as "*" and "+", try to match the shortest string, while "*?" and "+?" try to match the longest string.
To enable or disable the option only in the parentheses of (?: ), you can write an option character between ? and :. For example, the following two mean the same.
(?i:saturday|sunday)
(?:(?i)saturday|sunday)

For the regular expression, the POSIX character sets shown below are available in a character set expressed by [...].

[:NAME:] represents the character set of NAME, [:^NAME:] represents its complement set.

Character set nameIncluded character
alnumAlphanumeric characters
alphaAlphabetic characters
asciiCharacters of 0x00 - 0x7F in ASCII code
blankSpace (0x20) and horizontal tab (0x09)
cntrlControl characters of 0x00 - 0x1f and 0x7f in ASCII code
digitNumbers
graphPrintable characters (0x21 - 0x7e in ASCII code)
lowerLowercase alphabetic characters
printPrintable characters (0x21 - 0x7e in ASCII code) and space (0x20)
punctPrintable characters (0x21 - 0x7e in ASCII code) excluding alphanumeric characters
spaceSpace (0x20), horizontal tab (0x09), line break (0x0a), vertical tab (0x0b), page break (0x0c), and return (0x0d)
upperUppercase alphabetic characters
wordalphanumeric characters, and underscore (_) (same as \w)
xdigitNumbers and A-F, a-f

Capture

A pattern can include a sub-pattern enclosed by parentheses, which is called capture. When a pattern is matched, the partial string equivalent to the capture is saved for later use. Capturing is performed in the order in which the opening brackets occur. For example, in the patter "(a*(.)%w(%s*))", the first capture is the partial string equivalent to a*(.)%w(%s*), the second capture to ., and the third capture to %s*.

As a special case of the Lua patterns, an empty capture, (), captures the position in the string. For example, when the pattern "()aa()" is applied to the string "flaaap", 3 and 5 are captured. This empty capture cannot be used for the regular expression.

Regular Expression Syntactic Sugar

The regular expression is not the official type of Lua, but one of the userdata types. A regular expression object (a value of the userdata type where data or item for the regular expression are stored) is given as the return value of the string.regexp function, but you can also briefly write it as follows.

The regular expression and regular expression syntactic sugar can be used in the firmware with _RT_LUA_VERSION of "1.03" or later.

  • Enclose the regular expression string (the first argument of the string.regexp function) by / and /, place the option string (the second argument of the string.regexp function) immediately after the latter /.
  • Either a regular expression string or an option string is not enclosed by quotations.
  • To include / in a regular expression string, write \/. For \ itself, write \\.
  • A regular expression string always performs expression development.
  • A regular expression string can be written across multiple lines. If a page break comes immediately after the first /, the page break is ignored like a long string.
  • For an option string, only alphabetic characters are allowed.
  • If an option string is empty, nothing should be written after /.
/abc[def]ghi/i <==> string.regexp([=[abc[def]ghi]=], "i")

When a function has only one string as an argument, you can omit the parentheses after the function name, but cannot omit them if the argument is a regular expression. This is because the slash (/) at the beginning of the regular expression syntactic sugar is interpreted as the division symbol.

str = "hello world"
a, b = str:split(/\s/) --- Successful
a, b = str:split "%s" --- Successful
a, b = str:split /\s/ --- Error, / is treated as the division symbol.

The regular expression syntactic sugar does not write data directly in a program like numeric values or strings, but it just writes the calls of the string.regexp function briefly. An error regular expression string, if any, cannot be found until the statement is actually executed.


Table Operation

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

  • tbl ... Table type
  • sep ... String type
  • i, j ... Number type (FIXNUM)

This function handles a table as an array.

The function returns the concatenated values of elements in the table, tbl, from tbl[i] up to tbl[j], each of them is delimited by sep. The values from tbl[i] to tbl[j] must be the string type or the number type. In the case of the number type, the value concatenates a string to which the tonumber function is applied.

If sep is omitted, an empty string is assumed. If i or j is omitted, the length of 1 or tbl is assumed, respectively. If the j is larger than i, an empty string is returned.

t = { "hello", "world", "from", "Lua" }
s = table.concat(t, ";") -- s = "hello;world;from;Lua"

table.insert(tbl, pos, value)

  • tbl ... Table type
  • pos ... Number type (FIXNUM)
  • value ... Optional type

This function handles a table as an array.

This function inserts an element having the value, value, into the posth position in the table, tbl. The elements after the posth element are shifted backward by one position. If pos is omitted, the element is added to the end of the table.

table.insert returns nothing.

t = { "A", "B" }
table.insert(t, 2, "C") -- t = { "A", "C", "B" }
table.insert(t, "D")    -- t = { "A", "C", "B", "D" }

table.maxn(tbl)

  • tbl ... Table type

Among the key elements in the table, tbl, this function returns the maximum positive number (FIXNUM). If tbl does not have the key elements of a positive number (FIXNUM), 0 is returned.

This function linearly iterates all the tables to obtain a result. Therefore, it takes a long time for execution on a large table. If a table is an array, it is recommended to use the length operator, #.

t = { [1] = "A", [100] = "B", x = "C", [3] = "D" }
x = table.maxn(t) -- x = 100

table.remove(tbl, pos)

  • tbl ... Table type
  • pos ... Number type (FIXNUM)

This function handles a table as an array.

The function deletes the pos element from the table tbl, and shifts the following elements frontward by one position. If pos is omitted, the last element is deleted.

table.remove returns nothing.

t = { "A", "B", "C", "D" }
table.remove(t, 2) -- t = { "A", "C", "D" }
table.remove(t) -- t = { "A", "C" }

table.sort(table, comp)

  • tbl ... Table type
  • comp ... Function type

This function handles a table as an array.

This function sorts the table, tbl. The elements from tbl[1] to tbl[n] (where n = #tbl) are to be sorted. The comp, the function used to compare the largeness of values when sorting, takes two elements in tbl as arguments. If the first argument is larger than the second one, the function must return true; otherwise false. If comp is omitted, a function equivalent to the usual comparison operator, <, is used.

The algorithms of sorting are not stable. This means that if there are multiple elements considered equal with each other, the order of these elements may be switched before and after sorting.

table.sort returns nothing.

t = { 2, 4, 3, 1 }
table.sort(t)     -- t = { 1, 2, 3, 4 }

Mathematical Function

This function can be used in the firmware with the _RT_LUA_VERSION of "1.01" or later.

math.abs(x)

  • x ... Number type

This function returns the absolute value of x.

x = -1
y = math.abs(x)     -- y = 1

math.fmod(x, y)

  • x, y ... Number type

This function returns the remainder of x divided by y when the division result is rounded toward 0 unlike when the division operator (/) is used.

x = 5
y = -2
z1 = 5 % -2           -- z1 = -1
z2 = math.fmod(x, y)  -- z2 = 1

math.max(v, v...)

  • v ... Number type

This function returns the maximum argument value.

x = 5
y = -2
z = 3
w = 1
r = math.max(x, y, z, w)    -- r = 5

math.min(v, v...)

  • v ... Number type

This function returns the minimum argument value.

x = 5
y = -2
z = 3
w = 1
r = math.min(x, y, z, w)    -- r = -2

math.random(m, n)

  • m, n ... Numerical type (1 - 4294967295)

This function returns a pseudo-random number between m and n. Use the math.randomseed to specify the seed of the pseudo-random number.

If m is omitted, 1 is assumed. n cannot be omitted.

math.randomseed(os.time())
r = math.random(100)        -- r = 1~100
r = math.random(1000, 2000) -- r = 1000~2000

math.randomseed(s)

  • s ... Numerical type (1 - 4294967295)

This function specifies the seed of the pseudo-random number to be generated by the math.random function.

If the seeds of the pseudo-random numbers are the same, the math.random function returns the same array of pseudo-random numbers. To give meaning to pseudo-random numbers, make different seeds be given to scripts each time they are started by using, for example, the os.time function shown below.

math.randomseed(os.time())
r = math.random(100)        -- r = 1~100
r = math.random(1000, 2000) -- r = 1000~2000

I/O

The I/O library has two types. One operates the default I/O files without clearly specifying the file handle; the other one operates by specifying the file handle.

The file handle consists of the return values of the following three functions: io.input, io.output, and io.open. These are the data of the userdata type where information necessary for the library to operate the file is set. In the case of operation for which no file handle is specified, the file is specified with io.input and io.output, and I/O operations are performed by the function that is the element of the table io. On the other hand, operations that need to specify a file handle are defined as the method for the file handle that is the return value of io.open.

The standard Lua language provides the following three pre-defined file handles: io.stdin, io.stdout, and io.stderr. However, these are not available for the Yamaha router. In addition, io.input and io.output cannot have these handles as the initial value, and thus the initial value is not associated with any file.

file:close()

This function, the method for the file handle file, closes the file.

When the file is successfully closed, true is returned. If not, nil, an error message (string), and an error code (numeric value) are returned.

f = io.open("FILE.txt")
f:read(), f:write(),...
f:close()

io.close(file)

  • file ... File handle

This function closes the file handle file. If file is omitted, the function closes the default output files specified with io.output.

When the file is successfully closed, true is returned. If not, nil, an error message (string), and an error code (numeric value) are returned.

io.output("FILE.txt")
io.write(),...
io.close()

file:flush()

This function, the method for the file handle file, writes to a media or other item the data remaining in the OS buffer without actually being written to a media after the write operation was performed for the file.

When no data to be written remain or the data has been successfully written, true is returned. If not, nil, an error message (string), and an error code (numeric value) are returned.

f = io.open("FILE.txt", "w")
f:write(),...
f:flush()

io.flush()

This function writes to a media or other item the data remain in the OS buffer without actually being written to a media after the write operation was performed for the default output file specified by io.output.

When no data to be written remain or the data has been successfully written, true is returned. If not, nil, an error message (string), and an error code (numeric value) are returned.

io.output("FILE.txt")
io.write(),...
io.flush()

io.input(file)

  • file ... String type or file handle

If file is a string, this function considers it as the file name and opens it, and treats the file as the standard input file. If file is a file handle, this function uses it as the standard input file. In either case, the function returns the file handle of the newly available standard input file. If file is omitted, the function returns the file handle of the currently available standard input file.

If the specified file cannot be opened or other defective cases, an error occurs.

io.input("FILE.txt")
io.read()...

file:lines()

This function, the method for the file handle file, returns the iterator function that reads one-line at a time from the file. When the end of the file is reached, the iterator function returns nil but does not close the file.

By using the function with a generic for statement, you can write the code that processes the file on a line basis as follows:

f = io.open("FILE.txt")
for line in f:lines() do 
  -- Code that processes "FILE.txt" on a line basis 
end

io.lines(filename)

  • filename ... String type

If filename is specified, the function opens the file and then returns the iterator function that returns the contents of the file on a line basis. When the end of the file is reached, the iterator function returns nil but does not close the file.

If filename is omitted, the function returns the iterator function that returns the contents on a line basis for the default input file specified with io.input. When the end of the file is reached, the iterator function returns nil but not close the file.

By using the function with a generic for statement, you can write the code that processes the file on a line basis as follows:

for line in io.lines("FILE.txt") do 
  -- Code that processes "FILE.txt" on a line basis 
end

io.open(filename, mode)

  • filename ... String type
  • mode ... String type

This function opens the file filename in the mode specified for mode, and returns the file handle. If the file failed to be opened, nil, an error message (string), and an error code (numeric value) are returned.

mode is a string and must be any of the following. If mode is omitted, "r" is assumed.

String Description
"r" Reads in the text mode
"w" Writes in the text mode
"a" Adds in the text mode (only to a file on an external memory)
"rb" Reads in the binary mode
"wb" Writes in the binary mode
"ab" Adds in the binary mode (only to a file on an external memory)

In the text mode, the line break code is converted as shown below.

  • When reading the file, the string "\r\n" included in the file is converted into "\n".
  • When writing and adding codes to the file, the input string "\n" is converted into "\r\n".

If the line break code is not converted, the file is opened in the binary mode.

--[[ 
Function that copies the file
source, destination: Strings of filenames
]]
function file_copy(source, destination)
  local fhs, fhd, buf, estr, ecode
  fhs, estr, ecode = io.open(source, "r")
  if fhs == nil then
    return nil, estr, ecode
  end
  fhd, estr, ecode = io.open(destination, "w")
  if fhd == nil then
    fhs:close()
    return nil, estr, ecode
  end
  repeat
    buf = fhs:read(1000)
    if buf then
      fhd:write(buf)
    end
  until buf == nil
  fhd:close()
  fhs:close()
  return true
end

io.output(file)

  • file ... String type or file handle

If file is a string, this function considers it as the file name and opens the file, and also handles the file as the standard output file. If file is a file handle, this function uses it as the standard output file. In either case, the function returns the file handle of the newly available standard output file. If file is omitted, the function returns the file handle of the currently available standard output file.

If the specified file cannot be opened, an error occurs.

io.output("FILE.txt") 
io.write("Hello, world") -- Write "Hello, world" to "FILE.txt"

file:read(format, ...)

  • format ... String type or number type (FIXNUM)

This function, the method for the file handle file, returns the data read in the format format from the file. If the data was able to be read, the function returns it as the string, but if not, the function returns nil. The number of return values is the same as that of the arguments.

format must be any of the following. If format is omitted, only one "*l" is assumed to be specified.

  • "*a": Reads the entire file and returns it as the string. If this is found at the end of the file, an empty string is returned.
  • "*l": Reads the next line and returns it as the string. If this is found at the end of the file, nil is returned.
  • Numerical value: Reads the characters for the number of the specified bytes and returns them as the string. If this is found at the end of the file, nil is returned. If the numerical value is 0, nothing is read and an empty string is returned, but if the end of the file is reached, nil is returned.

io.read(format, ...)

  • format ... String type or number type (FIXNUM)

This function reads the standard input file specified with io.input. The meaning and return values of format are the same as those of file:read.


io.type(file)

  • file ... Optional type

This function checks whether or not file is the file handle.

If file is the file handle for the file that is open, this function returns the string "file". If it is the file handle for the closed file, this function returns the string "closed file". If file is not a file handle, nil is returned.


file:write(value, ...)

  • value ... String type

This function, the method for the file handle file, writes the specified data to file as the string.


io.write(value, ...)

  • value ... String type

This function writes the specified data to the standard output file specified with io.output.


Bit Operation

This function can be used in the firmware with the _RT_LUA_VERSION of "1.01" or later.


bit.band(v, v...)

  • v ... Numerical type (0 - 4294967295)

This function considers the given argument as the 32-bit unsigned integer and returns the result of AND of the bits.

x = 0x5a
y = 0xaf
z = bit.band(x, y) -- z = 0x0a

bit.btest(v, v...)

  • v ... Numerical type (0 - 4294967295)

This function considers the given argument as the 32-bit unsigned integer, and if the result of AND of the bits is 0, the function returns false; otherwise true.

x = 0x01
y = 0x02
z = bit.btest(x, y)   -- z = false

x = 0x01
y = 0x03
z = bit.btest(x, y)   -- z = true

bit.bor(v, v...)

  • v ... Numerical type (0 - 4294967295)

This function considers the given argument as the 32-bit unsigned integer and returns the result of OR of the bits.

x = 0x5a
y = 0xa5
z = bit.bor(x, y)  -- z = 0xff

bit.bxor(v, v...)

  • v ... Numerical type (0 - 4294967295)

This function considers the given argument as the 32-bit unsigned integer and returns the result of XOR of the bits.

x = 0x5a
y = 0xff
z = bit.bxor(x, y)  -- z = 0xa5

bit.bnot(v)

  • v ... Numerical type (0 - 4294967295)

This function considers the given argument as the 32-bit unsigned integer and returns the result of the logical NOT of the bits.

x = 0x5a
z = bit.bnot(x, y)  -- z = 0xffffffa5

bit.bshift(v, s)

  • v ... Numerical type (0 - 4294967295)
  • s ... Number type (FIXNUM)

This function considers v as the 32-bit unsigned integer and returns the value shifted by s. If the sign of s is positive, the value is shifted to the left, and if negative to the right.

If the absolute value of s is 32 or more, the return value is 0.

x = 0x5a
y = 4
z = bit.bshift(x, y)  -- z = 0x05a0

x = 0x05a0
y = -8
z = bit.bshift(x, y)  -- z = 0x0005

bit.brotate(v, s)

  • v ... Numerical type (0 - 4294967295)
  • s ... Numerical type (-31 - 31)

This function considers v as the 32-bit unsigned integer and returns the value rotated by s. If the sign of s is positive, the value is rotated in the left direction, and if negative in the right direction.

x = 0x12345678
y = 4
z = bit.brotate(x, y)  -- z = 0x23456781

x = 0x12345678
y = -8
z = bit.brotate(x, y)  -- z = 0x78123456

Yamaha Router API

Basic Library

rt.command(cmd, log)

  • cmd ... String type
  • log ... String type

Execute string cmd as the command of the router. The length of cmd must be within 4095 bytes. The cmd can include a pipe ("|") and redirection symbols (">", ">>").

If log is set as off, the result of executing command and execution result(true/false) are not output into SYSLOG. If log is omitted or specified as on, the result of executing command and execution result(true/false) is output into SYSLOG with DEBUG type.
log can be specified with the firmware supporting that _RT_LUA_VERSION is "1.07" or higher.

The function returns the execution result of the command. As the first return value, when the command was successfully executed, true is returned; if an error occurred, false is returned. As the second return value, the output of the command or an error message is returned as a string. If there is nothing to be returned, the function returns nil. The character code of the string returned as the second return value is determined according to the setting of the console character command.

In the command output of the router, a line break is expressed by two characters, "\r\n".

rt.command executes all the commands as the superuser.

The following commands cannot be executed from rt.command.

  • administrator
  • administrator password
  • administrator password encrypt
  • clear configuration
  • cold start
  • copy config
  • copy exec
  • delete config
  • delete exec
  • execute batch
  • exit
  • http revision-up go
  • Commands starting with less or commands in which links less using '|'
  • login password
  • login password encrypt
  • lua use
  • luac
  • mail notify
  • mail server pop
  • mail server smtp
  • mail server timeout
  • mail template
  • pri loopback active
  • pri loopback passive
  • quit
  • remote setup
  • scp
  • ssh
  • telnet

The following commands operate differently than those in the normal time.

  • ping, ping6 commands

    If the COUNT option is not specified, usually the command keeps sending the ICMP Echo packets until interrupted by Ctrl-C; however, if executed from rt.command, with the COUNT option omitted, the command assumes that 1 is specified for the COUNT option and sends ICMP Echo just once. With COUNT option set, the command sends ICMP Echo for the number of the specified times.

rtn, str = rt.command("show status lan2")
-- rtn = true
-- str = [[
LAN2
Description:
IP address:                  192.168.2.1/24
Ethernet address:            00:a0:de:12:34:56
Operation mode setting:      Auto Negotiation (Link Down)
Maximum packet length (MTU): 1500 octets
...
]]
rtn, str = rt.command("show status tunnel 9999")
-- rtn = false 
-- str = "Error: Parameter out of range\r\n"

rt.mail(param)

  • param ... Table type

This function sends an email according to the parameter specified for the table param.

When rt.mail is called, the function waits for one second and then sends an email. When the email transmission is finished, the function returns true. If communication with the server has failed, the function returns false.

Parameters that can be specified for param are as follows.

Key string Setting value Type Mandatory (M)
Optional (O) Default
smtp_address String representing the SMTP server address or the host name (Up to 64 characters) String type M
smtp_port Port number of the SMTP server (1 .. 65535) Number type O 25
smtp_auth_name String representing the user name for SMTP authentication (Up to 64 characters) String type O No
smtp_auth_password String representing the password for SMTP authentication (Up to 64 characters) String type O No
smtp_auth_protocol String representing the SMTP-AUTH authentication protocol; any of the following:
"cram-md5", "digest-md5", or "plain"
String type O Performs authentication negotiation in the representation order.
pop_before_smtp Specifies true when performing the POP before SMTP operation. Logical type O false
pop_port Port number of the POP server (1 .. 65535) Number type O 110
timeout Number of seconds of the timeout for the sending and receiving processing (1 .. 600) Number type O 60
from A string indicating the source e-mail address String type M
to String representing the receiver's mail address
When specifying multiple addresses, use a comma (,) to delimit them without inserting any space.
String type M
subject String representing the title (Up to 64 characters) String type O ""
date String representing the time displayed in the mail header. Specify the time in the format shown in RFC822. String type O The router time when the e-mail is sent
mime_version A string indicating the MIME-Version to be displayed in the e-mail header String type O "1.0"
content_type String representing the Content-Type displayed in the mail header
You can specify "text/plain" for the type/subject, "charset=us-ascii" and "charset=iso-2022-jp" for the parameter.
String type O "text/plain; charset=iso-2022-jp"
text String representing the body text (RTX5000: Up to 8000KB, RTX810/FWX120: Up to 640KB)
You cannot include control characters other than line feed and tab characters.
String type O ""
preface_of_text If the information on the router is not inserted at the beginning of the body text, specify false.
This can be specified in the firmware with _RT_LUA_VERSION of "1.05" or higher.
Logical type O true
Parameter required when pop_before_smtp is true
pop_address String representing the POP server address or the host name (Up to 64 characters) String type M
(When pop_before_smtp is true)
pop_protocol The following strings representing the protocol of receiving
"pop3", "apop"
String type
pop_auth_name String representing the user name for POP authentication (Up to 64 characters) String type
pop_auth_password String representing the password for POP authentication (Up to 64 characters) String type
cmd = "show techinfo"
mail_table = {
  smtp_address = "mx.example.jp",
  from = "foo@example.jp",
  to = "bar@example.jp",
  subject = cmd
}

rtn, str = rt.command(cmd)
if rtn and str then 
  mail_table.text = cmd .. "execution results \r\n\r\n" .. str 
  rt.mail(mail_table)
end

rt.sleep(seconds)

  • seconds ... Numerical type (1 - 864000)

When rt.sleep is called, response is returned from the function after seconds seconds. seconds must be set to a numerical value between 1 and 864000.

The return value of the function is 0. rt.sleep is used to delay the execution of a Lua script. During the function, the Lua task that called the function consumes little CPU power.

while true do
  ... 
  rt.sleep(600) -- Repeats some processing every 10 minutes. 
end

rt.syslog(type, text)

  • type ... String type
  • text ... String type

This function records text as log. It is also output as system log if the syslog server command or other command is set. text must be within 231 bytes.

type must be any of the following log types:

  • "notice" ... NOTICE type
  • "info" ... INFO type
  • "debug" ... DEBUG type
  • "log_only" ... INFO type but not transmitted to the system log server

The return value has two types: boolean type and string type. The first return value of the boolean type indicates whether the log output is successful or failed, and the second one shows an error message. When type is specified with notice/debug, if the corresponding syslog notice/debug command is set to off, the log output will fail and false is returned. If type is specified with info, the log is always output regardless of the setting of the corresponding syslog info command; however, the data are transmitted to the SYSLOG server only when the syslog info command is set to on.

rt.syslog("info", "[Lua] This is a LOG")

rt.syslogwatch(pattern, n, seconds)

  • pattern ... string type or regular expression object
  • n ... Number type (1 - 1000)
  • seconds ... Numerical type (1 - 864000)

When the line that matches the pattern pattern is newly recorded n times in the router log or when seconds seconds have passed, this function ends and the processing returns. The time stamp of the log is not checked to see if it matches the pattern.

n should be a numerical value between 1 and 1000; if omitted, 1 is assumed. seconds should be a numerical value between 1 and 864000; if omitted, the function waits infinitely for the log that matches the pattern to be found.

This function returns the number of times the log has matched the pattern and the array where the matched logs (with the time stamp) are stored. If the value is returned when seconds has passed, the number of times the pattern matched so far and the logs are returned. If no log has matched the pattern, the number of time is 0 and the second return value is nil.

Even in the case where pattern has been matched multiple times in one-line log, the number of times the pattern matched is counted as 1.

When rt.syslogwatch is called, without logging the record, the Lua task of the caller consumes little CPU power.

pattern = "IP Tunnel%[(%d+)%] Down"
while true do
  rtn, array = rt.syslogwatch(pattern, 1, 600)
  if rtn > 0 then
    io.output("FILE.txt") 
    io.write(string.format("Tunnel down: %s\n", string.match(array[1], pattern)))
    io.close()
  end
end

Hardware Library

rt.hw.open(resource, type)

  • resource ... String type
  • type ... String type

This function opens the hardware specified for resource to make it able to be controlled by a Lua script, and returns its descriptor.
Any of the following can be specified as resource.

  • Able to be specified when _RT_LUA_VERSION is "1.02" or higher;
    • "buzzer1" ... Buzzer
    • "status-led1" ... STATUS light (FWX120 and RTX810 only)
    • "alarm-led1" ... ALARM light (RTX5000 only)
    • "thermometer1" ... Thermometer (RTX5000 only)
    • "cpu1" ... CPU
    • "cpu2" ... CPU1 of the multi-core CPU (RTX5000 only)
    • "cpu3" ... CPU2 of the multi-core CPU (RTX5000 only)
    • "cpu3" ... CPU3 of the multi-core CPU (RTX5000 only)
  • Able to be specified when _RT_LUA_VERSION is "1.04" or higher;
    • "keyboard1" ... USB keyboard, USB bar code reader, etc.

      (Restrictions)
      • Only those that can be recognized as a USB keyboard can be controlled.
      • Even for a model equipped with multiple USB ports, only one unit can be simultaneously controlled.

When the hardware has been successfully opened, the descriptor is returned as the first return value, and nil as the second return value. If the hardware failed to be opened, nil is returned as the first return value, and a string representing an error message as the second return value.

type is a string representing the type of the USB keyboard. You can specify type only when controlling the USB keyboard "keyboard1". If this is specified when opening other hardware, the function ends with an error.
Any of the following can be specified as type.

  • "jp" ... Japanese 106 key type
  • "us" ... English 101 key type

If type is omitted, "jp" is assumed to control the keyboard.

The hardware opened by this function is occupied by the Lua task of the caller. Because of this, the hardware cannot be controlled from other Lua tasks until it is closed with hwd:close. Note that when a Lua task is occupying hardware other than the thermometer "thermometer1" and the CPU "cpu1", the other router functions also cannot control the occupied hardware, and thus the hardware does not work as expected.

-- Check the CPU utilization every minute, and if 80% is exceeded, sound a buzzer. 

threshold = 80
sleep_sec = 60

while (true) do
	cpu, err = rt.hw.open("cpu1")
	if (cpu) then
		load = cpu:read()
		cpu:close()
	end

	if (load.load_1m > threshold) then
		bz, str = rt.hw.open("buzzer1")
		if (bz) then
			bz:tone("B3")
		end
	else
		if (bz) then
			bz:off()
			bz:close()
		end
	end

	rt.sleep(sleep_sec)
end

The following can be used in the firmware with the _RT_LUA_VERSION of "1.02" or later.


hwd:close()

This function, the method of the descriptor hwd, closes hwd to finish controlling the hardware.

bz,str = rt.hw.open("buzzer1")
bz:tone("B2")
rt.sleep(10)
bz:off()
bz:close()

hwd:tone(tune)

This function, the method for the descriptor hwd of the buzzer, sounds a buzzer tone of the pitch specified by tune.

  • tune ... String type

tune is a string representing tune, being specified with the combination of one-digit alphabet out of C, D, E, F, G, A, and B and a number, such as "C1". The "C" in "C1" represents the tune. These alphabets correspond, respectively in order from C, to do, re, mi, fa, so, la, and ti. The "1" represents the pitch of the sound; as this value increments by 1, the buzzer sound gets higher by one octave. The following table shows the available tunes.

Model Output pitches
FWX120, RTX810, RTX5000 B2, E3, B3, B4
bz, str = rt.hw.open("buzzer1")
bz:tone("B2")...

hwd:on()

This function, the method for the descriptor hwd of LED, lights the LED.

led, str = rt.hw.open("status-led1")
led:on()...
  • interval_on ... Number type
  • interval_off ... Number type

This function, the method for the descriptor hwd of LED, blinks the LED.

interval_on/interval_off represents the time interval (milliseconds) between on and off of the LED. Each of the arguments can be specified in the range from 100 to 3000 by 100 milliseconds. If specified a value that is not divisible by 100, less than 100 is truncated.

led, str = rt.hw.open("status-led1")
led:blink(500, 500)...

hwd:off()

This function, the method for the descriptor hwd, stops the buzzer sounding when the hwd is the descriptor of the buzzer. If hwd is the descriptor of the buzzer, this function turns out the LED lit or blinking.

led = rt.hw.open("status-led1")
led:on()
led:off()...

hwd:read(n)

  • n ... Number type

This function, the method for the descriptor hwd, reads the thermometer in the router if the hwd is the descriptor of the thermometer, and returns the temperature in the number type. If hwd is the descriptor of the CPU, this function obtains the CPU utilization and returns the table storing the CPU utilization during each measurement. The contents of the table to be returned are as follows:

Field name Data type CPU utilization measurement time
load_5s Number type 5 seconds
load_1m Number type 1 minute
load_5m Number type 5 minutes

In the firmware with _RT_LUA_VERSION of "1.04" or later, if hwd is a USB keyboard, this function reads the output from the keyboard for the number of characters specified for n. The function returns the characters read from the keyboard.

Note that if hwd is the thermometer or the descriptor of the CPU, you cannot specify n.

[Example of reading CPU utilization]

cpu, err = rt.hw.open("cpu1")
if cpu then
  val_t = cpu:read()
  cpu:close() 
  print("CPU utilization for 5 minutes: " .. tostring(val_t.load_5m) .. "%") 
else
  print(err)
end 
[Example of reading characters from the keyboard]

kbd, err = rt.hw.open("keyboard1", "jp")
if kbd then
  data = kbd:read(5)
  kbd:close()
  print(data)
else
  print(err)
end

The following can be used in the firmware with the _RT_LUA_VERSION of "1.04" or later.


hwd:getc(NOWAIT)

  • NOWAIT ... Boolean type

This function, the method for the descriptor hwd of a USB keyboard, reads one-character output from the keyboard.

If false is specified for NOWAIT, this function can read the key input with NOWAIT.

kbd, str = rt.hw.open("keyboard1")
if kbd then
  str = ""

  data = kbd:getc()
  while data ~= '\n' do
    if data then
	    str = str .. data
      data = kbd:getc()
    end
  end

  kbd:close()
  print(str)
else
  print(str)
end

hwd:getchar()

This function, the method for the descriptor hwd of a USB keyboard, reads one-character output from the keyboard.

You can use this function in the same manner as the hwd:getc function except that you cannot specify NOWAIT.

hwd:gets()

This function, the method for the descriptor hwd of a USB keyboard, reads one line up to its line break output from the keyboard.

kbd, str = rt.hw.open("keyboard1")
if kbd then
  data = kbd:gets()
  if data then
    print(data)
  end
  kbd:close()
end

HTTP Library

This function can be used in the firmware with the _RT_LUA_VERSION of "1.02" or later.

rt.httprequest(param)

  • param ... Table type

This function sends data using HTTP according to the parameter specified for the table param.

When rt.httprequest is called, the HTTP Request according to the parameter is sent to the HTTP server, and when a response to it is received, the process returns from the function. The function returns the table storing the result of the HTTP communication and the data received from the server.

Parameters that can be specified for param are as follows.

Key string Setting value Type Mandatory (M)
Optional (O) Default
url URL to which a request is sent (Up to 255 characters)
Enter an URL in the format of "http://IP address or host name of the server/path name."
When the port number of the server is other than 80, specify the number in the URL in the format of "http://IP address or host name of the server:port number/path name."
String type M
method Any of the following string representing the HTTP method to be used for requests:
"GET", "HEAD", "POST"
String type M
proxy String representing the HTTP proxy server to be used for requests (Up to 128 characters) String type O No
proxy_port Port number of the HTTP proxy server to be used for requests (1 .. 65535) Number type O No
auth_type Any of the following strings representing the authentication method
"none" (No authentication), "basic" (Basic authentication)
String type O "none"
auth_name String representing the user name for authentication (Up to 64 characters) String type Required when auth_type="basic"
auth_pass String representing the password for authentication (Up to 64 characters) String type
timeout Number of seconds of the timeout for the request processing (1 .. 180) Number type O 30
save_file File name to which the received data are to be saved (Up to 64 characters)
When the file name, "config0" .. "config4", is specified, the data are saved to the configuration file of the router ("config0" only for NVR500).
When "HEAD" is specified for method, this string is ignored.
String type O No
post_text String representing the data transmitted via the POST method (RTX5000: Up to 8000KB, RTX810/FWX120: Up to 640KB)
When anything other than "POST" is specified for method, this string is ignored. Also, this item cannot be simultaneously specified with post_file.
String type When method="POST", either of these strings must be specified.
post_file File name to be transmitted via the POST method (Up to 64 characters)
When anything other than "POST" is specified, this string is ignored. Also, this item cannot be simultaneously specified with post_text.
String type
content_type String representing the format of data to be transmitted via the POST method (Up to 128 characters)
When anything other than "POST" is specified, this string is ignored.
String type Required when method="POST"

This function returns the following tables.

Key string Description Type
rtn1 Shows the result of the transmission of an HTTP request. When the response data from the server is successfully received, true is stored; otherwise false. Logical type
rtn2 Shows the result of the I/O for the file specified for save_file and post_file. If the I/O of the file is successful, true is stored; otherwise false. If no file I/O is performed for the files, this field does not exist. Logical type
err When an error occurs with the sending and receiving via HTTP or the file I/O, an error message is stored here. Without an error, this field does not exist. String type
code The HTTP status code of a response from the server is stored here. Number type
header The HTTP header of a response from the server is stored here. String type
body The main body response data from the server is stored here. If the upper limit of the data size (RTX5000:2MB, RTX810/FWX120:1MB) is exceeded, nil is stored here. String type or nil type

Socket Communication Library

This function can be used in the firmware with the _RT_LUA_VERSION of "1.06" or later.

The socket communication library is port of the LuaSocket library functions written in C. The LuaSocket version is 2.0.2.

LuaSocket is classified into the library functions in C language and the library functions in Lua language. While the library functions in C language provide low-level functions such as the one that calls a socket system call, the library functions in Lua language provide functions to use applications including HTTP, FTP, and SMTP.
In the router, the library functions in C language of LuaSocket was transplanted as APIs. Because of this, the scripts of the library functions in Lua language that are openly available on the homepage of LuaSocket cannot be used as they are. Use the following LuaSocket module file for the Yamaha router. For details on the library functions in Lua language, see the Reference of LuaSocket.

LuaSocket module file for the Yamaha router

This library generates a socket object and performs communication on an object basis. The objects differ in characteristics by protocol, and change their states according to particular functions.

  • TCP
    The objects to be used are as follows. Commonly in TCP, a server waits for incoming connections, and a client initiates TCP communication. However, the "server" and "client" of the objects are based on a concept different from TCP.
    Master object Object generated by rt.socket.tcp.
    Server object Object that can now wait for TCP connection.
    When the master object calls tcp:listen and becomes to be able to wait for connection, this object changes to the server object.
    Client object Object that can send and receive data after connection with a remote host was established. When the master object calls tcp:connect and changes to the client object or when the tcp:accept is executed in the server object and the connection is established, a client object is returned.
  • UDP
    There are two types of UDP objects as described below.
    connected object Object that communicates with a particular host only. When the unconnected object specifies a connection partner using setpeername, this object changes to the connected object. For this object, you must use udp:send/udp:receive for sending and receiving.
    unconnected object Object generated by rt.socket.udp. This object uses udp:sendto/udp:receivefrom for sending and receiving, and is available for communication with unspecified hosts.
  • MIME
    A group of functions that are used for performing operations such as encoding/decoding in Base64 or Quoted-Printable, inserting new lines into outgoing messages and converting line feed codes.
[Notes]
  • When accessing the port specified for LuaSocket from outside of the interface where NAT and the IP masquerade, the static NAT (or static masquerade) needs to be set.
  • To avoid malfunction, make sure that the port number specified for LuaSocket is not duplicate with the port number used by the functions of the router.
    The table below shows the port numbers used by the functions implemented in the router. Although the implemented functions differ depending on the model, and the port number actually used differs depending on whether the function is used or not, avoid the port number listed in this table not to be dependent on the model or settings.
    * The mark (*) in the table indicates that the port number can be changed by a command.

    Protocol Function name Port number
    TCP www settings 80 (*)
    TELNET server 23 (*)
    SSH server 22 (*)
    BGP 179
    PPTP 1723
    SIP 5060
    ONFS 49501, 49502 (*)
    IP masquerade 60000-64095 49152-59999 32096-49151 (*) (FWX120)
    TCP (Socket) 1024-5000
    UDP UDP ECHO 7
    Heartbeat 9
    DNS 53, Start point port: 10000-10999 (*)
    DHCP server 67
    DHCP client 68
    TFTP server 69
    SNMP 161
    IKE 500
    System Log 514 (*)
    RIP 520
    RIPng 521
    DHCP6 client 546
    DHCP6 agent 547
    RADIUS 1645
    L2TP 1701
    UPnP 1900
    NetVolante DNS 2002 (*)
    MGCP 2427-2433
    NAT traversal 4500
    Connection between data connection branches 4502
    RTP 5004-5059 (*)
    SIP 5060
    Heartbeat 2 8512
    QoS link (Load notification, Bandwidth detection) 59140 (*)
    UDP (Socket) 21024-25000
    IP masquerade 60000-64095 49152-59999 32096-49151 (*) (FWX120)

rt.socket.tcp()

This function generates a master object of TCP.

The generated master object calls tcp:listen to change to the server object or calls tcp:connect to change to the client object.

When an object is successfully generated, the generated object (userdata type) is returned. If an object fails to be generated, nil and an error message are returned.

-- Generate a TCP object and wait for connection. 
tcp = rt.socket.tcp()
tcp:setoption("reuseaddr", true)
res, err = tcp:bind("192.168.100.1", 11111)
if not res and err then
  print(err)
  os.exit(1)
end
res, err = tcp:listen()
if not res and err then
  print(err)
  os.exit(1)
end

while 1 do
  control = assert(tcp:accept())

  raddr, rport = control:getpeername()
  print("remote host address:" .. raddr .. " port:" .. rport) 

  -- Set the reception timeout to 30 seconds 
  control:settimeout(30)
  while 1 do
    msg, err, partial = control:receive()

    if (msg) then 
      -- Process the received data (The data is output to the console in this example) 
      print(msg) 

      -- Send a response 
      sent, err = control:send("response\n")
      if (err) then
        print("send error(" .. err .. ")")
        control:close()
        break
      end
    else
      if (err ~= "closed") then
        print(os.date() .. "receive error(" .. err .. ")")
        if (partial) then
          print("receive partial data(" .. partial .. ")")
        end
      end
      control:close()
      break;
    end
  end
end
-- Generate a TCP object, connect to the remote host, and transfer the data.

-- IP address and port number of the remote host 
host = "192.168.100.1"
port = 11111

tcp = rt.socket.tcp()

res, err = tcp:connect(host, port)
if not res then
  print("connect error(" .. err .. ")")
  os.exit(1)
end

print("Connected remote host:" ..host.. " port:" .. port)

lhost, lport = tcp:getsockname()
print("Local host:" ..lhost.. " port:" ..lport)

tcp:settimeout(5)
tcp:setoption("tcp-nodelay", true) 

-- Send the data. 
sent, err = tcp:send("test\n")
if (err) then
  print("send error(" .. err .. ")")
  tcp:close()
  os.exit(1)
end 

-- Receive a response from the server. 
data, err, partial = tcp:receive()
if (err) then
  print("receive error("..err..")")
  if (partial) then
    print("receive partial data("..partial..")")
  end
  tcp:close()
  os.exit(1)
end 

-- Process the received data (The data is output to the console in this example) 
print(data)

tcp:close()

rt.socket.udp()

This function generates an unconnected object of UDP.

When an object is successfully generated, the generated object (userdata type) is returned. If an object fails to be generated, nil and an error message are returned.

-- Generate a UDP object and wait for data transmission from the remote host. 
host = "192.168.100.1"
port = 22222

udp = rt.socket.udp()
res, err = udp:setsockname(host, port)
if (err) then
  print("setsockname error(" .. err .. ")")
  udp:close()
  os.exit(1)
end

lhost, lport = udp:getsockname()
print("Bind to host:" ..lhost.. " and port:" ..lport)

while 1 do
  dgram, ip, port = udp:receivefrom()
  if (dgram ~= nil) then 
    -- Process the received data
    -- (Here, as an example, the data is output to the console and the received string is returned directly to the peer) 
    print("Received '" .. dgram .. "' from " .. ip .. ":" .. port)
    udp:sendto(dgram, ip, port)
  else
    print(ip)
    udp:close()
    os.exit(0)
  end
end
-- Generate a UDP object and communicate with the remote host. 
udp = rt.socket.udp()
udp:setpeername("192.168.100.1", 22222)

rhost, rport = udp:getpeername()
print("remote host:" .. rhost .. " port:" .. rport) 

-- Send the data 
res, err = udp:send("test")
if (err) then
  print("send error(" .. err .. ")")
  udp:close()
  os.exit(1)
end 

udp:settimeout(10) -- Set the receiving timeout to 10 seconds. 

-- Receive the response from the partner. 
dgram, err = udp:receive()
if (not dgram) and err then
  print("receive error(" .. err .. ")")
  udp:close()
  os.exit(1)
end 
-- Process the received data (The data is output to the console in this example) 
print(dgram)

udp:close()

rt.socket.select(recvt, sendt, timeout)

This function monitors change in the status of the socket, and returns the array of the objects where the status has changed to readable or writable.

  • recvt ... Table type
  • sendt ... Table type
  • timeout ... Number type (FIXNUM)

For recvt, specify an array of objects (userdata type) waiting for the readable status, and for sendt an array of objects (userdata type) waiting for the writable status. If there is no object waiting for change in the status, specify nil or an empty table.
For timeout, specify seconds for an object to wait for change in the status. If timeout is omitted or a negative value is specified, the object waits infinitely for change in the status.

When successful, this function returns two tables: the table of the objects ready for reading and the table of the objects ready for writing. These tables contain a key consisting of an integer and an object, which uniquely shows which object has changed in the status.
If an error occurs, the function returns the following three: nil, nil, and an error message.

-- Wait for connection at multiple ports. 
function create(addr, port)
  s = rt.socket.tcp()
  s:setoption("reuseaddr", true)
  res, err = s:bind(addr, port)
  if not res and err then
    print(err)
    os.exit(1)
  end
  res, err = s:listen()
  if not res and err then
    print(err)
    os.exit(1)
  end

  return s
end

server1 = create("192.168.100.1", 11111)
server2 = create("192.168.100.1", 11112)

while 1 do
  rcv, snd, err = rt.socket.select({server1, server2}, nil)

  if rcv[server1] then
    server = server1
  elseif rcv[server2] then
    server = server2
  else
    print("select error:"..err)
    os.exit(1)
  end

  control = assert(server:accept())

  raddr, rport = control:getpeername()
  print("remote host address:" .. raddr .. " port:" .. rport) 

  -- Clear the statistical information. 
  res = control:setstats(0, 0) 

  -- Set the reception timeout to 30 seconds 
  control:settimeout(30)

  while 1 do
    msg, err, partial = control:receive()

    if (msg) then 
      -- Process the received data (The data is output to the console in this example) 
      print(msg) 

      -- Send a response 
      sent, err = control:send("response\n")
      if (err) then
        print("send error(" .. err .. ")")
        control:shutdown()
        break
      end
    else
      if (err ~= "closed") then
        print(os.date() .. "receive error(" .. err .. ")")
        if (partial) then
          print("receive partial data(" .. partial .. ")")
        end
      end
      control:shutdown()
      break;
    end
  end

  rcv, snd, alive = control:getstats() 
  -- Display the statistical information. 
  print("receive: " .. rcv .. "bytes, send: " .. snd .. "bytes, alive time: " .. alive .. "sec")

end

rt.socket.dns.toip(address)

This function converts the host name to the IPv4 address.

  • hostname ... String type

For hostname, specify the IPv4 address or the host name.

If successful, the function returns the IPv4 address and the information (table type) received from the resolver. The information received from the resolver is stored in the following table. If failed, the function returns the following two: nil and an error message.

Key string Setting value Type
name The official name of the host. String type
alias Alias of the host.
(*) The Yamaha router cannot obtain the alias of the host, and thus returns an empty table.
Array of the string types
ip IPv4 address.
(*) An array is returned, but only one IPv4 address is included.
Array of the string types
host = "example.com" -- Specify the host name. 
ip, tbl = rt.socket.dns.toip(host)
if ip then 
  print(ip) -- When successful, the IP address is returned. 
end

rt.socket.dns.tohostname(ip)

This function converts the IPv4 address into the host name.

  • ip ... String type

For ip, specify the IPv4 address or the host name.

If successful, the function returns the host name and the information (table type) received from the resolver. The information received from the resolver is stored in the following table. If failed, the function returns the following two: nil and an error message.

Key string Setting value Type
name The official name of the host. String type
alias Alias of the host.
(*) The Yamaha router cannot obtain the alias of the host, and thus returns an empty table.
Array of the string types
ip IPv4 address.
(*) An array is returned, but only one IPv4 address is included.
Array of the string types
ip = "10.0.0.1" -- Specify the IP address 
host, tbl = rt.socket.dns.tohostname(ip)
if host then 
  print(host) -- The host name of the router itself is returned if successful 
end

rt.socket.dns.gethostname()

This function returns the host name of the device.
The NetVolante DNS or the host name of the router itself set by the ip host command is returned.

When successful, the host name of the device is returned. If failed, the function returns the following two: nil and an error message.

host, err = rt.socket.dns.gethostname(host)
if host then 
  print(host) -- When successful, the host name of the router itself is returned. 
end

rt.socket.sleep(seconds)

This function sleeps the Lua task of the caller.

  • seconds ... Number type (FIXNUM)

When rt.socket.sleep is called, response is returned from the function after seconds seconds.

-- Send UDP packets every 10 minutes. 
udp = rt.socket.udp()
udp:setpeername("192.168.100.1", 22222)

while true do 
-- Send the data 
  res, err = udp:send("notification")
  if (err) then
    print("send error(" .. err .. ")")
    udp:close()
    os.exit(1)
  end

  rt.socket.sleep(600)
end

udp:close()

rt.socket.gettime()

This function returns the number of seconds that have passed after the router started.

t1 = rt.socket.gettime() 
-- Performs some process. 
...
t2 = rt.socket.gettime() - t1
print("execute time:" .. t2)

rt.socket.newtry(finalizer)

This function generates a function that performs processing before an exception error is thrown.

  • finalizer ... Function type

finalizer is a function that is called in the protection mode before an exception error is thrown. If nil is specified, nothing is performed when an error occurred.

A function is returned that performs processing when an exception error occurred.

c = rt.socket.tcp()
sample = rt.socket.protect(function() 
    -- Generate a function that calls close() in the event of an error. 
    local try = rt.socket.newtry(function() c:close() end) 
    -- The socket is always closed in the event of an error 
    try(c:connect("192.168.100.1", 8888))
    try(c:send("test\r\n"))
    local answer = try(c:receive()) 
    -- Process the received data 
    ...
    return c:close()
end)

ret, err = sample()
if not ret and err then
    print(err)
end

rt.socket.protect(func)

This function calls the func function in the protected mode.

  • func ... Function type

For func, specify a function that calls newtry, assert, or error to throw an exception error.

A function is returned that performs such processing that an exception error is not thrown. This returned function returns, in the case of an error, the following two: nil and an error message.

For setting examples, See here.


rt.socket.skip(num, ret1, ret2, ..retN)

This function discards the specified number of arguments and returns the remaining arguments.

  • num ... Number type (FIXNUM)
  • retN ... Optional type

Among the arguments listed as ret1, ret2.., this function discards the num arguments from the beginning and returns the remaining arguments from ret[num+1] until retN. By using this function, you do not have to provide a dummy variable to store the return values of unnecessary functions.

If the num+1th and subsequent arguments exist, this function returns all the num+1th and subsequent arguments. If the num is equal to the number of the arguments or if the number of arguments is less than num, nothing is returned.

-- Discard the numerical value representing the location where the pattern is matched, and return only the captured string. 
r = rt.socket.skip(2, string.find("ABCDE", "B(.)D"))
print(r) 

-- The following captured character is displayed in the console. 
-- C

rt.socket._VERSION()

This function returns the version of LuaSocket used as the socket communication library.


tcp:accept()

This function, the method of the object tcp of TCP, waits for connection from a TCP client, and after connection is established, returns the client object.

tcp:accept can be used in the server object.

When successful, this function returns the client object (userdata type). If failed, the function returns the following two: nil and an error message (string).

For usage examples, see here.


tcp:bind(address, port)

This function, the method of the object tcp of TCP, assigns an IP address and port number to an object.

  • address ... String type
  • port ... Numerical type (0 - 65535)

For address, specify the IPv4 address to assign to the object. When "*" is specified, all the interface is assigned with. For port, specify the port number to assign to the object. If 0 is specified, the port the system automatically uses is assigned with a number between 1024 and 5000.

When an IP is dynamically determined in such a case where an IP address is assigned from the DHCP server, specify "*" for address.

tcp:accept can be used in the master object.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


tcp:listen(backlog)

This function, the method of the object tcp of TCP, makes the TCP object be waiting for connection.

  • backlog ... Numerical type (0 - 128)

For backlog, specify the maximum length of the queue of connections on hold. When omitted, the default is 32.

tcp:listen can be used in the master object. If successful, this object will change to the server object.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


tcp:close()

This function, the method of the object tcp of TCP, closes the TCP object.

The socket used in the object is closed, and the address and port number assigned to the object will be able to be used for other application.

tcp:close can be used in the master object, server object, and client object.

The return value of this function is 1.

For usage examples, see here.


tcp:connect(address, port)

This function, the method of the object tcp of TCP, connects to a remote host.

  • address ... String type
  • port ... Numerical type (1 - 65535)

For address, specify the IPv4 address or the name of the remote host to connect to, and for port, specify the port number of the remote host.

When the connection is successful, the master object that called the function will change to the client object.

tcp:connect can be used in the master object.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


tcp:getpeername()

This function, the method of the object tcp of TCP, obtains the information on the remote host connected.

tcp.getpeername can be used in the client object.

If successful, the function returns the IPv4 address and port number of the remote host connected. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


tcp:getsockname()

This function, the method of the object tcp of TCP, assigns an IP address and port number to the object.

tcp:getsockname can be used in the master object, server object, and client object.

If successful, the function returns the IPv4 address and port number assigned to the object. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


tcp:getstats()

This function, the method of the object tcp of TCP, obtains the statistical information including the number of bytes and Time to Live (seconds) sent and received by the object.

tcp:getstats can be used in the master object, server object, and client object.

The function returns the return values in the order of the number of received bytes, the number of sending bytes, and the Time to Live of the object.

For usage examples, see here.


tcp:receive(pattern, prefix)

This function, the method of the object tcp of TCP, reads data from the object.

  • pattern ... String type or number type (FIXNUM)
  • prefix ... String type

pattern must be any of the following. If pattern is omitted, "*l" is assumed to be specified.

  • "*a": Reads data until the connection closes.
  • "*l": Reads a line with the line break code (LF:0x0A) at the end. The line break code (CR:0x0D, LF:0x0A) is not included in the return value.
  • Numerical value: Reads the data for the number of the specified bytes and returns them in the string type.

If prefix specified, the function returns received data with the string specified for prefix added to the front. If prefix is omitted, nothing is added to the front of the received data.

tcp:receive can be used in the client object.

If successful, the function returns the received data (string type). If failed, the function returns the following three: nil, an error message, and the data (string type) received before the error occurred. If the connection is closed while receiving data, "closed" is returned as an error message.

For usage examples, see here.


tcp:send(data, top, tail)

This function, the method of the object tcp of TCP, sends data to the connected party.

  • data ... String type
  • top ... Number type (FIXNUM)
  • tail ... Number type (FIXNUM)

For data, specify the data to send.

If top and tail are specified, data between the top and tail of data are sent. If top or tail is omitted, data from the beginning of data or until the end of data, respectively, are sent.
If a negative value is specified for top or tail, the start position is the position obtained by subtracting the specified number from the end of data. If this position is not within data, the value used when the parameter is omitted is used. Also, if the tail comes before top, data is not sent.

tcp:send can be used in the client object.

If successful, the function returns the last position of the data sent. If failed, the function returns nil, an error message, and the last position of data sent before the error occurred.

For usage examples, see here.


tcp:setoption(option, value)

This function, the method of the object tcp of TCP, sets the option of the socket included in the object.

  • option ... String type
  • value ... Boolean type

The values of option and value are as follows.

option valueDescription
reuseaddr true Allows reuse the same local address.
false Not allow reuse the same local address.
tcp-nodelay true Enables the Nagle algorithm.
false Disables the Nagle algorithm.

tcp:setoption can be used in the server object and client object.

If successful, the function returns 1; otherwise nil.

For usage examples, see here.


tcp:setstats (received, sent, age)

This function, the method of the object tcp of TCP, resets the statistical information of the object with the specified value.

  • received ... Number type (FIXNUM)
  • sent ... Number type (FIXNUM)
  • age ... Number type (FIXNUM)

With the values specified for received, sent, and age, reset, respectively, the number of received bytes, the number of sent bytes, and the Time to Live (seconds) of the object.

If received, sent, and age are omitted, the current number of received bytes, number of sent bytes, and Time to Live (seconds) of the object, respectively, are used.

tcp:getstats can be used in the master object, server object, and client object.

If successful, the function returns 1; otherwise nil.

For usage examples, see here.


tcp:settimeout(value, mode)

This function, the method of the object tcp of TCP, sets the timeout of the object.

  • value ... Number type (FIXNUM)
  • mode ... String type

For value, specify the number of seconds before a timeout occurs. If nil or a negative value is specified, this function indefinitely blocks the operation before the processing is completed.

For mode, specify the following value. If mode is omitted, the operation is performed with 'b' assumed.

  • b ... block timeout. Specifies the time period to block the object before one I/O operation is performed.
  • t ... Specifies the time period to block the object before returning from the library function.

When the timeout is set and the specified time has passed, the function blocking the object stops processing and returns an error.

tcp:settimeout can be used in the master object, server object, and client object.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


tcp:shutdown(, mode)

This function, the method of the object tcp of TCP, blocks the sending or receiving or the both.

  • mode ... String type

For mode, specify the following value. If omitted, the operation is performed with both assumed.

  • both ... Blocks the both of sending and receiving.
  • send ... Blocks only the sending.
  • receive ... Blocks only the receiving.

tcp:shutdown can be used in the client object.

The return value is 1.

For usage examples, see here.


udp:close()

This function, the method of the object udp of UDP, closes the socket.

The socket used in the object is closed, and the address and port number assigned to the object will be able to be used for other application.

udp:close can be used in the connected object and the unconnected object.

The return value is 1.

For usage examples, see here.


udp:getpeername()

This function, the method of the object udp of UDP, obtains the IP address and port number of the connected remote host.

udp:getpeername can be used in the connected object.

If successful, this function returns the IPv4 address and port number. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


udp:getsockname()

This function, the method of the object udp of UDP, obtains the IP address and port number assigned to the object.

For UDP, no address is assigned until either of setsockname or sendto is called.

udp:getsockname can be used in the connected object and the unconnected object.

If successful, this function returns the IPv4 address and port number. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


udp:receive(size)

This function, the method of the object udp of UDP, reads data from the object.

  • size ... Number type (FIXNUM)

For size, specify the maximum size of the datagram to receive. Use the data size specified for size or the default maximum size (2048 bytes), whichever smaller. If size is omitted, the maximum size of the datagram to receive is 2048 bytes.

udp:receive can be used in the connected object and the unconnected object. The connected object receives data only from the connected party, and the unconnected object receives data from unspecified hosts.

If successful, the function returns the received data (string type). If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


udp:receivefrom(size)

This function, the method of the object udp of UDP, reads data from the object.

  • size ... Number type (FIXNUM)

For size, specify the maximum size of the datagram to receive. Use the data size specified for size or the default maximum size (2048 bytes), whichever smaller. If size is omitted, the maximum size of the datagram to receive is 2048 bytes.

udp:receivefrom can be used in the unconnected object. While udp:receive returns only the received data, udp:receivefrom returns the information on the other party (IP address, port number) in addition to the received data.

If successful, the function returns the following three: the received data (string type), IP address and port number of the sender. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


udp:send(datagram)

This function, the method of the object udp of UDP, sends data to the party specified for udp:setpeername.

  • datagram ... String type

For datagram, specify the data to send.

The transmission of UDP is not blocked. Therefore, the processing is not affected by the value of udp:settimeout.

udp:send can be used in the connected object.

If successful, the number of sent bytes is returned. If failed, the function returns the following two: If failed, nil and an error message are returned.

For usage examples, see here.


udp:sendto(datagram, ip, port)

This function, the method of the object udp of UDP, sends data to the specified partner.

  • datagram ... String type
  • ip ... String type
  • port ... Number type (FIXNUM)

For datagram, specify the data to send.

For ip and port, specify the IPv4 address and port number, respectively, of the host to which data is sent.

The transmission of UDP is not blocked. Therefore, the processing is not affected by the value of udp:settimeout.

udp:sendto can be used in the unconnected object.

If successful, the number of sent bytes is returned. If failed, the function returns the following two: If failed, nil and an error message are returned.

For usage examples, see here.


udp:setpeername(address, port)

This function, the method of the object udp of UDP, specifies the partner to communicate with, and cancel it.

  • address ... String type
  • port ... Number type (FIXNUM)

For address, specify the IPv4 address or the host name, and "*" (asterisk). When "*" is specified, the association with the communications partner is canceled.

For port, specify the port number of the communications partner. When "*" is specified for address, the value of the port is ignored.

udp:setpeername can be used in the connected object and the unconnected object. When the specified partner is associated within the unconnected object, the object will change to the connected object. Also, to cancel the association with the communications partner in the connected object, specify "*" for address and omit port. When the association with the communications partner is canceled by this function, the object will change to the unconnected object.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


udp:setsockname(address, port)

This function, the method of the object udp of UDP, assigns the local address and port number to an object.

  • address ... String type
  • port ... Number type (FIXNUM)

For address, specify any of the IPv4 address, host name, or "*" (asterisk) to assign to the object. When "*" is specified, all the local interfaces are to be associated with.

For port, specify the port number to assign to the object. When 0 is specified for port, the system assigns a temporary port. The port number to be assigned falls between 21024 and 25000.

udp:setsockname can be used in the unconnected object only once before sending data. When data is sent via UDP, with this function omitted, the system makes all the local interfaces be associated, and assigns temporary ports.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


udp:settimeout(value)

This function, the method of the object udp of UDP, sets the timeout of the object.

  • value ... Number type (FIXNUM)

For value, specify the number of seconds before a timeout occurs. If nil or a negative value is specified, this function indefinitely blocks the operation before the processing is completed.

When the timeout is set and the specified time has passed, the function blocking the object stops processing and returns an error. Note that for UDP, tcp:send and tcp:sendto are not blocked, so sending the data is not affected by this function.

udp:settimeout can be used in the connected object and the unconnected object.

If successful, 1 is returned. If failed, the function returns the following two: nil and an error message.

For usage examples, see here.


rt.mime.b64(data1, data2)

This function encodes the specified data with Base64, and returns it.

  • data1 ... String type
  • data2 ... String type

For data1 and data2, specify the data (character string or binary data) to encode.
When data2 is specified, this function concatenates data1 with data2, and then encodes them with Base64. Padding is not performed, and the remaining byte data that could not be encoded is returned as the second return value. When data2 is omitted, this function encodes data1 with Base64. At this time, padding is added as necessary so that the entire data1 is encoded.

The function returns the string encoded with Base64. When data2 is specified, the remaining part that could not be encoded is returned as the second return value.
When there are chunks following the data, specify the second return value for the first argument, data1, and call the function.

estr = rt.mime.b64("test")
print(estr)
-- estr = dGVzdA==

rt.mime.dot(NUM, data)

This function converts <CRLF.CRLF>(*) included in a message.
*CRLF: Code for line break (In ASCII, CR: 0x0D, LF: 0x0A)

In SMTP transaction, <CRLF.CRLF> is sent to the receiver to notify the end of the message. If this pattern is included in the middle of a sending message, the receiver will receive an incomplete message. If the line feed CRLF is followed by a period (.) in a message, this function adds one more period (.) immediately after the period.

  • num ... Number type (FIXNUM)
  • data ... String type

For data, specify the sending message.

If the sending message is divided into multiple blocks, specify a value for num as follows according to the pattern of the string at the end of the immediately previous block.

num Description
1 If the last one byte of the immediately previous block is CR
2 If the last two bytes of the immediately previous block are CRLF
0 If neither of the above are applicable

The message body of SMTP is defined to start with CRLF. Therefore, to convert into the right message, you must specify 2 for num when calling this function for the first time.

This function returns the following two values: the converted message and the number of the line feed code at the end of the data. As for the second return value, the number of the line feed code, if the end of CR or CRLF, 1 or 2 is returned, respectively. Even when the end is LF, if the immediately before it is not CR, the second return value is 0.
If data is nil or omitted, this function returns nil and 2.
When there are chunks following the data, specify the second return value for the first argument, num, and call the function.

-- It is described as CR="\r", LF="\n" in Lua script 
dotstr, num = rt.mime.dot(2, ".\r\nSend message.\r\n.\r\n.test\r\n")
print(dotstr) 

--[[ The string after conversion. "." is added if CRLF is followed by "." 
..
Send message.
..
..test
]]

rt.mime.eol(code, data, marker)

This function converts a line feed code.

  • code ... Number type (FIXNUM)
  • data ... String type
  • marker ... String type

For data, specify a string that the line feed code is converted into.

If the sending message is divided into multiple blocks, specify for code the ASCII code of the character at the end of the immediately previous block.

For marker, specify a line feed code. The line feed codes included in data are converted into the code specified for the marker. If marker is omitted, the line feed code is replaced with <CRLF>.
* The line feed code indicates any of the following: CR, LF, CRLF, LFCR

This function returns the string that the line feed code has been converted into, and as the second return value, if the end of the data is part of the line feed code, returns its ASCII code, and otherwise 0. If data is nil or omitted, the function returns nil and 0 as the first and second return values, respectively.
When there are blocks following the data, specify the second return value for the first argument, code, and call the function.

-- It is described as CR="\r", LF="\n" in Lua script 
str, num = rt.mime.eol(0, "test\rexample\rtest\r", "\r\n")
print(str) 
-- Visualize and display the line feed code. 
print(string.gsub(str, "\r\n", "\\r\\n")) 

--[[ Conversion result (The string output to the console) 
test
example
test

test\r\nexample\r\ntest\r\n     3
]]

rt.mime.qp(data1, data2, marker)

This function encodes the specified data with Quoted-Printable, and returns it.

  • data1 ... String type
  • data2 ... String type
  • marker ... String type

For data1 and data2, specify the data to encode.
When data2 is specified, this function concatenates data1 with data2, and then encodes them with Quoted-Printable. The remaining characters that could not be encoded are returned, without being padded, as the second return value. If data2 is omitted, data1 is encoded with Quoted-Printable. At this time, the data is padded as needed for the entire data1 to be encoded.

For marker, specify a line feed code. The line feed code <CRLF> included in the specified data is converted into the code specified for the marker. If marker is omitted, the line feed code is replaced with <CRLF>.

The function returns the string encoded with Quoted-Printable. When data2 is specified, the remaining data that could not be encoded is returned as the second return value.
When there is a data block following the data, specify the second return value for the first argument, data1, and the data block that follows for data2, and then call the function.

estr, rem = rt.mime.qp("test") 
print(estr)
-- estr = =83e=83X=83g

rt.mime.qpwrp(left_len, data, length)

This function breaks a line for the length of one line of a string encoded with Quoted-Printable to be less than the length specified for length.

  • left_len ... Number type (FIXNUM)
  • data ... String type
  • length ... Number type (FIXNUM)

For data, specify the string encoded with Quoted-Printable.

For length, specify the length of one line. If length is omitted, the default is 76. If the length specified for length is reached in the middle of the string encoded with Quoted-Printable like "=XX", the function inserts line feed before the string encoded with Quoted-Printable. When the string includes the line feed code (CRLF), even if the length of one is less than length, the function breaks the line at the line feed code.

If the sending message is divided into multiple blocks, specify for left_len the length of the remaining part of the last line left after the immediately previous block is processed by this function. The length of the remaining part is returned as the second return value when this function performs processing on the immediately previous block.
If the string to process is the data at the beginning, specify 0 for left_len.

This function returns the two values: the string with line break at the position where the specified length was reached, and the length of the remaining part in the last line (value of length subtracted by the length of the last line). When there is a block following data, specify the second return value for the first argument, left_len, and call the function.

--Array of the strings encoded with Quoted-Printable

tbl = {
 "=82=A0=82=A2=82=A4=82=A6=82=A8=82=A9=82=AB=82=AD=82=AF=82=B1",
 "=82=B3=82=B5=82=B7=82=B9=82=BB=82=BD=82=BF=82=C2=82=C4=82=C6"
}

estr = {}
len = 0
for i, v in ipairs(tbl) do
  estr[i], len = rt.mime.qpwrp(len, v, 16)
end
print(estr[1] .. estr[2]) 

--[[ Conversion result (The string output to the console) 
=
=82=A0=82=A2=82=
=A4=82=A6=82=A8=
=82=A9=82=AB=82=
=AD=82=AF=82=B1=
=82=B3=82=B5=82=
=B7=82=B9=82=BB=
=82=BD=82=BF=82=
=C2=82=C4=82=C6
]]

rt.mime.unb64(data1, data2)

This function decodes the specified data with Base64, and returns it.

  • data1 ... String type
  • data2 ... String type

For data1 and data2, specify the string encoded with Base64.
When data2 is specified, this function concatenates data1 with data2, and then decodes them with Base64. The remaining characters that could not be decoded are returned as the second return value. If data2 is omitted, data1 is decoded with Base64.

The function returns the string decoded with Base64. When data2 is specified, the remaining part that could not be decoded is returned as the second return value.
When there are blocks following the data, specify the second return value for the first argument, data1, and call the function.

-- Decode the string encoded in base64 
estr = "gqKC64LNgsmC2YLWgsY="

str = rt.mime.unb64(estr)
print(str) 

--[[ Result of decoding. (String output to the console)

]]

rt.mime.unqp(data1, data2)

This function decodes the specified data with Quoted-Printable, and returns it.

  • data1 ... String type
  • data2 ... String type

For data1 and data2, specify the string encoded with Quoted-Printable.
When data2 is specified, this function concatenates data1 with data2, and then decodes them with Quoted-Printable. The remaining characters that could not be decoded are returned as the second return value. If data2 is omitted, data1 is decoded with Quoted-Printable.

The function returns the string decoded with Quoted-Printable. When data2 is specified, the remaining string that could not be decoded is returned as the second return value.
When there are blocks following the data, specify the second return value for the first argument, data1, and call the function.

-- Decode a string encoded in Quoted-Printable 
data = "=83e=83X=83g"

str = rt.mime.unqp(data)
print(str) 

--[[ Output result to the console
test
]]

rt.mime.wrp(num, data, length)

This function inserts a line feed into a string for the length of it to become less than that specified for length.

  • left_len ... Number type (FIXNUM)
  • data ... String type
  • length ... Number type (FIXNUM)

For data, specify a string where a line feed is to be inserted at the specified length.

For length, specify the length of one line. If length is omitted, the default is 76. The function inserts a line feed into the string at the length specified for length. When the string includes the line feed code (CRLF), even if the length of one is less than length, the function breaks the line at the line feed code.

If the sending message is divided into multiple blocks, specify for left_len the length of the remaining part of the last line left after the immediately previous block is processed by this function. The length of the remaining part is returned as the second return value when this function performs processing on the immediately previous block.
If the string to process is the data at the beginning, specify 0 for left_len.

This function returns the two values: the string with line break at the position where the specified length was reached, and the length of the remaining part in the last line (value of length subtracted by the length of the last line). When there is a block following data, specify the second return value for the first argument, left_len, and call the function.

-- An array of strings 
tbl = {
 "abcdefghijklmnopqrstuvwxyz",
 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
 "0123456789"
}

estr = {}
len = 0
for i, v in ipairs(tbl) do
  estr[i], len = rt.mime.wrp(len, v, 10)
end

print(estr[1] .. estr[2] .. estr[3]) 


--[[ Result of the line break. (String output to the console) 

abcdefghij
klmnopqrst
uvwxyzABCD
EFGHIJKLMN
OPQRSTUVWX
YZ01234567
89
]]

OS

os.clock()

This function returns the number of seconds from when the Lua script being executed started until the current time.

In the standard specifications of the Lua language, os.clock is supposed to return the rough number of seconds of the CPU time consumed by the Lua script being executed; however, this does not apply to the Yamaha router with Lua implemented. This implementation may be changed according to the standard specifications.

t1 = os.clock()
do 
    ... -- Processing that takes time 
end
t2 = os.clock() 
print("Execution time", t2 - t1) -- Display the execution time

os.date(format, time)

  • format ... String type
  • time ... Number type (FIXNUM)

This function returns the string or table that represents the specified time. time is the return value of os.time, and when this value exists, the time is applied. With time omitted, if the function is called, the current time is applied.

format defines the method of converting the time into the return value.

When the beginning of format is '!', the time is converted into UTC (Coordinated Universal Time). In other cases, the time is converted into the time in the time zone specified with the timezone command.

If the format after removing '!' which may be at the beginning is the string "*t", the time is converted into the table containing the elements having the following string as the keys.

  • year ... 4-digit number representing the year
  • month ... Number representing the month (1-12)
  • day ... Number representing the day (1-31)
  • hour ... Number representing the hour (0-23)
  • min ... Number representing the minutes (0-59)
  • sec ... Number representing the seconds (0-59)
  • wday ... Number representing day (1-7, 1 for Sunday, 2 for Monday, ..., 7 for Saturday)
  • yday ... Number representing the Nth day of the year (1-366)
  • isdst ... Always false

When format is other than "*t" format, it is treated as the format string for the strftime function of the C language.

If format is omitted, the current time is converted into a string with "%c" assumed to be given.


os.difftime(time2, time1)

  • time2 ... Number type (FIXNUM)
  • time1 ... Number type (FIXNUM)

This function returns the elapsed time from time1 to time2 in seconds. Both time1 and time2 must be the return values of os.time.

t1 = os.time()
do 
    ... -- Processing that takes time 
end
t2 = os.time() 
print("Execution time", os.difftime(t2, t1)) -- Display the execution time

os.exit(code)

  • code ... Number type (FIXNUM)

This function terminates the execution of a Lua script. code is an exit code and 0 indicates normal end. This function does not return to the caller.

function f(x)
  if x < 1 or x > 100 then
    print("Error")
    os.exit(0)
  end
...
end

os.getenv(varname)

  • varname ... String type

This function returns the value of the environment variable varname in string format. If varname is not defined, this function returns nil.

user = os.getenv("USER")
if user then
  print("USER:", user)
else
  print("USER: undefined")
end

os.remove(filename)

  • filename ... String type

This function deletes the filed specified for filename. To delete a directory, it must be empty.

If the file has been successfully deleted, true is returned; if failed, false and an error message (string) are returned.

os.remove("FILE.txt")

os.rename(oldname, newname)

  • oldname ... String type
  • newname ... String type

This function changes the name of the file specified for oldname to newname. You cannot change the directory where the file exists.

If the file has been successfully renamed, true is returned; if failed, false and an error message (string) are returned.

os.rename("FILE.txt", "NEW-FILE.txt")

os.time(tbl)

  • tbl ... Table type

This function returns the number representing the specified time. tbl is the table representing the time; this table must include year, month, and day as required elements. The table also can include hour, min, and sec. isdst, if any, is ignored. For the meaning of the elements, see os.date. If tbl is omitted, the function returns the current time when it is called.

The return value of os.time has a meaning only as the arguments of os.date and os.difftime.

t1 = os.time()
do 
    ... -- Processing that takes time 
end
t2 = os.time() 
print("Execution time", os.difftime(t2, t1)) -- Display the execution time

Module

A module is a mechanism to provide library functions. Many of the library function groups described in this document are also provided by the mechanism of modules.

When newly creating a module, you need to create a module file. A module file is a normal Lua script with the following differences.

  • The module function is called at the beginning of the file.
  • The file is placed in the directory indicated by the environment variable LUA_PATH.

Such a module file can be read by the require function from other Lua script, and the library functions defined in the module file becomes available.

The Yamaha router with Lua implemented cannot create or call a module in C language.


module(name, func...)

  • name ... String type
  • func ... Function type

This function creates a module. Usually, the function calls the module function at the beginning of a module file, and handles the file as the module file.

The string name is the name of the module. In normal cases, make the name the same as the module file name without the extension (.lua).

Under the global environment, a table named name is newly created, and the table becomes a new environment for the module file This enables the functions defined within the module file to be accessed as the elements of name from the Lua script where the module has been read by require.

[Router command]
set LUA_PATH="/lua/module/\?.lua;"
set PWD="/lua"

[/lua/module/mod1.lua]
module("mod1")
value = 100
function func(x)
  return x + 1
end

[/lua/script.lua]
require("mod1") 
print(mod1.value) -- Display the variable, value, of the module, mod1
x = mod1.func(10) -- Call the function, func, of the module, mod1

func is called with the module, as an argument, created after the environment was switched. For func, 0 or the desired number of arguments can be specified.

module changes the environment from the global to a unique environment. General library functions are registered by their names in the global environment. Because of this, you cannot use them as they are in module files. To avoid this, by specifying the package.seeall function for func, you can use the general library functions in module files for the effect of package.seeall.

[Router command]
set LUA_PATH="/lua/module/\?.lua;"
set PWD="/lua"

[/lua/module/mod2.lua]
module("mod2", package.seeall)
function func(x) 
  return string.format("%08x", x) -- The library function can be called by the effect of package.seeall 
end

[/lua/script.lua]
require("mod2") 
x = mod2.func(10) -- Call the function, func, of the module, mods

require(name)

  • name ... String type

This function reads a module file. name is a module name and part of the module file name.

A module file is searched for according to the environment variable LUA_PATH. A LUA_PATH is delimited at multiple places with semicolons (;), and the delimited parts are searched from the top. For the search in each delimited place, the character (?) in the LUA_PATH is replaced with the module name specified for name, and the file is searched for.

For example, when searching for the module name "foo" in the following LUA_PATH, the function searches the places in the order of ./foo.lua, /lua/module/foo.lua, and /lua/module/foo/init.lua for the file.

set LUA_PATH="./\?.lua;/lua/module/\?.lua;/lua/module/\?/init.lua"

package.seeall(name)

  • name ... String type

This function makes general library functions to be called from the module, name. This works by being specified as the second or a subsequent argument of module.


Coroutine

The Lua language supports coroutines in the language level, enabling coroutines to be used for across the coroutine.* library function groups. The coroutines allow you to easily write a program having a continuation situation such as an infinite list.

The following shows examples of using coroutines to obtain the Fibonacci sequence. A function to obtain the Fibonacci sequence can be briefly written, from its definition, by using recursion; however, because recursive call explosively increases along the permutation, it is not very practical. Using a coroutine enables you to follow the permutation infinitely.

-- The following function obtains the Fibonacci sequence by recursion. 

function fib(n)
  if n < 2 then
    return n
  else
    return fib(n - 1) + fib(n - 2)
  end
end 

-- The following function uses as the return value the function that returns the Fibonacci sequence of n or less. 

function generatefib(n)
  return coroutine.wrap(function ()
    local a, b = 1, 1
    while a <= n do
      coroutine.yield(a)
      a, b = b, a + b
    end
  end)
end 

-- Output the Fibonacci sequence of 1000 or less 
for i in generatefib(1000) do print(i) end

coroutine.create(func)

  • func ... Function type

This function creates a coroutine whose main body is the function func, and returns the coroutine (Thread type).


coroutine.resume(co, val1,...)

  • co ... Thread type
  • val1 ... Optional type

This function starts or restarts the coroutine co. When coroutine.resume is first called, the coroutine will start, and the function that is the main body of the coroutine is called with val1, ... as its arguments. When coroutine.resume is called for the suspended coroutine, the coroutine will restart. val1, ... are the return values of coroutine.yield.

If no error occurs during the execution of the coroutine, coroutine.resume returns true as the first return value, and then returns the argument of coroutine.yield or the return value of the function of the main body. If an error occurs during the execution of a coroutine, this function returns false as the first return value, and the string of an error message as the second return value.


coroutine.running()

This function returns the running coroutine (thread type). If there is no running coroutine, the function returns nil.


coroutine.status(co)

  • co ... Thread type

This function returns the status of the coroutine co in string format.

  • "running": The coroutine is running.
  • "suspended": The coroutine has never run or is suspended by coroutine.yield.
  • "normal": The coroutine is active but not running. This also applies to the status of the coroutine that has been resumed by another coroutine.
  • "dead": The function of the main body has ended or stopped due to an error.

coroutine.wrap(func)

  • func ... Function type

This function creates a coroutine whose main body is the function func, and returns the function that resumes the coroutine. The arguments given to the returned function has the same meaning as the coroutine.resume. The return value of this function is return value of the coroutine.resume without the first boolean type value. If an error occurs while the coroutine is running, the error is spread. This means that the entire script stops due to the error.


coroutine.yield(...)

This function suspends the execution of the coroutine. The given argument becomes the return value of coroutine.resume. The argument of coroutine.resume that was called to resume the coroutine becomes the return value of coroutine.yield.

Return to Top