Do file only once in Lua

你离开我真会死。 提交于 2019-12-05 21:28:05

well, require pretty much does that.

require "file" -- runs "file.lua"
require "file" -- does not run the "file" again

The only problem with require is that it works on module names, not file names. In particular, require does not handle names with paths (although it does use package.path and package.cpath to locate modules in the file system).

If you want to handle names with paths you can write a simple wrapper to dofile as follows:

do
  local cache={}
  local olddofile=dofile
  function dofile(x)
    if cache[x]==nil then
      olddofile(x)
      cache[x]=true
   end 
  end
end

based on lhf's answer, but utilising package, you can also do this once:

package.preload["something"]=dofile "/path/to/your/file.lua"

and then use:

local x=require "something"

to get the preloaded package again. but that's a bit abusive...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!