Arenas
Arena memory management.
Example
#[type] // definition of a prototype object named "Prompt"
Prompt: {
str! text: ''
list! blocks: []
#[static] // optional, but recommended for human eyes
fn new(text: str!, blocks: list = [], arena?: obj) -> Prompt {
new Prompt { text, blocks } on arena
}
fn push(prompt: Prompt) {
self.blocks.push_back(prompt);
}
fn out(level: int = 0) -> str {
const out = self.text;
const indent = '';
for (let _ in level + 1) indent.push('\t');
for (const prompt: Prompt in self.blocks) out.push(`\n${indent}${prompt.out(level + 1)}`);
out
}
}
#[main]
fn main() {
const arena = new {};
const top = <Prompt>.new('Title', arena = arena);
const mid = <Prompt>.new('Middle', [
<Prompt>.new('First', arena = arena),
<Prompt>.new('Second', arena = arena),
], arena);
top.push(mid);
const bot = <Prompt>.new('Bottom', [
<Prompt>.new('First', arena = arena),
], arena);
top.push(bot);
pln(top.out());
// All of the objects allocated have been in the arena
assert_eq(self.children().len(), 2); // Prompt type and arena obj
assert_eq(arena.children().len(), 6);
drop(arena);
assert_eq(self.children().len(), 1); // just the Prompt object
assert_not(arena.exists()); // all prompts have been removed from the document
}Output
Summary
Insights
Last updated