Check for files

Posted by Shaun Biggs on Tue 28 Jul 2009 02:31 AM — 3 posts, 18,256 views.

USA #0
Is there any way to check for a file before trying to use dofile() on it? Or, probably more usefully, is there any way to trap the error for when there is no file and do something instead of displaying something like the following?

Run-time error
World: Aardwolf - Balaam
Immediate execution
cannot open asdf.lua: No such file or directory
stack traceback:
        [C]: in function 'dofile'
        [string "Command line"]:1: in main chunk

USA #1
Ooooh! I came up against this one 2 or 3 weeks ago!

if utils.readdir("C:\\path\\to\\file.lua") then
-- do stuff.
end

Using ReadDir (not re-add ir, there is no infra red support ;) ) with a fully qualified file path will either return the file name, or nil if not found.

Australia Forum Administrator #2
If you check out the help for dofile, it says:


Using dofile is the same as:


function dofile (filename)
  local f = assert (loadfile (filename))
  return f ()
end -- dofile



Thus, if you do loadfile, you will get back nil if it fails. If not, you call the resulting function (see under loadfile).

So, basically:


function my_dofile (filename)
  local f = loadfile (filename)
  if not f then
    print "sigh -- foiled again!"
    return nil
  end -- can't load it
  return f ()
end -- my_dofile


This is more comprehensive than merely testing for the presence of the file, this checks it can be loaded (ie. it is valid Lua code).