# VBForums UtilityBank > UtilityBank - Tutorials >  Tutorial: Programming in Lua

## dday9

*Introduction*

Lua is a dynamically typed multi-paradigm programming language written in ANSI C. Because Lua is written in ANSI C, it is cross-platform which is very beneficial to Unix users. Lua is known for it's small footprint and quick speed. Best of all, Lua is completely free.

*Installation*

In order for you to compile Lua applications, you must have the Lua run-time installed. This can be found on Lua's official site here. However, if you are a Windows user, I suggest _Lua For Windows_ found here.

*Basics*

_Comments_ in Lua are ignored by the compiler. They simply represent a body of text that gives information to the programmer, but doesn't actually execute. There are two types of comments in Lua, the single line comment and the block comment.

A single line comment is represented by two hyphens:


```
-- this text is ignored by the compiler
```

A block comment starts with two hyphens, followed by two inner square brackets and is finished with two hyphens and two outer square brackets:


```
--[[ This
text is ignored by
the compiler --]]
```

_Data types_ in Lua are: nil, boolean, number, string, user data, function, thread, and table. I will not go over all of these in this chapter, but I will go over a few.

A nil value simply represents a non value. It is considered the absence of a value and all global variables declared in Lua are nil by default.

A boolean value is either a True or False value.

A number represents any number including decimals.

A string represents text. Strings are enclosed in double quotation marks:


```
"This is a string"
```

_String concatenation_ is a way to join to strings together. String concatenation in Lua is represented by two dots:


```
"hello" .. " world!" -- this is the same as "hello world!"
```

*Variables*

Variables in Lua represent a value by using an identifier. Because Lua is a dynamically typed language, you do not specify the data type when declaring a variable; the compiler converts the value to the data type. The simplest way of declaring a variable is to type the variable name(the identifier), use the equal sign, and set the variable's value:

Declaring a boolean value:


```
isTrue = true
```

Declaring a number value:


```
age = 22
```

Declaring a string value:


```
name = "David"
```

Variables also have the option of using an access modifier. Access modifiers set the accessibility of the variable. In Lua, there are only two access modifiers: global and local.

There is no keyword for the global access modifier. Whenever you declare a variable, it's automatically considered a global variable in that code block.

The keyword for the local access modifier is: _local_. Whenever you declare a local variable, that variable can only be used within it's scope. For example, if I declare a local variable in one chunk of code, I cannot access that variable within a different chunk of code. Here is an example of declaring a variable with the local access modifier:


```
local age = 22
```

*Input and Output*
To print out a statement on the Lua terminal, you call the _io.write()_ function. To read user input, you call the _io.read()_ function.

The io.write() function takes a string input and prints it out on the terminal. Here is an example:


```
io.write("hello world!")
```

Because Lua is a dynamically typed language, if you try to pass something that is not a string in io.write(), the compiler will try to convert that data type to a string. So it is acceptable to pass a number in the io.write() function. Here is one example:


```
age = 22
io.write("You are " .. age .. " years old.")
```

The io.read() function takes a string that the user inputted into the terminal. Here is an example of setting a variable to user input:


```
io.write("Enter in your name: ")
name = io.read()
io.write("Hello " .. name .. "!")
```

----------


## dday9

*Conditional Logic*
Conditional logic is used to evaluate 1 or more conditions and based on that evaluation it may or may not execute a block of code. In Lua, conditional logic is expressed by using the if, elseif, and else keywords.

To start an if statement, you type the keyword if, followed by an evaluation, and finished with the then keyword:


```
if 1 > 2 then
```

To expand on your if statement, you can add the elseif. The elseif will evaluate the condition if the condition above it fails. To use an elseif statement, you must first have one if statement. You type out elseif, followed by an evaluation, and finished with the then keyword. Expanding upon our if statement, above here is a quick example:


```
if 1 > 2 then
    -- some code here
elseif 1 > 3 then
    -- some different code here
```

