Skip to content

Instantly share code, notes, and snippets.

@daurnimator
Created May 15, 2017 15:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daurnimator/45839b0d6bd4a94c58d2d942c04b6789 to your computer and use it in GitHub Desktop.
Save daurnimator/45839b0d6bd4a94c58d2d942c04b6789 to your computer and use it in GitHub Desktop.
Pure lua implementation of package.searchpath https://www.lua.org/manual/5.3/manual.html#pdf-package.searchpath
local DIRSEP = package.config:sub(1, 1)
local function is_readable(filename)
local fd = io.open(filename, "r")
if fd then
fd:close()
return true
else
return false
end
end
function searchpath(name, path, sep, rep)
assert(type(name) == "string")
assert(type(path) == "string")
if sep == nil then
sep = "%."
else
assert(type(sep) == "string")
sep = sep:gsub("[%%%^%$%(%)%.%[%]%*%+%-%?]", "%%%0") -- need to escape sep so it doesn't get interpreted as a pattern later
end
if rep == nil then
rep = DIRSEP
else
assert(type(rep) == "string")
end
if #sep > 0 then
name = name:gsub(sep, rep)
end
local msg = ""
local repl_name = name:gsub("%%", "%%%%")
for template in path:gmatch("[^;]+") do -- PATH_SEP
local filename = template:gsub("%?", repl_name) -- PATH_MARK
if is_readable(filename) then
return filename
end
msg = msg .. "\n\tno file '" .. filename .. "'"
end
return nil, msg
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment