I saw this code in a Lua Style Guide
print(x == "yes" and "YES!" or x)
Context:
local function test(x)
print(x == "yes" and "YES!" or x)
-- rather than if x == "yes" then print("YES!") else print(x) end
end
What exactly happens at " x == "yes" and "YES!" ? Why does it print "YES!" or (x) not "true" or (x) ?
EDIT:
Is it like:
X == "yes" -- > true
true and (value) -- > value
print( (x == "yes") and value)
So checking x for the value "yes" results in true, adding true to a value gives the value and printing this process prints the value, right?
From the docs:
The operator and returns its first argument if it is false; otherwise, it returns its second argument.
Therefore, true and "YES!"
evaluates to "YES!"
.
This scheme works because if the first argument is falsy, the whole expression will become falsy (the same as the first argument); otherwise it will become the same as the second argument, which iff that is truthy will make the whole expression truthy.
来源:https://stackoverflow.com/questions/27978443/and-in-lua-how-is-it-processed