|
程序设计 | 游戏开发 | 3296 次查看 |
|---|---|---|
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中提到的配置方法呢? |
||