Author Topic: Introduction to Lua  (Read 8047 times)

0 Members and 1 Guest are viewing this topic.

Offline KYA

  • Charter Member
  • Full Member
  • *
  • Posts: 596
  • #include <nerd.h>
  • Field: Software Development
  • Real Name: Knowles Atchison, Jr.
  • Favorite OS: Windows
  • Programming Language: C++
Introduction to Lua
« on: April 09, 2009, 05:10:15 PM »
What is Lua?

From Lua's homepage, www.lua.org:

"Lua is a powerful, fast, lightweight, embeddable scripting language.

Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping. "



Now, to get started, download the appropriate package/binary for your OS. If you are using windows, I highly recommend the installer as it comes with a GUI similar to IDLE if you've ever programmed in Python. see here, Latest Windows Installer from LuaForge, and Lua Forge itself

This tutorial assumes you have some basic programming knowledge.

First off, let's discuss Lua's primitives, there are 8 types: nil, boolean, number, string, userdata, function, thread, and table. Comments start with a double hyphen "--"

Code: Lua [Select]
  1. --Comments are like this
  2. --> indicates what the result should be or what should be outputted, still a comment
  3. print(type("Hello World!")) -->string
  4. print(type(10*4))  --> number
  5. print(type(nil)) --> nil
  6. print(type(print)) --> function
  7.  
  8. --etc...
  9.  

Numbers are double floating point, however you can store integers, doubles, floats, etc... in them.
Booleans are simply true or false. Similar to C style languages any value other then false or nil represents true, there is no "one" case here. Zero and empty strings still evaluate to true. So if you want it to be false, assign nil or false directly to the variable.
Nil is the absence of a meaningful value. Variables that are uninitialized automatically have the value of nil. This is particularly important when dealing with global variables.
Strings are just like strings in any other language: a sequence of characters. It is important to know that they are immutable once created, unlike in C. Escape characters exist, just like C : "\n, \\, etc..."
Functions have great flexibility in Lua. They can be stored in variables, passed to other function, etc...

userdata, tables, and threads are beyond the scope of this tutorial, but will be covered later. Know, however, that userdata is a device for storing C data. (Lua and C have great interfacing capabilities).

Now, onto some code examples. Since you now have Lua set up, there are a few things you may need to know. The command prompt is interactive, meaning you can type print("Hello World!") and Hello Wold will be immediately printed to the screen. This interactivity is great for doing small things and testing snippets, but if you want to write a large chunk you will probably want to do it in a text file or in the GUI that came with the installer (the HUI has a built in interpreter to allow testing within the IDE, very handy).

Variables:

Code: Lua [Select]
  1. j = 10 --global variable
  2. local i = 5 --local variable
  3.  

If you have had any experience in programming before, you'll understand this immediately. local variables are local to the block in which they are declared (a loop, function, so on and so forth), but globals persist throughout the program.

Code: Lua [Select]
  1. --the structure of a function declaration
  2. function aFunction(var)
  3.    local value = var --value only exists in this function
  4.    --do stuff here
  5.    return var
  6. end
  7.  

The above would be called using:
Code: Lua [Select]
  1. var = something
  2. print(aFunction(var))
  3.  

Note that semicolons are not required to note a new line or end of one, however they can be used, the following are all equivalent:

Code: Lua [Select]
  1. a = 5
  2. b = 4
  3.  
  4. a = 5; b = 4
  5.  
  6. --messy but legal
  7. a = 5 b = 4
  8.  

Just like in Python and other scripting languages variables are dynamically typed at runtime. While this is a great and powerful feature, you still need to be aware of variable types and assignments as you code.

Relational Operators:

Lua has the same operators as most other languages: <, > , >=, <=, ==, and ~= (negation of equality)

Logical Operators:

Lua has three logical operators: and, or, not. They consider false and nil as false and everything else as true. When equating, these operators use short cut evaluation, meaning i they don't have to evaluate the second condition, they never will. While this is desired, if code isn't planned accordingly you may have a tough time finding the bug. Examples:

Code: Lua [Select]
  1. print (4 and 5)   -->5
  2. print(nil and 13) -->nil
  3. print(false and 15) -->false
  4. print(4 or 5) -->4
  5. print(false or 5) -->5
  6.  

Basic Control Statements:

Lua has the same basic control structures as C: for loops, while loops, if else structures, etc...

Code: Lua [Select]
  1. --if else syntax:
  2. if condition then
  3.      --do something
  4. else
  5.    --do something
  6. end
  7.  
  8. --NUMERIC FOR
  9. --for loop, table indexes generally start at 1 in Lua
  10. for i = 1, 10 do
  11.    --loop 10 times, typically traversing a table or such
  12. end
  13.  
  14. --GENERIC FOR
  15. --This example assumes the table is acting like a C/C++ array
  16. for i, v in ipairs(a) do --for all values in the table 'a', i is the index, v is the value
  17.      print(v)
  18. end
  19.  
  20. --ANOTHER GENERIC FOR
  21. --prints all keys of the table (more on tables in another tutorial)
  22. for k in pairs (t) do
  23.    print(k)
  24. end
  25.  
  26. --while loop
  27. while condition do
  28.    --loop stuff
  29. end
  30.  
  31. --repeat structure
  32. --gathers input until the first non empty line, then prints it
  33. repeat
  34.      line = os.read()
  35. until line ~= ""
  36. print(line)
  37.  

Notice that each block is ended with "end", whitespace is important, but block control is more prudent. Tables are so flexible and have so many variations, they will require their own tutorial, but know that they are not rigid as in C. Indexes can be strings, numbers, etc... There's no need to allocate space, it is done automatically. Here are two programming "staples" to test out you knoweldge and to ensure you have lua set up correctly for code testing:


Note: #tableName gives the length of the table, more on this later

Factorial of a number:

Code: Lua [Select]
  1. --Given a number 'n' calculate its factorial
  2. function factorial(n)
  3.   if n == 0 then
  4.     return 1
  5.   else
  6.     return n * factorial(n - 1)
  7.   end
  8. end
  9.  
  10. --example usage
  11. --Without any additional help, lua can calculate pas 12!
  12. --where most other language snippets would have an overflowed
  13. --integer value
  14. print (factorial(13))
  15.  


BubbleSort:


Code: Lua [Select]
  1. --sort a table passed to the function
  2. function bubbleSort(table)
  3. --check to make sure the table has some items in it
  4.         if #table < 2 then
  5.                 print("Table does not have enough data in it")
  6.                 return
  7.         end
  8.  
  9.         for i = 1, #table do --> array start to end
  10.                 for j = 2, #table do
  11.                         if table[j] < table[j-1] then -->switch
  12.                                 temp = table[j-1]
  13.                                 table[j-1] = table[j]
  14.                                 table[j] = temp
  15.                         end
  16.                 end
  17.         end
  18.  
  19.         return
  20. end
  21.  
  22. --example usage
  23. table = {1,10,5,6,7}
  24. for i = 1, #table do --print unsorted table
  25.         print(table[i])
  26. end
  27. bubbleSort(table)
  28. print("\n")
  29. for i = 1, #table do --print sorted table
  30.         print(table[i])
  31. end
  32.  


FindMax function:

Code: Lua [Select]
  1. --Functions fins the max value in a table
  2. --Also illustrates multiple returns in a function
  3. function findMax(a)
  4.         local mi = 1                    --index of max value
  5.         local m = a[mi]                 --max value
  6.         for i, val in ipairs(a) do
  7.                 if val > m then
  8.                         mi = i
  9.                         m = val
  10.                 end
  11.         end
  12.         return m, mi    --neat feature of lua, can return multiple values
  13. end
  14.  
  15.  
  16. --example usage
  17. print(findMax({2,6,90,45,67,88,100}))   -->100 7, max num and index location
  18.  


Hope you found this helpful. I plan on doing a whole series as I did not find Lua's wiki/tutorial section particularly helpful when I started. Happy Coding!

--KYA

For further reading see : Introduction to Lua - Part II and Introduction to Lua - Part III
« Last Edit: April 14, 2009, 09:56:30 PM by KYA »

Offline AJ32

  • TCC Webmaster
  • Administrator
  • Cube Head
  • *
  • Posts: 1,403
  • "TCC Fuhrer"
    • Fox Software
  • Field: Software & Web Development
  • Real Name: Andrew Warner
  • Favorite OS: Windows
  • Programming Language: PHP
Re: Introduction to Lua
« Reply #1 on: April 10, 2009, 01:39:49 AM »
Other languages board added, topic moved, kudos added. :)


"Data is eternal, immortal, immutable. Even when the engineers and intelligence
behind its creation are gone, information, facts, and knowledge never die."

Offline KYA

  • Charter Member
  • Full Member
  • *
  • Posts: 596
  • #include <nerd.h>
  • Field: Software Development
  • Real Name: Knowles Atchison, Jr.
  • Favorite OS: Windows
  • Programming Language: C++
Re: Introduction to Lua
« Reply #2 on: April 10, 2009, 02:23:25 AM »
Nice! Thanks for the addition and move. :)

Offline KYA

  • Charter Member
  • Full Member
  • *
  • Posts: 596
  • #include <nerd.h>
  • Field: Software Development
  • Real Name: Knowles Atchison, Jr.
  • Favorite OS: Windows
  • Programming Language: C++
Re: Introduction to Lua
« Reply #3 on: April 14, 2009, 09:57:00 PM »
Edited to add links to the next tutorials in the series, progression.