Omnimaga
Calculator Community => TI Calculators => Lua => Topic started by: Nick on May 24, 2012, 03:00:59 pm
-
Hi
i'm having trouble with a part of my code
1) a little bit of background information
I'm having a table filled with class instances, from the class cell. each instance has these values:
- xPos
- yPos
- radius
- xMov
- yMov
2) every loop i want to remove all the cells with a radius of zero (so self.radius = 0)
as far as i know, i can't do this with a for loop, since removing items out of the table while working with the tablelength in a for loop messes up everything
here's the code
cell = class()
cellTable = {}
timer.start(0.01)
function cell:init(x,y,radius)
self.xPos = x
self.yPos = y
self.radius = radius
self.xMov = math.random(-1,1)
self.yMov = math.random(-1,1)
end
function on.create()
text = "no collision"
end
table.insert(cellTable, cell(10,10,10))
table.insert(cellTable, cell(100,90,20))
table.insert(cellTable, cell(69,200,10))
table.insert(cellTable, cell(180,50,10))
table.insert(cellTable, cell(150,150,10))
function on.timer()
for k,v in pairs(cellTable) do
v:move()
end
removeCells()
platform.window:invalidate()
end
function on.paint(gc)
for k,v in pairs(cellTable) do
v:paint(gc)
end
checkCollision(cellTable)
end
function removeCells()
--here's the part that should remove items out of the list
end
function checkCollision()
--This function check for collisions (you don't say) and decreases or increases the radius when needed
end
this is only part of the code, but it's the part that matters (it's a school project i'm working on, and should not yet be made available till after the exams)
i hope i made pyself clear, and as always, any help would be greatly appreciated :)
Nick
-
Try this:
function removeEmpty(tbl)
for k, v in ipairs(tbl) do
if v.radius == 0 then
table.remove(tbl, k)
end
end
end
I think that is what you want.
-
Perfect, it works like a charm!!!
thanks again jim :)
-
I noticed it doesn't work properly at all times, so here is a better function:
function removeEmpty(tbl)
for k, v in ipairs(tbl) do
if v.radius == 0 then
table.remove(tbl, k)
removeEmpty(tbl)
break
end
end
end
It's a bit recursive, so if cellTable is huge (like over 9001 entries), I might need to script an iterative version.
Anyway, glad it works :)
Edit:
Here is a non recursive function, good if you are handling extremely large amounts of data
function removeEmpty(tbl)
local n = 1
local rep = true
while rep do
rep = false
for k = n, #tbl do
if tbl[k].radius == 0 then
table.remove(tbl, k)
rep = true
n = k
break
end
end
end
end