这个问题涉及 Lua 协程,这是我想要在 Lua/LuaTeX 脚本中访问的功能。以下代码片段有的带参数,有的不带参数(对于后者,这是我的最终目标)。
作为 Lua/LuaTeX 脚本的初学者,我尝试了很多次,但都没有成功,但最初的错误对于专家来说肯定是显而易见的。在阅读了几篇帖子和文档后,声明协程有两种方式:通过命名函数或不通过命名函数。对于这两种方式,问题似乎来自 and coroutine.yield
(和/或)coroutine.results
函数。
我看到的几个 LuaTeX 示例是 2010/2011 年的;在此期间可能有一些修改。如果发生更改,我错过了什么?因此,为什么我的编码是“肮脏的”?(目前对我来说调试起来有点困难)
代码测试
\documentclass{article}
\usepackage{luacode}
\begin{luacode}
-- Main function of the coroutine
--function luadisplay (argval)
-- tex.print("..argval..")
function luadisplay ()
for i = 0, 1, 1 do
if i==0 then
tex.print{"OK0"}
tex.print(coroutine.yield())
end
if i==1 then
tex.print{"OK1"}
tex.print(coroutine.yield())
end
end
end
-- Creating coroutine
luacoroutine = coroutine.create(luadisplay)
-- Starting and obtaining results
--tex.print("coroutine.resume(luacoroutine)") -- Does not work if "coroutine.yield" uncommented
\end{luacode}
\begin{luacode} -- That's compile but can't obtain result
-- Creating the damned coroutine directly (without argument)
myco = coroutine.create( function()
for i = 0, 1, 1 do
if i==0 then
tex.print{"OK0"}
tex.print(coroutine.yield())
end
if i==1 then
tex.print{"OK1"}
tex.print(coroutine.yield())
end
coroutine.resume(myco)
end
end)
\end{luacode}
%\directlua{require("luatexse.lua")} % If external file
%\newcommand{\luacoroutinecmd}{\directlua{luacoroutine()}} -- Without argument not works
%\newcommand{\luacoroutinecmd}[1]{\directlua{luacoroutine("#1")}} -- With argument not works
%\newcommand{\mycocmd}{\directlua{myco()}} -- Without argument not works
\parindent=0pt
\begin{document}
Is it work?
\bigskip\bigskip
%\luacoroutinecmd{Hi!}
\end{document}
答案1
错误消息显然意味着您正在将协程作为函数调用。通过coroutine.resume
运行调用它不会出错,但我不确定预期的结果是什么。
\documentclass{article}
\usepackage{luacode}
\begin{luacode}
-- Main function of the coroutine
--function luadisplay (argval)
-- tex.print("..argval..")
function luadisplay (m)
for i = 0, 1, 1 do
if i==0 then
tex.print{"OK0[" .. m .. "]"}
tex.print(coroutine.yield())
end
if i==1 then
tex.print{"OK1[" .. m .. "]"}
tex.print(coroutine.yield())
end
end
end
-- Creating coroutine
luacoroutine = coroutine.create(luadisplay)
-- Starting and obtaining results
--tex.print("coroutine.resume(luacoroutine)") -- Does not work if "coroutine.yield" uncommented
\end{luacode}
\newcommand{\luacoroutinecmd}[1]{\directlua{coroutine.resume(luacoroutine,"#1")}} %-- With argument not works
\parindent=0pt
\begin{document}
Is it work?
\bigskip\bigskip
A \luacoroutinecmd{Hi!}
\bigskip\bigskip
B \luacoroutinecmd{Hi!}
\bigskip\bigskip
C \luacoroutinecmd{Hi!}
\end{document}