Changes

Jump to navigation Jump to search
36 bytes removed ,  18:12, 18 January 2023
m
correct styling
The interweaving of ConTeXt and Lua consists of two elements: first you tell TeX that you're starting some Lua code; then, once inside Lua, you need to use the appropriate functions to put things into the TeX stream.
There are two main ways to execute Lua code in a ConTeXt document: The command <code>\{{cmd|ctxlua</code>}}, and the environment <code>\{{cmd|startluacode...\}}…{{cmd|stopluacode</code>}}. Both are wrappers around the LuaTeX primitive <code>\{{cmd|directlua</code>}}, which you should never need to use. In general, you will define a function inside a <code>\{{cmd|startluacode</code> }} block, and then define a TeX command that calls the function using <code>\{{cmd|ctxlua</code>, especially because <code>\{{cmd|ctxlua</code> }} has a few idiosyncracies.
The main thing about Lua code in a TeX document is this: the code is expanded by TeX ''before'' Lua gets to it. '''This means that all the Lua code, even the comments, must be valid TeX!''' A string like "\{{cmd|undefined" }} will cause an immediate failure.
== Calling a bit of Lua inline: \{{cmd|ctxlua }} ==
The command <code>\{{cmd|ctxlua</code> }} is for short inline snippets of Lua, such
as
</texcode>
<code>\{{cmd|ctxlua</code> }} operates under the normal TeX catcodes (category codes). This means the following two things for the Lua code inside:
* all newlines get treated as spaces
* special TeX characters like &, #, $, {, }, etc., need to be escaped.
== Calling a lua function with \{{cmd|cldcontext }} and get the return ==
One can execute a Lua code from within TeX and get back the result in TeX by using {{codecmd|\cldcontext}}. Thus, if {{code|myfunction}} is a function of a variable {{code|x}} defined in Lua, {{codecmd|\cldcontext|{myfunction(5)}}} returns the value {{code|myfunction(5)}} in TeX. This is equivalent to {{codecmd|\ctxlua|{context(myfunction(5))}}}.
== A larger Lua block: \{{cmd|startluacode...\}}…{{cmd|stopluacode }} ==
Inside the <code>\{{cmd|startluacode...\}}…{{cmd|stopluacode</code> }} environment, newlines and special characters behave normally. This solves the catcode problem that <code>\{{cmd|ctxlua</code> }} suffers from. Apart from these special characters, the main warning remains in force: all the Lua code, even the comments, must be valid TeX.
<texcode>
-- The unknown command \undefined will cause this entire block to fail.
-- Print a countdown '10, 8, ..., 0!'
-- `..` is Lua for string concatenation
for i = 10, 2, -2 do
function u.myfunction()
-- do stuff
end
\stopluacode
</texcode>
== Simple printing: context(), tex.print(), and tex.sprint() ==
Use <code>context(...)</code> for most things. It is equivalent to <code>tex.print(string.format(...))</code>, so
<texcode>
</texcode>
Then define the TeX command that expands to a <code>\{{cmd|ctxlua</code> }} call:
<texcode>
it is robust against <code>#1</code> containing the quotation mark
<code>"</code> which would terminate the Lua string prematurely.
Inside <code>\{{cmd|protect .. \}}…{{cmd|unprotect</code> }} the macros <code>\{{cmd|!!bs</code>}}and <code>\{{cmd|!!es</code> } are at your disposition.
They are equivalent to <code>[===[</code> and <code>]===]</code> and --
being single tokens to TeX -- parsed faster.
(See [http://repo.or.cz/w/context.git/blob/refs/heads/origin:/tex/context/base/luat-ini.mkiv#l174 <code>luat-ini.mkiv</code>].)
== Making \{{cmd|startenv...\}}…{{cmd|stopenv }} hook into Lua ==
The first job is, as ever, to have the Lua function at the ready
<texcode>
</texcode>
Lastly, we define the <code>\{{cmd|stopverynarrow</code> }} command such that it passes the recently-complated buffer to our <code>verynarrow</code> Lua function:
<texcode>
:H<sub>3</sub>SO<sub>4</sub><sup>+</sup>,
we must type
:<code>H\{{cmd|low|{3}}}SO\{{cmd|lohi|{4}}}{{{\cmd|textplus}}}</code>,
but we'd much rather type
:<code>\{{cmd|molecule|{H_3SO_4^+}</code>}}.
So, we need a function that can take a string like that, parse it, and turn it into the appropriate TeX code. LuaTeX includes a general parser based on PEG (parsing expression grammar) called [http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html lpeg], and it makes writing little parsers positively joyful. (Once you've got the knack of it, at least.) For example, the above <code>\{{cmd|molecule</code> }} macro can be written as follows.
<texcode>
== Manipulating verbatim text ==
''This example demonstrates defining a custom \{{cmd|start...\}}…{{cmd|stop }} buffer that gets processed through Lua in its entirety.''
Suppose we want to write an environment <code>\{{cmd|startdedentedtyping</code> ... <code>\}} … {{cmd|stopdedentedtyping</code> }} that removes the indentation of the first line from every line. Thus, the output of ...
<texcode>
\stopdedentedtyping
</texcode>
... should be the same as the output of ...
<texcode>
\stoptyping
</texcode>
... even though the leading whitespace is different.
Defining an environment in TeX that removes the leading spaces but leaves
</texcode>
Here is the code for defining the <code>\{{cmd|startdedentedtyping...\}} … {{cmd|stopdedentedtyping</code> }} pair:
<texcode>
= In detail: the interaction between TeX and Lua =
To a first approximation, the interaction between TeX and Lua is straightforward. When TeX (i.e., the LuaTeX engine) starts, it loads the input file in memory and processes it token by token. When TeX encounters <code>\{{cmd|directlua</code>}}, it stops reading the file in memory, <em>fully expands the argument of <code>\{{cmd|directlua</code>}}</em>, and passes the control to a Lua instance. The Lua instance, which runs with a few preloaded libraries, processes the expanded arguments of <code>\{{cmd|directlua</code>}}. This Lua instance has a special output stream which can be accessed using <code>tex.print(...)</code>. The function <code>tex.print(...)</code> is just like the Lua function <code>print(...)</code> except that <code>tex.print(...)</code> prints to a <em>TeX stream</em> rather than to the standard output. When the Lua instance finishes processing its input, it passes the contents of the <em>TeX stream</em> back to TeX.<ref>The output of <code>tex.print(...)</code> is buffered and not passed to TeX until the Lua instance has stopped.</ref> TeX then inserts the contents of the <em>TeX stream</em> at the current location of the file that it was reading; expands the contents of the <em>TeX stream</em>; and continues. If TeX encounters another <code>\{{cmd|directlua</code>{{cmd|, the above process is repeated.
As an exercise, imagine what happens when the following input is processed by LuaTeX. The answer is in the footnotes. <ref>In this example, two different kinds of quotations are used to avoid escaping quotes. Escaping quotes inside <code>\{{cmd|directlua</code> }} is tricky. The above was a contrived example; if you ever need to escape quotes, you can use the <code>\{{cmd|startluacode ... }}…{{cmd|\stopluacode</code> {{cmd| syntax.</ref>
<texcode>
139

edits

Navigation menu