3

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.

1
  • Welcome to TeX.SE.
    – Mico
    Sep 25, 2022 at 15:49

2 Answers 2

4

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.

0

You define \scoretable but you call \scortable which you haven't defined.

2
  • 1
    There's a deeper issue, beyond the typo in \scortable, with the OP's Lua code: It doesn't work at present, in part because the OP has failed to replace single-backslashes with double-backslashes.
    – Mico
    Sep 25, 2022 at 18:32
  • Sorry, that's a typing mistake, I didn't type incorrectly in my document.
    – youthdoo
    Sep 26, 2022 at 4:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .