RosettaCodeData/Task/History-variables/FreeBASIC/history-variables.basic

61 lines
1.3 KiB
Text
Raw Permalink Normal View History

2024-11-04 20:28:54 -08:00
REM integer history variable
Type HistoryInt
As Integer Ptr values
As Integer cnt
As Integer capacity
End Type
Function InitHistory() As HistoryInt Ptr
Dim As HistoryInt Ptr hist = Allocate(Sizeof(HistoryInt))
hist->capacity = 10
hist->values = Allocate(hist->capacity * Sizeof(Integer))
hist->cnt = 0
Return hist
End Function
Sub SetInt(hist As HistoryInt Ptr, value As Integer)
If hist->cnt >= hist->capacity Then
hist->capacity *= 2
hist->values = Reallocate(hist->values, hist->capacity * Sizeof(Integer))
End If
If hist->cnt = 0 Then
hist->values[hist->cnt] = 0
hist->cnt += 1
End If
hist->values[hist->cnt] = value
hist->cnt += 1
End Sub
Sub ShowHistory(hist As HistoryInt Ptr)
For i As Integer = 0 To hist->cnt - 1
Print hist->values[i]
Next
End Sub
Function UndoInt(hist As HistoryInt Ptr) As Integer
If hist->cnt <= 1 Then Return hist->values[0]
hist->cnt -= 1
Return hist->values[hist->cnt - 1]
End Function
' Main program
Randomize Timer
Dim As HistoryInt Ptr x = InitHistory()
For i As Integer = 0 To 3
SetInt(x, Int(Rnd * 50) + 100)
Next
Print "x history:"
ShowHistory(x)
Print
For i As Integer = 0 To 3
Print "undo, x ="; UndoInt(x)
Next
Sleep