Does it specifically need to call the Lua standard library print
function? Can you instead emulate the functionality of print
? Because that would be the easiest way.
However, if you want to have a wrapper around print
, there are two ways to do it: with pure Lua code, and with C/C++ code.
The pure Lua solution is as follows. Note that this should be done before loading any external scripts. First, open the Lua standard library that has print
in it. Then run this Lua script:
local internal_print = print
return function(...)
--Do display logic.
internal_print(...) --Or whatever else you want.
end
This will return the "display" function. You can store it in a global variable called display
if you like, or called something else.
After that, you can nil
out the print
global variable, thus making it almost entirely inaccessible.
If you want to do it from C/C++, it's very similar. First, as before, you register the Lua standard library that includes print
, so that you can get the function for it. Then, you use lua_getglobal(L, "print")
to get the print
function and push it onto the stack. Next, you register your C/C++ function using using lua_pushcclosure
. But you want to specify one upvalue, which Lua pops off the stack at registration time.
And now your registered function is on the stack, waiting to be pushed into a Lua variable or global table entry.
Warning: the Lua debug library can poke at upvalues and thus get the print
function from your new function. So if you want perfect security, get rid of debug.getupvalue
.