From 1c0b1014eec84f42450cda8257545fd7d6d5d988 Mon Sep 17 00:00:00 2001 From: kyren Date: Mon, 5 Jun 2017 01:46:45 -0400 Subject: [PATCH] Improve performance of create_table / create_array_table --- Cargo.toml | 2 +- src/lua.rs | 24 +++++++++++++----------- src/tests.rs | 7 +++++++ 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 74abdbb..85da801 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rlua" -version = "0.4.5" +version = "0.4.6" authors = ["kyren "] description = "High level bindings to Lua 5.3" repository = "https://github.com/chucklefish/rlua" diff --git a/src/lua.rs b/src/lua.rs index 4d02af8..049dddb 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -822,24 +822,26 @@ impl Lua { V: ToLua<'lua>, I: IntoIterator { - let table = self.create_empty_table()?; - for (k, v) in cont { - table.set(k, v)?; + unsafe { + stack_guard(self.state, 0, || { + check_stack(self.state, 3)?; + ffi::lua_newtable(self.state); + + for (k, v) in cont.into_iter() { + self.push_value(self.state, k.to_lua(self)?)?; + self.push_value(self.state, v.to_lua(self)?)?; + ffi::lua_rawset(self.state, -3); + } + Ok(LuaTable(self.pop_ref(self.state))) + }) } - Ok(table) } pub fn create_array_table<'lua, T, I>(&'lua self, cont: I) -> LuaResult where T: ToLua<'lua>, I: IntoIterator { - let table = self.create_empty_table()?; - let mut index = 1; - for elem in cont { - table.set(index, elem)?; - index += 1; - } - Ok(table) + self.create_table(cont.into_iter().enumerate().map(|(k, v)| (k + 1, v))) } pub fn create_function(&self, func: F) -> LuaResult diff --git a/src/tests.rs b/src/tests.rs index 5a499ef..2632d3e 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -77,6 +77,13 @@ fn test_table() { assert_eq!(table3.length().unwrap(), 5); assert_eq!(table3.array_values::>().unwrap(), vec![Some(1), Some(2), None, Some(4), Some(5)]); + + lua.set("table4", + lua.create_array_table(vec![1, 2, 3, 4, 5]).unwrap()) + .unwrap(); + let table4 = lua.get::<_, LuaTable>("table4").unwrap(); + assert_eq!(table4.pairs::().unwrap(), + vec![(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]); } #[test]