2020-08-08 10:03:14 +02:00
|
|
|
use rhai::{Engine, EvalAltResult, ParseErrorType, INT};
|
2017-11-03 17:58:51 +01:00
|
|
|
|
|
|
|
#[test]
|
2020-04-21 17:25:12 +02:00
|
|
|
fn test_loop() -> Result<(), Box<EvalAltResult>> {
|
2020-04-07 07:23:06 +02:00
|
|
|
let engine = Engine::new();
|
2017-11-03 17:58:51 +01:00
|
|
|
|
2020-03-17 10:33:37 +01:00
|
|
|
assert_eq!(
|
|
|
|
engine.eval::<INT>(
|
2021-04-20 06:01:35 +02:00
|
|
|
"
|
2020-03-17 10:33:37 +01:00
|
|
|
let x = 0;
|
|
|
|
let i = 0;
|
2017-11-03 17:58:51 +01:00
|
|
|
|
2020-03-17 10:33:37 +01:00
|
|
|
loop {
|
|
|
|
if i < 10 {
|
2020-04-01 10:22:18 +02:00
|
|
|
i += 1;
|
|
|
|
if x > 20 { continue; }
|
2020-07-06 10:20:03 +02:00
|
|
|
x += i;
|
2020-03-17 10:33:37 +01:00
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
2017-11-03 17:58:51 +01:00
|
|
|
}
|
|
|
|
|
2023-02-16 13:35:15 +01:00
|
|
|
x
|
2021-03-27 11:08:34 +01:00
|
|
|
"
|
2020-03-17 10:33:37 +01:00
|
|
|
)?,
|
2020-04-01 10:22:18 +02:00
|
|
|
21
|
2020-03-17 10:33:37 +01:00
|
|
|
);
|
2020-03-02 15:11:56 +01:00
|
|
|
|
2020-08-08 10:03:14 +02:00
|
|
|
assert_eq!(
|
|
|
|
*engine
|
|
|
|
.compile("let x = 0; break;")
|
|
|
|
.expect_err("should error")
|
2022-07-29 03:42:30 +02:00
|
|
|
.err_type(),
|
2020-08-08 10:03:14 +02:00
|
|
|
ParseErrorType::LoopBreak
|
|
|
|
);
|
2020-06-12 12:04:16 +02:00
|
|
|
|
2022-11-30 07:11:09 +01:00
|
|
|
#[cfg(not(feature = "no_function"))]
|
|
|
|
assert_eq!(
|
|
|
|
*engine
|
|
|
|
.compile("loop { let f = || { break; } }")
|
|
|
|
.expect_err("should error")
|
|
|
|
.err_type(),
|
|
|
|
ParseErrorType::LoopBreak
|
|
|
|
);
|
|
|
|
|
2020-08-08 10:03:14 +02:00
|
|
|
assert_eq!(
|
|
|
|
*engine
|
|
|
|
.compile("let x = 0; if x > 0 { continue; }")
|
|
|
|
.expect_err("should error")
|
2022-07-29 03:42:30 +02:00
|
|
|
.err_type(),
|
2020-08-08 10:03:14 +02:00
|
|
|
ParseErrorType::LoopBreak
|
|
|
|
);
|
2020-06-12 12:04:16 +02:00
|
|
|
|
2020-03-02 15:11:56 +01:00
|
|
|
Ok(())
|
2017-11-03 17:58:51 +01:00
|
|
|
}
|
2023-02-16 13:35:15 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_loop_expression() -> Result<(), Box<EvalAltResult>> {
|
|
|
|
let mut engine = Engine::new();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
engine.eval::<INT>(
|
|
|
|
"
|
|
|
|
let x = 0;
|
|
|
|
|
|
|
|
let value = while x < 10 {
|
|
|
|
if x % 5 == 0 { break 42; }
|
|
|
|
x += 1;
|
|
|
|
};
|
|
|
|
|
|
|
|
value
|
|
|
|
"
|
|
|
|
)?,
|
|
|
|
42
|
|
|
|
);
|
|
|
|
|
|
|
|
engine.set_allow_loop_expressions(false);
|
|
|
|
|
|
|
|
assert!(engine
|
|
|
|
.eval::<INT>(
|
|
|
|
"
|
|
|
|
let x = 0;
|
|
|
|
|
|
|
|
let value = while x < 10 {
|
|
|
|
if x % 5 == 0 { break 42; }
|
|
|
|
x += 1;
|
|
|
|
};
|
|
|
|
|
|
|
|
value
|
|
|
|
"
|
|
|
|
)
|
|
|
|
.is_err());
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|