Recursive Require

lua-users home
wiki

This is a simple function to handle recursive requires
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

Example Usage

main.lua (using a chatty version of the import function above):
-- 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

RecentChanges · preferences
edit · history
Last edited November 23, 2012 10:19 am GMT (diff)