- 追加された行はこの色です。
- 削除された行はこの色です。
*Luaで良く作る関数 ~string編~ [#jad89581]
-[[python型の文字列拡張書式指定>#pyformat]]
-[[文字列のスライシング>#strslice]]
&aname(pyformat);
**python型の文字列拡張書式指定。[#i7a7a2bf]
- pyformat.lua として保存
#sh(lua){{
-- グローバルで文字列に対して「%」演算出来るようにする。
getmetatable('').__mod = function(s, tab)
return (
s:gsub(
'%%%((%a%w*)%)([-0-9%.]*[cdeEfgGiouxXsq])',
function(k, fmt) return tab[k] and ("%"..fmt):format(tab[k]) or '%('..k..')'..fmt end
)
)
end
}}
-使い方~
test.lua
#sh(lua){{
require "pyformat"
local tbl = {key = "my variable", val = 56.2795}
print( "%(key)s is %(val)2.2f%" % tbl )
--> "my variable is 56.28%"
}}
&aname(strslice);
**文字列のスライシング。 [#uc04ec15]
- strslice.lua として保存
#sh(lua){{
-- 文字列のインデックス、及び、スライス。
getmetatable('').__call = function(str,i,j)
if j==nil then return string.sub(str,i,i) end
if type(i)~='table' then
return string.sub(str,i,j)
else
local t={}
for k,v in ipairs(i) do
t[k]=string.sub(str,v,v)
end
return table.concat(t)
end
end
}}
-使い方~
test.lua
#sh(lua){{
require "strslice"
local s = "abcdefg"
print(s(3)) --> c
print(s(3, 3)) --> c
print(s(2, 5)) --> bcde
print(s(3, -1)) --> cdefg
print(s(1, -2)) --> abcdef
print(("abc")(3)) --> c
}}