[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Keyed format specifier
- From: Eike Decker <eike@...>
- Date: Thu, 3 Jan 2008 23:27:28 +0100
local fmt = string.format
function string.format (str,...)
if type((...))=="table" then
local tab = (...)
local repl = {}
str = str:gsub("%%%((.-)%)",
function(val)
repl[#repl+1] = tab[val]
return "%"
end
)
return fmt(str,unpack(repl))
else
return fmt(str,...)
end
end
print(string.format("%(foo)s = %(bar)d", {foo = "variable", bar = 22}))
print(string.format("%s = %d", "variable", 22))
does the trick (for this case at least) - could be optimized maybe....
Neat idea btw.
Eike
> My apologies if this is the wrong place to suggest this, but how about
> adding a keyed format specifier for string.format?
>
> To me,
>
> string.format("%(foo)s = %(bar)d", {foo = "variable", bar = 22})
>
> which I stole from Python, would be very handy and fits comfortably into
> the primitive way I think about Lua.
>
> Erik von Reis
>