I am making an admin command script. It is all fine, but I have a question.
If I have a lot of if else statements. Will they affect performance or not?
If they do what is the better way of doing this?
Example code:
if (msg == "kill") then
...
else
...
else
...
else
...
else
...
else
...
else
...
else
...
else
...
else
...
end
The “command check” part of my admin commands is like this. Will this cause any performance issues?
If it will then what is the better way of doing this?
You can create a table with command functions, and refer to that arguments.
local Commands = {
["kill"] = function(users)
end,
["tp"] = function(user, target)
end
...
}
It is already something like this:
local Commands = {
["kill"] = function(users)
end,
["tp"] = function(user, target)
end
...
}
if (command == "kill") then
commands["kill"](plr,msg)
else
...
end
How can I optimize the if else part.
Well, simply do
if Commands[command:lower()] then
Commands[command:lower()(arguments)
end
You’ll need to unify the function arguments though.
2 Likes
How can I do commands[msg] because the player will chat “kill me” and not “kill”. I cannot do msg:sub(1,4) as the command might be different like “fly me”.
You should use string.split to properly get the arguments.
1 Like
Oh so something like this?
msg = msg:split(" ")
if (commands[msg[1]]) then
commands[msg[1]](plr,msg)
end
Yep!
Though, assuming this isn’t pseudocode, you should use local variables where possible - this is for efficiency reasons and it’s good to use proper scope (for code re-usability). Try to avoid global variables where possible (also, it avoids variable collisions)
1 Like