3

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.

André
  • 8,920
  • 1
  • 24
  • 24
  • If Test is declared that way, you cannot call Test() - it will not compile. What are you _really_ trying to do? – gabr May 23 '12 at 06:20
  • 1
    @gabr: In Smart you cannot call Test(), that's right. But you can use "Test" as a JS callback, and the function can execute this callback without any param! – André May 23 '12 at 06:37

2 Answers2

4

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;
Eric Grange
  • 5,931
  • 1
  • 39
  • 61
0

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.

Jon Lennart Aasenden
  • 3,920
  • 2
  • 29
  • 44