0
\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.

user19087
  • 819

2 Answers2

5

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
Henri Menke
  • 109,596
1

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
user19087
  • 819
  • 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}]==])} – Henri Menke Feb 12 '20 at 21:00