iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌕

Numeric Types in Lua

に公開
2022/12/21

Up to Lua 5.2

Until Lua 5.2, all numerical types in Lua were floating-point numbers (typically double-precision floating-point numbers).

For embedded environments, it was possible to customize it at compile time to use integer types.

In the case of double-precision floating-point numbers, integer values between -2^{53} and 2^{53} can be represented as a subset. In particular, it can represent signed 32-bit integers [-2^{31},2^{31}-1] and unsigned 32-bit integers [0,2^{32}-1].

This is the same as traditional JavaScript.

If you want to wrap-around 32-bit integer operations, for addition and subtraction you can do the following:

function add32(x, y)
  return (x + y) % 0x100000000
end
function sub32(x, y)
  return (x - y) % 0x100000000
end

Multiplication requires some ingenuity, such as splitting the high and low bits. Integer division can be done as follows:

function div32(x, y)
  return math.floor(x / y)
end
function quot32(x, y)
  return (math.modf(x / y))
end

bit32 in Lua 5.2

It accepts integers in the range of (-2^{51},2^{51}) (open interval) as input and uses the remainder divided by 2^{32} for bitwise operations. Results are returned as unsigned integers in the interval [0,2^{32}-1].

  • bit32.arshift(x, disp)
    • Arithmetic right shift
    • If the shift amount disp is negative, a left shift is performed.
    • If the absolute value of the shift amount is greater than 31, the result is 0 or 0xFFFFFFFF.
  • bit32.band(...)
  • bit32.bnot(x)
  • bit32.bor(...)
  • bit32.btest(...)
    • Something like bit32.band(...) ~= 0.
  • bit32.bxor(...)
  • bit32.extract(n, field [, width])
  • bit32.replace(n, v, field [, width])
  • bit32.lrotate(x, disp)
  • bit32.lshift(x, disp)
    • Left shift
    • If the shift amount disp is negative, a right shift is performed.
    • If the absolute value of the shift amount is greater than 31, the result is 0.
  • bit32.rrotate(x, disp)
  • bit32.rshift(x, disp)
    • Logical right shift
    • If the shift amount disp is negative, a left shift is performed.
    • If the absolute value of the shift amount is greater than 31, the result is 0.

Lua 5.3/5.4

Please refer to the link above.

Regarding bitwise operations, there is no operator for arithmetic right shift. You will likely use x // (1 << n) instead.

LuaJIT

LuaJIT is basically compatible with Lua 5.1, but it includes some unique extensions.

Bitwise Operations

For bitwise operations, a library called Lua BitOp is built-in, which is unrelated to Lua 5.2's bit32. Note that Lua BitOp was released earlier than Lua 5.2.

Lua BitOp also considers environments where the numerical type is a signed 32-bit integer. Therefore, even if unsigned 32-bit integers are used internally for each operation, the return value is a signed 32-bit integer.

If the Lua numerical type is a double-precision floating-point number, inputs in the range of \pm 2^{51} are allowed. The input is converted to an integer using an implementation-dependent rounding method, and the lower 32 bits are used.

List of functions:

  • bit.tobit(x)
    • Normalizes the given number to a signed 32-bit integer.
  • bit.tohex(x [, n])
    • Converts the given number to a hexadecimal string with the specified number of digits (absolute value of n).
    • If n is positive, lowercase letters are used; if negative, uppercase letters are used.
    • The absolute value of n must be between 1 and 8. If the argument cannot be converted to a string with the specified number of digits, only the lower |n| digits are returned.
  • bit.bnot(x)
  • bit.band(x1 [, x2...])
  • bit.bor(x1 [, x2...])
  • bit.bxor(x1 [, x2...])
  • bit.lshift(x, n)
    • Logical left shift
    • Only the lower 5 bits of n are used.
  • bit.rshift(x, n)
    • Logical right shift
    • Only the lower 5 bits of n are used.
  • bit.arshift(x, n)
    • Arithmetic right shift
    • Only the lower 5 bits of n are used.
  • bit.rol(x, n)
    • Only the lower 5 bits of n are used.
  • bit.ror(x, n)
    • Only the lower 5 bits of n are used.
  • bit.bswap

In the case of LuaJIT 2.1, it seems that the 64-bit integers described later can also be handled by Lua BitOp. In that case, tobit returns the lower 32 bits as a signed 32-bit integer, and shift operations use the lower 6 bits. If multiple types are mixed and passed to band etc., the priority seems to be uint64_t, int64_t, and then signed 32-bit integers.

Compared to Lua 5.2's bit32, the range of the return value ([0,2^{32}-1] unsigned vs. [-2^{31},2^{31}-1] signed) and the behavior when the shift amount is out of range are different.

64-bit Integers

LuaJIT's FFI library can handle (boxed) 64-bit integers.

The constructors uint64_t and int64_t can be obtained as follows:

local ffi = require("ffi")
local uint64_t = ffi.typeof("uint64_t")
local int64_t = ffi.typeof("int64_t")
print(uint64_t(1)) --> 1ULL
print(int64_t(1)) --> 1LL

When converted to a string, the suffixes ULL and LL are appended. Also, literals using these suffixes can be written in the source code (Parser Extensions).

Ordinary arithmetic operations (+, -, *, /, %, ^, unary minus) and Lua BitOp operations can be used on 64-bit integers. If argument types are mixed, the priority is uint64_t, int64_t, and then regular floating-point numbers. That is, if either operand is uint64_t, the other is converted to uint64_t before the operation is performed.

Comparison can be done using the standard comparison operators like <. If one side is uint64_t, the other is converted to uint64_t before comparison.

tonumber can be used to convert a 64-bit integer to a regular floating-point number.

[Addendum] I wrote a detailed article:

dual number mode and Negative Zero

LuaJIT uses dual number mode on some architectures (including AArch64). This mode internally represents values that can be expressed as signed 32-bit integers using the 32-bit integer type.

In dual number mode, unary minus and multiplication may not account for the IEEE 754 "negative zero".

You can work around this by using 0 / (-1) - x instead of unary minus, or by using code like the following for multiplication:

function float_mul(x, y)
  local z = x * y
  if z == 0 then
    if x < 0 then
      return 0 / (-1) * y
    elseif y < 0 then
      return 0 / (-1) * x
    end
  end
  return z
end

Bonus: Emulating 32-bit Floating-point Numbers

If a function exists to cast double-precision floating-point numbers to single-precision, similar to Math.fround in JavaScript, you can emulate single-precision floating-point operations.

In Lua 5.3 and later, you can cast to a single-precision floating-point number using string.pack:

function to_f32(x)
  return (string.unpack("f", string.pack("f", x)))
end
print(to_f32(3.14)) --> 3.1400001049042

In LuaJIT, you can cast to a single-precision floating-point number using ffi.typeof "float":

local ffi = require "ffi"
local float = ffi.typeof "float"
function to_f32(x)
  return tonumber(float(x))
end
print(to_f32(3.14)) --> 3.1400001049042

Discussion