Skip to content

Latest commit

 

History

History
1859 lines (1410 loc) · 84.6 KB

manual.md

File metadata and controls

1859 lines (1410 loc) · 84.6 KB

Summary


Basic Concepts

This section describes some basic concepts pertaining the modules described in the following sections.

Await Function

An await function suspends the execution of the calling coroutine (yields no value), but also registers the coroutine to be resumed implicitly on some specific condition.

Coroutines executing an await function can be resumed explicitly by coroutine.resume. In such case, the await function returns the values provided to coroutine.resume. Otherwise, the await function returns as described in the following sections. In any case, the coroutine is not registered to be implicitly resumed anymore once the await function returns.

Blocking Mode

Some await functions accept as argument a string with character ~ to avoid the function to yield. In such case, the function works like ordinary functions blocking the entire Lua state execution until its completion, thus preventing any other coroutine to execute.

Independent State

Chunks that run on a separate system thread are loaded into a independent state with only the package library loaded. This independent state inherits any preloaded modules from the caller of the function that creates it. Moreover, all other standard libraries are also provided as preloaded modules. Therefore function require can be called in the independent state to load all other standard libraries. In particular, basic functions can be loaded using require "_G".

Just bare in mind that requiring the preloaded modules for the standard libraries does not set their corresponding global tables. To mimic the set up of the standard standalone interpreter do something like:

for _, module in ipairs{
	"_G",
	"package", -- loaded, but no global 'package'
	"coroutine",
	"table",
	"io",
	"os",
	"string",
	"math",
	"utf8",
	"debug",
} do
	_ENV[module] = require(module)
end

Note: these independent states run in a separate thread, but share the same memory allocation and panic function of the caller. Therefore, it is required that thread-safe implementations are used, such as the ones used in the standard standalone interpreter.

Transferable Values

Values that are transfered between independent states are copied or recreated in the target state. Only nil, boolean, number, string and light userdata values are allowed as transferable values. Strings, in particular, are replicated in every state they are transfered to.

Failures

Unless otherwise stated, functions return fail on failure, plus an error message as a second result and a system-dependent error code as a third result. On success, some non-false value is returned.

Object-Oriented Style

Some modules that create objects also set a metatable for these objects, where the __index field points to the table with all the functions of the module. Therefore, you can use these library functions in object-oriented style on the objects they create.

Multithreading

This section describes modules for creation of threads of execution of Lua code, either using standard coroutines, or other abstractions that allows to execute code on multiple system threads.

Coroutine Finalizers

Module coutil.spawn provides functions to execute functions in new coroutines with an associated handler function to deal with the results.

spawn.catch (h, f, ...)

Calls function f with the given arguments in a new coroutine. If any error is raised in f, the coroutine executes the error message handler function h with the error message as argument. h is executed in the calling context of the raised error, just like an error message handler in xpcall. Returns the new coroutine.

spawn.trap (h, f, ...)

Calls function f with the given arguments in a new coroutine. If f executes without any error, the coroutine executes function h passing as arguments true followed by all the results from f. In case of any error in f, h is executed with arguments false and the error message. In the latter case, h is executed in the calling context of the raised error, just like a error message handler in xpcall. Returns the new coroutine.

State Coroutines

Module coutil.coroutine provides functions similar to the ones on module coroutine, but for state coroutines. In contrast to standard thread coroutines that execute a function in a Lua thread, state coroutines execute a chunk in an independent state (see system.resume).

You can access these library functions on state coroutines in object-oriented style. For instance, coroutine.status(co, ...) can be written as co:status(), where co is a state coroutine.

coroutine.close (co)

Similar to coroutine.close, but for state coroutines.

coroutine.load (chunk [, chunkname [, mode]])

On success, returns a new state coroutine loaded with the code given by the arguments chunk, chunkname, mode, which are the same arguments of load.

coroutine.loadfile ([filepath [, mode]])

Similar to coroutine.load, but gets the chunk from a file. The arguments filepath and mode are the same of loadfile.

coroutine.status (co)

Similar to coroutine.status, but for state coroutines. In particular, it returns:

  • "running": if the state coroutine is running (that is, it is being executed in another system thread);
  • "suspended": if the state coroutine is suspended in a call to yield (like, when its chunk calls coroutine.yield), or if it has not started running yet;
  • "dead": if the coroutine has finished its chunk, or if it has stopped with an error.

Thread Pools

Module coutil.threads provides functions for manipulation of thread pools that execute code chunks loaded as tasks using a set of distinct system threads.

You can access these library functions on thread pools in object-oriented style. For instance, threads.dostring(pool, ...) can be written as pool:dostring(...), where pool is a thread pool.

threads.create ([size])

On success, returns a new thread pool with size system threads to execute its tasks.

If size is omitted, returns a new reference to the thread pool where the calling code is executing, or nil if it is not executing in a thread pool (for instance, the main process thread).

threads.resize (pool, size [, create])

Defines that thread pool pool shall keep size system threads to execute its tasks.

If size is smaller than the current number of threads, the exceeding threads are destroyed at the rate they are released from the tasks currently executing in pool. Otherwise, new threads are created on demand until the defined value is reached. However, if create evaluates to true, new threads are created to reach the defined value before the function returns.

Returns true on success.

threads.count (pool, options)

Returns numbers corresponding to the ammount of components in thread pool pool according to the following characters present in string options:

  • n: the total number of tasks.
  • r: the number of tasks currently executing.
  • p: the number of tasks pending to be executed.
  • s: the number of tasks suspended on a channel.
  • e: the expected number of system threads.
  • a: the actual number of system threads.

threads.dostring (pool, chunk [, chunkname [, mode, ...]])

Loads a chunk in an independent state as a new task to be executed by the system threads from thread pool pool. It starts as soon as a system thread is available.

Arguments chunk, chunkname, mode are the same of load. Arguments ... are transferable values passed to the loaded chunk.

Whenever the loaded chunk yields it reschedules itself as pending to be resumed, and releases its running system thread.

Execution errors in the loaded chunk terminate the task, and gerenate a warning.

Returns true if chunk is loaded successfully.

Note: the loaded chunk can yield a string with a channel name followed by an endpoint name and the other arguments of system.awaitch to suspend the task awaiting on a channel without the need to load other modules. In such case, coroutine.yield returns just like system.awaitch.

