Check date from a table?

I’m working on a live event script, and i have the defined date in a table:

local t = {
    year = 2020,
    month = 6,
    day = 1,
    hour = 15,
    min = 35,
    sec = 0

And it will check every second if the date is the same as written in the statement, something like this:

if osdate.year == 2020 and osdate.month == 6 and etc then

However, i want to instead of doing that, i want to check the date by getting the table, for example:

if osdate == t then --// t = the table with the defined table.

And i don’t know if this is possible or not, and i really need this. Thanks for reading.

No. Tables are passed by reference, which means one table will never equal another table.

Yeah, i know that you can’t compare two tables, such as the example i gave, but i don’t know if it is possible to check is the date inside a table is the same as today’s date, without comparing two tables.

You can perform all the equivalence checks within an __eq metamethod. The __eq metamethod will be ran when the equivalence operator (==) is called on two tables, when the reference equality fails and if both tables have the same __eq metamethod.

Make this the sole metamethod of a metatable then wrap both the defined date dictionary and the one returns. This will ensure that when we check for equivalence, understandably the references will not be the same but they will both have the same __eq metamethod.

From here, there are a couple of ways you can do this, but I’ll stick to the one that has the least amount of work involved, which is to do a direct comparison. You’ll compare the keys of one table to those of another and see if their values match up, returning true at the end if all keys match or prematurely returning false if one key fails the check.

Remember, we are only actually checking values. Keys from iterating over the first table serve as our lookup for the second. We’re not concerned in if keys are similar, but if the values are, so we need to access the values from both tables using the same key.

This is how the metatable would look like:

local dateMeta = {
    __eq = function(left, right)
        for key, value in pairs(left) do
            if not (value == right[key]) then
                return false
        return true

Once you have this down, just wrap both tables with it. A little warning before I show some sample code: the less than metamethod may also get called if you use a <= operator, so to avoid both the __eq and __lt metamethods getting called, you’ll need an __le metamethod.

local t = above
local dateMeta = above

setmetatable(t, dateMeta)

-- osdate somewhere?

setmetatable(osdate, dateMeta)

print(t == osdate) -- boolean
1 Like