I wrote Lua require
function based on the include
function found in /system/lib/head.lua:791
.
This function loads Lua modules similar to standard require found in Lua:
- it loads the file
- executes the file
- returns the module returned by included file
- caches the module, so next call to require will return already loaded module
How to use:
- put the source code of
require
function in yourmain.lua
:
function require(name) if _modules == nil then _modules={} end local already_imported = _modules[name] if already_imported ~= nil then return already_imported end local filename = fullpath(name..'.lua') local src = fetch(filename) if (type(src) ~= "string") then notify("could not include "..filename) stop() return end -- https://www.lua.org/manual/5.4/manual.html#pdf-load -- chunk name (for error reporting), mode ("t" for text only -- no binary chunk loading), _ENV upvalue -- @ is a special character that tells debugger the string is a filename local func,err = load(src, "@"..filename, "t", _ENV) -- syntax error while loading if (not func) then send_message(3, {event="report_error", content = "*syntax error"}) send_message(3, {event="report_error", content = tostr(err)}) stop() return end local module = func() _modules[name]=module return module end |
- write modules, for example create file named
module.lua
:
M = {} function M.func() print("inside module.func()") end return M |
- import modules:
local module = require('module') -- will load and execute module.lua module.func() |
P#143480 2024-03-17 11:21 ( Edited 2024-03-23 23:46)