Lua 為什麼陣列下標從 1 開始?

時間 2021-06-01 14:17:12

1樓:Dionysos lai

留著,佔坑,待會兒回去講。

起始,原因並沒有像大家猜測的那樣。在官網lua-users wiki: Lua Faq和非非官網Lua Unofficial FAQ (uFAQ)都提到過這個問題。

這裡,貼一下其回答內容:

1.5.1 Why do Lua arrays count from one?

Oddly, the thing that really gets some people overexcited is that in Lua array indices count from one.

In mathematical notation array indices count from one, and so does Lua. In other words, they are not offsets.

The historical reason (see The Evolution of Lua) is that Lua evolved to solve engineering needs at the Brazillian state oil company (Petrobras). It was designed for engineers who were not professional programmers and more likely to be used to FORTRAN.

You can make your arrays start with zero, but the standard library functions (such as table.concat) will not recognise the zeroth entry. And # will return the size minus one.

t = -- table constructor is a little clunky

for i = 0,#t do print(i,t[i]) end -- not 0,#t-1 !

大概翻譯下,就是兩個原因,乙個是由於數學上的陣列是從1開始,因此lua也延續了這個特性:另乙個歷史原因是由於lua當時是為了巴西一家石油公司解決工程需要而開發的,使用的人都是一些傳統工程師,因此並不是那麼專業,跟像FORTRAN語言(其實,我根本不懂這個語言)。

2樓:

其實陣列(不是數學領域的陣列,可以看成放東西的格仔櫃)和數是不一樣的,從1開始確實直觀,1代表第乙個數,只不過程式語言編寫時想經可能向數學靠攏,所以造成了從0開始的情況。

凡是提出『』為什麼陣列不是從1開始的『』人,都理解的是陣列是放東西的地方,所以有1個算1個,有2個記2個

3樓:陳厚來

從1計數是反科學的。

如果個位數從1開始計數,為什麼十位,百位數要從0開始計數?

所以,最小的一位數是1, 最小的兩位數11, 最小的三位數是111?

4樓:

隨手貼個笑話...Should array indices start at 0 or 1? My compromise of 0.

5 was rejected without, I thought, proper consideration.

如何看待matlab陣列下標從1開始,for迴圈 ifelse 語句也和其他語言不同?

我先後學過大概10種語言吧。首先,for迴圈,if語句各個語言都不一樣,沒必要說MATLAB和其他語言不同。關於索引起始數。發現三大m語言 MATLAB,mathematica,maple 都是1開始的,R語言也是,Julia部分模仿MATLAB,也是1開始的,VBA最神奇,起始位置可以自己選擇。總...

為什麼C語言的陣列下標從0開始而不是從1開始?

In most programming language,the name of any array is a pointer,which is nothing but a reference to a memory location,and so the expression array n po...

C C 陣列的下標為何要從 0 開始,而不從 1 開始

MineCommander 先說個小常識,C C 中的陣列本質上都是指標。是的,你可以把陣列名當作乙個常量指標來使用,而這個指標指向的就是陣列開頭的元素。方括號 稱為索引運算子 就相當於返回從這個指標位址開始,往後找方括號內數字個的元素。比如乙個陣列int array 5 array 2 等價於 a...