I am wondering if it’s possible to run a function using a string, something like this as an example:
function test()
print("worked")
end
-- Wrong Way:
"test"()
-- Right Way:
test()
This would be very useful to me to create a system that will run a specific function whenever I want it to. Heres an example of what I tried to do:
-- This is WRONG and throws 16:14:32.218 - Workspace.Script:8: attempt to call a string value
function test()
print("hello")
end
function runFunction(key)
key()
end
runFunction("test")
I realize it is possible to do something like this by using if statements, But it isn’t as practical:
-- This works.
function test()
print("hello")
end
function runFunction(key)
if key == "test" then test() end
--if key == "test2" then test2() end
-- on and on...
end
runFunction("test")
I’ve asked this question before and the only responses I received was no. You’re going to have to do the if statement unfortunately. I’ve looked up if it was possible to do string to argument in lua but I wasn’t able to find a way to do it.
Im going to have an event purchasing system. Players use a RemoteEvent to pass to the server what event they want to purchase. Lets say billy purchases the “gun” event, so the server script is going to run the function called “gun”. Inside of the gun function, it handles giving every player the gun. This is my plan for using this.
You should not be doing this since exploiter can potentially pass any string over the remote event, instead just make a key and then make a dictionary that maps the key to function. That way you can verify the key by checking if it exist like this:
local Functions = {
Gun = function()
end
}
SomeRemote.OnServerEvent:Connect(function(Player, Key, ...)
local Function = Functions[Key]
if Function then
Function(...)
end
end)
I left out the part where I was going to verify the purchase. I was leaning towards making the if key == "test" then test() end so this wouldnt really have been an issue.
Then why not just use my method, what your requesting is not possible and you have two options: my method or @ozyubkx’s method. Your over complicating a simple issue.
Sort of off-topic, but this doesn’t really seem like an advantage of modular coding. Modular code is more about splitting up your code into reusable, self-contained components. This is more of a feature of Lua tables.
Yeah, I was actually planning on having the entire thing in a module to just get it out of the way so my MasterScript is easier to look at. Happy birthday!
Yea, the if key == "test" then test() end example I used in the initial post actually does work. Besides that, I will probably use ideas from your method and @ozyubkx’s method to get want I want. Thanks.