Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Created November 6, 2015 05:31
Show Gist options
  • Save cloudwu/ae8af935e16555e75d86 to your computer and use it in GitHub Desktop.
Save cloudwu/ae8af935e16555e75d86 to your computer and use it in GitHub Desktop.
Lua version package.searchpath
local DIRSEP, PATSEP, MARK = package.config:match "(.-)\n(.-)\n(.-)\n"
MARK = MARK:gsub(".", function (c) return "%" .. c end)
-- todo: replace your own readable function
local function readable(filename)
local f = io.open(filename)
if f then
f:close()
return true
end
end
local function searchpath(name, path)
name = name:gsub("%.", DIRSEP)
local index = 0
local err
repeat
local term, next = path:find(PATSEP,index+1,true)
local filename = term and path:sub(index+1, term-1) or path:sub(index+1)
filename = filename:gsub(MARK, name)
if readable(filename) then
return filename
end
err = string.format("%s\n\tno file '%s'", err or "", filename)
index = next
until term == nil
return nil, err
end
-- test
print(searchpath("searchpath", package.path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment