table 扩展
计算table 不为nil元素个数
]
function table.nums(t)
local count =
0
for k, v
in pairs(t)
do
count = count +
1
end
return count
end
判断table是否为空
]
function table.isEmpty(t)
return _G.next(t) == nil
end
判断table 是否为nil 或 空
]
function table.isNilOrEmpty(t)
return t == nil
or _G.next(t) == nil
end
遍历table元素
]]
function table.walk(t, fn)
for k, v
in pairs(t)
do
fn(v, k)
end
end
table 克隆
]
function table.clone(orig)
local orig_type = type(orig)
local copy
if orig_type ==
'table' then
copy = {}
for orig_key, orig_value
in next, orig, nil
do
copy[clone(orig_key)] = clone(orig_value)
end
setmetatable(copy, clone(getmetatable(orig)))
else
copy = orig
end
return copy
end
clone 对象
]
function clone(object)
local lookup_table = { }
local function _copy(object)
if type(object) ~=
"table" then
return object
elseif lookup_table[object]
then
return lookup_table[object]
end
local new_table = { }
lookup_table[object] = new_table
for key,
value in pairs(object)
do
new_table[
_copy(key)] =
_copy(
value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
String 扩展
去除输入字符串头部的空白字符,返回结果
]
function string.ltrim(input)
return string.gsub(input,
"^[ \t\n\r]+",
"")
end
去除输入字符串尾部的空白字符,返回结果
]]
function string.rtrim(input)
return string.gsub(input,
"[ \t\n\r]+$",
"")
end
去掉字符串首尾的空白字符,返回结果
]]
function string.trim(input)
input =
string.gsub(input,
"^[ \t\n\r]+",
"")
return string.gsub(input,
"[ \t\n\r]+$",
"")
end
过滤字符串中的空字符
function string.filterNullChar(str)
if not str
then
return str
end
local retStr =
""
for char in string.gmatch(str,
"[^%z]")
do
retStr = retStr..
char
end
return retStr
end
判断字符串是否为空
function string.isNilOrEmpty(str)
str =
string.filterNullChar(str)
return str == nil
or str ==
""
end
过滤字符串中的空字符
function string.filterNullChar(str)
if not str
then
return str
end
local retStr =
""
for char in string.gmatch(str,
"[^%z]")
do
retStr = retStr..
char
end
return retStr
end
Math扩展
function math.round(value)
value =
tonumber(value)
or 0
return math.floor(value +
0.5)
end