Aaron
Aaron

Reputation: 1051

Using strings containing integers as table keys

I realize this is usually not a great practice, but how would I use a string containing an integer (e.g. "7") as a table key? For example:

local myTable = {
  "1" = "Foo",
  "2" = "Bar"
}

If memory serves from reading the Lua manual back in the day, that should be possible with some special syntax, but what I've written above is a syntax error.

Upvotes: 1

Views: 231

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

Like this:

local myTable = {
  ["1"] = "Foo",
  ["2"] = "Bar"
}

Because the keys are not valid identifiers, you can't use the syntax sugar form.

Upvotes: 3

Related Questions