Numbers¶
In the interpreter, every value is a Lua value. A number carries its type with it, and every +
checks that type first. When the compiler can prove that a local only ever holds numbers, it keeps
that local in a machine register or in plain memory, and + becomes a single machine instruction.
Numeric Locals¶
A local that's only ever given numbers is a native number.
local total = 0;
for i = 1, 1000 do
total = total + i * 2.5; -- native multiply and add, no Lua values involved
end
Debug.Print(total); -- only here does total become a Lua value again
A number only becomes a Lua value again where Lua needs one: as an argument of a call, when it's stored in a table, concatenated, or returned.
What counts as "only ever numbers" are number literals, the variable of a numeric for, other
numeric locals, arithmetic on those, and the values of Values Known to Be
Numbers below. A local isn't a native number when:
- it's ever given something else, such as a string, a table, a global or a table field (but see Dynamic Locals below).
A captured local that never changes is still a native number. The functions that use it read it as a native number once, when they start.
local function solve(n)
local function place(row)
if row > n then return; end -- n is native in place too
end
end
Counters in Closures¶
A local that a function defined inside changes is shared by both. When it's only ever given numbers, it lives in a small native cell that the function and its closures share, and reading or changing it is a single memory access.
local clicks = 0;
local function OnClick()
clicks = clicks + 1; -- native: no table, no call into Lua
end
A counter like this has to start with a value (local clicks = 0;, not local clicks;), and no
function that sees it may call itself by name: there, every level of recursion would pay for the
cell.
Lua 5.3: Integers and Floats¶
Lua 5.3 has two kinds of numbers, integers and floats, and the difference shows: 1 prints as 1
and 1.0 as 1.0. Native numbers keep the kind exactly as the interpreter would.
local count = 0; -- always an integer: one native integer
local sum = 0.0; -- always a float: one native float
for i = 1, 10 do
count = count + 1;
sum = sum + i / 2; -- / always gives a float
end
A local that holds both kinds, such as the common local x = 0 followed by float arithmetic, is
still native. It carries a small tag that says which kind it holds right now, and each operation
picks integer or float arithmetic by that tag.
In a loop, the tag is usually only interesting in the first round. The first round runs a copy of the loop, and when every round leaves the local with the same kind, the rest of the loop knows that kind and checks nothing.
local sum = 0; -- an integer before the loop
for i = 1, 1000 do
sum = sum + i * 0.5; -- a float after the first round: no checks from round two on
end
Integer arithmetic wraps around exactly like it does in Lua 5.3, so math.maxinteger + 1 is
math.mininteger, natively too. // and % are native for both kinds: on integers as Lua 5.3
rounds them, on floats as the floor of the quotient.
Numeric For Loops¶
A numeric for with native numbers runs entirely natively: the counter, the limit and the step. In
Lua 5.3 it's an integer loop or a float loop, by the same rules as the interpreter.
for i = 1, #items do -- the loop itself costs no calls into Lua
ListBox.AddItem("Items", items[i], i);
end
Locals Declared Without a Value¶
local i, j starts both locals as nil. When every path through the function gives them a number
before they're read, that first nil is never seen, and they're native numbers like any other.
Values Known to Be Numbers¶
Some values are always numbers even though they aren't arithmetic. The compiler follows the type of
every local, not just whether it's a number: a local can be "a number or nil", "a string" or "a
table". From that it knows, for example, that x or 0 is a number when x is a number or nil.
local x;
if found then x = 5; end
local n = x or 0; -- a number: n is native
local step = (dir == "up") and 1 or -1; -- a comparison, then numbers: native too
local size = #text; -- text is always a string: native
Such a value is computed the ordinary way, and then read as a number without any check. Calls of
local functions that return a number or nil work the same way:
local function IndexOf(list, value)
for i = 1, #list do
if list[i] == value then return i; end
end
end
local at = IndexOf(names, "Bob") or 0; -- a number: at is native
This only works where the compiler sees every value a local is given. A global, a table field, a
method call or the call of a global function may be anything, so tonumber(s) or 0 stays an
ordinary value for now.
Checked for nil¶
A local that may be nil (or false) and is checked for it becomes a native number after the
check, when from there on it can only be a number:
local function Scale(value, factor)
if factor == nil then factor = 2; end -- from here on, factor is native
return value * factor;
end
Scale(10, 1.5);
Scale(10); -- factor is nil, then 2
local at;
for i = 1, #list do
if list[i] == wanted then at = i; break; end
end
if at == nil then return; end -- from here on, at is native
The check is an if without else, testing x == nil, x ~= nil, not x or x, whose body
gives the local a number or leaves (return, break). Before the check the local may only be
nil, false or numbers, so a parameter needs a function whose calls are all known, as for
Number Parameters. The local must be declared in the same block before the
check (or be a parameter, checked in the function's own body), must not be assigned again after
it, and must not be used by a function defined inside. A function with goto is left as it is.
Number Parameters¶
A parameter is a native number too, when the compiler can see every call of its function. That
means the function is a local function that's never assigned again, it's only ever called by its
name, and every call passes numbers.
local function lerp(a, b, t)
return a + (b - a) * t; -- a, b and t are native: every call passes numbers
end
for i = 0, 10 do
local x = lerp(0, 100, i / 10);
end
When a function like that also only computes with numbers and returns one number, it gets a fully
native version. Calling it passes native numbers and gets one back, without any Lua value in
between. This way, recursive functions such as the classic fib become native recursion:
local function fib(n)
if n < 2 then return n; end
return fib(n - 1) + fib(n - 2);
end
Debug.Print(fib(30));
A function that always returns one number but works with tables or other Lua values on the way still returns that number natively, when it's called by name the same way. Its arguments are passed as usual.
local function count(tree)
if tree[1] then return 1 + count(tree[1]) + count(tree[2]); end
return 1;
end
local total = count(root) * 2; -- the count comes back as a native number
Dynamic Locals¶
Values from tables, globals and calls can be anything, so the compiler can't prove that they're numbers. Inside loops it still tries: a local used in arithmetic or comparisons in a loop keeps its value natively whenever it happens to be a number, and as a Lua value otherwise.
An expression over such values checks each of them once. When they're all numbers it computes natively, and otherwise it runs the ordinary code, which does exactly what the interpreter does, metamethods and errors included.
local sum = 0;
for i = 1, #prices do
local p = prices[i]; -- could be anything
sum = sum + p * (1 + vat); -- checked once: native when p and vat are numbers
end
A parameter that the function never assigns gets the same treatment outside loops, when it's used in arithmetic or a comparison twice, or once with a number literal. It's checked once when the function starts. A function that calls itself by name keeps its parameters as Lua values, so deep recursion keeps its depth.
Account.Deposit = function(self, amount)
if amount > 1000 or amount <= 0 then return false; end -- amount checked once
self.balance = self.balance + amount;
return true;
end
Booleans¶
A local that only ever holds true, false, the result of a comparison, or not, and and or
of those, is a native flag.
Technical details
- Lua 5.1 numbers are doubles, computed with SSE2, which gives the same results as the hosts.
%is computed as Lua 5.1 does,a - floor(a / b) * b, and^calls the host's ownmath.pow, so even rounding matches. - Arithmetic on two numbers never calls a metamethod, in either Lua version, which is what
makes the native code safe. A string operand (
"10" + 1) always takes the ordinary path, so its conversion is the host's. - In Lua 5.3 an integer and a float compare exactly, as the interpreter does: natively when the integer is within ±2^53, through the host otherwise.
- In Lua 5.3, a fully native version of a function needs parameters and a result that each
have one kind: always integers, or always floats.
fibabove qualifies. So does a function that returns a native number with Lua arguments, such ascount, which may not take...or define functions inside. - Float
%in Lua 5.3 goes through the host, which computes it with the C library'sfmod. - Counters in closures and functions returning native numbers are one or the other in a script: a call of such a function could change a counter that the expression around it has already read.
- The same holds for values known to be numbers: in a script with counters in closures, such a value is only read as a number when computing it can't run any code (no call, no metamethod). And a value that reads a local which a function defined inside changes is never read early, since the interpreter reads that local after the rest of the expression.
- A value known to be a number is computed by the host, as the interpreter computes it, so
2 ^ 0.5still calls the host'spow, andx & 3with a floatxstill raises the interpreter's error whenxhas no integer value. - Dynamic locals are limited to loops on purpose: native variables live on the C stack, and every level of recursion pays for them.
- Numbers never keep anything alive: they aren't collected, so keeping them out of Lua has no effect on the garbage collector.