lua --- 表操作

c api 参考手册:http://www.leeon.me/a/lua-c-api-manual

 1 // LuaTest.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<iostream>
 6 using namespace std;
 7 #include<lua.hpp>
 8 
 9 #define MAX_COLOR 255
10 
11 //在应用中定义颜色
12 struct  ColorTable
13 {
14     char *name;
15     unsigned char red, green, blue;
16 }colortable[] =
17 {
18     { "WHITE", MAX_COLOR, MAX_COLOR, MAX_COLOR },
19     { "RED", MAX_COLOR, 0, 0 },
20     { "GREEN", 0, MAX_COLOR, 0 },
21     { "BLUE", 0, 0, MAX_COLOR },
22     { "BLACK", 0, 0, 0 },
23     { NULL, 0, 0, 0 }
24 };
25 
26 void setfield(lua_State *L, char *key, int value)
27 {
28     lua_pushstring(L, key);                            //key
29     lua_pushnumber(L, (double)(value / MAX_COLOR)); //value
30     //以栈顶元素作为 value,以栈顶的下一个元素作为 key,调用完成后弹出栈顶的两个元素
31     lua_settable(L, -3);
32 }
33 
34 void setcolor(lua_State *L, struct ColorTable *colTab)
35 {
36     lua_newtable(L);   //创建一个新的 table,然后将其入栈
37     setfield(L, "r", colTab->red);
38     setfield(L, "g", colTab->green);
39     setfield(L, "b", colTab->blue);
40     lua_setglobal(L, colTab->name);  //将 table 出栈并将其赋给一个全局变量名
41 }
42 
43 void registerAllColor(lua_State *L, struct ColorTable *colTab)
44 {
45     int i = 0;
46     while (colTab[i].name != NULL)
47     {
48         setcolor(L, &colTab[i++]);
49     }
50 }
51 
52 int _tmain(int argc, _TCHAR* argv[])
53 {
54     lua_State *l = luaL_newstate();
55     luaL_openlibs(l);
56     registerAllColor(l, colortable);
57 
58 
59 
60     //luaL_dofile(l, "main.lua");
61 
62     lua_close(l);
63     system("pause");
64     return 0;
65 }

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/10706416.html