Skip to content

Instantly share code, notes, and snippets.

@Gjum
Last active August 31, 2015 01:35
Show Gist options
  • Save Gjum/10bd136ca25304f30e02 to your computer and use it in GitHub Desktop.
Save Gjum/10bd136ca25304f30e02 to your computer and use it in GitHub Desktop.
Reload examples

#Reload examples Original code

###Minimal example Reload when '.' key is pressed.

class Leaderboard(Subscriber, Reloadable):
    # There is no __init__() with args and no state, so
    # neither capture_args() nor _persistent_attributes
    # are needed.

    # We want to reload somehow, so we use a key press event for this
    def on_key_pressed(self, val, char):
        if char == '.':  # reload when pressing '.'
            self.reload()  # note: does not check for syntax/runtime errors

    def on_draw_hud(self, c, w):
        # ...

###Complex example Auto-reload every second, keeping init args and instance state.

class MassGraph(Subscriber, Reloadable):
    _persistent_attributes = ['graph']  # restore graph after reload

    def __init__(self, client):
        # restore client after reload
        # (when calling __init__, client is supplied as argument)
        self.capture_args(locals())

        self.reload_timer = 0  # used below

        self.client = client  # set via init arg
        self.graph = []  # should be kept between reloads

    def on_respawn(self):
        # ...

    def on_world_update_post(self):
        # ...

        self.reload_timer += 1
        if self.reload_timer > 25:  # world updates occur 25x per second
            # Do not crash if the reload fails.
            # Note that this does not catch all syntax errors
            # and still no runtime errors.
            self.try_reload()

    def on_draw_hud(self, c, w):
        # ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment