To answer the second question (first question later):
Why we need this command in LuaTeX?
Imagine the following document:
\documentclass{article} \newcommand\foo[1]{% \directlua{tex.sprint("#1") }} \begin{document} \foo{bar} \end{document}
\foo{bar} is expanded to \directlua{tex.sprint("bar")} which outputs bar.
Now let's change the macro call:
\documentclass{article} \newcommand\foo[1]{% \directlua{tex.sprint("#1") }} \begin{document} \foo{"baz"} \end{document}
Now \foo{"baz"} gets expanded to \directlua{tex.sprint(""baz"") } which is not valid Lua syntax. To protect us from users who want to print quotation marks ", one can either check the argument manually (which tends to be very very difficult) or you can rely on the magic of \luaescapestring{...} - in LaTeX it's prefixed with luatex:
\documentclass{article} \newcommand\foo[1]{% \directlua{tex.sprint("\luatexluaescapestring{#1}") }} \begin{document} \foo{"baz"} \end{document}
now it expands to something like this: \directlua{tex.sprint("\"baz\"")}.
To answer the first question:
Why does \luaescapestring do this work?
\TeX is defined in plain TeX:
\def\TeX{T\kern-.1667em\lower.5ex\hbox{E}\kern-.125emX}
so the expansion of TeX is T\kern-.1667em\lower.5ex\hbox{E}\kern-.125emX which contains \k, \l, \h, which are control codes in Lua's strings (or could be). Therefore \luaescapestring adds a backslash to have \\k, \\l and \\h as the string source. Now you have tricked the system by using [[...]] to define the string, and in this double bracket string the backslashes don't do any harm. So in your case you didn't have to use \luaescapestring.
:)I was just pointing at the description. Patrick's answer is very detailed and it will surely help us all.:):-)