Likely very simple javascript question


#1

Hi!

Likely I'm being dumb, but:

        ScopedPointer<DynamicObject> dynamicObject = new DynamicObject();

        dynamicObject->setProperty("one", "0.333");
        dynamicObject->setProperty("two", "0.666");

        ScopedPointer<JavascriptEngine> jsengine = new JavascriptEngine();
        
        jsengine->registerNativeObject("doIReallyNeedThis", dynamicObject);

        String code = "1+2+doIReallyNeedThis.one+doIReallyNeedThis.two";

        var result = jsengine->evaluate(code);

        DBG("Result: " + result.toString());

gives me output: Result: 30.3330.666

a: how do I make this print 3.999?

b: how do I make this work with the input string: "1+2+one+two"?

Thanks!

 


#2

your "one" and "two" properties are strings, so it's concatenating them as strings, not adding them as numbers. You could make them doubles, or parse the strings with Integer.parseInt


#3

...Sorry yeah that one was a bit too obvious, I blame the late-night coding :D


#4

That leaves point b:

In the below code

        JavascriptEngine jsengine;
        DynamicObject*  dynamicObject = new DynamicObject();
        dynamicObject->setProperty("one", 0.333f);
        dynamicObject->setProperty("two", 0.666f);
        
        jsengine.registerNativeObject("a", dynamicObject);
        String code = "one + two";
here->  code = code.replace("one", "a.one");
here->  code = code.replace("two", "a.two");
        var result = jsengine.evaluate(code);
        DBG("Result: " + result.toString());

The two replace commands feel superflous, surely there should be a way to add two variables directly into the root/global context?

The string to be parsed I want to be as simple as possible, I do not want to ask users to know it has anything to do with JS, hence the replace.

Sorry if my questions are too trivial, I've managed to avoid everything web-related this far in my life, and that included JS...