Tables as Data Structures
Numeric Lookup
Array-style Lua tables use numeric indexes starting at 1.
one based index
Read a value by putting the numeric position inside brackets.
Numeric Lookup
numeric_lookup.lua
Replay: real traced execution (multi-file project)
local index = 2
local color = ({"red", "blue", "green"})[index]
print("index=" .. index)
print("color=" .. color)
local index = 1
local color = ({"red", "blue", "green"})[index]
print("index=" .. index)
print("color=" .. color)
local index = 3
local color = ({"red", "blue", "green"})[index]
print("index=" .. index)
print("color=" .. color)
index ← 2, color ← blue
1local index→ 2 = 2 --@index=1, 32local color→ blue = ({"red", "blue", "green"})[index]blue34print("index=" .. index2)5print("color=" .. colorblue)outputindex=2 color=blue
index ← 1, color ← red
1local index→ 1 = 12local color→ red = ({"red", "blue", "green"})[index]red34print("index=" .. index1)5print("color=" .. colorred)outputindex=1 color=red
index ← 3, color ← green
1local index→ 3 = 32local color→ green = ({"red", "blue", "green"})[index]green34print("index=" .. index3)5print("color=" .. colorgreen)outputindex=3 color=green
Pick by Position
- The table holds
red,blue, andgreen. - Lua positions start at
1. indexis2.- The lookup returns
blue. | Index | Value | Selected? | | --- | --- | --- | |1|red| no | |2|blue| yes | |3|green| no |
Exercise: numeric_lookup.lua
Pick a color from a table by numeric index and print the index and color