AND in Lua, how is it processed?

前端 未结 1 777
广开言路
广开言路 2021-01-21 05:21

I saw this code in a Lua Style Guide

print(x == \"yes\" and \"YES!\" or x)

Context:

local function test(x)
  print(x == \"yes\"         


        
相关标签:
1条回答
  • 2021-01-21 05:35

    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.

    0 讨论(0)
提交回复
热议问题