skwerlman
skwerlman

Reputation: 143

How can I tell when ANY variable is set to a given value in Lua?

If a local variable in some unknown scope gets set to 256, how can I know that it happened?

I'd like to be able to look for one value at a time, assuming that's possible.

I have access to the debug API.

Upvotes: 2

Views: 476

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

You can loop over all local variables at the current scope inside debug hook and check which one has the value you need:

do
  local seen = {}
  debug.sethook(function(ev, line)
      local level = 2
      local target = 256
      local i = 1
      while true do
        local name, value = debug.getlocal(level, i)
        if not name then break end
        if value == target and string.sub(name, 1, 1) ~= '(' and not seen[name] then
          print("at line", line, "variable", name, value)
          seen[name] = true
        elseif seen[name] and value ~= target then
          seen[name] = nil
        end
        i = i + 1
      end
    end, "l")
end

local a = 256
local b = 11
a = 13
a, b = 256, 256
print("done")

This prints the following for me:

at line 23  variable    a   256
at line 26  variable    a   256
at line 26  variable    b   256
done

This only applies to local variables. For global variables you can iterate over _G or _ENV tables and compare the values.

Note that the lines printed are the lines of the next statement and not the lines on which the change happens (as the hook stops before the line is executed).

There are two other options to track variable changes (with some limitations): (1) using metamethods and a proxy table, and (2) using a debugger.

Upvotes: 3

Related Questions