Search code examples
luarequireawesome-wmluafilesystem

Lua - require fallback / error handling


I'm currently using the awesome window manager on various Linux machines running different distributions. All of the machines utilize the same (lua) configuration file.

Some of the machine have lua-filesystem (lfs) installed, while others don't. My configuration would preferably use lfs, but if it is not installed I'd like to provide an alternative (suboptimal) fallback routine.

Here's my question in all of it's simplicity:

  • How would I go about catching the error thrown by the require(lfs) statement?

Solution

  • require is not a magical function. It's a function just like any other in Lua. And it signals errors using the standard error signaling facilities of Lua.

    Therefore, you catch errors from require exactly like you do any other function in Lua. Namely, you wrap it in pcall:

    local status, lfs = pcall(require, "lfs")
    if(status) then
        --lfs exists, so use it.
    end
    

    Indeed, you can make your own prequire function that works for loading anything:

    function prequire(...)
        local status, lib = pcall(require, ...)
        if(status) then return lib end
        --Library failed to load, so perhaps return `nil` or something?
        return nil
    end
    
    local lfs = prequire("lfs")
    
    if(lfs) then
        --use lfs.
    end