通過例子學(xué)習(xí)Lua(4)—函數(shù)的調(diào)用
1.不定參數(shù)
例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")
運行結(jié)果
FuNkY: one
FuNkY: two
程序說明
* 如果以...為參數(shù), 則表示參數(shù)的數(shù)量不定.
* 參數(shù)將會自動存儲到一個叫arg的table中.
* arg.n中存放參數(shù)的個數(shù). arg[]加下標(biāo)就可以遍歷所有的參數(shù).
2.以table做為參數(shù)
例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}
運行結(jié)果
x=10
y=20
程序說明
* print_contents{x=10, y=20}這句參數(shù)沒加圓括號, 因為以單個table為參數(shù)的時候, 不需要加圓括號
* for k,v in t do 這個語句是對table中的所有值遍歷, k中存放名稱, v中存放值
3.把Lua變成類似XML的數(shù)據(jù)描述語言
例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結(jié)合, 可以使Lua成為一種類似XML的數(shù)據(jù)描述語言
* e09中contact{...}, 是一種函數(shù)的調(diào)用方法, 不要弄混了
* [[...]]是表示多行字符串的方法
* 當(dāng)使用C API時此種方式的優(yōu)勢更明顯, 其中contact{..}部分可以另外存成一配置文件
4.試試看
想想看哪些地方可以用到例e09中提到的配置方法呢?
原文鏈接:http://tech.it168.com/j/2008-02-14/200802141347503.shtml