Sample code for 30+ languages & platforms
PureBasic Requires Chilkat v11.4.0+

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a boolean.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJs.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  This is the JavaScript function we'll call:

    ;  function isEven(number) {
    ;      return number % 2 === 0;
    ;  }

    sbScript.i = CkStringBuilder::ckCreate()
    If sbScript.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbScript,"function isEven(number) { return number % 2 === 0; }")

    js.i = CkJs::ckCreate()
    If js.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    result.i = CkJsonObject::ckCreate()
    If result.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkEmitCompact(result, 0)

    ;  Call Eval to add the function to the context's global object
    success = CkJs::ckEval(js,sbScript,result)
    If success = 0
        ;  Examine the result for an exception.
        Debug CkJsonObject::ckEmit(result)

        ;  Also examine the LastErrorText.
        Debug CkJs::ckLastErrorText(js)
        CkStringBuilder::ckDispose(sbScript)
        CkJs::ckDispose(js)
        CkJsonObject::ckDispose(result)
        ProcedureReturn
    EndIf

    ;  ------------------------------------------------------------------------------
    ;  Call the function isEven(8)

    funcCall.i = CkJsonObject::ckCreate()
    If funcCall.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Create JSON specifying the function name and arguments

    ;  {
    ;    "name": "isEven",
    ;    "args": [ 8 ]
    ;  }

    CkJsonObject::ckUpdateString(funcCall,"name","isEven")
    CkJsonObject::ckUpdateInt(funcCall,"args[0]",8)

    success = CkJs::ckCallFunction(js,funcCall,result)
    If success = 0
        ;  Examine the result for an exception.
        Debug CkJsonObject::ckEmit(result)

        ;  Also examine the LastErrorText.
        Debug CkJs::ckLastErrorText(js)
        CkStringBuilder::ckDispose(sbScript)
        CkJs::ckDispose(js)
        CkJsonObject::ckDispose(result)
        CkJsonObject::ckDispose(funcCall)
        ProcedureReturn
    EndIf

    Debug CkJsonObject::ckEmit(result)

    ;  Output:
    ;  {
    ;    "type": "bool",
    ;    "value": true
    ;  }

    retval.i = CkJsonObject::ckBoolOf(result,"value")
    Debug Str(retval)

    ;  Output:
    ;  1


    CkStringBuilder::ckDispose(sbScript)
    CkJs::ckDispose(js)
    CkJsonObject::ckDispose(result)
    CkJsonObject::ckDispose(funcCall)


    ProcedureReturn
EndProcedure