3
votes

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

3
What do you mean by "do a lua file"? - lutz
I'm using dofile() at the moment from multiple places on 1 file. - jameszhao00
i'd always prefer require before dofile, except you explicitely want to do the whole file on each call - nonchip

3 Answers

11
votes

well, require pretty much does that.

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

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
0
votes

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