Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

Introduction to Lua

Icon 4 Comments
Coming Soon to an "Other Language" Tutorial Section Near You! Tutorial here

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 "--"

--Comments are like this
--> indicates what the result should be or what should be outputted, still a comment
print(type("Hello World!")) -->string
print(type(10*4))  --> number
print(type(nil)) --> nil
print(type(print)) --> function

--etc...



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:

j = 10 --global variable
local i = 5 --local variable 



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.

--the structure of a function declaration
function aFunction(var)
   local value = var --value only exists in this function
   --do stuff here
   return var
end



The above would be called using:
var = something
print(aFunction(var))



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:

a = 5
b = 4

a = 5; b = 4

--messy but legal
a = 5 b = 4



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:

print (4 and 5)   -->5
print(nil and 13) -->nil
print(false and 15) -->false
print(4 or 5) -->4
print(false or 5) -->5



Basic Control Statements:

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

--if else syntax:
if condition then
	 --do something
else
   --do something
end

--NUMERIC FOR
--for loop, table indexes generally start at 1 in Lua
for i = 1, 10 do
   --loop 10 times, typically traversing a table or such
end

--GENERIC FOR
--This example assumes the table is acting like a C/C++ array
for i, v in ipairs(a) do --for all values in the table 'a', i is the index, v is the value
	 print(v)
end

--ANOTHER GENERIC FOR
--prints all keys of the table (more on tables in another tutorial)
for k in pairs (t) do
   print(k)
end

--while loop
while condition do
   --loop stuff
end

--repeat structure
--gathers input until the first non empty line, then prints it
repeat
	 line = os.read()
until line ~= ""
print(line)



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 your 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:

--Given a number 'n' calculate its factorial
function factorial(n)
  if n == 0 then
	return 1
  else
	return n * factorial(n - 1)
  end
end

--example usage
--Without any additional help, lua can calculate pas 12!
--where most other language snippets would have an overflowed
--integer value
print (factorial(13))




BubbleSort:


--sort a table passed to the function
function bubbleSort(table)
--check to make sure the table has some items in it
	if #table < 2 then
		print("Table does not have enough data in it")
		return
	end

	for i = 1, #table do --> array start to end
		for j = 2, #table do
			if table[j] < table[j-1] then -->switch
				temp = table[j-1]
				table[j-1] = table[j]
				table[j] = temp
			end
		end
	end

	return
end

--example usage
table = {1,10,5,6,7}
for i = 1, #table do --print unsorted table
	print(table[i])
end
bubbleSort(table)
print("\n")
for i = 1, #table do --print sorted table
	print(table[i])
end




FindMax function:

--Functions fins the max value in a table
--Also illustrates multiple returns in a function
function findMax(a)
	local mi = 1			--index of max value
	local m = a[mi]			--max value
	for i, val in ipairs(a) do
		if val > m then
			mi = i
			m = val
		end
	end
	return m, mi	--neat feature of lua, can return multiple values
end


--example usage
print(findMax({2,6,90,45,67,88,100}))	-->100 7, max num and index location




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

4 Comments On This Entry

Page 1 of 1

Amadeus 

09 April 2009 - 09:15 AM
I first got into Lua when I was asked if I could program some additional user interfaces/macros for WoW (asked by a user, not by Blizzard...WoW allows user to create add-ons for the game) and Lua is the scripting language they use. It has some neat features to it...I've never really gotten deeply enough into it to have tested everything it can do however, just the basics. I look forward to the rest of the series.
0

Smurphy 

09 April 2009 - 09:24 AM
Ya, that is the first place that I heard about it from. This is really interesting keep up the great work.
0

bodom658 

14 April 2009 - 01:11 PM
Idk if you said it in here but I just wanted to add that Crimson Editor at least and probably other Text Editors recognize Lua, and if the text editor has external tools, you can run the script by running lua.exe with the argument being the file name and extension (*.lua), or you can run it from a command line using lua file.lua, replacing file as necessary, from the directory containing lua.exe on your computer.
0

KYA 

14 April 2009 - 02:42 PM

bodom658, on 14 Apr, 2009 - 01:11 PM, said:

Idk if you said it in here but I just wanted to add that Crimson Editor at least and probably other Text Editors recognize Lua, and if the text editor has external tools, you can run the script by running lua.exe with the argument being the file name and extension (*.lua), or you can run it from a command line using lua file.lua, replacing file as necessary, from the directory containing lua.exe on your computer.


That's true. I didn't mention it though. I figured if the person wanted to use another editor, they had the know-how. Notepad++ has supports lua to if i recall correctly.

The lua compiler is luac.
0
Page 1 of 1

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    20 user(s) viewing

    20 Guests
    0 member(s)
    0 anonymous member(s)