Warm tip: This article is reproduced from stackoverflow.com, please click
lua string find

If x amount of these facts are true, then return y

发布于 2020-03-27 10:32:03

I had a function which was returning "Match" if all the facts are true (although I now seem to have broken it by fiddling around with my current predicament, but that's not my main question).

function dobMatch(x)
local result = "YearOfBirth" .. x .. "MonthOfBirth"
    if (result:find("DayOfBirth")~= nil and result:find("MonthOfBirth")~= nil and result:find("YearOfBirth")~= nil) then
        return "Match"
    else
        return nil
    end
end

dobList = {dobMatch("DayOfBirth"), dobMatch("Day")}

print(#dobList)

My actual question, is that if I trying to say that any 2 of the facts result:find("DayOfBirth")~= nil and result:find("MonthOfBirth")~= nil and result:find("YearOfBirth") rather than all 3.

Please bare in mind that my actual issue has 12 facts, of which 10 need to be true so it would be very long to iterate through all the combinations.

Thanks in advance for your help!


Bonus Round! (I misinterpreted my aim)

If I wanted to weight these facts differently, i.e. DayOfBirth is far more important than Month would I just change the 1 (in Nifim answer) to the value I want it weighted?

Questioner
Bee
Viewed
93
Nifim 2019-07-04 00:15

You can change the nature of your problem to make it a math problem.

You can do this by using a lua style ternary:

matches = (condition == check) and 1 or 0

What happens here is when the condition is true the expression returns a 1 if it is false a 0. this means you can add that result to a variable to track the matches. This lets you evaluate the number of matches simply.

As shown In this example I suggest moving the checks out side of the if statement condition to keep the code a little neater:

function dobMatch(x)
    local result = "YearOfBirth" .. x .. "MonthOfBirth"

    local matches = (result:find("DayOfBirth")~= nil) and 1 or 0
    matches = matches + ((result:find("MonthOfBirth")~= nil) and 1 or 0)
    matches = matches + ((result:find("YearOfBirth")~= nil) and 1 or 0)

    if ( matches >= 2) then
        return "Match"
    else
        return nil
    end
end

dobList = {dobMatch("DayOfBirth"), dobMatch("Day")}

print(#dobList)