LUA的一些工具备份

table.unpack遇到的问题

做了个中转的服务, socket+json 传递数据,
通过 {...} 封装不定参数然后 json.encode 传递到其他服务器,
然后其他服务器 json.decode之后再通过 table.unpack 解出之前 {...} 里面的参数,
如果这里是 table 还好,如果这里面是 n 个整型数据的话,后面会多了个 .0
例如, 1 会被转成 1.0,这会带来一些麻烦。
调查了许久,发现不是 json 导致的,而是在 table.unpack 导致的,
所以根据网上找到的方法,重写了一个 unpack 的方法以及一个判断数组的方法,如下:


function util.unpack(t,i)
    i = i or 1
    if t[i] ~= nil then
        if type(t[i]) == "number" and t[i]%1 == 0 then
            t[i] = t[i] >> 0
        end
        return t[i],util.unpack(t,i+1)
    end
end

--检查是否是数组类型
function util.checkArray(a)
    if type(a) ~= "table" then return false end
    local count = 0
    for k,v in pairs(a) do
        if type(k) ~= "number" then return false end
        count = count + 1
    end

    for i=1,count do
        if not a[i] and type(a[i]) ~= "nil" then return false end
    end

    return true
end

猜你喜欢

转载自www.cnblogs.com/adoontheway/p/9771658.html