It is currently April 19th, 2024, 10:39 pm

Lua and switch statements

Discuss the use of Lua in Script measures.
User avatar
smurfier
Moderator
Posts: 1931
Joined: January 29th, 2010, 1:43 am
Location: Willmar, MN

Lua and switch statements

Post by smurfier »

While Lua itself does not have support for Switch Statements there is a method to emulate them.

Without Switch Statements we need to result to long if/then/elseif statements which are sometimes inefficient and create redundancies.

Code: Select all

TestValue = 'Joe'

if string.lower(TestValue) == 'joe' then
	Result = 33
elseif string.lower(TestValue) == 'bob' then
	Result = 68
elseif string.lower(TestValue) == 'peter' then
	Result = 42
elseif string.lower(TestValue) == 'jane' then
	Result = 16
else
	Result = 0
end
A switch style statement can sometimes reduce the amount of code quite a bit.

Code: Select all

TestValue = 'Joe'

Switch = {
	joe = 33,
	bob = 68,
	peter = 42,
	jane = 16,
}

Result = Switch[string.lower(TestValue)] or 0
If we want to take an action instead of just returning a value, things start to look a bit different.

Code: Select all

TestValue = 'Joe'

Switch = {
	joe = function() return 33 end,
	bob = function() return 68 end,
	peter = function() return 42 end,
	jane = function() return 16 end,
}

local func = Switch[string.lower(TestValue)] or function() return 0 end

Result = func()
Since we have to test whether the value exists or not we use the func variable to store our function for one line.
GitHub | DeviantArt | Tumblr
This is the song that never ends. It just goes on and on my friends. Some people started singing it not knowing what it was, and they'll continue singing it forever just because . . .