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

Eval JavaScript Returning String

See more JavaScript Examples

Demonstrates getting the completion value of a JavaScript that returns a string.

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 a string.

    // 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_string.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 a string.
    js.eval(sb_script, result) catch {
        std.debug.print("{s}\n", .{try js.getLastErrorText(alloc)});
        return;
    };

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

    // Output:

    // {
    //   "type": "string",
    //   "value": "Ready for Chilkat.Js"
    // }
}
JavaScript
var status = "Ready";
var system = "Chilkat.Js";

// The last statement is an expression
status + " for " + system;