How can I convert data types?

Hellow ! Pleas tell my how i convert data types ?
For example i have a function that takes a positional parameter and i need to make it convert from text type to content type, from int to text or content and so on

let function(param1) = {

}

Don’t ask me why I need this.
thanks!

Just write if type(x) == str { … } else { … }.

If you don’t know which type should be used, inspect with panic(repr(type(…))).

If you need content and have a string (text) or numbers, it will convert automatically.

If you need to convert to another type, you can ususally use the target type name as a constructor, e.g. str(2) gives "2".
See the respective documentations on what can be converted from:

(Converting from content is usually not easily possible, and should be avoided)

1 Like

I think a string will always be permitted where content is expected (because @laurmaedje said so, which I regard as even more reliable than documentation :laughing:) while numbers are not always permitted. For example #grid(1) will unfortunately not compile. For numbers we interpolate them into content like this: #let n = 1; #grid([#n]).

Pleas, tell my how can i convert content type to str type, or int, float ?

Please avoid doing this. Whenever possible, try to only create content from data that has been processed completely already.

That being said, if necessary, you can the following function to convert it to a string which works most of the time (sometimes, it breaks in “fun” and “exciting” ways though):

Cursed Code
/// -> string
#let _to-string(
  /// -> content
  content,
) = {
  if content == none { "" } else if type(content) == str { content } else if type(content) == array {
    content.map(_to-string).join(", ")
  } else if content.has("text") { content.text } else if content.has("children") {
    if content.children.len() == 0 { "" } else { content.children.map(_to-string).join("") }
  } else if content.has("child") { _to-string(content.child) } else if content.has("body") {
    _to-string(_to-string(content.body))
  } else if content == [] { "" } else if content == [ ] { " " } else if content.func() == ref { "_ref_" } else {
    let offending = content
    ""
  }
}

(From a string you can then convert to int/float as usual)

2 Likes