Lua共通カスタム関数
10123 ワード
文字列の先頭と末尾のスペースを削除
function trim(s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
string1 = " RUNOOB "
string2 = trim(string1)
print(string2)
印刷テーブル
function print_r ( t )
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
elseif (type(val)=="string") then
print(indent.."["..pos..'] => "'..val..'"')
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
if (type(t)=="table") then
print(tostring(t).." {")
sub_print_r(t," ")
print("}")
else
sub_print_r(t," ")
end
print()
end
table脱重
table = {1 , 2 , 3 , 4 , 20 , 6 , 7 , 7 , 15 , 28};
function table_unique(t)
local check = {};
local n = {};
for key , value in pairs(t) do
if not check[value] then
n[key] = value
check[value] = value
end
end
return n
end
for key , value in pairs(table_unique(table)) do
print('value is ' , value)
end
tableの長さ
私たちがtableの長さを取得するとき、#を使用してもtableを使用しても.getnはいずれもインデックスが中断した場所でカウントを停止し、tableの長さを正しく取得できない.
代わりに次の方法を使用できます.
function table_leng(t)
local leng=0
for k, v in pairs(t) do
leng=leng+1
end
return leng;
end
table最大値
table.maxnはLua 5.2以降この方法は存在しなくなり、table_を定義しました.maxnメソッドを実装します.
function table_maxn(t)
local mn=nil;
for k, v in pairs(t) do
if(mn==nil) then
mn=v
end
if mn < v then
mn = v
end
end
return mn
end
tbl = {[1] = 2, [2] = 6, [3] = 34, [26] =5}
print("tbl :", table_maxn(tbl))
print("tbl ", #tbl)
アラビア数字を国語の漢字数字に変換する
local function NumToCN(num)
local size = #tostring(num)
local CN = ""
local StrCN = {" "," "," "," "," "," "," "," "," "}
for i = 1 , size do
CN = CN .. StrCN[tonumber(string.sub(tostring(num), i , i))]
end
return CN
end
print(NumToCN(56665))