Lua Tutorial for Freeswitch

5:52 pm in FreeSWITCH, Lua by admin

Lua is very lightweight programing language.Lua has a simple syntax that is easy both to learn and to read. Following is a
simple script:

— This is a sample Lua script
— Single line comments begin with two dashes

–[[
This is a multi-line comment.
Everything between the double square brackets
is part of the comment block.
]]

— Lua is loosely typed
var = 1 — This is a comment
var = �alpha� — Another comment
var = �A1� — You get the idea…

–[[
When the Lua script is called from the dialplan
you have a few magic objects. A handy one is
the 'freeswitch' object which lets you do things
like this:
freeswitch.consoleLog(�INFO�,�This is a log line\n�)

Another important one is the 'session' object which
Lets you manipulate the call:
session:answer()
session:hangup()
]]

— Lua makes extensive use of tables
— Tables are a hybrid of arrays and associative arrays
my_table = {
key1 = val1,
key2 = val2,
�index 1�,
�index 2�
}
freeswitch.consoleLog(�my_table key1 is ‘� .. my_table[key1] .. �’\n�)
freeswitch.consoleLog(�my_table index 1 is ‘� .. my_table[1] .. �’\n�)

— Access arguments passed in
arg1 = argv[1] — First argument
arg2 = argv[2] — Second argument

— Simple if/then
if ( var == �A1� ) then
freeswitch.consoleLog(�INFO�,�var is ‘A1′\n�)
end

— Simple if/then/else
if ( var == �A1� ) then
freeswitch.consoleLog(�INFO�,�var is ‘A1′\n�)
else
freeswitch.consoleLog(�INFO�,�var is not ‘A1′!\n�)
end

— String concatenation uses ..
var = �This � .. � and � .. �that�
freeswitch.consoleLog(�INFO�,�var contains ‘� .. var .. �’\n�)

— The end

Every Lua script that is executed from the Dialplan receives the session object,
which represents the call leg that is being processed. The session object is the
primary means of manipulating the call, and is used extensively in Lua scripting.