Check if function param is undefined in SmartMS?

211 Views Asked by At

How can I check if a function param is undefined?

procedure Test(aValue: TObject);
begin
  if aValue <> nil then
    ShowMessage('param filled')      <-- also when Test() is executed!
  else
    ShowMessage('no param filled')   <-- not called, only when Test(nil) is called
end;

However when this function is called in pure JS without a param, then aValue = undefined, but the <> nil check is converted to == null!

For example, when you have a JS function with a callback:

type
  TObjectProcedure = procedure(aValue: TObject);

procedure FetchUrlAsync(aUrl: string; aCallback: TObjectProcedure )
begin
  asm
    $().load(@aUrl, @aCallback);
  end;
end;

You can call this function with:

FetchUrlAsync('ajax/test.html', Test);

It is now depended on jQuery if "Test" is called with a param or not.

2

There are 2 best solutions below

2
Eric Grange On BEST ANSWER

In the next version, you'll be able to use Defined() special function, it will make a strict check against undefined (it will return true for a null value).

if Defined(aValue) then
   ...

In the current version you can define a function to check that

function IsDefined(aValue : TObject);
begin
   asm
      @result = (@aValue!==undefined);
   end;
end;
0
Jon Lennart Aasenden On

In the current version (1.0) you can use the function varIsValidRef() to check if a value is undefined. The function is a part of w3system.pas so it's always there. It looks like this:

function varIsValidRef(const aRef:Variant):Boolean;
begin
  asm
    if (@aRef == null) return false;
    if (@aRef == undefined) return false;
    return true;
  end;
end;

This checks for both null and undefined so you can use it against object references (type THandle is variant) as well.