Created
September 4, 2016 19:34
-
-
Save jirutka/666bccf338097b87873c447544c12424 to your computer and use it in GitHub Desktop.
String interpolation in Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- 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