0
votes

In Lua, using the type function on any number always returns 'number'. Is there a function which can tell you whether the Lua interpreter is using a 32 bit floats, 64 bit doubles, integers or something else for the number type?

I tried to write a function like this:

function numbertype()
  local rational = 5 / 2

  if rational == 2 then
    -- equals 2
    return 'int'
  else
    -- about 2.5
    return 'double' -- but could it be a 32 bit float or something else?
  end
end

print(numbertype())

It can't yet detect the difference between floats, doubles and unknown types. How can I query to see if Lua's number type is equivalent to an int, float or double in Lua's interpreter? I would like it to work in pure Lua.

4

4 Answers

5
votes

Pure Lua cannot inquire about such things from the interpreter. Since the ability of the interpreter to use different types is pretty free-form (you can pick any floating-point or integral type), the only way to expose this to Lua would be to have the interpreter coded to anticipate every possible type of number that it could be compiled with.

In general, you shouldn't bother caring. Applications that use something other than doubles are rare at best. Even LuaJIT, which has to deal with ARM and their terrible floating-point math, still hides its ability to use integer math effectively as an optimization; Lua code can't tell the difference.

Which is as it should be.

1
votes

According to the Lua 5.1 Reference Manual, numbers are only double-precision floating-point numbers. To use another type, Lua must be recompiled with a modified luaconf.h.

0
votes

Perhaps you can use the following workarround. Calculate number%1. If the remainder is 0 than it is most likely something like an integer number.

0
votes

From the helpful sources in catwell's comment, I wrote a function which can return the number type based on the bytecode header. The function is useful, but it should never be used because it only works for a specific interpreter. It would need to be entirely rewritten for lua 5.2 or luajit, which creates unnecessary burdens for code reuse.

Instead, lua scripts should be written independent of the interpreter or number type used.

For completeness, here it is function:

-- only work in Lua 5.1
function numbertype()
  local headertypes = {
    ['\4\1'] = 'int32',
    ['\8\1'] = 'int64',
    ['\4\0'] = 'float32',
    ['\8\0'] = 'float64'}

  -- returns nil if the type is something else
  return headertypes[string.dump(function () end):sub(11,12)]
end