1

In Lua 5.3.0, I run "true and print("Hi")":

> true and print("Hi")
Hi
nil

Why does program output nil?

1
  • 6
    Because print doesn't return anything? Commented Jun 28, 2015 at 10:06

2 Answers 2

7

The print function returns nil:

> print("Hi") == nil
Hi
true

The expression true and nil returns nil (see Logical operators in Lua):

> true and nil
nil

That's why your original expression returns nil.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, the print function returns nothing, but when used with a boolean operator the number of return values is adjust to one value (which is nil in this case). (print("Hi")) has the same effect for the same reason, plain print("Hi") will not write the nil to the console.
@siffiejoe You are right. It's even more evident at C level where the difference between a Lua function that returns no value and another function that returns a single nil parameter is evident. Thank you for your clarification.
6

This is a side effect of a new feature of the Lua interpreter in version 5.3.

In previous versions, this code was invalid:

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> true and print("Hi")
stdin:1: unexpected symbol near 'true'

Similarly:

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> 1+1
stdin:1: unexpected symbol near '1'

The interpreter only accepted statements, not expressions. You could prefix an expression with return or the shortcut = though:

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> =1+1
2
> =true and print("Hi")
Hi
nil

In Lua 5.3 a new feature has been introduced to make it simpler to use the interpreter like a calculator: if the input is invalid, then the interpreter tries to prefix it with return. This is why you get this result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.