tikzmath 庫中字串變數的條件測試

tikzmath 庫中字串變數的條件測試

是否可以測試 tikzmath 庫中的字串? (例如 if <變數>=<字串表達式> then foo)

我嘗試了一個簡單的測試,它回傳了這個錯誤:

Package PGF Math Error: Unknown function `text' (in ' text== text').

MWE如下:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{math}
\begin{document}
\tikzmath{
    let \str = text;
    if \str == \str then {%
        let \str = bird;
    };
}%
\str
\end{document}

答案1

\tikzmath函數不允許字串比較。您可以使用不同的策略:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{math}
\usepackage{pdftexcmds}

\makeatletter
\newcommand{\strequal}[2]{\pdf@strcmp{#1}{#2}==0}
\makeatother


\begin{document}
\tikzmath{
    let \str = text;
    if \strequal{\str}{\str} then {%
        let \str = bird;
    };
}%
\str

\tikzmath{
    let \str = text;
    if \strequal{\str}{bird} then {%
        let \str = bird;
    };
}%
\str
\end{document}

加載pdftexcmds可確保跨引擎的兼容性。

在此輸入影像描述

答案2

您可以在 a 中使用expl3's (我在using\tl_if_eq:nnTF之外提供了它 ) (但不能在a 中使用,因為它會再次嘗試將字串評估為函數名稱)。\ExplSyntaxOn\cs_set_eq:NNtikzpicture\tikzmath

\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}
\usetikzlibrary{calc}
\usetikzlibrary{math}
\ExplSyntaxOn
\cs_set_eq:NN \tlIfEqnnTF \tl_if_eq:nnTF
\ExplSyntaxOff
\begin{document}
\begin{tikzpicture}
  \tlIfEqnnTF{foo}{bar}
    {\node at (0,0) {correct};}
    {\node at (0,0) {false};}
\end{tikzpicture}
\end{document}

答案3

這是一個基本的 TeX 解決方案。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{math}

\newcommand{\ifstrA}{}% reserve global names
\newcommand{\ifstrB}{}
\newcommand{\ifstr}[4]{% #1 = string A, #2 = stirng B, #3 = true, #4= false
  \def\ifstrA{#1}%
  \def\ifstrB{#2}%
  \ifx\ifstrA\ifstrB #3\relax
  \else #4\relax
  \fi}

\begin{document}
\ifstr{text}{text}{bird}{oops}
\end{document}

相關內容