首页 > 代码库 > 86. LotusScript中的数组函数

86. LotusScript中的数组函数

R6对LotusScript有一些改进和增强,自那之后,Notes对象的接口时有补充和更新,但语言本身没有变化。那些改进就包括增加诸如ArrayGetIndex、ArrayUnique的有用函数。但在编程实践中,还有一些对数组的操作LotusScript没有提供原生的函数,好在基本上都能自己编写。下面的函数中用到的常数都在lsconst.lss或lserr.lss里定义,在脚本前要附加

%INCLUDE"lsconst.lss"

%INCLUDE"lserr.lss"

判断数组是否包含某个元素。

%REM
	Checks if an array contains a value.
	The ArrayGetIndex function returns null if the value is not found.
%END REM
Public Function ArrayContains(source As Variant, value As Variant) As Boolean
	‘the data type of source is not checked intentionally
	ArrayContains=Not IsNull(ArrayGetIndex(source,value))
End Function

LotusScript中的数组最多可以有八维(dimension),下面这个函数利用运行时错误(run-time error)ErrSubscriptOutOfRange获得维数。

‘Returns the number of an array‘s dimensions
Function ArrayDimension(array As Variant) As Integer
	If Not IsArray(array) Then
		ArrayDimension=0
		Exit Function 
	End If
	
	On Error ErrSubscriptOutOfRange GoTo RESULT
	Dim d As Integer, lb As Integer  
	For d=1 To 9
		lb=LBound(array, d)	
	Next
	
RESULT:
	ArrayDimension=d-1
	Exit Function 
End Function

返回多维数组的大小,即所有元素的个数。

Function ArraySize(array As Variant) As Integer
	If Not IsArray(array) Then
		ArraySize=0
		Exit Function 
	End If
	
	ArraySize=1
	Dim d As Integer
	d=ArrayDimension(array)
	Dim i As Integer
	For i=1 To d
		ArraySize=ArraySize*(UBound(array, i)-LBound(array,i)+1)
	Next	
End Function

判断两个数组的“形状”,也就是维数和每一维的上下限是否相同。这个函数在今后比较数组是否相等时有用。

Function ArrayBoundsEquals(a1 As Variant, a2 As Variant) As Boolean
	If (Not IsArray(a1)) Or (Not IsArray(a2)) Then
		ArrayBoundsEquals=False
		Exit Function 
	End If
	
	Dim d1 As Integer, d2 As Integer
	d1=ArrayDimension(a1)
	d2=ArrayDimension(a2)
	If d1<>d2 Then
		ArrayBoundsEquals=False
		Exit Function		
	End If
	
	Dim d As Integer
	For d=1 To d1
		If LBound(a1)><LBound(a2) Or UBound(a1)><UBound(a2) Then
			ArrayBoundsEquals=False
			Exit Function			
		End If
	Next
	
	ArrayBoundsEquals=True 
End Function

将多维数组转换成一维数组。这个函数同样用于比较两个数组是否相等。

Function ArrayToOneDimension(array As Variant) As Variant
	If Not IsArray(array) Then
		Call SetValue(ArrayToOneDimension, array)
		Exit Function 
	End If
	
	Dim d As Integer
	d=ArrayDimension(array)
	If d=1 Then
		ArrayToOneDimension=array
		Exit Function
	End If
	
	Dim size As Integer
	size=ArraySize(array)
	Dim result() As Variant
	ReDim result(size-1)
	Dim i As Integer 
	ForAll e In array
		result(i)=e
		i=i+1
	End ForAll
	
	ArrayToOneDimension=result
End Function





86. LotusScript中的数组函数