Lua Global Override

Nim*_*ima 2 debugging lua overriding global function

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

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

要么

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

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

Mij*_*ago 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');
Run Code Online (Sandbox Code Playgroud)

结果:

> dofile "test2.lua"
Print called by: test.lua
a       b
Print called by: test.lua
x       c
Print called by: test2.lua
a
Run Code Online (Sandbox Code Playgroud)

我用Lua 52测试了它,但我知道它也适用于Lua50-3,所以它也适用于Lua51.

简短的摘要:

local calling_script = debug.getinfo(2).short_src
Run Code Online (Sandbox Code Playgroud)

它使ALWAYS返回脚本,其中定义了调用print的函数.所以要小心..我不知道你想用它做什么,所以我不能给你一个100%的确切解决方案,但这应该引导你以正确的方式!