Is it possible to get a function via string?

Hey

Is it possible to find a function via string or get it from the environment or is it possible to convert a string into it’s function form

local a = "pri"
local b = a.."nt"
b("Hello.")

One way to do it is to use a table like this:

f = {
    ["print"] = print,
}

local a = "pri"
local b = f[a.."nt"]
b("Hello.")

That might work

1 Like

This is quite useful to know so thank you and I might use this if there is no other way

Woops, I had a error in there, forgot to add the []'s. Now it should work!

The simplest way is via a table value as demonstrated here. The following implementation uses getfenv.

local env = getfenv(0)
local lib = "math"
local const = "pi"
print(env[lib][const]) --3.14...
4 Likes

Dang, I was thinking that you could use getfenv but I’m not familiar with it so… I was doing some research. Edit: Just realized that that way still requires variables.

You can index directly.
print(getfenv(0).math.pi) --3.14...

1 Like

Yeah. that seems better it would probably be better also if you store the getfenv(0) in a variable like funcs. Btw Forummer, can you help me with something else? I sent you a DM a few days ago about it, if you don’t have time then it’s fine.

I confirm it works, thankyou and thankyou to @domboss37 for contributing you both gave me good ideas

You should probably mark Forummer’s OG reply as solution because that’s where the actual solution is found (it keeps things more organized)

Yeah just did it lol and appreciate the help :slight_smile:

1 Like

Just a warning because I didn’t see it mentioned. Using getfenv is not recommended because it disables some optimizations.

The optimizations are only in effect on functions with “pure” environments - because of this, the use of loadstring/getfenv/setfenv is not recommended. Note that getfenv deoptimizes the environment even if it’s only used to read values from the environment.

You should never need getfenv beyond impractical tech projects anyways, so if this is for a game you should probably do something different.

1 Like

I am using it for an obfuscator, just a little project I’m working on for fun

2 Likes