1. 函数的使用
以下程序演示了如何在Lua中使用函数, 及局部变量
例e02.lua
-- functions
function pythagorean(a, b)
local c2 = a^2 + b^2
return sqrt(c2)
end
print(pythagorean(3,4))
运行结果
5
程序说明
在Lua中函数的定义格式为:
function 函数名(参数)
...
end
与Pascal语言不同, end不需要与begin配对, 只需要在函数结束后打个end就可以了.
本例函数的作用是已知直角三角形直角边, 求斜边长度. 参数a,b分别表示直角边长,
在函数内定义了local形变量用于存储斜边的平方. 与C语言相同, 定义在函数内的代
码不会被直接执行, 只有主程序调用时才会被执行.
local表示定义一个局部变量, 如果不加local刚表示c2为一个全局变量, local的作用域
是在最里层的end和其配对的关键字之间, 如if ... end, while ... end等。全局变量的
作用域是整个程序。
2. 循环语句
例e03.lua
-- Loops
for i=1,5 do
print("i is now " .. i)
end
运行结果
i is now 1
i is now 2
i is now 3
i is now 4
i is now 5
程序说明
这里偶们用到了for语句
for 变量 = 参数1, 参数2, 参数3 do
循环体
end
变量将以参数3为步长, 由参数1变化到参数2
例如:
for i=1,f(x) do print(i) end
for i=10,1,-1 do print(i) end
这里print("i is now " .. i)中,偶们用到了..,这是用来连接两个字符串的,
偶在(1)的试试看中提到的,不知道你们答对了没有。
虽然这里i是一个整型量,Lua在处理的时候会自动转成字符串型,不需偶们费心。
3. 条件分支语句
例e04.lua
-- Loops and conditionals
for i=1,5 do
print(“i is now “ .. i)
if i < 2 then
print(“small”)
elseif i < 4 then
print(“medium”)
else
print(“big”)
end
end
运行结果
i is now 1
small
i is now 2
medium
i is now 3
medium
i is now 4
big
i is now 5
big
程序说明
if else用法比较简单, 类似于C语言, 不过此处需要注意的是整个if只需要一个end,
哪怕用了多个elseif, 也是一个end.
例如
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
Lua对Table占用内存的处理是自动的, 如下面这段代码
a = {}
a["x"] = 10
b = a -- `b' refers to the same table as `a'
print(b["x"]) --> 10
b["x"] = 20
print(a["x"]) --> 20
a = nil -- now only `b' still refers to the table
b = nil -- now there are no references left to the table
b和a都指向相同的table, 只占用一块内存, 当执行到a = nil时, b仍然指向table,
而当执行到b=nil时, 因为没有指向table的变量了, 所以Lua会自动释放table所占内存
1.不定参数
例e07.lua
-- Functions can take a
-- variable number of
-- arguments.
function funky_print (...)
for i=1, arg.n do
print("FuNkY: " .. arg)
end
end
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.]]
}