Pull Request: Add Switch Statement Utility #43
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR introduces a new
lib.switchutility function for Lua that provides a flexible, readable alternative to longif/elseifchains. The implementation supports value-based matching, lists of possible values, predicate functions, and a"default"fallback, with optional JavaScript-style fallthrough behavior.Changes Made
lib.switch(valueOrList, fallthrough, cases, ...)API:compilestep with weak-key caching to minimize recomputation.number,string, etc.).{2,4,6}).function(v) return v < 0 end)."default"(fallback if no match found).fallthrough = true: executes multiple cases sequentially untilbreakFn()is called.fallthrough = false(default): executes only the first matching case.breakFn()can halt fallthrough early.Testing
{'foo','bar'}) resolve to the earliest matching case.{2,4,6}) trigger correctly."default"triggers when no matches exist.breakFn()stops fallthrough early.Performance Impact
Example Usages
Example 1 – Basic Value Match
Example 2 – Fallthrough with List of Values
Additional Notes
ox_lib.lib.switch(value, false, cases, ...)) in hot code paths."default"case should be placed last for clarity.EDIT: Updated to reflect recent changes. The first argument, if a table, is now treated as a list of values to match.
Arguments are no longer accepted inside that table and must always be passed as variadic parameters (4th, 5th, 6th…).