More bigint type checks added

Strict checking is still off, however a check can be coerced
This commit is contained in:
Ishaan Bhardwaj 2021-02-21 20:38:16 -05:00
parent bf19f49323
commit 716de2814b

View File

@ -8,27 +8,7 @@ local strict = false
local bigint = {} local bigint = {}
local named_powers = require("libs.bigint.named-powers-of-ten") local mt = {
-- Create a new bigint or convert a number or string into a big
-- Returns an empty, positive bigint if no number or string is given
function bigint.new(num)
local self = {
sign = "+",
digits = {}
}
-- Return a new bigint with the same sign and digits
function self:clone()
local newint = bigint.new()
newint.sign = self.sign
for _, digit in pairs(self.digits) do
newint.digits[#newint.digits + 1] = digit
end
return newint
end
setmetatable(self, {
__add = function(lhs, rhs) __add = function(lhs, rhs)
return bigint.add(lhs, rhs) return bigint.add(lhs, rhs)
end, end,
@ -53,7 +33,29 @@ function bigint.new(num)
__tostring = function() __tostring = function()
return bigint.unserialize(self, "s") return bigint.unserialize(self, "s")
end end
}) }
local named_powers = require("libs.bigint.named-powers-of-ten")
-- Create a new bigint or convert a number or string into a big
-- Returns an empty, positive bigint if no number or string is given
function bigint.new(num)
local self = {
sign = "+",
digits = {}
}
-- Return a new bigint with the same sign and digits
function self:clone()
local newint = bigint.new()
newint.sign = self.sign
for _, digit in pairs(self.digits) do
newint.digits[#newint.digits + 1] = digit
end
return newint
end
setmetatable(self, mt)
if (num) then if (num) then
local num_string = tostring(num) local num_string = tostring(num)
@ -73,10 +75,11 @@ end
-- forced by supplying "true" as the second argument. -- forced by supplying "true" as the second argument.
function bigint.check(big, force) function bigint.check(big, force)
if (strict or force) then if (strict or force) then
assert(getmetatable(big) == mt, "at least one arg is not a bigint")
assert(#big.digits > 0, "bigint is empty") assert(#big.digits > 0, "bigint is empty")
assert(type(big.sign) == "string", "bigint is unsigned") assert(big.sign == "+" or big.sign == "-", "bigint is unsigned")
for _, digit in pairs(big.digits) do for _, digit in pairs(big.digits) do
assert(type(digit) == "number", digit .. " is not a number") assert(type(digit) == "number", "at least one digit is invalid")
assert(digit <= 9 and digit >= 0, digit .. " is not between 0 and 9") assert(digit <= 9 and digit >= 0, digit .. " is not between 0 and 9")
assert(math.floor(digit) == digit, digit .. " is not an integer") assert(math.floor(digit) == digit, digit .. " is not an integer")
end end