function - Lua 全局覆盖

标签 function debugging lua overriding global

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

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/

相关文章:

运行gprof后计算MIPS?

lua - 关于 Lua 5.3 字节码的文档

c - 如何在LuaJIT中打印固定的字符数组?

ios - 访问超出 Swift 范围的变量

javascript - JavaScript输出返回NaN

html - 缩小浏览器宽度时如何将图像保持在原位?

Lua:在字符串中查找十六进制值

求整数和的 Python 函数

function - Mapcat 是如何工作的?

c++ - 带有 “auto”或模板类型推导的功能: “no matching function for call to…”