Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a lua script from failing when a `require` fails to find the script required?

Tags:

lua

Is it possible to prevent a lua script from failing when a require fails to find the script required?

like image 423
MarkNS Avatar asked Dec 11 '22 12:12

MarkNS


2 Answers

This is basic usage

if pcall(require, 'test') then
    -- done but ...
    -- In lua 5.2 you can not access to loaded module.
else
    -- not found
end

But since Lua 5.2 it is deprecated set global variables when load library you should use returned value from require. And using only pcall you need :

local ok, mod = pcall(require, "test")
-- `mod` has returned value or error 
-- so you can not just test `if mod then` 
if not ok then mod = nil end
-- now you can test mod
if mod then
  -- done
end

I like this function

local function prequire(m) 
  local ok, err = pcall(require, m) 
  if not ok then return nil, err end
  return err
end

-- usage
local mod = prequire("test")
if mod then 
  -- done
end
like image 59
moteus Avatar answered May 23 '23 19:05

moteus


In Lua errors are handled by pcall function. You could wrap require with it:

local requireAllDependenciesCallback = function()
    testModul = require 'test';
    -- Other requires.
end;

if pcall(requireAllDependenciesCallback) then
    print('included');
else
    print('failed');
end

Demo

Note: pcall is really expensive and should not be actively used. Make sure, you really need to mute require fails.

like image 38
Leri Avatar answered May 23 '23 20:05

Leri