Lua get number type
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.
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.
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
.
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.
链接地址: http://www.djcxy.com/p/85584.html上一篇: 浮点数大于精度时称为什么?
下一篇: Lua获得号码类型