2

I want to call multiple methods in lua that are very similar except their parameters change by one character. The way I'm doing it now works but is extremely in efficient.

function scene:createScene(event)

screenGroup = self.view

level1= display.newRoundedRect( 50, 110, 50, 50, 5 )
level1:setFillColor( 100,0,200 )
level2= display.newRoundedRect( 105, 110, 50, 50, 5 )
level2:setFillColor (100,200,0)
--and so on so forth

screenGroup:insert (level1)
screenGroup:insert (level2)
screenGroup:insert (level3)
screenGroup:insert (level4)

end 

I plan on extending the screenGroop:insert method to hundreds of levels, maybe up to (level300). As you can see the way I'm doing it now is inefficient. I tried doing

for i=1, 4, 1 do 
screenGroup:insert(level..i)
end

but I get the error "table expected."

1

2 Answers 2

3

The best way in this case is to probably use a table:

local levels = {}
levels[1] = display.newRoundedRect( 50, 110, 50, 50, 5 )
levels[1]:setFillColor( 100,0,200 )
levels[2] = display.newRoundedRect( 105, 110, 50, 50, 5 )
levels[2]:setFillColor (100,200,0)
--and so on so forth

for _, level in ipairs(levels) do
  screenGroup:insert(level)
end

For other alternatives check the SO answer from @EtanReisner's comment.

Sign up to request clarification or add additional context in comments.

Comments

-1

If your 'level' tables are global, which is appears they are, you can use getfenv to index them.

for i = 1, number_of_levels do
    screenGroup:insert(getfenv()["level" .. i])
end

getfenv returns the environment, with all global variables, in the form of a dictionary. Therefore, you can index it like a normal table like getfenv()["key"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.