Conditionals in dictionaries

Main Question:

Can you use the conditional blocks such as or or and

	["Banana" or "Plantain"] = {
		["Value1"] = 1,
		["Value2"] = 1.25,
		["Value3"] = 1.5,
	},

-- I've tried something like this

Upon trying this method and calling Plantain it errored.

If there is anyway to work around this issue It would really help.

Thank you.

You can’t use or like that but you can create the table containing the values beforehand and then assign the same table to keys “Banana” and “Plantain”.

local values = {
    ["value1"] = 1
    ["value2"] = 1.25
    ["value3"] = 1.5
}
local dictionary = {
     ["Banana"] = values
     ["Plantain"] = values
}
4 Likes

^ as a bonus, if you change the values table later, it will change for both keys.

3 Likes

In that situation, the conditional will check the first key to determine if it is nil or not. If it isn’t, it will assign “Banana” as the key. However, if “Banana” is nil, then it will check the next value in the conditional and try to assign it in the table.

local test = {}
local key1 = nil
local key2 = "apple"

test = {
	[key1 or key2] = {
		1, 2 , 3
	}
}

print(test) -- outputs : {"apple" = {1, 2, 3}}

Edit: As a side note, you can use any conditional you want in a table, but some have unintended effects.

local key1 = "banana"
local key2 = "apple"

local key3 = nil
local key4 = "apple"

test = {
	[key1 and key2] = { -- assigns "apple" as the key
		1, 2, 3
	},
	
	[key3 and key4] = { -- errors out, because (nil and "apple") = nil
		4, 5, 6
	}
}
local key1 = 5
local key2 = 7

test = {
	[key1 <= key2] = { -- assigns true as the key
		1, 2, 3
	},
}
1 Like

^^ as a bonus bonus, if you don’t want that behavior you can simply clone/copy the ‘values’ table instead of assigning it directly. There’s also some stuff you can do with weak/strong tables but I’m not sure if roblox’s luau implements any of that, I’m kinda new here.

1 Like