Search code examples
lualuafilesystem

under lua, how can I if check file attributes only if the LuaFileSystem package is installed


I have some code which uses LuaFileSystem. However not all systems it will be run on have LuaFileSystem installed. I would like to check if it is installed, and only run the code if it is. Something like this (but this fails and states lfs is a null value)

local lfsExists, lfs = pcall(function () require "lfs" end)
if lfsExists then
    local lastUpdateTime = lfs.attributes( mapFilePName ).modification
end

Solution

  • That pcall-ed function doesn't return any values. Drop , lfs.

    Also you don't need the anonymous function.

    local lfsExists = pcall(require, "lfs")
    

    Or to use the return value from require instead of the (implicit) global.

    local lfsExists, lfs = pcall(require, "lfs")