Do file only once in Lua

我们两清 提交于 2019-12-07 12:08:55

问题


I was wondering if there's a way to do a lua file only once and have any subsequent attempts to do that lua file will result in a no-op.

I've already thought about doing something akin to C++ header's #if/else/endif trick. I'm wondering if there's a standard way to implement this.

James


回答1:


well, require pretty much does that.

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



回答2:


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



回答3:


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...



来源:https://stackoverflow.com/questions/1369646/do-file-only-once-in-lua

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