Hi, I want to know if there’s any difference in the output of tableName[keyName] and tableName.keyName in a table / dictionary
I know tableName.keyName only allows strings, and its like calling a children ig, it also prints out the same thing.
Is tableName.keyName useless since you can use tableName[keyName]?
Is there a more optimal one?
You can use either one. It just depends on the property name and how you prefer to index properties
3 Likes
Doing tableName.keyName
will return nil if keyName
does not exist.
Doing tableName[keyName]
will add keyName
if it doesn’t exist. If keyName
does exist, then it will replace keyName
with the new value.
I could be slightly wrong in either of these.
This only happens if you assign a value to the key. This happens between both methods, so this is not a recognizable difference between the two
1 Like
local tableName = {
sarah = '1',
hannah = '2',
ameera = '3',
["dülpeşa"] = '4',
keyName = '5',
["greqbool"] = '6',
}
for keyName, _ in next, tableName do
print(tableName[keyName])
print(tableName.keyName)
print()
end
1
5
2
5
3
5
4
5
5
5
6
5
1 Like
Both your code and output do not make sense, and realistically result in error. Please do not misinform
2 Likes
I apologize for the misinformation. As @HugeCoolboy2007 stated, they both yield the same results in most circumstances, but the difference lies in what dot notation cannot do compared to bracket notation. Dot notation requires you to specify an exact index in legal syntax, which means:
- Syntax violations, such as spaces, fully numerical identifiers (arrays), prefixes, and special characters, cannot appear in the key name.
- The key must be explicitly stated; you cannot use variables in index operations (dynamic queries).
Bracket notation solves these issues while also offering the same features as dot notation. However, bracket notation requires more code and can lead to unreadable code if overused—imagine using bracket notation to index everything, even properties. There is no performance benefit to using one notation over the other, so it ultimately comes down to personal preference or circumstance.