r/lua • u/RedNifre • Sep 20 '25
Lua when expression
I added a little pattern matching "when" code to my #pico8 #lua code base. You have to use "null" (just an empty object) instead of "nil", because Lua cuts off varargs on the first nil and you have to use _when for nested whens, which are fake lazy, by returning a #haskell style error thunk instead of crashing on non-exhaustive matches. E.g. if you checked an ace, the first _when would error, because it only matches jokers, but the outer when wouldn't care, since it only looks at the ace branch, completely ignoring the error thunk.
30
Upvotes
View all comments
Show parent comment
1
u/RedNifre Sep 20 '25
Oh, that's interesting, so it works while it is in "..." form, but you run into issues if it's a table? Why does it work so bad for tables?
In my code, I also use partition, and #partition{1,nil,nil,4},2} is 1, so the nils also cause troubles there. Should I implement a vararg partition instead that I call like vararg_partition(2, ...), or is there an easier way?
Also, I use "error("problem")" to crash (because "error" does not exist), is there a better way to crash/halt a Lua program, maybe with a generated error message?
Here is my current implementation, it's my first Lua code:
https://pastebin.com/c29SaQhq