Lua's built-in "fill a text with a few variables" function is string.format
, which works like C's printf family of functions.
You can write one that works they way you want by using gsub to find all instances of %n
, grab the n
and use that to look up one of your arguments by position:
function format(fmt, ...)
local args = {...}
return (fmt:gsub('%%(%d)', function(i) return args[tonumber(i)] end))
end
Now you can have your place holders refer to arguments by position:
format("Day: %1 is the %2th day in the %3th week", day, weekday, week) --> Day: 22 is the 2th day in the 3th week
format("in the %3 week the %2th day is your Day: %1", day, weekday, week) --> in the 3 week the 2th day is your Day: 22
format("%1 %2 %3 %2 %1", day, weekday, week) --> 22 2 3 2 22