# 剑孤寒的小站

posts - 75, comments - 290, trackbacks - 0, articles - 0
《在Lua中使用枚举型变量》

function CreatEnumTable(tbl, index)
assert(IsTable(tbl))
local enumtbl = {}
local enumindex = index or 0
for i, v in ipairs(tbl) do
enumtbl[v] = enumindex + i
end
return enumtbl
end

EnumTable =
{
"ET1",
"ET2",
}

EnumTable = CreatEnumTable(EnumTable )
print(EnumTable.ET1)
print(EnumTable.ET2)

1
2

EnumTable = CreatEnumTable(EnumTable, 10)

### Feedback

function enum(t)
local enumtable = {}
local enumindex = 0
local tmp,key,val
for _,v in ipairs(t) do
key,val = string.gmatch(v,"([%w_]+)[%s%c]*=[%s%c]*([%w%p%s]+)%c*")()
if key then
tmp = "return " .. string.gsub(val,"([%w_]+)",function (x) return enumtable[x] and enumtable[x] or (type(_G[x]) == "numbers" and _G[x] or x) end)
else
key = string.gsub(v,"([%w_]+)","%1");
end
enumtable[key] = enumindex
enumindex = enumindex + 1
end
return enumtable
end
---------------------------------------------------------------------------------------------------

MyGlobalNumber = 10
MyEnum = enum{
"a=1"
"b"
"c=MyGlobalNumber"
"d"
"e=100"
"f"
"g=2^3"
"h"
"i=math.floor(100.001)+MyGlobalNumber*10-100/5"
"j"
}

tmp = "return " .. string.gsub(val,"([%w_]+)",function (x) return enumtable[x] and enumtable[x] or (type(_G[x]) == "numbers" and _G[x] or x) end)

tmp = "return " .. string.gsub(val,"([%w_]+)",function (x) return enumtable[x] and enumtable[x] or x end)

 只有注册用户登录后才能发表评论。 【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库 相关文章: