1. 程式人生 > >重寫require使lua檔案模組化

重寫require使lua檔案模組化

local function useModuleRequire()
 --
 function readOnly(t)
  local proxy = {}
  local mt = {
   __index = t,
   __newindex = function(t, k, v)
    error("our moduleRequire forbid update a read-only module", 2)
   end
  }
  setmetatable(proxy, mt)
  return proxy
 end
 function readOnly2(t)
  local mt = {
   __newindex = function(t, k, v)
    error("our moduleRequire forbid update a read-only module", 2)
   end
  }
  setmetatable(t, mt)
  return t
 end
 
 --模組化的require,name是模組名,bReadOnly模組設定為是否只讀
 local function moduleRequire(name,bReadOnly)
  if not package.loaded[name] then
   local loader = loadfile
   if loader == nil then
    error("unable to load module "..name)
   end
   package.loaded[name] = true
   local loadRes = loader(name..".lua")
   local env = {_G = _G,} --引入全域性表的環境 通過_G.xxxx形式訪問全域性變數
   
   local loadResWithEnv = setfenv(loadRes,env) --設定環境,讓載入的檔案模組化
   local res = loadResWithEnv()
   local env2 = env
   if bReadOnly == nil then bReadOnly = true end
   if bReadOnly then
    env2 = readOnly2(env)
   else
    env2 = env
   end
   _G[name] = env2	--把模組變成只讀
   if res ~= nil then
    package.loaded[name] = res
   end
  end
  return package.loaded[name]
 end
 _G.originalRequire = _G.require
 _G.require = moduleRequire
end
useModuleRequire()
require("myMath")
print(myMath.myadd(2,3))