If Statement Organization + Tables

So I am working on an Anime RPG, my game features “classes” with their own move set of abilities.

Basically sometimes I have to check what player has what class and run something then etc… I want to know if I am able to use tables to make this process cleaner or any other method?? and obviously I create new classes very often so I don’t wanna have to dig back to through a bunch of code to copy and paste one more if statement. Here’s a basic idea of what I can do (not what I want to do lol)

if class == "magic" then
	if action == true then
		-- do stuff
	end
elseif class == "rat" then
	if action == true then
		-- do another stuff
	end
elseif class == "bruh" then
	if action == true then
		-- do more stuff
	end
end

If I can interpret your answer correctly, are you trying to achieve this? (C example)

switch (class) {
	case "magic":
		if (action) {
			// Do stuff
		};
		break;
	case "rat":
		if (action) {
			// Do another stuff
		};
		break;
	case "bruh"
		if (action) {
			// Do more stuff
		};
		break;
};

Something like this is the closest I can think of in Lua:

local class_functions =
{
	magic = function(action)
		if action then
			-- Do stuff
		end;
	end,
	rat = function(action)
		if action then
			-- Do another stuff
		end;
	end,
	bruh = function(action)
		if action then
			-- Do more stuff
		end;
	end,
};
--
class_functions[class](action);
1 Like

I tend to use a dictionary if I want to lower the amount of if statements I use. The benefit is you can create a single place to add an update and it should perform exactly the same without so many checks.

--Create a dictionary to search for what you what when you want it
--There's room for improvement, but it'll get the job done
local dictionary = {
	["magic"] = {
		["attackStat"] = 20
	};
	["rat"] = {
		["attackStat"] = 5
		
	};
	["bruh"] = {
		["attackStat"] = 9001
	}
}
--For simplicity I just set class and action here
local class = "rat"
local action = true

--I'm assuming this will be in an event so I made it flexible
if dictionary[class] then
	if action then
		local doSomethingWithStats = dictionary[class].attackStat * 100
		print(doSomethingWithStats)
	end
end

I added tables within the table with a non-changing index to show you how to access it.

I kinda like that, you basically created a low-key module. If you added this inside class_functions:

checkIt = function(class, action)
	if action then
		class_functions[class]()
	end
end

And changed the last line to the following, you could remove even more if statements.

class_functions.checkIt(class, action)

I like your answer better since it’s more flexible with what you can do.