Skip to content

Tables

Tables are where Lua code spends much of its time, and every access can run a metamethod (__index, __newindex). Compiled code always honours metamethods, so the optimizations on this page make the access itself cheaper instead.

Fixed Keys

t.name, t["name"] and, in Lua 5.3, t[1] look up their key directly, without first putting the key on Lua's stack.

local settings = LoadSettings();
local w = settings.width;      -- a direct field lookup
local h = settings["height"];  -- the same

Number Keys

t[i] with a number i passes the number straight to the lookup. In Lua 5.3, an integer key is a single call into the host.

for i = 1, #list do
    total = total + list[i];
end

Known Tables

A local made with a table constructor and never assigned again is known to be a table, so its accesses skip the "is this a table?" check.

local point = { x = 0, y = 0 };
point.x = 10;                  -- no check needed: point is always a table

The same goes for a local given the result of a local function that only ever returns table constructors, when that function is only called by its name and never assigned again.

local function NewItem(name)
    return { name = name, count = 0 };
end

local item = NewItem("apple");
item.count = item.count + 1;   -- no check needed: item is always a table

A local that holds a table some of the time, and is used in a loop or in several places, remembers whether it's a table right now. It asks once after each assignment, instead of on every access.

Lengths

#t of a known table is a single call into the host. In Lua 5.1 it's even a native number, so a loop like for i = 1, #t do runs entirely natively.

