專案中的工具類編寫,以utils.lua為例:首先建立乙個表。utils = utils or {}
尋找陣列中某個值的下標
utils = utils or
--尋找陣列中某個值的下標,僅在table中每個值都不一樣時有效
utils.
findidxbyvalue
=function
(arr,value)
local temparr = arr
local tempvalue = value
for i,v in
ipairs
(temparr)
doif v == tempvalue then
return i
endend
end
使用方法如下圖:
將字串型別轉變為table
--將string轉為table1
function utils.
stringtotable
(str, istablelist)
if str==
"" or str==nil then
return
endlocal ret, msg
if istablelist then
ret, msg =
loadstring
(string.
format
("return "
, str)
)else
ret, msg =
loadstring
(string.
format
("return %s"
, str)
) end
if not ret then
logmanager:
debuglog
("原文內容 "
,str)
logmanager:
debuglog
("loadstring error"
, msg)
return nil
endreturn
ret(
)end
使用方式跟上面一樣的,看下圖
去除字串兩邊的空格
--去除字串兩邊空格
function utils.
trim
(s)return
(string.
gsub
(s,"^%s*(.-)%s*$"
,"%1"
)) end
根據分隔符去切割字串
--根據分隔符分割字串,返回分割後的table
utils.
split
=function
(s, delim)
if not s then
return
endassert
(type
(delim)
=="string" and string.
len(delim)
>0,
"bad delimiter"
) local start =
1 local t =
while
true
do local pos = string.
find
(s, delim, start,
true
)if not pos then
break
endtable.
insert
(t, string.
sub(s, start, pos -1)
) start = pos + string.
len(delim)
endtable.
insert
(t, string.
sub(s, start)
)return t
end
使用方法如下,
local cur_list = utils.split(str,"-"),當然delim可以是「|【】-。」等等
當然還有其他工具類,還有很多,等以後有時間慢慢新增。
--獲取兩點之間的距離
utils.
getdistance
=function
(pone, ptwo)
if not pone then
return
0 end
if not ptwo then
return
0 end
local dx = ptwo.x - pone.x
local dy = ptwo.y - pone.y
return math.
sqrt
(dx * dx + dy * dy)
end--四捨五入
utils.
roundoff
=function
(num)
local integer, decimal = math.
modf
(num)
if decimal >=
0.5 then
return integer +
1else
return integer
endend--保留兩位小數
utils.
reservetwo
=function
(num)
return
tonumber
(string.
format
("%.2f"
, num)
)end
-- 是否中文字
utils.
iscn
=function
(c)return c:
byte()
>
128end
-- 判斷資源是否為jpg
function utils:
checkisjpeg
(filepath)
local isjpeg =
false
local inpfile = io.
open
(filepath,
"rb"
)-- 讀取前三位
local bytes = inpfile:
read(3
)if bytes then
local fileheadiden =
""for _, b in ipairs
do local val = string.
format
("%02x"
, b)
fileheadiden = fileheadiden.
.val
endif string.
upper
(fileheadiden)
=="ffd8ff" then
isjpeg =
true
else
print
("==> filepath : "..
tostring
(filepath)..
", fileheadiden : "..
tostring
(fileheadiden)
) end
endinpfile:
close()
return isjpeg
end
lua 工具類(一)
author my name date 2013 12 16 18 52 11 csv解析 去掉字串左空白 local function trim left s return string.gsub s,s end 去掉字串右空白 local function trim right s return...
lua模組編寫
lua允許我們編寫自定義模組以便後面呼叫,在編寫模組之前我們先認識2個知識點 1.lua語言中陣列,模組其實都是table 2.在之前的lua基本語法裡我們知道函式是可以賦值給變數的 好,我們新建乙個檔案my.lua 如下 local my my.name 滄浪水 my.url www.freecl...
lua簡單類的實現
類實現 myclass class myclass 這句話是重定義元表的索引,必需要有 myclass.index myclass function myclass test x,y local temp setmetatable temp,myclass 必需要有 self.x x self.y ...