Skip to content
This repository was archived by the owner on Apr 15, 2023. It is now read-only.
This repository was archived by the owner on Apr 15, 2023. It is now read-only.

Automatic resource management with destructors #56

@planetis-m

Description

@planetis-m

Structs like Image, Texture, RenderTexture, Font, Mesh, Shader, Material, Model, Wave, Sound, Music, and AudioStream can make use of destructors like this:

type
  Texture = object
  ...

proc `=destroy`(x: var Texture) =
  proc UnloadTexture(texture: Texture) {.cdecl, importc, header: raylibHeader.}
  UnloadTexture(x)
proc `=copy`*(dest: var Texture; source: Texture) {.error.}

However closeWindow needs to be called last, so we are forced to introduce a dummy type.

type
  RaylibHandle = distinct bool

var
  isRaylibInitialized: bool

proc `=copy`*(dest: var RaylibHandle; source: RaylibHandle) {.error.}
proc `=destroy`(x: var RaylibHandle) =
  if isRaylibInitialized and x.bool:
    closeWindow()
    isRaylibInitialized = false

proc rinit*(width: cint; height: cint; title: cstring): RaylibHandle =
  if isRaylibInitialized:
    assert false, "Cannot initialize raylib more than once."
  else:
    initWindow(width, height, title)
    isRaylibInitialized = true
    result = RaylibHandle(true)

Let's not dwell into thread/memory safety to much, else the api would become too cumbersome to use.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions