setting negative literals in NVelocity

94 Views Asked by At

I'm trying to set a negative literal in my NVelocity template and it doesn't parse. Is there a trick to making this work?

Positive numbers work:
#set($age = 27)

Negative numbers do not work:
#set($age = -27)
#set($age = 27*-1)

Lexical error: NVelocity.Runtime.Parser.TokenMgrError: Lexical error at line 62, column 15. Encountered: "-"

I'm using Castle.NVelocity (dll-AssemblyVersion 1.1.1.0, FileVersion=1.1.1.60), not the older Apache release

1

There are 1 best solutions below

0
On

Could you please provide a failing unit test because negative literals work for me. I used the HEAD of our NVelocity source repository, however I am not aware of any changes in that area since 1.1.1 was released. If my unit test fails for you with that build, I can look into when this was fixed if you like.

[Test]
public void NegativeLiterals()
{
    Assert.AreEqual("-27", Eval("#set($result = -27)\r\n$result"));
    Assert.AreEqual("-27", Eval("#set($result = 27 * -1)\r\n$result"));
    Assert.AreEqual("-27", Eval("#set($result = 27*-1)\r\n$result"));
    Assert.AreEqual("27", Eval("#set($result = -27*-1)\r\n$result"));
}

private string Eval(string template)
{
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.Init();

    using (StringWriter sw = new StringWriter())
    {
        bool ok = velocityEngine.Evaluate(new VelocityContext(), sw, "", template);
        Assert.IsTrue(ok, "Evaluation returned failure");
        return sw.ToString();
    }
}