Luatic
Luatic

Reputation: 11171

Difference between t.foo and t[foo] in Lua

Given a table

t = {foo = "bar", bar = "foo"}

and a variable

foo = "bar"

what's the difference between

print(t.foo)

which prints "bar" and

print(t[foo])

which prints "foo"

Upvotes: 2

Views: 94

Answers (1)

Luatic
Luatic

Reputation: 11171

t[expr] is the indexing operation, where t is the table to be indexed and expr is the expression of which the value is used as key. t[foo] thus evaluates to t["bar"]. The value for the key bar is the string foo. Thus print(t[foo]) prints "foo".

t.name is merely a shorthand for t["name"] where name matches Lua's lexical convention for an identifier:

Names (also called identifiers) in Lua can be any string of Latin letters, Arabic-Indic digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels.
- Lua 5.4 Reference Manual

This means that name is not evaluated as the expression name but rather as the string literal "name" when indexing the table. Thus t.foo is equivalent to t["foo"] which evaluates to bar.

TL;DR: To index tables with the variables of values or other expressions, use t[expr]. In particular you must use t[index] to index the list part of tables. You also have to use t[expr] if expr is a string literal that does not qualify as an identifier (ex: t["foo-bar"]). To index tables with keys that are names / identifiers, use t.name.

Upvotes: 3

Related Questions