遞迴 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(格林威治標準時間)(diff)