Skip to content

Instantly share code, notes, and snippets.

@sjshuck
Last active March 14, 2023 17:25
Show Gist options
  • Save sjshuck/cfa0a46a276c9345de4663dd9a94d3e2 to your computer and use it in GitHub Desktop.
Save sjshuck/cfa0a46a276c9345de4663dd9a94d3e2 to your computer and use it in GitHub Desktop.
try_require
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
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