Storing positions in a table

Hi. Quick question.

I want to store coordinates inside of a table, but how would I go about doing that?

I thought maybe something like this would work:

local coordinates = {
	["pos1"] = {22813.625, 1059.75, 2973.25},
	["pos2"] = {22991.992, 1216.25, 2255.659},
	["pos3"] = {30635, 1219.75, 2234.5}
}

print(coordinates["pos3"])

But that just prints everything in the table assigned to it.

image

I know I can just use CFrame/Vector3 instead but… I want to see if theres other solutions first. Also thats cheating and I kind of don’t want to :sunglasses:

1 Like

Instead of saving a table in a table, can’t you just save a Vector3 for each value?

Try something like this:

local coordinates = {
	["pos1"] = Vector3.new(22813.625, 1059.75, 2973.25),
	["pos2"] = Vector3.new(22991.992, 1216.25, 2255.659),
	["pos3"] = Vector3.new(30635, 1219.75, 2234.5)
}

print(coordinates["pos3"])

Vector3 is a DataType. It is how you directly set the X Y Z of parts in roblox. You just made 3 values containing containing a table containing 3 numbers.

:(( Are you telling me this is the only way to approach this?

… maybe this is what you’re looking for?

local vectorPos = Vector3.new(unpack(coordinates["pos3"]))
print(vectorPos)
2 Likes

Not at all. You can of course save the data into a table instead. You could have also done something like this:

local coordinates = {

["pos1"] = {22813.625, 1059.75, 2973.25},

["pos2"] = {22991.992, 1216.25, 2255.659},

["pos3"] = {30635, 1219.75, 2234.5}

}

function printCords(cordKeyName)

print(Vector3.new(coordinates[cordKeyName][1],coordinates[cordKeyName][2],coordinates[cordKeyName][3]))

end

printCords("pos3")

That script will create a correctly constructed Vector3 value without changing the dictionary at all.

If you don’t want to use Vector3 or CFrame, you can try using tons of tables and nest them into each other to represent the axes. Only downside is that its really complicated to work with.

--use tostring() so you can use negative or decimal indexes
local t = {}

function setPos(x, y, z)
  if not t[tostring(x)] then
    t[tostring(x)] = {}
  end
  if not t[tostring(x)][tostring(z)] then
    t[tostring(x)][tostring(z)] = {}
  end
  t[tostring(x)][tostring(z)][tostring(y)] = true --you can set it to anything
end

setPos(-36, 4.5, 33)
--in X, Z, Y order
print(t['-36']['33']['4.5']) --prints true

You can use negative/decimal indices without converting them to a string :smiley:

local a = { } a[-1.1] = 'b' print(a[-1.1]) --> b

Yeah… I think i’ll just use mew903’s method. Thanks anyway!