Cloud Strife
Cloud Strife

Reputation: 63

Evaluating anything as a Boolean

I am cleaning up another person's code, and I really want to be sure of this before I make a large number of replacements. The LUA documentation states that a Boolean evaluation will see anything other than false or nil, as true. Is this true of more complex objects such as classes and tables?

There is a class Monitor, which takes in a function and acts based on the boolean return of that function. It is called like this:

Monitor(middleFunction,otherparams):hook("doThing",otherstuff)

The function middleFunction has this:

function middleFunction(monitor,arg)
    return otherFunction() ~= nil

My understanding is that, since middleFunction is returning a boolean based on whether otherFunction is not returning nil, I could cut out the entire class and just pass otherFunction to Monitor. If the function returns nil, it will evaluate as false, and if it returns anything else it will evaluate as true:

Monitor(otherFunction,otherparams):hook("doThing",otherstuff)

Is this a safe change? In some cases I have no visibility into either otherFunction or Monitor, but I know that otherFunction returns either a table or nil. Are there any possible cases where it might not evaluate properly if I make this change?

Upvotes: 2

Views: 157

Answers (1)

shingo
shingo

Reputation: 27021

It's unsafe, the boolean evaluation only works for a single expression,

function Monitor(f, p)
    if f(monitor, arg) then
    end
end

But it doesn't work for relational operators, this example only accepts the boolean value true

function Monitor(f, p)
    if f(monitor, arg) == true then
    end
end

Upvotes: 2

Related Questions