使用流程
1. 函數的使用
以下程序演示了如何在Lua中使用函數, 及局部變量
例e02.lua
-- functions
function pythagorean(a, b)
local c2 = a^2 + b^2
return sqrt(c2)
end
print(pythagorean(3,4))
運行結果
5
程序說明
在Lua中函數的定義格式為:
function 函數名(參數)
...
end
與Pascal語言不同, end不需要與begin配對, 只需要在函數結束后打個end就可以了.
本例函數的作用是已知直角三角形直角邊, 求斜邊長度. 參數a,b分別表示直角邊長,
在函數內定義了local形變量用于存儲斜邊的平方. 與C語言相同, 定義在函數內的代
碼不會被直接執行, 只有主程序調用時才會被執行.
local表示定義一個局部變量, 如果不加local剛表示c2為一個全局變量, local的作用域
是在最里層的end和其配對的關鍵字之間, 如if ... end, while ... end等。全局變量的
作用域是整個程序。
2. 循環語句
例e03.lua
-- Loops
for i=1,5 do
print("i is now " .. i)
end
運行結果
i is now 1
i is now 2
i is now 3
i is now 4
i is now 5
程序說明
這里偶們用到了for語句
for 變量 = 參數1, 參數2, 參數3 do
循環體
end
變量將以參數3為步長, 由參數1變化到參數2
例如:
for i=1,f(x) do print(i) end
for i=10,1,-1 do print(i) end
這里print("i is now " .. i)中,偶們用到了..,這是用來連接兩個字符串的,
偶在(1)的試試看中提到的,不知道你們答對了沒有。
雖然這里i是一個整型量,Lua在處理的時候會自動轉成字符串型,不需偶們費心。
3. 條件分支語句
例e04.lua
-- Loops and conditionals
for i=1,5 do
print(“i is now “ .. i)
if i < 2 then
print(“small”)
elseif i < 4 then
print(“medium”)
else
print(“big”)
end
end
運行結果
i is now 1
small
i is now 2
medium
i is now 3
medium
i is now 4
big
i is now 5
big
程序說明
if else用法比較簡單, 類似于C語言, 不過此處需要注意的是整個if只需要一個end,
哪怕用了多個elseif, 也是一個end.
例如
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
4.試試看
Lua中除了for循環以外, 還支持多種循環, 請用while...do和repeat...until改寫本文中的for程序 <script type=text/javascript> bbscode('postcontent1');
數組的使用
1.簡介
Lua語言只有一種基本數據結構, 那就是table, 所有其他數據結構如數組啦,
類啦, 都可以由table實現.
2.table的下標
例e05.lua
-- Arrays
myData = {}
myData[0] = “foo”
myData[1] = 42
-- Hash tables
myData[“bar”] = “baz”
-- Iterate through the
-- structure
for key, value in myData do
print(key .. “=“ .. value)
end
輸出結果
0=foo
1=42
bar=baz
程序說明
首先定義了一個table myData={}, 然后用數字作為下標賦了兩個值給它. 這種
定義方法類似于C中的數組, 但與數組不同的是, 每個數組元素不需要為相同類型,
就像本例中一個為整型, 一個為字符串.
程序第二部分, 以字符串做為下標, 又向table內增加了一個元素. 這種table非常
像STL里面的map. table下標可以為Lua所支持的任意基本類型, 除了nil值以外.
Lua對Table占用內存的處理是自動的, 如下面這段代碼
a = {}
a["x"] = 10
b = a -- `b' refers to the same table as `a'
print(b["x"]) --> 10
b["x"] = 20
print(a["x"]) --> 20
a = nil -- now only `b' still refers to the table
b = nil -- now there are no references left to the table
b和a都指向相同的table, 只占用一塊內存, 當執行到a = nil時, b仍然指向table,
而當執行到b=nil時, 因為沒有指向table的變量了, 所以Lua會自動釋放table所占內存
3.Table的嵌套
Table的使用還可以嵌套,如下例
例e06.lua
-- Table ‘constructor’
myPolygon = {
color=“blue”,
thickness=2,
npoints=4;
{x=0, y=0},
{x=-10, y=0},
{x=-5, y=4},
{x=0, y=4}
}
-- Print the color
print(myPolygon[“color”])
-- Print it again using dot
-- notation
print(myPolygon.color)
-- The points are accessible
-- in myPolygon[1] to myPolygon[4]
-- Print the second point’s x
-- coordinate
print(myPolygon[2].x)
程序說明
首先建立一個table, 與上一例不同的是,在table的constructor里面有{x=0,y=0},
這是什么意思呢? 這其實就是一個小table, 定義在了大table之內, 小table的
table名省略了.
最后一行myPolygon[2].x,就是大table里面小table的訪問方式. <script type=text/javascript> bbscode('postcontent2');
文章來源于領測軟件測試網 http://www.kjueaiud.com/