Lua variables take several forms. One of these is boolean, which is either true or false. Often, however, you want to use that boolean variable to determine what text you want to display. Normally you would use an if statement or a function, but thanks to how Lua works there is a much easier way.
I was using a boolean variable to keep track of whether or not the critcounter I'm working on was enabled or not. Well, I came to the part where I display the critcounter, and I wanted to show the status (enabled/disabled) in text, and color the text green or red. The typical way of doing this would be something like this, right?
if critcounter.enabled then
AnsiNote (ansicolor (10), ("enabled")
else
AnsiNote (ansicolor (9), ("disabled")
end -- if
Well, I got to thinking, that's five lines for something simple, let's shorten it some. So I pulled my usual and used a table. It looked like this.
local text = {["true"] = "enabled", ["false"] = "disabled"}
local color = {["true"] = 10, ["false"] = 9}
AnsiNote (ansicolor (color[tostring (critcounter.enabled)]), text[tostring (critcounter.enabled)])
Very nice, eh? Down to three lines. I moved on to another part. But something was nagging at me. See, logical operators are perfect for use with boolean. Logical 'and' shows if both are true, and logical 'or' shows if one is true. Well, that's part of the story. How they actually work is this. Logical 'and' returns the first item if it is false or nil, otherwise it returns the second. Logical 'or' returns the first item if it is not false or nil, otherwise it returns the second. It doesn't matter if they are boolean or numbers or text. So I went and rewrote that line to look like this.
AnsiNote (ansicolor (critcounter.enabled and 10 or 9),
(critcounter.enabled and "enabled" or "disabled"))
And voila! It worked! But why? Let's look at the number part.
critcounter.enabled and 10 or 9
What it's really doing is this. If critcounter.enabled is true, 'and' returns 10. So then we have this statement: '10 or 9'. The 'or' operator then sees 10 is not false or nil, and returns 10. If critcounter.enabled is false, 'and' returns false. So then we have this statement: 'false or 9'. The 'or' operator then sees that the left side is false, so it returns the right side. It does the exact same thing with the enabled and disabled text.
view the full post