To expand on your if statement even more, you can add the else. The else will execute a block of code if all other conditions fail. To start an else statement, you must first have one if statement. The else statement is different in the fact that it does not require the then keyword. Here are two examples:


```
if 1 > 2 then
    -- some code here
else
    -- some different code here
```



```
if 1 > 2 then
    -- some code here
elseif 1 > 3 then
    -- some different code here
else
    -- this code would obviously execute because 1 is not greater than 2 or 3
```

If statements can be daisy chained. In otherwords, you can have multiple elseif's in your logic:


```
if 1 > 2 then
    -- some code here
elseif 1 > 3 then
    -- some different code here
elseif 2 < 1 then
    -- some different code here
else
    -- this code would obviously execute
```

Finally, all if statements are finished with the end keyword:


```
if 1 > 2 then
    -- some code here
end
```



```
if 1 > 2 then
    -- some code here
elseif 1 > 3 then
    -- some different code here
else
    -- this code would obviously execute
end
```



```
if 1 > 2 then
    -- some code here
elseif 1 > 3 then
    -- some different code here
elseif 2 < 1 then
    -- some different code here
else
    -- this code would obviously execute
end
```

*Operators*
You have already seen 2 different operators in the prior examples, the less than and greater than symbols. Operators are used to compare statements or evaluations.

The first set of operators are _relational operators_. Relational operators are used to check the relation of two objects. The different types of relational operators used in Lua are:
Symbol
Description

<
Less Than

>
Greater Than

<=
Less Than or Equal To

>=
Greater Than or Equal To

==
Equal To

~=
No Equal To



The next set of opeartors are _logical operators_. Logical operators are used to evaluate conditions. The different logical operators in Lua are:
Keyword
Description

and
Returns a True value if both conditions are True

or
Returns a True value if one of two conditions are True

Not
Returns a True value if a condition is False



Some examples of using logical operators are:
And operator


```
if 1 > 2 and 1 > 0 then
    -- This code would not execute because both conditions did not return a True value.
end
```

Or operator


```
if 1 > 2 or 1 > 0 then
    -- this code would execute because even though 1 is less than 2, 1 is greater than 0. So one of our conditions is true
end
```

*Loops*

Loops are designed to repeatedly execute code. Loops can be for a set amount of times or infinitely. In Lua, there are three different types of loops: _for_, _while_, _repeat_.

The for loop can be looked at as a numerical loop, it was stated earlier that loops can be for a set amount of times or infinitely; for loops can never be an infinite loop. It will begin at one number and end at another number at a certain increment. The way you specify a for loop is you start with the for keyword, specify where the loop will begin by declaring a variable and setting that variable, specify where the loop will end, specify the increment amount, finish that line with the do keyword. Just like conditional statements, for loops ends with the end keyword. Here is an example of a for loop:


```
for x = 1, 10, 1 do
    -- This loop will loop from 1 - 10 incrementing x by 1 everytime.
    -- X would equal: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and then the loop would be finished.
end
```

The while loop will loop until a condition has been evaluated as True. Because a while loop will continue until a condition has been evaluated as True, you are able to set a while loop to be an infinite loop. To create a while loop, you start with the keyword while, followed by the condition, followed by the do keyword. Just like in conditional statements, the while loop ends with the end keyword. Here is an example of an infinite loop:


```
while true do
    -- This loop will loop until the user closes out the program
end
```

The repeat loop is similar to the while loop. The difference is that the repeat loop checks the condition at the end rather than at the beginning. To create a repeat loop, you start with the keyword repeat, then you execute the code, and finally you end with the until keyword followed by the condition. Here is the same loop that was used as our while loop example, only as a repeat loop:


```
repeat
  -- This loop will loop until the user closes out the program
until not true
```

----------


## dday9

*Functions*

Functions are serve two purposes in Lua. One purpose is to simply execute a task, known as a subroutine. The other purpose is to return some value. To create a function, you start by typing in the keyword _function_ followed by the function's name. After the functions name you type in an open and a closed parenthesis. To end the function you simply use the end keyword. Here is a basic function:


