Code:
--[[ 2.lua
This will teach you about setting variables and using them in Lua ]]
x = 4 -- It's as simple as that. No need to define if x is an integer or string, Lua does that for you
print (x); -- Small point, Lua DOES NOT REQUIRE semi colons. They can or can't be ued based on user preference
x = "Hi" -- Now we've set x to a string, which Lua does automagically
print (x)
x = false -- Now x is a boolean value
print (x)
x = nil -- Lua is amazingly easy to clean up. If you want to clean out memory of unused varibles, set them to nil.
-- By default ALL variables are set to nil in Lua, so variables set to nil by the user become nonexistant.
print (x)
--[[ 3.lua
Simple info printing commands, to help with debugging ]]
x = 4
print (x, type(x)) -- type(x) prints out what type of variable x is being processed as. It's bad if you try to add two numbers
-- and they turn out to be strings.
-- If you noticed above, it gets printed out weirdly. The distance between 4 and number is huge. That is what the comma does, seperates
-- things by an amount of space. To make it continuous, we do the following:
print (x .. type(x))
-- The .. means "directly connect". No spaces, nothing. This also looks bad because it's now 4number. So what we would do to make it look pretty...
print (x .. " " .. type(x))
--[[ 4.lua
We learn about one last variable type: The table, which are similar to arrays ]]
x = {} -- This is how we set up an empty table. All values enclosed by the curly braces become part of the table.
x = { 1, 2, 3 } -- Separate values with a comma when initializing them in a table
first = x[1] -- You can assign values from a table to another variable. Unlike most languages, Lua starts it's position at 1, not 0
print (first)
test = x[0]
print (test) -- See? Position 0 doesn't exist.
-- You can also add values to a table after it's been initialized, like so:
table.insert(x, 4) -- table.insert (name of table, position to be inserted to (is NOT assumed, so if left empty, it'll just be added to the end),
-- value to input)
print (x[4])
-- Putting two cents together you can do this
y = {}
y[1] = "a"
y[2] = "b"
y[3] = "c"
print (y[1] .. ", " .. y[2] .. " and " .. y[3])
-- Here, I'll show you how to see the contents of your tables. VERY useful for debugging:
for i,v in pairs (y) do print (i,v) end -- This says for every position and value, in the pairs of them in table y, print them
-- You can see it's 3 positions long. But what if you have a huge table and need to know it's size? the pairs loop would be impractical
# y -- This tells you the size of a given table. # is the operator, y is the table name
-- So finally say I want spot number two to be filled with "z" instead of "b"
table.insert (y, 2, "z")
print (y[2])
--[[ 5.lua
If / elseif / else ]]
switch = false -- Setting the variable
if (switch == true) then -- The "then" is a very important part of the If / else structure
print ("True")
else
print ("False")
end -- %%%%%%%%%%%%%%%%%%% This is also another major point. At the end of any IF statement block, you must end with 'end"
-- Sidenote to you first time programmers, this is a common mistake. IF statements use TWO equal signs, not one. :)
-- In an If / Elseif / Else structure, any line containing "if" or "elseif" must have a "then" after the condition
-- If Mary is at the bar, then flirt with her. If switch is true, then print true.
flag = 2
if (flag == 1) then
print ("The flag was 1")
else if (flag == 2) then
print ("The flag was 2")
else if (flag == 3) then
print ("The flag was 3")
else
print ("The flag was " .. flag)
end -- %%%%%%%%%%%%%%%%%%%%%%%%%%% Ending with "end" at the end of the WHOLE block
-- Nesting If statements below, basically branching off like the limbs of a tree
ftw = true
wtf = false
if (ftw == true) then
if (wtf == true) then
print ("FTW? WTF!")
else -- wtf will be false
print ("FTW!")
end -- THE ALMIGHTY END
else --ftw will be false
if (wtf == true) then
print ("WTF?!")
else -- wtf will be false
print ("I am so confused...")
end -- THE ALMIGHTY END
end -- THE ALMIGHTY END
-- As you can see, we needed multiple ends for the multiple if statements. Having a loop or IF block inside another is called nesting.
--[[ 6.lua
LOOPS! YAY! ]]
-- While loop
count = 0 -- Initialize the counter variable
while (count <= 5) do -- Okay, this is self explanatory but I'll explin anyway. While count is less than or equal to five. do...
print (count) -- this, and print what count is and...
count = count + 1 -- advance the loop, adding one to count.
end -- %%%%%%%%%%%%%%% THIS IS AN IMPORTANT PART OF ANY CONTROL STRUCTURE. DONT FORGET END!
print ("#")
-- Repeat loop
repeat -- Repeat doing...
print (count) -- print the count...
count = count - 1 -- and subtract one from count total...
until (count <= 0) -- Until count is less than or equal to 0.
print ("#")
-- For loop
for i = 1,3 do -- Initialize i as equal to 1. Then set the condition for the loop to end as 3. So when i = 3, the loop ends. Thus, i = 1,3. Then do..
print(i) -- print i
end -- %%%%%%%%%%%%%%% THIS IS AN IMPORTANT PART OF ANY CONTROL STRUCTURE. DONT FORGET END!
--[[ 7.lua
Functions and some basic Object Oriented programming ]]
-- This program calculates the final value of a number, give the base and the exponent
function exponent (base, power) -- We define it as a function and give it a name we'll use later. Then we put two place holder variables
temp = 1 -- Initializes temp as 1, because anything raised to 0 is 1.
repeat -- Start a loop
temp = base * temp -- Multiply the base number by itself (or by one if just starting)
power = power - 1 -- And decrease the power counter
until (power <= 0) -- Until there is nothing left to calculate
print (temp)
end
print ("Please enter a base number: ")
user_base = io.read ()-- io.read() is the command one uses to grab input from the user
-- user_base = tonumber (io.read ()) is another way of doing it, if you would like to make sure the program sees the input as a number
print ("Please enter the exponent to raise the base number to: ")
user_power = io.read ()
user_base = tonumber (user_base) -- Again. tonumber ( something) makes sure that the something converts to a number
user_power = tonumber (user_power)
print ("Result is: ")
exponent (user_base, user_power)--[[We use the function like a cookie cutter now. Throw in our own variables
and run through the same set of commands held by one function. This is an object oriented programming principle, reusability ]]
--[[ 8.lua
The Math Library ]]
-- This program will introduce some fundamental math functions one would use in most scripts
-- math.abs : The absolute alue function. This takes any number and strips it to it's base. So negatives become positives
x = 1 -- x as a positive number
print ("x = " .. x)
x = -1 -- x as a negative number
print ("x = " .. x)
x = math.abs (x) -- x as its absolute value
print ("The absolute value of x = " .. x)
print ("")
-- math.ceil : The Round Up function. This takes any number and rounds it up to the next largest integer
x = 2.4
print ("x = " .. x)
x = math.ceil (x)
print ("x rounded up is " .. x)
print ("")
-- math.floor : The Round Down function. This takes any number and rounds it down to the next smallest integer
x = 2.4
print ("x = " .. x)
x = math.floor (x)
print ("x rounded down is " .. x)
print ("")
-- math.max : The Find Max Number function. This finds the largest number of a group of given numbers
print ("The largest number of 2, 41, -3 and 3.4 is " .. math.max (2, 41, -3, 3.4))
-- math.min : The Find Min Number function. This finds the smallest number of a group of given numbers
print ("The smallest number of 2, 41, -3 and 3.4 is " .. math.min (2, 41, -3, 3.4))
print ("")
-- math.pow : The Exponent function. This finds the numeric value of an exponential expression, given the base number and the power
x = 2
y = 4
z = math.pow (x, y) -- Is the normal way of writing the command. It is x raised y number of times
a = math.pow (x^y) -- Is another way of writing the command
print ("x = " .. x .. ", y = " .. y .. ", and math.pow (x, y) = " .. z)
print ("math.pow (x^y) also is equal to " .. a)
print ("")
-- math.sqrt : The Squre Root function. This finds the squre root of the given variable
x = 9
print (" The squre root of " .. x .. " = " .. math.sqrt (x))
-- math.random : The Random Number Picker function! This is what you'd use to make a gambling game :P More explained below
x = math.random () -- When called with no argument (ie, nothing in the parantheses), it returns a number between 0 and 1
print (x)
x = math.random (10) -- When called with one argument, it returns a number between 1 (assumed by Lua) and the number in the parentheses
print (x)
x = math.random (4, 8) -- When called with two arguments, it returns a number between both the numbers inputted
print (x)