记录一些工作中常用的工具函数
常见的table改造,日期格式化,字符串和表格式之间的转换
util.lua
local sformat = string.format
local sSub = string.sub
local sFind = string.find
local type = type
local pairs = pairs
local ipairs = ipairs
local loadstring = load
local string_byte = string.byte
--table 转为 string
function __tabToStr( tab)
if tab == nil then
return nil;
end;
local result = "{"
for k,v in pairs(tab) do
if type(k) == "number" then
if type(v) == "table" then
result = sformat( "%s[%d]=%s,", result, k, __tabToStr( v ,is) )
elseif type(v) == "number" then
result = sformat( "%s[%d]=%s,", result, k, tostring(v) )
elseif type(v) == "string" then
result = sformat( "%s[%d]=%q,", result, k, v )
elseif type(v) == "boolean" then
result = sformat( "%s[%d]=%s,", result, k, tostring(v) )
else
error("")
end
else
if type(v) == "table" then
result = sformat( "%s['%s']=%s,", result, k, __tabToStr( v, is ) )
elseif type(v) == "number" then
result = sformat( "%s['%s']=%s,", result, k, tostring(v) )
elseif type(v) == "string" then
result = sformat( "%s['%s']=%q,", result, k, v )
elseif type(v) == "boolean" then
result = sformat( "%s['%s']=%s,", result, k, tostring(v) )
else
error("")
end
end
end
result = result .. "}"
return result
end
function FormatTimeStamp(ts)
if not ts then
return "none"
end
local date = os.date("*t", ts)
return string.format("%04d-%02d-%02d %02d:%02d:%02d", date.year, date.month, date.day, date.hour, date.min, date.sec)
end
function string.isempty( str )
if str and str ~= "" then
return false
end
return true
end
local strB = string.byte("{", 1)
local strE = string.byte("}", 1)
function strToTable( str )
if not str then
return
end
if str:byte(1) ~= strB and str:byte(#str) ~= strE then
error("Invalid table string")
return
end
local chunk, _err = load( "return {"..str .. "}", "", "t", {})
if chunk then
local rt = chunk()
assert(#rt == 1)
rt = rt[1]
rt = (rt and type(rt) == "table") and rt or {}
return rt
else
error("Invalid table string");
end
end
--判断是不是同一月
function isSameMonth(old, now)
local oldMonth, newMonth = tonumber(os.date("%m", old)), tonumber(os.date("%m", now))
return (oldMonth == newMonth)
end
--判断是不是同一天
function IsSameDay(timeA, timeB)
if(os.date("%x", timeA) == os.date("%x", timeB))then
return true
end
return false
end
--获得给定日期的时间戳
--wady(1~7, 周日为1)指定哪个星期
function getTimeDate(wday, hour, min)
assert(wday <= 7 and wday >= 1)
local t = os.date("*t")
t.hour = hour or 0
t.min = min or 0
t.sec = 0
return os.time(t) + 86400 * (wday - t.wday)
end
--获取当月有多少天
function getMonthLen(now)
local curr_mon = tonumber(os.date("%m" , now))
local curr_year = tonumber(os.date("%Y" , now))
return getMonthLenByMonth(curr_year , curr_mon)
end
function getMonthLenByMonth(curr_year , curr_mon)
if curr_mon == 2 then
if (curr_year % 4 == 0 and curr_year % 100 ~= 0) or (curr_year % 400 == 0) then
return 29
else
return 28
end
elseif curr_mon == 1 or curr_mon == 3 or curr_mon == 5 or curr_mon == 7 or curr_mon == 8 or curr_mon == 10 or curr_mon == 12 then
return 31
else
return 30
end
end
--以给定时间为基准,取下一个每周的周期性时间点(比如在当前时间下,返回下一个每周五晚上20点活动开始的时间)
--wady(1~7, 周日为1)指定哪个星期, hour/min指定具体时间(默认为0)
function getWeekTime(curTime, wday, hour, min)
assert(wday <= 7 and wday >= 1)
if hour == nil then
hour = 0
end
if min == nil then
min = 0
end
local curDate = os.date('*t', curTime)
local diff = 0
if curDate.wday <= wday then
diff = wday - curDate.wday
else
diff = 7 - curDate.wday + wday
end
curDate.hour=0
curDate.min=0
curDate.sec=0
local weekTime = os.time(curDate) + diff * 3600 * 24 + hour * 3600 + min * 60
if curTime >= weekTime then
weekTime = weekTime + 7 * 24 * 3600
end
return weekTime
end
--是否同一周
--wday(1~7, 周日为1)指定以哪一星期为一周的分隔, hour/min指定具体的时间点(默认为0)
--后三个参数不指定的情况下默认以周一的0点0分0秒为一周开始
function IsSameWeek(timeA, timeB, wday, hour, min)
if wday == nil then
wday = 2 --周一
hour = 0
min = 0
end
if hour == nil then
hour = 0
end
if min == nil then
min = 0
end
if timeA > timeB then
local tmp = timeA
timeA = timeB
timeB = tmp
end
local boundTime = getWeekTime(timeA, wday, hour, min)
if timeB < boundTime then
return true
end
return false
end
-- 将某个时间转化成当天对应的0点时间
function getZeroTime(time)
local date = os.date("*t", time)
date.hour = 0
date.min = 0
date.sec = 0
return os.time(date)
end
function getPassDays(timeOld, timeNew)
if timeOld > timeNew then
return 0
end
local time_zone = os.time {year=2000, month=1, day=1, hour=0}
timeOld = timeOld - time_zone
timeNew = timeNew - time_zone
return math.floor(timeNew / 86400) - math.floor(timeOld / 86400)
end
function GetUTF8EndByteIndex(s, i)
if not i then
if #s == 0 then return nil end
return 1, true --fake flag (doesn't matter since this flag is not to be taken as full validation)
end
if i > #s then return end
local c = s:byte(i)
if c >= 0x00 and c <= 0x7F then
i = i + 1
elseif c >= 0xC2 and c <= 0xDF then
i = i + 2
elseif c >= 0xE0 and c <= 0xEF then
i = i + 3
elseif c >= 0xF0 and c <= 0xF4 then
i = i + 4
else --invalid
return i + 1, false
end
if i > #s+1 then return end
return i, true
end
function BindFunc(env, name, ...)
if not env[name] then
error(string.format("BindFunc check error: function %s not found", name))
end
local bindArgs = table.pack(...)
local bindArgsNum = bindArgs.n
return function(...)
local func = env[name]
if func then
if bindArgsNum > 0 then
return func(table.unpack(bindArgs, 1, bindArgsNum), ...)
else
return func(...)
end
else
error(string.format("BindFunc call error: function %s not found", name))
end
end
end
class.lua
function makeClass( t )
local mt = getmetatable(t)
mt.__call=function(t,...)
return t.new(...)
end
t.__index=t
t.new=function(...)
local ret={}
setmetatable(ret,t)
return ret
end
end
function Inherit(mod, base)
mod.__base = base
local meta = {__index = function(t, k)
return mod.__base[k]
end
}
setmetatable(mod, meta)
end
function MODULE(name)
_ENV[name] = _ENV[name] or {}
local m = setmetatable(_ENV[name], {__index = _ENV})
m._M = m
return m
end
table.lua
function table.indexof(tab, val)
for k, v in ipairs(tab) do
if v == val then
return k
end
end
return 0
end
function table.isempty(tab)
if not tab then
return true
end
for k,v in pairs(tab) do
return false
end
return true
end
function table.swap(tab, idx1, idx2)
tab[idx1], tab[idx2] = tab[idx2], tab[idx1]
end
function table.length( tab )
local length = 0
for _, v in pairs( tab ) do
length = length + 1
end
return length
end
function table.keys( tab )
local key_ary = {}
for key, _ in pairs( tab ) do
table.insert( key_ary, key )
end
return key_ary
end
function table.move(des, src, b, e)
des = des or {}
if src == nil or e < b then
return des
end
if b < 1 then
b = 1
end
if e > #src then
e = #src
end
for i = 1, e - b + 1 do
table.insert(des, table.remove(src, b))
end
return des
end
function table.removerange(tb, index, num)
local len = #tb
local deleteNum = 0
if index < 1 or index > len then
return deleteNum
end
if num <= 0 then
return deleteNum
end
deleteNum = math.min(len-index+1, num)
for i = index, len do
local backIndex = i + num
if backIndex <= len then
tb[i] = tb[backIndex]
else
tb[i] = nil
end
end
return deleteNum
end
function table.find( tab, val, find_func )
if not tab or not val then
return -1
end
for k, v in ipairs( tab ) do
if find_func then
if find_func( v, val ) then
return k
end
else
if v == val then
return k
end
end
end
return -1
end
function table.shuffle(tab)
for i=#tab, 1, -1 do
local j = math.random(1, i)
tab[i], tab[j] = tab[j], tab[i]
end
return tab
end
function table.flushh()
for i=#tab 1, -1 do
local rand_i = math.random(1, i)
tab[i], tab[rand_i] = tab[rand_i], tab[i]
end
end
function table.multiply(tab, num, is_new)
local result = is_new and {} or tab
if not result then
return result
end
for k, v in pairs(tab) do
result[k] = v * num
end
return result
end
function table.deepcopy(ta, tb)
if type(ta) ~= "table" or type(tb) ~= "table" then
return
end
for i, v in pairs(tb) do
if type(v) == "table" then
if not ta[i] then ta[i] = {} end
table.deepcopy(ta[i], v)
else
ta[i] = v
end
end
return ta
end
function table.deepcopy(ta, tb)
if type(ta) ~= "table" or type(tb) ~= "table" then
return
end
for i, v in pairs(tb) do
if type(v) == "table" then
if not ta[i] then ta[i] = {} end
table.deepcopy(ta[i], v)
else
ta[i] = v
end
end
return ta
end
function table.clear(tab)
for key,_ in pairs(tab) do
tab[key] = nil
end
end