How do I store x y values in a table?

Hey guys, I’m trying to store both x and y values in the same table like in python. How would I do this?

Here’s a screenshot of the table in the python:
image_2024-04-08_234222841

Any help is appreciated :pray:

white_locations = { {0, 0}, {1, 0} } --etc
-- Instead of brackets / Parenthesis, you use Curly Braces

print(white_locations[1][2])
-- first index / second value (Y)
-- or 
print(white_locations[1][1])
-- first index / first value (X)

Alternatively, you can use the Vector2 DataType for this purpose, which would simply the process:

white_locations = {Vector2.new(0, 0), Vector2.new(1, 0)} --etc
print(white_locations[1].Y)
-- or 
print(white_locations[1].X)

The only different thing worth noting is that the table index in Lua begins at 1, while Python (afaik) begins at 0 by default.

2 Likes

Since you are only using integers I suggest something like this:

local white_locations = {Vector2int16.new(0, 0), Vector2int16.new(1, 0), ...}

Adding on to the above replies, Vector3 is a LOT better of a choice for storing collections of two numbers than Vector2, Vector2int16 or a table like {x, y}. It uses less memory and is faster to operate on.
This is because Vector3s were recently (a few years ago) made actual Luau data types instead of userdata.

v = Vector2.new(1, 2)
print(type(v)) -- userdata
t = {[v] = 123}
print(t[Vector2.new(1, 2)]) -- nil because this is a different object

v = Vector2int16.new(1, 2)
print(type(v)) -- userdata
t = {[v] = 123}
print(t[Vector2int16.new(1, 2)]) -- nil because this is a different object

v = Vector3.new(1, 2)
print(type(v)) -- vector
t = {[v] = 123}
print(t[Vector3.new(1, 2)]) -- 123 because two of the same Vector3 are the same just like 1 and 1 are the same
1 Like

Their original question didn’t include the need for these placeholder 123s. Assigning Vector3s with missing parameters is incredibly slow as well. Vector2int16 is also way less memory intensive in larger scales than Vector3.

2 Likes

Ok tysm this worked. Btw I got a question, how would I check if {0,0) was is white_locations?

Here is an example of what I mean in python:
image_2024-04-17_230226946

For that, you’d have to make a function:

local function coordinate_in_location(x: number, y: number): boolean
   for _, coordData in white_locations do
       -- Loops through the array to check every coordinate individually
       -- See https://create.roblox.com/docs/luau/control-structures#generalized-iteration for more info
       if coordData[1] == x and coordData[2] == y then
           return true -- Coordinate data matches the provided x and y coordinate
       end
   end
   return false -- No coordinates matched
end
1 Like

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