Module:IP: Difference between revisions

From the Croc Wiki, the Croc encyclopedia
Jump to navigationJump to search
1,207 bytes added ,  7 years ago
check self parameters in IPAddress methods
(actually, I like your version better - it's simple, it sidesteps the accuracy problem, and it probably isn't too much more overhead)
(check self parameters in IPAddress methods)
Line 11:
local V4 = 'IPv4'
local V6 = 'IPv6'
 
--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------
 
local function makeCheckSelfFunc(className, objectName, isSelfFunc)
-- Makes a function for classes to check that their methods have a valid
-- self parameter.
return function (methodName, selfObject)
if not isSelfFunc(selfObject) then
error(string.format(
'invalid %s object. Did you call %s with a dot instead of a colon, i.e. %s.%s() instead of %s:%s()?',
className, methodName, objectName, methodName, objectName, methodName
), 3)
end
end
end
 
--------------------------------------------------------------------------------
Line 328 ⟶ 345:
-- is not available to other classes or other modules.
local dataKey = {}
 
-- Private static methods
local function isIPAddressObject(val)
return type(val) == 'table' and val[dataKey] ~= nil
end
 
-- A function to check whether methods are called with a valid self
-- parameter.
local checkSelf = makeCheckSelfFunc(
'IPAddress',
'ipAddress',
isIPAddressObject
)
 
-- Metamethods that don't need upvalues
Line 361 ⟶ 391:
-- Public methods
function obj:getIP()
checkSelf('getIP', self)
return tostring(data.rawIP)
end
 
function obj:getVersion()
checkSelf('getVersion', self)
return data.rawIP:getVersion()
end
 
function obj:isIPv4()
checkSelf('isIPv4', self)
return data.rawIP:isIPv4()
end
 
function obj:isIPv6()
checkSelf('isIPv6', self)
return data.rawIP:isIPv6()
end
 
function obj:isInSubnet(subnet)
checkSelf('isInSubnet', self)
return subnet:containsIP(self)
end
 
function obj:getSubnet(bitLength)
checkSelf('getSubnet', self)
return makeSubnet(data.rawIP, bitLength)
end
 
function obj:getNextIP()
checkSelf('getNextIP', self)
return makeIPAddress(data.rawIP:getAdjacent())
end
 
function obj:getPreviousIP()
checkSelf('getPreviousIP', self)
return makeIPAddress(data.rawIP:getAdjacent(true))
end
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu