Advertisement
Rochet2

Different ways to iterate array n element at a time

Apr 22nd, 2022
1,514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.16 KB | None | 0 0
  1. local sham_heal = { 586,4,593,4,583,2,587,2,582,0,581,2,588,2,594,4,1648,2,591,0,592,4,590,0,2084,0,2060,1,1697,1,1696,2,2061,2,1698,0,2059,1,2063,4,2064,0,614,4,613,4,607,2 }
  2.  
  3. ```lua
  4. for i = 1, #sham_heal, 2 do
  5.   print(sham_heal[i], sham_heal[i+1])
  6. end
  7. ```
  8. ```lua
  9. function apply(func, arg_table, num_args)
  10.   local unpack = unpack or table.unpack
  11.   for i = 1, #arg_table, num_args do
  12.     func(unpack(arg_table, i, i+num_args-1))
  13.   end
  14. end
  15.  
  16. apply(print, sham_heal, 2)
  17. ```
  18. ```lua
  19. function table_split(table_to_split, elements)
  20.   local unpack = unpack or table.unpack
  21.   local t = {}
  22.   for i = 1, #table_to_split, elements do
  23.     t[#t+1] = {unpack(table_to_split, i, i+elements-1)}
  24.   end
  25.   return t
  26. end
  27.  
  28. for _, v in ipairs(table_split(sham_heal, 2)) do
  29.      print(v[1], v[2])
  30. end
  31. ```
  32. ```lua
  33. function iterate_in_chunks(table_to_iterate, elements)
  34.   local unpack = unpack or table.unpack
  35.   local next_index = 1
  36.   local function f()
  37.     local index = next_index
  38.     next_index = next_index+elements
  39.     return unpack(table_to_iterate, index, next_index-1)
  40.   end
  41.   return f
  42. end
  43.  
  44. for a,b in iterate_in_chunks(sham_heal, 2) do
  45.     print(a,b)
  46. end
  47. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement