Skip to content

Instantly share code, notes, and snippets.

@mjf
Last active January 29, 2025 07:12
Show Gist options
  • Save mjf/a62616a0c754ee8c913935a3eac7a5e1 to your computer and use it in GitHub Desktop.
Save mjf/a62616a0c754ee8c913935a3eac7a5e1 to your computer and use it in GitHub Desktop.
Simple number formatter in Lua
-- Function formatNumber - Simple number formatter
-- Copyright (C) 2025 Matous Jan Fialka, <https://mjf.cz/>
-- Released under the terms of the "MIT" license
local function formatNumber(format, ...)
local args = { ... }
local argind = 1
local res = ''
local i = 1
while i <= #format do
local chr = format:sub(i, i)
if chr == '%' then
i = i + 1
local padchr = '0'
local padcnt = 0
if string.match(format:sub(i, i), '[^%dN]') then
padchr = format:sub(i, i)
i = i + 1
end
local cntstr = ''
while string.match(format:sub(i, i), '%d') do
cntstr = cntstr .. format:sub(i, i)
i = i + 1
end
if cntstr ~= '' then
padcnt = tonumber(cntstr)
end
if format:sub(i, i) == 'N' then
if argind <= #args then
local num = tostring(args[argind])
local neg = false
if string.sub(num, 1, 1) == '-' then
neg = true
num = string.sub(num, 2)
end
if padcnt == 0 and padchr ~= '0' then
padcnt = 2
end
local pad = string.rep(padchr,
math.max(0, padcnt - #num - (neg and 1 or 0)))
if neg and string.match(padchr, '%d') then
res = res .. '-' .. pad .. num
else
res = res .. pad .. (neg and '-' or '') .. num
end
argind = argind + 1
i = i + 1
else
error('Not enough arguments!')
end
else
res = res .. '%' .. format:sub(i, i)
i = i + 1
end
else
res = res .. chr
i = i + 1
end
end
if argind <= #args then
error('Too many arguments!')
end
return res
end
-- TESTS
-- print(formatNumber('%N', 123456))
-- print(formatNumber('%N', -123456))
-- print(formatNumber('%xN', 3))
-- print(formatNumber('%xN', -3))
-- print(formatNumber('%x2N', 3))
-- print(formatNumber('%x2N', -3))
-- print(formatNumber('%16N', 123456))
-- print(formatNumber('%16N', -123456))
-- print(formatNumber('%016N', 123456))
-- print(formatNumber('%016N', -123456))
-- print(formatNumber('% 16N', 123456))
-- print(formatNumber('% 16N', -123456))
-- print(formatNumber('%.16N', 123456))
-- print(formatNumber('%+16N', -123456))
-- vi:ft=lua
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment