Skip to content

Instantly share code, notes, and snippets.

@gphg
Last active February 22, 2024 04:36
Show Gist options
  • Save gphg/8de1aa2d5a6c62b87d23f879768f2185 to your computer and use it in GitHub Desktop.
Save gphg/8de1aa2d5a6c62b87d23f879768f2185 to your computer and use it in GitHub Desktop.
Lua function for format string by replaces %1, %2 and so on in the passed string of the passed arguments.
---Replaces %1, %2 and so on in the passed string of the passed arguments.
---@param str string # The string pattern contains %1 to %9.
---@param ... any # Any types will be passed to tostring.
---@return string str # New formated replaced string.
---@return integer count # Number of operations.
local stringformat = function(str, ...)
local tostring, select, gsub, t = tostring, select, string.gsub, {}
for i = 1, select('#', ...) do
t[tostring(i)] = tostring(select(i, ...))
end
return gsub(str, "%%([%d]+)", t)
end
---
---Examples
---
local s = [[%1 says to %2, that %2 did't pay $%3 to %4 for nothing.]]
local t = setmetatable({
name = 'Aura'
}, {
__tostring = function(t)
return tostring(t.name)
end
})
local a = {
'Serra',
'Terra',
69,
-- special case where table passed to tostring
t,
-- get ignored
'this get thrown away'
}
local x = stringformat(s, unpack(a))
print(x)
local y = stringformat([[$%3 is $%3.]], unpack(a))
print(y)
local z = stringformat('$%1 is $%1.', 50)
print(z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment