const c = @cImport({ @cInclude("SDL2/SDL.h"); @cInclude("lua/lua.h"); @cInclude("lua/lualib.h"); @cInclude("lua/lauxlib.h"); }); const std = @import("std"); fn luaAlloc(userdata: ?*anyopaque, ptr: ?*anyopaque, original_size: usize, updated_size: usize) callconv(.C) ?*anyopaque { // Implementation derived from // https://github.com/natecraddock/ziglua/blob/master/src/ziglua.zig. const alignment = @alignOf(std.c.max_align_t); const Allocator = std.mem.Allocator; const allocator = @ptrCast(*Allocator, @alignCast(@alignOf(Allocator), userdata.?)); if (@ptrCast(?[*]align(alignment) u8, @alignCast(alignment, ptr))) |prev_ptr| { // Allocator is working with an existing pointer. const prev_slice = prev_ptr[0 .. original_size]; if (updated_size == 0) { // Updated size of `0` to free the existing memory block. allocator.free(prev_slice); return null; } // Resize the existing memory block. return (allocator.reallocAdvanced(prev_slice, alignment, updated_size, .exact) catch return null).ptr; } // No existing pointer, allocate a new block of memory. return (allocator.alignedAlloc(u8, alignment, updated_size) catch return null).ptr; } pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; if (c.SDL_Init(c.SDL_INIT_EVERYTHING) != 0) { c.SDL_LogCritical(c.SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize SDL2 runtime"); return error.SystemFailure; } defer c.SDL_Quit(); var lua_allocator = gpa.allocator(); const lua_state = c.lua_newstate(luaAlloc, @ptrCast(*anyopaque, &lua_allocator)); if (lua_state == null) { c.SDL_LogCritical(c.SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize Lua virtual machine"); return error.SystemFailure; } defer c.lua_close(lua_state); const sdl_window = create_sdl_window: { const pos = c.SDL_WINDOWPOS_UNDEFINED; var flags = @as(u32, 0); break: create_sdl_window c.SDL_CreateWindow("Ona", pos, pos, 640, 480, flags); }; if (sdl_window == null) { c.SDL_LogCritical(c.SDL_LOG_CATEGORY_VIDEO, "Failed to create SDL2 window"); return error.SystemFailure; } defer c.SDL_DestroyWindow(sdl_window); const sdl_renderer = create_sdl_renderer: { var flags = @as(u32, 0); break: create_sdl_renderer c.SDL_CreateRenderer(sdl_window, -1, flags); }; if (sdl_renderer == null) { c.SDL_LogCritical(c.SDL_LOG_CATEGORY_VIDEO, "Failed to create SDL2 renderer"); return error.SystemFailure; } defer c.SDL_DestroyRenderer(sdl_renderer); var is_running = true; while (is_running) { var sdl_event = std.mem.zeroes(c.SDL_Event); while (c.SDL_PollEvent(&sdl_event) != 0) { switch (sdl_event.type) { c.SDL_QUIT => is_running = false, else => {}, } } _ = c.SDL_SetRenderDrawColor(sdl_renderer, 0, 0, 0, 255); _ = c.SDL_RenderClear(sdl_renderer); c.SDL_RenderPresent(sdl_renderer); } }