threads.dofile (pool, filepath [, mode, ...])

Similar to threads:dostring, but gets the chunk from a file. The arguments filepath and mode are the same of loadfile.

threads.close (pool)

When this function is called from a task of thread pool pool (that is, using a reference obtained by calling thread.create() without any argument), it has no effect other than prevent further use of pool.

Otherwise, it waits until there are either no more tasks or no more system threads, and closes pool releasing all of its underlying resources.

Note that when pool is garbage collected before this function is called, it will retain minimum resources until the termination of the Lua state it was created. To avoid accumulative resource consumption by creation of multiple thread pools, call this function on every thread pool.

Moreover, a thread pool that is not closed will prevent the current Lua state to terminate (lua_close to return) until it has either no more tasks or no more system threads.

Returns true on success.

Synchronization

This section describes modules for synchronization and communication between threads of execution of Lua code, either between standard coroutines, or independent states running in separate system threads.

Channels

Module coutil.channel provides functions for manipulation of channels to be used to synchronize and transfer values between coroutines running in different states.

Channels can also be used by coroutines in the same state. However events are usually more flexible and efficient in such case.

You can access these library functions on channels in object-oriented style. For instance, channel.sync(ch, ...) can be written as ch:sync(...), where ch is a channel.

channel.close (ch)

Closes channel ch. Note that channels are automatically closed when they are garbage collected, but that takes an unpredictable amount of time to happen.

channel.create (name)

In case of success, returns a new channel with name given by string name.

Channels with the same name share the same two opposite endpoints.

channel.getname (ch)

Returns the name of channel ch.

channel.getnames ([names])

In case of success, returns a table mapping each name of existing channels to true.

If table names is provided, it checks only the names stored as string keys in names, and returns names with each of its string keys set to either true, when there is a channel with that name, or nil otherwise. In other words, any non existent channel name as a key in names is removed from it.

channel.sync (ch, endpoint, ...)

Similar to system.awaitch when there already is a matching call on the endpoint of channel ch. Otherwise, it fails with message "empty".

Events

Module coutil.event provides functions for synchronization of coroutines using events. Coroutines might suspend awaiting for events on any value (except nil) in order to be resumed when events are emitted on these values.

A coroutine awaiting an event on a value does not prevent the value nor the coroutine to be collected, but the coroutine will not be collected as long as the value does not become garbage.

event.await (e)

Equivalent to event.awaitany(e).

event.awaitall ([e1, ...])

Await function that awaits an event on every one of values e1, .... Any nil in e1, ... is ignored. Any repeated values in e1, ... are treated as a single one. If e1, ... are not provided or are all nil, this function returns immediately.

Returns true after events are emitted on all values e1, ..., or if e1, ... are not provided or are all nil.

event.awaitany (e1, ...)

Await function that awaits an event on any of the values e1, .... Any nil in e1, ... is ignored. At least one value in e1, ... must not be nil.

Returns the value in e1, ... on which the event was emmited, followed by all the additional arguments passed to emitone or emitall.

event.emitall (e, ...)

Resumes all coroutines awaiting for event e in the same order they were suspended. The additional arguments ... are passed to every resumed coroutine. This function returns after resuming all coroutines awaiting event e at the moment its call is initiated.

Returns true if there was some coroutine awaiting the event, or false otherwise.

event.emitone (e, ...)

Same as event.emitall, but resumes only one single coroutine awaiting for event e, if there is any.

event.pending (e)

Returns true if there is some coroutine suspended awaiting for event e, or false otherwise.

Queued Events

Module coutil.queued provides functions similar to module coutil.event, however the functions in this module store events emitted in a queue to be consumed later, as if they were emitted immediately after a coroutine awaits for them.

A coroutine awaiting an event on a value does not prevent the value nor the coroutine and the event arguments to be collected, but the coroutine and the event arguments will not be collected as long as the value does not become garbage.

queued.await (e)

Same as event.await, but it consumes a stored event emitted on value e, if there is any.

queued.awaitall ([e1, ...])

Same as event.awaitall, but it first attempts to consume one stored event on each value e1, ..., and only await on the values e1, ... that do not have a stored event.

queued.awaitany (e1, ...)

Same as event.awaitany, but if there is a stored event on any of values e1, ..., the stored event on the leftmost value e1, ... is consumed instead of awaiting for events.

queued.emitall (e, ...)

Same as event.emitall, but if there is no coroutine awaiting on e, it stores the event to be consumed later.

queued.emitone (e, ...)

Same as event.emitone, but if there is no coroutine awaiting on e, it stores the event to be consumed later.

queued.isqueued (e)

Returns true if there is some stored event on e, or false otherwise.

queued.pending (e)

Alias for event.pending.

Mutex

Module coutil.mutex provides functions for mutual exclusion of coroutines when using a resource.

mutex.lock (e)

Acquires to the current coroutine the exclusive ownership identified by value e. If the ownership is not taken then the function acquires the ownership and returns immediately. Otherwise, it awaits an event on value e until the ownership is released (see mutex.unlock), so it can be acquired to the coroutine.

mutex.unlock (e)

Releases from the current coroutine the exclusive ownership identified by value e. It also emits an event on e to resume one of the coroutines awaiting to acquire this ownership (see mutex.lock).

mutex.islocked (e)

Returns true if the exclusive ownership identified by value e is taken, and false otherwise.

mutex.ownlock (e)

Returns true if the exclusive ownership identified by value e belongs to the calling coroutine, and false otherwise.

Promises

Module coutil.promise provides functions for synchronization of coroutines using promises. Promises are used to obtain results that will only be available at a later moment, when the promise is fulfilled. Coroutines that claim an unfulfilled promise suspend awaiting its fulfillment in order to receive the results. But once a promise is fulfilled its results become readily available for those that claims them.

promise.create ()

Returns a new promise, followed by a fulfillment function.

The promise is a function that returns the promise's results. If the promise is unfulfilled, it suspends the calling coroutine awaiting its fulfillment. If the promise is called with an argument that evaluates to true, it never suspends the calling coroutine, and just returns true if the promise is fulfiled, or false otherwise.

The fulfillment function shall be called in order to fulfill the promise. The arguments passed to the fulfillment function become the promise's results. It returns true the first time it is called, or false otherwise.

