無法使用協程編譯 Lua/LuaTeX 腳本 [coroutine.yield] 與

無法使用協程編譯 Lua/LuaTeX 腳本 [coroutine.yield] 與

這個問題涉及 Lua 協程,這是我想在 Lua/LuaTeX 腳本中訪問的功能。以下片段無論是否通過參數(對於後者,這就是我想要的最終目標)。

作為 Lua/LuaTeX 腳本的初學者,我做了很多嘗試/錯誤但沒有成功,但原始錯誤對於專家來說肯定是顯而易見的。在閱讀了幾篇文章和文件後,可以使用兩種方向來聲明協程:透過命名函數或不透過命名函數。對於這兩種做法,問題似乎來自coroutine.yieldand (和/或)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}

相關內容