Skip to content

Function References Not Working As Expected

Summary

Function references ("reference to" types) are not operating correctly when assigned to a method. Calling a method and function reference yields different results. The function reference result is wrong.

System Information

Operating system: Linux Mint, x86_64 Processor architecture: x86-64 Compiler version: trunk Device: Computer

Steps to reproduce

Using FPC trunk compiler create a new application with Lazarus. Add two buttons to the form and two events handlers to the buttons. Use the code below. Both Button1Click and Button2Click should create the same sequence of numbers written to the terminal. Button1Click always writes out 0. This is a bug.

Example Project

unit Unit1;

{$mode delphi}
{$modeswitch functionreferences}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;

{ TForm1 }

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    function MultiplyMethod(Value: Integer): Integer;
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

type
  TMultiply = reference to function(Value: Integer): Integer;

function TForm1.MultiplyMethod(Value: Integer): Integer;
begin
  Result := Value * Tag;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  M: TMultiply;
begin
  M := MultiplyMethod;
  WriteLn(M(4));
  Tag := Tag + 1;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  WriteLn(MultiplyMethod(4));
  Tag := Tag + 1;
end;

end.

What is the current bug behavior?

Both Button1Click and Button2Click should output the same values in the WriteLn calls. What is happening is that the function reference version (Button1Click) always writes 0 to the console.

Button1Click outputs:

0
0
0
0
0

Button2Click outputs:

0
4
8
12
16

What is the expected (correct) behavior?

Both Button1Click and Button2Click should output the same number sequence.

Edited by Anthony Walter
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information