Search code examples
lualua-table

why is tables in lua designed in this way?


I am confused about below grammer in language lua:

w = {x=0, y=0}
w[1] = "another"

in my opinion, the first sentence descirbe the w as a dict-like strcture and next a array, are the w of the first and of the second same? if so, why? why can two different things can be stored in a w?

I'm a rookie in lua and also in english, pardon.

I want to know some thoughts of designation of lua and the explanation of my qustion.


Solution

  • An array is conceptually just a series of key/value pairs. It's just that the "keys" are all integers and are a sequence of integers starting from (in Lua's case) 1.

    Lua recognizes that a "dictionary" and "array" are really the same thing. It bundles these two concepts together into a single type: Lua's "table".

    In a Lua table, keys can be (almost) anything. Including integers. Including integers starting from 1 and increasing. As such, a Lua table is said to have an "array portion", which are all of the integer keys from the integer 1 to the highest integer whose value is not nil. This is what it means to take the "length" of a table.