Tables

  • Tables are associative arrays
    • Can be indexed with number or strings (common way of doing this)
      • or with other values of the language except nil
  • Tables are the main data structures of the language
    • The only primitive data structure
  • They are dynamically allocated
  • A program has references to them
  • They are created by a constructor expression

a = {} -- creates a table and puts a reference in a a["earth"] = "imageEarth.jpg" -- put the filename of an image into a at key "earth" print(a["earth"]) -- prints the string "imageEarth.jpg" a[10] = "imageMars.jpg" print(a[10]) print("The earth image is " .. a["earth"]) -- use the alternate syntax for a["earth"] print("The earth image is also " .. a.earth) local image = "earth" print ("This also gives the earth image " .. a[image]) -- assigning functions to variables (be careful) printFunction = print printFunction("this is a string") a["printIt"] = print a.printIt("Printing using an index into a table reference")

Table Constructors

-- The simplest constructor a = {} -- an empty table print(a[1]) -- table indexed by integers b = {"Earth", "Mars", "Saturn", "Jupiter"} print (b[1]) -- table with string indices c = {x="Earth", y="Mars", z=10} print(c.x) print(c["x"]) print(c.z) -- nesting tables within tables d = {x="Piano", y={"Trumpet", z="Violin"}} print(d.x) print(d.y[1]) print(d.y.z)

References