debug.getupvalue

Gets an upvalue from a function by index.

Syntax

debug.getupvalue(func: function | number, index: number) -> any

Parameters

ParameterTypeDescription
funcfunction or numberThe function or stack level
indexnumberThe upvalue index (1-based)

Returns

TypeDescription
anyThe upvalue at the specified index

Description

debug.getupvalue retrieves an upvalue (captured variable from an outer scope) from a function. Upvalues are variables that a closure "closes over" from its enclosing environment.

Example

local counter = 0
local prefix = "Count: "

local function increment()
    counter = counter + 1
    return prefix .. counter
end

-- Upvalue order is compiler-dependent
for index in ipairs(debug.getupvalues(increment)) do
    print(index, debug.getupvalue(increment, index))
end

-- After calling the function
increment()

Use Cases

  • Inspect closures: See what variables a function has captured
  • Debugging: Examine the state of captured variables
  • Modification: Read before modifying with setupvalue