luametatablelua-userdata

Lua: extending userdata in metatables


I am trying to find a proper solution for some protected employee userData that I want extend with additional entries/data for easy access

Here's a rough example of what I'm trying to do:
This works, but I dont like that I have to put all the custom logic inside the index function

setmetatable(self, {
    __index = function(t,k)
        if k == "isDriving" then --custom data
            return user.inCar and user.onRoad
        elseif k == "isLateToWork" then --custom data
            return user.wokeUpLate and user.startTime < user.arrivalTime
        else
            return user[k] --original userData
        end
    end
})

and how I access the custom data:

print(employee.isDriving)

Ideally I would want to put the custom logic in a separate function, like the example below:
This doesnt work, can also not pass an argument (returns nil)...

if k == "isDriving" then --custom data
    return self:IsDriving(t) --t holds carData and roadData

How can I solve this problem? Are there better solutions?


Solution

  • self:IsDriving(t) is sugar for self.IsDriving(self,t).

    So, the first time the index metamethod is called with k equal to IsDriving, create a function that does what you want, rawset it to IsDriving, and return it.

    However, it's simply easier to create a plain method called IsDriving in the first place.