Re: Show off clean code examples
Posted: Fri Nov 07, 2014 10:42 am
You are definitely right, but The Great Kikito's not wrong either.Ortimh wrote:In case I only want to return true value if func function returns true, so I shouldn't replacewithCode: Select all
if (func()) then return true end
because if I return func function returned value then it returns either true or false.Code: Select all
return func()
In Lua, any non-nil value is considered to be true. Only nil and false are falsy values.
In that case, if you have a function which returns a non-nil value which is also not false, the returned value will pass a truth test.
Here is an exceprt from the online free book PiL (Programming In Lua), taken from chapter 2.2:
Here is an example:The boolean type has two values, false and true, which represent the traditional boolean values. However, they do not hold a monopoly of condition values: In Lua, any value may represent a condition. Conditionals (such as the ones in control structures) consider false and nil as false and anything else as true. Beware that, unlike some other scripting languages, Lua considers both zero and the empty string as true in conditional tests.
Code: Select all
local function identity(value) return value end
local function test(f, v)
if f(v) then
print("true!")
else
print("false!")
end
end
test(identity, 1) -- > "true!" -- number 1 is true
test(identity, 0) -- > "true!" -- even 0 is considered to be true
test(identity, true) -- > "true!" -- true is obviously true
test(identity, "") -- > "true!" -- any string, even an empty one, is true
test(identity, {}) -- > "true!" -- any table, even an empty one, is true
test(identity, function() end) -- > "true!" -- any function, even an empty function, is true
test(identity, false) -- > "false!" -- false is obviously false
test(identity, nil) -- > "false!" -- nil is also a falsy value
But of course, you are not completely wrong, since you can't compare the value to a boolean straight. It won't work. Therefore, if you need your function to return explicitely a boolean value, you can use a very simple trick with the "not" operator. So, instead of :
Code: Select all
if (func()) then return true end
Code: Select all
return not not func()