Built-in Library

Use ‘require’ for loading a module: local math = require ‘math’

Built-in modules: string, table, math, time, json,’require’ is not required when use

In addition, more built-in modules can be used in non-contract mode, such as OS, net, IO, HTTP, jsonrpc, etc

Built-in Global Function

The function name Function type signature (return type (parameter function list)) describe

print: (…) => nil Standard output parameters, encountered table or function, output type name: 0000000000000000

pprint: (…) => nil Standard output parameter after tojsonstring results

type: (object) => string According to the run-time parameter type output parameter type corresponding string, return number, string, table, function, boolean, encountered other types of parameters, return to the previous five corresponding string

Such as:

let a1 = 1
let a2 = type(a1) -- The a2 value is' number ', the int and number of the runtime, and the type function returns 'number'.
let b1: object = 1
let b2 = type(b1) -- The b2 value is' number 'because the runtime type is used
type Person = {}
let c1 = Person()
let c2 = type(c1) -- The c2 value is' table ', the table and record type at runtime, and the type function returns' table'

require: (string) => object References to other modules, and not as a contract reference, the referenced module is loaded after the result of the return as a result of the require function

import_contract: (string) => table To reference the contract, the parameter is the name string of the contract and returns the table corresponding to the contract

emit: (string, string) => nil Throw an event event, recorded by the block chain

exit: (object) => object End the run, the parameter is the end code

pairs: (table) => object Returns the iterator of the table, traversing the order is to traverse the array part and then traverse the hash table part of the hash table part of the key key in the string before the traversal, the same string type key, short string in the long string before , The same length of the string key, according to ASCII characters from small to large

ipairs: (table) => object Return the iterator of the array of tables

error: (…) => object error

getmetatable: (table) => table

tostring: (object) => string Turn the parameter into string, for table and function, return type name: 0

tojsonstring: (object) => string Turn the parameter into a json string, for the function, return function: 0, for the nested table in the table, if there is a circular reference, use the ‘address’ substitution value.When json is used, the hash table will be small to large in order of the character of the key, and then the sequence of characters from left to right.For empty table, return “[]”

tonumber: (object) => number Turn the parameter into number, run into a string, read the number from the string, encounter an unparsed string or table or function, and return nil

tointeger: (object) => int Turns the argument into an integer, encounters a string, reads an integer from the string, encounters an unparsed string or table or function, returns nil

todouble: (object) => number Turn the parameter into number type and return nil with an unparsed value

toboolean: (obj) => bool Turn the parameter obj into a Boolean value, and obj returns false on false or nil, otherwise it returns true

totable: (object) => table Use the parameters as table, and if the parameter is not table return nil, it is mainly used to compile the static type conversion

next: (…) => object Move iterators to the next step

rawequal: (object, object) => bool Directly compare whether the two values are the same value (= = comparison is preferred to use the __eq__ function)

rawlen: (object) => int Gets the length of the array of a table directly

rawget: (object, object) => object Gets a property of a table directly

rawset: (object, object, object) => nil Set a property of a table directly

select: (…) => object When the index for the digital will return all the index greater than the index parameters: such as: select (2, “a”, “b”) returns “b”. When the index is a “#”, returns the number of total in the parameters (not including the index)

setmetatable: (table, table) => nil Set the table’s meta-table

table Module

table.concat(table, sep, start=1, end=the length of the array part of the table) Separate the table from <start> to <end> and connect each item with <seq>.Return the string after slicing.

table.insert(table, pos, value) Insert a value at the <pos> position of the array . If only pass 2 parameters <table> and <value>,insert the value after the last position of the array. No return value.

table.append(table, value) Insert the value after the last position of the array. No return value.

table.length(table) Get the length of the array portion of the array

table.remove(table, pos=the length of the array part of the table) Delete and return the array part of the element in the <pos> position. Subsequent elements will be moved forward. Parameter <pos> is optional and its default value is the length of the table. That is, delete from the last element.This method returns the deleted value.

table.sort(table) Sort the given table in ascending order.Element type in the table need to be the same. No return value.

For Example:

> tbl = {"alpha", "beta", "gamma", "delta"}
> table.sort(tbl)
> print(table.concat(tbl, ", "))
alpha, beta, delta, gamma

Global function rawlen. Return the number of array part in the table.

math module

math.abs(n) Gets the absolute value of parameter <n>.

math.ceil(n) Return the smallest integer that is not less than <n>.

math.floor(n) Return the largest integer that does not exceed <n>.

math.max(n1,n2,…) Return the maximum value of multiple values in the parameter list, requiring at least one parameter.

math.maxinteger The maxium integer.

