Skip to content

Instantly share code, notes, and snippets.

@neomantra
Created December 7, 2022 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neomantra/9017a7291bdc13e7e541f6fc5bf17822 to your computer and use it in GitHub Desktop.
Save neomantra/9017a7291bdc13e7e541f6fc5bf17822 to your computer and use it in GitHub Desktop.
Lua function to convert thousands-separated numbers into plain numbers
-- 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