I’m working on a 2d Game. I use lua script in all game logic. Now the problem is the sorting too slow. Can anyone help to improve it?
Here is my code about zobject list.
local c = class("ZList") -- class is a function to generate a "Class"
function c:insert(v) -- every v(value or object) has a z field
if v.z == nil then v.z = -1 end
if self.head == nil then
self.head = {val=v, nxt=nil}
else
local p = self.head
local pp = p -- pp is a pointer to pre node
while v.z and p and p.val.z and p.val.z <= v.z do
pp = p
p = p.nxt
end
if p == self.head then
self.head = {val=v, nxt=p}
else
pp.nxt = {val=v, nxt=p}
end
end
end
function c:delete(v)
local p = self.head
local pp
while p and p.val ~= v do
pp = p
p = p.nxt
end
if p ~= nil then
if p == self.head then
self.head = p.nxt
else
pp.nxt = p.nxt
end
end
end
___ update ______
Thank you Nicol and every replied! I followed your suggestion: use table.insert and table.sort, use a static list which don’t need to be sort. Here are my final codes:
local remove_list
sort(Graphics.viewports, comp)
for _, viewport in pairs(Graphics.viewports) do
if viewport.visible then
remove_list = {}
if not viewport.static then sort(viewport.sprites, comp) end
for k, sprite in pairs(viewport.sprites) do
if not sprite:paint() then
table.insert(remove_list,1, k)
end
end
for _, k in pairs(remove_list) do
table.remove(viewport.sprites, k)
end
end
end
Stop putting your sprites in a linked list. Put them in a regular list. Insertion time is not going to hurt you nearly as badly as the memory allocations and such for a linked list will. Just use a regular Lua list, with
table.insertand so forth.Alternatively, do you really need all of your sprites to be sorted? Most likely (depending on the circumstances of course), you can just draw them in layers: all of Layer 0 (in any order), then all of Layer 1, etc.