Jump to content

Closures/Value capture: Difference between revisions

Fixed code to not use wrong variable capturing that got hidden by looping again using that variable.
(Fixed code to not use wrong variable capturing that got hidden by looping again using that variable.)
Line 399:
 
type
TFuncIntResult = reference to function : integerInteger;
 
// use function that returns anonymous method to avoid capturing the loop variable
var
function CreateFunc(i: Funcs Integer): array [0..9] of TFuncIntResult;
begin
i : integer;
Result :=
function: Integer
begin
Result := i * i;
end;
end;
 
var
Funcs: array[0..9] of TFuncIntResult;
i : integer;
begin
// Createcreate 10 anonymous functions
for i := Low(Funcs) to High(Funcs) do
Funcs[i] := functionCreateFunc(i) : integer begin Result := i*i; end;
 
// call all 10 functions
for i := Low(Funcs) to High(Funcs) do
writelnWriteln( Funcs[i]() );
 
end.</lang>
{{out}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.