Guest User

Lua when

a guest
Sep 20th, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.41 KB | None | 0 0
  1. -- less difficult than nil
  2. null = {}
  3. -- see haskell
  4. error_thunk = {}
  5.  
  6. --[[
  7. pattern matches with optional
  8. else fallback. if no else is
  9. given and nothing matches, it
  10. crashes.
  11.  
  12. Don't pass nil, except for the
  13. subject. Use null instead
  14. everywhere else, or it doesn't
  15. work correctly.
  16.  
  17. When nesting whens, use "_when"
  18. for all nested whens and only
  19. "when" for the outer one.
  20. ]]
  21. function when(s, ...)
  22.  local result = _when(s,...)
  23.  if(result == error_thunk) then
  24.    -- no match (not exhaustive)
  25.   print("when did not match " ..
  26.     tostring(subject),0,0,8)
  27.   print("result: " ..
  28.    tostring(result))
  29.   print("m:" ..
  30.    tostring(matches))
  31.   for i, v in ipairs(matches) do
  32.     print(tostring(v[1]) ..
  33.     " -> " .. tostring(v[2]))
  34.   end
  35.   local now = t()
  36.   local crashtime = now + 4
  37. --while(t() < crashtime )do end
  38.   error("when not exhaustive!")
  39.  elseif(result == null) then
  40.   return nil
  41.  end
  42.  return result
  43. end
  44.  
  45. --[[
  46. Use this for nested whens.
  47. ]]
  48. function _when(s, ...)
  49.  local subject = s
  50.  if subject == nil then
  51.   subject = null
  52.  end
  53.  
  54.  local matches =
  55.   partition({...},2)
  56.  
  57.  local result = nil
  58.  for _,cond in ipairs(matches)do
  59.   if #cond == 1 and
  60.    result == nil then
  61.    result = cond[1]
  62.   elseif subject == cond[1] and
  63.    result == nil then
  64.    result = cond[2]
  65.   end
  66.  end
  67.  
  68.  -- match found!
  69.  if result != nil then
  70.   return result
  71.  end
  72.  
  73.  -- no match
  74.  return error_thunk
  75. end
Advertisement
Add Comment
Please, Sign In to add comment