# Which Lua environment should I use with LuaTeX (LuaLaTeX)?

## Lua code environment

I moved on to XeTeX (XeLaTeX) a while ago. I was using pdfLaTeX before that, but now I'm quite comfortable with XeLaTeX.

Now, I'd like to use LuaLaTeX to embed Lua in some LaTeX documents. The doc states several ways to embed Lua in TeX, but they confuse me more than actually explain what I need to know about embedding Lua.

There's \directlua{ ... }, \luacode ... \endluacode, and \begin{luacode} ... \end{luacode} with the luacode package. The dots (...) is where Lua code would go.

Now, which one should I use?


Now to your second question about Saving variables. If you don't declare your variables local, they are accessible in all Lua chunks. But you are asking to pass Lua code to TeX. You can do this for example:

\begin{luacode*}
tex.sprint("\setcounter{mycounter}{" .. my_lua_value .. "}")
\end{luacode*}


to create a \setcounter command with your value. Or you can use the tex.count Lua interface:

\begin{luacode*}
tex.count[10] = my_lua_value
\end{luacode*}


and your value is in \count10. But this is a bit dangerous as you have to be certain to use a free counter.

-
Thanks for clarifying. When defining a command, couldn't I use \directlua{} just as well? Or is there a significant difference with \luaexec{}? –  polemon Oct 30 '11 at 18:50
@polemon You can use \directlua{} instead. But all kinds of characters will spoil your experience: %, \ , --, \\  and ~. You have to be careful and escape them. I strongly suggest to define a function in a separate lua file and call that function from your \directlua{} or \luaexec{} command. Then you don't have to worry about TeX interpreting some funny characters even before Lua gets to see them. –  topskip Oct 30 '11 at 19:05
Your example with \repeat{4}{Hello world\par} does not work here with LuaTeX from MiKTeX 2.9. I get the error message { for i=1,4 do tex.sprint("\luatexluaescapestring {Hello world ! Paragraph ended before \luaexec was complete. <to be read again> \par l.28 \repeat{4}{Hello world\par} It works nicely without \par though, is this somehow not allowed in this command? –  Alexander Aug 25 '12 at 12:22
@Alexander thanks for the pointer. My example was broken. I can't really tell why it failed due to lack of internal insight. –  topskip Aug 25 '12 at 13:04
@MartinSchröder have you tried tex.tprint()? Without looking at the manual, I guess the following could do: tex.tprint({"\\"},{-2,"foo@bar"}). But IIRC -2 changes the catcodes to 'other' which doesn't help with command names. Perhaps surround this with \makeat...? –  topskip Sep 13 '12 at 17:56