Anyway to turn string into function?

For example, I would want to turn “print” into function and run it.

Is there any way to do that?

1 Like
local function test()
    print("test")
end

test()
--Would print "test"

This is how you would make a function, and then call it when ever you want.

2 Likes

What’s your specific use case? Why are you trying to do this? It sounds like you could be running into various problems attempting to do this with respect to performance and all.

I was looking for a way to shorten my admin code in this way without the usage of getfenv.

If you wanted to turn a simple string and convert it into a function, loadstring does it for you. However, this requires ServerScriptService.LoadStringEnabled to be enabled… There are other modules that can do the same thing (albeit slightly slower) that don’t require that property to be enabled.

Example:

loadstring("print(\"Hello world!\")")() --Hello world!

Do keep in mind that this is probably bad practice to do such thing (in this case), but whatever floats your boat.

1 Like

Is that not a bad idea to enable loadstring in your game because of exploiters?

1 Like

Ehh, I wouldn’t necessarily say it’s a bad thing. Exploiters could run code anyway (on the client) and I’m pretty sure, if not definitely sure they can’t run code on the server through one specific function that’s normally disabled (unless of course, you have a remote event that exposes this).

The “loadstring” controversy should probably deserve some clarification as to why loadstring is “bad because of exploiters”.

I’m not saying I recommend it, but I’m also not saying that I don’t recommend it. If you want to use it or not, that’s your choice.

1 Like