Add Me!Close Menu Navigation

Learn Lua the Hard Way

This series more or less mirrors the series of the same name for Python. It’s in my belief that the only way to learn the in and outs of a language is to learn by practice, and by that virtue, to practice as often as possible until you get the hang of the language.

1. Other Tutorials

Chapters 6–10 → The Table Tutorial.
Chapter 11. The project team problem part 1

2. Table of contents


3. Introduction

This tutorial is targeted at people who have never been exposed to programming previously but have mastered the elementary functions of a computer and wish to get the most out of their experience. The same goes for people who are coming from a game or application that utilizes the Lua engine for third party modding support but are a little more than intimidated by the unnatural feel of programming languages.

After completing these tutorials, you will have command of the most common features of Lua and the necessary problem solving abilities to perform some of the most common tasks that all programmers need to understand.

In order to complete this tutorial and in turn gain an understanding of the Lua programming language (as well as the general skills necessary to program a computer using any arbitrary language), you must do the following:

  1. Go through each exercise
  2. Type in each example exactly
  3. Run it (or correct it and make it run if it refuses to)

This all sounds remarkably similar to the introduction of “Learn Python the Hard Way”, and I apologize for my lack of originality, but the fundamental philosophy of that book resonates with me and so too shall I attempt to follow its author’s style of teaching in order to help you gain the most from this tutorial. If you are interested in Python, I highly recommend that book.

4. The setup:

http://code.google.com/p/luaforwindows/downloads/list

As Lua is mainly used as an embedded language within the industry, most of the tools provided with the “Batteries Included” philosophy will not commonly be included in your working environment. Nevertheless, on most embedded platforms running Lua, you’ll still be able to extend the language with external libraries at your own discretion so you’ll still be able to use these tools. But for all practical purposes, I will attempt to stick as close as possible to the vanilla distribution of Lua in the course of this tutorial.

5. Chapter 1: A first program.

This exercise will introduce you to writing and running a complete Lua program.

After installing LuaForWindows, you should have an icon on your desktop with the label SciTE. Open it

In the blank text area, type in

print("Hello World")
print("Hi again")

Now go to your My Document directory and create a new directory titled “learn_lua” (This isn’t really necessary, it just helps) and save this code as ex1.lua by pressing ctrl+s or the save icon on the toolbar and navigating to the new directory.

You can now run the program by either pressing F5 or clicking on the blue Play button on the toolbar.

You should see the following output:

Hello World
Hi again

Additional exercises:

  1. Make the program display another line containing “Hi from Lua”
  2. Print another line of text of your choosing.
  3. Put -- at the beginning of the first line, what do you see?
  4. What if you delete one of the double-quotes? What will happen?
  5. What if you replaced all of the double-quotes with single-quotes? what will happen?
  6. How can you print out "I have a quote in front of me?
  7. What will happen if you just get rid of all of the parenthesis?
  8. What happens when you type in print("Hello","World")?

6. Chapter 2: Comments

As your program begins to grow, you will invariably write certain pieces of code so complex that it even makes you scratch your head the next time that you read through it. Imagine how that code will look after a good night of sleep. This is where descriptions of your code that do not actually contribute to the program are useful. Such strings of text are called comments and are prefixed with two dashes (--)

-- Here's a piece of comment that describes what the program does.
-- The following line of code prints out some text
print("Some random text...")
-- Two dashes found in a print text are not comments
print("-- This will still print")

print("There's a comment after this") -- Comments can also come after the code.

-- In fact, everything that comes after -- in code not inside of text are comments.

Output:

Some random text...
-- This will still print
There's a comment after this

Additional Exercise:

  1. If you type in print (-- "hello there"), what will happen?
  2. Can you explain why 1. throws an error?
  3. What about print -- ("Hello World!")?

7. Chapter 3: Numerical Arithmetic

Mathematics is an integral part of programming. After all, we don’t call a computer a computer for no reasons. By definition, any machine or complex system that can logically compute certain systems of problems can be categorized as a computer. To this end, our modern computer is rather a be-all-end-all solution as it can pretty much compute nearly every class of problems out there. Anyways, Lua define numbers by their numerical literals, so that 1 is 1, 50 is 50, and so on. Decimal numbers and negative numbers are also valid so you can have something like 0.12 or -10, even -10.12.

In order to work with these numbers, Lua also provides a set of numerical operators. Most of these operators are binary, meaning that they need 2 and exactly 2 numbers or operands in order to perform a computation, they are:

  1. + (add, as in 1 + 1 = 2)
  2. - (subtract, as in 1 – 1 = 0)
  3. / (divide, as in 6 / 2 = 3)
  4. * (multiply, as in 2 * 5 = 10)
  5. % (remainder, as in 5 % 2 = 1 → 5/2 = 2 remainder 1, or 2 + ½)
  6. ^ (exponent, as in 2 ^ 3 = 8)
  7. == (equals, as in 1 == 1 is true)
  8. < (less than, as in 1 < 2 is true)
  9. > (greater than, as in 2 > 3 is false)
  10. <= (less than or equal to)
  11. >= (greater than or equal to)

print(1)
print(1.1)
print(-10.12)
print(1+2)
print(1-1)
print(6/2)
print(2*5)
print(5%2)
print(2^3)
print(1<3)
print(2>3)
print(1<=2)
print(2>=2)

Output:

1
1.1
-10.12
3
0
3
10
1
8
true
false
true
true

Before we continue, know that you can bring out the Lua interpreter by typing lua in your run/search textbox in the Windows Start menu.

Additional Exercises:

  1. Write a program that computes the average of the following numbers: 95, 100, 76, 83, 91
  2. What will happen if you type in print(5/2)?
  3. What will happen if you type in print(1.9999999999999)?
  4. What will happen if you type in print(1.99999999999999)?
  5. How do you compute 2 to the 16th power?
  6. Can you find 2 to the 16th power without using any mathematical operators or typing in the answer in decimal form? (Hint: google for base16 literals)

8. Chapter 4: Variables

Having the ability to compute and print numbers and text is nice, but what if you need to store the results somewhere so that you can use it later? Lua allows you to assign values to arbitrary names or identifiers as long as they do not contain spaces or non-alphanumeric characters except for the underscore (_) or are keywords.

a = 1
b = 1

print(a + b)
a = a + b
print(a*b)

Output:

2
2

Unlike in many other statically typed languages, declarations do no need to be prefixed with its type, hence each name can correspond with any object. This is especially powerful, but with power also comes responsibility. Do not do something like this

omg = print
print = 2^16
omg(print) -- print(2^16), but it looks so confusing....

Output:

65536

Hence there are a few best practices to consider when naming objects in Lua:

  1. Make sure that a name is meaningful if you’re going to use the object associated with it multiple times.
  2. When a name contains two words, the Lua “convention” for such a name would be word1_word2 (word1 underscore word2). This is to maintain readability, but if you need more than 2 words to describe some variable/object, please just shorten. Something like the_sixteenth_power_of_two is a bit too verbose.
  3. Temporary objects that are used only a few times or are used as counters are usually denoted with i, j, k, n, or m. (You can choose to not follow this rule, as it contradicts the first rule a little bit)

For example, if we wanted to find the velocity of a car, who travels 100 kilometers in 1 hour, we can express this in Lua code:

distance = 100 -- kilometers
time = 1 -- hour
velocity = distance / time 
print("The car is traveling at a velocity of",velocity) -- but where is the unit?

Output:

The car is traveling at a velocity of  100

Additional Exercises:

  1. is _ = 3 a valid statement? How about __ = 3? (2 underscores)
  2. What about for = 3?
  3. Can you find any other words that can’t be used as a name for an object?
  4. How about a = a? (Where you haven’t used a before)
  5. If you assign a = 3, what will happen if you print(A)?

9. Chapter 5: Strings.

Strings are basically blocks of text. The name is derived from the fact that they are literally a “string” of characters or letters+numbers+everything else. We can assign strings to variables and identifiers just the same as numbers.

text = "Hello World"
print(text)

Output:

Hello World