Coroutines suspeded awaiting a promise's fulfillment are actually suspended awaiting an event on the promise (see await). Such coroutines can be resumed by emitting an event on the promise. In such case, the additional values to emitone or emitall will be returned by the promise. Similarly, the coroutines can be resumed prematurely by coroutine.resume. In such case, the promisse returns the values provided to the resume (like coroutine.yield). In either case, the promise will remain unfulfilled. Therefore, when the promise is called again, it will suspend the calling coroutine awaiting an event on the promise (the promise fulfillment).

The first time the fulfillment function is called, an event is emitted on the promise with the promise's results as additional values. Therefore, to suspend awaiting the fulfillment of a promise, a coroutine can simply await an event on the promise. However, once a promise is fulfilled, any coroutine that suspends awaiting events on the promise will remain suspended until an event on the promise is emitted, since the fulfillment function will not emit the event even if is called again.

promise.awaitall ([p, ...])

Await function that awaits the fulfillment of all promises p, .... Returns true when all promises p, ... are fulfilled.

promise.awaitany (p, ...)

Await function that awaits the fulfillment of any of the promises in p, ..., if there are no fulfilled promises in p, .... Otherwise it returns immediately. In any case, it returns a fulfilled promise.

promise.onlypending ([p, ...])

Returns all promises p, ... that are unfulfilled.

promise.pickready ([p, ...])

Returns the first promise p, ... that is fulfilled, or no value if none of promises p, ... is fulfilled.

System Features

Module coutil.system provides functions that expose system functionalities, including await functions to await on system conditions.

Event Processing

This section describes functions of coutil.system related to the processing of system events and resumption of coroutines executing await functions of coutil.system.

system.run ([mode])

Resumes coroutines executing await functions of coutil.system when they are ready, which is when their await function have some result to process. Note that even though a coroutine is ready, its await function may not return just yet, because it may require additional results to conclude and return.

mode is a string that defines how run executes, as described below:

  • "loop" (default): it executes continously resuming every awaiting coroutine when they become ready, until there are no more coroutines awaiting, or system.halt is called.
  • "step": it resumes every ready coroutine once, or waits to resume at least one coroutine that becomes ready.
  • "ready": does not wait, and just resumes coroutines that are currently ready.

Returns true if there are remaining awaiting coroutines, or false otherwise.

Note: when called with mode as "loop" in the chunk of a task and there are only system.awaitch calls pending, this call yields, suspending the task until one of the pending calls is matched.

system.isrunning ()

Returns true if system.run is executing, or false otherwise.

system.halt ()

Sets up system.run to terminate prematurely, and returns before system.run terminates. Must be called while system.run is executing.

Thread Synchronization

This section describes functions of coutil.system for thread synchronization and communication using channels and state coroutines.

system.awaitch (ch, endpoint, ...)

Await function that awaits on an endpoint of channel ch for a similar call on the opposite endpoint, either from another coroutine, or task.

endpoint is either string "in" or "out", each identifying an opposite endpoint. Therefore, the call system.awaitch(ch1, "in") will await for a call like system.awaitch(ch2, "out") if both ch1 and ch2 are distinct channels with the same name.

Alternativelly, if endpoint is either nil or "any", the call will await for a matching call on either endpoints. For instance, the call system.awaitch(ch1, "any") will match either a call system.awaitch(ch2, "in"), or system.awaitch(ch2, "out"), or even system.awaitch(ch2, "any") if both ch1 and ch2 are distinct channels with the same name.

Returns true followed by the extra transferable arguments ... from the matching call. Otherwise, it fails with an error message related to transfering the arguments from the matching call. In any case, if this call does not raise errors, nor is resumed prematurely by a call of coroutine.resume, then it successfully resumed the coroutine or task of the matching call.

system.resume (co, ...)

Similar to coroutine.resume, but for state coroutines. It is an await function that executes state coroutine co on a separate system thread, and awaits for its completion or suspension. Moreover, only transferable values can be passed as arguments, yielded, or returned from co.

If the coroutine executing this await function is explicitly resumed, the execution of co continues in the separate thread, and it will not be able to be resumed again until it suspends. In such case, the results of this execution of co are discarded.

State coroutines are executed using a limited set of threads that are also used by the underlying system to execute some await functions. The number of threads is given by environment variable UV_THREADPOOL_SIZE. Therefore, state coroutines that do not execute briefly, might degrade the performance of some await functions.

For long running tasks, consider using a thread pool.

Time Measure

This section describes functions of coutil.system to obtain a measure of time or to wait for a particular period of time.

system.nanosecs ()

Returns a timestamp in nanoseconds that represents the current time of the system. It increases monotonically from some arbitrary point in time, and is not subject to clock drift.

system.time ([mode])

Returns a timestamp as a number of seconds with precision of milliseconds according to the value of mode, as described below:

  • "cached" (default): the cached timestamp periodically updated by system.run before resuming coroutines that are ready. It is used as the current time to calculate when future calls to system.suspend shall be resumed. It increases monotonically from some arbitrary point in time, and is not subject to clock drift.
  • "updated": updates the cached timestamp to reflect the current time, and returns this updated timestamp.
  • "epoch": a timestamp relative to UNIX Epoch, based on the current time set in the system. Therefore, unlike the other options, it is affected by discontinuous jumps in the system time (for instance, if the system administrator manually changes the system time).

system.suspend ([seconds [, mode]])

Await function that awaits seconds since timestamp provided by system.time("cached").

If seconds is not provided, is nil, or negative, it is assumed as zero, so the calling coroutine will be resumed as soon as possible.

If string mode is provided with character ~, it executes in blocking mode.

System Processes

This section describes functions of coutil.system for manipulation of the current process (signals, priority, current directory, and environment variables), and other processes, as well as creating new processes by executing programs.

system.emitsig (pid, signal)

Emits a signal specified by string signal to the process with identifier pid. Aside from the values for signal listed in system.awaitsig, this function also accepts the following values for signal:

signal POSIX Action
"STOP" SIGSTOP stop
"TERMINATE" SIGKILL terminate

signal can also be the platform-dependent number of the signal to be emitted.

system.awaitsig (signal)

Await function that awaits for the current process to receive the signal indicated by string signal, as listed below:

