0

I have a very long string for use as a map. It is about 50 characters (10 for my example though). I also have a string that I want to use as a number that represents the players position on the map string:

@ECHO OFF
SET map=CGWGWBBBTB
SET playerposition=1

So if playerposition was 3 I would want to receive W from this next line of code:

%map:~%playerposition%,1%

It seems I can not retrieve the playereposition variable like that.

soundslikeodd
  • 1,078
  • 3
  • 19
  • 32
  • 1
    `!map:~%playerposition%,1!` with Delayed Expansion enabled, or `call %%map:~%playerposition%,1%%` without. This management is explained at [this answer](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) although the question is not the same... – Aacini Jan 15 '17 at 15:22
  • @Aacini Thanks! This was very helpful! Would upvote if that were a thing for comments... – Iceball 457 Jan 16 '17 at 23:53
  • Well, you may upvote the linked answer... **`;)`** – Aacini Jan 17 '17 at 02:40

1 Answers1

1
@ECHO OFF
SETLOCAL
@ECHO OFF
SET map=CGWGWBBBTB
SET playerposition=1
CALL SET playereposition=%%map:~%playerposition%,1%%
SET play
SET playerposition=2
CALL SET playereposition=%%map:~%playerposition%,1%%
SET play
SET playerposition=3
CALL SET playereposition=%%map:~%playerposition%,1%%
SET play

You could also use a subroutine:

SET playerposition=4
CALL :setsubstr playereposition map %playerposition% 1
SET play

GOTO :EOF

:setsubstr
SETLOCAL ENABLEDELAYEDEXPANSION
SET "return=!%2:~%3,%4!"
endlocal&SET "%1=%return%"
GOTO :EOF

Here, the temporary variable return is used to contain the substring-from-3rd-parameter-length-4th-parameter-of the string second-parameter into variable-name first-parameter.

The endlocal&... disposes of the temporary variable and uses a parsing trick to assign the value to %1.

Note that using this approach also allows the routine to be made "smart" by allowing (with changes) an omitted 4th parameter to default to 1, for instance.

Note also in all of this that position-counting in a string starts from 0, not 1.

Magoo
  • 77,302
  • 8
  • 62
  • 84