Skip to content

access to Allocator inside wrapped Zig functions #40

Closed
@nurpax

Description

@nurpax

When calling a wrapped Zig function from within Lua, lua.allocator seems to be always null:

pub const Player = struct {
    score: i32,

    pub fn init() Player {
        return Player{
            .score = 0,
        };
    }

    pub fn incScore(self: @This()) void {
        self.score += 1;
    }
};

fn newPlayer(lua: *Lua) i32 {
    std.debug.print("newPlayer zig\n", .{});
    if (lua.allocator) |a| {
        const p = a.create(Player) catch unreachable;
        const udata = lua.newUserdata(*Player);
        udata.* = p;
    } else {
        std.debug.print("lua allocator is null?\n", .{});
        return 0;
    }
    return 1;
}

pub fn register(lua: *Lua) void {
    lua.pushFunction(ziglua.wrap(newPlayer), "newPlayer");
    lua.setGlobal("newPlayer");
}

I think it's due to how wrapZigFn creates a new Lua context:

/// Wrap a ZigFn in a CFn for passing to the API
fn wrapZigFn(comptime f: ZigFn) CFn {
    return struct {
        fn inner(state: ?*LuaState) callconv(.C) c_int {
            // this is called by Lua, state should never be null
            var lua: Lua = .{ .state = state.? };
            return @call(.always_inline, f, .{&lua});
        }
    }.inner;
}

I suppose it should somehow setup the allocator field too.

IMO having a working allocator within the wrapped functions would be useful, so that I can go ahead and use whatever allocator is passed through the lua state.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions