Why do Lua arrays(tables) start at 1 instead of 0?

后端 未结 8 2095
情歌与酒
情歌与酒 2020-12-12 18:34

I don\'t understand the rationale behind the decision of this part of Lua. Why does indexing start at 1? I have read (as many others did) this great paper. It seems to me a

相关标签:
8条回答
  • 2020-12-12 19:13

    Perhaps a less significant point, but one I haven't heard mentioned yet: there is better symmetry in the fact that the first and last characters in a string are at 1 and -1 respectively, instead of 0 and -1.

    0 讨论(0)
  • 2020-12-12 19:21

    Lua libraries prefer to use indices which start at 1. However, you can use any index you want. You can use 0, you can use 1, you can use -5. It is even in their manual, which can be found at (https://www.lua.org/pil/11.1.html).

    In fact, something cool here is internal lua libraries will treat SOME passed 0's as 1's. Just be cautious when using ipairs.
    So that: ("abc"):sub(0,1) == "a" and ("abc"):sub(1,1) == "a" will be true.

     You can start an array at index 0, 1, or any other value:
    
    -- creates an array with indices from -5 to 5
    a = {}
    for i=-5, 5 do
      a[i] = 0
    end
    
    0 讨论(0)
提交回复
热议问题