Appending, t[#t + 1] = value;, reads the length once and stores at the next position directly. In Lua 5.3 the new position is a native integer whenever the length is one.

local lines = {};
for i = 1, n do
    lines[#lines + 1] = string.format("%d: %s", i, names[i]);   -- stored where the call left it
end

A value that's the result of a call (t.name = f(x);, t[i] = f(x);, total = f(x);) is stored right from where the call left it.

Chains in Lua 5.3

a.b.c checks each step once, by the type the previous lookup returned, instead of asking again.

local scale = Config.display.scale;

pairs and ipairs

A generic for over pairs(t) or ipairs(t) runs the host's own table walk directly, instead of calling the iterator function each round.

for key, value in pairs(options) do      -- no function call per round
    Debug.Print(key .. " = " .. tostring(value) .. "\r\n");
end

This is decided once per loop. When the iterator isn't the host's own, for instance because a table has a __pairs or __ipairs metamethod (Lua 5.3) or pairs was replaced, the loop calls it as usual. A Lua 5.3 ipairs loop still reads each element with its __index metamethod, as ipairs does there.

Fields Read Again

When a local table has no metatable, a field you just wrote or read keeps its number in native code. Reading the field again in arithmetic or a comparison takes that number, without asking the host, as long as nothing in between can change the table: no call, no access to another table that could run a metamethod.

for i = 1, #points do
    local p = points[i];
    p.x = p.x + 1;              -- p.x is read and written, and kept
    sum = sum + p.x - p.y;      -- p.x comes from native code, p.y from the table
end

Every store still goes to the table, in the same order. A table with a metatable gets the usual lookups, so its __index and __newindex run exactly as often as before.

Native Arrays

A table that nothing but its own function ever sees doesn't need to be a Lua table at all. When a local is made with {}, never assigned again, never passed anywhere, and only ever stored into with number keys, its elements live in native memory. Reading and writing them then involves no Lua at all.

local function primes(n)
    local sieve = {};                    -- a native array
    for i = 2, n do sieve[i] = true; end
    for i = 2, n do
        if sieve[i] then
            for j = i * i, n, i do sieve[j] = false; end
        end
    end
    local count = 0;
    for i = 2, n do
        if sieve[i] then count = count + 1; end
    end
    return count;
end

Elements may be nil, true, false or numbers. When the code stores anything else, or uses a key that isn't a reasonable integer, the array turns into a real table with the same contents, on the spot, and carries on as a table. Your code can't tell the difference. A store may take any value, such as a call's result: it's checked when it's stored.

A table of constants works the same way, when its constructor holds only numbers, booleans and nil, without names:

local K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5 };   -- a native array, filled at once

Reads may use any key: a number names an element, and anything else, such as a string or nil, finds nil, as it would in the table. A key computed from values read at run time is computed natively when they're numbers:

for i = 1, #data do
    local byte = data:byte(i);
    crc = crc_table[(crc ~ byte) & 0xFF] ~ (crc >> 8);   -- crc_table is a native array
end

A table isn't a native array when you pass it to a function, return it, store it in another table, take its length with #, iterate over it with pairs or give it a metatable.

Nested functions may use it too, under the same rules: they only index it, with numbers. The function and its nested functions then share the one array, which also stays alive as long as a nested function does.

local function queens(n)
    local columns, up, down = {}, {}, {};   -- native arrays, shared with place
    local solutions = 0;
    local function place(row)
        if row > n then
            solutions = solutions + 1;
            return;
        end
        for col = 1, n do
            local u, d = row + col, row - col + n;
            if not columns[col] and not up[u] and not down[d] then
                columns[col], up[u], down[d] = true, true, true;
                place(row + 1);
                columns[col], up[u], down[d] = false, false, false;
            end
        end
    end
    place(1);
    return solutions;
end

Native Records

A table made with named fields, { x = 1, y = 2 }, that only your compiled code ever looks into doesn't need to be a Lua table either. When every use of it reads or writes a field by its name, it is a record in native memory, and a field access involves no Lua at all.

local function body(x, y, mass)
    return { x = x, y = y, vx = 0, vy = 0, mass = mass };
end

local bodies = { body(0, 0, 10), body(5, 1, 1), body(-3, 2, 2) };   -- an array of records

local function advance(dt)
    for i = 1, #bodies do
        local b = bodies[i];               -- no call into the host
        b.x = b.x + dt * b.vx;             -- native loads and stores
        b.y = b.y + dt * b.vy;
    end
end

The tables a function like body returns qualify too, and so does a list of them made with a table constructor (bodies above) that is never assigned again. Your nested functions may index that list and measure it with #, but never store into it.

Records are all or nothing: when one table could reach code that sees it as a table, every table it could meet stays a table. That happens when you pass it to a function (also print, pairs or setmetatable), return it from the chunk, compare it, test it in a condition, store it in another table or a global, call a method on it, or use it in a nested function.

Technical details
  • Fixed keys use lua_getfield and lua_setfield, which run exactly the same lookup as the interpreter, metamethods included. Lua 5.3 integer keys use lua_geti and lua_seti.
  • A known table's metatable can still change with setmetatable, so lookups on it still go through the host. Only the type check is skipped.
  • Lua 5.1 never calls a metamethod for # of a table, so lua_objlen gives the length directly. Lua 5.3 honours __len, so its length is lua_len.
  • The module records the host's next (and in Lua 5.1 the ipairs iterator) when it's loaded. A loop whose iterator is one of those, with a table as its state, walks the table itself.
  • Lua 5.3's ipairs iterator can only be found by calling ipairs, so the module records ipairs itself. A loop over ipairs(t) checks that the function it calls is that one, that t is a table and that t has no __ipairs; then ipairs isn't called at all, and each round is lua_geti, as the host's iterator does it.
  • For a field read again, the table is checked with lua_getmetatable once. Every operation that may run Lua code or change a table (a call, a lookup in another table, a store elsewhere) forgets the kept numbers, so a number taken from native code is always the one in the table. Only locals that are never assigned again qualify, and only numbers are kept.
  • A native array is a userdata in the local's slot, 16 bytes per element. It's collected like any other value, also when an error unwinds the function. Only collectgarbage("count") can see the difference in memory use.
  • An array that nested functions use is reached through a small userdata that the function and its nested functions all hold. Each of them looks at it before every use of the array, since a call in between may have grown it or turned it into a table.
  • Keys that are nil or NaN raise the interpreter's errors, with the line.
  • A record is a userdata of 16 bytes per field. nil, booleans and numbers are stored in it; any other value is kept alive in a table that belongs to the record, and is let go when the field is overwritten. The analysis covers the whole script at once, since records go from function to function.
  • A list of records is a userdata of pointers. It keeps its records alive, and since it never changes, # is the number of items. A local read from it holds only the pointer.
  • Reading a record that is nil (an index past the end of a list, for instance) raises the interpreter's attempt to index error, with the line.