lua-users home
lua-l archive

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


On Mon, 3 Oct 2022 at 18:26, Enrico Colombini <> wrote:
> Hi, I've not used Lua for some time (due to bad health, workload and
> other problems).
> tl:dr
> -----
> 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", ...)

For me it is easier to reason about if you zap the syntactic sugar: => f["abc"](...)

As they have pointed to you, it works even if you do not store it, but
regenerate the closure everytime. In fact, you are always storing
["k"] which means it does not work right for f.k. If I append

f.k("But this code is buggy.")

I get:

abc    Lua    is very well designed
abc    But this code is buggy.

If you just want that effect you can ommit the intermediate stuff of
building a callable object and just return a closure capturing the key
( it will be slower if you call it in a loop ) ( sample stripped for
brevity )

function g(k, ...)   print(k, ...) end
f = {}
setmetatable(f, {
    __index = function(t, k)
                  return function(...) g(k, ...) end
    })"Lua", "is very well designed")
f.k("No longer buggy now.")

You can rely on it until lua changes its working, which it does for
other things, but has not done in a way for fundamental things as
this. And I suppose you'll get ample warning on this case.

Francisco Olarte.