Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 4 years ago

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.

0
You can use loadstring, just make sure to use it carefully. hiimgoodpack 2009 — 4y
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 chess123mate 5873 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

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!

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 incapaz 195 — 4y
Ad

Answer this question