a = {} --新建一个数组
for i=1, 1000 do
a[i] = 0
end
在Lua中,有两种方式来表示矩阵。第一种是使用一个“数组的数组”,也就是一个table 中的每个元素是另一个table:
mt = {} --新建矩阵
for i=1, N do
mt[i] = {} --创建一个新行
for j=1, M do
mt[i][j] = 0
end
end
表示矩阵的第二种方式是将两个索引合并为一个索引。如果两个索引是整数,可以将第一个索引乘以一个适当的常量,并加上第二个索引:
mt = {} --创建矩阵
for i=1, N do
for j=1, M do
mt[(i-1)*M + j] = 0
end
end
链表的创建:
list = nil
在表头插入一个元素,元素值为v:
list = {next=list, value=v}
遍历此列表:
local l = list while l do <访问l.value> l = l.next end
队列的创建:
List = {}
function List.new()
return {first=0, last=-1}
end
在队列两端插入或删除元素:
function List.pushfirst(list, value)
local first = list.first - 1
list.first = first
list[first] = value
end
function List.pushlast(list, value)
local last = list.last + 1
list.last = last
list[last] = value
end
function List.popfirst(list)
local first = list.first
if first > list.last then error("list is empty") end
local value = list[first]
list[first] = nil --为了允许垃圾收集
list.first = first + 1
return value
end
function List.poplast(list)
local last = list.last
if list.first > last then error("list is empty") end
local value = list[last]
list[last] = nil --为了允许垃圾收集
list.last = last - 1
return value
end
逐行的读取一个文件:
local t = {}
for line in io.lines() do
t[#t + 1] = line .."\n"
end
local s = table.concat(t)
函数table.concat 会将给定列表中的所有字符串连接起来,并返回连接的结果。
concat函数还有第二个可选参数,可以指定一个插在字符串间的分隔符:
local t = {}
for line in io.lines() do
t[#t + 1] = line
end
s = table.concat(t, "\n") .."\n"