Lua Global Override

时间:2014-08-04 18:43:43

标签: function debugging lua override global

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

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

OR

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

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

1 个答案:

答案 0 :(得分:5)

试试这个:

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%的确切解决方案,但这应该引导你以正确的方式!