Added support for numerical keys to lume.format()

This commit is contained in:
rxi 2014-03-04 12:18:50 +00:00
parent bdb2f0003e
commit fb64932134
2 changed files with 7 additions and 4 deletions

View File

@ -213,10 +213,11 @@ lume.trim(" Hello ") -- Returns "Hello"
### lume.format(str [, vars]) ### lume.format(str [, vars])
Returns a formatted string. The values of keys in the table `vars` can be Returns a formatted string. The values of keys in the table `vars` can be
inserted into the string by using the form `"{key}"` in `str`. inserted into the string by using the form `"{key}"` in `str`; numerical keys
can also be used.
```lua ```lua
lume.format("Hello {a}, I hope {a} is {b}.", {a = "world", b = "well"}) lume.format("{b} hi {a}", {a = "mark", b = "Oh"}) -- Returns "Oh hi mark"
-- Returns "Hello world, I hope world is well." lume.format("Hello {1}!", {"world"}) -- Returns "Hello world!"
``` ```
### lume.trace(...) ### lume.trace(...)

View File

@ -232,7 +232,9 @@ end
function lume.format(str, vars) function lume.format(str, vars)
if not vars then return str end if not vars then return str end
local f = function(x) return tostring(vars[x] or "{" .. x .. "}") end local f = function(x)
return tostring(vars[x] or vars[tonumber(x)] or "{" .. x .. "}")
end
return (str:gsub("{(.-)}", f)) return (str:gsub("{(.-)}", f))
end end