How to use a dictionary?

hello I’m having issues with a dictionary.

local PosPosPos = {
	Pos1 = {UDim2.new(0.092, 0,0.343, 0), UDim2.new(0.861, 0,0.343, 0)},
	Pos2 = {UDim2.new(0.092, 0,0.612, 0), UDim2.new(0.861, 0,0.612, 0)},
	Pos3 = {UDim2.new(0.092, 0,0.887, 0), UDim2.new(0.861, 0,0.888, 0)},
}
	local Randompos = PosPosPos[math.random(1,3)]
	clone.Position = Randompos[1] <- attempt to index nil with number
	clone:TweenPosition(Randompos[2])

The script is erroring at the part where it says

clone.Position = Randompos[1]

and the error is clone.Position = Randompos[1]

I don’t know why it errors as in my mind it should work

Dictionaries use non-integral keys (that’s why they’re called dictionaries)

So for example, Pos1, 2 and 3, are the keys.

Meaning, their values are not bound to numerical indices, so attempting to use a numerical index will return nil.

It doesn’t seem you need to use a dictionary here. Get rid of your keys and it should work as intended. Or, you can just concatenate the key:

PosPosPos["Pos"..math.random(1,3)]
1 Like

This is the problem. A dictionary-like table is still a table: There are keys, corresponding to values. When you get a random number, it’s a number. However, none of the keys are numbers in the table: The keys are strings (in a table a = b is the same as ["a"] = b); Pos and a number afterwards. Concatenate "Pos" with the random number:

local Randompos = PosPosPos["Pos" .. math.random(1,3)]

It doesn’t error on that line, since that will return nil. And then, Randompos is nil, and you’re trying to index it. That’s why you get attempt to index nil with number.

@KrimsonWoIf I think you should choose @C_Sharper’s reply as the solution, he posted it before me

2 Likes

so like local Randompos = PosPosPos[“Pos”…math.random(1,3)]
clone.Position = Randompos[1]
clone:TweenPosition(Randompos[2])