# Formatting table with a lua for loop

I was trying to get a table like this

  1
2 3 4
5 6 7
8 9 10


with this function

function myTable()
t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for k = 1, #t do
if k == 1 then
tex.print(string.format([["& %d & \\"]], t[1]))
else
tex.print(string.format([["%d & %d & %d \\"]],
t[k], t[k + 1], t[k + 2]))
k = k + 2
end
end
end


but it says:

ua:25: bad argument #4 to 'format' (number expected, got nil)


How to do that? Looks like lua's got a weird way of implementing for loop, am I wrong?

In my document I've:

\documentclass{article}
\setmainfont{Kalpurush}[RawFeature={mode=harf}]
\parindent 0pt
\directlua{require("test.lua")}

\begin{document}

\begin{table}[h]
\centering
\begin{tabular}{ccc}
\directlua{myTable()}
\end{tabular}
\end{table}

\end{document}


From the lua.org site:

... you should never change the value of the control variable [of a for loop]: The effect of such changes is unpredictable.

In short, it's not a good idea to increment the value of k (the control variable of your for loop) "by hand".

I therefore think that you should use a while loop instead of a for loop. Then, increment k by 1 if k==1 is true and by 3 if it is not. Finally, you should omit the " symbols from the first argument of string.format; alternatively, omit the [[ and ]] directives and replace \\ with \\\\.)

\documentclass{article}
\usepackage{luacode}
\begin{luacode}
function myTable()
t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
k=1
while k<#t do
if k == 1 then
tex.print(string.format([[ & %d & \\]], t[k]))
k=k+1
else
tex.print(string.format([[%d & %d & %d \\]],
t[k], t[k + 1], t[k + 2]))
k = k + 3
end
end
end
\end{luacode}

\begin{document}
\begin{tabular}{ccc}
\directlua{myTable()}
\end{tabular}
\end{document}