Recursive Require |
|
if not package.loading then package.loading = {} end function import(x) if package.loading[x] == nil then package.loading[x] = true require(x) package.loading[x] = nil end end
-- without the below statement you can't use something like: -- import('main') in main.lua if not package.loading then package.loading = {} end -- a chatty version of the actual import function above function import(x) if package.loading[x] == nil then package.loading[x]=true print('loading started for ' .. x) require(x) print('loading ended for ' .. x) package.loading[x]=nil else print('already loading ' .. x) end end import "a" print("second attempt") import 'a'
a.lua :
import "b" print "module a"
b.lua :
import "a" print "module b"
Output:
loading started for a loading started for b already loading a module b loading ended for b module a loading ended for a second attempt loading started for a loading ended for a