Lua 与C/C++ 交互系列:注冊枚举enum到Lua Code中
在Lua Code中注冊C/C++的枚举很easy,就像注冊全局变量一样。我们使用枚举名称作为命名空间,来避免注冊的枚举发生冲突。注冊的枚举存储在全局环境(线程环境)中。
当在Lua Code中訪问枚举时,通过名称来訪问相应的值。
sample_9.cpp c++代码例如以下:
//在Lua Code中注冊的enum,为了避免冲突,以名称作为enumTable来存储 enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, }; //定义宏用来方便使用设置键值 #define LUA_ENUM(L, val) \ lua_pushliteral(L, #val); \ lua_pushnumber(L, val); \ lua_settable(L, -3) void register_enum(lua_State* L) { //创建一个enumTable,用于存储Enum的全部枚举。通过枚举名称=枚举值 lua_newtable(L); //设置 enumTable["Monday"]=Monday LUA_ENUM(L, Monday); LUA_ENUM(L, Tuesday); LUA_ENUM(L, Wednesday); LUA_ENUM(L, Thursday); LUA_ENUM(L, Friday); LUA_ENUM(L, Saturday); LUA_ENUM(L, Sunday); //把enumTable存在在_G 全局环境(线程环境)中,以枚举名称作为键 lua_setglobal(L,"Week"); } int main(int argc, char *argv[]) { lua_State* L = lua_open(); luaL_openlibs(L); register_enum(L); luaL_dofile(L, "sample_9.lua"); lua_close(L); return 0; }sample_9.lua Lua Code代码例如以下:
local Week=_G["Week"] print(Week) print(Week.Monday) print(Week.Tuesday) print(Week.Wednesday) print(Week.Thursday) print(Week.Friday) print(Week.Saturday) print(Week.Sunday)
输出结果:
posted on 2017-05-23 14:39 gavanwanggw 阅读(402) 评论(0) 编辑 收藏 举报