Lua
Varliables
- Global variables (default type)
- Local variables (limited to their scope)
- Tables (special type of variable that can hold anything except nil)
Example
c , d = 5, 10; --declaration of c and d as global variables.
e, f = 10 --[[declaration of e and f as global variables.
Here value of f is nil --]]
local a , b = 5 ,10 --declaration of a and b as local variables.
Data Types
Lua is a dynamically typed language, so the variables don't have types, only the values have types.
- nil (used to differentiate the value from having some data or no(nil) data)
- boolean
- number (real(double precision floating point) numbers)
- string
- function (C or Lua function)
- userdata (arbitrary C data)
- thread
- table
Example
print("= Data types =")
print(type("What is my type"))
Operators
- Arithmetic: + - * / % ^ -
- Relational: == ~= > < >= <=
- Logical: and or not
- Misc: .. (concatinates two strings) # (returns the length of a string)
Example
print("= Operators =")
print("5.2 % 3 = ",5.2%3)
Loops
While loop
Syntax
while(condition) do statement(s) end
For loop
Syntax
for init,max/min value, increment do statement(s) end
Example
print("= For loop =")
for i = 10,1,-1
do
print(i)
end
Repeat-until loop
Syntax
repeat statement(s) until(condition)
Example
print("= Repeat until loop =")
a = 10
repeat
print("a = ",a)
a = a + 1
until(a>15)
Conditionals
Any combination of Boolean true and non-nil values as true, and if it is either boolean false or nil, then it is assumed as false value. Zero is evaluated as true.
if-then-else
if(condition) then statement(s) else other_statement(s) end
Functions
Syntax
optional_function_scope function function_name( argument_1, argument_2, ... argument_n) function_body return result_parameters_separated_by_commas end optional_function_scope - keyword local to limit the scope of the function or ignore the scope section, which will make it a global function return − possible to return multiple values by following the return keyword with the comma separated return values
Functions can be assigned to variables and passed as parameters of another function.
Example
print("= Functions =")
function one_up(x)
return x + 1
end
print("one_up(1) = ",one_up(1))
up = function(x)
return x + 1
end
print("up(1) = ",up(1))
twice = function(x,fun)
return fun(fun(x))
end
print("apply_twice(1,up) = ",twice(1,up))
Strings
Syntax
str1 = "string" str2 = 'string' srt3 = [[ string; potentiall long and containing linebreaks ]]
Escape sequences: \a \b \f \n \r \t \v \\ \" \' \[ \]
String manipulation functions
string.strlen(str)
string.upper(str)
string.lower(str)
string.sub(str,StartIndex,optionalEndIndex)
string.gsub(str,find_str,replace_str)
string.find(str,find_str,optionalStartIndex,optionalEndIndex)
string.reverse(str)
string.format(...)
Formatting options: %s - string
%c - character
%f - float
%d - decimal
%x - hexadecimal
%o - octal
string.char(n)
Returns internal numeric representation.
string.byte(str,optionalCharacterIndex)
Returns internal character representation.
string.rep(str,n)
Returns a string by repeating the input string n times.
..
Concatinates two strings.
Example
print("= Strings =")
long_str = "a long string"
short_str = string.gsub(long_str,"long","")
print(long_str)
print(short_str)
s, e = string.find(long_str,"long")
substr = string.sub(long_str,s,e)
print(substr)
print(string.byte("abcd",2))
print(string.byte("abcd",-2))
Arrays
Syntax
array ={"alice", "bob"}
array[1] = "alice"
array[2] = "bob
Indexing generally starts at index 1 but it is possible to create objects at index 0 and below 0 as well. Accessing an index that is not used will result in nil.
Example
print("= Arrays =")
array = {}
for i = -3,3,1 do
array[i] = 2^i
end
for i = -3,3,1 do
print(array[i])
end
Iterators
Functions represent iterators. Based on the state maintenance in these iterator functions the two main types are stateless and stateful iterators.
Generic iterator
Example
print("Generic iterator")
array = {"alice", "bob"}
for k,v in ipairs(array) do
print(k,v)
end
Stateless iterators
Example
print("Stateless iterators")
function square(max_count,count)
-- max_count is the invariant state
-- count is the control variable
if count <= max_count then
count = count + 1
return count,count * count
end
end
for k,v in square,4,0 do
print(k,v)
end
Stateful iterators
Example
print("Stateful iterators")
function simpleCounter(n)
local count = 0
return function()
count = count + 1
if count > n then
return nil
end
return count
end
end
for v in simpleCounter(5) do
print(v)
end
Tables
Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.
Lua uses tables in all representations including representation of packages. When we access a method string.format, it means, we are accessing the format function available in the string package.
Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself.
Example
print("= Tables =")
table = {}
table[1]="alice"
table["two"]="bob"
table[3]={"a","b","c"}
print(table[1])
print(table["two"])
print("Print table:")
for k,v in pairs(table) do
print(k,v)
end
print("Print table in table:")
for k,v in ipairs(table[3]) do
print(k,v)
end
Common functions
table.concat(table,optionalSeperator,optionaStartIndex,optionalEndIndex)
Concatenate the elements of a table to form a string. Each element must be able to be coerced into a string.
A separator can be specified which is placed between concatenated elements.
Additionally a range can be specified within the table, starting at the i-th element and finishing at the j-th element.
table.sort(table,optionalComparisonFunction)
Sort the elements of a table in-place (i.e. alter the table).
table.insert(table,optionalPosition,value)
table.remove(table,optionalPosition)
Remove an element from a table.If no position is given remove the last element in the table which is specified by the size of the table.
table.maxn(table)
Returns largest numeric index.
Example
tab={"alice","bob","eve","ben","ken"}
table.remove(tab)
print(table.concat(tab,"~"))
table.sort(tab)
print(table.concat(tab,"~"))
Modules
All these functions and variables are wrapped in to the table, which acts as a namespace. Also, a well behaved module has necessary provisions to return this table on require.
Example
local mymath = {}
function mymath.add1(a)
return a + 1
end
Loading a module
mymathmodule = require("mymath")
mymathmodule.add1(3)
require "mymath" local add1 = mymath.add1 add1(3)
File I/O
file = io.open (filename [, mode]) Modes: "r" - Read-only mode and is the default mode where an existing file is opened. "w" - Write enabled mode that overwrites the existing file or creates a new file. "a" - Append mode that opens an existing file or creates a new file for appending. "r+" - Read and write mode for an existing file. "w+" - All existing data is removed if file exists or new file is created with read write permissions. "a+" - Append mode with read mode enabled that opens an existing file or creates a new file. io.input(file) io.output(file) io.write(x) io.close(file) io.tmpfile() io.lines(optionalFileName) Provides a generic for loop iterator that loops through the file and closes the file in the end, in case the file name is provided or the default file is used and not closed in the end of the loop.