lua-users home
lua-l archive

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


For of all, many thanks for sharing your thoughts. Really useful.

> The switch of tostring returning "2.0" instead of "2" is somewhat significant:

We really thought that change would be small. The manual always has
recomended programmers not to use 'tostring' for "serious" output:

  * tostring (v)
    Receives a value of any type and converts it to a string in a
    reasonable format. (For complete control of how numbers are
    converted, use string.format.)


> There are a few other cases where you need just the integer of a
> result and you want to append it to some other text, like when you're
> formatting a number with commas, a social security number or a phone
> number. There is a decent amount of implemented Lua that will return
> "1.0,234.0,567.0" (1,234,567), "+1.0 (612.0) 555.0-5555.0" (+1 (612)
> 555-5555), etc.

Are you sure this is so frequent? Wouldn't these numbers be usually
represented as integers (and therefore printed as such)?


> The fix for this feels different than even the one for _ENV/setfenv.
> You can overload or replace tostring to check for an integer and
> return the integer portion but this is a "patch" that brings back old
> behavior.

What is the problem here? If you explicitly want the old behavior,
put it back:

  local oldtostring = tostring
  tostring = function (x)
    if math.type(x) == "float" then return string.format("%.14g", x)
    else return oldtostring(x)
    end
  end

(That is why 'print' uses 'totring' after all.)


> If you want to use "//" but also need to support users of
> older Lua, then you have to have access to "load", or require and
> pall, or  a macro processor...

You can also use math.ifloor:

> = math.ifloor(3.0)
3

(I am not sure 'ifloor' was already present in work 1...) For older
versions, you simply define it to be floor:

  math.ifloor = math.ifloor or math.floor


> Also, code that uses "//" consistently will be different than code
> that uses "math.floor", every now and again. Let's say that you want
> an integer value to appear, without a ".0":
> --5.2 behavior
> > = string.format("%s", n)
> 1001
> --5.3 behavior
> > = string.format("%s", n)
> 1001.0

Again, if you are printing numbers, shouldn't you be using a proper
number format here, instead of "%s"? Or, again, you can use ifloor.
And, yet again, wouln't 'n' be a proper integer, more often than not?

The main idea of printing 2.0 instead of 2 (for people) is to make
them aware that a number that probably should be an integer is not.
(When the number should really be a float, it could print 2.1 or 2.2,
so 2.0 should not cause any harm.) More often than not that could be
(and should be) fixed in the code.

Maybe a new function to "normalize" a number (make it an integer if
it has an integer value) would be a useful adddition...

-- Roberto