Reference
NOTE: Some functions require DNS lookups, which is handled internally
by LuaSocket. This is being done in a blocking manner. Hence every function
that accepts a hostname as an argument (e.g. tcp:connect()
,
udp:sendto()
, etc.) is potentially blocking on the DNS resolving part.
So either provide IP addresses (assuming the underlying OS will detect those and resolve
locally, non-blocking) or accept that the lookup might block.
Getting started examples
Example for a server handling incoming connections:
local copas = require("copas") local socket = require("socket") local address = "*" local port = 20000 local ssl_params = { wrap = { mode = "server", protocol = "any", -- not really secure... }, } local server_socket = assert(socket.bind(address, port)) local function connection_handler(skt) local data, err = skt:receive() -- do something end copas.addthread(function() copas.addserver(server_socket, copas.handler(connection_handler, ssl_params), "my_TCP_server") copas.waitforexit() copas.removeserver(server_socket) end) copas()
Example for a client making a connection to a remote server:
local copas = require("copas") local socket = require("socket") copas.addthread(function() local port = 20000 local host = "somehost.com" local ssl_params = { wrap = { mode = "client", protocol = "any", -- not really secure... }, } local sock = copas.wrap(socket.tcp(), ssl_params) copas.setsocketname("my_TCP_client", sock) assert(sock:connect(host, port)) local data, err = sock:receive("*l") -- do something end) copas()
Copas dispatcher main functions
The group of functions is relative to the use of the dispatcher itself and are used to register servers and to execute the main loop of Copas:
copas([init_func, ][timeout])
-
This is a shortcut to
copas.loop
. copas.addserver(server, handler [, timeout [, name]])
-
Adds a new
server
and itshandler
to the dispatcher using an optionaltimeout
.server
is a LuaSocket server socket created usingsocket.bind()
.handler
is a function that receives a LuaSocket client socket and handles the communication with that client. The handler will be executed in parallel with other threads and registered handlers as long as it uses the Copas socket functions.timeout
is the timeout in seconds. Upon accepting connections, the timeout will be inherited by TCP client sockets (only applies to TCP).name
is the internal name to use for this socket. The handler threads and (in case of TCP) the incoming client connections will get a name derived from the server socket.- TCP: client-socket name:
"[server_name]:client_XX"
and the handler thread"[server_name]:handler_XX"
whereXX
is a sequential number matching between the client-socket and handler. - UDP: the handler thread will be named
"[server_name]:handler"
- TCP: client-socket name:
coro = copas.addnamedthread(name, func [, ...])
-
Same as
copas.addthread
, but also names the new thread. coro = copas.addthread(func [, ...])
-
Adds a function as a new coroutine/thread to the dispatcher. The optional parameters will be passed to the function
func
.The thread will be executed in parallel with other threads and the registered handlers as long as it uses the Copas socket/sleep functions.
It returns the created coroutine.
copas.autoclose
-
Boolean that controls whether sockets are automatically closed (defaults to
true
). This only applies to incoming connections accepted on a TCP server socket.When a TCP handler function completes and terminates, then the client socket will automatically be closed when
copas.autoclose
is truthy. copas.exit()
-
Sets a flag that the application is intending to exit. After calling this function
copas.exiting()
will be returningtrue
, and all threads blocked oncopas.waitforexit()
will be released.Copas itself will call this function when
copas.finished()
returnstrue
. bool = copas.exiting()
-
Returns a flag indicating whether the application is supposed to exit. Returns
false
until aftercopas.exit()
has been called, after which it will start returningtrue
.Clients should check whether they are to cease their operation and exit. They can do this by checking this flag, or by registering a task waiting on
copas.waitforexit()
. Clients should cancel pending work and close sockets when an exit is announced, otherwise Copas will not exit. bool = copas.finished()
-
Checks whether anything remains to be done.
Returns
false
when the socket lists for reading and writing are empty and there is not another (sleeping) task to execute.NOTE: when tasks or sockets have been scheduled/setup this function will return
true
even if the loop has not yet started. See alsocopas.running
. func = copas.geterrorhandler([coro])
-
Returns the currently active errorhandler function for the coroutine (either the explicitly set errorhandler, or the default one).
coro
will default to the currently running coroutine if omitted. string = copas.getsocketname(skt)
-
Returns the name for the socket.
string = copas.getthreadname([co])
-
Returns the name for the coroutine/thread. If not given defaults to the currently running coroutine.
number = copas.gettime()
-
Returns the (fractional) number of seconds since the epoch. This directly maps to either the LuaSocket or LuaSystem implementation of
gettime()
. string = copas.gettraceback([msg], [co], [skt])
-
Creates a traceback (string). Can be used from custom errorhandlers to create a proper trace. See
copas.seterrorhandler
. func = copas.handler(connhandler [, sslparams])
-
Wraps the
connhandler
function.Returns a new function that wraps the client socket, and (if
sslparams
is provided) performs the ssl handshake, before callingconnhandler
.See
sslparams
definition below. copas.loop([init_func, ][timeout])
-
Starts the Copas loop accepting client connections for the registered servers and handling those connections with the corresponding handlers. Calling on the module table itself is a shortcut to this function. Every time a server accepts a connection, Copas calls the associated handler passing the client socket returned by
socket.accept()
.The
init_func
function is an optional initialization function that runs as a Copas thread (with name"copas_initializer"
). Thetimeout
parameter is optional, and is passed to thecopas.step()
function.The loop returns when
copas.finished() == true
. result = copas.removeserver(skt [, keep_open])
-
Removes a server socket from the Copas scheduler. By default, the socket will be closed to allow the socket to be reused right away after removing the server. If
keep_open
istrue
, the socket is removed from the scheduler but it is not closed.Returns the result of
skt:close()
ortrue
if the socket was kept open. copas.removethread(coroutine)
-
Removes a coroutine added to the Copas scheduler. Takes a
coroutine
created bycopas.addthread()
and removes it from the dispatcher the next time it tries to resume. Ifcoroutine
isn't registered, it does nothing. copas.running
-
A flag set to
true
whencopas.loop()
starts, and reset tofalse
when the loop exits. See alsocopas.finished()
. copas.seterrorhandler([func], [default])
-
Sets the error handling function for the current thread. Any errors will be forwarded to this handler, it will receive the error, coroutine, and socket as arguments;
function(err, co, skt)
. See the Copas source code on how to deal with the arguments when implementing your own, and checkcopas.gettraceback
.If
func
is omitted, then the error handler is cleared (restores the default handler for this coroutine).If
default
is truthy, then the handler will become the new default, used for all threads that do not have their own set (in this casefunc
must be provided). copas.setsocketname(name, skt)
-
Sets the name for the socket.
copas.setthreadname(name [,co])
-
Sets the name for the coroutine/thread.
co
defaults to the currently running coroutine. copas.waitforexit()
-
This will block the calling coroutine until the
copas.exit()
function is called. Clients should check whether they are to cease their operation and exit. They can do this by waiting on this call, or by checking thecopas.exiting()
flag. Clients should cancel pending work and close sockets when an exit is announced, otherwise Copas will not exit. skt = copas.wrap(skt [, sslparams] )
-
Wraps a LuaSocket socket and returns a Copas socket that implements LuaSocket's API but use Copas' methods like
copas.send()
andcopas.receive()
automatically. If the socket was already wrapped, then it will not wrap it again.If the
sslparams
is provided, then a call to the wrappedsock:connect()
method will automatically include the handshake (and in that caseconnect()
might throw an error instead of returning nil+error, seecopas.dohandshake()
).See
sslparams
definition below. sslparams
-
This is the data-structure that is passed to the
copas.handler
, andcopas.wrap
functions. Passing the structure will allow Copas to take care of the entire TLS handshake process.The structure is set up to mimic the LuaSec functions for the handshake.
{ wrap = table | context, -- parameter to LuaSec 'wrap()' sni = { -- parameters to LuaSec 'sni()' names = string | table -- 1st parameter strict = bool -- 2nd parameter } }
Non-blocking data exchange and timer/sleep functions
These are used by the handler functions to exchange data with
the clients, and by threads registered with addthread
to
exchange data with other services.
copas.pause([delay])
-
Pauses the current co-routine. Parameter
delay
(in seconds) is optional and defaults to 0. Ifdelay <= 0
then it will pause for 0 seconds. copas.pauseforever()
-
Pauses the current co-routine until explicitly woken by a call to
copas.wakeup()
. copas.sleep([sleeptime])
-
Deprecated: use
copas.pause
andcopas.pauseforever
instead. copas.wakeup(co)
-
Immediately wakes up a coroutine that was sleeping or sleeping-forever.
co
is the coroutine to wakeup, seecopas.pause()
andcopas.pauseforever()
. Does nothing if the coroutine wasn't sleeping. sock:close()
-
Equivalent to the LuaSocket method (after
copas.wrap
). sock:connect(address, port)
-
Non-blocking equivalent to the LuaSocket method (after
copas.wrap
).If
sslparams
was provided when wrapping the socket, theconnect
method will also perform the full TLS handshake. So afterconnect
returns the connection will be secured. sock:dohandshake(sslparams)
-
Non-blocking quivalent to the LuaSec method (after
copas.wrap
). Instead of using this method, it is preferred to pass thesslparams
to the functionscopas.handler
(for incoming connections) andcopas.wrap
(for outgoing connections), which then ensures that the connection will automatically be secured when started. sock:receive([pattern [, prefix]])
-
Non-blocking equivalent to the LuaSocket method (after
copas.wrap
). Please seesock:receivepartial
for differences with LuaSocket, especially when using the"*a"
pattern. sock:receivefrom([size])
-
Reads data from a UDP socket just like LuaSocket, but non-blocking.
socket:receivefrom()
. sock:receivepartial([pattern [, prefix]])
-
This method is the same as the
receive
method, the difference being that this method will return on any data received, even if the specified pattern was not yet satisfied.When using delimited formats or known byte-size (pattern is
"*l"
or a number) the regularreceive
method will usually be fine. But when reading a stream with the"*a"
pattern thereceivepartial
method should be used.The reason for this is the difference in timeouts between Copas and LuaSocket. The Copas timeout will apply on each underlying socket read/write operation. So on every chunk received Copas will reset the timeout. So if reading pattern
"*a"
with a 10 second timeout, and the sender sends a stream of data (unlimited size), in 1kb chunks, with 5 seconds intervals, then there will never be a timeout when usingreceive
, and hence the call would never return.If using
receivepartial
with the"*a"
pattern, the (repeated) call would return the 1kb chunks, with a"timeout"
error. sock:send(data [, i [, j]])
-
Non-blocking equivalent to the LuaSocket method (after
copas.wrap
). sock:settimeout([timeout])
-
Sets the timeouts (in seconds) for a socket (after
copas.wrap
). The default is to not have a timeout and wait indefinitely. If a timeout is hit, the operation will returnnil + "timeout"
. This method is compatible with LuaSocket, but sets all three timeouts to the same value.Behaviour:
nil
: block indefinitelynumber < 0
: block indefinitelynumber >= 0
: timeout value in seconds
sock:settimeouts
, wherenil
means 'do not change' the timeout. sock:settimeouts([connect], [send], [receive])
-
Sets the timeouts (in seconds) for a socket (after
copas.wrap
). A positive number sets the timeout, a negative number removes the timeout, andnil
will not change the currently set timeout. The default is to not have a timeout and wait indefinitely.Behaviour:
nil
: do not change the current settingnumber < 0
: block indefinitelynumber >= 0
: timeout value in seconds
sock:settimeout
, wherenil
means 'wait indefinitely'.If a timeout is hit, the operation will return
nil + "timeout"
. sock:sni(...)
-
Equivalent to the LuaSec method (after
copas.wrap
). Instead of using this method, it is preferred to pass thesslparams
to the functionscopas.handler
(for incoming connections) andcopas.wrap
(for outgoing connections), which then ensures that the connection will automatically be secured when started. lock:destroy()
-
Will destroy the lock and release all waiting threads. The result for those threads will be
nil + "destroyed" + wait_time
, any new call on any method will returnnil + "destroyed"
from here on. lock:get([timeout])
-
Will try and acquire the lock. The optional
timeout
can be used to override the timeout value set when the lock was created.If the lock is not available, the coroutine will yield until either the lock becomes available, or it times out. The one exception is when
timeout
is 0, then it will immediately return without yielding. If the timeout is set tomath.huge
, then it will wait forever.Upon success, it will return the
wait-time
in seconds. Upon failure it will returnnil + error + wait-time
. Upon a timeout the error value will be "timeout". copas.lock.new([timeout], [not_reentrant])
-
Creates and returns a new lock. The
timeout
specifies the default timeout for the lock in seconds, and defaults to 10 (set it tomath.huge
to wait forever).By default the lock is re-entrant, except if
not_reentrant
is set to a truthy value. lock:release()
-
Releases the currently held lock.
Returns
true
ornil + error
. queue:add_worker(func)
-
Adds a worker that will handle whatever is passed into the queue. Can be called multiple times to add more workers. The function
func
is wrapped and added as a copas thread. The threads automatically exit when the queue is destroyed.Worker function signature:
function(item)
(Note: worker functions run unprotected, so wrap code in an (x)pcall if errors are expected, otherwise the worker will exit on an error, and queue handling will stop).Returns the coroutine added, or
nil+"destroyed"
. queue:destroy()
-
Destroys a queue immediately. Abandons what is left in the queue. Releases all waiting calls to
queue:pop()
withnil+"destroyed"
. Returnstrue
, ornil+"destroyed"
. queue:finish([timeout], [no_destroy_on_timeout])
-
Finishes a queue. Calls
queue:stop()
and then waits for the queue to run empty (and be destroyed) before returning.When using "workers" via
queue:add_worker()
then this method will return after the worker has finished processing the popped item. When using your own threads and callingqueue:pop()
, then this method will return after the last item has been popped, but not necessarily also processed.The
timeout
defaults to 10 seconds (the default timeout value for a lock),math.huge
can be used to wait forever.Parameter
no_destroy_on_timeout
indicates if the queue is not to be forcefully destroyed on a timeout (abandonning what ever is left in the queue).Returns
true
, ornil+"timeout"
, ornil+"destroyed"
. queue:get_size()
-
Gets the number of items in the queue currently. Returns
number
ornil + "destroyed"
. queue:get_workers()
-
Returns a list/array of current workers (coroutines) handling the queue (only the workers added by
queue:add_worker()
, and still active, will be in the list). Returnslist
ornil + "destroyed"
. queue.name
-
A field set to name of the queue. See
copas.queue.new()
. copas.queue.new([options])
-
Creates and returns a new queue. The
options
table has the following fields:options.name
: (optional) the name for the queue, the default name will be"copas_queue_XX"
. The name will be used to name any workers added to the queue usingqueue:add_worker()
, their name will be"[queue_name]:worker_XX"
queue:pop([timeout])
-
Will pop an item from the queue. If there are no items in the queue it will yield until there are or a timeout happens (exception is when
timeout == 0
, then it will not yield but return immediately, be careful not to create a hanging loop!).Timeout defaults to the default time-out of a semaphore. If the timeout is
math.huge
then it will wait forever.Returns an item, or
nil+"timeout"
, ornil+"destroyed"
. Since an item can benil
, make sure to check for the error message to detect errors. queue:push(item)
-
Will push a new item in the queue. Item can be any type, including 'nil'.
Returns
true
ornil + "destroyed"
. queue:stop()
-
Instructs the queue to stop, and returns immediately. It will no longer accept calls to
queue:push()
, and will callqueue:destroy()
once the queue is empty.Returns
true
ornil + "destroyed"
. semaphore:destroy()
-
Will destroy the sempahore and release all waiting threads. The result for those threads will be
nil + "destroyed"
, any new call on any method will returnnil + "destroyed"
from here on. semaphore:get_count()
-
Returns the number of resources currently available in the semaphore.
semaphore:get_wait()
-
Returns the total number of resources requested by all currently waiting threads minus the available resources. Such that
sempahore:give(semaphore:get_wait())
will release all waiting threads and leave the semaphore with 0 resources. If there are no waiting threads then the result will be 0, and the number of resources in the semaphore will be greater than or equal to 0. semaphore:give([given])
-
Gives resources to the semaphore. Parameter
given
is the number of resources given to the semaphore, if omitted it defaults to 1.If the total resources in the semaphore exceed the maximum, then it will be capped at the maximum. In that case the result will be
nil + "too many"
. copas.semaphore.new(max, [start], [timeout])
-
Creates and returns a new semaphore (fifo).
max
specifies the maximum number of resources the semaphore can hold. The optionalstart
parameter (default 0) specifies the number of resources upon creation.The
timeout
specifies the default timeout for the semaphore in seconds, and defaults to 10 (math.huge
can be used to wait forever). semaphore:take([requested], [timeout])
-
Takes resources from the semaphore. Parameter
requested
is the number of resources requested from the semaphore, if omitted it defaults to 1.If not enough resources are available it will yield and wait until enough resources are available, or a timeout occurs. The exception is when
timeout
is set to 0, in that case it will immediately return without yielding if there are not enough resources available.The optional
timeout
parameter can be used to override the default timeout as set upon semaphore creation. If the timeout ismath.huge
then it will wait forever.Returns
true
upon success ornil + "timeout"
on a timeout. In case more resources are requested than maximum available the error will be"too many"
. copas.timer.new(options)
-
Creates and returns an (armed) timer object. The
options
table has the following fields;options.name
(optional): the name for the timer, the default name will be"copas_timer_XX"
. The name will be used to name the timer thread.options.recurring
(optional, defaultfalse
): booleanoptions.delay
: expiry delay in secondsoptions.initial_delay
(optional): seetimer:arm()
options.params
(optional): an opaque value that is passed to the callback upon expiryoptions.callback
: is the function to execute on timer expiry. The callback function hasfunction(timer_obj, params)
as signature, whereparams
is the value initially passed inoptions.params
options.errorhandler
(optional): a Copas errorhandler function (seecopas.seterrorhandler
for the signature.
timer:arm([initial_delay])
-
Arms a timer that was previously cancelled or exited (arming a non-recurring timer again from its own handler is explicitly supported). Returns the timer.
The optional parameter
initial_delay
, determines the first delay. For example a recurring timer withdelay = 5
, andinitial_delay = 0
will execute immediately and then recur every 5 seconds. timer:cancel()
-
Will cancel the timer.
High level request functions
The last ones are the higher level client functions to perform requests to (remote) servers.
copas.http.request(url [, body])
or
copas.http.request(requestparams)
-
Performs an http or https request, identical to the LuaSocket and LuaSec implementations, but wrapped in an async operation. As opposed to the original implementations, this one also allows for redirects cross scheme (http to https and viceversa).
Options:
options.url
: the URL for the request.options.sink
(optional): the LTN12 sink to pass the body chunks to.options.method
(optional, default "GET"): the http request method.options.headers
(optional): any additional HTTP headers to send with the request. Hash-table, header-values by header-names.options.source
(optional): simple LTN12 source to provide the request body. If there is a body, you need to provide an appropriate "content-length" request header field, or the function will attempt to send the body as "chunked" (something few servers support). Defaults to the empty sourceoptions.step
(optional): LTN12 pump step function used to move data. Defaults to the LTN12pump.step
function.proxy
(optional, default none): The URL of a proxy server to use.options.redirect
(optional, defaulttrue
): Set tofalse
to prevent GET or HEAD requests from automatically following 301, 302, 303, and 307 server redirect messages.
Note: https to http redirects are not allowed by default, but only when this option is set to a string value"all"
.options.create
(optional): a function to be used instead ofsocket.tcp
when the communications socket is created.options.maxredirects
(optional, default 5): An optional number specifying the maximum number of redirects to follow. A booleanfalse
value means no maximum (unlimited).options.timeout
(optional, default 60): A number specifying the timeout for connect/send/receive operations. Or a table with keys"connect"
,"send"
, and"receive"
, to specify individual timeouts (keys omitted from the table will get a default of 30).
copas.ftp.put(url, content)
or
copas.ftp.put(requestparams)
-
Performs an ftp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.ftp.get(url)
or
copas.ftp.get(requestparams)
-
Performs an ftp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.smtp.send(msgparams)
-
Sends an smtp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.smtp.message(msgt)
-
Just points to
socket.smtp.message
, provided so thecopas.smtp
module is a drop-in replacement for thesocket.smtp
module.
Low level Copas functions
Most of these are wrapped in the socket wrapper functions, and wouldn't need to be used by user code on a regular basis.
copas.close(skt)
-
Closes the socket. Any read/write operations in progress will return with an error.
copas.connect(skt, address, port)
-
Connects and transforms a master socket to a client just like LuaSocket
socket:connect()
. The Copas version does not block and allows the multitasking of the other handlers and threads. copas.dohandshake(skt, sslparams)
-
Performs an ssl handshake on an already connected TCP client socket. It returns the new ssl-socket on success, or throws an error on failure.
copas.flush(skt)
-
(deprecated)
copas.receive(skt [, pattern [, prefix]])
(TCP) or
copas.receive(size)
(UDP)-
Reads data from a client socket according to a pattern just like LuaSocket
socket:receive()
. The Copas version does not block and allows the multitasking of the other handlers and threads.Note: for UDP sockets the
size
parameter is NOT optional. For the wrapped functionsocket:receive([size])
it is optional again. copas.receivepartial(skt [, pattern [, prefix]])
-
The same as
receive
, except that this method will return on any data received. Seesock:receivepartial
for details. copas.receivefrom(skt [, size])
-
Reads data from a UDP socket just like LuaSocket
socket:receivefrom()
. The Copas version does not block and allows the multitasking of the other handlers and threads. copas.send(skt, data [, i [, j]])
(TCP) or
copas.send(skt, datagram)
(UDP)-
Sends data to a client socket just like
socket:send()
. The Copas version is buffered and does not block, allowing the multitasking of the other handlers and threads.Note: only for TCP, UDP send doesn't block, hence doesn't require this function to be used.
copas.settimeout(skt, [timeout])
-
Sets the timeout (in seconds) for a socket. A negative timout or absent timeout (
nil
) will wait indefinitely.Important: this behaviour is the same as LuaSocket, but different from
copas.settimeouts
, wherenil
means 'do not change' the timeout.If a timeout is hit, the operation will return
nil + "timeout"
. Timeouts are applied on:receive, receivefrom, receivepartial, send, connect, dohandshake
.See
copas.usesockettimeouterrors()
below for alternative error messages. copas.settimeouts(skt, [connect], [send], [receive])
-
Sets the timeouts (in seconds) for a socket. The default is to not have a timeout and wait indefinitely.
Important: this behaviour is different from
copas.settimeout
, wherenil
means 'wait indefinitely'.If a timeout is hit, the operation will return
nil + "timeout"
. Timeouts are applied on:receive, receivefrom, receivepartial, send, connect, dohandshake
.See
copas.usesockettimeouterrors()
below for alternative error messages. t = copas.status([enable_stats])
-
Returns metadata about the current scheduler status. By default only number/type of tasks is being reported. If
enable_stats == true
then detailed statistics will be enabled. Calling it again later withenable_stats == false
will disabled it again.t.running
: boolean, same ascopas.running
.t.read
: the number of tasks waiting to read on a socket.t.write
: the number of tasks waiting to write to a socket.t.active
: the number of tasks ready to resume.t.timer
: the number of timers for tasks (in the binary tree).t.inactive
: the number of tasks waiting to be woken up.t.timeout
: the number of timers for timeouts (in the timerwheel).t.time_start
*: measurement time started (seconds, previous call to status).t.time_end
*: measurement time ended (seconds, now, current call to status).t.time_avg
*: average time per step (millisec).t.steps
*: the number of loop steps executed.t.duration_tot
*: total time spent executing (millisec, processing tasks, excluding waiting for the network select call).t.duration_min
*: smallest execution time per step (millisec).t.duration_min_ever
*: smallest execution time per step ever (millisec).t.duration_max
*: highest execution time per step (millisec).t.duration_max_ever
*: highest execution time per step ever (millisec).t.duration_avg
*: average execution time per step (millisec).
bool = copas.step([timeout])
-
Executes one copas iteration accepting client connections for the registered servers and handling those connections with the corresponding handlers. When a server accepts a connection, Copas calls the associated handler passing the client socket returned by
socket.accept()
. Thetimeout
parameter is optional. It returnsfalse
when no data was handled (timeout) ortrue
if there was data handled (or alternatively nil + error message in case of errors).NOTE: the
copas.running
flag will not automatically be (un)set. So when using your own main loop, consider manually setting the flag. copas.timeout(delay [, callback])
-
Creates a timeout timer for the current coroutine. The
delay
is the timeout in seconds, and thecallback
will be called upon an actual timeout occuring.Calling it with
delay = 0
(ormath.huge
) will cancel the timeout.Calling it repeatedly will simply replace the timeout on the current coroutine and any previous callback set will no longer be called.
NOTE: The timeouts are a low-level Copas feature, and should only be used to wrap an explicit yield to the Copas scheduler. They should not be used to wrap user code.
Example usage:
local copas = require "copas" local result = "nothing" copas(function() local function timeout_handler(co) -- co will be the coroutine from which 'timeout()' was called print("executing timeout handler") result = "timeout" copas.removethread(co) -- drop the thread, because we timed out end copas.addthread(function() copas.timeout(5, timeout_handler) -- timeout on the current coroutine after 5 seconds copas.pause(10) -- sleep for 10 seconds print("just woke up") result = "slept like a baby" copas.timeout(0) -- cancel the timeout on the current coroutine end) end) print("result: ", result)
For usage examples see the
lock
andsemaphore
implementations. copas.usesockettimeouterrors([bool])
-
Sets the timeout errors to return for the current co-routine. The default is
false
, meaning that a timeout error will always return an error string"timeout"
. If you are porting an existing application to Copas and want LuaSocket or LuaSec compatible error messages then set it totrue
.In case of using socket timeout errors, they can also be
"wantread"
or"wantwrite"
when using ssl/tls connections. These can be returned at any point if during a read or write operation an ssl-renegotiation happens.Due to platform difference the
connect
method may also return"Operation already in progress"
as a timeout error message.
Copas debugging functions
These functions are mainly used for debugging Copas itself and should be considered experimental.
copas.debug.start([logger] [, core])
-
This will internally replace coroutine handler functions to provide log output to the provided
logger
function. The logger signature isfunction(...)
and the default value is the globalprint()
function.If the
core
parameter is truthy, then also the Copas core timer will be logged (very noisy). copas.debug.stop()
-
Stops the debug output being generated.
debug_socket = copas.debug.socket(socket)
-
This wraps the socket in a debug-wrapper. This will for each method call on the socket object print the method, the parameters and the return values. Check the source code on how to add additional introspection using extra callbacks etc.
Extremely noisy and experimental!
NOTE 1: for TLS you'll probably need to first do the TLS handshake.
NOTE 2: this is separate from the other debugging functions.