diff options
-rw-r--r-- | src/table.rs | 41 | ||||
-rw-r--r-- | tests/debug.rs | 2 | ||||
-rw-r--r-- | tests/table.rs | 3 |
3 files changed, 38 insertions, 8 deletions
diff --git a/src/table.rs b/src/table.rs index dc0fb56..9430415 100644 --- a/src/table.rs +++ b/src/table.rs @@ -777,16 +777,45 @@ impl Table { let mut pairs = self.pairs::<Value, Value>().flatten().collect::<Vec<_>>(); // 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 + } + }); if pairs.is_empty() { return write!(fmt, "{{}}"); } writeln!(fmt, "{{")?; - for (key, value) in pairs { - write!(fmt, "{}[", " ".repeat(ident + 2))?; - key.fmt_pretty(fmt, false, ident + 2, visited)?; - write!(fmt, "] = ")?; - value.fmt_pretty(fmt, true, ident + 2, visited)?; - writeln!(fmt, ",")?; + if is_sequence { + // Format as list + for (_, value) in pairs { + write!(fmt, "{}", " ".repeat(ident + 2))?; + value.fmt_pretty(fmt, true, ident + 2, visited)?; + writeln!(fmt, ",")?; + } + } else { + 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' | '_')) => + { + write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?; + write!(fmt, " = ")?; + } + _ => { + write!(fmt, "{}[", " ".repeat(ident + 2))?; + key.fmt_pretty(fmt, false, ident + 2, visited)?; + write!(fmt, "] = ")?; + } + } + value.fmt_pretty(fmt, true, ident + 2, visited)?; + writeln!(fmt, ",")?; + } } write!(fmt, "{}}}", " ".repeat(ident)) } diff --git a/tests/debug.rs b/tests/debug.rs index 3bb6b8b..24c8adc 100644 --- a/tests/debug.rs +++ b/tests/debug.rs @@ -7,7 +7,7 @@ fn test_debug_format() -> Result<()> { // Globals let globals = lua.globals(); let dump = format!("{globals:#?}"); - assert!(dump.starts_with("{\n [\"_G\"] = table:")); + assert!(dump.starts_with("{\n _G = table:")); // TODO: Other cases diff --git a/tests/table.rs b/tests/table.rs index d7a425e..d6cc90f 100644 --- a/tests/table.rs +++ b/tests/table.rs @@ -397,6 +397,7 @@ fn test_table_fmt() -> Result<()> { .load( r#" local t = {1, 2, 3, a = 5, b = { 6 }} + t["special-<chars>"] = 10 t[9.2] = 9.2 t[1.99] = 1.99 t[true] = true @@ -410,7 +411,7 @@ fn test_table_fmt() -> Result<()> { // Pretty print assert_eq!( format!("{table:#?}"), - "{\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 [1] = 6,\n },\n}" + "{\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-<chars>\"] = 10,\n}" ); Ok(()) |