ConTeXt does not load png file given by lua code
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
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
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
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