lua-users home
lua-l archive

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


On 18 February 2016 at 13:33, Jonathan Goble <jcgoble3@gmail.com> wrote:
> On Wed, Feb 17, 2016 at 9:19 PM, Daurnimator <quae@daurnimator.com> wrote:
>> On 18 February 2016 at 12:48, Mason Bogue <scythe+lua@ortsz.com> wrote:
>>> and 0/0 or nil
>>
>> ^^ I'm not sure what that was meant to be, as 0/0 is always truthy, so
>> the `or nil` is never hit.
>
> It's the classic idiom "test and value_if_true or value_if_false",
> just extended with two tests. For reference, the function posted by
> Mason (plus some line breaks and indentation to eliminate hard line
> wraps) was:
>
> function __index(self, k)
>     return type(k) == "number" and k <= #self and 0/0 or nil
> end
>
> First, 'type(k) == "number"' is tested. If false, then the binary
> operation 'type(k) == "number" and k <= #self' short-circuits and
> returns its first argument, the boolean false. Then 'false and 0/0'
> short-circuits, returning its first argument (false). That leaves
> 'false or nil', which returns its second argument, nil, as the result
> of the whole chain of operations.
>
> If type(k) is a number, though, then 'type(k) == "number" and k <=
> #self' returns the result of 'k <= #self'. If that is false, then the
> next 'and' operation short-circuits as above, and nil is again the
> final result. If true, then you get 'true and 0/0', which results in
> the truthy '0/0', which then short-circuits the final op.
>
> Does that all make sense now?
>

Yep. sorry, had a brain fail :)