Last active
March 14, 2023 17:25
-
-
Save sjshuck/cfa0a46a276c9345de4663dd9a94d3e2 to your computer and use it in GitHub Desktop.
try_require
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function try_require(module_name) | |
local success, module = pcall(require, module_name) | |
local first_time = true | |
return function() | |
if success and first_time then | |
first_time = false | |
return module | |
end | |
end | |
end | |
for foo in try_require 'foo' do | |
local x = foo.do_stuff() | |
print(x) | |
-- whatever | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function with_require(module_name, action) | |
local success, module = pcall(require, module_name) | |
if success then | |
return action(module) | |
end | |
end | |
with_require('foo', function(foo) | |
local x = foo.do_stuff() | |
print(x) | |
-- whatever | |
end) | |
-- This seems less flexible |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment