Lua Cheatsheet




Sample program

name = io.read("*a")
print ("Hello ", name)
  • io.read : to read the data from console

  • print : to output the data to console.

  • -- : comment

  • --[[ Multi

    Line

    comments --]]

Variables

  • Lua is a dynamically typed language and hence only the values will have types not the variables.

Examples

-- global variables, variables are by default global
x = 10

-- local variables

local x = 30

Data types

Value TypeDescription
numberRepresents numbers
stringRepresents text
nilDifferentiates values whether it has data or not
booleanValue can be either true or false
functionRepresents a sub-routine
userdataRepresents arbitary C data
threadRepresents independent threads of execution.
tableCan hold any value except nil

Operators

Operator typeDescription
Arithmetic Operator+ , - , * , / , %, -
comparision Operator< , > , <= , >=, ~=, ==
Logical Operatorand , or, not
Misc Operator.. , #

There are no ++, --, ternary operators in lua

String methods

MethodDescription
str1 .. str2String concatenation
string.len(str)To get the length of a string
string.gsub(str, "t1", "t2")Used to Replace t1 with t2 in the string str
string.find(str, txt)Searches for txt in str string and returns it's index
string.upper(str)to change the str to upper case
string.lower(str)to change the str to lower case

Conditional statements

1. If

if conditional-expression then
--code
end

2. If-else

if conditional-expression then
   --code
elseif conditional-expression then
    --code
else
    --code
end

There is no switch in Lua

Loops

1. While

while(condition)
do
--code
end

2. Repeat-Until

repeat
   --code
until( condition )

3. For

for init,max/min value, increment
do
   --code
end

Functions

[function_scope] function function_name( argument1, argument2, argument3........, argumentn)
--code
return params with comma seperated
end

Example

function sum(x,y)
	sum=x+y
	return sum
end

print(sum(10,20))