nielsAD / lape

Scripting engine with Pascal-like syntax for FPC and Delphi
119 stars 28 forks source link

Records: Add class variables/constants #141

Closed ollydev closed 3 years ago

ollydev commented 4 years ago

Like FPC's advanced records I've added support for class variables and constants.

type
  TPoint = record
  class var
    ClassVar1: Int32 = 100;
    ClassVar2: Int32 = 200;
  class const
    ClassConst1,
    ClassConst2 = 'Hello World';
  var
    X, Y: Int32;
  end;

It's quite simple, it just references a global variable internally.

Default value assignments must be constants, Allowing := would be pretty weird in this instance, plus we'd have to find somewhere to compile the assignments - not worth it.

nielsAD commented 4 years ago

Good idea! However, I think the current approach is a bit redundant.

You should be able to reuse functionality that is currently used for type methods rather than introducing an extra ClassVarMap tracker. Every TLapeType is a TLapeManagingDeclaration, which means you can use addSubDeclaration to add TLapeGlobalVar instances to the type that will inherently work with HasChild and op_dot operations. As class variables are guaranteed to be global, I think that should suffice.

ollydev commented 4 years ago

@nielsAD Awesome idea. I've implemented it. Tests pass: https://travis-ci.org/github/nielsAD/lape/builds/675060129

slackydev commented 3 years ago

But if you pass such a record to a function in a dll the constants would be lost?

ollydev commented 3 years ago

Yes, but it's the same with FPC's advanced records. Class const/var don't modify the record. It's pretty much a scoped variable.

type 
  TPoint = record
  class var
     test: Byte;
  var
    X, Y: Integer;
  end;

begin
  WriteLn(SizeOf(TPoint)); // 8 still
end;

So yeah, anything external will just see a regular TPoint