Expression surface:valid() returns false if the underlying drawing target is no longer valid, for instance because the window has been closed. Otherwise it returns true.
surface:valid()
false
true