`lastid` has to retain its value during the traversal, so we move it to an outer scope. Patch contributed by Litiano Moura.