How I can overwrite built-in function, like print() globally?

Hello, devs. I want to make custom output window. But, after some progress, I realized that I can’t get source of script. So, I’m now trying to find a way to either overwrite built-in functions globally (like print), or find way to get script source.

The only way to find script source I found can cover only 1/3 of my needs, and it’s ScriptContext.Error, which works well only for error function, and not for warn and print.

1 Like

there isn’t really a way to overwrite a global function (sadly)
the best you can do is either making a module with your function or just putting it at the top of your script

local old = print
local print = function(...)
    warn("Called print", ...)
    old(...)
end
1 Like

There’s comes my main problem - I need such things for plugin, which should act as output for every script. So, putting this thing in every script won’t be comfortable for people.

Here’s something quick little bootleg fix I made that might help

local Gloabls = [[
local function print(...)
    warn(debug.info(2, "n"), "|", ...)
end
]]

local ScriptEditor = game:GetService("ScriptEditorService")

local function initscript(Script)
    Script = Script:GetScript()
    if Script and not Script:GetAttribute("AddedGlobals") then
        Script:SetAttribute("AddedGlobals", true)
        ScriptEditor:UpdateSourceAsync(Script, function(CurrentSource : string)
            return `{Gloabls}\n{CurrentSource}`
        end)
    end
end

ScriptEditor.TextDocumentDidOpen:Connect(initscript)

for i,v in ScriptEditor:GetScriptDocuments() do
    initscript(v)
end

you can initialize it in command bar if you really want to

1 Like

But this solution won’t cover scripts like CoreScript and Plugin ones. (CoreScripts can send messages sometimes)

I don’t think you can overwrite global functions.

What you CAN do is make use of LogService!

I’m already using it to get content of message. But, I need get LINE and SCRIPT which printed message, and I can’t find any way to get them.

IIRC, the following library might be useful for this:

I tried to use this aswell. It gives info about where Message exists. So, if I use debug.traceback or debug.info on Message which I got from LogService.MessageOut, it will return me info about where I called debug.traceback:


(I use \Skip to “break” infinite print loops)