LuaTeX 中的格式化数字打印输出?

LuaTeX 中的格式化数字打印输出?

我有这段代码,我从中复制而来您可以使用 LuaTeX 做什么的简单示例是什么?

\documentclass{article}
\usepackage{luacode}

\def\score#1#2#3{%
    \directlua{
        s1 = #1;
        s2 = #2;
        s3 = #3;

        if s1 > 0 then
            s1 = 11 - s1
        end

        avgscore = (s1 + (10 * s2 / 3) + (10 * s3 / 3)) / 3;

        tex.print("Score 1: ", s1, ", ")
        tex.print("Score 2: ", s2, ", ")
        tex.print("Score 3: ", s3, ", ")
        tex.print("Combined Score: ", string.format("\%0.2f", avgscore))
    }
}

\begin{document}  

\score{8}{3}{0}

\end{document}

但是,该代码无法编译。

! LuaTeX error [\directlua]:1: invalid escape sequence near '\%'.
\score ... ", string.format("\%0.2f", avgscore)) }

我谷歌了一下,然后从这篇文章lualatex 和 string.format,我了解到该代码不再起作用。

\luaexec可以包含控制字符,但它似乎不接受多个 Lua 命令,所以我不得不使用\luaexec最后一行代码。

\usepackage{luatextra}
...
\def\score#1#2#3{%
    \directlua{
        s1 = #1;
        s2 = #2;
        s3 = #3;

        if s1 > 0 then
            s1 = 11 - s1
        end

        avgscore = (s1 + (10 * s2 / 3) + (10 * s3 / 3)) / 3;

        tex.print("Score 1: ", s1, ", ")
        tex.print("Score 2: ", s2, ", ")
        tex.print("Score 3: ", s3, ", ")
    }
    \luaexec{tex.print("Combined Score: ", string.format("\%0.2f", avgscore))}
}

我不确定这是在 LuaTeX 中使用格式字符串的最佳方式,还有哪些其他选择?

答案1

在环境中编写 Lua 代码luacode*,并调用其中的函数\luaexec可能是其他解决方案。

\documentclass{minimal}
\usepackage{luacode}

\begin{luacode*}
function format_print(s1, s2, s3)
    if s1 == 0 then
        s1 = 11 - s1
    end

    avgscore = (s1 + s2 + s3) / 3;
    tex.print("Score 1: ", s1, ", ")
    tex.print("Score 2: ", s2, ", ")
    tex.print("Score 3: ", s3, ", ")
    tex.print("Combined Score: ", string.format("%0.2f", avgscore))
end
\end{luacode*}

\def\score#1#2#3{%
    \luaexec{format_print(#1, #2, #3)}
}

\begin{document}

\score{8}{3}{0}

\end{document}

相关内容