ITPub博客

首页 > IT职业 > IT生活 > 通过例子学习Lua(4)--函数的调用(转)

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

原创 IT生活 作者:post0 时间:2007-08-12 19:36:52 0 删除 编辑
通过例子学习Lua(4)--函数的调用(转)[@more@]

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

  

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8225414/viewspace-951603/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    2018
  • 访问量
    8225980