lua-users home
lua-l archive

Re: Keyed format specifier

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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
> 

AltStyle によって変換されたページ (->オリジナル) /