Skip to content

Instantly share code, notes, and snippets.

@jirutka
Created September 4, 2016 19:34
Show Gist options
  • Save jirutka/666bccf338097b87873c447544c12424 to your computer and use it in GitHub Desktop.
Save jirutka/666bccf338097b87873c447544c12424 to your computer and use it in GitHub Desktop.
String interpolation in Lua
--- Add support for interpolation into string using %.
--
-- Examples:
-- "Hi, %s!" % 'Mindy' --> Hi, Mindy!
-- "Hi, ${name}!" % {name = 'Mindy'} --> Hi, Mindy!
getmetatable('').__mod = function(str, args)
if type(args) ~= 'table' then
args = { args }
end
return str:format(unpack(args)):gsub('($%b{})', function(placeholder)
return args[placeholder:sub(3, -2)] or placeholder
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment