Skip to content

Instantly share code, notes, and snippets.

@henkboom
Created January 5, 2010 00:43
Show Gist options
  • Save henkboom/269038 to your computer and use it in GitHub Desktop.
Save henkboom/269038 to your computer and use it in GitHub Desktop.
-- state migration prototype inspired by circa's demo video and circa's
-- notes/stateful_code
---- handles state migration --------------------------------------------------
local saved_states = {}
local index = 1
function prepare_for_reload()
index = 1
end
function state(value)
-- to be more resilient to code changes this key would have to be determined
-- based on an analysis of the control flow, using the lua debug library.
local key = index
index = index + 1
if saved_states[key] == nil then
saved_states[key] = value
end
return {
set = function (new_value) saved_states[key] = new_value end,
get = function () return saved_states[key] end,
}
end
---- test game ----------------------------------------------------------------
function make_the_game(timer_init)
local timer = state(timer_init)
print('game initialized, timer is ' .. timer.get())
return {
update = function ()
timer.set(timer.get() + 1)
print('game updated, timer is ' .. timer.get())
end
}
end
---- simulate load and re-load ------------------------------------------------
-- initialize the game for the first time
print('initial load')
game = make_the_game(5)
game.update()
game.update()
game.update()
-- simulate 're-loading' the game after a code change
prepare_for_reload()
print('second load')
game = make_the_game(5)
game.update()
-- the output is:
--
-- initial load
-- game initialized, timer is 5
-- game updated, timer is 6
-- game updated, timer is 7
-- game updated, timer is 8
-- second load
-- game initialized, timer is 8
-- game updated, timer is 9
--
-- MAGIC! :D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment