What is `context.user_index` and `context.user_ptr` for?

They’re defined in the context and even used on the odin overview but there’s no explanation anywhere of what they do.

They don’t do anything on their own, they’re just a place for you to put stuff when you don’t have a better way to do it.

One of the most common cases it comes up in is as a means to pass userdata to a callback where you don’t have a dedicated argument to use to pass that data. For example, to sort some points by distance to some arbitrary point:

points: [][3]f32 = ...
target_pos: [3]f32 = ...

context.user_ptr = &target_pos
slice.sort_by(points[:], proc (a, b: [3]f32) -> bool {
  target_pos := cast(^[3]f32)context.user_ptr
  return linalg.distance(a, target_pos^) < linalg.distance(b, target_pos^)
})

By the normal flow of the context, the context (with user_ptr set) is passed through the call stack to the proc called by sort_by. It’s a useful tool to have, but you should use more explicit means when possible.

3 Likes