Vectors

A vector is a native data structure of Rune which is a dynamic list of values. A vector isn't typed, and can store any Rune values.

pub fn main() {
    let values = ["Hello", 42];

    println!("{}", values[0]);
    println!("{}", values.1); // items in vectors can be accessed like tuple fields.

    for v in values {
        println!("{}", v);
    }
}
$> cargo run --bin rune -- run scripts/book/vectors/vectors.rn
Hello
42
Hello
42
== () (5.0674ms)

As you can see, you can iterate over a vector because it implements the iterator protocol. It is also possible to create and use an iterator manually using Vec::iter, giving you more control over it.

pub fn main() {
    let values = ["Hello", 42];

    for v in values.iter().rev() {
        println!("{}", v);
    }
}
$> cargo run --bin rune -- run scripts/book/vectors/vectors_rev.rn
42
Hello
== () (2.9116ms)

Using vectors from Rust

Vectors are represented externally as the standard Vec.

use rune_tests::*;
use std::sync::Arc;

fn main() -> runestick::Result<()> {
    let context = Arc::new(rune_modules::default_context()?);

    let input: Vec<i64> = vec![1, 2, 3, 4];

    let output: Vec<i64> = run(
        &context,
        r#"
        pub fn calc(input) {
            let output = 0;

            for value in input {
                output += value;
            }

            [output]
        }
        "#,
        &["calc"],
        (input,),
    )?;

    println!("{:?}", output);
    Ok(())
}
$> cargo run --example vector
[10]

If you have a vector which has values of non-uniform types, you can use VecTuple to deal with them.

use rune_tests::run;
use runestick::VecTuple;
use std::sync::Arc;

fn main() -> runestick::Result<()> {
    let context = Arc::new(rune_modules::default_context()?);

    let input: VecTuple<(i64, String)> = VecTuple::new((1, String::from("Hello")));

    let output: VecTuple<(i64, String)> = run(
        &context,
        r#"
        pub fn calc(input) {
            let a = input[0] + 1;
            let b = `{input[1]} World`;
            [a, b]
        }
        "#,
        &["calc"],
        (input,),
    )?;

    let VecTuple((a, b)) = output;
    println!("({:?}, {:?})", a, b);
    Ok(())
}
$> cargo run --example vec_tuple
(2, "Hello World")