take – Conceptual question regarding an integer in Lua

Question:

Hello.

I am learning the Lua language. I am trying to understand the cocentual moment: the language has only three atomic data types: 1. boolean 2. Number 3. String

As for Number, digging into the config file https://www.lua.org/source/5.1/luaconf.h.html

there is the following definition:

#define LUA_NUMBER      double

There is no int type, but there is a built-in interpreter:

LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
  TValue n;
  const TValue *o = index2adr(L, idx);
  if (tonumber(o, &n)) {
    lua_Integer res;
    lua_Number num = nvalue(o);
    lua_number2integer(res, num);
    return res;
  }
  else
    return 0;
}

Can anyone argue for and against such a conceptual structure of the language and its atomic data types?

How does this help, how does it complicate the whole work?

Answer:

This rationale is given by Robert Jeruzalimsky in his book Programming in Lua:

Some fear that even simple operations such as increment and comparison may not work correctly with floating point numbers. However, in reality this is not the case. Almost all platforms now support the IEEE 754 floating point standard. According to this standard, the only possible source of error is when the number cannot be accurately represented. An operation rounds its result only if the result cannot be accurately represented as the corresponding floating point value. Any operation whose result can be accurately represented will have a precise meaning.

In fact, any integer up to 2 ^ 53 (approximately 10 ^ 16) is exactly represented as a double-precision floating-point number (double). When you use a double-precision floating-point value to represent integers, there are no rounding errors unless the modulus is greater than 2 ^ 53. In particular, Lua is capable of representing any 32-bit integer values ​​without rounding problems. Of course, fractional numbers will have rounding problems.

Before we continue, remember that integers are accurate and therefore don't have rounding errors. Most modern CPUs perform floating point operations just as fast (or even faster) than integers.

Scroll to Top