小刀客
unread,Nov 10, 2009, 2:26:14 AM11/10/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to programming with GNU software
1、在文件中include lua头文件
#include "lua.hpp"
2、在工程中设置,包含lua51.lib
3、在文件的开始处,写如下的宏
#define get_value(TYPE,L,T,S) \
lua_pushstring(L,S); \
lua_gettable(L,-2); \
T = lua_to##TYPE(L,-1);\
lua_pop(L,1)
#define get_table(name,L,T,Func) \
lua_pushstring(L,name); \
lua_gettable(L,-2); \
Func(L,T); \
lua_pop(L,1)
4、在文件的结尾处取消宏定义
#undef get_value
#undef get_table
5、假设我们读取的数据结构如下
typdef struct Pt{
double x;
double y;
double z;
}Pt;
typedef struct Mem{
int index;
char[16] name;
vector<Pt> pts;
}Mem;
typedef struct Steel{
int index;
Mem mem;
}Steel;
6、相应的输入文件input的格式为
entry{
index = 12,
mem = {
index = 10,
name = [[mem1]], --this is comment
pts = {
{
x = 12.0, -- this is comment
y = 13.0,
z = 14.0,
},
{
x = 11.0,
y = 15.0,
z = 16.0, -- this is comment
},
},
}
--[[
this is multiline
comment.
]]--
entry{
index = 13,
mem = {
index = 11,
name = [[mem2]],
pts = {
{
x = 12.0,
y = 13.0
z = 14.0,
},
{
x = 11.0,
y = 15.0,
z = 16.0,
},
{
x = 13.0,
y = 14.0,
z = 16.0,
},
},
}
7、定义读取 stell mem pt的函数
static int input_pt(lua_State* L,Pt* pt)
{
get_value("number",L,pt->x,"x");
get_value("number",L,pt->y,"y");
get_value("number",L,pt->z,"z");
return 1;
}
static int input_mem(lua_State* L,Mem* mem)
{
get_value("number",L,mem->index,"index");
char* tmp = NULL;
get_value("string",L,tmp,"name");
strcpy(mem->name,tmp); //warning maybe strlen(tmp) > 16!
// get array
lua_pushstring(L,"pts");
lua_gettable(L,-2);
int index = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L,index) !=0){
Pt pt;
input_pt(L,&pt);
pts.push_back(pt);
}
lua_pop(L,1);
}
static int input_steel(lua_State* L,Steel* steel)
{
get_value("number",L,steel->index,"index");
get_table("mem",L,&steel->mem,input_mem);
}
8、读取过程
static vector<Steel> steels;
static int entry_db(lua_State* L)
{
Steel steel;
input_steel(&steel);
steels.push_back(steel);
}
static void read_input()
{
lua_State *L = lua_open(); /* opens Lua */
luaopen_base(L); /* opens the basic library */
luaopen_table(L); /* opens the table library */
luaopen_io(L); /* opens the I/O library */
luaopen_string(L); /* opens the string lib. */
luaopen_math(L); /* opens the math lib. */
lua_pushcfunction(L,&entry_gb);
lua_setglobal(L,"entry");
luaL_loadfile(L,"path/input-file-name");
lua_pcall(L,0,0,0);
lua_close(L);
}