0

I feel like this is a really silly question...

t = {
a = {x,y},
b = {z},
}

How do I print the first value of the key 'a'? ("x") Neither

print(t["a"][1]) 

nor

print(t.a[1])

does it, so how would I go about?

What's the difference between '[]' and '.' btw?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Easypeasy
  • 150
  • 2
  • 11

2 Answers2

3

What's the difference between '[]' and '.' btw?

The dot is just a shortcut / syntax sugar for the index operator [] with strings. foo.bar is equivalent to foo["bar"]. foo[bar] on the other hand would return the value at the index of the value of the variable bar, so if bar happens to be baz it would do foo["baz"] / foo.baz.

You must use the []-syntax when using strings which are no valid Lua identifiers ("variable names") or non-strings as indices, like foo["Jon Doe"] or foo[3].

Oberon
  • 3,219
  • 15
  • 30
1

In this code, x, y, and z are all undefined and so t.a and t.b are empty tables. My answer to your previous question stores x, y, and z as strings (but as keys, not as values).

Community
  • 1
  • 1
lhf
  • 70,581
  • 9
  • 108
  • 149