We can also paste two pieces of text together in an operation known as concatenation. To do this, we place .. (two dots) between two pieces of string.

space = " "
text = "Hello" .. space .. "World"
print(text)

Output:

Hello World

Up until now, we’ve used code with print(...) quite profusely, but we’ve never quite discussed what it is, we just assume through common sense that by typing this out, the ... in print(...) will be printed onto the screen through some form of dark magic. Well, print is a function, which is a little different from what the algebraic equivalent means. A function in Lua is a block of code that does something, anything. That may seem a bit general right now, but let’s just accept that definition as we’ll be discussing about functions later on in the series. But to start off, print is only one such function that can work with strings, there’s an entire module of different functions that can be used to manipulate a string. We’ll start off with a very simple one that is used quite often:

string.sub(text, i, j)

text = "Hello World"

print(string.sub(text, 2))
print(string.sub(text, 1, 10))

Output:

ello World
Hello Worl

If you haven’t figured it out yet, the string.sub function takes in a string and 2 numbers (a,b) and returns everything in the string starting in the a position and ends at the b position. This is called a substring, and it is quite useful in string manipulation.

We will look at several other string functions in the future, but in the meantime.

Additional Exercises:

  1. Find out what the purposes of string.byte, string.find, string.len, string.lower, and string.rep are.
  2. Find the third letter of "Hello World".
  3. Find the last 4 letters of "Hello World".
  4. What happens when you enter #"", how about #"W00T"?
  5. What will "asdf" == "asdf" be?
  6. What will "ASDF" == "asdf" be?
  7. What will "asdf" > "asdf" be?
  8. What about "asdf" > "asdf"?
  9. What about "asdfb" > "bsdf"?
  10. Generalize what >, <, >=, <=, and == do with strings.

Continue to Part 2 about tables.

10. To be continued...

That is it for now. If you find this tutorial to be too slow for your liking, then please visit http://luatut.com/crash_course.html for a more comprehensive introduction to the Lua language.

Posted By Lee

