Find error: Using Lualatex to print a table

luacodeluatex

I have 题 as a counter. I'm using LuaLaTeX and loaded the luacode package.

\newcommand{\scoretable}{
    \directlua{
        tex.print("\begin{tabular}{|c|")
        for i=1,\the题 do
        tex.print("c|") end
        tex.print("}\hline 题号")
        for i=1,\the题 do
        tex.print("&") tex.print(i) end
        tex.print("\\\hline\end{tabular}")
    }
}

Could anyone find the mistake? When I use this command \scortable it says it's not defined meaning that there's an error in the definition. Code above is in the .cls file.

Best Answer

The following modified version of your code works. :-)

The main change, really, is not to expand \the题 inside the Lua code block. Instead, I suggest expanding the value of the counter first and then passing it to Lua. Also, note that \ (backslash) is the generic "escape character" in Lua. Hence, one must write \\ in Lua to generate a single \ character for further prosessing by TeX.

enter image description here

\documentclass{article} % or some other suitable document class
\usepackage{array}      % for "\extrarowheight" length parameter
\usepackage{fontspec}
\setmainfont{Noto Serif SC} % or some other suitable font
\newcounter{题}

\usepackage{luacode} % for "luacode" environment
\begin{luacode}
function scoretable ( n )
    local s 
    s = "\\begin{tabular}{|c|" 
    for i = 1 , n do 
       s = s .. "c|" 
    end
    s = s .. "} \\hline 题号" 
    for i = 1 , n do 
       s = s.."&"..i 
    end
    s = s .. "\\\\ \\hline \\end{tabular}"
    tex.sprint ( s )
end
\end{luacode}

%% LaTeX utility macro:
\newcommand\scoretable[1]{\directlua{scoretable(#1)}}

\begin{document}
\setlength\extrarowheight{2pt} % make the table look less cramped
\setcounter{题}{8}

\scoretable{\the题}

\end{document}

Addendum: If you wanted to stay closer to your original setup, I suggest you define the LaTeX macro called \scoretable via

\newcommand{\scoretable}[1]{
    \directlua{
        tex.sprint ( "\\begin{tabular}{|c|" )
        for i = 1,#1 do tex.sprint ( "c|" ) end
        tex.sprint ( "}\\hline 题号" )
        for i = 1,#1 do tex.sprint ( "&"..i ) end
        tex.sprint("\\\\ \\hline \\end{tabular}")
    }
}

and invoke it as follows: \scoretable{\the题}. Note the use of \\ instead of \, as well as the fact the macro is defined to take an argument.

Related Question