[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: This works... but is it guaranteed to?
- From: Viacheslav Usov <via.usov@...>
- Date: Mon, 3 Oct 2022 18:57:05 +0200
On Mon, Oct 3, 2022 at 6:26 PM Enrico Colombini <erix@erix.it> wrote:
> -----
> if I call f.abc() where .abc does not exist,
> create an f.abc subtable in the __index metamethod
> and assign a __call metamethod to f.abc,
> is the f.abc() call guaranteed to work?
Well, "guaranteed" is a big word. In any version of Lua that you have
tried and found this to work, yes, it is guaranteed. Everything else,
especially in the case of future versions of Lua, will be a
conjecture.
Given all I know about Lua 's metatables, the behaviour you observe is
regular and, I'd say, intended. It would seem strange to me if it were
radically changed.
Cheers,
V.
>
>
> In detail (see attached code)
> -----------------------------
> In restructuring an ancient program of mine, I'd like:
>
> f.abc(...)
>
> 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 f.abc subtable in the __index metamethod for f
> (nothing strange here) then, while still in the __index metamethod, I
> attach to the newly created f.abc a metatable with a __call metamethod.
>
> Note that all this happens in the middle of a pending call of a
> non-existing f.abc() '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?
>
> --
> Enrico