• What am i doing wrong with this for loop?
    5 replies, posted
I've been doing various programs for quite a while but i'm really new when it comes to lua... what is wrong in my code? [lua] --radiation stirring, every 5 seconds: ---list active/inactive radiation pockets ---IF there is at least one active and one inactive pocket ---choose a random active and a random inactive ---make them inactive and active respectively if self.StirTime < CurTime() then self.StirTime = CurTime() + 5 if #ents.FindByClass( "point_radiation" ) < 1 then return end local rad_active_pockets = {} local rad_inactive_pockets = {} for k,v in pairs( ents.FindByClass( "point_radiation" ) ) do if v:IsActive() then table.insert(rad_active_pockets,v) else table.insert(rad_inactive_pockets,v) end end if table.Count(rad_inactive_pocket) < 1 or table.Count(rad_active_pocket) < 1 then return end local rad = table.Random(rad_active_pockets) local rad2 = table.Random(rad_inactive_pockets) rad:SetActive( false ) rad2:SetActive( true ) end [/lua] I keep getting errors about the 'pairs()' being provided a 'nil' value and i can't figure out why, ents.FindByClass should return a table normally.
Can you not just do this? [lua]for k,v in pairs( ents.GetAll() ) do if v:GetClass() == "point_radiation" then ... end end[/lua]
i could probably, but why wouldn't ent.findbyclass not return a table?
okay this is my new loop, now it's telling me this: [code] attempt to get length of global 'rad_inactive_pocket' (a nil value) [/code] I don't get it, it's declared as a local, then why is it trying to pull out the value of global? [lua] if self.StirTime < CurTime() then self.StirTime = CurTime() + 5 if #ents.FindByClass( "point_radiation" ) < 1 then return end local rad_active_pockets = {} local rad_inactive_pockets = {} local arr = ents.GetAll() --we loop through entities looking for radiation pockets for k,v in pairs( arr ) do if v:GetClass() == "point_radiation" then --and we sort them if v:IsActive() then table.insert(rad_active_pockets,v) else table.insert(rad_inactive_pockets,v) end end end if #rad_inactive_pocket > 0 then local rad2 = table.Random(rad_inactive_pockets) rad2:SetActive( true ) end if #rad_active_pocket > 0 then local rad = table.Random(rad_active_pockets) rad:SetActive( false ) end end [/lua]
You are right, beginner error... coming back once i tested this, thanks! Awesome, all work fine now *blame lua for not pointing the good line for errors*
Sorry, you need to Log In to post a reply to this thread.