Professional Documents
Culture Documents
Programming in Lua
Part I. The Language
Chapter 2. Types and Values
2.5 – Tables
The table type implements associative arrays.
An associative array is an array
that can be indexed not only with numbers,
but also with strings or any other
value of the language,
except nil.
Moreover, tables have no fixed size;
you can
add as many elements as you want to a table dynamically.
Tables are the main
(in fact, the only) data structuring mechanism in Lua,
and a powerful one.
We
use tables to represent ordinary arrays,
symbol tables, sets, records, queues,
and other data structures,
in a simple, uniform, and efficient way.
Lua uses
tables to represent packages as well.
When we write io.read,
we mean "the
read entry from the io package".
For Lua, that means
"index the table io using
the string "read" as the key".
k = "x"
print(a["x"]) --> 10
k = 20
print(a["x"]) --> 11
a["x"] = 10
print(b["x"]) --> 10
b["x"] = 20
print(a["x"]) --> 20
a = {} -- empty table
print(a[9]) --> 18
a["x"] = 10
print(a["x"]) --> 10
a = {}
x = "y"
a = {}
for i=1,10 do
a[i] = io.read()
end
print(line)
end
a = {}