# Cannot access arguments in a lua block

The follow code is trying simply to print the first argument of a macro. I've tried various things found on the net(there is very little) to get #1 printed in lua but nothing works. I assume there is an issue with interpreting it in lua. Would be nice if there was some tutorial on bridging the gap between tex and lua. Most stuff I've seen use external lua files or do not reference anything except macros in a directlua block.

\documentclass[11pt]{book} % use larger type; default would be 10pt

\usepackage{luatex}
\usepackage{pgffor}

\tracingonline 6

\directlua{
tex.enableprimitives('',tex.extraprimitives())
local lpeg = require "lpeg"
}

\begin{document}

\def\Parse#1{

\directlua{
cmdString = tostring(#1)

tex.print(cmdString)
}
}

\Parse{hello12341234asdf}

\end{document}

-

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}

-

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}")  }}

-