I need to change the width of a saved box and want it to look as if it was constructed at that width.
For example, this centers A in a 4cm wide box:
\hbox to 4cm{\hfil A\hfil} But this centers B in the original 2cm wide box, and then adds 2cm to the right making the resulting box the desired width, but without telling the glues about it:
\setbox0=\hbox to 2cm{\hfil B\hfil} \wd0=4cm \box0 And this just puts the text on the left with zero-width glues:
\setbox0=\hbox{\hfil C\hfil} \wd0=4cm \box0 Is there a way to change the width in a way that centers B and C in the adjusted boxes like A?

I'm not sure if this will make it easier or harder, but how do I do this in LuaTeX, because in practice I'm collecting boxes, adjusting them in Lua code and then put them back, like so:
\setbox0=\hbox{\hfil D\hfil}% \directlua{ local b = node.copy(tex.box[0]) b.width = tex.sp('4cm') node.write(b) } i.e. at the point where I'm handling the box it has already been typeset, which would make a solution that stores the tokens and creates a new box of the target width and typesets it again quite complicated. I'm hoping there's a simple API call that will simply recompute this?
\setbox0=\hbox to 2cm{\hfil B\hfil}you can do\hbox to 4cm{\unhbox0}. In the picture I addedXat the sides of the boxes and\hrulefillinstead of\hfilto see the effect