rhaiscript / rhai

Rhai - An embedded scripting language for Rust.
https://crates.io/crates/rhai
Apache License 2.0
3.82k stars 180 forks source link

Indexers and += #551

Closed markusmoenig closed 2 years ago

markusmoenig commented 2 years ago

Hi,

great job with this, I am using Rhai in my classical RPG creator Eldiron.com for evaluating expressions and scripts. See attached.

Question: When using Indexers and using them in a script, why does code like

target["HP"] += 1

not throw an error ? Because it gets evaluated as

target["HP"] = 1

which is different than what is intended.

Thanks,

Screen Shot 2022-04-14 at 08 26 12
schungx commented 2 years ago

Using an object map, I can't reproduce the error.

target["HP"] += 1; is syntactic sugar for target["HP"] = target["HP"] + 1;

https://rhai.rs/book/language/assignment-op.html

Are you defining your own indexer functions? If so, it should "get" the value, and then sets it to the new value...

schungx commented 2 years ago

Ah OK, I can reproduce that with a custom indexer. It seems to be a bug.

markusmoenig commented 2 years ago

OK :)

It also has something to do with the type. My variables are f64. When I do

target["HP"] += 1

which should work fine but I get:

Err(ErrorIndexingType("server::gamedata::script::InstanceVariables [string] = i64", 1:7))

When I use

target["HP"] += 1.0

I get no error and HP is always set to 1.

schungx commented 2 years ago

You can pull from https://github.com/rhaiscript/rhai/ to try out the fix.

It so happens a compound assignment statement on an indexer is missing the appropriate calls.

Good job catching this!

markusmoenig commented 2 years ago

Thanks so much for the quick fix! Works perfect!

You can close this issue at your convenience. Note I have opened up #553 as a follow up feature request.