How to apply a LuaLaTeX function to only a specific font?

In the italic font I am using, the apostrophe appears too far right in its bounding box, and therefore a space between an apostrophe and a glyph appears smaller than a space between two glyphs. I adapted code from Kerning against word space in LuaTeX in order to increase this space. However, the code applies to all fonts used in the document, but I want it to apply to only the italic font. Is there a way to do this?

Current output:

Desired output:

(the spaces have been exaggerated for purposes of demonstration)

MWE:

\documentclass{article}
\usepackage{fontspec}
\directlua{
for space in node.traverse_id(node.id('glue'), head) do
if space.subtype == 13 then
local prev = node.prev(space)
local next = node.next(space)
if prev.id == 29 and next.id == 29 then
if prev.char == 8217 then
space.width = space.width + 1000000
end
end
end
end
return true
end
}
\setmainfont{times.ttf}[
ItalicFont = timesi.ttf
]
\begin{document}
It's time to rock 'n' roll,' he said. \par
\textit{It's time to rock 'n' roll,' he said.}
\end{document}

• It would be imho more sensible to implement that as font feature which you then load with the font. Or try to patch the font: tex.stackexchange.com/a/420568/2388 – Ulrike Fischer Jul 29 '19 at 13:37
• @UlrikeFischer I guess that's the crux of my question: how do I implement my code as a font feature, or patch the font using my code? – solisoc Jul 29 '19 at 13:50

I tried out Ulrike Fischer’s suggestion for a kerning problem (» + W in a regular and a italic font). The approach will show how to add a font-feature, but may not solve the specific problem regarding the spacing. Furthermore, my knowledge of luatex and font-features is rather restricted.

1. Add the font feature. In my case, this was simply a kerning issue. This will add ktest as font-feature and will move CHAR2 100 units closer to CHAR1 when they appear together.

\directlua
{
name = "ktest",
type = "kern",
data = {["CHAR1"] = {["CHAR2"] = -100}
}
}
}

2. Then add another font-feature ktestit that does the same thing, but just 50 units less. We will use this for italic fonts only.

\directlua
{
name = "ktestit",
type = "kern",
data = {["CHAR1"] = {["CHAR2"] = -50}
}
}
}

3. RawFeature will add ktest as global font-feature. The optional parameter ItalicFeatures in \setmainfont will then specify that ktest will be substituted by your italic-only font-feature ktestit. However, I have only tested this with an .otf-font. Maybe it is possible for you to switch.

\setmainfont{YOURFONT}
[Extension=.otf,
ItalicFont=ITALICFONT,
RawFeature=+ktest,
ItalicFeatures={RawFeature={-ktest;+ktestit}}
]