signal POSIX Action Indication
"abort" SIGABRT core dump Process shall abort.
"brokenpipe" SIGPIPE terminate Write on a pipe with no one to read it.
"child" SIGCHLD ignore Child process terminated, stopped, or continued.
"clocktime" SIGALRM terminate Real or clock time elapsed.
"continue" SIGCONT continue Process shall continue, if stopped.
"cpulimit" SIGXCPU core dump Defined CPU time limit exceeded.
"cputime" SIGVTALRM terminate CPU time used by the process elapsed.
"cputotal" SIGPROF terminate CPU time used by the process and by the system on behalf of the process elapses.
"filelimit" SIGXFSZ core dump Allowed file size limit exceeded.
"hangup" SIGHUP terminate Terminal was closed.
"interrupt" SIGINT terminate Terminal requests the process to terminate. (Ctrl+C)
"polling" SIGPOLL terminate Event occurred on watched file descriptor.
"quit" SIGQUIT core dump Terminal requests the process to quit with a core dump. (Ctrl+\)
"stdinoff" SIGTTIN stop Read from terminal while in background.
"stdoutoff" SIGTTOU stop Write to terminal while in background.
"stop" SIGTSTP stop Terminal requests the process to stop. (Ctrl+Z)
"sysargerr" SIGSYS core dump System call with a bad argument.
"terminate" SIGTERM terminate Process shall terminate.
"trap" SIGTRAP core dump Exception or debug trap occurs.
"urgentsock" SIGURG core dump High-bandwidth data is available at a socket.
"userdef1" SIGUSR1 terminate User-defined conditions.
"userdef2" SIGUSR2 terminate User-defined conditions.
"winresize" SIGWINCH ignore Terminal window size has changed.

Returns string signal in case of success.

Note: not all signals are availabe in all platforms. For more details, see the documentation on signal support by libuv.

system.getpriority (pid)

On success, returns a string and a number corresponding to the scheduling priority of the process with identifier pid. The first value returned is one of the following strings, which indicates some convenient distinct priority value (from highest to lowest):

  • "highest"
  • "high"
  • "above"
  • "normal"
  • "below"
  • "low"

The string "other" is returned for any other priorities values placed inbetween these reference values.

The second returned value is a number ranging from -20 (for highest priority) to 19 (for lowest priority) corresponding to the scheduling priority of the process.

system.setpriority (pid, value)

Changes the scheduling priority of the process with identifier pid. value can be any of the string or number values described as the return values of system.getpriority, except string "other", which does not denote a specific priority value.

system.getdir ()

On success, returns the path of the current working directory.

system.setdir (path)

Changes the current working directory to the path in string path.

system.getenv ([name])

If name is not provided, returns a table mapping all current environment variable names to their corresponding values.

Alternatively, If name is a table, the results are added to it, and name is returned.

Otherwise, name is the name of the process environment variable which value must be returned. Fails if the variable name is not defined.

system.setenv (name, value)

Sets the contents of string value as the value of the process environment variable name. If value is nil, deletes the environment variable.

system.packenv (vars)

Returns a packed environment that encapsulates environment variables from table vars, which shall map variable names to their corresponding value.

Note: by indexing a packed environment env, like env.LUA_PATH, a linear search is performed in the list of packed variables to return the value of variable LUA_PATH. If such variable does not exist in the packed environment, nil is returned.

system.unpackenv (env [, tab])

Returns a table mapping all environment variable names in packed environment env to their corresponding values. If table tab is provided, the results are added to it, and tab is returned.

system.execute (cmd, ...)

Await function that executes a new process, and awaits its termination. cmd is the path of the executable image for the new process. Every other extra arguments are strings to be used as command-line arguments for the executable image of the new process.

Alternatively, cmd can be a table with the fields described below. Unless stated otherwise, when one of these field are not defined in table cmd, or cmd is a string, the new process inherits the characteristics of the current process, like the current directory, the environment variables, or standard files.

  • execfile: path of the executable image for the new process. This field is required.

  • runpath: path of the current directory of the new process.

  • stdin, stdout, stderr: the standard input, output and error output of the new process. The possible values are:

    • A Lua file to be provided to the process.
    • A stream socket to be provided to the process.
    • false to indicate it should be discarded (for instance, /dev/null shall be used).
    • A string with the following characters that indicate a stream socket shall be created and stored in the field to allow communication with the process.
      • r: a readable stream socket to receive data from the process.
      • w: a writable stream socket to send data to the process.
      • s: a stream socket that allows transmission of stream sockets (see domain "share").
  • arguments: table with the sequence of command-line arguments for the executable image of the new process. When this field is not provided, the new process's executable image receives no arguments.

  • environment: a packed environment created by system.packenv, or a table mapping environment variable names to the values they must assume for the new process. In the latter case, a packed environment is implicitly created from the table. If this field is provided, only the variables defined will be available for the new process.

If cmd is a table, the field pid is set with the identifier of the new process before the calling coroutine is suspended.

Returns the string "exit", followed by a number of the exit status when the process terminates normally. Otherwise, it returns a string indicating the signal that terminated the program, as accepted by system.emitsig, followed by the platform-dependent number of the signal. For signals not listed there, the string "signal" is returned instead. Use the platform-dependent number to differentiate such signals. It fails if the process cannot be created.

Network & IPC

This section describes functions of coutil.system for creation of network sockets and other IPC mechanisms.

system.address (type [, data [, port [, mode]]])

Returns a new IP address structure. type is either the string "ipv4" or "ipv6", to indicate the address to be created shall be a IPv4 or IPv6 address, respectively.

If data is not provided the structure created is initilized with null data: 0.0.0.0:0 for "ipv4", or [::]:0 for "ipv6". Otherwise, data is a string with the information to be stored in the structure created.

If only data is provided, it must be a literal address as formatted inside a URI, like "192.0.2.128:80" (IPv4), or "[::ffff:c000:0280]:80" (IPv6). Moreover, if port is provided, data is a host address and port is a port number to be used to initialize the address structure. The string mode controls whether data is textual or binary. It may be the string "b" (binary data), or "t" (text data). The default is "t".

The following calls create addresses with the same contents:

system.address("ipv4")
system.address("ipv4", "0.0.0.0:0")
system.address("ipv4", "0.0.0.0", 0)
system.address("ipv4", "\0\0\0\0", 0, "b")

The returned object provides the following fields:

  • type: (read-only) is either the string "ipv4" or "ipv6", to indicate the address is a IPv4 or IPv6 address, respectively.
  • literal: is the text representation of the host address, like "192.0.2.128" (IPv4) or "::ffff:c000:0280" (IPv6).
  • binary: is the binary representation of the host address, like "\192\0\2\128" (IPv4) or "\0\0\0\0\0\0\0\0\0\0\xff\xff\xc0\x00\x02\x80" (IPv6).
  • port: is the port number of the IPv4 and IPv6 address.

Moreover, you can pass the object to the standard function tostring to obtain the address as a string inside a URI, like "192.0.2.128:80" (IPv4) or [::ffff:c000:0280]:80 (IPv6).

system.nameaddr (address [, mode])

Await function that searches for a network name for address, and awaits for the names found. If address is an address object, it returns a host name and a port service name for the address. If address is a number, it returns the service name for that port number. If address is a string, it returns a canonical name for that network name.

The string mode can contain any of the following characters:

  • l: for local names instead of Fully Qualified Domain Names (FQDN).
  • d: for names of datagram services instead of stream services.
  • i: for names in the Internationalized Domain Name (IDN) format.
  • u: allows unassigned Unicode code points (implies i).
  • a: checks host name is conforming to STD3 (implies i).

By default, mode is the empty string.

system.findaddr (name [, service [, mode]])

Await function that searches for the addresses of network name name, and awaits for the addresses found. If name is nil, the loopback address is searched. If name is "*", the wildcard address is searched.

service is either a service name to be used to resolve the port number of the resulting addresses, or a port number to be set in the resulting addresses. When service is absent, the port zero is used in the results. The string mode defines the search domain. It can contain any of the following characters:

  • 4: for IPv4 addresses.
  • 6: for IPv6 addresses.
  • m: for IPv4-mapped addresses.
  • d: for addresses for datagram sockets.
  • s: for addresses for stream or passive sockets.

When neither 4 nor 6 are provided, the search only includes addresses of the same type configured in the local machine. When neither d nor s are provided, the search behaves as if both d and s were provided. By default, mode is the empty string.

In case of success, returns an addresses object that encapsulates all addresses found, and provides methods to navigate through the addresses found and get them.

addresses:close ()

Closes addresses, releasing all its internal resources. It also prevents further use of its methods.

addresses:next ()

Returns false if addresses points to its last address. Otherwise, returns true and makes addresses point to the next address.

addresses:reset ()

Makes addresses point to the first address. Returns no value.

addresses:getaddress ([address])

Stores the address pointed by addresses in address, and returns it. If address is not provided, the pointed address is stored in a new address and returned.

addresses:getdomain ()

Returns the type of the address pointed by addresses. The possible values are the same of attribute type of an address.

addresses:getsocktype ()

Returns the type of the socket to be used to connect to the address pointed by addresses. The possible values are the same of argument type of system.socket.

system.socket (type, domain)

Creates a socket of the type specified by type, which is either:

  • "datagram" creates datagram socket for data transfers.
  • "stream" creates stream socket for data transfers.
  • "passive" creates passive socket to accept connected stream sockets.

The domain string defines the socket's address domain (or family), which is either:

  • "ipv4" for UDP (datagram) or TCP (stream) sockets over IPv4.
  • "ipv6" for UDP (datagram) or TCP (stream) sockets over IPv6.
  • "local" for sockets which addresses are file paths on Unix, or pipe names on Windows.
  • "share" same as "local", but allows for transmission of stream sockets.

In case of success, it returns the new socket.

socket:close ()

Closes socket socket. Note that sockets are automatically closed when they are garbage collected, but that takes an unpredictable amount of time to happen.

socket:getdomain ()

Returns the address domain of socket, The possible values are the same of argument domain in system.socket.

socket:setoption (name, value, ...)

Sets value as the value of option name for socket socket. This operation is not available for passive TCP sockets. The available options are:

UDP Socket

  • "broadcast": value is true to enable broadcast in socket, or false otherwise.
  • "mcastloop": value is true to enable loopback of outgoing multicast datagrams, or false otherwise.
  • "mcastttl": value is a number from 1 to 255 to define the multicast time to live.
  • "mcastiface": value is the literal host address of the interface for multicast. Otherwise, an appropriate interface is chosen by the system.
  • "mcastjoin" or "mcastleave": value is the literal host address of the multicast group the application wants to join or leave. If an extra third argument is provided, it is the literal host address of the local interface with which the system should join or leave the multicast group. Otherwise, an appropriate interface is chosen by the system. If an extra fourth argument is provided, it defines the literal host address of a source the application shall receive data from. Otherwise, it can receive data from any source.

TCP Socket

  • "keepalive": value is a number of seconds of the initial delay of the periodic transmission of messages when the TCP keep-alive option is enabled, or nil otherwise.
  • "nodelay": value is true when coalescing of small segments shall be avoided, or false otherwise.

Local Socket

  • "permission": value is a string that indicate the permissions over the socket by processes run by other users. It can contain the following characters:
    • r indicate processes have permission to read from the socket.
    • w indicate processes have permission to write to the socket.

socket:bind (address)

Binds socket socket to the address provided as address.

For non-local sockets address must be an IP address. For local sockets address must be a string (either a path on Unix or a pipe name on Windows).

socket:connect ([address])

Binds socket socket to the peer address provided as address, thus any data send over the socket is targeted to that address.

For non-local domain sockets, address must be an IP address. For local domain sockets, address must be a string (either a path on Unix or a pipe name on Windows).

If address is not provided and socket is a datagram socket then it is unbinded from its previous binded peer address (that is, it is disconnected). For stream sockets argument address is mandatory, and it is necessary to bind the socket to a peer address before sending any data. It is an await function that awaits for the connection establishment on stream sockets. This operation is not available for passive sockets.

socket:getaddress ([site [, address]])

On success, returns the address associated with socket socket, as indicated by site, which can be:

  • "self": The socket's address (the default).
  • "peer": The socket's peer address.

For non-local domain sockets, address can be an IP address to store the result, otherwise a new address object is returned with the result data. For local domain sockets, it returns a string (either a path on Unix or a pipe name on Windows).

