Enumerations

Thalassicus

Bytes and Nibblers
Joined
Nov 9, 2005
Messages
11,057
Location
Texas
I'm having difficulty finding the proper keywords/syntax to create and use enumerations in Lua. In particular, how do I do these two things:

  • Make LevelType immutable.
  • Make :setOutputLevel and :print require a LevelType for the first parameter.

PHP:
LevelType = {
DEBUG,
INFO,
WARN,
ERROR
}

LoggerType = { logLevel = DEBUG };
 
function LoggerType:new(o)
    o = o or {};
    setmetatable(o, self);
    self.__index = self;
    return o;
end
 
function LoggerType:setOutputLevel(level)
    self.logLevel = level;
end

function LoggerType:print(level, text)
    if level >= self.logLevel then
        print(text);
    end
end

-- usage example
-- myLogger = LoggerType:new();
-- myLogger:setOutputLevel(DEBUG);
-- myLogger:print(ERROR,"Error message");
 
http://lua-users.org/wiki/ImmutableObjects

but as long as you dont modify LevelType then it shouldnt be a problem? i like the all caps style for those kinds of variables

checking the arguments being passed you could do this

Code:
LevelType = {
DEBUG = 1,
INFO = 2,
WARN = 3,
ERROR = 4
}

not sure how to get a numeric position from a table element, but in that fashion you have a numeric value to each level, but when calling them they have to be as strings

Code:
a = DEBUG;
LevelType[ a ] == nil -- bad

b = "DEBUG";
LevelType[ b ] == 1 -- good
 
Back
Top Bottom