笔记: Lua基础: 函数 控制流

来源:互联网 发布:开淘宝店快递怎么合作 编辑:程序博客网 时间:2024/05/04 03:31

作者: apex.Cliz

函数的声明

用以下的语句来产生一个函数:

function hello()
  print("Hello Azeroth!")
end

如果需要参数, 可以在函数名后的括号中加入参数列表.

function hello(name)
  print("Hello " .. name)
end

特别的, Lua支持不确定个数的参数列表:
(参考: Paul Schuytema和Mark Manyen的Game Development with LUA)

function listout(...)
  if arg.n > 0 then
    for indx = 1, arg.n do
      local temp = string.format("%s%d", "Argument ", indx, ":")
      print(temp, arg[indx])
    end
  else
    print("No arguments.")
  end
end


附注: =运算符比较的, 是两个函数是否指向实际的同一个函数, 而非两函数的内容是否相等

> hello = function() print("Hello Azeroth!") end
> hello2 = hello
> print(hello2 == hello)
true
> hello2 = function() print("Hello Azeroth!") end
> print(hello2 == hello)
false


if语句

和一部分script language类似, 必须以end结尾.

if (num==7) then
  print("You found the magic number!")
end

如果需要串接else if, 应使用elseif语句, 并在最后用一个end结尾.

function greeting(name)
  if (type(name) == "string") then
    print("Hello " .. name)
  elseif (type(name) == "nil") then
    print("Hello friend")
  else
    error("Invalid name was entered")
  end
end


循环语句

for语句的通用格式如下:

for indx = start, end, (step) do
  -- statements
end

step在这里表示每次indx的增量, 默认为1.

与其他语言类似的repeat和while语句的格式如下:

repeat
  -- statements
until <boolean expression>

以及

while <boolean expression> do
  -- body
end

在循环中修改循环的条件变量, 不会影响循环的进行次数; 这是在进入循环语句前已经计算完毕的.

参考下面的语句:

for i=1, upper do
  upper = upper + 1
end

这个循环不会成为死循环.

Tag标签: Lua
原创粉丝点击