Skip to content

Instantly share code, notes, and snippets.

@zr-tex8r
Created June 3, 2017 05:29
Show Gist options
  • Save zr-tex8r/0bbb1e25f6c4b977244d6cd39a501674 to your computer and use it in GitHub Desktop.
Save zr-tex8r/0bbb1e25f6c4b977244d6cd39a501674 to your computer and use it in GitHub Desktop.
Lua: CP932なWindowsでbasename
-- 文字コードはCP932
function basename(path)
if type(path) ~= "string" or not lfs.isfile(path) then
return path -- 引数が不適切
end
local k, cs = 0, path:gsub("/", "\\"):explode("\\")
for i = 1, #cs - 1 do
local d = table.concat({ table.unpack(cs, 1, i) }, "\\")
if lfs.isdir(d) then k = i end
end
print(k, #cs)
return table.concat({ table.unpack(cs, k + 1) }, "\\")
end
-- CP932のWindowsで; 存在するファイル
print(basename([[ほげ]])) -- ほげ
print(basename([[予定]])) -- 予定
print(basename([[予約\ふが]])) -- ふが
print(basename([[予約\予定]])) -- 予定
print(basename([[予約/ふが]])) -- ふが
print(basename([[予約/予定]])) -- 予定
print(basename([[予定表\予定表]])) -- 予定表
print(basename([[予定表/予定表]])) -- 予定表
-- 存在しないファイル
print(basename([[ふが/ぴよ]])) -- ふが/ぴよ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment