Returning nil with ternary operators?

Hello!

Is it possible to return a falsy value (particularly nil) when using ternary operators?

So for example,

local t = {}

local expression = #t > 0 and t or nil

expression is set false because #t is 0, and therefore t can’t be returned because of Lua doing shorthand operations, however it doesn’t evaluate to nil because nil is falsy. Is there a way around this, and make expression nil if the #t > 0 and t condition isn’t met?

local t = {}

local expression = if #t > 0 then t else nil

if-then-else works fine for this

2 Likes

I had no idea you could do that, I don’t think I’ve ever seen that before. Thanks!

well it’s still fairly new to luau
more info

1 Like
local t = {}

local expression = #t > 0 and t

Would result in a bool value of false being assigned to “expression” which is essentially equal to nil in terms of Lua Boolean logic.

They’re both falsy but nil is not false and false is not nil. False indicates something is not true and nil indicates nothing.

and by new, we mean within the last 48 hours. :stuck_out_tongue:

It was designed officially for this use, so this makes sense.

2 Likes

only thing I’m confused about is what to call it
it isn’t ternary because of elseif, you can do many of them at once
so you can’t call them ternary operators

2 Likes

Officially, it’s called an “if expression”.
Sidenote: “ternary operator” isn’t very descriptive in the first place since it just means it takes 3 operands and doesn’t actually describe what it is. Thus, it is sometimes described as the “conditional operator”.

2 Likes