Sometimes, we would like to reload automatically an updated module
within a long-running program. The hotswap
module provides such
functionality, using various backends for change detection.
See Wikipedia
This module is available in luarocks:
luarocks install hotswap
The easiest way to use this library is as below:
local hotswap = require "hotswap".new ()
local mymodule = hotswap.require "mymodule"
...
Note that this is useless, as there is not hotswapping in the default
behavior. Note also that the .new ()
can be omitted if you need only one
instance of the hotswap
module.
An easy way to use hotswapping is to require the updated module within a loop. The following code reloads the module only when its file hash hash changed:
local hotswap = require "hotswap.hash"
while true do
local mymodule = hotswap.require "mymodule"
...
end
The same applies with file modification date given by lfs
:
local hotswap = require "hotswap.lfs"
while true do
local mymodule = hotswap.require "mymodule"
...
end
A more advanced use is for instance with lua-ev
in a idle loop:
local ev = require "ev"
local hotswap = require "hotswap.ev"
ev.Idle.new (function ()
local mymodule = hotswap.require "mymodule"
...
end):start (ev.Loop.default)
ev.Loop.default:loop ()
The hotswap
can even replace the require
function easily:
require = require "hotswap.xxx".require
Currently, the following backends are supported:
hotswap
: the default backend does not perform any change detection, see this example;hotswap.ev
: this backend detects module changes usinglua-ev
, see this example;hotswap.hash
: this backend detects module changes by checking file hashes usingxxhah
, see this example;hotswap.http
: this backend loads modules from a HTTP server, and avoids useless downloads, see this example;hotswap.lfs
: this backend detects module changes by observing file modification date usingluafilesystem
, see this example.
Notice that the dependencies for each backend are not listed in the rockspec. Make sure to install them!
This module makes use of package.searchers
, available from Lua 5.2. If you
are running under Lua 5.1 or LuaJIT, a fake package.searchers
will be
automatically created.
The bench directory contains benchmarks for the backends. They can be run using:
cd bench/
for bench in bench-*.lua
do
echo ${bench}
luajit ${bench}
done
cd ..
Tests are written for busted.
busted test/*.lua