Reputation: 131
Im trying to set the counter to 0 if counterFlag[name] is less than 0.
if counterFlag[name] <== 0 then
counterFlag[name] = 0
end
How could I do that?
I get the ''unexpected symbol'' error.
Upvotes: 1
Views: 804
Reputation: 20772
Maybe you actually want to set the counter to 0 if it is not a number greater than 0.
counterFlag[name] =
type(counterFlag[name]="number")
and (counterFlag[name] > 0)
and counterFlag[name]
or 0
and
is an operator that returns its first effectively false operand, otherwise its last operand.
or
is an operator that returns its first effectively true operand, otherwise its last operand.
Effectively false means having a value of nil
or false
.
Effectively true means the opposite.
So the first part conditionally keeps the same value and the second part gives 0 if the conditions aren't met.
Alternatively, a Lua idiom is often used to initialize a variable that might be nil
:
counterFlag[name] = counterFlag[name] or 0
You could put this before code that uses counterFlag[name]
so it then wouldn't have to check for nil
. And, because, presumably, you wouldn't have assigned any other non-number value, the code could use operators that require number values without checking for that.
See Programming in Lua.
Upvotes: 0
Reputation: 122383
As simple as this:
if counterFlag[name] < 0 then
counterFlag[name] = 0
end
Or use <=
for less than or equal to, it has the same effect in this scenario.
Upvotes: 2