为了表示RGB颜色,假设在C程序中需要用三个0~255数字,在Lua由于是实数就用0~1表示。
在lua中你可以用一个表来写:
--lua
background = {r=0.30, g=0.10, b=0}
你也就可以这样使用预定义颜色:
--lua
BLUE = {r=0, g=0, b=1.0}
<other color definitions>
background = BLUE
一、获取表信息
在C程序中就可以这样写:
//c
#define MAX_COLOR 255
/* assume that table is on the stack top */
int getcolorfield (lua_State *L, const char *key) {
int result;
lua_getfield(L, -1, key);
if (!lua_isnumber(L, -1))
error(L, "invalid component in background color");
result = (int)(lua_tonumber(L, -1) * MAX_COLOR);
lua_pop(L, 1); /* remove number */
return result;
}
lua_getglobal(L, "background");
if (!lua_istable(L, -1))
error(L, "'background' is not a table");
red = getcolorfield(L, "r");
green = getcolorfield(L, "g");
blue = getcolorfield(L, "b");
二、填写表信息
//c
void setcolorfield (lua_State *L, const char *index, int value) {
lua_pushnumber(L, (double)value / MAX_COLOR);
lua_setfield(L, -2, index);
}
void setcolor (lua_State *L, struct ColorTable *ct) {
lua_newtable(L); /* creates a table */
setcolorfield(L, "r", ct->red); /* table.r = ct->r */
setcolorfield(L, "g", ct->green); /* table.g = ct->g */
setcolorfield(L, "b", ct->blue); /* table.b = ct->b */
lua_setglobal(L, ct->name); /* 'name' = table */
}
你可以在C中写预定义颜色:
//c
struct ColorTable {
char *name;
unsigned char red, green, blue;
} colortable[] = {
{"WHITE", MAX_COLOR, MAX_COLOR, MAX_COLOR},
{"RED", MAX_COLOR, 0, 0},
{"GREEN", 0, MAX_COLOR, 0},
{"BLUE", 0, 0, MAX_COLOR},
<other colors>
{NULL, 0, 0, 0} /* sentinel */
};
然后传给lua:
//c
int i = 0;
while (colortable[i].name != NULL)
setcolor(L, &colortable[i++]);
不过建议还是从lua中写预定义颜色,这样可以检测拼写错误。
最后这里是读取lua中的颜色示例(无论C语言预定义好的字符串还是表):
//c
lua_getglobal(L, "background");
if (lua_isstring(L, -1)) { /* value is a string? */
const char *name = lua_tostring(L, -1); /* get string */
int i; /* search the color table */
for (i = 0; colortable[i].name != NULL; i++) {
if (strcmp(colorname, colortable[i].name) == 0)
break;
}
if (colortable[i].name == NULL) /* string not found? */
error(L, "invalid color name (%s)", colorname);
else { /* use colortable[i] */
red = colortable[i].red;
green = colortable[i].green;
blue = colortable[i].blue;
}
} else if (lua_istable(L, -1)) {
red = getcolorfield(L, "r");
green = getcolorfield(L, "g");
blue = getcolorfield(L, "b");
} else
error(L, "invalid value for 'background'");