在mod_lua.cpp文件中定义了两个api
SWITCH_STANDARD_APP(lua_function)
SWITCH_STANDARD_API(luarun_api_function)
分别对应lua和luarun命令,所有以宏SWITCH_STANDARD_API定义的都是freeswitch暴露的api接口。
我们这里以luarun为例分析
SWITCH_STANDARD_API(luarun_api_function)
{
if (zstr(cmd)) {
stream->write_function(stream, "-ERR no args specified!\n");
} else {
lua_thread(cmd);
stream->write_function(stream, "+OK\n");
}
return SWITCH_STATUS_SUCCESS;
}
所以当执行luarun的时候主要是调用lua_thread()函数处理。
int lua_thread(const char *text)
{
switch_thread_t *thread;
switch_threadattr_t *thd_attr = NULL;
switch_memory_pool_t *pool;
lua_thread_helper *lth;
switch_core_new_memory_pool(&pool);
lth = (lua_thread_helper *) switch_core_alloc(pool, sizeof(*lth));
lth->pool = pool;
lth->input_code = switch_core_strdup(lth->pool, text);
switch_threadattr_create(&thd_attr, lth->pool);
switch_threadattr_detach_set(thd_attr, 1);
switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
switch_thread_create(&thread, thd_attr, lua_thread_run, lth, lth->pool);
return 0;
}
在lua_thread中主要是创建一个新线程,并在线程里面执行:lua_thread_run
static void *SWITCH_THREAD_FUNC lua_thread_run(switch_thread_t *thread, void *obj)
{
struct lua_thread_helper *lth = (struct lua_thread_helper *) obj;
switch_memory_pool_t *pool = lth->pool;
lua_State *L = lua_init(); /* opens Lua */
lua_parse_and_execute(L, lth->input_code, NULL);
lth = NULL;
switch_core_destroy_memory_pool(&pool);
lua_uninit(L);
return NULL;
}
在lua_thread_run中先初始化了一个lua_State,然后调用lua_parse_and_execute去加载lua脚本文件并执行
static int lua_parse_and_execute(lua_State * L, char *input_code, switch_core_session_t *session)
{
int error = 0;
if (zstr(input_code)) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "No code to execute!\n");
return 1;
}
while(input_code && (*input_code =