diff --git a/src/table.rs b/src/table.rs index d09b6622..ddf3ff35 100644 --- a/src/table.rs +++ b/src/table.rs @@ -778,13 +778,8 @@ impl Table { let mut pairs = self.pairs::().flatten().collect::>(); // Sort keys pairs.sort_by(|(a, _), (b, _)| a.sort_cmp(b)); - let is_sequence = pairs.iter().enumerate().all(|(i, (k, _))| { - if let Value::Integer(n) = k { - *n == (i + 1) as Integer - } else { - false - } - }); + let is_sequence = (pairs.iter().enumerate()) + .all(|(i, (k, _))| matches!(k, Value::Integer(n) if *n == (i + 1) as Integer)); if pairs.is_empty() { return write!(fmt, "{{}}"); } @@ -797,14 +792,14 @@ impl Table { writeln!(fmt, ",")?; } } else { + fn is_simple_key(key: &[u8]) -> bool { + key.iter().take(1).all(|c| c.is_ascii_alphabetic() || *c == b'_') + && key.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_') + } + for (key, value) in pairs { match key { - Value::String(key) - if key - .to_string_lossy() - .chars() - .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_')) => - { + Value::String(key) if is_simple_key(&key.as_bytes()) => { write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?; write!(fmt, " = ")?; } diff --git a/tests/table.rs b/tests/table.rs index d6cc90f7..d2e49363 100644 --- a/tests/table.rs +++ b/tests/table.rs @@ -414,6 +414,9 @@ fn test_table_fmt() -> Result<()> { "{\n [false] = false,\n [true] = true,\n [1] = 1,\n [1.99] = 1.99,\n [2] = 2,\n [3] = 3,\n [9.2] = 9.2,\n a = 5,\n b = {\n 6,\n },\n [\"special-\"] = 10,\n}" ); + let table2 = lua.create_table_from([("1", "first"), ("2", "second")])?; + assert_eq!(format!("{table2:#?}"), "{\n [\"1\"] = \"first\",\n [\"2\"] = \"second\",\n}"); + Ok(()) }