lua-users home
lua-l archive

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

Yes, this is legal. But you have one mistake.
At the first call of the key abc doesn’t exist, so __index metamethod is fired.
In that metamethod you created a field `k`. Literally. So now table has t[“k”] = {}, not t[“abc”] = {}.
To create a key from a value, use [] brackets instead of a dot. But still your code works because at the end you still return that t.k, not t[“k”].
At the line `return t.k` the key `k` exists and it returns it.
On 3 Oct 2022, 19:26 +0300, Enrico Colombini <>, wrote:
Hi, I've not used Lua for some time (due to bad health, workload and
other problems).

if I call where .abc does not exist,
create an subtable in the __index metamethod
and assign a __call metamethod to,
is the call guaranteed to work?

In detail (see attached code)
In restructuring an ancient program of mine, I'd like:

where 'abc' does not exist,
to have the effect of calling:

g("abc", ...)

I did my homework and found a solution (see attached simplified code).

Basically, I create the subtable in the __index metamethod for f
(nothing strange here) then, while still in the __index metamethod, I
attach to the newly created a metatable with a __call metamethod.

Note that all this happens in the middle of a pending call of a
non-existing 'function', which is akin to changing the engine of
a running car.

It seems to work fine (I tried it in Lua 5.4.0) confirming my impression
that Lua very often effortlessly does 'the right thing', but I'm not
entirely sure it is 'legal'.

So I have two questions:

1) Can I rely on it even in the future, on other platforms, etc.?
2) Is there a simpler way?