From cb66e7065325e1117371e6aad1cd7955088dd33d Mon Sep 17 00:00:00 2001 From: Udo Klimaschewski Date: Tue, 25 May 2021 11:00:26 +0200 Subject: [PATCH] String variable was not recognized when passed as a param (#258) Co-authored-by: Fanime Fartoon --- .../java/com/udojava/evalex/Expression.java | 3 +- .../java/com/udojava/evalex/TestCustoms.java | 37 ++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/udojava/evalex/Expression.java b/src/main/java/com/udojava/evalex/Expression.java index 61f3876e..6db4cd78 100644 --- a/src/main/java/com/udojava/evalex/Expression.java +++ b/src/main/java/com/udojava/evalex/Expression.java @@ -1452,7 +1452,8 @@ public BigDecimal eval() { } public String getString() { - return token.surface; + LazyNumber lazyVariable = variables.get(token.surface); + return lazyVariable.getString(); } }); break; diff --git a/src/test/java/com/udojava/evalex/TestCustoms.java b/src/test/java/com/udojava/evalex/TestCustoms.java index 5b0d2c0c..212ae0c5 100644 --- a/src/test/java/com/udojava/evalex/TestCustoms.java +++ b/src/test/java/com/udojava/evalex/TestCustoms.java @@ -229,4 +229,39 @@ public BigDecimal eval(BigDecimal v1, BigDecimal v2) { assertEquals("1", e.eval().toPlainString()); } -} + + @Test + public void testCustomFunctionWithStringParams() { + Expression e = new Expression("INDEXOF(STRING1, STRING2)"); + e.addLazyFunction(new AbstractLazyFunction("INDEXOF", 2) { + @Override + public LazyNumber lazyEval(List lazyParams) { + String st1 = lazyParams.get(0).getString(); + String st2 = lazyParams.get(1).getString(); + final int index = st1.indexOf(st2); + + return new LazyNumber() { + @Override + public BigDecimal eval() { + return new BigDecimal(index); + } + + @Override + public String getString() { + return Integer.toString(index); + } + }; + } + }); + + e.setVariable("STRING1", "The quick brown fox"); + e.setVariable("STRING2", "The"); + + assertEquals("0", e.eval().toPlainString()); + + e.setVariable("STRING1", "The quick brown fox"); + e.setVariable("STRING2", "brown"); + + assertEquals("10", e.eval().toPlainString()); + } +}