Using Vector2's As Keys In Dictionaries

Hello everyone! Thank you for checking out this post. Any feedback would be appreciated.

I am simply wondering if it’s possible to read from a dictionary with Vector2’s for keys, and if so, how to go about it. This example code snippet will output nil.

local V2s = {
	[Vector2.new(0,1)] = "Hi",
	[Vector2.new(2,3)] = "Bye"
}

print("Key test with direct Vector2")
print(V2s[Vector2.new(0,1)]) -- outputs nil

local variableV2 = Vector2.new(0,1)
print("Key test with variable Vector2")
print(V2s[variableV2]) -- outputs nil

Ideally, this code should output “Hi”.
If anyone could shed some light on this for me, I’d be grateful!

its because the keys are stored as memory locations of the vector2s, so you have to use the exact same object (not just another object with the same values) to get that value from the dictionary

instead you could make something like a unique hash for each vector by converting the components to a string, then string keys should work as intended in the dictionary

local function hashVector2(vector)
  return tostring(vector.X).."/"..tostring(vector.Y)
end

V2s[hashVector2(Vector2.new(1,2))] = "test"

print(V2s[hashVector2(Vector2.new(1,2))]) -- should print test
1 Like

you shouldnt need to hash them, you could literally just use the same Vector2 as a key. Just use the same variable.

local var = Vector2.new(1, 2)
local dict = {
    [var] = "test"
}

print(dict[var]) --> should output "test"

Vector3s are special “vector” types in Luau, and thus don’t require special custom hashing (they do that for you) and thus are wonderful for this use-case. So just use Vector3s instead of Vector2s.

local t = {}
t[Vector3.new(1, 2, 3)] = "Hello"
print(t[Vector3.new(1, 2, 3)]) --> Hello

This will be by far the most performant method for what you want. And it’s trivial to convert to/from a Vector2 if you really need it.

3 Likes

In my particular situation, I cannot use the same variable, as I need to be able to reference the dictionary by the two values in the Vector2. I still appreciate your feedback!

That’ll do the trick nicely. Thank you so much!

This is a fantastic solution. Thank you so much for your help!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.