rhaiscript / rhai

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

Comparing Number with Function #491

Closed Kaiser1989 closed 2 years ago

Kaiser1989 commented 2 years ago

I noticed some strange comparison behaviours:

print(2.0 > 1.0);
print(2.0 > 1);
print(2.0 > true);
print(1.0 > |x| x + 1);

// but:

print(1.0 + |x| x + 1);

output:

Waiting for Web Worker to finish loading...
Running script at 2021-11-23T08:23:38.133Z

[PRINT] true
[PRINT] true
[PRINT] false
[PRINT] false

EXCEPTION: Function not found: + (f64, Fn) (line 3, position 11)
Finished at 2021-11-23T08:34:42.034Z

where comparing any number with booleans or closures returns false (would expect an error, function not found).

schungx commented 2 years ago

This is by design.

Comparison operators (i.e. ==, !=, <, <=, >, >=), when applied to different types, will always return false (!= returns true), unless that specific operator has been defined with a custom function.

https://rhai.rs/book/language/logic.html#comparing-different-types-defaults-to-false

This is to simplify a lot of code, for example:

let x = get_some_value();

if x == 42 { ... }     // defaults to false for all non-numeric values of x, e.g. ()
Kaiser1989 commented 2 years ago

Perfect, Thanks for your fast answer!

This means i have to add some comparators now ;)

schungx commented 2 years ago

If it is just for printing you can do:

print(`1.0 ${|x| x + 1}`);