socket:write (data [, i [, j [, address]]])

Await function that awaits until it sends through socket socket the substring of data that starts at i and continues until j, following the same sematics of these arguments in functions of memory.

For unbinded datagram sockets, address must be destination address, but it must be omitted for datagram sockets binded to a peer address. For stream sockets, address is ignored, except for "share" stream sockets, where address might be the stream socket to be transferred. This operation is not available for passive sockets.

Note: if data is a memory, it is not converted to a Lua string prior to have its specified contents transfered.

socket:read (buffer [, i [, j [, address]]])

Await function that awaits until it receives from socket socket at most the number of bytes necessary to fill memory buffer from position i until j, following the same sematics of these arguments in functions of memory.

For datagram sockets, if address is provided, it is used to store the peer address that sent the data. For stream sockets, address is ignored. This operation is not available for passive sockets.

In case of success, this function returns the number of bytes copied to buffer. For datagram sockets, it also returns a boolean indicating whether the copied data was truncated. For "share" stream sockets, it returns the transfered stream socket after the number of bytes.

socket:shutdown ()

Shuts down the write side of stream socket socket.

This operation is only available for stream sockets.

socket:listen (backlog)

Starts listening for new connections on passive socket socket. backlog is a hint for the underlying system about the suggested number of outstanding connections that shall be kept in the socket's listen queue.

This operation is only available for passive sockets.

socket:accept ()

Await function that awaits until passive socket socket accepts a new connection.

This operation is only available for passive sockets.

In case of success, this function returns a new stream socket for the accepted connection.

File System

This section describes functions of coutil.system to access files and the file system.

system.linkfile (path, destiny [, mode])

Await function that awaits for the creation of a link on path destiny refering the file on path given by string path.

It fails if a file in destiny already exists.

String mode might contain s to create a symbolic link, instead of a hard link.

On Windows, mode can contain the following characters to control how the symbolic link will be created. (all imply s):

  • d: indicates that path points to a directory.
  • j: request that the symlink is created using junction points.

mode might also contain character ~ to execute it in blocking mode.

system.copyfile (path, destiny [, mode])

Await function that awaits until file from path is copied to path given by string destiny.

mode can contain the following characters:

  • ~: executes in blocking mode.
  • n: fails if already exists a file in destiny.
  • c: attempt to create a copy-on-write reflink.
  • C: creates a copy-on-write reflink, or fails otherwise.

system.movefile (path, destiny [, mode])

Await function that awaits until file from path is moved to path given by string destiny.

If string mode is provided with character ~, it executes in blocking mode.

system.removefile (path [, mode])

Await function that awaits to remove from path path a file, or an empty directory if mode is a string with character d. mode might also contain character ~ to execute it in blocking mode.

system.maketemp (prefix [, mode])

Await function that awaits for the creation of a uniquely named temporary directory or file with the prefix given by string prefix.

String mode might contain any of the following characters to make it create a file instead of a directory. These characters also define the sequence of values returned by the call in case of success.

  • f: returns the path to the file created.
  • o: returns the created file already opened.

If mode does not contain any of the above characters, this function returns the path to the created directory on success.

mode might also be prefixed with character ~ to execute it in blocking mode.

By default, mode is the empty string.

system.makedir (path, perm [, mode])

Await function that awaits the creation of a new directory on path. perm indicates the permissions of the directory to be created, just like argument perm of file:grant.

It fails if a file in path already exists.

If string mode is provided with character ~, it executes in blocking mode.

system.listdir (path [, mode])

Await function that awaits to obtain the list of the file entries in the directory in path.

On success, returns an iterator that lists the entries obtained. The control variable is the name of the file entry, and an additional loop variable is a string with the type of the file entry (same values by ? in file:info).

If string mode is provided with character ~, it executes in blocking mode.

This function never fails. It raises errors instead.

system.touchfile (path [, mode, times...])

Similar to file:touch, but for file in path given by string path. The other arguments are the same of file:touch.

mode can also be prefixed with l to indicate that, if path refers a symbolic link, the time values are changed for the symbolic link file instead of the link's target file.

system.ownfile (path, uid, gid [, mode])

Similar to file:own, but for file in path given by string path. The other arguments are the same of file:own.

mode can also be prefixed with l to indicate that, if path refers a symbolic link, the ownership is changed for the symbolic link file instead of the link's target file.

system.grantfile (path, perm [, mode])

Similar to file:grant, but for file in path given by string path. The other arguments are the same of file:grant.

system.openfile (path [, mode [, perm]])

Await function that awaits until file in path in opened. The string mode can contain the following characters that define how the file is opened.

  • a: write operations are done at the end of the file (implies w).
  • n: if such file does not exist, instead of failing, a new file is created in path and opened.
  • N: ensure a new file is created in path, or fails otherwise.
  • r: allows reading operations.
  • f: write operations transfers all data to the file's device (implies w).
  • t: file contents are erased, that is, it is truncated to length 0 (implies w).
  • w: allows writing operations.
  • x: file is not inheritable to child processes (see O_CLOEXEC).

mode might also be prefixed with character ~ to execute it in blocking mode.

When either n or N are present in mode, perm indicates the permissions of the file to be created, just like argument perm of file:grant.

Note: these file permissions are not enforced by the call that creates the file. They only affect future accesses. Files created by this call always allows for all permissions regardless of the permissions defined.

On success, returns the file opened.

file:close ([mode])

Await function that awaits until file is closed. Note that files are automatically closed when they are garbage collected, but that takes an unpredictable amount of time to happen.

If string mode is provided with character ~, it executes in blocking mode.

file:read (buffer [, i [, j [, offset [, mode]]]])

Await function that awaits until it reads from file file at most the number of bytes necessary to fill memory buffer from position i until j, following the same sematics of these arguments in functions of memory.

If offset is provided, it is the byte offset from the begin of the file where the data must be read. In such case, the file offset is not changed by this call. Otherwise, the current file offset is used and updated.

If string mode is provided with character ~, it executes in blocking mode.

On success, returns the number of bytes copied to buffer.

file:write (data [, i [, j [, offset [, mode]]]])

Await function that awaits until it writes to file file the substring of data that starts at i and continues until j, following the same sematics of these arguments in functions of memory.

