【问题标题】:Lua Global OverrideLua 全局覆盖
【发布时间】:2014-09-27 07:48:46
【问题描述】:

我试图弄清楚当我全局覆盖它时如何找到调用特定函数的脚本。例如:

rawset(_G, 'print',
function()
    --check if xxx program is calling, then print a different way
end)

_G.print = 
fucntion()
    --check if xxx program is calling, then print a different way
end

我如何确定哪个脚本正在调用 print()? 我知道我应该使用 lua 的调试功能,但我不确定具体是什么。

【问题讨论】:

  • 应该指出,您可能无法在此处实际执行您想要的操作,因为您可能没有想要检查调用函数的信息(如名称) .
  • Etan,所以我没有办法做到这一点吗?我尝试了 debug.getinfo,似乎我无法获取有关调用该函数的文件的信息。
  • 您是否控制调用 print 的脚本的加载?如果你这样做了,你可以尝试改变它的环境。

标签: function debugging lua overriding global


【解决方案1】:

试试这个:

old_print = print
print = function(...) 
    local calling_script = debug.getinfo(2).short_src
    old_print('Print called by: '..calling_script)
    old_print(...)
end
print('a','b')
print('x','c');

结果:

> dofile "test2.lua"
Print called by: test.lua
a       b
Print called by: test.lua
x       c
Print called by: test2.lua
a

我用 Lua 52 测试过,但我知道它也适用于 Lua50-3,所以它也应该适用于 Lua51。

简短的总结:

local calling_script = debug.getinfo(2).short_src

它总是返回已定义调用打印的函数的脚本。所以要小心.. 我不完全知道你想用这个做什么,所以我不能给你一个 100% 准确的解决方案,但这应该会引导你找到正确的方法!

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 2019-07-14
    • 1970-01-01
    • 2020-07-28
    • 2015-04-23
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多