# Pass and run a TeX macro from Lua

``````\starttext

\startluacode
userdata = userdata or {}

function userdata.simple(c)
context("\\%s{%s}{%s}",c,1,4)
context.par()
context[c](1,4)
end
\stopluacode

\define[1]\tolua{\ctxlua{userdata.simple("#1")}}

\define[2]\simple{-#1#2-}

\simple{22}{55}

% This is what I have to do, because the below causes an error:
\tolua{simple}

% This is what I'd prefer, because the above feels like a confusing mix of Lua and TeX:
\tolua{\simple}

\stoptext
``````

Here we're passing a TeX macro (`\simple`) into Lua, then calling it from Lua. It works but the goal is to write `\tolua{\simple}` instead of `\tolua{simple}`. I think the error I'm getting has to do with the TeX macro being expanded.

• After reading the question, I have no idea what you are trying to do, or what your question is. Could you add any information about what you are trying to archive instead of only writing what you want to avoid? Feb 12 '20 at 17:56
• please don't edit the answer into the question it makes the post format very confusing for later readers. You can post an answer to your own question. Feb 12 '20 at 19:18

## 2 Answers

To pass macros from TeX to Lua, a common idiom has to be followed:

``````\directlua{whatever("\luaescapestring{\unexpanded{#1}}")}
``````

In ConTeXt some of the things have different names, so the idiom would read

``````\ctxlua{whatever("\luaescapestring{\normalunexpanded{#1}}")}
``````

With that your code works without problems.

``````\starttext

\startluacode
userdata = userdata or {}

function userdata.simple(c)
context("%s{%s}{%s}",c,1,4)
end
\stopluacode

\define[1]\tolua{\ctxlua{userdata.simple("\luaescapestring{\normalunexpanded{#1}}")}}

\define[2]\simple{-#1#2-}

\simple{22}{55}

\tolua{\simple}

\stoptext
``````

So the error I was getting with `\tolua{\simple}` doesn't have anything to do with `\simple` being expanded within the `\ctxlua` block, but simply that `\s` in `"\simple"` was triggering an invalid Lua escape sequence. Not the error I was expecting - I thought I'd have to use `\noexpand`. But this is all that needs to be done:

``````\starttext

\startluacode
userdata = userdata or {}

function userdata.simple(c)
context("%s{%s}{%s}",c,1,4)
end
\stopluacode

\define[1]\tolua{\ctxlua{userdata.simple([==[#1]==])}}

\define[2]\simple{-#1#2-}

\simple{22}{55}

\tolua{\simple}

\stoptext
``````
• That's going to blow up if you input something that's not expandable but also not protected. This doesn't happen often in ConTeXt, but a common LaTeX pitfall is `\directlua{whatever([==[\section{boom}]==])}` Feb 12 '20 at 21:00