Je code un certain C qui appelle Lua. il y a trois fichiers Lua: init.lua, redis_pool.lua et run.lua. Tout d'abord, j'initialisés Redis piscine redis_pool.lua (appelant init.lua et init.lua appelant redis_pool.lua) et le redis_pool.lua semble comme ça:Comment stocker les données initialisées dans 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
après initialisation, table redis_pool
semble comme ça:
redis_pool = {
['pool1'] = {pool_sz, pool = {...}}
['pool2'] = {pool_sz, pool = {...}}
['pool3'] = {pool_sz, pool = {...}}
['pool4'] = {pool_sz, pool = {...}}
-- some other functions...
}
maintenant, je pense que la table redis_pool
est prêt, alors je cal ling run.lua en 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
J'ai initialisé la table redis_pool
, mais pourquoi il est devenu nil
en C Appeler un autre Lua pour y accéder? Dois-je renvoyer la pile redis_pool
à la pile C et la transmettre à la fonction d'accès Lua suivante?
Mise à jour
certains de ces codes 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;
}
Veuillez poster les parties du code C où vous exécutez les fichiers. –
@llmo Euro: Mise à jour du code C. – coanor