GroupButler icon indicating copy to clipboard operation
GroupButler copied to clipboard

Replace positional parameters in strings (%s) with named parameters ({something})

Open yangm97 opened this issue 6 years ago • 0 comments

Solution: Named Parameters in Table

Here's one simple implementation (-- RiciLake):

function interp(s, tab)
  return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end
print( interp("${name} is ${value}", {name = "foo", value = "bar"}) )

getmetatable("").__mod = interp
print( "${name} is ${value}" % {name = "foo", value = "bar"} )
-- Outputs "foo is bar"

Reference: http://lua-users.org/wiki/StringInterpolation

yangm97 avatar Jun 30 '18 15:06 yangm97