Search code examples
luafreeswitch

Passing session between two lua files


I want to call another lua script from my main script say like session:execute("lua","/path/somefile.lua "..somearg1.." "..somearg2..) its working fine and somefile.lua is executing but suppose i also want to use session there i.e. i am accessing a database in somefile.lua and want to speak a query result in somefile.lua by using session. (session:speak(queryResult)).

i also tried sending session as one of argument session:execute("lua","/path/somefile.lua "..session) but it gives a error "attempt to concatenate global 'session' (a userdata value)" any advise..??

code of first lua file

session:answer();
session:setAutoHangup(false);
session:set_tts_params("flite","kal");
callerId = session:getVariable("caller_id_number");
session:execute("lua ","/etc/freeswitch/scripts/checkbal.lua "..callerId.." "..session);
session:destroy();

code for 2nd lua file

callerId=argv[1];
session=argv[2];
luasql = require "luasql.postgres";
env=assert(luasql:postgres());
con=assert(env:connect("mydb","postgres","password","127.0.0.1","5432"));
cur=assert(con:execute("select balance from bal where number='"..callerId.."'"));  
session:set_tts_params("flite","kal");
row=cur:fetch({},"a");
res=row.balance;
session:speak(res);

Solution

  • Rig your second file to be a module that returns a function or a table of functions. Here is an example that has second file return a "speak" function that you can then re-use as many times as desired:

    Code of first Lua file:

    session:answer()
    session:setAutoHangup(false)
    session:set_tts_params("flite","kal")
    callerId = session:getVariable("caller_id_number")
    speak = require 'checkbal'
    speak(session, callerId)
    -- session:execute("lua ","/etc/freeswitch/scripts/checkbal.lua "..callerId.." "..session)
    session:destroy()
    

    Code for 2nd Lua file:

    luasql = require "luasql.postgres"
    
    local env=assert(luasql:postgres())
    local con=assert(env:connect("mydb","postgres","password","127.0.0.1","5432"))
    
    local function speak(session, callerId)
        local cur = assert(con:execute("select balance from bal where number='"..callerId.."'"))
        session:set_tts_params("flite","kal")
        row=cur:fetch({},"a")
        res=row.balance
        session:speak(res)
    end
    
    return speak
    

    Note: this is Lua: no need for semicolons.

    I would consider making "session" an object (table with methods) with a "speak" method, but this is going beyond scope of this question and is not necessary, may just lead to more maintainable code later.