Login
Community
DARK THEME

Iterating over a list

I have a list which contains other lists like so

cp=[ [10,10,4,-1], [100,100,12,1], ... ]

If I try to iterate over the list and add values like this...

for e in cp
  e[0] += e[3]
  ...

I get an error: "Warning: e is not defined..."

Is this form of iteration read only? I can read values using this syntax elsewhere in the program:

for e in cp
  local x = e[0]

Maybe it would work using a numeric for loop instead, if so what's the syntax, something like this?

for i = 0, 10
  a = cp[i][0]

I'll probably dump the 'lists within a list' idea but I'm curious as to why it doesn't seem to work.

Do you use the microScript language? Or is it another language?

I tried to do something similar and it works (I'll leave the code below). But what exactly do you want to do with the list items?

init = function()
  list = [[1,2,3],[4,5,6]]
end

update = function()
  
  for e in list
    e[0] += e[1]
  end
  
  print(list[0])
  
end

Thanks Constantine_RetroGamer, that works as I'd expect, there must be some subtle bug elsewhere in my code (it's only a short test program so shouldn't be too hard to find!). Oh, yes, I'm testing with microScript.

Found the problem, had a bracket in the wrong place when I added an extra 'field' to the list which while syntactically ok was obviously not what I wanted!

cp.push([200, 100, random.nextInt(40)], 1)

should be:

cp.push([200, 100, random.nextInt(40), 1])

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community