我一直在尝试编写一段 ConTeXt 代码,用从 ConTeXt 端解析的变量填充持久性 lua 数组,但出于某种原因,似乎每次\question{}{}{}
调用都会执行两次,导致数组的总值是应有值的两倍,长度也是应有值的两倍。这是预期的行为吗?我只是不明白 ConTeXt 如何解析 lua 代码,还是存在我看不到的错误?
\setuppapersize[A4]
\usepath[Assets]
\startluacode
userdata = userdata or {}
qVals={}
table.reduce = function (list, fn)
local acc
for k, v in ipairs(list) do
if 1== k then
acc = v
else
acc = fn(acc, v)
end
end
return acc
end
local sumT = function (a, b)
return a +b
end
function userdata.getQval(weight, question)
qVals[#qVals+1]=tonumber(weight)
tot = table.reduce(qVals, sumT)
context("(" .. weight .. " points) " .. question .. " " .. tot)
end
\stopluacode
\defineenumeration[questionEnumeration]
[
text={},
title=yes,
titlestyle=bold,
titleright={},
titleleft={},
]
\def\getQuestionVal#1#2{%
\ctxlua{userdata.getQval([==[#1]==], [==[#2]==])}%
}
\def\question#1#2#3{%
\startquestionEnumeration[title=\getQuestionVal{#1}{#2}]
\doifmodeelse{key}{\startcolor[red]#3\stopcolor}{\blank[#1*2em]}
\stopquestionEnumeration
}
\starttext
%\enablemode[key]
\question{3}{This is the question}{this is its sol}
\question{7}{Another question}{another sol}
\question{5}{and another}{yet another sol}
\stoptext
PS:我已经找到了一种解决方法,即使用一个递增的数字作为数组索引(从而覆盖重复项),但如果存在的话,我更喜欢真正的解决方案。
答案1
当您使用枚举或描述设置时,为了获得标题长度的正确尺寸,width=fit
ConTeXt 必须在标题的完整内容中进行试运行。
当您现在遇到随着标题而增加值的情况时,您必须使用trialtypesetting
条件或模式来阻止增加值。
\defineenumeration [question] [text=Question ,title=yes]
\definecounter[testcounter]
\starttext
\startquestion[title={Testcounter: \incrementedcounter[testcounter]}]
First question
\stopquestion
\startquestion[title={Testcounter: \incrementedcounter[testcounter]}]
Second question
\stopquestion
\startquestion[title={Testcounter: \iftrialtypesetting\else\incrementedcounter[testcounter]\fi}]
Third question
\stopquestion
\startquestion[title={Testcounter: \doifnotmode{*trialtypesetting}{\incrementedcounter[testcounter]}}]
Fourth question
\stopquestion
\stoptext