>       local optimized_string = formatted_string:gsub('^(%d*\.%d-)(0*)$', '%1')

  Actually, I just realized that the primitive tostring does exactly the
same transformation (probably in a much safer way), so we can use it in
the much more complete code:

====

-- Thank you, Lua-users wiki :-)
-- http://lua-users.org/wiki/VarargTheSecondClassCitizen Issue #7

-- The first two functions below implement a map over a "..." list
local function map_rec(f, n, a, ...)
  if n > 0 then return f(a), map_rec(f, n-1, ...) end
end

local function map(f, ...)
  return map_rec(f, select('#', ...), ...)
end

-- Our "better formatting" function
function string.better_format(form, ...)
  -- Every number-kind-of-format -> %s
  form = form:gsub('%%[0-9]-%.?[0-9]-f', '%%s')
  form = form:gsub('%%d', '%%s')
  form = form:gsub('%%i', '%%s')
  -- Then make every argument in the list into a string
  return(string.format(form, map(tostring, ...)))
end

-- Now Lua will happily strip the trailing zeroes
print(string.better_format("%f %f m", 94.486000, 30.000))
print(string.better_format("%5f %.7f l", .577, 2.7828))
print(string.better_format("%5f %.7f %d l", 3.14000, 2.7828, 3))

====

        Arthur
_______________________________________________
dev-context mailing list
[email protected]
http://www.ntg.nl/mailman/listinfo/dev-context

Reply via email to