lua-users home
lua-l archive

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


> I hope this message finds you well. I was studying the Lua source code and
> came across a condition in the luaH_getint function, which I found
> intriguing. The code snippet in question is as follows:
> ```c
> else if (!limitequalsasize(t) && (l_castS2U(key) == t->alimit + 1 ||
> l_castS2U(key) - 1u < luaH_realasize(t))) {
>     /* key still may be in the array part? */
>     t->alimit = cast_uint(key); /* probably '#t' is here now */
>     return &t->array[key - 1];
> }
> ```
> In this code, I am wondering about the necessity of the `l_castS2U(key) ==
> t->alimit + 1` condition.
> It seems to me that if `l_castS2U(key) - 1u < luaH_realasize(t)` is `true`,
> then the `l_castS2U(key) == t->alimit + 1` condition is irrelevant.
> Conversely, if `l_castS2U(key) - 1u < luaH_realasize(t)` is `false`, then
> `l_castS2U(key) == t->alimit + 1` will never be true. As such, I believe
> that the condition `l_castS2U(key) == t->alimit + 1` might be redundant.

This test is redundant. It is there because 'luaH_realasize' can be
a little expensive to compute, so the redundancy avoids that call
in a quite common case. The comment explains that:

** [...]  In
** this case, try to avoid a call to 'luaH_realasize' when key is just
** one more than the limit (so that it can be incremented without
** changing the real size of the array).

-- Roberto