我编写了一些调用 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
我已经初始化了表redis_pool
,但是为什么C调用另一个Lua访问它时它变成了nil
?
是否必须将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;
}
最佳答案
你有两个独立的 Lua 状态用于初始化和使用:
/* C code to call init.lua */
int init_redis_pool(void) {
int ret = 0;
lua_State *ls = luaL_newstate(); // ls is a local variable
luaL_openlibs(ls);
ret = luaL_loadfile(ls, "init.lua");
/* calling run.lua from C */
int some_func() {
...
ret = luaL_loadfile(ls, "run.lua"); // ls is another local variable
当您加载 init.lua
并初始化池时,更改仅适用于您的本地 ls
变量。当您在另一个函数中访问 run.lua
时,您之前的 Lua 状态已经关闭并销毁。
您需要在函数之间共享您的 Lua 状态变量。一种方法是在两个函数之外创建状态并将其传递给每个函数:
/* C code to call init.lua */
int init_redis_pool(lua_State *ls) {
/* calling run.lua from C */
int some_func(lua_State *ls) {
...
关于c - 如何存储在Lua中初始化的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16439033/