1.不定參數
例e07.lua
-- Functions can take a
-- variable number of
-- arguments.
function funky_print (...)
for i=1, arg.n do
print("FuNkY: " .. arg[i])
end
end
funky_print("one", "two")
運行結果
FuNkY: one
FuNkY: two
程序說明
* 如果以...為參數, 則表示參數的數量不定.
* 參數將會自動存儲到一個叫arg的table中.
* arg.n中存放參數的個數. arg[]加下標就可以遍歷所有的參數.
2.以table做為參數
例e08.lua
-- Functions with table
-- parameters
function print_contents(t)
for k,v in t do
print(k .. "=" .. v)
end
end
print_contents{x=10, y=20}
運行結果
x=10
y=20
程序說明
* print_contents{x=10, y=20}這句參數沒加圓括號, 因為以單個table為參數的時候, 不需要加圓括號
* for k,v in t do 這個語句是對table中的所有值遍歷, k中存放名稱, v中存放值
3.把Lua變成類似XML的數據描述語言
例e09.lua
function contact(t)
-- add the contact ‘t’, which is
-- stored as a table, to a database
end
contact {
name = "Game Developer",
email = "hack@ogdev.net",
url = "http://www.ogdev.net",
quote = [[
There are
10 types of people
who can understand binary.]]
}
contact {
-- some other contact
}
程序說明
* 把function和table結合, 可以使Lua成為一種類似XML的數據描述語言
* e09中contact{...}, 是一種函數的調用方法, 不要弄混了
* [[...]]是表示多行字符串的方法
* 當使用C API時此種方式的優勢更明顯, 其中contact{..}部分可以另外存成一配置文件
4.試試看
想想看哪些地方可以用到例e09中提到的配置方法呢?
文章來源于領測軟件測試網 http://www.kjueaiud.com/