我編寫了一些調用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