12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 | -- Module loaders, which find a Nomsu module's code by its name
Files = require "files"
-- Turn a list of directories into a search path for Nomsu modules, like package.path.
-- With optimization, precompiled .lua versions of modules are used when they exist.
search_path = (directories, optimization)->
suffixes = if optimization > 0
{"?.lua", "?/init.lua", "?.nom", "?/init.nom"}
else {"?.nom", "?/init.nom"}
return table.concat([dir.."/"..s for dir in *directories for s in *suffixes], ";")
-- A module loader that looks for modules in a list of directories. Module names that
-- end in .nom or .lua are paths to files.
file_loader = (directories, optimization=1)->
nomsupath = search_path(directories, optimization)
return (name)->
local path
if name\match("%.nom$") or name\match("%.lua$")
path = name
else
path, err = package.searchpath(name, nomsupath, "/")
return nil, err unless path
path = path\gsub("^%./", "")
code = Files.read(path)
return nil, "Couldn't read the file '#{path}'" unless code
-- Don't use a precompiled .lua file if its .nom source has changed since then
if path\match("%.lua$")
nom_path = path\gsub("%.lua$", ".nom")
if nom_code = Files.read(nom_path)
unless code\match("^[^\n]*\n%-%- Source hash: (%x+)") == Files.hash(nom_code)
return nom_code, nom_path
return code, path
-- A module loader for modules in a table, which maps module names to Nomsu code
table_loader = (modules)->
return (name)->
code = modules[name]
return nil, "There's no module named '#{name}'" unless code
return code, (name\match("%.nom$") and name or name..".nom")
-- A module loader that tries each of the given loaders, in order
chain_loaders = (...)->
loaders = {...}
return (name)->
errors = {}
for loader in *loaders
code, filename = loader(name)
return code, filename if code
table.insert errors, filename
return nil, table.concat(errors, "\n")
return {:search_path, :file_loader, :table_loader, :chain_loaders}
|