Error array variable has incorrect number of subscripts or subscript dimension range exceeded

Помогите пожалуйста. Я в Autoit не соображаю. Каждый раз при загрузке системы (ХР) выскакивает ошибка "Autoit line-1: Error: Array variable has incorrect number of subscripts or subscript dimension range exceeded." я уже и в гугле искал ответы, но ничего не помогло. :( Подскажите что делать...
#include <Array.au3>

$aAutoItProcList = _ProcessListEx("CompiledScript", "AutoIt", 0)

If @error Then
	MsgBox(48, "_ProcessListEx - Error", StringFormat("There was an error to get ProcessList (@error = %i)", @error))
Else
	_ArrayDisplay($aAutoItProcList, "_ProcessListEx Demo (AutoIt Processes)")
EndIf

;===============================================================================
;
; Function Name:  		   _ProcessListEx()
;
; Function Description:    Gets Process List with extended info, plus can retrieve only a processes with specific resources strings.
;
; Parameter(s):            $sResourceName [Optional] - Resource name of the process filename, i.e. "CompiledScript".
;                          $sInResString [Optional] - String to check in the resource name.
;                          $iWholeWord [Optional] - Defines if the $sInResString will be compared as whole string (default is 1).
;
; Requirement(s):          None.
;
; Return Value(s):         On Success -  Return 2-dimentional array, where:
;                                                                   $aRet_List[0][0] = Total processes (array elements).
;                                                                   $aRet_List[N][0] = Process Name.
;                                                                   $aRet_List[N][1] = PID (Process ID).
;                                                                   $aRet_List[N][2] = Process File Path.
;                          On Failure -  Return '' (empty string) and set @error to:
;                                                                   1 - Unable to Open Kernel32.dll.
;                                                                   2 - Unable to Open Psapi.dll.
;                                                                   3 - No Processes Found.
;
; Author(s):               G.Sandler (a.k.a MrCreatoR) - CreatoR's Lab (http://creator-lab.ucoz.ru)
;
;=====================================================================
Func _ProcessListEx($sResourceName="", $sInResString="", $iWholeWord=1)
	Local $aProcList = ProcessList()
	Local $hKernel32_Dll = DllOpen('Kernel32.dll'), $hPsapi_Dll = DllOpen('Psapi.dll')
	Local $aOpenProc, $aProcPath, $sFileVersion, $aRet_List[1][1]
	
	If $hKernel32_Dll = -1 Then Return SetError(1, 0, '')
	
	If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@SystemDir & 'Psapi.dll')
	If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@WindowsDir & 'Psapi.dll')
	If $hPsapi_Dll = -1 Then Return SetError(2, 0, '')
	
	Local $vStruct 		= DllStructCreate('int[1024]')
	Local $pStructPtr 	= DllStructGetPtr($vStruct)
	Local $iStructSize 	= DllStructGetSize($vStruct)
	
	For $i = 1 To UBound($aProcList)-1
		$aOpenProc = DllCall($hKernel32_Dll, 'hwnd', 'OpenProcess', _
			'int', BitOR(0x0400, 0x0010), 'int', 0, 'int', $aProcList[$i][1])
		
		If Not IsArray($aOpenProc) Or Not $aOpenProc[0] Then ContinueLoop
		
		DllCall($hPsapi_Dll, 'int', 'EnumProcessModules', _
			'hwnd', $aOpenProc[0], _
			'ptr', $pStructPtr, _
			'int', $iStructSize, _
			'int*', 0)
		
		$aProcPath = DllCall($hPsapi_Dll, 'int', 'GetModuleFileNameEx', _
			'hwnd', $aOpenProc[0], _
			'int', DllStructGetData($vStruct, 1), _
			'str', '', _
			'int', 2048)
		
		DllCall($hKernel32_Dll, 'int', 'CloseHandle', 'int', $aOpenProc[0])
		
		If Not IsArray($aProcPath) Or StringLen($aProcPath[3]) = 0 Then ContinueLoop
		
		$sFileVersion = FileGetVersion($aProcPath[3], $sResourceName)
		
		If $sResourceName = "" Or $sFileVersion = $sInResString Or _
			($iWholeWord = 0 And StringInStr($sFileVersion, $sInResString)) Then
			
			$aRet_List[0][0] += 1
			ReDim $aRet_List[$aRet_List[0][0]+1][3]
			$aRet_List[$aRet_List[0][0]][0] = $aProcList[$i][0] 	;Process Name
			$aRet_List[$aRet_List[0][0]][1] = $aProcList[$i][1] 	;PID (Process ID)
			$aRet_List[$aRet_List[0][0]][2] = $aProcPath[3] 		;Process File Path
		EndIf
	Next
	
	DllClose($hKernel32_Dll)
	DllClose($hPsapi_Dll)
	
	If $aRet_List[0][0] < 1 Then Return SetError(3, 0, '')
	Return $aRet_List
