Closures/Value capture: Difference between revisions

Content added Content deleted
(Fixed code to not use wrong variable capturing that got hidden by looping again using that variable.)
Line 399: Line 399:


type
type
TFuncIntResult = reference to function : integer;
TFuncIntResult = reference to function: Integer;


// use function that returns anonymous method to avoid capturing the loop variable
var
Funcs : array [0..9] of TFuncIntResult;
function CreateFunc(i: Integer): TFuncIntResult;
begin
i : integer;
Result :=
function: Integer
begin
Result := i * i;
end;
end;


var
Funcs: array[0..9] of TFuncIntResult;
i: integer;
begin
begin
// Create 10 anonymous functions
// create 10 anonymous functions
for i := Low(Funcs) to High(Funcs) do
for i := Low(Funcs) to High(Funcs) do
Funcs[i] := function() : integer begin Result := i*i; end;
Funcs[i] := CreateFunc(i);


// call all 10 functions
// call all 10 functions
for i := Low(Funcs) to High(Funcs) do
for i := Low(Funcs) to High(Funcs) do
writeln( Funcs[i]() );
Writeln(Funcs[i]());

end.</lang>
end.</lang>
{{out}}
{{out}}