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

开发 前端
想想看哪些地方可以用到例e09中提到的配置方法呢?

1.不定参数

例e07.lua

  1. -- Functions can take a 
  2. -- variable number of 
  3. -- arguments. 
  4. function funky_print (...)   
  5. for i=1, arg.n do   
  6. print("FuNkY: " .. arg[i])   
  7. end   end   
  8. funky_print("one", "two") 

运行结果

FuNkY: one

FuNkY: two

程序说明

* 如果以...为参数, 则表示参数的数量不定.

* 参数将会自动存储到一个叫arg的table中.

* arg.n中存放参数的个数. arg[]加下标就可以遍历所有的参数.

2.以table做为参数

例e08.lua

  1. -- Functions with table 
  2.   -- parameters 
  3.   function print_contents(t) 
  4.   for k,v in t do 
  5.   print(k .. "=" .. v) 
  6.   end 
  7.   end 
  8.   print_contents{x=10y=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

  1. function contact(t)   
  2. -- add the contact ‘t’, which is   
  3. -- stored as a table, to a database   
  4. end   
  5. contact {   name = "Game Developer",   
  6. email = "hack@ogdev.net",   
  7. url = "http://www.ogdev.net",   
  8. quote = [[   There are   
  9. 10 types of people   
  10. who can understand binary.]]   
  11. }   contact {   -- some other contact   } 

程序说明

* 把function和table结合, 可以使Lua成为一种类似XML的数据描述语言

* e09中contact{...}, 是一种函数的调用方法, 不要弄混了

* [[...]]是表示多行字符串的方法

* 当使用C API时此种方式的优势更明显, 其中contact{..}部分可以另外存成一配置文件

4.试试看

想想看哪些地方可以用到例e09中提到的配置方法呢?

原文链接:http://tech.it168.com/j/2008-02-14/200802141347503.shtml

责任编辑:陈四芳 来源: 来自ITPUB论坛
相关推荐

2013-12-13 16:53:00

Lua脚本语言C++

2013-12-13 15:48:52

Lua脚本语言

2013-12-13 15:42:32

Lua脚本语言

2013-12-12 17:30:03

Lua例子

2013-12-13 16:46:18

Lua脚本语言

2011-08-22 17:25:31

LuaC++函数

2011-08-29 15:58:51

Lua函数

2021-01-12 06:42:50

Lua脚本语言编程语言

2011-06-22 14:07:42

Lua

2011-08-23 16:59:16

C++LUA脚本LUA API

2011-08-22 17:13:00

LuaC++函数

2011-08-23 16:22:45

Lua 4.0函数

2011-08-25 16:47:53

LuaC++ 证书

2011-08-23 11:13:56

Lua

2011-08-23 16:14:27

Lua函数库函数

2011-08-23 16:48:41

Lua 5.1API 函数

2011-08-29 15:45:59

Lua函数

2023-07-26 06:43:07

函数调用

2022-10-14 06:45:25

grepLinux

2011-08-23 18:00:00

lua 脚本测试C
点赞
收藏

51CTO技术栈公众号