4.2 – Manipulating Local Variables and Upvalues
For the manipulation of local variables and upvalues, the debug interface uses indices: The first parameter or local variable has index 1, and so on, until the last active local variable. Upvalues have no particular order, as they are active through the whole function.
The following functions allow the manipulation of the local variables of a given activation record:
- const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
- const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
The parameter ar
must be a valid activation record that was filled by a previous call to lua_getstack
or given as argument to a hook (see 4.3). lua_getlocal
gets the index n
of a local variable, pushes the variable’s value onto the stack, and returns its name. lua_setlocal
assigns the value at the top of the stack to the variable and returns its name. Both functions return NULL
when the index is greater than the number of active local variables.
The following functions allow the manipulation of the upvalues of a given function (unlike local variables, the upvalues of a function are accessible even when the function is not active):
- const char *lua_getupvalue (lua_State *L, int funcindex, int n);
- const char *lua_setupvalue (lua_State *L, int funcindex, int n);
These functions operate both on Lua functions and on C functions. (For Lua functions, upvalues are the external local variables that the function uses, and that consequently are included in its closure.) funcindex
points to a function in the stack. lua_getupvalue
gets the index n
of an upvalue, pushes the upvalue’s value onto the stack, and returns its name. lua_setupvalue
assigns the value at the top of the stack to the upvalue and returns its name. Both functions return NULL
when the index is greater than the number of upvalues. For C functions, these functions use the empty string ""
as a name for all upvalues.
As an example, the following function lists the names of all local variables and upvalues for a function at a given level of the stack:
- int listvars (lua_State *L, int level) {
- lua_Debug ar;
- int i;
- const char *name;
- if (lua_getstack(L, level, &ar) == 0)
- return 0; /* failure: no such level in the stack */
- i = 1;
- while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
- printf("local %d %s\n", i-1, name);
- lua_pop(L, 1); /* remove variable value */
- }
- lua_getinfo(L, "f", &ar); /* retrieves function */
- i = 1;
- while ((name = lua_getupvalue(L, -1, i++)) != NULL) {
- printf("upvalue %d %s\n", i-1, name);
- lua_pop(L, 1); /* remove upvalue value */
- }
- return 1;
- }