Created
December 7, 2022 13:51
-
-
Save neomantra/9017a7291bdc13e7e541f6fc5bf17822 to your computer and use it in GitHub Desktop.
Lua function to convert thousands-separated numbers into plain numbers
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
-- converts thousands-separated numbers into plain numbers | |
-- for example: | |
-- cnum(0) == 0 | |
-- cnum(1,000) == 1000 | |
-- cnum(3,141,593) == 3141593 | |
-- cnum(-9,001) == -9001 | |
function cnum(...) | |
local superbase = 1000 | |
local sign = 1 | |
local result = 0 | |
if arg.n ~= #arg then -- maybe a nil arg? arg.n counts it | |
error("group count mismatch (nil group?)", 2) | |
end | |
-- in the case of a single argument, be more flexible | |
if #arg == 1 then | |
local number = tonumber(arg[1]) | |
if not number then | |
error("argument of wrong type: "..type(group), 2) | |
end | |
return number | |
end | |
for ii, group in ipairs(arg) do | |
local number = tonumber(group) | |
if not number then | |
error("numeric group ("..ii..") of wrong type: "..type(group), 2) | |
end | |
if number < 0 and ii == 1 then | |
sign = -1 | |
number = -number | |
end | |
if number < 0 or number >= superbase then | |
error("numeric group ("..ii..") out of range: "..number, 2) | |
elseif number % 1 ~= 0 and ii ~= #arg then | |
error("numeric group ("..ii..") not integral: "..number, 2) | |
end | |
result = result * superbase + number | |
end | |
return sign * result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment