Created
December 4, 2011 18:42
-
-
Save annulen/1430957 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Version = {} | |
function Version:clear() | |
for k,_ in ipairs(self) do | |
self[k] = nil | |
end | |
end | |
function Version:parse(str) | |
self:clear() | |
if type(str) == "string" then | |
-- Split string by '.' and '-' | |
for c in str:gmatch("[^%.%-]+") do | |
-- Split numbers and strings | |
n, str = c:match("(%d*)(%a*)") | |
if n then | |
table.insert(self, tonumber(n)) | |
end | |
if str and #str > 0 then | |
table.insert(self, str) | |
end | |
end | |
end | |
end | |
function Version:__eq(other) | |
if #self ~= #other then | |
return false | |
end | |
for i = 1, #self do | |
if self[i] ~= other[i] then | |
return false | |
end | |
end | |
return true | |
end | |
-- true if self <= other | |
function Version:__le(other) | |
local m = 0 | |
if #self > #other then | |
m = #self | |
else | |
m = #other | |
end | |
for i = 1, m do | |
print ("-->", self[i] or 0, other[i] or 0) | |
if (self[i] or 0) > (other[i] or 0) then | |
return false | |
end | |
end | |
return true | |
end | |
function Version:__lt(other) | |
local m = 0 | |
if #self > #other then | |
m = #self | |
else | |
m = #other | |
end | |
for i = 1, m do | |
local s = self[i] or 0 | |
local o = other[i] or 0 | |
if type(s) ~= type(o) then | |
print(s, o) | |
return false | |
end | |
print ("-->", s, o) | |
if s < o then | |
return true | |
end | |
end | |
return true | |
end | |
function Version:__tostring() | |
if self.original then | |
return self.original | |
else | |
return table.concat(self, ".") | |
end | |
end | |
function Version:new(t) | |
if type(t) == "table" then | |
v = t | |
setmetatable(v, self) | |
self.__index = self | |
return v | |
elseif type(t) == "string" then | |
v = {} | |
setmetatable(v, self) | |
self.__index = self | |
v.original = t | |
v:parse(t) | |
return v | |
end | |
end | |
local v = Version:new {1,2,3} | |
assert(tostring(v) == "1.2.3") | |
local v2 = Version:new "0.9.8d" | |
assert(tostring(v2) == "0.9.8d") | |
local v3 = Version:new("1.0.0-2") | |
local v4 = Version:new("1.0.0.2") | |
assert(v3 == v4) | |
assert(v3 <= v4) | |
assert(v3 >= v4) | |
local v5 = Version:new("0.9") | |
print(v, v2, v3, v5) | |
assert(v3 < v) | |
v:parse("0.9.8c") | |
assert(tostring(v) == "0.9.8.c") | |
print "OK" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment