Chapter 3. Extending Lua with Functions

One of the key concepts in programming is abstraction, which means ignoring unimportant details. Consider the following set of instructions:

  1. Get two slices of bread, a jar of peanut butter, a jar of jelly, and a butter knife.

  2. Using the butter knife, spread a thin layer of peanut butter on one side of one piece of bread.

  3. Using the butter knife, spread a thin layer of jelly on one side of the other piece of bread.

  4. Attach the two pieces of bread together by pressing the peanut-buttered side of the one to the jellied side of the other.

Now compare those instructions with the following:

  1. Make a peanut-butter-and-jelly sandwich.

The first set of instructions is less abstract than the second, because it contains details that would only be helpful to someone naïve in the ways of sandwich preparation. The second set of instructions abstracts away these details. Consider the following code:


This is less abstract than the following code:

for I = 1, 10 do

Both examples do the same thing, but the second one takes advantage of the fact that Lua knows how to count. This demonstrates one of the benefits of abstraction—there's less to type! A related benefit is that it makes code easier to understand: When you know how for loops work, you can tell at a glance that the second example prints the numbers from 1 to 10, whereas you'd only know that for sure about the first ...

Get Beginning Lua Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.