我编写了一些调用 Lua 的 C 代码。共有三个 Lua 文件:init.lua、redis_pool.lua和run.lua。首先,我在redis_pool.lua中初始化了 redis 池(调用init.lua和init.lua调用redis_pool.lua),redis_pool.lua看起来是这样的:
-- init.lua
local redis_pool = require('redis_pool')
redis_pool.init_pools()
...
-- redis_pool.lua
local redis_pool = {}
function init_pools()
-- init data in redis_pool
end
function redis_pool.get_pool(pool_name)
-- return one of redis in @redis_pool
return redis_pool[pool_name]
end
初始化后,表redis_pool
看起来像这样:
redis_pool = {
['pool1'] = {pool_sz, pool = {...}}
['pool2'] = {pool_sz, pool = {...}}
['pool3'] = {pool_sz, pool = {...}}
['pool4'] = {pool_sz, pool = {...}}
-- some other functions...
}
现在,我认为表redis_pool
已经准备好了,然后我在 C 中调用run.lua
-- run.lua
local redis_pool = require('redis_pool')
function run_func
-- error, redis_pool['pool1'] is nil!!
local pool = redis_pool.get_pool('pool1')
end
我已经初始化了 table redis_pool
,但是为什么它变成了nil
C 调用另一个 Lua 来访问它?我是否必须返回redis_pool
C 堆栈,并将其传递给后续的 Lua 访问函数?
更新
其中一些 C 代码:
/* C code to call init.lua */
int init_redis_pool(void) {
int ret = 0;
lua_State *ls = luaL_newstate();
luaL_openlibs(ls);
ret = luaL_loadfile(ls, "init.lua");
const char *err;
(void)err;
if (ret) {
err = lua_tostring(ls, -1);
return -1;
}
/* preload */
ret = lua_pcall(ls, 0, 0, 0);
if (ret) {
err = lua_tostring(ls, -1);
return -1;
}
lua_getglobal(ls, "init_pools");
ret = lua_pcall(ls, 0, 0, 0);
if (ret) {
err = lua_tostring(ls, -1);
return -1
}
lua_close(ls);
return 0;
}
/* calling run.lua from C */
int some_func() {
...
ret = luaL_loadfile(ls, "run.lua");
...
lua_getglobal(ls, "run_func")
ret = lua_pcall(ls, 0, 0, 0)
if (ret) {
/* error here */
err = lua_tostring(ls, -1);
return -1;
}
...
return 0;
}