Table manipulation in Lua


In Lua, arrays are tables. Tables can be iterated over using inbuilt functions such as pairs. Tables can have indexes other than numeric values. The example below creates two tables, adds contents of one to another, then prints the data in the resulting table.

table1 = {
  ["red"] = {Description="Red", RGB=0xFF0000},
  ["green"] = {Description="Green", RGB=0x00FF00}
}

table2 = {
  ["blue"] = {Description="Blue", RGB=0x0000FF}
}

for color,val in pairs(table1) do
  table2[color] = table1[color]
  -- or table2[color] = val
end

for color in pairs(table2) do
  print(string.format("%06x - %s", table2[color].RGB, table2[color].Description))
end

Here’s how the output looks. The order in which the colors appear is entirely unpredictable.

0000ff - Blue
00ff00 - Green
ff0000 - Red

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s