github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/lua/for.lua (about)

     1  local function countsteps(start, stop, step)
     2      local n = 0
     3      if step then
     4          for i = start, stop, step do
     5              n = n + 1
     6          end
     7      else
     8          for i = start, stop do
     9              n = n + 1
    10          end
    11      end
    12      return n
    13  end
    14  
    15  print(countsteps(1, 3))
    16  --> =3
    17  
    18  print(countsteps(math.maxinteger - 1, 1e100))
    19  --> =2
    20  
    21  print(countsteps(1, -10))
    22  --> =0
    23  
    24  print(countsteps(math.mininteger, math.mininteger + 1))
    25  --> =2
    26  
    27  print(countsteps(math.mininteger + 2, -1e100, -1))
    28  --> =3
    29  
    30  print(countsteps(1.0, 6, 2))
    31  --> =3
    32  
    33  for i = 1, 2, 1.1 do
    34      print(math.type(i))
    35  end
    36  --> =float
    37  
    38  print(pcall(function() for i = 1, 1, 0 do end end))
    39  --> ~false\t.*'for' step is zero
    40  
    41  -- Errors
    42  do
    43      local function err(init)
    44          local f = load('for i = ' .. init .. ' do end')
    45          ok, msg = pcall(f)
    46          print(msg)
    47      end
    48  
    49      err[['a', 2, 3]]
    50      --> ~'for' initial value: expected number, got string
    51  
    52      err[[1, {}]]
    53      --> ~'for' limit: expected number, got table
    54  
    55      err[[1, 2, false]]
    56      --> ~'for' step: expected number, got boolean
    57  
    58      err[[1, 2, 0]]
    59      --> ~'for' step is zero
    60  end