Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 510
warspyking Avatar asked Oct 09 '15 16:10

warspyking


1 Answers

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.

like image 138
Yu Hao Avatar answered Nov 15 '22 09:11

Yu Hao