lua函数

print("test fun1")
function fun1()
  return 1,2
end

a,b = fun1()
print(a,b)

function fun2(t)
  for i in ipairs(t) do
  print(t[i])
  end
end

f = string.find
a = {"hello", "ll"}

print("test fun2")
print(fun2(a))

print("test function unpack")
print(f(unpack(a)))

function fun3(a,b,...)
  for i,v in ipairs(arg) do
    print(v)
  end
end

print("test function variable parameter")
print(fun3(1,2,3,4,5,6,7))



test fun1
1	2
test fun2
hello
ll

test function unpack
3	4
test function variable parameter
3
4
5
6
7



--string.format
str = string.format("A:%d%s",1,"a")
print(str)

a = {p=print}
a.p("abc")
print("def")

--table sort
function printTable(t)
  for e in pairs(t) do
    print(t[e].name..":"..t[e].age)
  end
end

people = {{name="zhangsan",age="26"},
  {name="lisi",age="25"},
  {name="wangwu",age="21"}}

function f(p1,p2)
  return p1.age<p2.age
end

print("before sort:")
printTable(people)
table.sort(people,f)
print("after sort:")
printTable(people)

function f1()
  local i = 0
  return function()--anonymous function
    i = i+1
    return i
  end
end

ff1 = f1()
print(ff1())
print(ff1())

--Lua 编译时遇到 fact(n-1)并不知道他是局部函数 fact
local fact --loop need
fact = function (n)
  if n == 0 then
    return 1
  else
    return n*fact(n-1)
  end
end

print(fact(4))


A:1a
abc
def
before sort:
zhangsan:26
lisi:25
wangwu:21
after sort:
wangwu:21
lisi:25
zhangsan:26
1
2
24

你可能感兴趣的:(lua)