EndFunc

Нашли строку, но не знаете что с ней делать? Поставьте перед сбойной строкой MsgBox с выводом значения переменной, чтоб увидеть, являются ли данные тем, что необходимо получить. И если переменная является массивом, то используйте _ArrayDisplay, добавив в начало скрипта

Если скрипт был найден на форуме, то попытайтесь выяснить версию AutoIt3, с которой использовался скрипт, например по дате поста. Проверьте чтобы все необходимые скрипту

Если окно ошибки указывает на переменную являющуюся элементом массива, даже если вы уверены что с массивом всё в порядке, то очень вероятно, что цикл использует индекс превышающий существующие индексы в массиве. Используйте

Ниже приведен полный список фатальных ошибок AutoIt, возникающих при неправильном написании скриптов пользователем. Всего 74

Текст ошибки Перевод текста Unable to open the script file. Не удается открыть файл сценария. Badly formatted «Func» statement. Неправильный формат оператора «Func» Unable to parse line. Не удалось разобрать строку. Missing right bracket ‘)’ in expression. Отсутствует правая скобка ‘)’ в выражении. Missing operator in expression. Отсутствует оператор в выражении. Unbalanced brackets in expression. Незакрытые скобки в выражении. Error in expression. Ошибка в выражении Error parsing function call. Ошибка разбора (парсинга, синтаксиса) вызываемой функции Incorrect number of parameters in function call. Неверное количество параметров при вызове функции «ReDim» used without an array variable. «ReDim» используется с переменной не являющейся массивом Illegal text at the end of statement (one statement per line). Недопустимый текст в конце оператора (один оператор в строке) «If» statement has no matching «EndIf» statement. Оператор «If» не имеет сопровождающий его оператор «EndIf» «Else» statement with no matching «If» statement. Оператор «Else» не имеет сопровождающий его оператор «If» «EndIf» statement with no matching «If» statement. Оператор «EndIf» не имеет сопровождающий его оператор «If» Too many «Else» statements for matching «If» statement. Слишком много операторов «Else» для одного оператора «If» «While» statement has no matching «Wend» statement. Оператор «While» не имеет сопровождающий его оператор «Wend» «Wend» statement with no matching «While» statement. Оператор «Wend» не имеет сопровождающий его оператор «While» Variable used without being declared. Переменная используется без первоначального объявления Array variable has incorrect number of subscripts or subscript dimension range exceeded. Переменная массива имеет неверное количество индексов или индекс превышает размер массива. Array variable subscript badly formatted. Неправильный формат индекса в переменной массива. Subscript used with non-Array variable. Индекс используется с переменной не являющейся массивом Too many subscripts used for an array. Слишком много индексов для массива. Пример Dim $a[1] = [[1]] Missing subscript dimensions in «Dim» statement. Отсутствуют индексы измерений в операторе «Dim». Пример Dim $a[1] = 1 No variable given for «Dim», «Local», «Global» or «Const» statement. Отсутствует объявление переменной в операторах «Dim», «Local», «Global» или «Const» Expected a «=» operator in assignment statement. Ожидается оператор «=» в конструкции присваивания. Invalid keyword at the start of this line. Недопустимое ключевое слово в начале этой линии Array maximum size exceeded. Превышен максимальный размер массива «Func» statement has no matching «EndFunc». Оператор «Func» не имеет сопровождающий его оператор «EndFunc» Duplicate function name. Дубликат имени функции (Одна и та же функция встречается в скрипте дважды) Unknown function name. Неизвестное имя функции (Вызов отсутствующей функции) Unknown macro. Неизвестное имя макроса (опечатка или устаревший макро) Unable to execute the external program. Не удается выполнить внешнюю программу. Unknown option or bad parameter specified. (?) Неизвестный параметр или плохо указанного параметра. Unable to load the internet libraries. (?) Не удается загрузить библиотеки Интернет Unable to open file, the maximum number of open files has been exceeded. Не удается открыть файл, превышено максимальное количество открытых файлов. Invalid file handle used. Используется неверный дескриптор файла Invalid file filter given. (?) Неверно задан файловый фильтр Expected a variable in user function call. Ожидается переменная при вызове пользовательской функции. Пример Func _FuncName(ByRef) «Do» statement has no matching «Until» statement. Оператор «Do» не имеет сопровождающий его оператор «Until» «Until» statement with no matching «Do» statement. Оператор «Until» не имеет сопровождающий его оператор «Do» «For» statement is badly formatted. Оператор «For» имеет неправильный формат «Next» statement with no matching «For» statement. Оператор «Next» не имеет сопровождающий его оператор «For» «ExitLoop/ContinueLoop» statements only valid from inside a For/Do/While loop. Операторы «ExitLoop/ContinueLoop» допускаются только внутри циклов For/Do/While. «For» statement has no matching «Next» statement. Оператор «For» не имеет сопровождающий его оператор «Next» «Case» statement with no matching «Select»or «Switch» statement. Оператор «Case» не имеет сопровождающий его оператор «Select» или «Switch» «EndSelect» statement with no matching «Select» statement. Оператор «EndSelect» не имеет сопровождающий его оператор «Select» Recursion level has been exceeded — AutoIt will quit to prevent stack overflow. Уровень рекурсии был превышен, AutoIt завершает работу, чтобы предотвратить переполнение стека Unable to access RunAs API. Не удается получить доступ RunAs API String missing closing quote. Строка не содержит закрывающую кавычку Unterminated string. Незавершенная строка Badly formated variable or macro. Неправильный формат переменной или макро This keyword cannot be used after a «Then» keyword. Это ключевое слово не может быть использована после ключевого слова «Then» «Select» statement is missing «EndSelect» or «Case» statement. Оператор «Select» не имеет сопровождающий его оператор «EndSelect» или «Case» «If» statements must have a «Then» keyword. Оператор «If» должен иметь ключевое слово «Then» Cannot assign values to constants. Невозможно присвоить значения константе. Cannot make existing variables into constants. Невозможно сделать существующие переменные в константы Object referenced outside a «With» statement. Объект ссылается за пределами оператора «With». Nested «With» statements are not allowed. Вложенные операторы «With» не допускается Variable must be of type «Object». Переменная должна быть типом «Object» The requested action with this object has failed. Запрашиваемое действие с этим объектом не удалось Variable appears more than once in function declaration. (?) Переменная появляется более одного раза в объявлении функции ReDim array can not be initialized in this manner. ReDim массива не может быть выполнен таким способом. Пример ReDim $arr1[1] = [1] An array variable can not be used in this manner. Переменная массива не может быть использована таким образом. Can not redeclare a constant. Невозможно декларировать константу повторно Can not redeclare a parameter inside a user function. Невозможно объявить переменную, переданную как параметр внутри пользовательской функции. Can pass constants by reference only to parameters with «Const» keyword. Можно передавать константы как ссылки только на параметры с ключевым словом «Const». Например _FuncName(ByRef $w) Can not initialize a variable with itself. текст Incorrect way to use this parameter. Неправильный способ использования этого параметра «EndSwitch» statement with no matching «Switch» statement. Оператор «EndSwitch» не имеет сопровождающий его оператор «Switch» «Switch» statement is missing «EndSwitch» or «Case» statement. Оператор «Switch» не имеет сопровождающий его оператор «EndSwitch» или «Case» «ContinueCase» statement with no matching «Select»or «Switch» statement. Оператор «ContinueCase» не имеет сопровождающий его оператор «Select» или «Switch» Assert Failed! Утверждение неудачно! AutoIt has encountered a fatal crash as a result of:r Unable to execute DLLCall. AutoIt столкнулся с фатальным крахом в результате осуществления: не удается выполнить DLLCall Obsolete function/parameter. Устаревшая функция / параметр Invalid Exitcode (reserved for AutoIt internal use). Недопустимый Exitcode (зарезервировано для внутреннего использования AutoIt). Cannot parse #include Не удается выполнить разбор #include Error opening the file Ошибка при открытии файла (при несуществующем #include-файле)

