[NTG-context] getting ConTeXt results back to Lua (for typesetting solutions at end of document)

Sanjoy Mahajan sanjoy at olin.edu
Thu Jan 31 22:51:20 CET 2019


Dear List,

I'm trying to have problem solutions automatically collected, each with
its corresponding problem number, e.g. 2.3, and then typeset at the end
of a document.  Thus, I imagine something like

\startproblem{A problem title}  % Problem 1.1
A question                

\startsolution
An answer
\stopsolution

\stopproblem

And then the solution(s) would appear at the end (with the "1.1"
remembered from when the problem was typeset):

  Solution to Problem 1.1.

  An answer

It seems that buffers are the way to do this.  But I cannot quite get
the automatic numbering to work.  The delayed evaluation and information
passing between lua and ConTeXt has me confused and tangled in a knot.

Below is a minimal almost-working example.  The issue is in the line

      {\ctxlua{userdata.addTempToBuffer('#1', [==[\getnumber[problem]]==])}}

which ends up putting the verbatim string "\getnumber[problem]" into the
temp buffer, rather than the typeset result, which would be something
like 1.1 or 1.2.

I've read the cld-mkiv.pdf manual, but I must be missing a simple
solution to getting ConTeXt to send back the result of
\getnumber[problem].  I've also tried the analogous
context.getnumber({"problem"}), though without success.

Does anyone see what I am missing?

Many thanks!

-Sanjoy

\defineenumeration[problem]
                  [title=yes, text=Problem, way=bychapter, prefix=chapter]
\defineenumeration[solution][problem]
\setupenumeration [solution][text={Solution to problem}, number=no]

\def\test#1{[#1]}

% appendbuffer modified from Sietse Brouwer's on mailing list (Jan 15, 2013)
\startluacode
    userdata = userdata or { }
    function userdata.addTempToBuffer(buffername, problem)
        buffers.append(
            buffername,
            '\\startsolution{' .. problem .. '}\n' .. buffers.getcontent('APPENDTEMP') .. '\n\\stopsolution\n\n'
        )
    end
\stopluacode

\def\startappendbuffer[#1]%
  {\def\stopappendbuffer%
      {\ctxlua{userdata.addTempToBuffer('#1', [==[\getnumber[problem]]==])}}
   \dostartbuffer[APPENDTEMP][startappendbuffer][stopappendbuffer]}

\starttext

\chapter{One}

\startproblem{Test}
  Test problem
\startappendbuffer[soln]
Solution
\stopappendbuffer
\stopproblem

\startproblem{Test}
Test problem
\startappendbuffer[soln]
Solution
\stopappendbuffer
\stopproblem

\typebuffer[soln]

\stoptext


More information about the ntg-context mailing list