News for hackers. Stuff that matters.
Re:Lua, a Misunderstood Language by bilkow on Friday January 15, 2021 @06:33PM (#25798093)
You clearly have a different experience using 1-based index than me, it has caused me many off-by-one mistakes. Also, I almost never need to -1 with 0-based index, but in 1-based index its pretty common, specially if moving slices inside an array, the new index of the element is move_position + old_index - 1 (see example). Also see arguments by Djikstra [0].

Example:

  # python
  lov = ['l', 'o', 'v']
  o_index = 1;
  array = ['a', 'b', 'c', 'd', 'e', 'f']
  move_position = 3
  # elements moved here
  array = ['a', 'b', 'c', 'l', 'o', 'v']
  new_o_index = move_position + o_index
  print(array[new_o_index]) # prints 'o'

  -- lua
  local lov = { 'l', 'o', 'v' }
  local o_index = 2;
  local array = { 'a', 'b', 'c', 'd', 'e', 'f' }
  local move_position = 4
  -- elements moved here
  array = { 'a', 'b', 'c', 'l', 'o', 'v' }
  local new_o_index = move_position + o_index - 1
  print(array[new_o_index]) -- prints 'o'
Note that I'm not saying 0-based indexing is always absolutely better, but I generally prefer it and believe it usually makes more sense even outside of programming (including math), we're just not taught that way.

[0] https://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF transcript: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/E...

There are no comments on this comment yet.