Hello, today I loaded into my place one script from toolbox.
And I have 1 question about this script:
return list and list[x] and list[x][y] and list[x][y][z]
why this will return array’s value, instead of boolean?
I think this and’s will check, does list[x][y][z] exist, and after, it should give true if it exist or false if not?
So cool thing about this. Lua and a few other languages such as JavaScript and Python use ‘truthy’ values for if statements.
if 1 then print(1) end
if "test" then print("Test") end
if true then print(true) end
if false then print(false) end
if nil then print(nil) end
--> 1
--> Test
--> true
So what happens is that in while loops, repeat untils, and if statements, anything is considered ‘truthy’ unless it is nil or false. This means that to save on complexity behind the scenes, and
and or
only need to return the last result they checked.
print(1 and 2) --> 2 because this is an and operation, both sides need to be truthy.
print(false and 2) --> false because both sides need to be truthy, it doesn't bother checking the second side.
print(1 or 2) --> 1 because this is an or operation, only one of the sides needs to be truthy.
print(false or 2) --> 2 because the first side was false.
This is also how people used to make ternary operators. This also works in Python and JavaScript but I don’t recommend it in languages where an existing ternary operator syntax exists.
local yes = false
print(yes and "It's yes" or "It's not") --> It's not
yes = true
print(yes and "It's yes" or "It's not") --> It's yes
If you really want this to be a bool, all you need to do is chain one more and
:
return list and list[x] and list[x][y] and list[x][y][z] and true
If list[x][y] is nil or false, it won’t check list[x][y][z]. Instead, it will end and return list[x][y], which is nil or false. So this will only return nil, false, or true.
1 Like