Preserve script state and clean up objects when needed.