LUA脚本语言使用例程

来源:百度文库 编辑:神马文学网 时间:2024/04/27 18:01:22
使用例程
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
数组的使用
1.简介
Lua语言只有一种基本数据结构, 那就是table, 所有其他数据结构如数组啦,
类啦, 都可以由table实现.
2.table的下标
例e05.lua
-- Arrays
myData = {}
myData[0] = “foo”
myData[1] = 42
-- Hash tables
myData[“bar”] = “baz”
-- Iterate through the
-- structure
for key, value in myData do
print(key .. “=“ .. value)
end
输出结果
0=foo
1=42
bar=baz
程序说明
首先定义了一个table myData={}, 然后用数字作为下标赋了两个值给它. 这种
定义方法类似于C中的数组, 但与数组不同的是, 每个数组元素不需要为相同类型,
就像本例中一个为整型, 一个为字符串.
程序第二部分, 以字符串做为下标, 又向table内增加了一个元素. 这种table非常
像STL里面的map. table下标可以为Lua所支持的任意基本类型, 除了nil值以外.
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所占内存
3.Table的嵌套
Table的使用还可以嵌套,如下例
例e06.lua
-- Table ‘constructor’
myPolygon = {
color=“blue”,
thickness=2,
npoints=4;
{x=0, y=0},
{x=-10, y=0},
{x=-5, y=4},
{x=0, y=4}
}
-- Print the color
print(myPolygon[“color”])
-- Print it again using dot
-- notation
print(myPolygon.color)
-- The points are accessible
-- in myPolygon[1] to myPolygon[4]
-- Print the second point’s x
-- coordinate
print(myPolygon[2].x)
程序说明
首先建立一个table, 与上一例不同的是,在table的constructor里面有{x=0,y=0},
这是什么意思呢? 这其实就是一个小table, 定义在了大table之内, 小table的
table名省略了.
最后一行myPolygon[2].x,就是大table里面小table的访问方式.
LUA是脚本语言,你需要的是用解释器执行脚本。LUA PLAYER就是解释器了。