Zig Requires Chilkat v11.4.0+
Zig
Call a JavaScript Function Returning a String
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns a string.Chilkat Zig Downloads
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 greet(name) {
// return "Hello, " + name + "!";
// }
const sb_script = try chilkat.StringBuilder.init();
defer sb_script.deinit();
sb_script.append("function greet(name) { return \"Hello, \" + name + \"!\"; }") 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 greet("Michael")
const func_call = try chilkat.JsonObject.init();
defer func_call.deinit();
// Create JSON specifying the function name and arguments
// {
// "name": "greet",
// "args": [ "Michael" ]
// }
func_call.updateString("name", "greet") catch {};
func_call.updateString("args[0]", "Michael") 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": "string",
// "value": "Hello, Michael!"
// }
const retval = try result.stringOf(alloc, "value");
std.debug.print("{s}\n", .{retval});
// Output:
// Hello, Michael!
}