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

Eval JavaScript Returning Int

See more JavaScript Examples

Demonstrates getting the completion value of a JavaScript that returns an integer.

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 example demonstrates getting the completion value of a script,
    // where the last evaluated expression is an integer.

    // The Javascript run in this example is shown below.

    // Load the JavaScript from a file.
    const sb_script = try chilkat.StringBuilder.init();
    defer sb_script.deinit();
    sb_script.loadFile("js_eval_return_int.js", "utf-8") catch {
        std.debug.print("{s}\n", .{try sb_script.getLastErrorText(alloc)});
        return;
    };

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

    // Run the JavaScript
    // Eval returns the completion value of the script. This is generally the value of the last evaluated expression.
    // In this case, the last evaluated expression is an int.
    js.eval(sb_script, result) catch {
        std.debug.print("{s}\n", .{try sb_script.getLastErrorText(alloc)});
        return;
    };

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

    // Output:

    // {
    //   "type": "int",
    //   "value": 42
    // }
}
JavaScript
const base = 10;
const multiplier = 4;
const offset = 2;

// The last line is a calculation resulting in an integer
// Returns 42.
(base * multiplier) + offset;