lua-users home
lua-l archive

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

First, you can easily avoid using s:reverse(), which creates a new string, instead reverse the direction of the loop.
But in fact you can easily detect that a double is returned for -4611686018427387904.0 (and only this integer value) and avoid the costly loop performing custom multiplication by 10:

The integer  (-4611686018427387904) is simply the _expression_ (- 4611686018427387903 - 1), where all numbers are already integers in expressions (you may also avoid the cost of computing this _expression_ by keeping it in a cache within the function closure

Normally a Lua compiler should be able to preevaluate that _expression_ because all items are constant. Usually (but not generally) the function context does not override the unary and binary minus operators; there should be a clean way to declare to the Lua interpret or compiler that it should ignore the context and use only builtin operators, or a way to use those buoting operators using their implied functional form under a global non-overridable scope, using a formal path, but visibly all is made in Lua to forbid any function to get a granted acces to the global scope, so it's difficult to determine if the result of the _expression_ (- 4611686018427387903 - 1) is really constant or if it has other side effects, even if all its parameters and operator names look as constants; the constant status is true for the two integers but not for the two operators). Your attempt using these two functions are also unable to assert that the expressions used will really be integers as it uses more operators and some additional "global" functions supposed to work on strings and retuirn strings, plus the "|0" construct which is supposed to return an integer (but still not warrantied as "|" is also overridable by the context).

There's no well-defined way in Lua to select specific types to use for evaluating expressions using their attached method.

Le lun. 3 déc. 2018 à 20:13, Magicks M <> a écrit :
Quoting from Programming in lua:
We can write constants larger than 2^63 -1 directly, despite appearances:
  > x = 13835058055282163712 -- 3 << 62
 > x                        --> -4611686018427387904
When I enter this example into an interpreter (you can try in the lua demo) the number is cast to a float, is that supposed to happen?

I wrote the following helper function(s) to "tonumber" strings which may be UInts, but I was wondering I could do it by a more direct method as discussed in the manual:
local function by10(n, i) i = i or 1
    for _ = 1, i do n = (n << 4) - (n << 2) - (n << 1) end
    return n

function integer(s) s = s:reverse()
    local n = 0
    for i = 0, #s -1 do
        n = n + by10(s:sub(i+1,i+1)|0, i)
    return n