[ Lua C API ] lua_upvalueid - index > # upvalues?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

[ Lua C API ] lua_upvalueid - index > # upvalues?

JeanHeyd Meneide
Dear Lua List,

     The Manual for Lua (pretty consistently across versions) says that you are not supposed to call lua_upvalueid for upvalues that do not exist:

> Parameters funcindex and n are as in the function lua_getupvalue, but n cannot be greater than the number of upvalues

So... what happens if you do? Undefined behavior, essentially? I was semi-hoping to have a cheap way to check that there are at least N upvalues without pushing anything onto the stack, but lua_upvalueid's documentation does not make it clear that it would do something like return NULL reliably.

As the docs are written, I can't really rely on NULL getting passed back when I go too high. Is that intentional? Is NULL a valid upvalueid that can pop out of lua_upvalueid?

Sincerely,
Derp
Reply | Threaded
Open this post in threaded view
|

Re: [ Lua C API ] lua_upvalueid - index > # upvalues?

Viacheslav Usov
On Sat, Sep 26, 2020 at 3:23 PM JeanHeyd Meneide
<[hidden email]> wrote:

> So... what happens if you do?

Here is what the code does:

LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
  StkId fi = index2addr(L, fidx);
  switch (ttype(fi)) {
    case LUA_TLCL: {  /* lua closure */
      return *getupvalref(L, fidx, n, NULL);
    }
    case LUA_TCCL: {  /* C closure */
      CClosure *f = clCvalue(fi);
      api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
      return &f->upvalue[n - 1];
    }
    default: {
      api_check(L, 0, "closure expected");
      return NULL;
    }
  }
}

And here is another bit:

typedef struct CClosure {
  ClosureHeader;
  lua_CFunction f;
  TValue upvalue[1];  /* list of upvalues */
} CClosure;

If the implications are not obvious, you should just follow the manual :)

Cheers,
V.
Reply | Threaded
Open this post in threaded view
|

Re: [ Lua C API ] lua_upvalueid - index > # upvalues?

Luiz Henrique de Figueiredo
In reply to this post by JeanHeyd Meneide
>      The Manual for Lua (pretty consistently across versions) says that you are not supposed to call lua_upvalueid for upvalues that do not exist:
>
> So... what happens if you do? Undefined behavior, essentially?

Yes. The C API does not hold your hand. If you give it bad input, then
bad things may happen.