Advertisement
Inksaver

Lua iterator example

Apr 20th, 2020
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.57 KB | None | 0 0
  1. function values(v) -- general diy iterator
  2.     local i = 0
  3.     return function()
  4.         i = i + 1
  5.         return v[i]
  6.     end
  7. end
  8.  
  9. function printColours()
  10.     local colours = {"red","blue","green"} --lua table acting as a list
  11.     for colour in values(colours) do -- call the iterator function
  12.         print(colour)
  13.     end
  14. end
  15.  
  16. function printCommands()
  17.     local go = "U3 L6 R5 F15 B3 D2"
  18.     print("Original go:"..go)
  19.    
  20.     go = string.gsub(go, " ", "") -- remove all spaces and substitute with empty string ""
  21.     print("Stripped go:"..go)
  22.    
  23.     local commandList = {}
  24.     local command = ""
  25.     -- make a list of commands from go string eg "U3L6R5F15B3D2" = {"U3", "L6", "R5", "F15", "B3", "D2"}
  26.     for i = 1, string.len(go) do
  27.         local character = string.sub(go, i, i) -- examine each character in the string
  28.         if tonumber(character) == nil then -- char is NOT a number
  29.             if command ~= "" then -- command is NOT empty eg "x0"
  30.                 table.insert(commandList, command) -- add to table eg "x0"
  31.             end
  32.             command = character -- replace command with new character eg "F"
  33.         else -- char IS a number
  34.             command = command..character -- add eg 1 to F = F1, 5 to F1 = F15
  35.             if i == string.len(go) then -- last character in the string
  36.                 table.insert(commandList, command)
  37.             end
  38.         end
  39.     end
  40.    
  41.     for command in values(commandList) do -- call the iterator function
  42.         print(command)
  43.     end
  44. end
  45.  
  46. function main()
  47. --[[
  48.     Python:
  49.     colours = ["red", "blue", "green"]
  50.     for colour in colours:
  51.         print(colour)
  52. ]]
  53.    
  54.     --lua has to have a generic iterator to do the same thing:
  55.    
  56.     printColours()
  57.    
  58.     printCommands()
  59.    
  60. end
  61.  
  62. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement