Fishy Magic

Arrays in lua

· by Jameson · Read in about 3 min · (445 Words)
Tags: code, lua

An important starting note: arrays in lua don’t really exist. Lua has only one aggregate type, called a table. But the table can do the job of just about any other aggregate type with some work.

Arrays are fundamental to programming, and serve as a good starting point for how tables work in general. But first…

What is an Array?

At its core, an array is what you think of as a list (don’t call it a list, that sometimes means something else). It is a simple list of elements, each one having an index in the array. You can create an array in lua as simply as

myArray = {}

That’s it! It’s empty, but it’s an array. You can set an element in the array using square brackets:

myArray[1] = "food"

This sets the first element of the array to "food". You don’t have to use explicit numbers, you can use variables too:

someVar = 3
myArray[someVar] = "eggs"

To make talking about this easier, it’s important to know that the bit inside those square brackets is called the ‘index’. It just means the number of the position in the array. In Lua, an array starts at index 1, and the next element is at index 2, and so forth.

If we wanted to see what was in our array we would not write

print(myArray[1])
print(myArray[2])
print(myArray[3])

and so on. Not least of all because it’s boring, but also because we don’t know how many elements there are in the array. Instead we would probably write something like:

for i, v in ipairs(myArray) do
	print(i .. ": " .. v)
end

which would print out the index and value of everything in the array automatically. ipairs is a special function for iterating over arrays. At each loop, i will be set to the current index (so 1 initially, then 2 etc), and v will be the value of the array at that position.

We can use this to do things like double all odd numbers:

for i, v in ipairs(myArray) do
	if v % 2 == 1 then
		myArray[i] = 2 * v
	end
end

(% is the modulo operator, it gives you the remainder after division)

As indicated above, arrays can contain any type at each index: numbers, strings, even other arrays.

Tables library

like ipairs there are a few functions for manipulating arrays more easily.

table.insert(myArray, 7) -- put the entry '7' on the end of the array
table.remove(myArray,2) -- remove the element at index 2, and move everything else down
table.sort(myArray) -- sort the elements numerically, or alphabetically
table.concat(arr1, arr2) -- combine two arrays into one

find out more here

Comments