If offset is provided, it is the byte offset from the begin of the file where the data must be written. In such case, the file offset is not changed by this call. Otherwise, the current file offset is used and updated.

If data is a file opened for reading, it works as if the contents of the file were the string data. In such case, i and j are mandatory, and must be positive. Moreover, offset is ignored in this case, thus the current offset of file is used and updated.

If string mode is provided with character ~, it executes in blocking mode.

On success, returns the number of bytes written to file.

file:resize (size [, mode])

Await function that awaits until it resizes file to size bytes. If the file is larger than this size, the extra data is lost. If the file is shorter, it is extended, and the extended part reads as null bytes.

If string mode is provided with character ~, it executes in blocking mode.

file:flush ([mode])

Await function that awaits until it saves any data written to file into the file's device.

If string mode contains d, it minimizes the device activity by skipping metadata not necessary for later data retrieval.

mode might also contain character ~ to execute it in blocking mode.

file:touch ([mode, times...])

Await function that awaits until it changes the access and modification times of file. String mode contains a sequence of characters indicating how each provided time value times... shall be used in file.

  • a: as the access time.
  • m: as the modification time.
  • b: as both access and modification times.

Whenever a time value is not provided for either the access or modification time, the current time set in the system is used.

mode might also be prefixed with character ~ to execute it in blocking mode. Unlike other characters, ~ does not consume a time value from times....

Note: all time values are seconds relative to UNIX Epoch with sub-second precision.

file:own (uid, gid [, mode])

Await function that awaits until it changes the owner IDs of file to numbers uid for the user ID, and gid for the group ID. If the uid or gid is specified as -1, then that ID is not changed.

If string mode is provided with character ~, it executes in blocking mode.

file:grant (perm [, mode])

Await function that awaits until it changes the permission bits of file. perm must be either a number with the permission bits, or a string with characters defining the bits to be set for the file, as listed below:

  • U Set-user-ID bit.
  • G Set-group-ID bit.
  • S Sticky bit.
  • r Read permission for the file's onwer user ID.
  • w Write permission for the file's onwer user ID.
  • x Execute permission for the file's onwer user ID.
  • R Read permission for the file's owner group ID.
  • W Write permission for the file's owner group ID.
  • X Execute permission for the file's owner group ID.
  • 4 Read permission for others.
  • 2 Write permission for others.
  • 1 Execute permission for others.

If string mode is provided with character ~, it executes in blocking mode.

file:info (mode)

Await function that awaits for information related to file.

On success, returns values according to the following characters in string mode:

Character Value Description
? string Type of the file as one of the field names of bitmasks for file types.
M integer Bit flags of the file (imode mode).
_ integer User defined flags for the file.
u integer Owner user identifier (uid).
g integer Owner user group identifier (gid).
# integer ID of the file in the file system (inode number).
D integer ID of the device containing the file.
d integer ID of the device represented by the file, or 0 if not applicable.
* integer Number of hard links to the file.
B integer Total size of the file (bytes).
b integer Number of 512B blocks allocated for the file.
i integer Ideal transfer block size for the file.
v integer Generation number of the file.
a number Time of last access of the file.
s number Time of last status change of the file.
m number Time of last modification of the file.
c number Time of file creation.

mode can also contain any of the characters valid for argument perm of file:grant. For these characters a boolean is returned indicating whether such bit is set.

mode might also be prefixed with character ~ to execute it in blocking mode. Unlike other characters, ~ does not produce a value to be returned.

Note: all time values returned are seconds relative to UNIX Epoch.

system.filebits

Table with the following fields with numberic values of the bitmask for file mode bits.

File Types

  • type: Bitmask for the following fields identifying different file types:
    • socket: Socket file type.
    • link: Symbolic link file type.
    • file: Regular file type.
    • block: Block device file type.
    • directory: Directory file type.
    • character: Character device file type.
    • pipe: FIFO file type.

Permissions

  • setuid: Set-user-ID bit.
  • setgid: Set-group-ID bit.
  • sticky: Sticky bit.
  • ruser: Read permission bit for the file's onwer user ID.
  • wuser: Write permission bit for the file's onwer user ID.
  • xuser: Execute permission bit for the file's onwer user ID.
  • rgroup: Read permission bit for the file's owner group ID.
  • wgroup: Write permission bit for the file's owner group ID.
  • xgroup: Execute permission bit for the file's owner group ID.
  • rother: Read permission bit for others.
  • wother: Write permission bit for others.
  • xother: Execute permission bit for others.

system.fileinfo (path, mode)

Similar to file:info but for file in path given by string path. In addition to the characters supported by file:info, mode can also contain:

Character Value Description
p string Canonicalized absolute path name for the file.
= string The value of the symbolic link, or nil if path does not refer a symbolic link.
@ string Type of the file system of the file.
N integer Numeric ID of the type of the file system of the file.
I integer Ideal transfer block size for the file system of the file.
A integer Free blocks available to unprivileged user in the file system of the file.
F integer Free blocks in the file system of the file.
f integer Free inodes in the file system of the file.
T integer Total data blocks in the file system of the file.
t integer Total inodes in the file system of the file.

Moreover, mode can also be prefixed with l to indicate that, if path refers a symbolic link, the values corresponding to characters supported by file:info shall be about the symbolic link file instead of the link's target file. The value of the other options are not affected. Similar to ~, l does not produce a value to be returned.

Standard Streams

This section describes objects provided in coutil.system to access the current process standard streams.

system.stdin|stdout|stderr

Terminal, socket or file representing the standard input (stdin), output (stdout), or error (stderr) stream of the current process. Or nil if the type of such stream is unsupported.

terminal:close ()

Closes terminal terminal.

terminal:read (buffer [, i [, j]])

Same as read of stream sockets.

terminal:write (data [, i [, j]])

Same as write of stream sockets.

terminal:shutdown ()

Same as shutdown of stream sockets.

terminal:setmode (mode)

Sets the terminal mode, according the following values of mode:

  • "normal": normal terminal mode
  • "raw": raw input mode (on Windows, ENABLE_WINDOW_INPUT is also enabled)
  • "binary": binary-safe I/O mode for IPC (Unix-only)

terminal:winsize ()

Returns the width and height of the current terminal window size (in number of characters).

