Search code examples
luaexpressionmetatable

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?


Solution

  • 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