3

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

asked Sep 2, 2009 at 19:26
3
  • What do you mean by "do a lua file"? Commented Sep 2, 2009 at 19:28
  • I'm using dofile() at the moment from multiple places on 1 file. Commented Sep 2, 2009 at 19:43
  • i'd always prefer require before dofile, except you explicitely want to do the whole file on each call Commented Aug 30, 2013 at 13:43

3 Answers 3

11

well, require pretty much does that.

require "file" -- runs "file.lua"
require "file" -- does not run the "file" again
answered Sep 2, 2009 at 19:33
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome thanks. I kept thinking I needed a module definition for the lua files too for some reason.
If the file run by require doesn't create a module table or return something, require stores true in package.loaded. Otherwise, it stores the value returned by executing the file. The module function interacts with this well. This is all explained in PiL, but the online copy is not as good as the print edition on these details.
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
answered Sep 3, 2009 at 2:01

4 Comments

THC4k's solution above works on files too. If a file is called abc.lua, require('abc') works.
Yes, but not if you do dofile"/home/lhf/scripts/abc.lua".
actually you can also use require"/path/to/file.lua"
ok, sorry, misremembered that. what you can do is require "relative/path/to/file" (without .lua), because the default search path includes ./?.lua.
0

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

answered Aug 30, 2013 at 13:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.