Codex NG
Recurrent Flamer
- Joined
- Jul 24, 2015
- Messages
- 2,994
- Solutions
- 12
- Reaction score
- 1,657
I should just have 1 thread for all my experimental code, but then how would you find anything heh
Anyone who has ever programmed in c,c++, php, java, javascript etc.. knows how powerful a switch statement can be and since lua doesn't seem to have one and we have to resort to countless if / else statements I thought it would be nice to create one.
So I created a mixed table with different types of indexes and values.
Then I created a function which would take 1 argument called switch just as it is seen in the languages mentioned above.
Then to test it I used a generic for loop with pairs()
And this is the results
Using this switch function should make decision making a lot easier
Anyone who has ever programmed in c,c++, php, java, javascript etc.. knows how powerful a switch statement can be and since lua doesn't seem to have one and we have to resort to countless if / else statements I thought it would be nice to create one.
So I created a mixed table with different types of indexes and values.
Code:
local case = {
['a'] = function() return 2 end,
['b'] = 2,
['c'] = {1,2,4},
name = "codex",
[10] = ' this is from index 10 ',
5 * 6,
[45] = 20 + 7,
{5, 23, 27},
["two words"] = 'hey you'
}
Then I created a function which would take 1 argument called switch just as it is seen in the languages mentioned above.
Code:
function switch(x)
if type(case[x]) == "function" then
return case[x]()
elseif type(case[x]) == "table" then
return unpack(case[x])
else
return case[x]
end
end
Then to test it I used a generic for loop with pairs()
Code:
for k, v in pairs(case) do
print("index "..k, switch(k) )
end
And this is the results
Code:
index 1 5 23 27
index 2 30
index a 2
index c 1 2 4
index b 2
index 45 27
index two words hey you
index 10 this is from index 10
index name codex
Using this switch function should make decision making a lot easier