Lua 常用数据结构
Posted Linux大师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lua 常用数据结构相关的知识,希望对你有一定的参考价值。
一、数组
a = {}
for i = 1,100 do
a[i] = 0
end
print("The length of array 'a' is " .. #a)
squares = {1, 4, 9, 16, 25}
print("The length of array 'a' is " .. #squares)
二、二维数组
local N = 3
local M = 3
mt = {}
for i = 1,N do
mt[i] = {}
for j = 1,M do
mt[i][j] = i * j
end
end
mt = {}
for i = 1, N do
for j = 1, M do
mt[(i - 1) * M + j] = i * j
end
end
三、链表
list = nil
for i = 1, 10 do
list = { next = list ,value = i}
end
local l = list
while l do
--print(l.value)
l = l.next
end
四、队列与双向队列
List = {}
--创建
function List.new()
return {first = 0,last = -1}
end
--队列头插入
function List.pushFront(list,value)
local first = list.first - 1
list.first = first
list[first] = value
end
--队列尾插入
function List.popFront(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.popBack(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 testList = {first = 0,last = -1}
local tableTest = 12
List.pushFront(testList,tableTest)
print( List.popFront(testList))
五、栈
local stackMng = {}
stackMng.__index = stackMng
function stackMng:new()
local temp = {}
setmetatable(temp,stackMng)
return temp
end
function stackMng:init()
self.stackList = {}
end
function stackMng:reset()
self:init()
end
function stackMng:clear()
self.stackList = {}
end
function stackMng:pop()
if #self.stackList == 0 then
return
end
if self.stackList[1] then
print(self.stackList[1])
end
return table.remove(self.stackList,1)
end
function stackMng:push(t)
table.insert(self.stackList,t)
end
function stackMng:Count()
return #self.stackList
end
--测试代码
object = stackMng:new()
object:init()
object:push(1)
object:pop()
六、集合在Lua中用table实现集合是非常简单的,见如下代码:reserved = {
["while"] = true, ["end"] = true,
["function"] = true, ["local"] = true,
}
for k,v in pairs(reserved) do
print(k,"->",v)
end
以上是关于Lua 常用数据结构的主要内容,如果未能解决你的问题,请参考以下文章