expr-lang / expr

Expression language and expression evaluation for Go
https://expr-lang.org
MIT License
6.19k stars 395 forks source link

When I define field names with numbers in front of them, there is an error when running #716

Closed anthony-zh closed 57 minutes ago

anthony-zh commented 2 hours ago

env := map[string]interface{}{ "1greet": "Hello, %v!", "names": []string{"world", "you"}, "sprintf": fmt.Sprintf, }

program, err := expr.Compile(`sprintf(1greet, names[0])`, expr.Env(env))
if err != nil {
    panic(err)
}

output, err := expr.Run(program, env)
if err != nil {
    panic(err)
}

fmt.Print(output) // Hello, world!

=== RUN TestExpr2 --- FAIL: TestExpr2 (0.00s) panic: bad number syntax: "1g" (1:10) | sprintf(1greet, names[0]) | .........^ [recovered] panic: bad number syntax: "1g" (1:10) | sprintf(1greet, names[0]) | .........^

mdmcconnell commented 2 hours ago

Variable names can not begin with a number, so the parser will believe they are numbers and raise the error you have noticed. If those variables are defined in your environment, and you need to access them, you can wrap in $env, like $env["1greet"].

antonmedv commented 57 minutes ago

@mdmcconnell is right. Use $env:

$env["1greet"]