Skip to content

Current objects (~) #224

@bvssvni

Description

@bvssvni

In Dyon you need a stack reference to mutate arrays with push(mut,_) and pop(mut). This does not work very well with deep object hierarchies, because it does a copy-on-write when there is more than one reference to a variable on the heap. This encourages programmers to use data-oriented programming style, where you iterate over arrays.

A normal application requires many flat structures, and you end up with long function names like this:

fn render_dlist_world_bullets_comets(mut dlist, world, bullets, comets) { ... }

By using current objects, you can reduce the length of function names and the amount of typing:

// Uses current objects `dlist`, `world`, `bullets`, `comets`.
fn render_world() ~ mut dlist, world, bullets, comets { ... }

Syntax

To declare a new current object, one uses ~ in front of the variable name:

fn main() {
    // The `~` sign make these current objects for the scope of called functions.
    ~ window := new_window(title: "hello world!")
    ~ bullets := init_bullets()
    ~ comets := init_comets()
    loop {
        if !next_event(mut window) { break }
        ...
        set(title: "start the game!")
        ...
        update_world(dt)
    }
}

To use current objects, you put ~ and a list of variables after function arguments:

fn set_title(title: str) ~ mut window {
    // Set the title of the current window.
    set(window: window, title: title)
}

fn update_world(dt) ~ mut bullets, mut comets {
    // Move objects.
    move(bullets, dt)
    move(comets, dt)
    ...
}

fn move(mut objects, dt) {
    for i { objects[i][0] += dt * objects[i][1] }
}

Motivation

These rules are designed for

  • Make refactoring easier
  • Improve readability
  • Reduce typing

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions