![如何从外部化的 tikz 图片全局修改变量?](https://linux22.com/image/477945/%E5%A6%82%E4%BD%95%E4%BB%8E%E5%A4%96%E9%83%A8%E5%8C%96%E7%9A%84%20tikz%20%E5%9B%BE%E7%89%87%E5%85%A8%E5%B1%80%E4%BF%AE%E6%94%B9%E5%8F%98%E9%87%8F%EF%BC%9F.png)
是否可以从外部化的 tikz 图片中更新全局变量?
我希望全局修饰符(在本例中\tl_gput_right:Nn
)能够超越 tikz 图片的范围。
以下是 MWE:
\documentclass{article}
\usepackage [utf8] {inputenc}
\usepackage {tikz}
\usepackage {xparse}
% Setup externalization.
\usetikzlibrary{external}
\tikzexternalize[prefix=images/]
\tikzset{png export/.style={external/system call/.add={}{; convert -density 300 "\image.pdf" "\image.png"}}}
\tikzset{png export}
% Declare global variable.
\ExplSyntaxOn
\tl_clear_new:N \something
\ExplSyntaxOff
\begin {document}
\ExplSyntaxOn
% Draw a picture and update global variable.
\begin{tikzpicture}
\draw node {aaa};
\tl_gput_right:Nn \something {AAA}
\tl_log:N \something % Value is "AAA".
\end{tikzpicture}
% Print global variable afterwards.
\tl_log:N \something % Value is "".
\ExplSyntaxOff
\end {document}
我希望最后\tl_log:N
显示的值AAA
就像externalization
部分被注释掉一样。
答案1
作为菲利佩·奥莱尼克根据评论中的建议,我最终将数据从tikzpicture
环境写入外部文件,然后在tikzpicture
结束时将其读回。
一种方法是:
\documentclass{article}
\usepackage [utf8] {inputenc}
\usepackage {tikz}
\usepackage {xparse}
% Setup externalization.
\usetikzlibrary{external}
\tikzexternalize[prefix=images/]
\tikzset{png export/.style={external/system call/.add={}{; convert -density 300 "\image.pdf" "\image.png"}}}
\tikzset{png export}
% Declare global variables.
\ExplSyntaxOn
% Streams for reading and writing to file.
\iow_new:N \output_stream
\ior_new:N \input_stream
\tl_clear_new:N \something
\ExplSyntaxOff
\begin {document}
\ExplSyntaxOn
% Draw a picture and update global variable.
\begin{tikzpicture}
\draw node {aaa};
\tl_gput_right:Nn \something {AAA}
\tl_log:N \something % Value is "AAA".
% Store data in file to use it outside of tikzpicture.
\iow_open:Nn \output_stream {stored_data}
\iow_now:Nx \output_stream {\something} % You can generate \iow_now:NV variant instead of \iow_now:Nx
\iow_close:N \output_stream
\end{tikzpicture}
% Read stored data from file.
\ior_open:Nn \input_stream {stored_data}
\ior_get:NN \input_stream \something
\ior_close:N \input_stream
% Print global variable afterwards.
\tl_log:N \something % Value is now "AAA".
\ExplSyntaxOff
\end {document}