开发者

Can scripting in iphone app instantiate a variable

I am trying to understand the benefit of using a scripting language like lua in game development on the iphone (using cocos2d for instance) and if it can help solve my problem (and improve my coding skills). In my game I have the following code:

-(void)MenuItem:(CCMenuItem  *) menuItem {
 switch (menuItem.tag) {
  case 1:
   [[CCDirector sharedDirector] replaceScene:[Level1 scene]];
   break;
  case 2:
   [[CCDirector sharedDirector] replaceScene:[Level2 scene]];
   break;
  case 3:
   [[CCDirector sharedDirector] replaceScene:[Level3 scene]];
   break;
  case 4:
   [[CCDirector sharedDirector] replaceScene:[Level4 scene]];
   break;
  case 5:
   [[CCDirector sharedDirector] replaceScene:[Level5 scene]];
   break;
  case 6:
   [[CCDirector sharedDirector] replaceScene:[Level6 scene]];
   break;
  case 7:
   [[CCDirector sharedDirector] replaceScene:[Level7 scene]];
   break;
  case 8:
   [[CCDirector sharedDirector] replaceScene:[Level8 scene]];
   break; 
  default:
   break;
 }

The problem with that开发者_JS百科 function is if I have 50 levels, this function will take 3 pages of code. I would like to replace this entire function with:

-(void)MenuItem:(CCMenuItem  *) menuItem {
[[CCDirector sharedDirector] replaceScene:[<script> @"Level" + menuItem.tag</script> scene]];
}

where script> /script> would be a way to embed a scripting language that would concatenate the string "Level" and the level number, thus creating the name of the class. So this function would be independent of the number of levels. So my question is: Can scripting help ? If yes, how can it help and if no, is there a solution to do that?


I'd suggest this:

NSString *levelToLoad = [NSString stringWithFormat:@"Level%d", menuItem.tag];
[[CCDirector sharedDirector] replaceScene:[NSClassFromString(levelToLoad) scene]];

Yeah, I just saved you hours of typing.


AppStore rules prohibit the use of scripting languages in your apps.

But that is not your problem, you could use the reflection API:

[[NSClassFromString([NSString stringWithFormat:@"Level%i", menuItem.tag]) scene]];

Which is not the best way to go, since you are in control of all the code, therefore you don't need to use it, it "just works" and feels hacky. You should rather implement a level manager and have it search for the given level for you (example):

[MyLevelManager levelWithId:menuItem.tag];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