Why do I see some people using ["foo"] = "bar", over foo = "bar" in a dictionary

I look at some peoples code, and I often will see many using [“foo”] in a dictionary as a key, which has always left me wondering, why not just use foo on its own instead. Are there any performance impacts, or is it simply preference?


local fruit = {
	apple = "Yummy";
	banana = "Better";


local fruit = {
	["apple"] = "Yummy";
	["banana"] = "Better";

It’s just preference. It does indeed more clearly outline what in the table is a key and what is a value, so some people may prefer that.

1 Like

Yes, that is why I used it in the title.

Okay. Do you know if there are any performance impacts?

I get what you mean now, there’s no performance impacts as far as I’m aware, some may consider using square brackets to allow for spaces within string indexes (any other reason is obvious, e.g number indexes can’t be defined without brackets) that’s all, or any other reason concerning preference.

The way you define your indexes isn’t consequential whatsoever to how they’re handled.

1 Like

If your key is a number_key, say someone’s userid, a string key will do over a key

local userid = consider:gen("id", 12) -- Returns a random int from the userid min to 10
local x = {
82832923 = userid -- error
local z = {
["82832923"] = safe
1 Like

Okay, so it would be more consistent to always use [“x”] instead?

1 Like

I only ever use it when I am using it in expressions, so it’s up to you

This will actually work if you put it in brackets, it doesn’t need to be a string.
[82832923] = userid
Actually, any variable or value can be a key so long as you put it inside of brackets. This allows you to create some unique shortcuts if you’re clever.

local partWeights = {
    [script.Parent.Body] = 15,
    [script.Parent.Chassis] = 30,
    [script.Parent.LeftWheel] = 5
    local playerData = {}
    for _, player in pairs(game.Players:GetPlayers()) do
        playerData[game.Players.Player1] = {kills, deaths, blah blah blah}