Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Is it right? :-)
Started by Kangmin Won Apr 24 2018 01:05 AM

3 replies to this topic
[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

Kangmin Won

[GLOBAL: userInfoPane.html]
Kangmin Won
  • Contributor

  • 149 posts
  • Corona SDK

What value does the code below print?

local result = (true and nil or "Huh?")
print("result:", result)

result: Huh?

 

Why? Haha..



[TOPIC: post.html]
#2

horacebury

[GLOBAL: userInfoPane.html]
horacebury
  • Corona Geek

  • 2,933 posts
  • Corona SDK

The expression evaluates as:

true and nil == false

And then:

"Huh?" == true

In Lua, the expression is equivalent to:

if (true == true and nil == true) then
  return true
elseif ("Huh?" == true) then
  return "Huh?"
end

The reason is that any value which is non-false and non-nil will be true. Any expression which has 'and' and 'or' will evaluate the 'and' portion and then the 'or' portion, taking the result of the 'and' portion as an input. (Which is why the 'if' block above separates them.

 

You are asking for a return value from the expression and Lua will return the successful portion of your expression as a value. This means that because the "Huh?" is not evaluated as 'false' (but the 'and' portion of the expression evaluates as 'false') you will receive the value of the 'true' portion of the expression.

 

In short: Lua returned the portion of the expression which is 'true'. In your case, "Huh?" is not nil and not 0, so it is returned.



[TOPIC: post.html]
#3

ldurniat

[GLOBAL: userInfoPane.html]
ldurniat
  • Contributor

  • 278 posts
  • Corona SDK

From lua.org

 

Conditionals (such as the ones in control structures) consider false and nil as false and anything else as true. Beware that, unlike some other scripting languages, Lua considers both zero and the empty string as true in conditional tests.

 


  • horacebury and roaminggamer like this

[TOPIC: post.html]
#4

Kangmin Won

[GLOBAL: userInfoPane.html]
Kangmin Won
  • Contributor

  • 149 posts
  • Corona SDK

Oh, I guessed incorrectly.
I thought 'and, or' condition is 'if, else'.
 
local result
if true then
  result = nil
else
  result = "Huh?"
end

print("result:", result)

I learned a new thing. Thank you very much! :-)




[topic_controls]
[/topic_controls]