math.min(n1,n2,…) Return the minimum value of multiple values in the parameter list, requiring at least one parameter.

math.mininteger The minimum integer.

math.pi Constant pi, 3.14159265358…

math.sqrt(n) Get the square root of <n>

math.tointeger(n) Convert the parameter <n> into an integer. If <n> itself is an integer, directly convert <n> into an integer. If you can not convert, return nil

math.type(num) Determine whether the first argument <num> is an integer or a floating point.

string module

string.split(str, sep) Divide <str> by <sep> into multiple strings. Return a string array.

string.byte(s) Return the ASCII number of the first character of the string.

string.char(i1, i2, …) Return the string constructed by the ascii characters corresponding to input integers.

string.find(str, pattern, [init=1, [plain=nil]]) Find the <pattern> string in the <str>. Start from position <init>. <plain> Indicates whether the <pattern> is used as a plain text string instead of a pattern string.Returns the first character index of the first substring that satisfies the condition or nil.

The pattern string can be used to match some of the substrings in the source string with the following symbols.

  • .(point): Match any character.
  • %a: Match any letter.
  • %c: Match any control character (for example : n)
  • %d: Match any number.
  • %l: Match any lower letter.
  • %p: Match any punctuation.
  • %s: Match any blank character.
  • %u: Match any capital letter.
  • %w: Match any letter or number.
  • %x: Match any hexadecimal number.
  • %z: Match any character that represents 0.
  • %x( <x> is a non-alphabetic non-numeric character): Match character <x>. Mainly used to deal with the expression of the characters(^$()%.[]*+-?) in the expression of the matching problem. For example, match ‘%%’ and ‘%’.
  • [Several character classes]: Match any character contained in []. for example [%w_] match with any letter or number. Or match with underline.
  • [^Several character classes]: Match any character not contained in []. for example [^%s] match any non-whitespace character.

For example:

let p1 = "%d%d:%d%d"
let s = "2016/11/11 11:11"
let a = string.find(s, p1)  -- The result of a is 11.That is, the index of the first character of the substring "11:11".
let b = string.sub(s, a)    -- The result of b is "11:11".
let c = string.find(s, p1, 3)  -- The result of c is 12.
let d = string.find(s, p1, 1, true)  -- The result of d is nil.Because the fourth argument is true, so we regard <p1> as a normal string to match.

string.format(formatstring, …args) Similar to method sprintf in C language.

For example:

let a = string.format("hello, %s, the number is %d", "China", 123)

string.gmatch(str, pattern) Return the iterator that traverses the pattern string pattern in <str>.

For example:

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

string.gsub(str, pattern, replacer, [n]) Replace the sub-string in <str> that match <pattern> with <replacer> or function.

string.len(str) Get the length of <str>.

string.match(str, pattern, [init=1]) Find the first substring the matches <pattern>.Starting from position <init>.

string.rep(str, n, [sep=’’]) Return the result of <str> repeating <n> times separate by <sep>.

string.reverse(str) Return the reverse of <str>.

string.sub(str, i, [,j=-1]) Get the substring of <str> from character <i> to <j> (including <i> and <j>).<i> and <j> can be negative,representing the <i>th and <j>th character of <str> from opposite position.

string.upper(str) Convert characters in <str> into capital and return.

time module

time.add(timestamp, field, offset) Return a new timestamp. <field> is one of the string in year/month/day/hour/minute/second. <offset> can be changing from postive, zero to negative.

time.tostr(timestamp) Convert timestamp into string. The format is %yy-%m-%d %H:%M:%S.

time.difftime(timestamp1, timestamp2) Compare the number of seconds between 2 timestamps.

json module

json.dumps(any lua value) Change the lua value to a json string.

json.loads(string) Change the json string to lua.If failed ,return nil

utf8 module

utf8.char(…) Accepts several numbers in the parameter.Return the corresponding UTF8 encoded byte sequence.

utf8.charpattern Constant,Can match a string pattern of UTF8 byte sequence.

utf8.codes(s) Return an iterator of all the characters in the variable <s>, encoded by utf8.

utf8.codepoint(s, i, j) Returns the character string of utf8 encoded within string [i, j]

utf8.len(s, i, j) Returns the character length of the string <s> in the index [i, j] encoded by utf8.

utf8.offset(s, n, i) Returns the byte index from the i-th byte of the nth character in <s>.

os module

os.clock() Returns the number of clock seconds to execute the program CPU

os.date(format, time) Parameter timestamp is optional, and if no time is given, current time will be returned, a formatted string or time information in table Type

os.difftime(t2, t1) Returns the difference of ‘t2 - t1’

