1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use hashbrown::HashMap;

use crate::value::Value;

pub struct Table {
    data: HashMap<Value, Value>,
    /** replicate standard lua behavior */
    counter: i64,
    id: usize,
}

impl Table {
    pub fn new(id: usize) -> Self {
        Table {
            data: HashMap::new(),
            counter: 0,
            id,
        }
    }
    pub fn insert(&mut self, key: Value, value: Value) {
        self.data.insert(key, value);
    }
    pub fn get(&self, key: &Value) -> Option<&Value> {
        self.data.get(key)
    }
    pub fn get_value(&self, key: &Value) -> Value {
        match self.data.get(key) {
            Some(v) => v.clone(),
            None => Value::Nil,
        }
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }

    /** push by counter's current index, if it aready exists keep incrementing until empty position is found */
    pub fn push(&mut self, value: Value) {
        // DEV this just feels clunky to replicate lua's behavior
        self.counter += 1;
        let mut key = Value::Integer(self.counter);
        while self.data.contains_key(&key) {
            self.counter += 1;
            key.force_to_int(self.counter);
        }
        self.data.insert(key, value);
    }
}

impl ToString for Table {
    fn to_string(&self) -> String {
        format!(
            "table{}[{}]{{{}}}",
            self.id,
            self.data.len(),
            self.data
                .iter()
                .map(|(k, v)| format!("{}: {}", k, v))
                .collect::<Vec<String>>()
                .join(", ")
        )
    }
}