warspyking
warspyking

Reputation: 3113

Why does my code only print nil once?

It's super-easy to fix; simply make it return nil, but why doesn't my code work without that line?

function x(bool)
    if bool then
        return "!"
    end
end

print(x(true), x(false), x(false))

What makes it even more confusing, is that always prints the nil, as many times as I call x(false) subtract 1.

I can't seem to wrap my ahead around why this is happening.

Upvotes: 5

Views: 171

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

The manual says:

If control reaches the end of a function without encountering a return statement, then the function returns with no results.

Note that returning no result is different from returning nil.


In this call:

print(x(true), x(false), x(false))

both x(false) returns nothing, however, all except the last element are always adjusted to exactly one result.

Usually we see functions call that return one or more results are left with only the first. Here no result is filled with a nil as well.

Upvotes: 6

Related Questions