nu_cmd_lang/core_commands/
loop_.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct Loop;
6
7impl Command for Loop {
8    fn name(&self) -> &str {
9        "loop"
10    }
11
12    fn description(&self) -> &str {
13        "Run a block in a loop."
14    }
15
16    fn signature(&self) -> nu_protocol::Signature {
17        Signature::build("loop")
18            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
19            .allow_variants_without_examples(true)
20            .required("block", SyntaxShape::Block, "Block to loop.")
21            .category(Category::Core)
22    }
23
24    fn extra_description(&self) -> &str {
25        r#"This command is a parser keyword. For details, check:
26  https://www.nushell.sh/book/thinking_in_nu.html"#
27    }
28
29    fn command_type(&self) -> CommandType {
30        CommandType::Keyword
31    }
32
33    fn run(
34        &self,
35        _engine_state: &EngineState,
36        _stack: &mut Stack,
37        _call: &Call,
38        _input: PipelineData,
39    ) -> Result<PipelineData, ShellError> {
40        // This is compiled specially by the IR compiler. The code here is never used when
41        // running in IR mode.
42        eprintln!(
43            "Tried to execute 'run' for the 'loop' command: this code path should never be reached in IR mode"
44        );
45        unreachable!()
46    }
47
48    fn examples(&self) -> Vec<Example<'_>> {
49        vec![Example {
50            description: "Loop while a condition is true",
51            example: "mut x = 0; loop { if $x > 10 { break }; $x = $x + 1 }; $x",
52            result: Some(Value::test_int(11)),
53        }]
54    }
55}
56
57#[cfg(test)]
58mod test {
59    use super::*;
60
61    #[test]
62    fn test_examples() {
63        use crate::test_examples;
64
65        test_examples(Loop {})
66    }
67}