Hacker News new | ask | show | jobs
by filwit 4067 days ago
> I should clarify: What's confusing me is the indexing stuff. I'm not sure if this is referring to something about the `Option<T>` or something else.

By indexing, I meant as an alternative to references.. For example, if you had a Sprite type which held a 'reference' to a Texture in your game's Texture list.. as soon as you allocate a Sprite it must borrow a reference to a Texture, preventing any future mutation of the Textures list for the lifetime of the Sprite, which obviously is too restricting for most games.. so the alternative is to have the Sprite simply hold an index to an item in the array instead, but this basically comes with the same pitfalls as nilable refs (ie, if you accidentally change it, your program can crash due to bounds-checking errors.. or end up with visual glitches.. not sure which would be more annoying).

The other alternative is to use an Option<&Texture> instead. However, I'm not familiar enough with Rust to know of the restrictions here, or even if that's possible (taking a look at the docs, it looks like it's possible, but life-time vars come into play, which could complicate things).

1 comments

Rust solutions would probably be the following: Some kind of runtime assistance (`Rc<T>`, `Arc<T>` et al), using indices as you mentioned (though with `list.get(index)` you'd still have to deal with the fact that it might not be valid, since `get` will return an `Option<T>`)[1] Another solution might be to allocate the textures in an arena that lives outside of the scope of your game logic, and have both the texture list and sprites contain borrows (Note I'm not sure about this, as I haven't done much with arenas yet).

Although I'm unsure where the `not nil` as discussed above comes into play here. What part in Nim would be `nil` here where Rust would have `Option<T>`? The difference between `Option<&Texture>` and `&Texture` is that you have to somehow deal with the possibility of no texture when handling the former.

[1] I should note that actual indexing behavior (`list[index]`) will assume you know there is one in there and panic if it isn't. This is one of the things I dislike and hope there will be an optional (no pun intended) lint post-1.0.