Sample code for 30+ languages & platforms
Zig 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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This is the JavaScript function we'll call:

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

    const sb_script = try chilkat.StringBuilder.init();
    defer sb_script.deinit();
    sb_script.append("function isEven(number) { return number % 2 === 0; }") catch {};

    const js = try chilkat.Js.init();
    defer js.deinit();

    const result = try chilkat.JsonObject.init();
    defer result.deinit();
    result.setEmitCompact(false);

    // Call Eval to add the function to the context's global object
    js.eval(sb_script, result) catch {
        // Examine the result for an exception.
        std.debug.print("{s}\n", .{try result.emit(alloc)});

        // Also examine the LastErrorText.
        std.debug.print("{s}\n", .{try js.getLastErrorText(alloc)});
        return;
    };

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

    const func_call = try chilkat.JsonObject.init();
    defer func_call.deinit();

    // Create JSON specifying the function name and arguments

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

    func_call.updateString("name", "isEven") catch {};
    func_call.updateInt("args[0]", 8) catch {};

    js.callFunction(func_call, result) catch {
        // Examine the result for an exception.
        std.debug.print("{s}\n", .{try result.emit(alloc)});

        // Also examine the LastErrorText.
        std.debug.print("{s}\n", .{try js.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try result.emit(alloc)});

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

    const retval = result.boolOf("value");
    std.debug.print("{}\n", .{retval});

    // Output:
    // true
}