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

  .不定参数

  例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中提到的配置方法呢?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值