我试图弄清楚当我全局覆盖它时如何找到调用特定函数的脚本。例如:
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 的调试功能,但我不确定到底是什么。
最佳答案
试试这个:
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%准确的解决方案,但这应该会引导你找到正确的方法!
关于function - Lua 全局覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125435/