Hello there,

I created a little script the should read out a raster of blocks out of the game Bejeweled 3.

The language is written in a Basic-like language (for Autoit)

The only issue is: When reading out Pixelcolors it gives me an error on my created Function.

Can you guys tell me what I am doing wrong?

Func _readPixels()
_log("Start reading pixels")
$pixelShift = _getNextPixelShiftSet()
$shiftHorizontal = $pixelShift[1]
$shiftVertical = $pixelShift[2]
ToolTip('Reading pixels playfield', 0, 0)
dim $Field[8][8]
$k=0
$l=0
for $j = $field1[1] to $field3[1] step $blockWidth
for $i = $field1[0] to $field2[0] step $blockWidth
$field[$k][$l] = pixelgetColor($i + $shiftHorizontal,$j + $shiftVertical)
;mousemove($i + $shiftHorizontal,$j + $shiftVertical,40)
;Sleep(500)
$k = $k + 1
next
$l = $l + 1
$k = 0
next
return $field
EndFunc

The complete script till now is:

;-------------------- DECLARATION SECTION --------------------
#include <array.au3>
#include <file.au3>

Global $paused ;sets up pause hotkey
HotKeySet("{ESC}", "_quit") ;set escape hotkey to exit
HotKeySet("{PAUSE}", "_pause") ;set pasue hotkey to pause

