Reputation: 11
I've been taught to program in Java. Lua is new to me and I've tried to do my homework but am not sure what an if statement of the following nature means.
The code is as follows:
local function getMinHeight(self)
local minHeight = 0
for i=1, minimizedLines do
local line = select(9+i, self:GetRegions())
**if(line) then
minHeight = minHeight + line:GetHeight() + 2.5
end**
end
if(minHeight == 0) then
minHeight = select(2, self:GetFont()) + 2.5
end
return minHeight
end
The if statement with the ** before and after is the part I'm not sure about. I don't know what the if statement is checking. If the line is not nil? If the line exists? If what?
Upvotes: 1
Views: 455
Reputation: 29000
In Lua, anything that's not nil
or false
evaluates to true in a conditional.
If the line is not nil? If the line exists?
Yes to both, because they kinda mean the same thing.
The select
function returns a specific argument from it's list of arguments. It's used primarily with ...
, but in this case it's being used to select the (i+9)th value returned by self:GetRegions
. If there is no such value (for instance, if GetRegions only returns 5 values), then select
returns nil.
if(line)
is checking to see that it got a value back from select
.
if(line)
is being used as a shortcut for if(line ~= nil)
, since nil evaluates to false in a conditional.
It's worth pointing out that this shortcut is not always appropriate. For instance, we can iterate all the values in a table like this:
key, val = next(lookup)
while key do
print(key, val)
key, val = next(lookup, key)
end
However, this will fail if one of the table's keys happens be false
:
lookup = {
["fred"] = "Fred Flinstone",
[true] = "True",
[false] = "False",
}
So we have to explicitly check for nil
:
key, val = next(lookup)
while key ~= nil do
print(key, val)
key, val = next(lookup, key)
end
Upvotes: 8
Reputation: 52668
As Mud says, in lua anything other than nil
and false
is considered truthy. So the if
above will pass as long as line
is not nil
or false
.
That said, it worries me a bit the way you have phrased the question - "an if with only one argument".
First, it's not called "argument" - it's called expression. And in most languages is always one. In java, for example, you could do something like this:
bool found = false
...
if(found) {
...
}
if
s only care about the final value of the expression; they don't care whether it's a single variable or a more complex construction.
Upvotes: 2