Back to Blog

Learn Lua in Neovim: Table Array Operations — Sort, Concat & Custom Comparators | Episode 18

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Table Array Operations — Sort, Concat & Custom Comparators | Episode 18 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Table Array Operations — Sort, Concat & Custom Comparators

In this tutorial, you'll learn how to manipulate Lua arrays (tables) effectively within Neovim. We'll explore sorting arrays with table.sort, joining elements into strings using table.concat, creating custom sort orders with comparator functions, and modifying arrays by inserting or removing elements at specific positions.

Code

-- Define an array of names
local names = { "Zara", "Alice", "Bob", "Charlie" }

-- Sort the array in ascending order (in-place)
table.sort(names)

-- Concatenate array elements with a comma and space separator
local joined_names = table.concat(names, ", ")
print("Sorted names: " .. joined_names)

-- Custom comparator to sort in descending order
table.sort(names, function(a, b)
  return a > b  -- sort descending
end)
print("Descending order: " .. table.concat(names, ", "))

-- Insert a new name at position 2
table.insert(names, 2, "Diana")
print("After insert: " .. table.concat(names, ", "))

-- Remove the element at position 4
table.remove(names, 4)
print("After remove: " .. table.concat(names, ", "))

Key Points

  • table.sort(t) sorts the array t in place in ascending order by default.
  • table.concat(t, sep) joins all elements of t into a string separated by sep.
  • Custom comparator functions passed to table.sort allow flexible sorting, such as descending order.
  • table.insert(t, pos, value) inserts value at the specified position pos in the array.
  • table.remove(t, pos) removes the element at position pos from the array.