Hi,
I am trying to reproduce a functionality I had many years ago in VB old program. basically, there, I had some expression written by the user involving some logic expression. the syntax for the user was something like:
"{Var1} <> 3 AND ({Var2} <5 OR {Var2} > 8)"
in the code I was looking for all the variables name inside {} and replace them with some values from a database, so for example if Var1 was 2 and Var2 was 4 , I could create at runtime the variable
"2 <> 3 AND (4 < 5 OR 4>8)"
at this point I was doing:
B4X:
Set EvalEng = CreateObject("ScriptControl")
EvalEng.Language = "VBScript" 'JavaScript was another option
txt = ReplacedUserText 'in the example above "2<>3 AND (4<5 OR 4>8)"
Result = EvalEng.Eval(txt)
I am pretty sure there is somenthing like that in B4X but I could not find it. I would assume it should be in the RegEx but I need some guidance.
Can sameone help?
thanks!
Here is a start, (e.Eval is in the example posted by @Erel):
B4X:
Dim a As Int = 3
Dim b As Int = 5
Dim c As Int = -1
Dim logic1 As Int = IIf(a < b, 1, 0)
Dim logic2 As Int = IIf(c > 0, 1, 0)
Log(LogicalEval($"${logic1} OR ${logic2}"$))
B4X:
Sub LogicalEval(s As String) As Boolean
Dim result As Int
s = s.Replace("OR", "+").Replace("AND", "*")
result = e.Eval(s)
Return result > 0
End Sub
July 1 is our national holiday, happy Canada Day!
I have modified the routine by @Erel to handle comparator operators.
B4X:
Sub Process_Globals
Dim e As B4XLogicalEval
End Sub
Sub AppStart (Args() As String)
e.Initialize(Me, "Eval")
Log(LogicalEval("(a <> b) OR ((c < 0) AND (d > 0))", CreateMap("a": 3, "b": 5, "c": -1, "d": 52)))
End Sub
Sub LogicalEval(s As String, substitutions As Map) As Boolean
For Each kw As String In substitutions.keys
s = s.Replace(kw, substitutions.Get(kw))
Next
Return e.Eval(s.Replace(" OR ", "+").Replace(" AND ", "*").Replace("~", "-")) > 0
End Sub
Note: "~" is the unary NOT operator.
Note: AND and OR need to be surrounded by blanks.