Cannot access arguments in a lua block

Mico has already given the correct answer. Let me extend the explanation. When you write:

\def\Parse#1{\directlua{   cmdString = tostring(#1)  }}

and call \Parse{hello12341234asdf}, the result is pretty much like this:

\directlua{   cmdString = tostring(hello12341234asdf)  }

Which is, of course, not what you want. You need to put the quotation marks around the definition:

\def\Parse#1{\directlua{   cmdString = tostring("#1")  }}

and a call to \Parse{hello12341234asdf}, gives

\directlua{   cmdString = tostring("hello12341234asdf")  }

Now what happens if you call \Parse{hello"1234}? You get

\directlua{   cmdString = tostring("hello"1234")  }

which, again, is not what you want. Therefore you need to escape the contents of #1. This is what \luaescapestring{} does for you. But this won't work in LaTeX, because in LaTeX every Lua command from the reference manual is prefixed with luatex (except for \directlua). Therefore the defintion is that what Mico writes:

\def\Parse#1{\directlua{   cmdString = tostring("\luatexluaescapestring{#1}")  }}

You shouldn't just specify #1 as the argument of tostring; rather, try something like "\luatexluaescapestring{#1}". With this modificaton, your MWE works fine:

\documentclass[11pt]{book}
\usepackage{luatex,pgffor}
\tracingonline 6
\directlua{
    tex.enableprimitives('',tex.extraprimitives())
    local lpeg = require "lpeg"
}
\def\Parse#1{
    \directlua{
        cmdString = tostring("\luatexluaescapestring{#1}")
        tex.print(cmdString)
    }
}
\begin{document}
\Parse{hello12341234asdf}
\end{document}

Update, May 2016: Alain Matthes has pointed out in a comment that the code shown above no longer runs, at least not with TeXLive2015. The problem turns out to be related to the version of the luatex package that's installed on one's system. Happily, earlier this month Heiko Oberdiek released an update to the luatex package which fixes this issue.

As TeXLive2015 is currently "frozen", one needs to either download the updated package from the CTAN and install it manually, switch to the latest release of TeXLive2016-pre, or wait a few more weeks until the official version of TeXLive2016 is released and may be installed.

Alternatively, load the luacode package instead of the luatex package.

Tags:

Luatex