c使用lua作为作为配置文件
读取配置文件感觉有点坑, 利用已学习的lua,作为配置文件,思路是这样的:
配置文件正确性的判断,用lua写,检查配置文件正确性也用lua写,然后c通过操作lua状态机堆栈对去读取相关配置
1.C创建lua虚拟机
2.C通过调用lua的luaL_dofile函数,把结果(一个table)返回
- 执lua脚本检查配置文件,把最终的结果(table)留在堆栈
4.c通过操作堆栈,把结果读出
#include <stdio.h>
//lua
#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>
#include <lua5.3/luaconf.h>
//配置文件table名称m_name
int loadprofile(lua_State *L,const char *m_name){
if (LUA_OK != luaL_dofile(L,"./hello.lua")) return 0;
//执行完了必须要留下一个table
if (lua_gettop(L) ==0 || lua_type(L,-1)!=LUA_TTABLE) return 0;
lua_setglobal(L,m_name);//弹出保存到全局表
return 1;
}
int main()
{
lua_State *L; //创建虚拟机
L = luaL_newstate();
luaL_openlibs(L);
loadprofile(L,"hello");
if (lua_getglobal(L,"hello")!= LUA_TTABLE){
printf("读取配置文件失败");
goto end;
}
//取出配置文件
//读取ip
lua_pushstring(L,"ip");
if (lua_gettable(L,-2)==LUA_TSTRING){
printf("IP:%s\n",lua_tostring(L,-1));
}
lua_pop(L,1);//弹出栈顶元素
//读取端口
lua_pushstring(L,"port");
if (lua_gettable(L,-2)==LUA_TNUMBER){
printf("port:%d\n",lua_tointeger(L,-1));
}
lua_pop(L,1);
//销毁状态机
end:
lua_close(L);
return 0;
}
lua脚本
-- a是配置
a={ip="127.0.0.1",port=22,name="我的电脑"}
-- 以下是配置检查
print("检查配置:")
function checkpro(pro)
--检查端口正确性
if type(pro.port) ~= "number" or pro.port > 65535 or pro.port < 0 then
print("端口必须为整数");
return nil
end
-- 检查ip
head,tail,A,B,C,D=string.find(pro.ip,"(%d+)%.(%d+)%.(%d+)%.(%d+)")
--检查函数
local ck = function(n)
if tonumber(n)>255 or tonumber(n)<0 then
return false
end
return true
end
if ck(A) and ck(B) and ck(C) and ck(D) then
--重新格式化字符串避免有空格出错
pro.ip=string.format("%d.%d.%d.%d",A,B,C,D)
else
print(string.format("IP范围有错:%s.%s.%s.%s",A,B,C,D))
return nil
end
print("测试pass")
return pro
end
return checkpro(a)
当然,在arpa/inet.h下,有字符串转换ip的函数,这里功能不全,仅仅测试学习
以下是执行结果


网友评论