递归 Require

lua-users home
wiki

这是一个处理递归 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

示例用法

main.lua (使用上面导入函数的详细版本)
-- 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"

输出

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

最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2012 年 11 月 23 日上午 11:19 GMT (差异)