How would i use tables as switch statements?

i never understood how they work. please give me examples and explain them to me like i’m 5.
i’m trying to avoid elseif chains/yandere dev syndrome.

Do you mind clarifying what you mean?

like using tables instead of doing an elseif chain

There is a Post about it:

Ima look tho

i looked at those and didn’t understand. that’s exactly why is said “explain them to me like i’m 5”

Look at this:

Basically, just make a dictionary with the keys being the condition that needs to be met, and the value being whatever you need exactly.

You just have a table, the key is what the condition should be and the value is what happens or a returned value or wherever you needed

if var == 1 then
	print("a")
elseif var == 2 then
	print("b")
	--and repeat for a lot of numbers
end
local t = {
	1 = "a",
	2 = "b", 
	--and repeat for others
} 

for i, v in pairs(t) do
	if var == i then
		print(v) 
	end
end

So this isn’t how it should be u can just do print(t[var]) but I’m giving you a simple example.

1 Like

the problem is i’m managing randomized maps. i have maps in a table and i am using math.random and i don’t wanna use an elseif chain

local maps = {
    map1 = path.to.map;
}

local chosenMap = maps[math.random(1,#maps)]

Then you can add more maps by adding more of those in the table.

2 Likes

i’m not that big of an idiot right? i really hope this works
jesus christ

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.