From 11d25e3c66eed7685066ea4926e6d8a7be32416f Mon Sep 17 00:00:00 2001 From: Max Chernoff <49086429+gucci-on-fleek@users.noreply.github.com> Date: Tue, 17 May 2022 17:59:44 -0600 Subject: [PATCH] Use `try_require` instead of `pcall(require,...)` --- l3kernel/l3luatex.dtx | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/l3kernel/l3luatex.dtx b/l3kernel/l3luatex.dtx index 0b84997c36..d449dfaaaf 100644 --- a/l3kernel/l3luatex.dtx +++ b/l3kernel/l3luatex.dtx @@ -361,6 +361,9 @@ local cprint = tex.cprint local write = tex.write local write_nl = texio.write_nl local utf8_char = utf8.char +local package_loaded = package.loaded +local package_searchers = package.searchers +local table_concat = table.concat local scan_int = token.scan_int or token.scan_integer local scan_string = token.scan_string @@ -605,6 +608,33 @@ end % \end{macrocode} % \end{macro} % +% \begin{macro}[int]{try_require} +% Loads a Lua module. This function loads the module similarly to the standard +% Lua global function |require|, with a few differences. On success, +% |try_require| returns |true, module|. If the module cannot be found, it +% returns |false, err_msg|. If the module is found, but something goes wrong +% when loading it, the function throws an error. +% \begin{macrocode} +local function try_require(name) + if package_loaded[name] then + return true, package_loaded[name] + end + + local failure_details = {} + for _, searcher in ipairs(package_searchers) do + local loader, data = searcher(name) + if type(loader) == 'function' then + package_loaded[name] = loader(name, data) or true + return true, package_loaded[name] + elseif type(loader) == 'string' then + failure_details[#failure_details + 1] = loader + end + end + + return false, table_concat(failure_details, '\n') +end +% \end{macrocode} +% \end{macro} % % \begin{macro}{\@@_load_module_p:n} % Check to see if we can load a module using |require|. If we @@ -617,7 +647,7 @@ local c_false_bool = token_create(0, char_given) local c_str_cctab = token_create('c_str_cctab').mode luacmd('@@_load_module_p:n', function() - local success, result = pcall(require, scan_string()) + local success, result = try_require(scan_string()) if success then set_macro(c_str_cctab, 'l_@@_err_msg_str', '') put_next(c_true_bool)