跳至內容

TI-Lua/流程控制

計算器百科,非營利的計算器專業知識百科。

流程控制

本節將討論 TI-Lua 中的流程控制,其中包括條件判斷、循環與無條件跳轉

條件判斷

形式

if-else 結構是基本的條件判斷流程。其結構如下:

if cond then
  -- executes when cond is true
else
  -- executes when cond is false
end

其中,cond 是一個布爾值。下同。

例子

輸入:

if 1 == 2 then
  print("Our math is broken!")
else
  print("Everything is fine.")
end

輸出:

Everything is fine.

註: TI-Lua 已經在 3.1 之後的版本中去除了 print 函數(這個函數在機上可向串口輸出數據,但是其實際功能是向標準輸出中輸出數據)。這裡僅作示意用途。

循環

形式

循環體分為 for 循環、 while 循環和 repeat-until 循環。我們首先來討論 while 循環。

while 循環

while 循環結構如下:

while cond do
  -- something
end

該循環會不斷執行,直到 cond 為假。

repeat-until 循環

repeat-until 循環結構如下:

repeat
  -- something
until cond

該循環會不斷執行,直到 cond 為真。

for 循環

for 循環具有兩種形式。第一種是」步進型「,第二種是」遍歷型「(即 foreach)。

for 循環結構如下:

-- 步进型
for v = v_begin, v_end, v_step do
  -- something
end

在此代碼中, v 是一個自變量, v_begin, v_end, v_step 分別代表 v 的初始值、終止值與步長。 這種循環會不斷執行,在執行過程中,v 的值會從 v_beginv_step 的步長增長到 v_end, 然後結束。如果按照步長,v 在最後一步時會超過 v_end, v 的值仍會保留而不會再將 v_end 的值賦給 v.

-- 遍历型
for v1, v2, ..., vn in a_list do
  -- something
end

在此代碼中, v1, v2, ..., vn 是有窮多個自變量。a_list 是一個列表或能夠產生列表的表達式。在循環過程中,(產生的)列表中的項中的元素會按順序賦給 v1, v2, ..., vn,直到每一個項按順序訪問過一遍。

需要注意到一個項中可以包含多個元素。這一點我們會在示例中說明。

例子

輸入:

local i, j, arr
i = 0
j = 0
arr = {"Calculator", "Wiki"}

-- while example
print("While example:")
while i < 5 do
  print(i)
  i = i+1
end

-- repeat example
print("Repeat example:")
repeat
  print(j)
  j = j+1
until j >= 5

-- numeric for example
print("Numeric for example:")
for i, 0, 10, 3 do
  print(i)
end

-- generic for example
print("Generic for example:")
for i, j in ipairs(arr) do
  print(i, j)
end

輸出:

While example:
0
1
2
3
4
Repeat example:
0
1
2
3
4
Numeric for example:
0
3
6
9
Generic for example
1       Calculator
2       Wiki

跳轉

由於 TI-Lua 是 Lua 5.1 的實現,而 goto 指令於 Lua 5.2 才添加,因此該小節可能不具有實際意義。