Fix scoping issue using closures, cache length vars for looping.