_log("Initializing bejeweled bot...")

$iniFile=stringleft(@ScriptName,stringlen(@scriptname)-4) & ".ini"
if not FileExists($iniFile) Then
msgbox(0,"","The ini file could not be found at following location: " & $iniFile)
exit
EndIf

$windowBejeweled3=IniRead ( $iniFile, "Common" , "windowBejeweled3", "" )

$cornerColor1=IniRead ( $iniFile, "Common" , "cornerColor1", "0x9A6043" )
$cornerColor4=IniRead ( $iniFile, "Common" , "cornerColor4", "0x040404" )

$corner1 = _ArrayCreate("","")
$corner2 = _ArrayCreate("","")
$corner3 = _ArrayCreate("","")
$corner4 = _ArrayCreate("","")

$Field1 = _ArrayCreate("","")
$Field2 = _ArrayCreate("","")
$Field3 = _ArrayCreate("","")

$BlockWidth = 0

$AmountGems=IniRead ( $iniFile, "Common" , "AmountGems", 0 )

;Calculate distance between center of each gem
$BlockWidth = ($Corner2[0] - $Corner1[0]) / $AmountGems

$Field1[0]=$Corner1[0] + ($BlockWidth / 2)
$Field1[1]=$Corner1[1] + ($BlockWidth / 2)

$Field2[0]=$Corner2[0] - ($BlockWidth / 2)
$Field2[1]=$Corner1[1] + ($BlockWidth / 2)

$Field3[0]=$Corner3[0] + ($BlockWidth / 2)
$Field3[1]=$Corner3[1] - ($BlockWidth / 2)

$pixelShift=IniRead ( $iniFile, "Common" , "pixelShift", 0 )

$searchDelay=IniRead ( $iniFile, "Common" , "searchDelay", 1200 )

;-------------------- MAIN SECTION ---------------------------
if winactivate($windowBejeweled3)= 0 then
msgbox(0,"","Window " & $windowBejeweled3 & " could not be found.")
exit
endif

_log("Searching top left Color of playfield")
ToolTip('Searching top left Color pixel with Color ' & hex($cornerColor1, 6) , 0, 0)

$Corner1 = pixelSearch(0,0,@DesktopWidth,@DesktopHeight, $cornerColor1,0)
If @error Then
msgbox(0,"","Top Left pixel with Color: " & hex($cornerColor1, 6) & " not found")
exit
Else
MouseMove($corner1[0],$corner1[1])
endif

_log("Searching bottom right Color of playfield")
ToolTip('Searching bottom right Color pixel with Color ' & hex($CornerColor4, 6) , 0, 0)

$Corner4=_pixelSearchReverse(0,0,@DesktopWidth,@DesktopHeight, $CornerColor4)
If @error Then
msgbox(0,"","Bottom Right pixel with Color: " & hex($CornerColor4, 6) & " not found")
exit
Else
MouseMove($corner4[0],$corner4[1])
endif

;Calculate Color of remaining corners
$Corner2[0]=$Corner4[0]
$Corner2[1]=$Corner1[1]

$Corner3[0]=$Corner1[0]
$Corner3[1]=$Corner4[1]