os.execute(command) Execute the system command command

os.exit(code, close) Exit process, code is error code, close indicates whether to exit the current virtual stack

os.getenv(varname) Access to environment variables

os.remove(filename) Delete files or empty folders

os.rename(oldname, newname) Rename file

os.setlocale(locale, category) Set the time zone for the current program, and the category can select the default value ‘all’, indicating the scope of ‘locale’

os.time(table) ‘table’ represents the table of time information, the default is the information of the current time, and returns the timestamp

os.tmpname() Returns a temporary file name

io Module

io.close(file) Close file

io.flush() Output buffer zone

io.input(file) Read mode to open file

io.lines(filename) Read mode to open the file and return the iterators that iterate through the contents of the file

io.open(filename, mode) According to the specified mode to open the file, mode options: read mode ‘r’; write mode ‘w’ ; add mode ‘a’; keep old content and update mode ‘r +’; abandon the old content update mode “w +”; keep old content and can only add the end-of-file update mode ‘a +’; the default is ‘ r ‘

io.read(read_mode) Read the content of the current opening input file and return, the parameter read_mode can have more than one optional value, and the effect of the different values is as follows:

"*all"    Reads the entire file
"*line"    Reads the next line
"*number"    Reads a number
<num>    Reads a string that does not exceed <num> characters

io.seek(pos ?: int) Sets or gets the current position to open the file to read and write, if provide ‘pos’ parameters, which is to modify the current position to open the file to read and write, if don’t, which is to return the current position to open the file to read and write

io.write(content: string) Writes the contents of ‘content’ to the current opening file

Example:

let io = require 'io';
let lines = io.lines("test/in.txt")     -- Read the contents of the file and put them into lines(table Type)
let text = table.concat(lines, ',')
io.open("test/out.txt", "w")            -- The write mode opens the file (current opening file is test/out.txt)
io.write(text)                          -- Write the text to the currently opening file (i.e., test/out.txt)
let cur_pos = io.seek()                 -- The read-write location for the current open file is cur_pos
io.close()                              -- Close current opening file

net Module

net.listen(address, port) TCP listens on port port of address address, listens to ports of all addresses with ‘0.0.0.0’, returns TcpServer object

net.connect(address, port) Initiating the TCP connection

net.accept(server: TcpServer) The TCP listener block waits for the TCP client connection and returns TcpSocket

net.accept_async(server: TcpServer, handler: Function) TCP asynchronously listen to TCP client connections, and when a new connection occurs, the handler function is triggered using the connection socket

net.start_io_loop(server: TcpServer) Start the TCP asynchronous server event loop, which is called if the accept_async asynchronous TCP service is used

net.read(socket, count) Read the count bytes from the socket

net.read_until(socket, end: string) Read the byte stream from the socket until encounter ‘end’, the return result contains ‘end’

net.write(socket, data) Writes a byte stream or string to a socket

net.close_socket(socket) Close socket connection

net.close_server(server) Close TcpServer

net.shutdown() Close the entire IO event loop

Example:

let server = net.listen("127.0.0.1", 3000)
while true do
    let ctx = net.accept(server)
    let data = net.read(ctx, 10)
    pprint(data)
end

http Module

http.listen(address: string, port: int) Listen to HTTP requests on PORT ports of address

http.connect(address: string, port: int) Connect to the HTTP server side (generally not directly used)

http.request(method: string, url: string, body: string, headers: table) Send HTTP request and return HTTP response

http.close(ctx) Close the HTTP request context

http.accept(server: HttpServer) Wait for the HTTP request and return the HTTP request context

http.accept_async(server: HttpServer, handler: Function) Asynchronously listen to HTTP requests, and when a new HTTP request is received, use the HttpContext object as a parameter for calling handler function

http.start_io_loop(server: HttpServer) Start the HTTP asynchronous server event loop, which is called after the accept_async asynchronous TCP service is used

http.get_req_header(ctx, key: string) Get key value in the HTTP request head message

http.get_res_header(ctx, key: string) Get key value in the HTTP response head messagee

http.get_req_http_method(ctx) Get HTTP methods (string) in the HTTP requests

http.get_req_path(ctx) Get path in the HTTP requests

http.get_req_http_protocol Get HTTP protocol (string) in the HTTP requests

http.get_req_body(ctx) Gets the body content in the HTTP request

http.set_res_header(ctx, key: string, value: string) Set the header information in the HTTP response

http.write_res_body(ctx, data: string) Appends the data to an HTTP response

http.set_status(ctx, status_code: int, status_message: string) Set the status codes and information in the HTTP response

http.get_status(ctx) Gets the status code for the HTTP response

