zoukankan      html  css  js  c++  java
  • Lua工具类

    1、打印table

    --一个用以打印table的函数
    function print_r (t, name)   
        print(pr(t,name))   
    end   
    
    function pr (t, name, indent)   
        local tableList = {}   
        function table_r (t, name, indent, full)   
            local id = not full and name or type(name)~="number" and tostring(name) or '['..name..']'   
            local tag = indent .. id .. ' = '   
            local out = {}  -- result   
            if type(t) == "table" then   
                if tableList[t] ~= nil then   
                    table.insert(out, tag .. '{} -- ' .. tableList[t] .. ' (self reference)')   
                else  
                    tableList[t]= full and (full .. '.' .. id) or id  
                    if next(t) then -- Table not empty   
                        table.insert(out, tag .. '{')   
                        for key,value in pairs(t) do   
                            table.insert(out,table_r(value,key,indent .. '   ',tableList[t]))   
                        end   
                        table.insert(out,indent .. '}')   
                    else table.insert(out,tag .. '{}') end   
                end   
            else  
                local val = type(t)~="number" and type(t)~="boolean" and '"'..tostring(t)..'"' or tostring(t)   
                table.insert(out, tag .. val)   
            end   
            return table.concat(out, '
    ')   
        end   
        return table_r(t,name or 'Value',indent or '')   
    end  

    2、三元运算符

    (a and {b} or {c})[1]   --如果a为true的话,那么返回b,否则返回c

    3、判断一个table是否包含某个键

    function ui_jchd_list.AddToSet(set, key)
        set[key] = true
    end
    
    function ui_jchd_list.RemoveFromSet(set, key)
        set[key] = nil
    end
    
    function ui_jchd_list.SetContains(set, key)
        return set[key] ~= nil
    end

     4、获取本地时间(不要用其他的方式,不然有可能在苹果设备上显示错误)

    local ctime = os.date("%Y-%m-%d", os.time())

         因为时区的关系,我们获取本地时间要通过如下方式获取:

    local function getTimeZone(  )
        local now = os.time()
        local zone= os.difftime(now, os.time(os.date("!*t", now)))
        return zone
    end
    
    local function getLocalTime( time,zone )
        local localTime = time-zone*3600+getTimeZone()
        return localTime
    end
    --北京为东八区
    local time1 = getLocalTime(os.time(),8)
    print(os.date('%H:%M',time1))
    --不能简简单单通过下面的方式获取,自己可以通过改变电脑的时间时区来测试就知道了(但是客户端应该有个getServerTime函数来获取服务器的本地时间,而不是拿客户端的本地时间去计算,服务端时间每隔一分钟应该同步到客户端一次)
    print(os.date("%H:%M",os.time()))

    5、拷贝table

    function copy_table(ori_tab)
        if type(ori_tab) ~= "table" then
            return
        end
        local new_tab = {}
        for k,v in pairs(ori_tab) do
            local vtype = type(v)
            if vtype == "table" then
                new_tab[k] = copy_table(v)
            else
                new_tab[k] = v
            end
        end
        return new_tab
    end
    
    function deepcopy(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 index, value in pairs(object) do
                new_table[_copy(index)] = _copy(value)
            end
            return setmetatable(new_table, getmetatable(object))
        end
        return _copy(object)
    end

     6、总秒数格式化

    --总秒数格式化   传总秒数   
    function ConfigHelpers.FormatSecond( senconds )
        local hour = math.modf(senconds / 3600)
        local min = math.modf((senconds - hour * 3600) / 60)
        local sec = math.modf((senconds - hour * 3600) % 60)
         if sec < 10 then
           sec = '0'..sec
        end
        if min < 10 then
           min = '0'..min
        end
        if hour < 10 then
           hour = '0'..hour
        end
        return hour..':'..min..':'..sec
    end

    7、continue

    for i = 1, 10 do
            while true do
                if i % 2 == 0 then 
                    --这里写continue到的代码
                    break 
                end
                --这里写没有continue到的代码
            break
    end

     8、今天距离星期几还有几天

    --今天距离星期几还有几天(tday[0-6 = Sunday-Saturday])
        local function mondayDays( tday )
            local today = os.date("%w", os.time()) --今天星期几  %w weekday (3) [0-6 = Sunday-Saturday]
            local weeks = {[1]=0,[2]=6,[3]=5,[4]=4,[5]=3,[6]=2,[0]=1}--这是距离星期一所对应的天数集合
            local span = tday - 1        
            for k,v in pairs(weeks) do
                local t = v + span
                   weeks[k] = t >= 7 and (t - 7) or t
            end
            return weeks[tonumber(today)]
        end

     9、删除table中的元素

    function RemoveTableItem( tableList , func , removeAll )
        local i = 1
        while i <= #tableList do
            if func(tableList[i]) then
                table.remove(tableList, i)
                if removeAll == false then
                    return
                end
            else
                i = i + 1
            end
        end
    end
    --------------------------测试方法-------------------------------
    local list = {2, 3, 4, 8, 9, 100, 20, 13, 15, 7, 11}
    RemoveTableItem(list,function ( v )
         if v%2 == 0 then
              return true
         else
              return false
         end
    end,true)
    for i,v in ipairs(list) do
         print(i..' = '..v)
    end

     10、判断字符串中 汉字、字母、数字、其他字符 的个数

    --判断字符串中 汉字、字母、数字、其他字符 的个数
    M2.util.getCharCount = function(content)
        local chineseCount = 0
        local englishCount = 0
        local numberCount = 0
        local otherCount = 0
        local contentArray = string.gmatch(content, ".[128-191]*")
        for w in contentArray do   
            local ascii = string.byte(w)
            if (ascii >= 65 and ascii <= 90) or (ascii>=97 and ascii <=122) then
                englishCount = englishCount + 1
            elseif ascii >= 48 and ascii <= 57 then
                numberCount = numberCount + 1
            elseif (ascii >= 0 and ascii <= 47) or (ascii >= 58 and ascii <= 64) or 
                (ascii >= 91 and ascii <= 96) or (ascii >= 123 and ascii <= 127)  then
                otherCount = otherCount + 1
            else
                --ios输入法上可以输入系统表情,而此表情的ascii码值正好在这个区间,所以要用字节数来判断是否是中文
                --226 227 239 240 为ios系统表情的ascii码值
                if string.len(w) == 3 and ascii ~= 226 and ascii ~= 227 and ascii ~= 239 and ascii ~= 240  then
                    chineseCount = chineseCount + 1
                else
                    otherCount = otherCount + 1
                end
            end
        end
        return chineseCount,englishCount,numberCount,otherCount
    end
    
    --判断输入的字符串个数(2个英文字母算一个,1个汉字算一个,如果含特殊字符,返回-1,否则返回正确个数)
    M2.util.checkNameCount = function(content)
        local chineseCount,englishCount,numberCount,otherCount = M2.util.getCharCount(content)
        if otherCount > 0 then
            return -1
        else
            local eCount = englishCount / 2
            return chineseCount+eCount+numberCount
        end
    end

     11、相隔时间格式化

    function formatDiffTime( endtime , nowtime )
        local overtime=0 day=0 hour=0 minu=0 sec=0
        local diffSeconds = os.difftime(endtime,nowtime) --os.difftime (t2, t1) 返回t1到t2相差的秒数
    
        if diffSeconds <= 0 then --如果diffSeconds<=0,那么表示结束时间小于现在的时间(已经超时)
            overtime = 1        
        else
            overtime = 0
        end
    
        diffSeconds = math.abs(diffSeconds)
        if diffSeconds <= 60 then
            sec = diffSeconds
            day=0 hour=0 minu=0
        else
            hour = diffSeconds / (60*60)  -- 总共多少小时
            day = hour / 24 
            if day >= 1 then
                local t1 , t2 = math.modf(day)
                day = t1
                hour = t2 * 24
                local r1 , r2 = math.modf(hour)
                hour = r1
                minu = r2 * 60
                local k1 , k2 = math.modf(minu)
                minu = k1
                sec = math.ceil(k2 * 60)
            else
                day = 0
                if hour >= 1 then        
                    local t1 , t2 = math.modf(hour)
                    hour = t1
                    minu = t2 * 60
                    local r1 , r2 = math.modf(minu)
                    minu = r1
                    sec = math.ceil(r2 * 60)
                else
                    minu = hour * 60
                    hour = 0
                    local t1 , t2 = math.modf(minu)
                    minu = t1
                    sec = math.ceil(t2 * 60)
                end
            end
        end
        return overtime,day,hour,minu,sec
    end
  • 相关阅读:
    使用ClassLoader加载配置文件
    Io流和Properties集合的联合应用
    文件拷贝案例
    倒计时
    静态代码块
    数组的四种排序(冒泡排序,选择排序,插入排序,快速排序)
    通过map集合统计每个字符出现的次数
    随机输入几个数字,删除重复数字(但要保留一个),留下不重复的数字
    流程图学习-1-基础符号
    Java-List的对象的校验不起作用的解决方案
  • 原文地址:https://www.cnblogs.com/MrZivChu/p/LuaHelper.html
Copyright © 2011-2022 走看看