every programmer should know how to use.
First off, let's talk about their use. A look-up table's primary use is to replace the ugly and time consuming method of if-elseif chains, like this one
if a then
-- stuff
elseif b then
-- other stuff
elseif c then
-- more stuff
elseif d then
-- even more stuff
elseif e then
-- too much stuff
else
-- Something we didn't expect
end
That looks just plain ugly. It also looks hard to write, which it is. So we're going to fix it.
Consider these two functions :
function myFunction()
print("Hello!");
end
function myOtherFunction()
print("Goodbye!");
end
I'm collecting input from the user, and I want to run myFunction when the user enters "hi" and run myOtherFunction when the user enters "bye."
In order to do this, we create a table. In this table, the key corresponds to the function I want to run if I receive it.
Let's make a table to do this :
local myLookupTable = {
["hi"] = myFunction,
["bye"] = myOtherFunction,
};
Notice how when I typed the function names, I did not use parenthesis with them. This is because I am not calling them, but getting the code they point to.
Now, all I have to do to check the user input is this
if myLookupTable[input] then
myLookupTable[input]();
else
-- Just in case the user types a word that we don't know about.
print("Word not found");
end
If you look closely, I put parenthesis after the second myLookupTable[input]. Because the data at myLookupTable[input] is a run-able function, all I have to do to run it is to call it by adding parenthesis.
Now my word asking code looks like this
write("Type a word : ");
local input = read();
if myLookupTable[input] then
myLookupTable[input]();
else
print("Word not found");
end
And as TheOriginalBIT has pointed out, you don't necessarily need to have your lookup table made of functions.
Consider BIT's code :
local validSides = {
["left"] = true,
["right"] = true,
["up"] = true,
["down"] = true,
}
write("Type a side: ")
local input = read()
if validSides[input] then
print("Thank you")
else
print(input.." is not a valid side")
end
I can see how you might think that the lookup table didn't really make our code any less ugly,
and that typing if-elseif-else-end wouldn't be too hard. I'd agree with that statement.
Remember though, that there are times when you can be working with 4+ different expected outputs,
at which point the if-elseif-else-end isn't going to cut it.
Using a lookup table for smaller checks might not be necessary, but for bigger checks it is vital if you want clean, readable code.
That is all. Be sure to make friends with your look-up tables. They will certainly make life easier in bigger programs.
Please post any comments, suggestions, or questions.
~Sora