Lua,Lua API,配置文件
来源:互联网 发布:北京网络公安报警电话 编辑:程序博客网 时间:2024/05/16 12:41
想像一个场景:你的c程序需要有一个窗口,你想让用户可以自定义窗口大小。方法很多,比如使用环境变量,或键值对的文件。不管怎样,你需要解析它。使用lua配置文件是个不错的选择。
首先,你可以定义如下的配置文件:
--define window size
width = 100
height = 50
width = 100
height = 50
然后,我们写个函数来解析它,使用lua API 来指导lua解析配置。,下面是完整的程序:
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
void load(lua_State* L, const char* fname, int *w, int *h)
{
if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0)) {
error(L, "error:%s", lua_tostring(L, -1));
}
lua_getglobal(L, "width");
lua_getglobal(L, "height");
if (!lua_isnumber(L, -2)) {
error(L, "width shuld be num.");
}
if (!lua_isnumber(L, -1)) {
error(L, "height shuld be num");
}
*w = lua_tointeger(L, -2);
*h = lua_tointeger(L, -1);
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
int w, h;
load(L, "config", &w, &h);
printf("%d,%d", w, h);
return 0;
}
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
void load(lua_State* L, const char* fname, int *w, int *h)
{
if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0)) {
error(L, "error:%s", lua_tostring(L, -1));
}
lua_getglobal(L, "width");
lua_getglobal(L, "height");
if (!lua_isnumber(L, -2)) {
error(L, "width shuld be num.");
}
if (!lua_isnumber(L, -1)) {
error(L, "height shuld be num");
}
*w = lua_tointeger(L, -2);
*h = lua_tointeger(L, -1);
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
int w, h;
load(L, "config", &w, &h);
printf("%d,%d", w, h);
return 0;
}
使用lua配置文件有什么好处呢?我想,大概有以下理由:
1.Lua为你处理了所有语法细节(包括错误)
2.配置内容可读性好,甚至你可以写上注释。
3.可以很容易添加新的配置信息。
(完)
0 0
- Lua,Lua API,配置文件
- lua api
- lua学习:lua作配置文件
- lua学习:lua作配置文件
- Lua写配置文件
- lua作配置文件
- Lua 配置文件示例
- lua当作配置文件
- 【cocos2dx 3.3 lua】09 lua配置文件读写
- Lua API 小记
- lua c api
- LUA C API
- Lua protobuf相关API
- Lua中的API函数
- lua C Api 简介
- nginx api for lua
- Lua API 小记1
- lua-C API
- centos 安装setuptools、mysqldb
- 从宏观到细节
- 水樹 奈々 Blog 20140908 鶴姫の鎧に興奮っ!译文
- Linux系统分析工具之mpstat,iostat(二)
- PHP 图像处理
- Lua,Lua API,配置文件
- How can I change a file's encoding with vim?
- Asp.net Mvc使用PagedList分页
- C/C++中Static的作用详述
- Java NIO系列教程(八) SocketChannel
- Linux系统分析工具之vmstat,free,ping(三)
- ZOJ 3819 Average Score (2014牡丹江区域赛)
- C++判断字符串是否为数字
- OpenMP并行程序设计——Eclipse开发环境的搭建