Back to Blog

Learn Lua in Neovim: Tables as Arrays — 1-Based Indexing, Insert, Remove & Length | Episode 17

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Tables as Arrays — 1-Based Indexing, Insert, Remove & Length | Episode 17 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Tables as Arrays — 1-Based Indexing, Insert, Remove & Length

Lua's tables are versatile and fundamental, serving as arrays, dictionaries, and more. In this example, we focus on using tables as arrays: creating them with curly braces, understanding Lua's 1-based indexing, measuring length with the hash operator, and dynamically modifying arrays with table.insert and table.remove.

Code

-- Create an array-style table with fruits
local fruits = { "apple", "banana", "cherry" }

-- Access elements using 1-based indexing
print("First fruit:", fruits[1])    -- Output: apple
print("Third fruit:", fruits[3])    -- Output: cherry

-- Get the length of the array using the hash operator
print("Number of fruits:", #fruits) -- Output: 3

-- Insert a new fruit at the end
table.insert(fruits, "elderberry")
print("After insert:", table.concat(fruits, ", ")) -- apple, banana, cherry, elderberry

-- Remove the second fruit ("banana")
table.remove(fruits, 2)
print("After remove:", table.concat(fruits, ", ")) -- apple, cherry, elderberry

-- Loop through the array and print each fruit
for i = 1, #fruits do
  print(i, fruits[i])
end

Key Points

  • Lua tables are created with curly braces and can be used as arrays or dictionaries.
  • Array indices in Lua start at 1, unlike many languages that start at 0.
  • The hash operator (#) returns the length of an array-style table.
  • table.insert adds elements at a specified position or at the end by default.
  • table.remove deletes an element at a given index and shifts subsequent elements left.