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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use std::marker::PhantomData;

use libc;

use td_clua::{self, lua_State};
use LuaGuard;
use LuaPush;
use LuaRead;
/// Represents a table stored in the Lua context.
///
/// Loading this type mutably borrows the Lua context.
pub struct LuaTable {
    table: *mut lua_State,
    pop: i32,
    index: i32,
}

impl LuaRead for LuaTable {
    fn lua_read_with_pop(lua: *mut lua_State, index: i32, pop: i32) -> Option<LuaTable> {
        if unsafe { td_clua::lua_istable(lua, index) } {
            for _ in 0..pop {
                unsafe {
                    td_clua::lua_pushnil(lua);
                }
            }
            Some(LuaTable {
                table: lua,
                pop: pop,
                index: index,
            })
        } else {
            None
        }
    }
}

impl Drop for LuaTable {
    fn drop(&mut self) {
        if self.pop != 0 {
            unsafe {
                td_clua::lua_pop(self.table, self.pop);
            };
            self.pop = 0;
        }
    }
}

/// Iterator that enumerates the content of a Lua table.
// while the LuaTableIterator is active, the current key is constantly pushed over the table
pub struct LuaTableIterator<'t, K, V> {
    table: &'t mut LuaTable,
    finished: bool, // if true, the key is not on the stack anymore
    marker: PhantomData<(K, V)>,
}

impl LuaTable {
    /// Destroys the LuaTable and returns its inner Lua context. Useful when it takes Lua by value.
    pub fn into_inner(self) -> *mut lua_State {
        self.table
    }

    /// Iterates over the elements inside the table.
    pub fn iter<K, V>(&mut self) -> LuaTableIterator<K, V> {
        unsafe { td_clua::lua_pushnil(self.table) };

        LuaTableIterator {
            table: self,
            finished: false,
            marker: PhantomData,
        }
    }

    /// Loads a value in the table given its index.
    pub fn query<'a, R, I>(&'a mut self, index: I) -> Option<R>
    where
        R: LuaRead,
        I: LuaPush,
    {
        index.push_to_lua(self.table);
        unsafe {
            td_clua::lua_gettable(
                self.table,
                if self.index > 0 {
                    self.index
                } else {
                    self.index - 1
                },
            );
        }
        let _guard = LuaGuard::new(self.table, 1);
        LuaRead::lua_read_with_pop(self.table, -1, 1)
    }

    /// Inserts or modifies an elements of the table.
    pub fn set<I, V>(&mut self, index: I, value: V)
    where
        I: LuaPush,
        V: LuaPush,
    {
        index.push_to_lua(self.table);
        value.push_to_lua(self.table);
        unsafe {
            td_clua::lua_settable(
                self.table,
                if self.index > 0 {
                    self.index
                } else {
                    self.index - 2
                },
            );
        }
    }

    /// Inserts or modifies an elements of the table.
    pub fn register<I>(&mut self, index: I, func: extern "C" fn(*mut lua_State) -> libc::c_int)
    where
        I: LuaPush,
    {
        index.push_to_lua(self.table);
        unsafe {
            td_clua::lua_pushcfunction(self.table, func);
            td_clua::lua_settable(
                self.table,
                if self.index > 0 {
                    self.index
                } else {
                    self.index - 2
                },
            );
        }
    }

    // /// Inserts an empty table, then loads it.
    pub fn empty_table<I>(&mut self, index: I) -> LuaTable
    where
        I: LuaPush + Clone,
    {
        index.clone().push_to_lua(self.table);
        unsafe {
            td_clua::lua_newtable(self.table);
            td_clua::lua_settable(
                self.table,
                if self.index > 0 {
                    self.index
                } else {
                    self.index - 2
                },
            );
        }
        self.query(index).unwrap()
    }

    pub fn table_len(&mut self) -> usize {
        unsafe { td_clua::lua_rawlen(self.table, self.index) }
    }

    // /// Obtains or create the metatable of the table.
    pub fn get_or_create_metatable(&mut self) -> LuaTable {
        let result = unsafe { td_clua::lua_getmetatable(self.table, self.index) };

        if result == 0 {
            unsafe {
                td_clua::lua_newtable(self.table);
                td_clua::lua_setmetatable(self.table, -2);
                let r = td_clua::lua_getmetatable(self.table, self.index);
                assert!(r != 0);
            }
        }

        LuaTable {
            table: self.table,
            pop: 1,
            index: -1,
        }
    }
}

impl<'t, K, V> Iterator for LuaTableIterator<'t, K, V>
where
    K: LuaRead + 'static,
    V: LuaRead + 'static,
{
    type Item = Option<(K, V)>;

    fn next(&mut self) -> Option<Option<(K, V)>> {
        if self.finished {
            return None;
        }
        let state = self.table.table;
        // this call pushes the next key and value on the stack
        if unsafe { !td_clua::lua_istable(state, -2) || td_clua::lua_next(state, -2) == 0 } {
            self.finished = true;
            return None;
        }

        let key = LuaRead::lua_read_at_position(state, -2);
        let value = LuaRead::lua_read_at_position(state, -1);
        // removing the value, leaving only the key on the top of the stack
        unsafe { td_clua::lua_pop(state, 1) };

        if key.is_none() || value.is_none() {
            Some(None)
        } else {
            Some(Some((key.unwrap(), value.unwrap())))
        }
    }
}

impl<'t, K, V> Drop for LuaTableIterator<'t, K, V> {
    fn drop(&mut self) {
        if !self.finished {
            unsafe { td_clua::lua_pop(self.table.table, 1) }
        }
    }
}