1

I am trying to loadstring a string and run it as a function. Here is my problem:

a = "hello"
loadstring("print(a)")()

I dont want the code above to use any vars/funcs outside of it. My goal is to make the script above print nil since a isnt defined inside the loadstring.

Sorry if the question is very brief. It was hard to explain my problem.

1
  • @Joseph Sible-Reinstate Monica sorry my bad. I meant to have a global var not local. Commented Dec 11, 2020 at 6:43

1 Answer 1

1

Your variable a lives in the global environment. To keep your chunk from seeing it, you need to give it a different environment. In Lua 5.1, you'd do that like this:

a = "hello"
local chunk = loadstring("print(a)")
setfenv(chunk, {print = print})
chunk()

In Lua 5.2 or newer, you'd do that like this:

a = "hello"
load("print(a)", nil, "t", {print = print})()

It's important to note that print isn't magic. It won't be in the new environment unless you put it there explicitly, like I did.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much! I do still have a problem. What if this said string was dynamic. I don't know what is going to be executed. Will I have to define every single LuaU (Roblox Lua) function?
@Cottient You could do tricks like deep-copying _G and then removing what you don't want, but this is really starting to sound like an XY problem. What are you actually trying to achieve by restricting a script like this? Could you just use locals instead, like you did when you first posted the question?
What I am trying to achieve is something like a script editor. The user types the code and presses execute. Think of it as a command line. If there are no other solutions then I guess I will just make everything local.
@Cottient In that case, that's definitely what you should do. Good practice when writing Lua is that everything should always be local unless you have a good reason for it to not be. In this case you don't, and in fact you have a good reason for it to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.