How to Edit Script code with Plugin

Hello, I am trying to read & edit Client, Server & Module code with a plugin.
In this current example I’m trying to find the word Banana and change it
with Apple. It does print, but it does not change.

local ScriptEditorService = game:GetService("ScriptEditorService")
local Selection = game:GetService("Selection")

local function replaceBananaWithApple(Script)
	local source = Script.Source
	local modifiedSource = source:gsub("Banana", "Apple")


	if source ~= modifiedSource then
		Script.Source = modifiedSource
		print("Replaced 'Banana' with 'Apple' in script:", Script:GetFullName())
	end
end


local function onScriptChanged(Script)
	if Script:IsA("LuaSourceContainer") then
		replaceBananaWithApple(Script)
	end
end


ScriptEditorService.TextDocumentDidChange:Connect(function(doc)
	local Script = doc:GetScript()
	if Script then
		replaceBananaWithApple(Script)
	end
end)

I’ve seen that it is possible, here are some sources.
But I cannot get it to work.

I’ve seen that it should be possible:

1 Like

I’ve gotten it to work, but can I make it work live?

1 Like

Yes, it can work live, but with one exception…

When you use a Plugin that modifies or peeks at your code, (Haven’t checked that yet…) it must require you, the user to accept that you know what this Plugin does, and if you’re okay with it.

1 Like

Yes yes yes, how do I do that I am so confused?

1 Like

When you mean work live do you mean publishing the plugin for everyone to use or updating it?

1 Like

so as soon as someone has written Banana, the person editing can see it changing to Apple.

That already applies when you’re using ScriptEditorService.

Yeah well it doesn’t update until the script is Inactive.

@kexy123 sort of already gave you the answer. You need to be using ScriptEditorService, not Script.Source.

ScriptEditorService:UpdateSourceAsync