Richard Avalos
Richard Avalos

Reputation: 599

Lua: Expression from metatable returns nil instead of false

I have a metatable set up like this example:

    setmetatable(self, {
    __index = function(_,k)
        return Class[k] and Class[k](self, ref) or ref[k]
    end
})

And my function:

function Class:isDriving(person)
   return (person.onRoad and person.inCar) or false
end

All together it allows me to do something like this:

print(driver.isDriving)

Now this all works, When the expression is true it returns a boolean true. The only problem I have is that the expression returns nil when its false, instead of just a boolean false.

--I tried this too, but also returns nil
return (person.onRoad and person.inCar) or (nil and false)

How can I fix this?

Upvotes: 1

Views: 275

Answers (1)

Egor   Skriptunoff
Egor Skriptunoff

Reputation: 974

The problem is Class[k](self, ref) may return false
Rewrite

return Class[k] and Class[k](self, ref) or ref[k]

as

if Class[k] then
   return Class[k](self, ref)
else
   return ref[k]
end

Upvotes: 2

Related Questions