版本对比函数

--[[
-- 函数说明: 版本字符串对比
-- 返回说明: localVersion < serverVersion
]]
function isVersionLessThan(localVersion, serverVersion)
    local idx1 = 1
    local idx2 = 1

    local num1 = 1
    local num2 = 1
    while(true) do
        local begin1, ended1 = string.find(localVersion, '%.', idx1)
        local begin2, ended2 = string.find(serverVersion, '%.', idx2)
        if((not begin1) or (not begin2)) then
            num1 = string.match(localVersion, "(%d+)", idx1) or 0
            num2 = string.match(serverVersion, "(%d+)", idx2) or 0

            if(tonumber(num1) < tonumber(num2)) then
                return true
            else
                return false
            end
        end
        num1 = string.sub(localVersion, idx1, begin1 - 1)
        num2 = string.sub(serverVersion, idx2, begin2 - 1)

        if(tonumber(num1) < tonumber(num2)) then
            return true
        elseif(tonumber(num1) > tonumber(num2)) then
            return false
        end

        idx1 = ended1 + 1
        idx2 = ended2 + 1
    end
end

例子:

    print(isVersionLessThan("1.21", "1.22"))   -- true
    print(isVersionLessThan("1.21", "1.12"))   -- false
    print(isVersionLessThan("1.2.1", "1.2.2")) -- true
    print(isVersionLessThan("1.2.1", "1.1.2")) -- false
    print(isVersionLessThan("1.2.1", "1.2.1")) -- false
    print(isVersionLessThan("1.2", "1.1.8"))   -- false

你可能感兴趣的:(版本对比函数)