From text to command without an if statement

Basically, I want to be able to take string str, and run a lua function called the same way. For example:


str = "text"
local function text()
	print( "This is a function" )
end

I want to redirect str to run the function.
In the case this isn’t possible - is there any way at all to direct a string to a command without having an if statement?

If you want you can create a table to store functions and just represent each key as the text you want to activate it.

Example:


FunctionTable = {}
FunctionTable[ "text" ] = function() print( "This is a function" ) return true end


Then you’d just call the table as a variable in this manner:


local callfunc = FunctionTable[ textinput ]

If the function exists, callfunc will become that function. Otherwise it’ll be nil due to no key existing.

Can I ask what exactly you’re trying to use this for? There could be better ways to get the results

I want to make all chat messages beginning with ! or / a chat command, so if a command is not registered in the table of commands it will display an error message, and if it is - it will redirect to the appropriate command. I just tried to make it as easy as possible to add new commands (I’m working with other people and they have different ways of doing things, so I wanted to make it really simple)

Oh so this’ll work, just be sure to add this line


if callfunc then callfunc() else INSERTYOURERRORMESSAGE end

Thanks!
But wouldn’t callfunc() try to find a command called callfunc? I thought I should just do


if callfunc then
	callfunc
else
	//Blah blah errors
end

Of course it would, but



if callfunc then


Checks if the function works (well, checks if it isn’t nil).

Also,



if callfunc then
	callfunc -- then do nothing to the function?
else
	//Blah blah errors
end


Is the exact same thing as the other person posted, except you’re not calling the function if the function isn’t nil, don’t you want to call it?

Basically, what they’re saying is you do something like this:
[lua]local ChatCommands = {
["/kill"] = function(ply) – It’s probably a good idea to pass the player on as an argument
ply:Kill()
ply:ChatPrint(“Look what you just did. Sigh”)
end,
– Inser more commands here
end

hook.Add(“PlayerSay”, “AwesomeAutoChatCommands”, function(ply, text)
local func = ChatCommands[text]
if func then
func(ply)
end
end[/lua]
You could probably also remove the / from the commands and check for that or an ! In the PlayerSay hook directly and then remove that from the text before looking it up in the table, that way both would work.

Ohh gotcha.
And ye I was already gonna not include / ! and pass players as a function, but thanks!