| 279 | } |
| 280 | |
| 281 | int |
| 282 | ts_lua_add_module(ts_lua_instance_conf *conf, ts_lua_main_ctx *arr, int n, int argc, char *argv[], char *errbuf, int errbuf_size) |
| 283 | { |
| 284 | int i, ret; |
| 285 | int t; |
| 286 | lua_State *L; |
| 287 | |
| 288 | for (i = 0; i < n; i++) { |
| 289 | conf->_first = (i == 0) ? 1 : 0; |
| 290 | conf->_last = (i == n - 1) ? 1 : 0; |
| 291 | |
| 292 | TSMutexLock(arr[i].mutexp); |
| 293 | |
| 294 | L = arr[i].lua; |
| 295 | |
| 296 | lua_newtable(L); /* new TB1 */ |
| 297 | lua_pushvalue(L, -1); /* new TB2 */ |
| 298 | lua_setfield(L, -2, "_G"); /* TB1[_G] = TB2 empty table, we can change _G to xx */ |
| 299 | lua_newtable(L); /* new TB3 */ |
| 300 | lua_rawgeti(L, LUA_REGISTRYINDEX, arr[i].gref); /* push L[GLOBAL] */ |
| 301 | lua_setfield(L, -2, "__index"); /* TB3[__index] = L[GLOBAL] which has ts.xxx api */ |
| 302 | lua_setmetatable(L, -2); /* TB1[META] = TB3 */ |
| 303 | lua_replace(L, LUA_GLOBALSINDEX); /* L[GLOBAL] = TB1 */ |
| 304 | |
| 305 | ts_lua_set_instance_conf(L, conf); |
| 306 | |
| 307 | if (conf->content) { |
| 308 | if (luaL_loadstring(L, conf->content)) { |
| 309 | snprintf(errbuf, errbuf_size, "[%s] luaL_loadstring failed: %s", __FUNCTION__, lua_tostring(L, -1)); |
| 310 | lua_pop(L, 1); |
| 311 | TSMutexUnlock(arr[i].mutexp); |
| 312 | return -1; |
| 313 | } |
| 314 | |
| 315 | } else if (strlen(conf->script)) { |
| 316 | if (luaL_loadfile(L, conf->script)) { |
| 317 | snprintf(errbuf, errbuf_size, "[%s] luaL_loadfile %s failed: %s", __FUNCTION__, conf->script, lua_tostring(L, -1)); |
| 318 | lua_pop(L, 1); |
| 319 | TSMutexUnlock(arr[i].mutexp); |
| 320 | return -1; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | if (lua_pcall(L, 0, 0, 0)) { |
| 325 | snprintf(errbuf, errbuf_size, "[%s] lua_pcall %s failed: %s", __FUNCTION__, conf->script, lua_tostring(L, -1)); |
| 326 | lua_pop(L, 1); |
| 327 | TSMutexUnlock(arr[i].mutexp); |
| 328 | return -1; |
| 329 | } |
| 330 | |
| 331 | /* call "__init__", to parse parameters */ |
| 332 | lua_getglobal(L, "__init__"); |
| 333 | |
| 334 | if (lua_type(L, -1) == LUA_TFUNCTION) { |
| 335 | // specifying that the file has an __init__ function |
| 336 | conf->init_func = 1; |
| 337 | |
| 338 | lua_newtable(L); |
no test coverage detected