Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How do I create a custom Enum?

Asked by 8 years ago

Let's say I have property that I only want to have a variable number of states. For example, let's take an elemental attribute. We've got Fire, Grass, Water, Earth, and Wind.

Would I create a separate object for this purpose which retains a value and reference table?

local Type = {}
function Type.new(input) --input is a number or string in this case.
    local o = {}
    local o.Value = 0;
    local typeChart = {"Fire", "Grass", "Water", "Earth", "Wind"}

    if input:IsA("Number") then --Don't know exactly how to determine Data Types. If you can fill me in on this, please do.
        o.Value = input;
    else
        for i, v in pairs(typeChart)
            if input == v then
                o.Value = i;
                break
            end 
        end
    end

    function o:getString() -- Returns the String associated with o.Value in the typeChart
    function o:equals(type) -- Returns true or false when comparing two Type objects

    return o;
end

Or is there a simpler way of doing this?

1 answer

Log in to vote
2
Answered by 8 years ago

How about a custom enum table where we magically define everything as both itself, its place value and its key.

function newEnum(t)
local et = {go,home};
local i = 1;
for k,v in next, t do
et[k] = v;
et[v] = v;
et[i] = v;
i = i+1;
end;
return et;
end

As an example:

local StatusEffects = newEnum {
 Fire = function(s,i)
    s:TakeDamage(i*3);
 end;
 Ice = function(s,i)
    s.WalkSpeed = 16/i;
 end;
};

print(StatusEffects.Ice) --> Ice;
print(StatusEffects[2]) --> Ice;
print(StatusEffects[StatusEffects[Ice]]) --> Ice.
0
I'm sorry I never really learned this, but what does "next" do? randomsmileyface 375 — 8y
0
Goes to the next [key]=value pair in a table. PlsNoDiscrimination 0 — 8y
Ad

Answer this question