Page 1 of 1

Introduction to Lua variable types, control structures, and functions

#1 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,140
  • Joined: 14-September 07

Posted 09 April 2009 - 08:34 AM

Introduction to Lua


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

--[[ indicates the beginning of a block comment
ends with 
--]]
--[=[You can also put any number of equal signs between brackets
to not have any conflict wioth array index brackets, etc... ends the same as it began:
--]=]

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

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

edited for typos

4/10/09

edited to include block comments

This post has been edited by KYA: 10 April 2009 - 03:51 PM


Is This A Good Question/Topic? 3
  • +

Replies To: Introduction to Lua

#2 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 144
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Posted 09 April 2009 - 02:56 PM

Nice tut kya. thanks.
Was This Post Helpful? 0
  • +
  • -

#3 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Posted 11 April 2009 - 08:28 AM

Awesome tutorial KYA! Thanks!
Was This Post Helpful? 0
  • +
  • -

#4 Mercurial  Icon User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 178
  • Joined: 06-November 09

Posted 31 January 2010 - 05:53 AM

Interesting thing to point out is how switch is easily done in Lua. For example, in your bubble sort function you could've just write
table[j-1], table[j] = table[j], table[j-1]
but I'm sure you did it this way because you didn't explain multiple assignments yet(up untill that moment).
Was This Post Helpful? 0
  • +
  • -

#5 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,140
  • Joined: 14-September 07

Posted 31 January 2010 - 06:01 PM

View PostMercurial, on 31 Jan, 2010 - 05:53 AM, said:

but I'm sure you did it this way because you didn't explain multiple assignments yet(up untill that moment).


That's exactly why. It's in one of the other tutorials.
Was This Post Helpful? 0
  • +
  • -

#6 FreezingHazard  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 148
  • Joined: 22-February 10

Posted 29 April 2010 - 11:33 PM

Finally some good lua info I mean not to be mean BUT LUAS DOCUMENTATION is empty. How can a language be successful if no one knows it?
Was This Post Helpful? 0
  • +
  • -

#7 Guest_Brianoh*


Reputation:

Posted 14 August 2010 - 08:39 PM

Buy one of the books or search the web.
Was This Post Helpful? 0

#8 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,140
  • Joined: 14-September 07

Posted 14 August 2010 - 08:42 PM

Yeah, that's about the only way to do Lua. Programming in Lua 2nd Edition in print or check out the first edition + documentation on Lua's site.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1