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:

  1. const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
  2. 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):

  1. const char *lua_getupvalue (lua_State *L, int funcindex, int n);
  2. 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:

  1. int listvars (lua_State *L, int level) {
  2. lua_Debug ar;
  3. int i;
  4. const char *name;
  5. if (lua_getstack(L, level, &ar) == 0)
  6. return 0; /* failure: no such level in the stack */
  7. i = 1;
  8. while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
  9. printf("local %d %s\n", i-1, name);
  10. lua_pop(L, 1); /* remove variable value */
  11. }
  12. lua_getinfo(L, "f", &ar); /* retrieves function */
  13. i = 1;
  14. while ((name = lua_getupvalue(L, -1, i++)) != NULL) {
  15. printf("upvalue %d %s\n", i-1, name);
  16. lua_pop(L, 1); /* remove upvalue value */
  17. }
  18. return 1;
  19. }