Nima
Nima

Reputation: 43

Lua Global Override

I'm trying to figure out how to find the script that's calling a specific function when I globally override it. For example:

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

How do I figure out which script is calling print()? I know I'm supposed to use the debug features of lua, but I'm not sure exactly what.

Upvotes: 2

Views: 4305

Answers (1)

Mijago
Mijago

Reputation: 1639

Try this:

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');

Result:

> dofile "test2.lua"
Print called by: test.lua
a       b
Print called by: test.lua
x       c
Print called by: test2.lua
a

I tested it with Lua 52, but i know that it also works with Lua50-3, so it should also work with Lua51.

Short summary:

local calling_script = debug.getinfo(2).short_src

It gives ALWAYS back the script where the function which calls the print has been defined. So be careful.. I don't exactly know what you want to do with this, so i can't give you an 100% exact solution, but this should lead you to the correct way!

Upvotes: 6

Related Questions