通过例子学习Lua(4)--函数的调用

王朝other·作者佚名  2008-05-19
窄屏简体版  字體: |||超大  

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中提到的配置方法呢?

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航