Lua全局覆盖

我正在努力找出如何在全局覆盖函数时找到调用特定函数的脚本。例如:

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的调试功能,但我不确定具体是什么。

点赞
用户3909575
用户3909575

尝试这个:

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

它总是返回调用print的函数所在的脚本。因此要小心...我不确定您想要做什么,因此我无法给您100%精确的解决方案,但这应该可以引导您走向正确的方向!

2014-08-05 09:11:35