Anonymous user
Module:IP: Difference between revisions
From the Croc Wiki, the Croc encyclopedia
Jump to navigationJump to search
use __index plus a unique key to access any IPAddress object's internal data
(implement Subnet (very rushed; will check and refactor!)) |
(use __index plus a unique key to access any IPAddress object's internal data) |
||
Line 10:
local V4 = 'IPv4'
local V6 = 'IPv6'
------------------------------------------------------------------------
Line 263 ⟶ 239:
do
local dataKey = {} -- A unique key to access objects' internal data.
-- Static private methods
local function ipEquals(ip1, ip2)
local lhs = ip1[dataKey].parts
local rhs = ip2[dataKey].parts
if lhs.n == rhs.n then
for i = 1, lhs.n do
if lhs[i] ~= rhs[i] then
return false
end
end
return true
end
return false
end
local function ipLessThan(ip1, ip2)
local lhs = ip1[dataKey].parts
local rhs = ip2[dataKey].parts
if lhs.n == rhs.n then
for i = 1, lhs.n do
if lhs[i] ~= rhs[i] then
return lhs[i] < rhs[i]
end
end
return false
end
return lhs.n < rhs.n
end
-- Constructor
function IPAddress.new(ip, parts)
checkType('IPAddress.new', 1, ip, 'string')
-- Set up structure
local obj =
local data = {}
-- Set initial values
if not (ipv4Address(data, ip) or ipv6Address(data, ip)) then
error('invalid IP', 2)
end
data.version = data.parts.n == 2 and V4 or V6
-- Public methods
Line 322 ⟶ 332:
end
--
return setmetatable(obj, {
__lt = ipLessThan,
__index = function (self, key)
if
return data
end
end,
__concat = function (self, obj)
return tostring(self) .. tostring(obj)
end,
__tostring = function (self)
return ipString(self:getIPParts())
end,
})
end
end
|