AND in Lua, how is it processed?

牧云@^-^@ 提交于 2019-12-02 00:07:18

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!