lua-users home
lua-l archive

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


As far as I know, it’s not possible to add(create) a new upvalue for a lua function already been compiled.

If you check the source code, you would find that the size of the upvalues list in Closure (the c struct of a lua/c function) is determined (and fixed) when the function is loaded.

Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e) {
Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems)));
luaC_link(L, obj2gco(c), LUA_TFUNCTION);
c->l.isC = 0;
c->l.env = e;
c->l.nupvalues = cast_byte(nelems);
while (nelems--) c->l.upvals[nelems] = NULL;
return c;
}

#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \
cast(int, sizeof(TValue *)*((n)-1)))

As you can see in the above code (Lua5.1 as an example), the size of a Closure is fixed according to the nelems parameter, which is the number of upvalues.
So for the question you asked:


> 2. Is there any way to create a new upvalue from C side on the caller using C api?
No. You can only modify(or maybe delete) an existing upvalue.

> 3. In case (1) and (2) are impossible, is it due to some security or limitation on generated bytecode of the function once it is interpreted by Lua?
I am not sure. There are many way to turn the upvalue list to a dynamic list. Maybe someone could answer this question?