Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is there a way to change the code inside a script with another script?

I have an idea for a short game, and in the game, certain players would get access to this console where they can write out a command and when they press enter it creates a new script instance, executes the command, then destroys the script. I know how to do everything except changing the code in the script. Thank you for taking the time to read this all.

2 comments

0

You can use loadstring, just make sure to use it carefully.

0

Do be wary of malicious scripts that get into infinite loops; they could waste processing time and/or memory -- even with no access to coroutines/spawn/etc, you could fill a table with limitless values

1 answer

✓ Accepted answer

You need to use loadstring. loadstring returns a function based on code from the string you pass (if it doesn't error) that you can execute. This is very dangerous, so you will need to sandbox it by limiting what it can access. You do this by setting the function's environment.

local code = [[
for i = 1, 10 do
	print('rafor is cool')
end
]]

local newEnv = {
	print = print -- and so on
}


do -- put it in a different scope
	local success, err = pcall(function()
		loadstring(code)()
	end)
end

You need to set ServerScriptService.LoadStringEnabled to true however.

Reply with further questions,

and please mark as correct if this solution works for you!

1 comment

0

You don't need to pcall loadstring btw. Loadstring returns nil and the error message if there was a compile-time error. If there was an exception, then yeah use pcall on the returned function

This discussion is preserved as it was. New answers, comments, and votes are closed.