Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I create a custom Enum?

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

✓ Accepted answer

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.

2 comments

0

I'm sorry I never really learned this, but what does "next" do?

0

Goes to the next [key]=value pair in a table.

This discussion is preserved as it was. New answers, comments, and votes are closed.