在Lua中使用List

15 views
Skip to first unread message

剑孤寒

unread,
Mar 14, 2008, 10:32:30 PM3/14/08
to 剑孤寒的游戏编程小站
在Lua中使用List
转载请注明出处:http://groups.google.com/group/jianguhan

在《Programming in Lua》一书中提到了一个双端队列的实现方法,我把它拿来改进了一下用在了我正在制作的一个RPG游戏里,用起觉得
来还不错,加了一个GetSize()来取得List的大小,这个在游戏制作中用处还是很大的^_^

源代码如下:
CList = class()

function CList:ctor()
self.m_list = { first = 0, last = -1 }
end

function CList:PushFront(value)
local first = self.m_list.first - 1
self.m_list.first = first
self.m_list[first] = value
end

function CList:PushBack(value)
local last = self.m_list.last + 1
self.m_list.last = last
self.m_list[last] = value
end

function CList:PopFront()
local first = self.m_list.first
if first > self.m_list.last then return nil end
local value = self.m_list[first]
self.m_list[first] = nil
self.m_list.first = first + 1
return value
end

function CList:PopBack()
local last = self.m_list.last
if self.m_list.first > last then return nil end
local value = self.m_list[last]
self.m_list[last] = nil
self.m_list.last = last - 1
return value
end

function CList:GetSize()
if self.m_list.first > self.m_list.last then
return 0
else
return math.abs(self.m_list.last - self.m_list.first) + 1
end
end


在最前面的那句CList = class() 这里使用了云风写的一个class函数创建一个类,
这个函数可以在云风的博客上找到,为了方便起见我就在这里先抄一下了:

local _class={}

function class(super)
local class_type={}
class_type.ctor=false
class_type.super=super
class_type.new=function(...)
local obj={}
do
local create
create = function(c,...)
if c.super then
create(c.super,...)
end
if c.ctor then
c.ctor(obj,...)
end
end

create(class_type,...)
end
setmetatable(obj,{ __index=_class[class_type] })
return obj
end
local vtbl={}
_class[class_type]=vtbl

setmetatable(class_type,{__newindex=
function(t,k,v)
vtbl[k]=v
end
})

if super then
setmetatable(vtbl,{__index=
function(t,k)
local ret=_class[super][k]
vtbl[k]=ret
return ret
end
})
end

return class_type
end
Reply all
Reply to author
Forward
0 new messages