Question

I have a scenario, in which I want to evaluate a boolean expression given as a string.

For example, "1==4" when passed to some function would evaluate-to/return FALSE.

Similarly, "1==1" when passed to the same function would evaluate-to TRUE.

If this can be done, then I would definitely want some way in which I can evaluate a dynamic boolean expression. For example, "workHours==4" is the the string expression and workHours is a variable.

Let me know of any solution if you know. Thanks.

Was it helpful?

Solution 2

Self learned the answer:

Here's the code sample, how you can do it.

static void Job22(Args _args)
{

 str expr = 'ab==2';
 str method = @'boolean eval(int ab){return ' + expr + ';}';
 boolean result;
 ;
 result = runBuf(method, 5);
 info (strfmt("Calculation result is %1", result));

}

OTHER TIPS

There are ways to evaluate X++ expressions from text via .NET (with XLNT Framework, for example) and via some intrinsic functions in X++. But I'm pretty sure you can get to the same solution with a more clean aproach. For example, you can pass a container to a function and then compare their values, or something like that.

If you still want to go that way, take a look to the runbuf function in X++.

http://msdn.microsoft.com/en-us/library/aa656300.aspx

This might be a better example for your use where you can easily just change expression.

static void RunBufExample()
{
    str                 expression = '2==1';
    str                 func = 'boolean myFunc() {return ' + expression + ';}';
    boolean             retVal;       
    new ExecutePermission().assert();
    retVal = runBuf(func);
    CodeAccessPermission::revertAssert();
    info(strFmt("%1", retVal));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top