Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- NOTE: This function does not currently work with tables however I plan on adding that in the near future.
- local function switch(val, ...)
- local allowedTypes = {
- "number",
- "string"
- }
- local allow = false
- for _, t in pairs(allowedTypes) do
- if typeof(val) == t then
- allow = true
- break
- end
- end
- if not allow then
- error("Invalid switch variable type")
- end
- ---
- local cases = {...}
- local default
- if type(cases[#cases]) == 'function' then
- default = cases[#cases]
- table.remove(cases, #cases)
- end
- local caseVals = {}
- for _, case in pairs(cases) do
- table.insert(caseVals, case[1])
- end
- for i1, v1 in pairs(caseVals) do
- for i2, v2 in pairs(caseVals) do
- if v1 == v2 and i1 ~= i2 then
- error("Duplicate case error: case #"..i2.." is a duplicate of case #"..i1)
- end
- end
- end
- for _, case in pairs(cases) do
- if val == case[1] then
- return case[2]()
- end
- end
- if default then
- return default()
- end
- end
- -- USAGE EXAMPLE:
- local nutrition
- local food = "Pizza"
- switch(food,
- {"Fruit",
- function()
- nutrition = 100
- end
- },
- {"Beef",
- function()
- nutrition = 75
- end
- },
- {"Pizza",
- function()
- nutrition = 40
- end
- },
- {"Candy",
- function()
- nutrition = 10
- end
- },
- {"Salad",
- function()
- nutrition = 95
- end
- },
- function()
- nutrition = 50
- end)
- print(food.." has a nutritional value of "..nutrition)
- --[[ Processing/Java code translation
- int nutrition;
- String food = "Pizza";
- switch(food) {
- case "Fruit":
- nutrition = 100;
- break;
- case "Beef":
- nutrition = 75;
- break;
- case "Pizza":
- nutrition = 40;
- break;
- case "Candy":
- nutrition = 10;
- break;
- case "Salad":
- nutrition = 95;
- break;
- default:
- nutrition = 50;
- break;
- }
- println(food + " has a nutritional value of " + nutrition);
- --]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement