Skip to content

Instantly share code, notes, and snippets.

@cyrusfirheir
Created September 2, 2020 12:46
Show Gist options
  • Save cyrusfirheir/3c0056b1321ae86ddbf9d5b4b279dd51 to your computer and use it in GitHub Desktop.
Save cyrusfirheir/3c0056b1321ae86ddbf9d5b4b279dd51 to your computer and use it in GitHub Desktop.
SugarCube 2 - Branch out of the State system to create a snapshot for later use
(function() {
"use strict";
Macro.add("branch", {
handler() {
let id = this.args[0];
let list = this.args.slice(1);
variables()["#macro-branch"] = variables()["#macro-branch"] || {};
variables()["#macro-branch"][id] = variables()["#macro-branch"][id] || {};
let init = variables()["#macro-branch"][id].__init;
let post = variables()["#macro-branch"][id].__post;
if (init) {
post = {};
list.forEach(el => {
post[el] = clone(State.getVar(el));
State.setVar(el, clone(init[el]));
});
} else {
init = {};
list.forEach(el => {
init[el] = clone(State.getVar(el));
});
}
variables()["#macro-branch"][id] = {
__init: init,
__post: post
};
}
});
Macro.add("closeBranch", {
handler() {
let id = this.args[0];
variables()["#macro-branch"] = variables()["#macro-branch"] || {};
variables()["#macro-branch"][id] = variables()["#macro-branch"][id] || {};
let post = variables()["#macro-branch"][id].__post;
if (post) {
Object.keys(post).forEach(el => {
State.setVar(el, post[el])
});
}
}
});
})();
:: StoryInit
<<set $someVar to 0>>
<<set $anotherVar to true>>
:: Start
<<= $someVar>>
<<= $anotherVar>>
<<button "Add 50 to first variable">>
<<set $someVar += 50>>
<</button>>
<<button "Toggle second variable">>
<<set $anotherVar = !$anotherVar>>
<</button>>
[[Branch passage]]
:: Branch passage
<<branch "UID"
"$someVar"
"$anotherVar"
>>
<<set $someVar += 10>>
<<set $anotherVar to false>>
<<= $someVar>>
<<= $anotherVar>>
<<closeBranch "UID">>
[[Start]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment