6

This is my code:

\defineexpandable[1]\background{
  \directlua{
    local cases = {
      "noise-blue.png",
      "noise-yellow.png",
      "noise-red.png",
      "noise-green.png"
    }

    tex.sprint(cases[#1])
  }
}

\starttext
  \background{1}                             % (1)
  \externalfigure[noise-blue.png][width=4cm] % (2)
  \externalfigure[\background{1}][width=4cm] % (3)
\stoptext

(1) gives me noise-blue.png in the output.
(2) correctly renders the image noise-blue.png.
(3) gives a gray box with

name: noise-blue.png
file: noise-blue.png
state: unknown

Why doesn't it render the image?

  • The \background command already exists in ConTeXt, use \Background instead. – Wolfgang Schuster Jan 26 at 16:00
9

You add spaces in the output of your command at the begin and end of the definition.

\defineexpandable[1]\Background{
  \directlua{
    local cases = {
      "noise-blue.png",
      "noise-yellow.png",
      "noise-red.png",
      "noise-green.png"
    }
    tex.sprint(cases[#1])
  }
}

\starttext
“\Background{1}”
\stoptext

enter image description here

To get rid of the spaces you have to add a comment sign after the braces.

\defineexpandable[1]\Background{%
  \directlua{
    local cases = {
      "noise-blue.png",
      "noise-yellow.png",
      "noise-red.png",
      "noise-green.png"
    }
    tex.sprint(cases[#1])
  }%
}

\starttext
“\Background{1}”
\stoptext

enter image description here

You can also use the texdefinition environment to create the command which doesn’t convert the end of a line into a space.

\starttexdefinition Background #1
  \startlua
    local cases = {
        "noise-blue.png",
        "noise-yellow.png",
        "noise-red.png",
        "noise-green.png"
    }
    context(cases[#1])
  \stoplua
\stoptexdefinition

Alternative solution

A different way to create a index for your images is the \setvariables which you can use to assign a key to each image. The graphics can than be accessed with the \getvariable command.

\setvariables
  [background]
  [1={noise-blue.png},
   2={noise-yellow.png},
   3={noise-red.png},
   4={noise-green.png}]

\starttext
“\getvariable{background}{1}”
\stoptext
6

As an alternative to Wolfgang's answer and as alternative to your Lua solution, you might want to consider using \useexternalfigure which allows you to name figures.

\useexternalfigure[background:1][noise-blue.png]
\useexternalfigure[background:2][noise-yellow.png]
\useexternalfigure[background:3][noise-red.png]
\useexternalfigure[background:4][noise-green.png]

\starttext
  \externalfigure[background:1][width=4cm]
\stoptext
  • Thanks for this tip! I'll keep Wolfgang's answer accepted since it solves the question but I'll consider using this code instead. – flyx Jan 26 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.