gpt4 book ai didi

lua - 如何检测 Lua 脚本何时访问全局变量?

转载 作者:行者123 更新时间:2023-12-02 08:33:32 25 4
gpt4 key购买 nike

我开始使用一个有点乱的 C++/Lua 代码库,当我在应用程序执行过程中转储 _G 的内容时,有有数百个变量,我确信它们只在某处初始化,但不再在代码中的其他任何地方使用。为了解决这个问题,我想设置一种机制,每当 Lua 访问全局变量时都会记录下来。

这是我关于如何实现这一目标的想法——我想设置一个代理 _G,它只会通过 __index__newindex 传递所有读写访问 连同它自己的原始 _G 副本。然而,这个简单的脚本不起作用,只输出:

C:\Programs\lua-5.1.5_Win32_bin\lua5.1: 错误处理错误

GProx = 
{
vars = _G
}

setmetatable(GProx, {

__index = function (t, name)

print("Read> " .. name)
return t.vars[name]

end,

__newindex = function (t, name, val)

print("Write> " .. name .. ' = ' .. val)
t.vars[name] = val

end

})

setfenv(0, GProx)

a = 1 --> Expected to print 'Write> a'
print(a) --> Expected to print 'Read> print', 'Read> a', and '1'

这是一个好的方法还是有更好的方法?
如果这是一个有效的思路,那么我的代码片段有什么问题?

最佳答案

试试这个代码段,它可以处理读取和写入:

do
-- Use local variables
local old_G, new_G = _G, {}

-- Copy values if you want to silence logging
-- about already set fields (eg. predeclared globals).
-- for k, v in pairs(old_G) do new_G[k] = v end

setmetatable(new_G, {
__index = function (t, key)
print("Read> " .. tostring(key))
return old_G[key]
end,

__newindex = function (t, key, val)
print("Write> " .. tostring(key) .. ' = ' .. tostring(val))
old_G[key] = val
end,
})

-- Set it at level 1 (top-level function)
setfenv(1, new_G)
end

以下是更改的概要:

  • block 用于对旧_G 进行本地引用。在您提议的实现中,如果设置了名为 vars 的全局变量,它将覆盖 GProx.vars 并破坏代理。
  • keyval 应该在打印之前经过 tostring,因为大多数值(即表)不会隐式转换为字符串。
  • 将环境设置在 1 级别通常就足够了,不会干扰 Lua 的内部工作。

关于lua - 如何检测 Lua 脚本何时访问全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24284646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com