将环境传递给 \luatexluaescapestring 失败

将环境传递给 \luatexluaescapestring 失败

有人能解释为什么下面的宏\makequesone会失败和/或建议修复吗?逐字选项有效(如在 MWE 中一样),但我希望参数的内容能够包含相对任意的文本和数学内容,因此我认为逐字选项并不理想。

基本要点是将问题列表存储在 lua 表中,然后通过从库中随机选择问题来生成考试。现在,我只是让存储检索部分工作。

第四个参数将包含一个考试问题,我认为\luatexluaescapestring应该使用它来防止不好的事情发生。在下面的工作代码中,我使用了一个v类型参数,但使用m类型参数并仅将参数存储在标记列表中而不对它们执行任何操作不会产生任何错误,所以我觉得问题出在某个地方\luatexluaescapestring,似乎不像\par。“修复”将允许我相对自由地将第四个参数的内容传递给 lua 并使用 检索它\getquestion。无论哪种情况,解释发生了什么都会很好 :)

\documentclass{article}
\usepackage{xparse}
\usepackage{luacode}
\begin{luacode*}

cats = {}
function makequestion(c,id,pt,q)
    -- if question category doesn't exist, then create a table for it
    if not cats[c] then 
      cats[c] = {}
    end
    -- add new question with tag "id" to category "c" table.
    -- question worth "pt" points, and has content "q"
    -- some questions may have entries for the parts subtable
    cats[c][id]={points = pt, ques = q, parts = {}}
end

function getquestion (c,id)
    tex.sprint(cats[c][id].ques)
end

\end{luacode*}

% Adds a question of category #1 and question id #2 to the table.
% the question point value is #3 and the actual question is #4.
% in use, there will be a 5th field for question parts.
% 
% #1 = category
% #2 = id
% #3 = points
% #4 = question

\NewDocumentCommand{\makequesone}{ m m m +m }
    {
        \directlua{makequestion("\luatexluaescapestring{#1}","\luatexluaescapestring{#2}","\luatexluaescapestring{#3}","\luatexluaescapestring{#4}")}
    }

\NewDocumentCommand{\makequestwo}{ m m m v }
    {
        \directlua{makequestion("\luatexluaescapestring{#1}","\luatexluaescapestring{#2}","\luatexluaescapestring{#3}","\luatexluaescapestring{#4}")}
    }

\NewDocumentCommand{\getquestion} { m m }
    {
        \directlua{getquestion("\luatexluaescapestring{#1}","\luatexluaescapestring{#2}")}
    }

\begin{document}
hi
% fails
%\makequesone{factor}{id1}{1}{\begin{itemize}\item fish\end{itemize}}


% works
\makequestwo{factor}{id1}{1}!Here is my question \begin{itemize}\item fish\end{itemize}!

\getquestion{factor}{id1}

\end{document}

答案1

添加\unexpanded\directlua 在将结果传递给 Lua 之前,请先进行宏扩展。另外,请注意宏定义中的空格。

\NewDocumentCommand{\makequesone}{ m m m +m }
 {%
  \directlua{makequestion(%
    "\luatexluaescapestring{#1}",
    "\luatexluaescapestring{#2}",
    "\luatexluaescapestring{#3}",
    "\luatexluaescapestring{\unexpanded{#4}}")}%
 }

相关内容