Fix type and tostring metamethods not always being respected during table formatting

This commit is contained in:
Filip Tibell 2024-08-10 13:01:13 +02:00
parent 98b31b9f67
commit ea7013322f
No known key found for this signature in database
2 changed files with 20 additions and 1 deletions

View file

@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Fixed `fs.readDir` with trailing forward-slash on Windows ([#220]) - Fixed `fs.readDir` with trailing forward-slash on Windows ([#220])
- Fixed `__type` and `__tostring` metamethods not always being respected when formatting tables
[#220]: https://github.com/lune-org/lune/pull/220 [#220]: https://github.com/lune-org/lune/pull/220
[#224]: https://github.com/lune-org/lune/pull/224 [#224]: https://github.com/lune-org/lune/pull/224

View file

@ -4,6 +4,7 @@ use std::fmt::{self, Write as _};
use mlua::prelude::*; use mlua::prelude::*;
use super::metamethods::{call_table_tostring_metamethod, get_table_type_metavalue};
use super::{ use super::{
basic::{format_value_styled, lua_value_as_plain_string_key}, basic::{format_value_styled, lua_value_as_plain_string_key},
config::ValueFormatConfig, config::ValueFormatConfig,
@ -46,7 +47,12 @@ pub(crate) fn format_value_recursive(
let mut buffer = String::new(); let mut buffer = String::new();
if let LuaValue::Table(ref t) = value { if let LuaValue::Table(ref t) = value {
if depth >= config.max_depth { if let Some(formatted) = format_typename_and_tostringed(
get_table_type_metavalue(t),
call_table_tostring_metamethod(t),
) {
write!(buffer, "{formatted}")?;
} else if depth >= config.max_depth {
write!(buffer, "{}", STYLE_DIM.apply_to("{ ... }"))?; write!(buffer, "{}", STYLE_DIM.apply_to("{ ... }"))?;
} else if !visited.insert(LuaValueId::from(t)) { } else if !visited.insert(LuaValueId::from(t)) {
write!(buffer, "{}", STYLE_DIM.apply_to("{ recursive }"))?; write!(buffer, "{}", STYLE_DIM.apply_to("{ recursive }"))?;
@ -164,3 +170,15 @@ fn format_table(
}) })
.collect() .collect()
} }
fn format_typename_and_tostringed(
typename: Option<String>,
tostringed: Option<String>,
) -> Option<String> {
match (typename, tostringed) {
(Some(typename), Some(tostringed)) => Some(format!("<{typename}({tostringed})>")),
(Some(typename), None) => Some(format!("<{typename}>")),
(None, Some(tostringed)) => Some(tostringed),
(None, None) => None,
}
}