http.get_status_message(ctx) Get the status information (string) in the HTTP response

http.get_res_body(ctx) Get the body content in the HTTP response

http.finish_res(ctx) To pass the HTTP reply to the client, you must call this function to actually response

Here’s an example of the simplest blocking HTTP module (note that this is just a code example of a blocking API, not recommended for direct use)

let http = require 'http'
let net = require 'net'

let res = http.request('GET', "http://www.gov.cn/", '', {
    Accept="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    ["User-Agent"]="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
})
pprint(http.get_res_header(res, "Content-Length"))
pprint(http.get_res_body(res))
http.close(res)

let server = http.listen("0.0.0.0", 3000)

pprint("listening on 0.0.0.0:3000\n")

-- async api

let function handler(ctx)
    let net = require 'net'
    pprint("got new connection", ctx)
    -- pprint('get req body', http.get_req_body(ctx), '\n')
    net.write(ctx, "HTTP/1.1 200 OK\r\nContent-Type:text/html; utf-8\r\nContent-Length:5\r\n\r\nhello")
    net.close_socket(ctx)
end

net.accept_async(server, handler)
net.start_io_loop(server)

pprint("starting sync http server")

while true do
    let ctx = http.accept(server)
    pprint('get req body', http.get_req_body(ctx), '\n')
    http.write_res_body(ctx, "hello world")
    http.set_status(ctx, 200, 'OK')
    http.set_res_header(ctx, "Content-Type", "text/html; utf-8")
    http.finish_res(ctx)
    http.close(ctx)
end

jsonrpc mode

Temporarily Unavailable

Built-in Global Function

The function name Function type signature (return type (parameter function list)) describe

print: (…) => nil Standard output parameters, encountered table or function, output type name: 0000000000000000

pprint: (…) => nil Standard output parameter after tojsonstring results

type: (object) => string According to the run-time parameter type output parameter type corresponding string, return number, string, table, function, boolean, encountered other types of parameters, return to the previous five corresponding string

Such as:

let a1 = 1
let a2 = type(a1) -- The a2 value is' number ', the int and number of the runtime, and the type function returns 'number'.
let b1: object = 1
let b2 = type(b1) -- The b2 value is' number 'because the runtime type is used
type Person = {}
let c1 = Person()
let c2 = type(c1) -- The c2 value is' table ', the table and record type at runtime, and the type function returns' table'

require: (string) => object References to other modules, and not as a contract reference, the referenced module is loaded after the result of the return as a result of the require function

import_contract: (string) => table To reference the contract, the parameter is the name string of the contract and returns the table corresponding to the contract

emit: (string, string) => nil Throw an event event, recorded by the block chain

exit: (object) => object End the run, the parameter is the end code

pairs: (table) => object Returns the iterator of the table, traversing the order is to traverse the array part and then traverse the hash table part of the hash table part of the key key in the string before the traversal, the same string type key, short string in the long string before , The same length of the string key, according to ASCII characters from small to large

ipairs: (table) => object Return the iterator of the array of tables

error: (…) => object error

getmetatable: (table) => table

tostring: (object) => string Turn the parameter into string, for table and function, return type name: 0

tojsonstring: (object) => string Turn the parameter into a json string, for the function, return function: 0, for the nested table in the table, if there is a circular reference, use the ‘address’ substitution value.When json is used, the hash table will be small to large in order of the character of the key, and then the sequence of characters from left to right.For empty table, return “[]”

tonumber: (object) => number Turn the parameter into number, run into a string, read the number from the string, encounter an unparsed string or table or function, and return nil

tointeger: (object) => int Turns the argument into an integer, encounters a string, reads an integer from the string, encounters an unparsed string or table or function, returns nil

todouble: (object) => number Turn the parameter into number type and return nil with an unparsed value

toboolean: (obj) => bool Turn the parameter obj into a Boolean value, and obj returns false on false or nil, otherwise it returns true

totable: (object) => table Use the parameters as table, and if the parameter is not table return nil, it is mainly used to compile the static type conversion

next: (…) => object Move iterators to the next step

rawequal: (object, object) => bool Directly compare whether the two values are the same value (= = comparison is preferred to use the __eq__ function)

rawlen: (object) => int Gets the length of the array of a table directly

rawget: (object, object) => object Gets a property of a table directly

rawset: (object, object, object) => nil Set a property of a table directly

select: (…) => object When the index for the digital will return all the index greater than the index parameters: such as: select (2, “a”, “b”) returns “b”. When the index is a “#”, returns the number of total in the parameters (not including the index)

setmetatable: (table, table) => nil Set the table’s meta-table