lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Jul 21, 2022 at 9:05 PM Gé Weijers wrote:
local N <const> = 0x1 << 30

local index_count = 0

local meta = {
    __index = function(meta, key)
        index_count = index_count + 1
        if index_count <= N then
            return "a"
        else
            return "bb"
        end
    end,
}

local t = setmetatable({}, meta)

print(table.concat(t, "", 1, N))


Never do this in a production code.  Part 2.
Again, you're relying on unspecified behavior here.
Why do you think table.concat must read each table element only once?
The Lua manual never promised that.

When evaluating an _expression_, Lua does not guarantee the number of times each term is extracted.
Simple example: how many times the field "a" is read while evaluating the following _expression_?
local b = t.a - t.a
The correct answer: it depends on the current implementation.
BTW, if "t.a" is implemented with a metamethod and is extracted twice,
Lua promises nothing about whether the first invocation returns minuend or subtrahend,
so the arithmetic result is not predictable.
Your favorite tricks with non-constant table elements are actually not well supported by Lua.

I have started this thread with a description of a real problem every programmer may stumble upon:
when your Lua script utilizes a better part of your RAM
some goals are achievable with the concatenation operator but not with table.concat.
Why do you reply to me with a contrived code that does not solve any problem?
I can't imagine what your code might be useful for in practice.