Embedding Files
Added in
lrc v1.1.0
lrc
supports embedding arbitrary resource-files into the output executable, shared library or Lua bundle.
Files can be embedded by putting a comment in the format of --lr:embed <file>
anywhere in the Lua source-code and will be accessible via io.open
.
The comment-syntax is described below:
Syntax
--lr:embed [@[module]:]<filename>
Example
--lr:embed file.txt
-- Then anywhere in the program
local file = io.open('file.txt', 'r')
print(file:read '*a') -- outputs: the embedded file contents!
Embedding Files with Ambiguous Names
When embedded resources have simple names (e.g. button.jpg
) it could become a problem if a user of the compiled application chooses to access a file on their disk with the same name.
For this reason lrc
offers a variant of the embed syntax which works together with datafile
:
--lr:embed @:file.txt
-- Then anywhere else:
local file = datafile.open 'file.txt'
The @:
signals lrc
to enable namespacing for the given embed statement. This keeps the embedded file accessible through datafile
, while io.open
will remain able to open files on the local disk under the same name.
Embedding Other Modules’ Files
When a require
d module happens to use datafile (e.g. LuaNLP), it is also possible to embed its resources without altering the module code!
--lr:embed @luanlp:luanlp/pos/model/perceptron-pretrained.cmlz
local postagger = require 'luanlp.pos.perceptron'
-- magically, the LuaNLP module finds its model-file on any machine:
postagger:tag { 'The', 'deer', 'jumps', 'high' }
The @luanlp:
signals lrc
to enable namespacing for the given embed statement and switch into the datafile
-context of the luanlp
module specifically.
This way, datafile.open()
will only return the embedded file when called from within luanlp
. Natrually this avoids name clashing between modules and allows different modules to load distinct resources with equal filenames.
Referencing Embedded Files Explicitly
Last but not least, embedded files can be referenced in io.open()
-based calls using the filename scheme lr://[@[module]:]<filename>
which follows the same syntax as the --embed
-statement.
Adding a third slash to the lr:///
-scheme allows to reference raw paths inside the embedded archive. This for example allows to access the raw code of bundled lua modules or embedded files namespaced under a specific module.