#generate function at runtime

1 messages · Page 1 of 1 (latest)

fading tulip
#

How would I generate a function at runtime? NOT at comptime. I don't want for the user to need the zig compiler installed either.

Like how you can do this in JS

var nearestPointOnLine = function(ax, ay, bx, by) {
    var dx = bx - ax;  /* Vector from A to B (run) */
    var dy = by - ay;  /* ... (rise) */
    var mag2 = dx*dx + dy*dy;  /* Squared distance between A and B */
    
    /* Find and return the nearest point on line AB to point P. */
    var nearest = function(px, py) {
        var a2pX = px - ax;  /* Vector from A to P */
        var a2pY = py - ay;
        var a2pDota2b = a2pX*dx + a2pY*dy;  /* AP ⦁ AB */
        var t = a2pDota2b / mag2;  /* Parametric distance from A to THE point */
        return {
            x: ax + dx*t,
            y: ay + dy*t 
        };
    };
    
    return nearest;
};
magic ibex
#

Those are not functions that are generated at runtime - they are closures; which are just functions that implicitly allocate their state, and then automatically pass them to the function when it's called as a hidden function parameter.

#

You can generally refactor a closure into another form.

fading tulip
#

oh. will Zig get closures?

sharp cradle
#

no

cedar idol
#

JS is an interpreted language where you can do crazy runtime schenanigans. Zig is compiled. You can, of course, run an interpreter as part of your application.

pastel field
#

Yep, embed a Lua interpreter (or one of the excellent toy languages you can find on this discord), then generate scripts on the fly from your main app to execute at runtime

wheat sail
#

you can close over the variables yourself, and manage the state yourself:

const std = @import("std");

const LineInfo = struct {
    ax: f32,
    ay: f32,
    dx: f32,
    dy: f32,
    mag2: f32,

    pub fn fromLine(ax: f32, ay: f32, bx: f32, by: f32) LineInfo {
        const dx = bx - ax;
        const dy = by - ay;
        return .{
            .ax = ax,
            .ay = ay,
            .dx = dx,
            .dy = dy,
            .mag2 = dx * dx + dy * dy,
        };
    }

    pub fn nearest(info: LineInfo, px: f32, py: f32) struct { x: f32, y: f32 } {
        const a2pX = px - info.ax;
        const a2pY = py - info.ay;
        const a2pDota2b = a2pX * info.dx + a2pY * info.dy;
        const t = a2pDota2b / info.mag2;
        return .{
            .x = info.ax + info.dx * t,
            .y = info.ay + info.dy * t,
        };
    }
};

test LineInfo {
    std.debug.print("{any}\n", .{LineInfo.fromLine(0, 0, 5, 5).nearest(3, 3)});
    std.debug.print("{any}\n", .{LineInfo.fromLine(0, 0, 5, 5).nearest(3, 5)});
}