ISibboI/evalexpr

Support for dot notation variables and nested context_map

Opened this issue · 5 comments

Is it possible to access variables in context by dot notation like this?

use evalexpr::*;

fn main() {

    let ctx = context_map! {
        "a" => context_map! {
            "b" => 4
        }
    };

    assert_eq!(
        eval_with_context("a.b", ctx),
        Ok(4.into())
    );
}

No, that is not possible. I was thinking about implementing something like this at some point, but I think I would rather leave that up to a pull request.

I think we can expand this feature to a native JSON support, I will try to make a PR later, this will a big and useful feature.

proposal

eval("
    enemy = { x: 100, y: 200, z: get_z() };
    // return the coordinate
   (enemy.x, enemy.y, enemy.z)
")

This is how I am doing this currently:

    fn add_value_to_context(
        &self,
        prefix: &str,
        value: &serde_json::Value,
        context: &mut HashMapContext,
    ) -> Result<(), EvalexprError> {
        match value {
            serde_json::Value::Object(obj) => {
                for (key, value) in obj {
                    let new_key = if prefix.is_empty() {
                        key.to_string()
                    } else {
                        format!("{}.{}", prefix, key)
                    };
                    self.add_value_to_context(&new_key, value, context)?;
                }
            }
      ...

And I can access a variable as such:

'object.nested.number == 5'

@odyslam do you have a pr for this implementation or can you point to where this code is implemented

Hi @odyslam did you make any further progress on this?