System Information

This section describes functions of coutil.system for obtaining information provided or maintained by the underlying operating system.

system.procinfo (which)

Returns values corresponding to information about the current process and the system where it is running. The following characters in string which define the values to be returned:

Character Value Description
e string executable file path of the process (see note below).
n string network host name of the system.
T string current temporary directory path.
h string operating system hardware name.
k string operating system kernel name.
v string operating system release version name.
V string operating system version name.
$ string current user shell path.
H string current user home directory path.
U string current user name.
u integer current user identifier (uid).
g integer current user group identifier (gid).
= integer integral unshared stack size of the process (bytes).
d integer integral unshared data size of the process (bytes).
m integer integral shared memory size of the process (bytes).
R integer maximum resident set size of the process (bytes).
< integer IPC messages received by the process.
> integer IPC messages sent by the process.
i integer block input operations of the process.
o integer block output operations of the process.
p integer page reclaims (soft page faults) of the process.
P integer page faults (hard page faults) of the process.
S integer signals received by the process.
w integer swaps of the process.
x integer voluntary context switches of the process.
X integer involuntary context switches of the process.
c number user CPU time used of the process (seconds).
s number system CPU time used of the process (seconds).
1 number system load of last 1 minute.
l number system load of last 5 minutes.
L number system load of last 15 minutes.
t number current system uptime (seconds).
# integer current process identifier (pid).
^ integer parent process identifier (pid).
b integer total amount of physical memory in the system (bytes).
f integer amount of free memory available in the system (bytes).
M integer limit of memory available to the process (bytes).
r integer resident memory size of the process (bytes).

This function never fails. It raises errors instead.

Note: option "e" may raise an error on Unix and AIX systems when used in the standard standalone interpreter or any program that does not execute uv_setup_args properly.

system.cpuinfo (which)

Returns an iterator that produces information about each individual CPU of the system in each iteration. The control variable is the index of the CPU. The values of the other loop variables are given by the following characters in string which:

Character Value Description
m string CPU model name.
c integer current CPU clock speed (MHz).
u integer time the CPU spent executing normal processes in user mode (milliseconds).
n integer time the CPU spent executing prioritized (niced) processes in user mode (milliseconds).
s integer time the CPU spent executing processes in kernel mode (milliseconds).
d integer time the CPU spent servicing device interrupts. (milliseconds).
i integer time the CPU was idle (milliseconds).

This function never fails. It raises errors instead.

Note: the state value returned is which, and it only dictates how the values are returned in each call, because the iterator contains all the information that can be produced. The initial value for the control variable is 0. Also, the iterator is the closing value used, therefore it can be used in a to-be-closed variable. Finally, the iterator supports the length operator # to obtain the number of elements to be iterated.

system.netinfo (option, which)

Returns values according to the value of option, as described below:

  • "name": the name of the network interface corresponding to the interface index which.
  • "id": a string with the identifier suitable for use in an IPv6 scoped address corresponding to the interface index which.
  • "all": an iterator that produces information about the addresses of the network interfaces of the system. The control variable is the index of the network interface address, not the interface index. The values of the other loop variables are given by the following characters in string which:
Character Value Description
n string the name of the network interface.
i boolean true if the network interface address is internal, or false otherwise.
d string the domain of the network interface address ("ipv4" or "ipv6").
l integer the length of the subnet mask of the network interface address.
m string the binary representation of the subnet mask of the network interface address.
t string the text representation of the network interface address.
b string the binary representation of the network interface address.
T string the text representation of the physical address (MAC) of the network interface.
B string the binary representation physical address (MAC) of the network interface.

Note: this iterator have the same characteristics of the one returned by system.cpuinfo.

system.random (buffer [, i [, j [, mode]]])

Await function that awaits until it fills memory buffer with cryptographically strong random bytes, from position i until j, following the same sematics of these arguments in functions of memory.

If string mode is provided with character ~, it executes in blocking mode.

In case of success, this function returns buffer.

Note: this function may not complete when the system is low on entropy.

Index

coutil.channel
    channel.close
    channel.create
    channel.getname
    channel.getnames
    channel.sync
coutil.coroutine
    coroutine.close
    coroutine.load
    coroutine.loadfile
    coroutine.status
coutil.event
    event.await
    event.awaitall
    event.awaitany
    event.emitall
    event.emitone
    event.pending
coutil.mutex
    mutex.islocked
    mutex.lock
    mutex.ownlock
    mutex.unlock
coutil.promise
    promise.awaitall
    promise.awaitany
    promise.create
    promise.onlypending
    promise.pickready
coutil.queued
    queued.await
    queued.awaitall
    queued.awaitany
    queued.emitall
    queued.emitone
    queued.isqueued
    queued.pending
coutil.spawn
    spawn.catch
    spawn.trap
coutil.system
    system.address
    system.awaitch
    system.awaitsig
    system.copyfile
    system.cpuinfo
    system.emitsig
    system.execute
    system.filebits
    system.fileinfo
    system.findaddr
        addresses:close
        addresses:getaddress
        addresses:getdomain
        addresses:getsocktype
        addresses:next
        addresses:reset
    system.getdir
    system.getenv
    system.getpriority
    system.grantfile
    system.halt
    system.isrunning
    system.linkfile
    system.listdir
    system.makedir
    system.maketemp
    system.movefile
    system.nameaddr
    system.nanosecs
    system.netinfo
    system.openfile
        file:close
        file:flush
        file:grant
        file:info
        file:own
        file:read
        file:resize
        file:touch
        file:write
    system.ownfile
    system.packenv
    system.procinfo
    system.random
    system.removefile
    system.resume
    system.run
    system.setdir
    system.setenv
    system.setpriority
    system.socket
        socket:accept
        socket:bind
        socket:close
        socket:connect
        socket:getaddress
        socket:getdomain
        socket:listen
        socket:read
        socket:setoption
        socket:shutdown
        socket:write
    system.stdin|stdout|stderr
        terminal:close
        terminal:read
        terminal:setmode
        terminal:shutdown
        terminal:winsize
        terminal:write
    system.suspend
    system.time
    system.touchfile
    system.unpackenv
coutil.threads
    threads.close
    threads.count
    threads.create
    threads.dofile
    threads.dostring
    threads.resize