Skip to content

Commit

Permalink
Fix type and tostring metamethods not always being respected during t…
Browse files Browse the repository at this point in the history
…able formatting
  • Loading branch information
filiptibell committed Aug 10, 2024
1 parent 98b31b9 commit ea70133
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 19 additions & 1 deletion crates/lune-utils/src/fmt/value/recursive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 }"))?;
Expand Down Expand Up @@ -164,3 +170,15 @@ fn format_table(
})
.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,
}
}

0 comments on commit ea70133

Please sign in to comment.