Hello!
Welcome to the world of programming (in Lua).
Programming?
Programming is writing out instructions for a machine—a computer.
Like when learning a foreign language, there are many arbitrary rules and restrictions on how you are able to
explain how to do certain things.
Still, there's always a way.
Programming languages (like Lua) are made to be easy for both humans and computers to read. Computers are good at
reading assembly, while humans are good at reading English. Programming languages are somewhere in the middle.
Lua?
Lua is a dynamically typed, semi-functional, embedded programming language.
It is designed to be small and
simple.
Link to Java Image
Link to Java Image
Compile Java Online
Compile Java Online
Sound fun? Let's get started.
Hello, world!
It's in the tradition of programming instruction to start language teaching by having the computer say "Hello,
world!"
print("Hello, world!")
Hello, world!
So here's your first Lua program. print puts whatever is inside the ( ) that follow it
onto the output display. Here the output is shown in the box with the dashed outline below the code. Note that the color is
purely cosmetic - when writing Lua, the text isn't assigned colors. Color is used throughout this presentation for clarity
and emphasis. Also notice the quotation marks around the phrase. We'll get back to this later.
What else can we print?
print(12)
12
Numbers! Just put one in the parnetheses and it will be printed too!
Note that print must be spelled exactly this way and remain uncapitalized—in Lua, names are case-
sensitive.
What if you we want to do some work, though? We can put expressions of any kind inside print to get
it evaluated.
Expressions
print(5 + 9)
14
Lua follows PEMDAS. Exponentiation is written using the caret ^, multiplication with the asterisk
*, division with the forward slash, /, and addition and subtraction with plus and minus.
What does this code do?
print( (12 - 5*9) / 3 )
So we can use Lua like a calculator.
You can use functions in a similar manner to mathematics. Some common numerical functions exist in the
math library. For example,
print(math.sqrt(4))
2
sqrt here is short for square root. Just consider the math. prefix to
be part of its name. Some other functions which may be useful:
- math.sin(x) "Computes the sine of x (in radians)."
- math.cos(x) "Computes the cosine of x (in radians)."
- math.tan(x) "Computes the tangent of x (in radians)."
- math.deg(r) "Converts r to degrees."
- math.rad(d) "Converts d to radians."
- math.atan2(y,x) "Tells you the angle (from 0 to 2pi) the point (x,y) makes about the
origin."
- math.pow(a,b) "The same as a^b"
- math.max(a,b) "The larger value of 'a' and 'b'"
- math.min(a,b) "The smaller value of 'a' and 'b'"
- math.abs(x) "The absolute value of x."
- math.log(x) "The natural logarithm (base e) of x."
- math.floor(a) "The floor of a (rounding down)."
What does this code print approximately?
print(3 * math.cos(3.14) + math.sin(1.57))
These functions take one or more arguments or parameters. math.log takes 1 argument, while
math.max takes 2.
Functions can also use each other to produce values (also like mathematics). Here's some examples of everything so
far together:
print( math.max(2,7) )
7
print( math.abs( 2 - 10 ) )
8
print( 3^3 - math.tan( math.rad(45) ) )
26
print( math.cos( math.sqrt(5) ) )
-0.61727287645717
What does this code approximately print?
print(math.pow( 5 , math.cos(-3.14) * 2 ))
Variables
Variables are names whose values are allowed to change (vary) as opposed to remain constant (e.g., 5
is a constant).
Here's a simple bit of a code with our first variable, x.
x = 5
print(x)
5
When x was to be printed, it was evaluated in the same way that 5 + 5 is evaluated to 10.
Variables can be used in expressions in any way.
a = 4
b = 3
print(math.sqrt(a^2 + b^2))
5
Variables are allowed to be made of letters (uppercase or lowercase, but are case sensitive), underscores (_), and
numbers, but cannot start with a number.
These are all different valid variable names:
x
X
apple
APPLE
applE
ApL
apple_sauce
_apple_sauce_
apple9
a1p2l3e4
These are not valid variables names (they contain spaces, start with numbers, or contain other illegal characters)
1apple
apple sauce
apple'ssauce
What will this print?
apple = 17
banana = -4
print(apple - banana + math.sqrt(-banana));
Assignment
As stated before, variables are allowed to change. Variables are changed using assignment which is done using
the equals sign (=).
Assignment was already used to set (assign) the values to the variables in the above examples:
a = 4
b = 3
Like with printing, assignment can use arbitrary expressions:
apple = 3 + math.sqrt(9)
print(apple)
6
Only the name itself appears at the left of the (=). Variables can then be used in the assignment of other
variables.
apple = 5
banana = apple - 2
print(banana)
3
What does this print?
apple = 17 - 6
banana = math.sqrt(apple + 5) * 2
print(banana)
Assignment is not an algebraic constraint like in math; the following is valid:
apple = 1
apple = 5
The second assignment overwrites the value of the first. The computer forget that apple used to be 1; for
all it cares, it's only ever been 5.
This is useful, because it means that a variable can change in any pattern.
apple = 1
banana = apple + 1
print(banana)
apple = banana + 1
print(apple)
2
3
See if you can figure out the number printed in this next example:
candies = 99
take = 4*4
candies = candies - take
print(candies)
?
Conditions
So far, we've used Lua like a calculator. However, we haven't done anything a typical scientific calculator
couldn't. Let's look at if statements.
if false then
print(1)
end
if true then
print(2)
end
2
The if-statements above are actually fairly straightforward. They have two parts: a condition and a
body. The two conditions are (respectively) false and true. The two bodies are
print(1) and print(2). When the computer comes to an if-statement, it evaluates the
condition. If the result of the condition is true then it runs through the if-statement's body. If it's
false then it skips to the end.
if 5 > 3 then
print(1)
end
if 5 < 3 then
print(2)
end
1
Here we see a comparison being performed in each condition. 5 > 3 is the same thing as
true. Meanwhile, 5 < 3 is the same as false.
for loops
How can you print the numbers one to ten? Here's one way:
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)
print(10)
However, it's pretty obvious that this leaves something to be desired. It takes a long time to type and read, and you could
easily make a mistake if the list were longer. And if you wanted to print the squares of these numbers, or do some other
operation on them, you'd need to calculate it yourself!
That's why we have for loops. The following code also prints the numbers 1 to 10:
for n = 1, 10 do
print(n)
end
The code is much shorter and far more clear. for loops are very useful. Here's a for loop
that prints the first 20 squares:
for n = 1, 20 do
print(n^2)
end
Problems
Writing the code to solve each of these problems helps you understand what you're doing and put it to practical use.
Pythagorean Theorem
The Pythagorean theorem says that if you have a right triangle with legs of length 'a' and 'b' and a hypotenuse of length
'c', then a2 + b2 = c2. Your program will start with an a = ? and a
c = ?. Print the value of 'b' according to the Pythagorean theorem. Your program should work no matter what
value of 'a' and 'c' you start with.
Perfect Squares
A perfect square n is a number which is the square of a whole number. The first few perfect squares are 1, 4, 9, 16,
and 25. Your program will start with n = ?. Write a program that prints "n is square" if n
is a perfect square and "n is not a square" if n is not a perfect square.
Many Numbers
Print the numbers 1 to 43.
A Big Sum
The sum of the numbers 1 to 10 is 55. Find the sum of the numbers 1 to 146. Part of the program (as a hint) appears below:
Factorial
The factorial n! of a number n is the product of the numbers below it. For instance, 5! = 1×2×3×4×5 = 120.
Given a number n, find and print n!
A hint on how to start is given.
Divisibility by 17
Find how many positive numbers below 1500 are divisible by 17. Print the result. As a reminder, a % b is
the remainder of a divided by b.
Primes
A number is prime if its factors (the numbers it is divisible by) are only itself and 1. The first few primes are 2,
3, 5, 7, 11, 13, 17, 19, and 23. Note that 0 and 1 are not considered to be prime, but your program doesn't need to deal
with them. Your task is to write a program that tells you if a given number is prime. Print "Prime!" if the
given number is prime and "Composite!" otherwise. (Numbers which are not prime are composite (with the
exception of 0 and 1, but you don't need to worry about that)).
Lots of Primes
The primes under 12 are 2, 3, 5, 7, and 11. Print the primes under 444.
Functions
Let's say we want to solve quadratic equations.
We could use the following code:
a = 1
b = 2
c = 1
x1 = (-b + math.sqrt(b*b - 4*a*c) ) / (2 * a)
x2 = (-b - math.sqrt(b*b - 4*a*c) ) / (2 * a)
print(x1)
print(x2)
-1
-1
So, let's say we wanted to solve three quadratic equations:
a = 1
b = 2
c = -3
x1 = (-b + math.sqrt(b*b - 4*a*c) ) / (2 * a)
x2 = (-b - math.sqrt(b*b - 4*a*c) ) / (2 * a)
print(x1)
print(x2)
a = 1
b = 0
c = -1
x1 = (-b + math.sqrt(b*b - 4*a*c) ) / (2 * a)
x2 = (-b - math.sqrt(b*b - 4*a*c) ) / (2 * a)
print(x1)
print(x2)
a = 3
b = -24
c = 45
x1 = (-b + math.sqrt(b*b - 4*a*c) ) / (2 * a)
x2 = (-b - math.sqrt(b*b - 4*a*c) ) / (2 * a)
print(x1)
print(x2)
1
-3
1
-1
5
3
This also works, but it has a lot of redundancy in it.
We can't easily fix this with loops, since there isn't
some pattern that our polynomials follow.
The solution is to use functions.
A function executes a block of code with particular variables defined by the function's parameters. For solving
quadratic equations, the parameters would be the coefficients, since the answer varies solely based on those
coefficients.
Here's an example of the quadratic formula implemented using functions:
function root1(a,b,c) --These are the function's parameters
x1 = (-b + math.sqrt(b*b - 4*a*c) ) / (2 * a)
print(x1)
end
function root2(a,b,c)
x2 = (-b - math.sqrt(b*b - 4*a*c) ) / (2 * a)
print(x2)
end
root1(3,-24,45)
root2(3,-24,45)
5
3
This makes the code much shorter and more straightforward. It's also much less likely for there to be errors, because an
error in the quadratic formula can only be inside root1 or root2.
In this example, a,b,c are the parameters to the function. Their values in this example are 3,-
24,45; that is, for the execution of root1 and root2, a = 3,
b = -24 and c = 45.
Functions can be called (the term for when you use a function) any number of times with different arguments:
--(with the function from definitions up above)
root1(1,2,-3)
root2(1,2,-3)
root1(1,0,-1)
root2(1,0,-1)
root(3,-24,45)
root(3,-24,45)
1
-3
1
-1
5
3
return Statements
The above functions for computing the quadratic formula have a downside. The roots that were found can't be used elsewhere
in the program; they are only printed to the console. If we wanted to, for instance, add 5 to each root, we would
not be able to do that, because the roots are stored away in the output.
Instead, we might like a function that acts the way that math.cos or math.pow
works—they return a value that we can use for something else. Making this change is very simple. We
simply replace our print statement with a return statement:
function root1(a,b,c) --These are the function's parameters
x1 = (-b + math.sqrt(b*b - 4*a*c) ) / (2 * a)
return x1
end
function root2(a,b,c)
x2 = (-b - math.sqrt(b*b - 4*a*c) ) / (2 * a)
return x2
end
print( root1(1,2,-3) )
1
Notice how root1 is being used here, in a way very similar to math.sqrt or similar
mathematical functions.
Lists
So far, all values that have been discussed have been variables. They hold a single value. While these are useful (and
necessary), sometimes holding a large amount of data at once is necessary.
We can use lists (called tables in Lua) to store many pieces of data.
x = 36
list = {5,x,9,math.sqrt(x)}
print(list)
print(list[1])
print(list[4])
table: 0xd973f0
5
6
The curly brackets here define a list filled with elements separated by commas.
Our variable, list, is a table. We can access its elements using the square brackets.
list[1] refers to the first element of list. We can find the length of a list using #:
print(#list) results in 4.
We can use loops to look at things in a list. For instance, we can sum up all of the numbers in a list:
list = {3,8,-1,6}
sum = 0
for i = 1, #list do
sum = sum + list[i]
end
print(sum)
16
In this example, list[i] refers to the ith element of the list. So we add the
first, second, third, ..., second to last, last element of list to sum.
Java
Java is a programming language, just like Lua is. Lua and Java are similar in many ways (as you have used Lua so far, there is not too much difference). The primary differences you'll see between the two come in two forms: syntax and types.
Syntax
Syntax is the grammar of a language. Here is a "Hello, World!" program in Lua"
print("Hello, World!")
and then in the equivalent Java:
public class MainClass {
public static void main(String[] a) {
System.out.println("Hello, World!");
}
}
Java requires additional structure in order to run. In Lua, what you write is executed in the order you write it. In Java, this is also true, but Java's interpreter (the thing which actually performs the actions you write) looks for a particular place to start. That place is the public static void main(String[] a) function. The code within the { } which follow it is the main body of the code. It is called the "main function" or "main method" because it is the "main" or first thing that is run. Any other code your program runs will be called from the main method.
In Java, all code is wrapped up within classes. Classes are a way to organize your code; they also make Java an Object Oriented Programming language (or OOP language). For now, you will define only one class, which will contain your main method.
Java requires semicolons at the end of statements (that is, any assignment or function call) as well as a few other special cases. Don't forget them!
Types
"Types" are the "type" (kind or variety) of a particular piece of data. 5 is a number, "apples" is a string and true is a boolean.
When you ask your Java code to be run, before the compiler runs it, it first checks that your types are valid. You cannot treat a value as a type which it is not. For example, you cannot multiply strings. What would "apples" * "oranges" be equal to?
In order to enforce "type safety," or the proper use of valid types, every variable has a known, constant type which cannot be changed. More importantly, each variable's type must be stated when it is first assigned a value (declared).
public class MainClass {
public static void main(String[] a) {
int a = 6;
int b = 9;
System.out.println(a + b);
}
}
Again, note the presence of the class declaration and the public static void main(String[] a) { ... } which houses the actual code.
This program is equivalent to the (probably simpler) Lua:
a = 6
b = 9
print(a + b)
When a and b are declared, they are preceded by the keyword int. int is not a variable name (if you notice, I have written it in a different color). Rather, it is a type.
int is an abbreviation of "integer", or a number that can be written without a fractional or decimal component.[1]
But not all numbers are integers. Suppose you try the following:
public class MainClass {
public static void main(String[] a) {
int a = 1.5;
int b = 0.5;
System.out.println(a + b);
}
}
The Java compiler will complain- you're trying to pass a decimal number off as an integer! There is no sensible way to call 1.5 an integer, so the Java compiler will reject your program and tell you there's an error. When we want to be able to use decimal numbers, we use the type double. That's short for "double-precision 64-bit IEEE 754 floating point." The specifics are not largely important unless you're doing precise numerical computation. The important bit is that these numbers can have decimal values in them. All of Lua's numbers are essentially doubles.
Onward
If you've read through the tutorial up to this point, redo all of the assignments in Java. If you've accomplished that, go to Project Euler and solve the first 10 problems.