我怎么知道何时在Lua中将ANY变量设置为给定值? [英] How can I tell when ANY variable is set to a given value in Lua?

查看:304
本文介绍了我怎么知道何时在Lua中将ANY变量设置为给定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某个未知范围内的局部变量设置为256,我怎么知道它发生了?

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.

我可以访问debug API.

推荐答案

您可以在调试钩子内循环遍历当前作用域中的所有局部变量,并检查哪个变量具有所需的值:

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

这仅适用于局部变量.对于全局变量,您可以遍历_G_ENV表并比较值.

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).

还有两个其他选项可以跟踪变量的变化(有一些限制):(1)使用元方法和代理表,以及(2)

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

这篇关于我怎么知道何时在Lua中将ANY变量设置为给定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