Save on variables

From NSIS Wiki
Jump to navigationJump to search
Author: Afrow UK (talk, contrib)


Description

This script (macro) will allow you to split up a variable into separate parts for use. The string stored in the variable must look something like this:

$0 = "string1|string2"

The macro will then split it up to use one piece of the string (e.g. string1)

Usage1

!insertmacro SPLIT_STRING $0 1 ;$0 = input, 1 = get 1st part
Pop $1

Usage2

!insertmacro SPLIT_STRING $0 2 ;$0 = input, 2 = get 2nd (last) part
Pop $1

Usage Example

StrCpy $1 0
top:
IntOp $1 $1 + 1
!insertmacro SPLIT_STRING $0 $1
Pop $2
  MessageBox MB_OK $2
StrCmp $2 2 0 top

The Macro

!macro SPLIT_STRING INPUT PART
Push $R0
Push $R1
 
 StrCpy $R0 0
 StrCmp ${PART} 1 getpart1_loop_${PART}
 StrCmp ${PART} 2 getpart2_top_${PART}
Goto error_${PART}
 
getpart1_loop_${PART}:
 IntOp $R0 $R0 - 1
 StrCpy $R1 ${INPUT} 1 $R0
  StrCmp $R1 "" error_${PART}
  StrCmp $R1 "|" 0 getpart1_loop_${PART}
 
 IntOp $R0 $R0 + 1
 StrCpy $R0 ${INPUT} "" $R0
Goto done_${PART}
 
getpart2_top_${PART}:
 StrLen $R0 ${INPUT}
getpart2_loop_${PART}:
 IntOp $R0 $R0 - 1
 StrCpy $R1 ${INPUT} 1 -$R0
  StrCmp $R1 "" error_${PART}
  StrCmp $R1 "|" 0 getpart2_loop_${PART}
 
 StrCpy $R0 ${INPUT} -$R0
Goto done_${PART}
 
error_${PART}:
 StrCpy $R0 error
 
done_${PART}:
 
Pop $R1
Exch $R0
!macroend

May be helpful!

Note: You cannot use multiple !insertmacro SPLIT_STRING within the same function/section using the same part. Doing so will stop your script compiling. e.g.

Function ThisFunctionIsFine
!insertmacro SPLIT_STRING $0 1
!insertmacro SPLIT_STRING $0 2
FunctionEnd
 
Function ThisFunctionIs'''NOT'''Fine
!insertmacro SPLIT_STRING $0 1
!insertmacro SPLIT_STRING $0 1
FunctionEnd

-Stu