[5.4] The string metatable and arbitrary-precision arithmetic

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

[5.4] The string metatable and arbitrary-precision arithmetic

Dirk Laurie-2
There is only one incompatibility listed in the Lua 5.4 (work2) manuall.

> The coercion of strings to numbers in arithmetic and bitwise operations has been removed from the core language. The string library does a similar job for arithmetic (but not for bitwise) operations using the string metamethods. However, unlike in previous versions, the new implementation preserves the implicit type of the numeral in the string. For instance, the result of "1" + "2" now is an integer, not a float.

If backward compatibility of coercion arithmetic is not desired, these
metamethods could be replaed to give arbitrary-precision arithmetic.

For example:

$ sudo luarocks install lbc
$ lua5.4 -l bc
Lua 5.4.0  Copyright (C) 1994-2017 Lua.org, PUC-Rio
    meta = getmetatable''
    for k,v in pairs(bc) do
      if k~='__index' then meta[k] = bc[k] end
    end
    function fermat(n)
      if n==0 then return '3'
      else return (fermat(n-1)-1)^2+1
      end
    end
    fermat(7)
340282366920938463463374607431768211457

Reply | Threaded
Open this post in threaded view
|

Re: [5.4] The string metatable and arbitrary-precision arithmetic

Luiz Henrique de Figueiredo
> If backward compatibility of coercion arithmetic is not desired, these
> metamethods could be replaed to give arbitrary-precision arithmetic.

Very nice! You've reminded me that lbc does not handle __idiv. I'll
fix that soon.

However, you probably want

    for k,v in pairs(meta) do

instead of

    for k,v in pairs(bc) do

Otherwise, you'll put a lot of garbage in the string metatable.

Reply | Threaded
Open this post in threaded view
|

Re: [5.4] The string metatable and arbitrary-precision arithmetic

Dirk Laurie-2
2018-06-26 16:30 GMT+02:00 Luiz Henrique de Figueiredo <[hidden email]>:

>> If backward compatibility of coercion arithmetic is not desired, these
>> metamethods could be replaed to give arbitrary-precision arithmetic.
>
> Very nice! You've reminded me that lbc does not handle __idiv. I'll
> fix that soon.
>
> However, you probably want
>
>     for k,v in pairs(meta) do
>
> instead of
>
>     for k,v in pairs(bc) do
>
> Otherwise, you'll put a lot of garbage in the string metatable.

Yes, that is the right way round.