[fpc-devel] Delphi anonymous methods
Vasiliy Kevroletin
kevroletin at gmail.com
Sun Mar 3 08:07:20 CET 2013
> If the "x" is really located in the FrameObject and that object exists
> only once then it is rather likely that the output of 'Before 123: '
> is different from the output of 'After 123: ', right? Again I think
> this is a bad thing...
I was wrong. Local variables of anonymous function located where they
should be: on stack.
> So in my opinion an implementation with a stricter division between
> the single instances of an anonymous function would be the better choice
Am I understand correctly that loop
for i := 1 to 5 do
procArr[i] := procedure begin
DoSmth();
end;
should create 5 separate instances?
It is as I thought about closures before. But this is useless without
capturing of variables by value. During creation of anonymous method you
*can not bind any values* to it. Anonymous method have only references
to captured variables. Pascal don't allows to create static variables
inside function like in c-like languages. So you also not able to create
unique static variable which available only to one instance of same
anonymous method. Even if implementation will create many separate
objects for one anonymous function then all instances will be
equivalent. Because all instances will refer to same data.
Capturing variables by value will allow simple creation of parametrised
closures. Now you also can do parametrised anonymous method but you
should wrap generation of such method into other anonymous function. For
example like this:
=== example
for i := 1 to 5 do
procArr[i] := Call(
function: TProc
var stored: Integer;
begin
stored := i;
Result := procedure
begin
Writeln(stored);
end;
end );
===
This can be simplified by support of capturing by value (please don't
make many attention to syntax, it's not main part of my proposal).
=== example
for i := 1 to 5 do
procArr[i] := procedure
capture i: byValue;
begin
Writeln(i);
end;
end );
===
What do you think about extension which will allow to specify how to
capture. Either by value or by reference?
Vasiliy K.
More information about the fpc-devel
mailing list