```
function foo()
    -- code here
end
```

To return values from a function, you use the _return_ keyword followed by the value. Here is an example of returning a true Boolean value:


```
function ReturnTrue()

	return true

end
```

To set a variable to a function's value, you would set it using the equal sign and then the functions name. So to expand on our example above:


```
function ReturnTrue()

	return true

end

isTrue = ReturnTrue
```

In Lua, you're able to use something called _parameters_. Parameters work exactly as local variables inside of a function. To create a parameter, you simply set the parameter's name inside the function's parenthesis and parameters are separated by commas. A good example of using parameters is to create a function that returns the result of adding two numbers together:


```
function addition(x, y)
	return x + y
end
```

To call that function you would set the parameters to some number:


```
function addition(x, y)
	return x + y
end

sum = addition(5, 10) -- result = 15
```

*Arrays*

Arrays in Lua are simply a collection of values of the same type. Arrays in Lua do not have to start at a specified index, however if an index is not specified then the default index of an array is 1. You are able to declare an array by using the curly brackets. For example to declare an empty array you use this:


```
foo = {}
```

To set the values of an array, you have a few options. The first option is to set each individual item in the array by it's index. To access an array element by it's index you simply type in the arrays name, followed by square brackets, and the index you want to manipulate is based on the number inside of those square brackets. Look at this example:


```
arr = {}
arr[1] = "foo"
```

In that example, we declared a blank array named arr. Next we set item number 1 in the blank array to a string value with the value of foo.

The next option of setting values in an array is to do so when declaring the array. Each value is separated by a comma inside of the curly brackets:


```
arr = {1, 2, 3, 4, 5}
```

In that example, we declared an array named arr and set item 1 in the array to 1, item 2 in the array to 2, etc. up until item 5.

*Conclusion*
Lua is a simple and easy to learn programming language which I encourage everyone to learn. Hopefully you have learned the basics from these couple of post and I hope that you will look at some of the project suggestions in the next post to help build up your Lua skills.

----------


## dday9

*Project Suggestions*

To help build up your Lua skills, I have constructed a list of easy to create programs. The programs that have links to them are projects that I have already completed and would be a good reference guide for you if you get stuck.

*Beginner*
_Name that Number_ - A program that will take a number that the user inputted and converts that numerical number to the number spelled out in letters. For example, if a user inputs 100 then the program would print out _one hundred_. For an added bonus, allow for commas and decimals. This will help with basic logic.

_Number Guessing Game_ - A game in which a computer picks a number between x - y. It's the user's job to try and guess the number that the computer picks. The computer will tell the user if he/she guessed to high or to low until the user finally guesses the number that the computer picked. For an added bonus, rate the user on how well he/she guessed. This project will help basic logic and simple loops.

_Sentence Generator_ - A program that creates random sentences based on real grammatical rules. For an added bonus, do not allow for the sentence to contain two of the same articles or two of the same nouns. This project will help with arrays.

_Temperature Converter_ - A program in which the user is able to input a value and the computer converts that value to Fahrenheit or Celsius. For an added bonus, allow the user to chose if they're converting from or to Fahrenheit or Celsius. This project will help with basic mathematics and functions.

*Intermediate*
_Text Based Game_ - You know you want a little bit of nostalgia and revisit the world of text based games. Create a game where the user can move through scenes, get a general description of the scene, and use different commands to interact with the scene. For an added bonus, give the user the ability to earn treasure based on certain commands in different scenes. This project will help nearly all basic components: user input, conditional logic, arrays, and more!

_Bubble Sort Algorithm_ - Create a bubble sort function. This will return an array of integers that are sorted using the bubble sort algorithm. For an added bonus, give the user the ability to sort from lowest to highest or vice-versa. This project will help with conditional logic, arrays, functions, and loops.

----------

