4

I have this code that I copied from What is a simple example of something you can do with 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}

However, this code doesn't compile.

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

I googled, and from this post lualatex and string.format, I learned that the code is not working anymore .

\luaexec can contain the control character, but it doesn't seem to accept multiple Lua commands, so I had to use \luaexec for the last line of code.

\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))}
}

I'm not sure this is the best way to use format string in LuaTeX, what might be other options?

prosseek
  • 6,033

1 Answers1

6

Making the Lua code in luacode* environment, and call the function in \luaexec may be other solution.

\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}
prosseek
  • 6,033
  • 1
    Since the Lua-side code contains no backslash characters, it would be OK to place it in a luacode rather than a luacode* environment. Similarly, since the TeX-side code that invokes the Lua function contains no backslash or percent characters, it would also be OK to use \directlua instead of \luaexec in the definiton of \score. – Mico Mar 12 '15 at 09:34