[英]How to store data initialized in Lua?
我编写了一些调用Lua的C代码。 有三个Lua文件: init.lua , redis_pool.lua和run.lua 。 首先,我初始化的Redis在redis_pool.lua池(调用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
在init之后,表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
,但为什么它变为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;
}
您有两个独立的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) {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.