Make the file only once in Lua

I was wondering if there is a way to make the lua file only once and any subsequent attempts to make this lua file will lead to the creation of no-op.

I was already thinking of doing something similar to the C ++ header if if / else / endif. I am wondering if there is a standard way to implement this.

James

+3
source share
3 answers

well, requirepretty much doing it.

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

, , . , require ( package.path package.cpath ).

, dofile :

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

based on lhf answer, but using package, you can also do this once:

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

and then use:

local x=require "something"

to download the preloaded package again. but it's a little offensive ...

0
source

Source: https://habr.com/ru/post/1716721/


All Articles