lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Apr 18, 2015 at 11:45 AM,  <tonyp@acm.org> wrote:
> As you can see in the sample code below, print does not show the implicit
> nil (when it is last in the list of things to print), yet it shows the
> explicit one.  However, in every other regard, nil seems to behave the same
> in both cases.
>
> Can someone explain why there is a difference in 'nil' treatment between
> these two?
> (I can see the compiler produces slightly different code for each case but
> if they are equivalent, shouldn’t it produce the exact same code for both
> cases?)
>
> And, is the difference evident only in print or elsewhere also?
>
> I’m mostly interested if I should expect the exact same execution path for
> code receiving either nil, or not?  Because obviously print has a different
> execution for each case.
>
> Thank you.
>
> function implicit()
>   return                      --implicit nil
> end
>
> function explicit()
>   return nil                  --explicit nil
> end
>
> print(implicit()==nil,implicit() or 'hidden',implicit())
> print(explicit()==nil,explicit() or 'shown',explicit())
> print(implicit() == explicit())
>
> --- And here’s what the compiler output looks like for the two functions ---
>
> function <implicit> (2 instructions at 004CC030)
> 0 params, 2 slots, 0 upvalues, 0 locals, 0 constants, 0 functions
>         1       [2]     RETURN          0 1
>         2       [3]     RETURN          0 1
>
> function <explicit> (3 instructions at 004CE790)
> 0 params, 2 slots, 0 upvalues, 0 locals, 0 constants, 0 functions
>         1       [6]     LOADNIL         0 0
>         2       [6]     RETURN          0 2
>         3       [7]     RETURN          0 1
>

The main difference is in the number of return values, which the
caller has to care about to know how many stack slots are being used
(though this fact is invisible to Lua code, but if you're writing code
with the C API you need to care).

/s/ Adam