![从外部 Lua 文件中读取表并打印其内容](https://linux22.com/image/477978/%E4%BB%8E%E5%A4%96%E9%83%A8%20Lua%20%E6%96%87%E4%BB%B6%E4%B8%AD%E8%AF%BB%E5%8F%96%E8%A1%A8%E5%B9%B6%E6%89%93%E5%8D%B0%E5%85%B6%E5%86%85%E5%AE%B9.png)
我正在做一个创建闪存卡的项目,我已经将想要包含在闪存卡中的字符串保存在一个名为的外部文件中
all_text.lua
,数据以链接列表的形式存储在表单中list = {next = list, value = {'front of the flash card', 'back of the flashcard'}}
,现在我想为每个元素创建一个闪存卡list
;也就是说,给出命令
\begin{flashcard}{front of the flashcard}
back of the flashcard
\end{flashcard}
我尝试过
\begin{luacode}
local l = list
while l do
front = l.value[1]
back = l.value[2]
tex.sprint('\string\\begin{flashcard}{'.. front .. '}')
tex.sprint( back .. '\string\\end{flashcard}')
end
\end{luacode}
有什么建议么?
答案1
正如我在评论中所写,我不确定实际的问题是什么,但提供的代码中的一个问题是无限循环:
循环变量l
永远不会改变,因此while
条件永远不会改变。这导致循环输出第一张牌的无限重复。这可以通过l=l.next
在循环末尾添加以下内容来解决:
\documentclass{article}
\usepackage{luacode}
\newenvironment{flashcard}[1]{\paragraph{Front}#1\paragraph{Back}}{}
\begin{document}
\begin{luacode*}
local list
list = {next = list, value = {"Front of the last card", "Back of the last card"}}
list = {next = list, value = {"Front of the middle card", "Back of the middle card"}}
list = {next = list, value = {"Front of the first card", "Back of the first card"}}
local l = list
while l do
local front, back = table.unpack(l.value)
tex.sprint('\\begin{flashcard}{'.. front .. '}')
tex.sprint( back .. '\\end{flashcard}')
l = l.next
end
\end{luacode*}
\end{document}