How to Convert String to Function?

  1. What do you want to achieve? I am trying to make it so if a function is called in a string, it can call the function through the string. There is an example below.

  2. What is the issue? I can’t think of any way to do it.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub? Yes, I have.

Here’s an example of what I mean if I was a little confusing:

function test(num)
    print(num))
end

local string = [[test(5)]]

How would I make the function inside of the variable string run?

1 Like

Traditionally, you would use loadstring() to do this. This is typically considered unsafe, since you could execute arbitrary code. The same reason why JavaScript programmers are advised to never use eval().

By default, using loadstring is disabled for safety purposes. If you want to use it, you have to check the LoadStringEnabled property under the ServerScriptService.

When you use loadstring, it will essentially return a function that will then execute the source code provided.

Then your code could look something like this:

function test(num)
    print(num))
end

local string = loadstring([[test(5)]])()

Again, under best practices, you should avoid using loadstring.

8 Likes

Why does it have the () at the end? The string all ready has the parentheses and so does load string.

1 Like

loadstring returns a function built off the source string you provided.

1 Like

Loadstring returns a closure compiled from the provided source code passed into the function. I wouldn’t say its “built off” the source provided but instead it’s like running an entirely new script, but it inherits the same function environment of the caller of loadstring.

1 Like