Preventing Duplicate dofile() Calls in Lua

I’m using dofile() to pull in support files, similar to how you would use #include <filename> in C++.  However, you can’t do the C++ #ifdef syntax to prevent a file from getting included more than once. You can however customize the dofile() function to do something similar.  Remember that all function names are variables that you can assign in Lua.  Here’s the code:

local oldDoFile = dofile
local loadedFiles = {}
function dofile(filename)
  if loadedFiles[filename] ~= true then
    print("Loading " .. filename)
    loadedFiles[filename] = true
    print("Skipping load for " .. filename)

First you save a reference to the existing dofile() function, but call it oldDoFile.  We also have a local table to store all filenames that have been loaded called “loadedFiles”.  Then we can redefine dofile() to check this table before calling the oldDoFile() function.  Now you can add dofile() calls to the tops of your various .lua scripts without worrying that a file will get included twice!

Leave a Reply