我编写了一些调用Lua的C语言。有三个Lua文件:init.lua,redis_pool.lua和run.lua。首先,我初始化Redis的池redis_pool.lua(主叫init.lua和init.lua调用redis_pool.lua),以及redis_pool.lua好像是:如何存储在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
准备好,然后我CAL凌run.lua用C
-- 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
我已经初始化表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;
}
请发布运行文件的C代码部分。 – 2013-05-08 11:31:23
@llmo Euro:更新了C代码。 – coanor 2013-05-08 11:49:01