Storing values

Tables store values; a table is a relational data structure. This makes the table similar to a dictionary in other languages. To store a variable in a table, use the following syntax:

table[key] = value

The following example demonstrates how to make a table, store a value with the key x, and how to retrieve that value:

tbl = {}
tbl["x"] = 20
i = "x"

print (tbl["x"])
print (tbl[i])

The key of a table can be any type (even another table!), except for nil. This makes the following code valid—hard to read, but valid:

tbl = {}

tbl["x"] = 10
tbl[10] = "x"

print ("x: " .. tbl["x"])
print ("10: " .. tbl[10])

If you use a string key for a table, you can access it with the dot syntax. This syntax allows you to access the same data, but is easier to type. The dot syntax feels more natural than braces.

The following code declares the x variable using a string key, then retrieves the value of x using a string literal, a string stored in a variable, and finally the dot syntax. Next, the sample code declares the y variable using the dot syntax:

tbl = {}
tbl["x"] = 20
i = "x"

print (tbl["x"])
print (tbl[i])
print (tbl.x)

tbl.y = 10

print ("x + y: " .. tbl.x + tbl.y)
print (tbl["y"])
print (tbl.y)

One last thing to note about storing values in tables is the default value. Just like global variables, if you don't assign a value to a key in a table, the default value is nil. The following code demonstrates this:

tbl = {}
-- z is never added to the table!
print (tostring(tbl["z"])) -- nil
print (tostring(tbl.z)) -- nil

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.230.81