diff --git a/CHANGELOG.md b/CHANGELOG.md index 0012e3d..4415540 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - 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 [#224]: https://github.com/lune-org/lune/pull/224 diff --git a/crates/lune-utils/src/fmt/value/recursive.rs b/crates/lune-utils/src/fmt/value/recursive.rs index d8c7f4c..ca20429 100644 --- a/crates/lune-utils/src/fmt/value/recursive.rs +++ b/crates/lune-utils/src/fmt/value/recursive.rs @@ -4,6 +4,7 @@ use std::fmt::{self, Write as _}; use mlua::prelude::*; +use super::metamethods::{call_table_tostring_metamethod, get_table_type_metavalue}; use super::{ basic::{format_value_styled, lua_value_as_plain_string_key}, config::ValueFormatConfig, @@ -46,7 +47,12 @@ pub(crate) fn format_value_recursive( let mut buffer = String::new(); 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("{ ... }"))?; } else if !visited.insert(LuaValueId::from(t)) { write!(buffer, "{}", STYLE_DIM.apply_to("{ recursive }"))?; @@ -164,3 +170,15 @@ fn format_table( }) .collect() } + +fn format_typename_and_tostringed( + typename: Option, + tostringed: Option, +) -> Option { + 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, + } +}