Woosh

  • Anonymous

    Awesome to see you working on more Lua tutorials, loved the luatut series. When you are you going to update it with Functions and metatables and the like?

  • |fruit|

    the letters are so big :L
    nice tut

  • http://phailed.me/ Phailure

    @TheAncientGoat: Thanks man, I didn’t think anyone actually read my Lua tutorial so I haven’t really thought about continuing it, but I definitely will be updating it in the near future (as soon as my midterms are out of the way)

    • Anonymous

      I replied to the post on your other blog, but it seems you missed that one. I’ve been looking for absolute beginner Lua tuts for a game engine/platform I’m working on, and you do very well in that regard, so please do continue!

      Our lead engine dev (quaker66, maybe you know him) has read a lot of your stuff as well, so you’re like the unseen inspiration behind the project ;)

      • http://phailed.me/ Phailure

        Oh yeah, the IntenseDebate plugin started acting up so all of the comments created after June of 2010 were deleted automatically, which is why I went back to the default comment system on the Failboat blog.

        You just made my day :D, thanks for the kind words and I’ll be sure to update you guys when the new tutorials come out.

  • http://twitter.com/pixiemars Mike Pixael

    Hey dude, I would love to see more of this!

  • Liam Jones

    Brilliant tutorial! Really appreciate the work you have put in here!

  • Pingback: .:[ d4 n3wS ]:. » Learn Lua the hard way

  • Zeljko Dakic

    It is really nice tutorial, it helps understanding Lua better, however, I think you should pick different name, Zed Shaw is pretty much created his brand and this looks to me like you would like to piggy-back on good will he created. Anyhow, I would just name it differently, it can be Learn Lua the Right Way if you like this expression.

    • http://phailed.me/ Phailure

      Hey, thanks for bringing that up. I originally started off with Shaw’s python tutorial and that was such an eye-opener that I decided to write something similar for Lua in his honor. I never realized that he began a Learn x the Hard Way series soon after I began. Unfortunately, college and life caught up with me soon afterwards and I haven’t really had the time or motivation to update the series. I’ll try to come up with another name for this series so Shaw can have the namesake back.

  • http://twitter.com/mawaldne Mike Waldner

    More please. Good stuff!

  • Pingback: Tutoriels | Pearltrees

  • Viorel Bianu

    Thanks, it’s a very nice introduction!

  • Pingback: To read 2 | Pearltrees

  • PaulRNeubauer

    My question, which, admittedly, may be out of order since I already followed a link that got me here, is “Why do I want to learn Lua?”

    I’m not at all saying that I don’t want to, but if I do, I don’t yet know it yet. What can I do with Lua that I can’t do with a couple of dozen other languages? Or, more likely, what can I do better with Lua than with those couple of dozen other languages? There has to be a reason that someone created Lua. What was it? 

    • http://phailed.me/ Phailure

      No, that’s a perfectly reasonable question to ask, and I’m embarrassed to say that what I know is only hearsay from other people passed down to me when I started using Lua (I was an active player in the community of an extremely small scale indie shooter game back in 08, and I asked the creator of the game the same exact thing)

      Lua was born from a language (DEL) that was mainly used to keep track of program settings and configurations (really just a glorified parser, hash table, and printer that supports a few common arithmetic operations). My guess (and this is just speculation) was that this was probably just a hobby project of one of the researchers there, and it just so happened to become extremely useful to them, so much so that it began to be shipped with their products. The language was such a hit with the users that TeCGRAF had no choice but to continually add features to the language. Eventually, they realized that the language was perfect as “that sidekick language.”

      And this is where Lua really shines. It’s extremely easy to embed Lua within C, and once you get used to handling Lua objects in C, it becomes the most useful thing ever, as you can just prototype your code directly into Lua, and translate the critical parts of your code into C on demand, I do this whenever I can afford it since debugging Lua is (sometimes) much easier.

      Furthermore, because of its embedability, it became hugely popular within the video game industry as the lightweight scripting language glue. Recently, both the Android and the iPhone development communities have began taking an interest in Lua as well (see Corona and Codea)

      Anyways, Lua can’t compete feature wise with some of the other modern languages out there such as Python, Ruby, or Javascript since its standard library is woefully lacking. However, as a language that you can easily plug in anywhere for temporary plumbing or gluing, Lua is great

      • middleware

        I think the lack of standard library is a blessing in some sense. For most developers seeking for a solution of scriptability of their product, a robust C interface is important. Much more important than a standard library, which is trivial to borrow from POSIX/STL/boost/… if you have the best C interface in the first place.

        Lua’s C interface is elegant per se. And most important, its maturity is incomparable. Because of the lack of a standard library, every Lua programmer has to test the interface somewhat. Other programming languages do not undergo such rigor test, only their standard library developer test the interface, and such a narrow group of developers usually use workaround for bugs rather than fix them as the document supposed strictly.

        And I don’t think competing feature wise is impossible. Lua is Lisp without full continuation and macro. That’s a fantastic feature list.

    • http://phailed.me/ Phailure

      Also, and don’t tell anyone else I said this, I’ve found the (main) Lua community to be much more receptive to beginners and are generally nicer people, which is something I don’t see very commonly whenever I browse r/programming. This was probably a major factor in my sticking with Lua in the first place

  • Pingback: [LotRO] Lua Plugins and you! « Shards of Imagination

  • Pingback: Programming Guides | Sam Snyder

  • Pingback: Internet, Computers, Mobiles & Engineering | Pearltrees

  • Wilson

    Hey, nice tutorial, really helpful. At the last section it looks like Additional Exercises 7 and 8 are the same thing.

  • Pingback: URL

  • Pingback: Chapters 1–5 → An introduction to Lua. | CodingSnake

  • http://moebiuseye.jeannedhack.org/ moebius_eye

    Very good start for a non-programmer. I come from python and C. I hope to see some interesting posts in your RSS.

  • RootProgram

    I’m from not-so-advanced VBScripting.

    print(1/0)

  • Pingback: Embedded Development with Lua in NetBeans | Google Trender

  • joshywoods

    I don’t understand how a substring works? Could you explain it to me?

  • Pingback: cigarettes sale - buy online smokes