;Read pixel shift sets into an array
Global $pixelShiftSetCounter = 0
Global $pixelShiftSet = StringSplit($PixelShift,"/")

;For each pixel shift set, create an array storing the x and y coordinates
for $i = 1 to Ubound($pixelShiftSet) - 1
$pixelShiftSet[$i] = stringSplit($pixelShiftSet[$i],",")
Next

while 1
$switched = false
$field = _ReadPixels()
_LogPixels()

ToolTip('Start checking if gems can be moved', 0, 0)

;PLACEHOLDER for the movement of gems

ToolTip('Stop checking if gems can be moved', 0, 0)

if $switched = true then
 sleep($searchDelay)
 _log("a move was performed")
Else
 _log("checked whole field, no moves were done")
endif
_log("")
wend

;-------------------- FUNCTION SECTION -----------------------
;makes a quit function
Func _quit()
Exit
EndFunc

;makes a pause function
Func _pause()
$paused = Not $paused
While $paused
Sleep(100)
ToolTip('Script is "Paused, to unpause press pause key"', 0, 0)
WEnd
ToolTip("")
EndFunc

Func _Log($message)
_FileWriteLog(@scriptDir & "output.txt", $message)
EndFunc

Func _pixelSearchReverse($left,$top,$right,$bottom,$Color)
$coordFoundColor=_ArrayCreate("-1","-1")
$i = 0
$j = 0

for $i = @DesktopWidth to 0 Step -1
 for $j = @DesktopHeight to 0 Step -1

  $currentColor = PixelGetColor($i,$j)
  if $currentColor = $Color then
   $coordFoundColor[0] = $i
   $coordFoundColor[1] = $j
   return $coordFoundColor
  endif

 next
next
SetError(-1)
endFunc

Func _ArrayCreate($v_0, $v_1 = 0, $v_2 = 0, $v_3 = 0, $v_4 = 0, $v_5 = 0, $v_6 = 0, $v_7 = 0, $v_8 = 0, $v_9 = 0, $v_10 = 0, $v_11 = 0, $v_12 = 0, $v_13 = 0, $v_14 = 0, $v_15 = 0, $v_16 = 0, $v_17 = 0, $v_18 = 0, $v_19 = 0, $v_20 = 0)
    Local $av_Array[21] = [$v_0, $v_1, $v_2, $v_3, $v_4, $v_5, $v_6, $v_7, $v_8, $v_9, $v_10, $v_11, $v_12, $v_13, $v_14, $v_15, $v_16, $v_17, $v_18, $v_19, $v_20]
    ReDim $av_Array[@NumParams]
    Return $av_Array
EndFunc   ;==>_ArrayCreate

Func _getNextPixelShiftSet()
if $PixelShiftSetcounter < (Ubound($PixelShiftSet) - 1) then
$PixelShiftSetcounter = $PixelShiftSetcounter + 1  
else
$PixelShiftSetcounter = 1  
endif
_log("Using Pixelshiftset with number " & $PixelShiftSetcounter & " and content " & _ArrayToString($PixelShiftSet[$PixelShiftSetcounter],",",1))
return $PixelShiftSet[$PixelShiftSetcounter]
EndFunc

Func _readPixels()
_log("Start reading pixels")
$pixelShift = _getNextPixelShiftSet()
$shiftHorizontal = $pixelShift[1]
$shiftVertical = $pixelShift[2]
ToolTip('Reading pixels playfield', 0, 0)
dim $Field[8][8]
$k=0
$l=0
for $j = $field1[1] to $field3[1] step $blockWidth
for $i = $field1[0] to $field2[0] step $blockWidth
$field[$k][$l] = pixelgetColor($i + $shiftHorizontal,$j + $shiftVertical)
;mousemove($i + $shiftHorizontal,$j + $shiftVertical,40)
;Sleep(500)
$k = $k + 1
next
$l = $l + 1
$k = 0
next
return $field
EndFunc

Func _logpixels()
$i = 0
$j = 0
for $j = 0 to 7
 $line = ""
 for $i = 0 to 7
  $temp = $field[$i][$j]
  $line = $line & " " & hex($temp)
 next
 _Log($line)
next
_Log("")
EndFunc

Понравилась статья? Поделить с друзьями:
  • Error bars что это
  • Error array type has incomplete element type
  • Error band перевод
  • Error array subscript is not an integer
  • Error baldi basics