Last active
July 12, 2023 15:34
-
-
Save bamchoh/e0cd3934813de65d7732c53248237311 to your computer and use it in GitHub Desktop.
Tiny searchpath for loading Lua script by Lua V5.1.4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local searchpath_lua = require('searchpath_lua') | |
local filename = searchpath_lua("test") | |
print(filename) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local split_str = function(str, sep) | |
local tbl = {} | |
local start_i = 1 | |
for i = start_i, string.len(str) do | |
if str:sub(i,i) == sep then | |
table.insert(tbl, string.sub(str, start_i, i - 1)) | |
start_i = i + 1 | |
end | |
end | |
return tbl | |
end | |
local LUA_PATH_SEP = "" | |
local LUA_PATH_MARK = "" | |
local DIR_SEP = "" | |
local set_consts = function() | |
local tbl = split_str(package.config, "\n") | |
for k, v in pairs(tbl) do | |
if k == 1 then | |
DIR_SEP = v | |
end | |
if k == 2 then | |
LUA_PATH_SEP = v | |
end | |
if k == 3 then | |
LUA_PATH_MARK = v | |
end | |
end | |
end | |
local readable = function(filename) | |
local f = io.open(filename, "r") | |
if f == nil then | |
return false | |
end | |
f:close() | |
return true | |
end | |
local get_luapaths = function() | |
return split_str(package.path, LUA_PATH_SEP) | |
end | |
return function(name) | |
set_consts() | |
name = string.gsub(name, "%.", DIR_SEP) | |
for _, path in pairs(get_luapaths()) do | |
local filename = string.gsub(path, "%" .. LUA_PATH_MARK, name) | |
if readable(filename) then | |
return filename | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment