LeeS quick LUA questions and advice requests

LeeS

Imperator
Joined
Jul 23, 2013
Messages
7,241
Location
Illinois, USA
If I do this:
Code:
local bCanLandOnCarrier = (GameInfo.Units[iUnitType].Domain == "DOMAIN_AIR") and (GameInfo.Units[iUnitType].Special == "SPECIALUNIT_FIGHTER")
Is that a correct lua format to get "true" only when the two conditions are met, and "false" when both or either are not met, or am I going to get "nil" or a syntax error for units that don't match those conditions ?
 
I thought it would but I haven't tried to 'stack-up' those sorts of things all into one line before so something about it made me think perhaps I had a syntax mistake in there.

All of the other GW Basic-like languages I have done intensive programming in would have barfed in many many different ways over a construction like that shown all on a single line :)
 
The short answer is that it will return true or false but only for that line as you have structured it.

Long answer:
In some languages, the word and will return you a true or false, based on whether or not both statements (or more) specified with and are true or not.

In Lua, this is a little different -- and (and by extension, or) do not actually return true or false on their own!

The way this works in Lua is that it returns one of the values from that list.

Let's suppose we have the following:
Code:
[B]A = B and C[/B]

Depending on what values B and C hold, you would expect A to either be true or false.
However, this is not quite the case.

In Lua, if B is nil or false, then Lua returns that value.
If B is not nil or false, then Lua returns the value of C, whatever it may be!

In this case, C may not necessarily be a condition that would evaluate to and/or return a true or false.

If B contained nil or false, then A = nil or false.
If B contained any value besides those, for example, true, 17, or the string "I like cats", then A = C.

In other words, for and in Lua, A = B and C is equivalent to, and is a shortcut for, doing this:
Code:
if B then
	A = C
else
	A = B
end

You can check this yourself via the Lua Demo page I like using so much and pasting this:
Code:
B = 1
C = "Seventeen"

A = B and C

print(A)

Change B and C to various permutations of nil, false, and other values and see what happens.

In short:
In Lua, and returns the Left-side value if it is nil or false, otherwise it returns the Right-side value.

Since I mentioned it earlier, or functions similarly, except it will evaluate expressions from left to right and return the first value that is not nil or false.

This also allows us to set up Ternary operations using and and or -- I've used this moderately in Holo's Lua.
 
Back
Top Bottom