LAP: Lua Asynchronous Protocol
Lua has one of the coolest yet most underutilized asynchronous programming
tools: the
coroutine module, specifically
coroutine.yield. Lua's
yield
can be called from any depth, resuming execution at the callsite upon
coroutine.resume. This means that if we swap out traditionally blocking APIs
like
file:read with ones that are non-blocking and yielding (i.e. by running
IO in a separate thread or using unix's
aio interface) we use most libraries
asynchronously without changing a single line of code.
For an example of implementing the LAP protocol see
#Package_fd
LAP is a lightweight zero-dependency asynchronous protocol which aims to take
advantage of Lua's awesomeness. It is architected to allow libraries to provide
a lightweight "asynchronous mode" so that they can be used asynchronously by a
coroutine executor. This allows users and library authors to write code that
looks synchronous but which can be executed asynchronously at the application
author's discression.
This folder also contains the
lap.lua library, see the Library section.
Library authors
do not need to depend on this library to work with the LAP
protocol.
The LAP protocol has two components:
- yielding protocol: An ultra simple yet optionally-performant to communicate
with the executor loop (example: see lap.Lap)
- two global tables which libraries can use to schedule coroutines (LAP_READY)
and register their asynchronous API (LAP_FNS_ASYNC and LAP_FNS_SYNC)
Library authors can fully support the protocol by following the
Yielding Protocol below and copy/pasting the following:
LAP_FNS_SYNC = LAP_FNS_SYNC or {}
LAP_FNS_ASYNC = LAP_FNS_ASYNC or {}
// register functions to switch modes, see end of lap.lua for example
table.insert(LAP_FNS_SYNC, function() ... end)
table.insert(LAP_FNS_ASYNC, function() ... end)
// implement your asynchronous functions by following the protocol.
Library authors should make their default API
synchronous (blocking) by
default, except for items that cannot be used synchronously.
LAP_READY Global Table
LAP_READY is a global key/value table where the keys are the coroutines which
should be run at some later time (by the executor). The values are arbitrary
(typically a string identifier for debugging).
This means that a coroutine can schedule another coroutine
cor by simply doing
LAP_READY[cor = "my_identifier"