The Ring programming language - Version 1.14 documentation

msfclipper 0 views 190 slides Oct 08, 2025
Slide 1
Slide 1 of 1865
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235
Slide 236
236
Slide 237
237
Slide 238
238
Slide 239
239
Slide 240
240
Slide 241
241
Slide 242
242
Slide 243
243
Slide 244
244
Slide 245
245
Slide 246
246
Slide 247
247
Slide 248
248
Slide 249
249
Slide 250
250
Slide 251
251
Slide 252
252
Slide 253
253
Slide 254
254
Slide 255
255
Slide 256
256
Slide 257
257
Slide 258
258
Slide 259
259
Slide 260
260
Slide 261
261
Slide 262
262
Slide 263
263
Slide 264
264
Slide 265
265
Slide 266
266
Slide 267
267
Slide 268
268
Slide 269
269
Slide 270
270
Slide 271
271
Slide 272
272
Slide 273
273
Slide 274
274
Slide 275
275
Slide 276
276
Slide 277
277
Slide 278
278
Slide 279
279
Slide 280
280
Slide 281
281
Slide 282
282
Slide 283
283
Slide 284
284
Slide 285
285
Slide 286
286
Slide 287
287
Slide 288
288
Slide 289
289
Slide 290
290
Slide 291
291
Slide 292
292
Slide 293
293
Slide 294
294
Slide 295
295
Slide 296
296
Slide 297
297
Slide 298
298
Slide 299
299
Slide 300
300
Slide 301
301
Slide 302
302
Slide 303
303
Slide 304
304
Slide 305
305
Slide 306
306
Slide 307
307
Slide 308
308
Slide 309
309
Slide 310
310
Slide 311
311
Slide 312
312
Slide 313
313
Slide 314
314
Slide 315
315
Slide 316
316
Slide 317
317
Slide 318
318
Slide 319
319
Slide 320
320
Slide 321
321
Slide 322
322
Slide 323
323
Slide 324
324
Slide 325
325
Slide 326
326
Slide 327
327
Slide 328
328
Slide 329
329
Slide 330
330
Slide 331
331
Slide 332
332
Slide 333
333
Slide 334
334
Slide 335
335
Slide 336
336
Slide 337
337
Slide 338
338
Slide 339
339
Slide 340
340
Slide 341
341
Slide 342
342
Slide 343
343
Slide 344
344
Slide 345
345
Slide 346
346
Slide 347
347
Slide 348
348
Slide 349
349
Slide 350
350
Slide 351
351
Slide 352
352
Slide 353
353
Slide 354
354
Slide 355
355
Slide 356
356
Slide 357
357
Slide 358
358
Slide 359
359
Slide 360
360
Slide 361
361
Slide 362
362
Slide 363
363
Slide 364
364
Slide 365
365
Slide 366
366
Slide 367
367
Slide 368
368
Slide 369
369
Slide 370
370
Slide 371
371
Slide 372
372
Slide 373
373
Slide 374
374
Slide 375
375
Slide 376
376
Slide 377
377
Slide 378
378
Slide 379
379
Slide 380
380
Slide 381
381
Slide 382
382
Slide 383
383
Slide 384
384
Slide 385
385
Slide 386
386
Slide 387
387
Slide 388
388
Slide 389
389
Slide 390
390
Slide 391
391
Slide 392
392
Slide 393
393
Slide 394
394
Slide 395
395
Slide 396
396
Slide 397
397
Slide 398
398
Slide 399
399
Slide 400
400
Slide 401
401
Slide 402
402
Slide 403
403
Slide 404
404
Slide 405
405
Slide 406
406
Slide 407
407
Slide 408
408
Slide 409
409
Slide 410
410
Slide 411
411
Slide 412
412
Slide 413
413
Slide 414
414
Slide 415
415
Slide 416
416
Slide 417
417
Slide 418
418
Slide 419
419
Slide 420
420
Slide 421
421
Slide 422
422
Slide 423
423
Slide 424
424
Slide 425
425
Slide 426
426
Slide 427
427
Slide 428
428
Slide 429
429
Slide 430
430
Slide 431
431
Slide 432
432
Slide 433
433
Slide 434
434
Slide 435
435
Slide 436
436
Slide 437
437
Slide 438
438
Slide 439
439
Slide 440
440
Slide 441
441
Slide 442
442
Slide 443
443
Slide 444
444
Slide 445
445
Slide 446
446
Slide 447
447
Slide 448
448
Slide 449
449
Slide 450
450
Slide 451
451
Slide 452
452
Slide 453
453
Slide 454
454
Slide 455
455
Slide 456
456
Slide 457
457
Slide 458
458
Slide 459
459
Slide 460
460
Slide 461
461
Slide 462
462
Slide 463
463
Slide 464
464
Slide 465
465
Slide 466
466
Slide 467
467
Slide 468
468
Slide 469
469
Slide 470
470
Slide 471
471
Slide 472
472
Slide 473
473
Slide 474
474
Slide 475
475
Slide 476
476
Slide 477
477
Slide 478
478
Slide 479
479
Slide 480
480
Slide 481
481
Slide 482
482
Slide 483
483
Slide 484
484
Slide 485
485
Slide 486
486
Slide 487
487
Slide 488
488
Slide 489
489
Slide 490
490
Slide 491
491
Slide 492
492
Slide 493
493
Slide 494
494
Slide 495
495
Slide 496
496
Slide 497
497
Slide 498
498
Slide 499
499
Slide 500
500
Slide 501
501
Slide 502
502
Slide 503
503
Slide 504
504
Slide 505
505
Slide 506
506
Slide 507
507
Slide 508
508
Slide 509
509
Slide 510
510
Slide 511
511
Slide 512
512
Slide 513
513
Slide 514
514
Slide 515
515
Slide 516
516
Slide 517
517
Slide 518
518
Slide 519
519
Slide 520
520
Slide 521
521
Slide 522
522
Slide 523
523
Slide 524
524
Slide 525
525
Slide 526
526
Slide 527
527
Slide 528
528
Slide 529
529
Slide 530
530
Slide 531
531
Slide 532
532
Slide 533
533
Slide 534
534
Slide 535
535
Slide 536
536
Slide 537
537
Slide 538
538
Slide 539
539
Slide 540
540
Slide 541
541
Slide 542
542
Slide 543
543
Slide 544
544
Slide 545
545
Slide 546
546
Slide 547
547
Slide 548
548
Slide 549
549
Slide 550
550
Slide 551
551
Slide 552
552
Slide 553
553
Slide 554
554
Slide 555
555
Slide 556
556
Slide 557
557
Slide 558
558
Slide 559
559
Slide 560
560
Slide 561
561
Slide 562
562
Slide 563
563
Slide 564
564
Slide 565
565
Slide 566
566
Slide 567
567
Slide 568
568
Slide 569
569
Slide 570
570
Slide 571
571
Slide 572
572
Slide 573
573
Slide 574
574
Slide 575
575
Slide 576
576
Slide 577
577
Slide 578
578
Slide 579
579
Slide 580
580
Slide 581
581
Slide 582
582
Slide 583
583
Slide 584
584
Slide 585
585
Slide 586
586
Slide 587
587
Slide 588
588
Slide 589
589
Slide 590
590
Slide 591
591
Slide 592
592
Slide 593
593
Slide 594
594
Slide 595
595
Slide 596
596
Slide 597
597
Slide 598
598
Slide 599
599
Slide 600
600
Slide 601
601
Slide 602
602
Slide 603
603
Slide 604
604
Slide 605
605
Slide 606
606
Slide 607
607
Slide 608
608
Slide 609
609
Slide 610
610
Slide 611
611
Slide 612
612
Slide 613
613
Slide 614
614
Slide 615
615
Slide 616
616
Slide 617
617
Slide 618
618
Slide 619
619
Slide 620
620
Slide 621
621
Slide 622
622
Slide 623
623
Slide 624
624
Slide 625
625
Slide 626
626
Slide 627
627
Slide 628
628
Slide 629
629
Slide 630
630
Slide 631
631
Slide 632
632
Slide 633
633
Slide 634
634
Slide 635
635
Slide 636
636
Slide 637
637
Slide 638
638
Slide 639
639
Slide 640
640
Slide 641
641
Slide 642
642
Slide 643
643
Slide 644
644
Slide 645
645
Slide 646
646
Slide 647
647
Slide 648
648
Slide 649
649
Slide 650
650
Slide 651
651
Slide 652
652
Slide 653
653
Slide 654
654
Slide 655
655
Slide 656
656
Slide 657
657
Slide 658
658
Slide 659
659
Slide 660
660
Slide 661
661
Slide 662
662
Slide 663
663
Slide 664
664
Slide 665
665
Slide 666
666
Slide 667
667
Slide 668
668
Slide 669
669
Slide 670
670
Slide 671
671
Slide 672
672
Slide 673
673
Slide 674
674
Slide 675
675
Slide 676
676
Slide 677
677
Slide 678
678
Slide 679
679
Slide 680
680
Slide 681
681
Slide 682
682
Slide 683
683
Slide 684
684
Slide 685
685
Slide 686
686
Slide 687
687
Slide 688
688
Slide 689
689
Slide 690
690
Slide 691
691
Slide 692
692
Slide 693
693
Slide 694
694
Slide 695
695
Slide 696
696
Slide 697
697
Slide 698
698
Slide 699
699
Slide 700
700
Slide 701
701
Slide 702
702
Slide 703
703
Slide 704
704
Slide 705
705
Slide 706
706
Slide 707
707
Slide 708
708
Slide 709
709
Slide 710
710
Slide 711
711
Slide 712
712
Slide 713
713
Slide 714
714
Slide 715
715
Slide 716
716
Slide 717
717
Slide 718
718
Slide 719
719
Slide 720
720
Slide 721
721
Slide 722
722
Slide 723
723
Slide 724
724
Slide 725
725
Slide 726
726
Slide 727
727
Slide 728
728
Slide 729
729
Slide 730
730
Slide 731
731
Slide 732
732
Slide 733
733
Slide 734
734
Slide 735
735
Slide 736
736
Slide 737
737
Slide 738
738
Slide 739
739
Slide 740
740
Slide 741
741
Slide 742
742
Slide 743
743
Slide 744
744
Slide 745
745
Slide 746
746
Slide 747
747
Slide 748
748
Slide 749
749
Slide 750
750
Slide 751
751
Slide 752
752
Slide 753
753
Slide 754
754
Slide 755
755
Slide 756
756
Slide 757
757
Slide 758
758
Slide 759
759
Slide 760
760
Slide 761
761
Slide 762
762
Slide 763
763
Slide 764
764
Slide 765
765
Slide 766
766
Slide 767
767
Slide 768
768
Slide 769
769
Slide 770
770
Slide 771
771
Slide 772
772
Slide 773
773
Slide 774
774
Slide 775
775
Slide 776
776
Slide 777
777
Slide 778
778
Slide 779
779
Slide 780
780
Slide 781
781
Slide 782
782
Slide 783
783
Slide 784
784
Slide 785
785
Slide 786
786
Slide 787
787
Slide 788
788
Slide 789
789
Slide 790
790
Slide 791
791
Slide 792
792
Slide 793
793
Slide 794
794
Slide 795
795
Slide 796
796
Slide 797
797
Slide 798
798
Slide 799
799
Slide 800
800
Slide 801
801
Slide 802
802
Slide 803
803
Slide 804
804
Slide 805
805
Slide 806
806
Slide 807
807
Slide 808
808
Slide 809
809
Slide 810
810
Slide 811
811
Slide 812
812
Slide 813
813
Slide 814
814
Slide 815
815
Slide 816
816
Slide 817
817
Slide 818
818
Slide 819
819
Slide 820
820
Slide 821
821
Slide 822
822
Slide 823
823
Slide 824
824
Slide 825
825
Slide 826
826
Slide 827
827
Slide 828
828
Slide 829
829
Slide 830
830
Slide 831
831
Slide 832
832
Slide 833
833
Slide 834
834
Slide 835
835
Slide 836
836
Slide 837
837
Slide 838
838
Slide 839
839
Slide 840
840
Slide 841
841
Slide 842
842
Slide 843
843
Slide 844
844
Slide 845
845
Slide 846
846
Slide 847
847
Slide 848
848
Slide 849
849
Slide 850
850
Slide 851
851
Slide 852
852
Slide 853
853
Slide 854
854
Slide 855
855
Slide 856
856
Slide 857
857
Slide 858
858
Slide 859
859
Slide 860
860
Slide 861
861
Slide 862
862
Slide 863
863
Slide 864
864
Slide 865
865
Slide 866
866
Slide 867
867
Slide 868
868
Slide 869
869
Slide 870
870
Slide 871
871
Slide 872
872
Slide 873
873
Slide 874
874
Slide 875
875
Slide 876
876
Slide 877
877
Slide 878
878
Slide 879
879
Slide 880
880
Slide 881
881
Slide 882
882
Slide 883
883
Slide 884
884
Slide 885
885
Slide 886
886
Slide 887
887
Slide 888
888
Slide 889
889
Slide 890
890
Slide 891
891
Slide 892
892
Slide 893
893
Slide 894
894
Slide 895
895
Slide 896
896
Slide 897
897
Slide 898
898
Slide 899
899
Slide 900
900
Slide 901
901
Slide 902
902
Slide 903
903
Slide 904
904
Slide 905
905
Slide 906
906
Slide 907
907
Slide 908
908
Slide 909
909
Slide 910
910
Slide 911
911
Slide 912
912
Slide 913
913
Slide 914
914
Slide 915
915
Slide 916
916
Slide 917
917
Slide 918
918
Slide 919
919
Slide 920
920
Slide 921
921
Slide 922
922
Slide 923
923
Slide 924
924
Slide 925
925
Slide 926
926
Slide 927
927
Slide 928
928
Slide 929
929
Slide 930
930
Slide 931
931
Slide 932
932
Slide 933
933
Slide 934
934
Slide 935
935
Slide 936
936
Slide 937
937
Slide 938
938
Slide 939
939
Slide 940
940
Slide 941
941
Slide 942
942
Slide 943
943
Slide 944
944
Slide 945
945
Slide 946
946
Slide 947
947
Slide 948
948
Slide 949
949
Slide 950
950
Slide 951
951
Slide 952
952
Slide 953
953
Slide 954
954
Slide 955
955
Slide 956
956
Slide 957
957
Slide 958
958
Slide 959
959
Slide 960
960
Slide 961
961
Slide 962
962
Slide 963
963
Slide 964
964
Slide 965
965
Slide 966
966
Slide 967
967
Slide 968
968
Slide 969
969
Slide 970
970
Slide 971
971
Slide 972
972
Slide 973
973
Slide 974
974
Slide 975
975
Slide 976
976
Slide 977
977
Slide 978
978
Slide 979
979
Slide 980
980
Slide 981
981
Slide 982
982
Slide 983
983
Slide 984
984
Slide 985
985
Slide 986
986
Slide 987
987
Slide 988
988
Slide 989
989
Slide 990
990
Slide 991
991
Slide 992
992
Slide 993
993
Slide 994
994
Slide 995
995
Slide 996
996
Slide 997
997
Slide 998
998
Slide 999
999
Slide 1000
1000
Slide 1001
1001
Slide 1002
1002
Slide 1003
1003
Slide 1004
1004
Slide 1005
1005
Slide 1006
1006
Slide 1007
1007
Slide 1008
1008
Slide 1009
1009
Slide 1010
1010
Slide 1011
1011
Slide 1012
1012
Slide 1013
1013
Slide 1014
1014
Slide 1015
1015
Slide 1016
1016
Slide 1017
1017
Slide 1018
1018
Slide 1019
1019
Slide 1020
1020
Slide 1021
1021
Slide 1022
1022
Slide 1023
1023
Slide 1024
1024
Slide 1025
1025
Slide 1026
1026
Slide 1027
1027
Slide 1028
1028
Slide 1029
1029
Slide 1030
1030
Slide 1031
1031
Slide 1032
1032
Slide 1033
1033
Slide 1034
1034
Slide 1035
1035
Slide 1036
1036
Slide 1037
1037
Slide 1038
1038
Slide 1039
1039
Slide 1040
1040
Slide 1041
1041
Slide 1042
1042
Slide 1043
1043
Slide 1044
1044
Slide 1045
1045
Slide 1046
1046
Slide 1047
1047
Slide 1048
1048
Slide 1049
1049
Slide 1050
1050
Slide 1051
1051
Slide 1052
1052
Slide 1053
1053
Slide 1054
1054
Slide 1055
1055
Slide 1056
1056
Slide 1057
1057
Slide 1058
1058
Slide 1059
1059
Slide 1060
1060
Slide 1061
1061
Slide 1062
1062
Slide 1063
1063
Slide 1064
1064
Slide 1065
1065
Slide 1066
1066
Slide 1067
1067
Slide 1068
1068
Slide 1069
1069
Slide 1070
1070
Slide 1071
1071
Slide 1072
1072
Slide 1073
1073
Slide 1074
1074
Slide 1075
1075
Slide 1076
1076
Slide 1077
1077
Slide 1078
1078
Slide 1079
1079
Slide 1080
1080
Slide 1081
1081
Slide 1082
1082
Slide 1083
1083
Slide 1084
1084
Slide 1085
1085
Slide 1086
1086
Slide 1087
1087
Slide 1088
1088
Slide 1089
1089
Slide 1090
1090
Slide 1091
1091
Slide 1092
1092
Slide 1093
1093
Slide 1094
1094
Slide 1095
1095
Slide 1096
1096
Slide 1097
1097
Slide 1098
1098
Slide 1099
1099
Slide 1100
1100
Slide 1101
1101
Slide 1102
1102
Slide 1103
1103
Slide 1104
1104
Slide 1105
1105
Slide 1106
1106
Slide 1107
1107
Slide 1108
1108
Slide 1109
1109
Slide 1110
1110
Slide 1111
1111
Slide 1112
1112
Slide 1113
1113
Slide 1114
1114
Slide 1115
1115
Slide 1116
1116
Slide 1117
1117
Slide 1118
1118
Slide 1119
1119
Slide 1120
1120
Slide 1121
1121
Slide 1122
1122
Slide 1123
1123
Slide 1124
1124
Slide 1125
1125
Slide 1126
1126
Slide 1127
1127
Slide 1128
1128
Slide 1129
1129
Slide 1130
1130
Slide 1131
1131
Slide 1132
1132
Slide 1133
1133
Slide 1134
1134
Slide 1135
1135
Slide 1136
1136
Slide 1137
1137
Slide 1138
1138
Slide 1139
1139
Slide 1140
1140
Slide 1141
1141
Slide 1142
1142
Slide 1143
1143
Slide 1144
1144
Slide 1145
1145
Slide 1146
1146
Slide 1147
1147
Slide 1148
1148
Slide 1149
1149
Slide 1150
1150
Slide 1151
1151
Slide 1152
1152
Slide 1153
1153
Slide 1154
1154
Slide 1155
1155
Slide 1156
1156
Slide 1157
1157
Slide 1158
1158
Slide 1159
1159
Slide 1160
1160
Slide 1161
1161
Slide 1162
1162
Slide 1163
1163
Slide 1164
1164
Slide 1165
1165
Slide 1166
1166
Slide 1167
1167
Slide 1168
1168
Slide 1169
1169
Slide 1170
1170
Slide 1171
1171
Slide 1172
1172
Slide 1173
1173
Slide 1174
1174
Slide 1175
1175
Slide 1176
1176
Slide 1177
1177
Slide 1178
1178
Slide 1179
1179
Slide 1180
1180
Slide 1181
1181
Slide 1182
1182
Slide 1183
1183
Slide 1184
1184
Slide 1185
1185
Slide 1186
1186
Slide 1187
1187
Slide 1188
1188
Slide 1189
1189
Slide 1190
1190
Slide 1191
1191
Slide 1192
1192
Slide 1193
1193
Slide 1194
1194
Slide 1195
1195
Slide 1196
1196
Slide 1197
1197
Slide 1198
1198
Slide 1199
1199
Slide 1200
1200
Slide 1201
1201
Slide 1202
1202
Slide 1203
1203
Slide 1204
1204
Slide 1205
1205
Slide 1206
1206
Slide 1207
1207
Slide 1208
1208
Slide 1209
1209
Slide 1210
1210
Slide 1211
1211
Slide 1212
1212
Slide 1213
1213
Slide 1214
1214
Slide 1215
1215
Slide 1216
1216
Slide 1217
1217
Slide 1218
1218
Slide 1219
1219
Slide 1220
1220
Slide 1221
1221
Slide 1222
1222
Slide 1223
1223
Slide 1224
1224
Slide 1225
1225
Slide 1226
1226
Slide 1227
1227
Slide 1228
1228
Slide 1229
1229
Slide 1230
1230
Slide 1231
1231
Slide 1232
1232
Slide 1233
1233
Slide 1234
1234
Slide 1235
1235
Slide 1236
1236
Slide 1237
1237
Slide 1238
1238
Slide 1239
1239
Slide 1240
1240
Slide 1241
1241
Slide 1242
1242
Slide 1243
1243
Slide 1244
1244
Slide 1245
1245
Slide 1246
1246
Slide 1247
1247
Slide 1248
1248
Slide 1249
1249
Slide 1250
1250
Slide 1251
1251
Slide 1252
1252
Slide 1253
1253
Slide 1254
1254
Slide 1255
1255
Slide 1256
1256
Slide 1257
1257
Slide 1258
1258
Slide 1259
1259
Slide 1260
1260
Slide 1261
1261
Slide 1262
1262
Slide 1263
1263
Slide 1264
1264
Slide 1265
1265
Slide 1266
1266
Slide 1267
1267
Slide 1268
1268
Slide 1269
1269
Slide 1270
1270
Slide 1271
1271
Slide 1272
1272
Slide 1273
1273
Slide 1274
1274
Slide 1275
1275
Slide 1276
1276
Slide 1277
1277
Slide 1278
1278
Slide 1279
1279
Slide 1280
1280
Slide 1281
1281
Slide 1282
1282
Slide 1283
1283
Slide 1284
1284
Slide 1285
1285
Slide 1286
1286
Slide 1287
1287
Slide 1288
1288
Slide 1289
1289
Slide 1290
1290
Slide 1291
1291
Slide 1292
1292
Slide 1293
1293
Slide 1294
1294
Slide 1295
1295
Slide 1296
1296
Slide 1297
1297
Slide 1298
1298
Slide 1299
1299
Slide 1300
1300
Slide 1301
1301
Slide 1302
1302
Slide 1303
1303
Slide 1304
1304
Slide 1305
1305
Slide 1306
1306
Slide 1307
1307
Slide 1308
1308
Slide 1309
1309
Slide 1310
1310
Slide 1311
1311
Slide 1312
1312
Slide 1313
1313
Slide 1314
1314
Slide 1315
1315
Slide 1316
1316
Slide 1317
1317
Slide 1318
1318
Slide 1319
1319
Slide 1320
1320
Slide 1321
1321
Slide 1322
1322
Slide 1323
1323
Slide 1324
1324
Slide 1325
1325
Slide 1326
1326
Slide 1327
1327
Slide 1328
1328
Slide 1329
1329
Slide 1330
1330
Slide 1331
1331
Slide 1332
1332
Slide 1333
1333
Slide 1334
1334
Slide 1335
1335
Slide 1336
1336
Slide 1337
1337
Slide 1338
1338
Slide 1339
1339
Slide 1340
1340
Slide 1341
1341
Slide 1342
1342
Slide 1343
1343
Slide 1344
1344
Slide 1345
1345
Slide 1346
1346
Slide 1347
1347
Slide 1348
1348
Slide 1349
1349
Slide 1350
1350
Slide 1351
1351
Slide 1352
1352
Slide 1353
1353
Slide 1354
1354
Slide 1355
1355
Slide 1356
1356
Slide 1357
1357
Slide 1358
1358
Slide 1359
1359
Slide 1360
1360
Slide 1361
1361
Slide 1362
1362
Slide 1363
1363
Slide 1364
1364
Slide 1365
1365
Slide 1366
1366
Slide 1367
1367
Slide 1368
1368
Slide 1369
1369
Slide 1370
1370
Slide 1371
1371
Slide 1372
1372
Slide 1373
1373
Slide 1374
1374
Slide 1375
1375
Slide 1376
1376
Slide 1377
1377
Slide 1378
1378
Slide 1379
1379
Slide 1380
1380
Slide 1381
1381
Slide 1382
1382
Slide 1383
1383
Slide 1384
1384
Slide 1385
1385
Slide 1386
1386
Slide 1387
1387
Slide 1388
1388
Slide 1389
1389
Slide 1390
1390
Slide 1391
1391
Slide 1392
1392
Slide 1393
1393
Slide 1394
1394
Slide 1395
1395
Slide 1396
1396
Slide 1397
1397
Slide 1398
1398
Slide 1399
1399
Slide 1400
1400
Slide 1401
1401
Slide 1402
1402
Slide 1403
1403
Slide 1404
1404
Slide 1405
1405
Slide 1406
1406
Slide 1407
1407
Slide 1408
1408
Slide 1409
1409
Slide 1410
1410
Slide 1411
1411
Slide 1412
1412
Slide 1413
1413
Slide 1414
1414
Slide 1415
1415
Slide 1416
1416
Slide 1417
1417
Slide 1418
1418
Slide 1419
1419
Slide 1420
1420
Slide 1421
1421
Slide 1422
1422
Slide 1423
1423
Slide 1424
1424
Slide 1425
1425
Slide 1426
1426
Slide 1427
1427
Slide 1428
1428
Slide 1429
1429
Slide 1430
1430
Slide 1431
1431
Slide 1432
1432
Slide 1433
1433
Slide 1434
1434
Slide 1435
1435
Slide 1436
1436
Slide 1437
1437
Slide 1438
1438
Slide 1439
1439
Slide 1440
1440
Slide 1441
1441
Slide 1442
1442
Slide 1443
1443
Slide 1444
1444
Slide 1445
1445
Slide 1446
1446
Slide 1447
1447
Slide 1448
1448
Slide 1449
1449
Slide 1450
1450
Slide 1451
1451
Slide 1452
1452
Slide 1453
1453
Slide 1454
1454
Slide 1455
1455
Slide 1456
1456
Slide 1457
1457
Slide 1458
1458
Slide 1459
1459
Slide 1460
1460
Slide 1461
1461
Slide 1462
1462
Slide 1463
1463
Slide 1464
1464
Slide 1465
1465
Slide 1466
1466
Slide 1467
1467
Slide 1468
1468
Slide 1469
1469
Slide 1470
1470
Slide 1471
1471
Slide 1472
1472
Slide 1473
1473
Slide 1474
1474
Slide 1475
1475
Slide 1476
1476
Slide 1477
1477
Slide 1478
1478
Slide 1479
1479
Slide 1480
1480
Slide 1481
1481
Slide 1482
1482
Slide 1483
1483
Slide 1484
1484
Slide 1485
1485
Slide 1486
1486
Slide 1487
1487
Slide 1488
1488
Slide 1489
1489
Slide 1490
1490
Slide 1491
1491
Slide 1492
1492
Slide 1493
1493
Slide 1494
1494
Slide 1495
1495
Slide 1496
1496
Slide 1497
1497
Slide 1498
1498
Slide 1499
1499
Slide 1500
1500
Slide 1501
1501
Slide 1502
1502
Slide 1503
1503
Slide 1504
1504
Slide 1505
1505
Slide 1506
1506
Slide 1507
1507
Slide 1508
1508
Slide 1509
1509
Slide 1510
1510
Slide 1511
1511
Slide 1512
1512
Slide 1513
1513
Slide 1514
1514
Slide 1515
1515
Slide 1516
1516
Slide 1517
1517
Slide 1518
1518
Slide 1519
1519
Slide 1520
1520
Slide 1521
1521
Slide 1522
1522
Slide 1523
1523
Slide 1524
1524
Slide 1525
1525
Slide 1526
1526
Slide 1527
1527
Slide 1528
1528
Slide 1529
1529
Slide 1530
1530
Slide 1531
1531
Slide 1532
1532
Slide 1533
1533
Slide 1534
1534
Slide 1535
1535
Slide 1536
1536
Slide 1537
1537
Slide 1538
1538
Slide 1539
1539
Slide 1540
1540
Slide 1541
1541
Slide 1542
1542
Slide 1543
1543
Slide 1544
1544
Slide 1545
1545
Slide 1546
1546
Slide 1547
1547
Slide 1548
1548
Slide 1549
1549
Slide 1550
1550
Slide 1551
1551
Slide 1552
1552
Slide 1553
1553
Slide 1554
1554
Slide 1555
1555
Slide 1556
1556
Slide 1557
1557
Slide 1558
1558
Slide 1559
1559
Slide 1560
1560
Slide 1561
1561
Slide 1562
1562
Slide 1563
1563
Slide 1564
1564
Slide 1565
1565
Slide 1566
1566
Slide 1567
1567
Slide 1568
1568
Slide 1569
1569
Slide 1570
1570
Slide 1571
1571
Slide 1572
1572
Slide 1573
1573
Slide 1574
1574
Slide 1575
1575
Slide 1576
1576
Slide 1577
1577
Slide 1578
1578
Slide 1579
1579
Slide 1580
1580
Slide 1581
1581
Slide 1582
1582
Slide 1583
1583
Slide 1584
1584
Slide 1585
1585
Slide 1586
1586
Slide 1587
1587
Slide 1588
1588
Slide 1589
1589
Slide 1590
1590
Slide 1591
1591
Slide 1592
1592
Slide 1593
1593
Slide 1594
1594
Slide 1595
1595
Slide 1596
1596
Slide 1597
1597
Slide 1598
1598
Slide 1599
1599
Slide 1600
1600
Slide 1601
1601
Slide 1602
1602
Slide 1603
1603
Slide 1604
1604
Slide 1605
1605
Slide 1606
1606
Slide 1607
1607
Slide 1608
1608
Slide 1609
1609
Slide 1610
1610
Slide 1611
1611
Slide 1612
1612
Slide 1613
1613
Slide 1614
1614
Slide 1615
1615
Slide 1616
1616
Slide 1617
1617
Slide 1618
1618
Slide 1619
1619
Slide 1620
1620
Slide 1621
1621
Slide 1622
1622
Slide 1623
1623
Slide 1624
1624
Slide 1625
1625
Slide 1626
1626
Slide 1627
1627
Slide 1628
1628
Slide 1629
1629
Slide 1630
1630
Slide 1631
1631
Slide 1632
1632
Slide 1633
1633
Slide 1634
1634
Slide 1635
1635
Slide 1636
1636
Slide 1637
1637
Slide 1638
1638
Slide 1639
1639
Slide 1640
1640
Slide 1641
1641
Slide 1642
1642
Slide 1643
1643
Slide 1644
1644
Slide 1645
1645
Slide 1646
1646
Slide 1647
1647
Slide 1648
1648
Slide 1649
1649
Slide 1650
1650
Slide 1651
1651
Slide 1652
1652
Slide 1653
1653
Slide 1654
1654
Slide 1655
1655
Slide 1656
1656
Slide 1657
1657
Slide 1658
1658
Slide 1659
1659
Slide 1660
1660
Slide 1661
1661
Slide 1662
1662
Slide 1663
1663
Slide 1664
1664
Slide 1665
1665
Slide 1666
1666
Slide 1667
1667
Slide 1668
1668
Slide 1669
1669
Slide 1670
1670
Slide 1671
1671
Slide 1672
1672
Slide 1673
1673
Slide 1674
1674
Slide 1675
1675
Slide 1676
1676
Slide 1677
1677
Slide 1678
1678
Slide 1679
1679
Slide 1680
1680
Slide 1681
1681
Slide 1682
1682
Slide 1683
1683
Slide 1684
1684
Slide 1685
1685
Slide 1686
1686
Slide 1687
1687
Slide 1688
1688
Slide 1689
1689
Slide 1690
1690
Slide 1691
1691
Slide 1692
1692
Slide 1693
1693
Slide 1694
1694
Slide 1695
1695
Slide 1696
1696
Slide 1697
1697
Slide 1698
1698
Slide 1699
1699
Slide 1700
1700
Slide 1701
1701
Slide 1702
1702
Slide 1703
1703
Slide 1704
1704
Slide 1705
1705
Slide 1706
1706
Slide 1707
1707
Slide 1708
1708
Slide 1709
1709
Slide 1710
1710
Slide 1711
1711
Slide 1712
1712
Slide 1713
1713
Slide 1714
1714
Slide 1715
1715
Slide 1716
1716
Slide 1717
1717
Slide 1718
1718
Slide 1719
1719
Slide 1720
1720
Slide 1721
1721
Slide 1722
1722
Slide 1723
1723
Slide 1724
1724
Slide 1725
1725
Slide 1726
1726
Slide 1727
1727
Slide 1728
1728
Slide 1729
1729
Slide 1730
1730
Slide 1731
1731
Slide 1732
1732
Slide 1733
1733
Slide 1734
1734
Slide 1735
1735
Slide 1736
1736
Slide 1737
1737
Slide 1738
1738
Slide 1739
1739
Slide 1740
1740
Slide 1741
1741
Slide 1742
1742
Slide 1743
1743
Slide 1744
1744
Slide 1745
1745
Slide 1746
1746
Slide 1747
1747
Slide 1748
1748
Slide 1749
1749
Slide 1750
1750
Slide 1751
1751
Slide 1752
1752
Slide 1753
1753
Slide 1754
1754
Slide 1755
1755
Slide 1756
1756
Slide 1757
1757
Slide 1758
1758
Slide 1759
1759
Slide 1760
1760
Slide 1761
1761
Slide 1762
1762
Slide 1763
1763
Slide 1764
1764
Slide 1765
1765
Slide 1766
1766
Slide 1767
1767
Slide 1768
1768
Slide 1769
1769
Slide 1770
1770
Slide 1771
1771
Slide 1772
1772
Slide 1773
1773
Slide 1774
1774
Slide 1775
1775
Slide 1776
1776
Slide 1777
1777
Slide 1778
1778
Slide 1779
1779
Slide 1780
1780
Slide 1781
1781
Slide 1782
1782
Slide 1783
1783
Slide 1784
1784
Slide 1785
1785
Slide 1786
1786
Slide 1787
1787
Slide 1788
1788
Slide 1789
1789
Slide 1790
1790
Slide 1791
1791
Slide 1792
1792
Slide 1793
1793
Slide 1794
1794
Slide 1795
1795
Slide 1796
1796
Slide 1797
1797
Slide 1798
1798
Slide 1799
1799
Slide 1800
1800
Slide 1801
1801
Slide 1802
1802
Slide 1803
1803
Slide 1804
1804
Slide 1805
1805
Slide 1806
1806
Slide 1807
1807
Slide 1808
1808
Slide 1809
1809
Slide 1810
1810
Slide 1811
1811
Slide 1812
1812
Slide 1813
1813
Slide 1814
1814
Slide 1815
1815
Slide 1816
1816
Slide 1817
1817
Slide 1818
1818
Slide 1819
1819
Slide 1820
1820
Slide 1821
1821
Slide 1822
1822
Slide 1823
1823
Slide 1824
1824
Slide 1825
1825
Slide 1826
1826
Slide 1827
1827
Slide 1828
1828
Slide 1829
1829
Slide 1830
1830
Slide 1831
1831
Slide 1832
1832
Slide 1833
1833
Slide 1834
1834
Slide 1835
1835
Slide 1836
1836
Slide 1837
1837
Slide 1838
1838
Slide 1839
1839
Slide 1840
1840
Slide 1841
1841
Slide 1842
1842
Slide 1843
1843
Slide 1844
1844
Slide 1845
1845
Slide 1846
1846
Slide 1847
1847
Slide 1848
1848
Slide 1849
1849
Slide 1850
1850
Slide 1851
1851
Slide 1852
1852
Slide 1853
1853
Slide 1854
1854
Slide 1855
1855
Slide 1856
1856
Slide 1857
1857
Slide 1858
1858
Slide 1859
1859
Slide 1860
1860
Slide 1861
1861
Slide 1862
1862
Slide 1863
1863
Slide 1864
1864
Slide 1865
1865

About This Presentation

The Ring programming language - Version 1.14 documentation


Slide Content

RingDocumentation
Release 1.14
Ring Team
Jan 25, 2021

CONTENTS
1 Applications developed in a few hours
1.1 Quotes about Ring
1.2 FetchStockData Application
1.3 Google API Shortener Application
1.4 Video-Music-Player Application
1.5 Fifteen Puzzle Game
1.6 Analog Clock
1.7 Squares Puzzle Game
1.8 Samples in this book
1.9 Innovative
1.10 Practical
2 Introduction 23
2.1 Motivation
2.2 Ring and other languages
2.3 History
2.4 Features
2.5 License
3 Using Ring Notepad 29
3.1 Ring Notepad - Main Window
3.2 Creating and running your rst Console Application
3.3 Creating and running your rst GUI/WebAssembly/Mobile Application
3.4 Creating and running your rst Web Application
3.5 Creating and running your rst Desktop/Mobile Game
3.6 The Main File in the Project
3.7 The File Menu
3.8 The Edit Menu
3.9 The View Menu
3.10 The Program Menu
3.11 The Browser Menu
3.12 The Tools Menu
3.13 The Distribute Menu
3.14 The Help Menu
4 Getting Started - First Style
4.1 Hello World
4.2 Run the program
4.3 Create Executable File
4.4 Not Case-Sensitive
i

4.5 Multi-Line literals
4.6 Getting Input
4.7 No Explicit End For Statements
4.8 Using ? to print expression then new line
4.9 Writing Comments
5 Getting Started - Second Style
5.1 Hello World
5.2 Run the program
5.3 Create Executable File
5.4 Not Case-Sensitive
5.5 Multi-Line literals
5.6 Getting Input
5.7 No Explicit End For Statements
5.8 Writing Comments
6 Getting Started - Third Style
6.1 Hello World
6.2 Run the program
6.3 Create Executable File
6.4 Not Case-Sensitive
6.5 Multi-Line literals
6.6 Getting Input
6.7 No Explicit End For Statements
6.8 Writing Comments
7 Variables 52
7.1 Dynamic Typing
7.2 Deep Copy
7.3 Implicit Conversion
8 Operators 54
8.1 Arithmetic Operators
8.2 Relational Operators
8.3 Logical Operators
8.4 Bitwise Operators
8.5 Assignment Operators
8.6 Misc Operators
8.7 Operators Precedence
9 Control Structures - First Style
9.1 Branching
9.2 Looping
9.3 Using The Step option with For in
9.4 Using For in to modify lists
9.5 Do Again Loop
9.6 Exit Command
9.7 Exit from two loops
9.8 Loop Command
9.9 Short-circuit evaluation
9.10 Comments about evaluation
10 Control Structures - Second Style
10.1 Branching
10.2 Looping
ii

10.3 Exceptions
11 Control Structures - Third Style
11.1 Branching
11.2 Looping
11.3 Exceptions
12 Getting Input 73
12.1 Give Command
12.2 GetChar() Function
12.3 Input() Function
13 Functions - First Style 75
13.1 Dene Functions
13.2 Call Functions
13.3 Declare parameters
13.4 Send Parameters
13.5 Main Function
13.6 Variables Scope
13.7 Return Value
13.8 Recursion
14 Functions - Second Style 79
14.1 Dene Functions
14.2 Call Functions
14.3 Declare parameters
14.4 Send Parameters
14.5 Main Function
14.6 Variables Scope
14.7 Return Value
14.8 Recursion
15 Functions - Third Style 83
15.1 Dene Functions
15.2 Call Functions
15.3 Declare parameters
15.4 Send Parameters
15.5 Main Function
15.6 Variables Scope
15.7 Return Value
15.8 Recursion
16 Program Structure 87
16.1 Source Code File Sections
16.2 Using Many Source Code Files
16.3 Load Package
16.4 Load Again
17 Lists 90
17.1 Create Lists
17.2 Add Items
17.3 Get List Size
17.4 Delete Item From List
17.5 Get List Item
17.6 Set List Item
iii

17.7 Search
17.8 Sort
17.9 Reverse
17.10 Insert Items
17.11 Nested Lists
17.12 Copy Lists
17.13 First-class lists
17.14 Using Lists during denition
17.15 Passing Lists to Functions
17.16 Access List Items by String Index
17.17 Passing Parameters or Argumnents Using List
17.18 Passing Parameters or Argumnents Using List Array
17.19 Return Parameters as List or Hash Table
17.20 Creating a Multi-Dimensional Array using List
17.21 Swap Items
18 Strings 102
18.1 String Literals
18.2 Get String Length
18.3 Convert Letters Case
18.4 Access String Letters
18.5 Left() Function
18.6 Right() Function
18.7 Trim() Function
18.8 Copy() Function
18.9 Lines() Function
18.10 Substr() Function
18.11 Find substring
18.12 Get substring from position to end
18.13 Get Number of Characters From Position
18.14 Transform Substring To Another Substring
18.15 strcmp() Function
18.16 str2list() and list2str() Functions
18.17 Merge binary characters
19 Date and Time 109
19.1 Clock() Function
19.2 ClocksPerSecond() Function
19.3 Time() Function
19.4 Date() Function
19.5 TimeList() Function
19.6 AddDays() Function
19.7 DiffDays() Function
19.8 EpochTime() Function
20 Check Data Type and Conversion
20.1 Check Data Type
20.2 IsString() Function
20.3 IsNumber() Function
20.4 IsList() Function
20.5 Type() Function
20.6 IsNULL() Function
20.7 Check Character
20.8 IsAlNum() Function
iv

20.9 IsAlpha() Function
20.10 IsCntrl() Function
20.11 IsDigit() Function
20.12 IsGraph() Function
20.13 IsLower() Function
20.14 IsPrint() Function
20.15 IsPunct() Function
20.16 IsSpace() Function
20.17 IsUpper() Function
20.18 IsXdigit() Function
20.19 Conversion
20.20 Number() Function
20.21 String() Function
20.22 Ascii() Function
20.23 Char() Function
20.24 Hex() Function
20.25 Dec() Function
20.26 Str2hex() Function
20.27 Hex2str() Function
21 Mathematical Functions 123
21.1 List of functions
21.2 Example
21.3 Random() Function
21.4 SRandom() Function
21.5 Unsigned() Function
21.6 Decimals() Functions
21.7 Using _ in numbers
21.8 Using f after numbers
21.9 Using Hexadecimal Numbers
22 Files 129
22.1 Read() Function
22.2 Write() Function
22.3 Dir() Function
22.4 Rename() Function
22.5 Remove() Function
22.6 Fopen() Function
22.7 Fclose() Function
22.8 Fush() Function
22.9 Freopen() Function
22.10 Temple() Function
22.11 Tempname() Function
22.12 Fseek() Function
22.13 Ftell() Function
22.14 Rewind() Function
22.15 Fgetpos() Function
22.16 Fsetpos() Function
22.17 Clearerr() Function
22.18 Feof() Function
22.19 Ferror() Function
22.20 Perror() Function
22.21 Fgetc() Function
22.22 Fgets() Function
v

22.23 Fputc() Function
22.24 Fputs() Function
22.25 Ungetc() Function
22.26 Fread() Function
22.27 Fwrite() Function
22.28 Fexists() Function
22.29 Direxists() Function
22.30 Getpathtype() Function
22.31 Example
22.32 Numbers and Bytes
23 System Functions 141
23.1 System() Function
23.2 SysGet() Function
23.3 SysSet() Function
23.4 SysUnset() Function
23.5 IsMSDOS() Function
23.6 IsWindows() Function
23.7 IsWindows64() Function
23.8 IsUnix() Function
23.9 IsMacOSX() Function
23.10 IsLinux() Function
23.11 IsFreeBSD() Function
23.12 IsAndroid() Function
23.13 Example
23.14 GetArch() Function
23.15 Windowsnl() Function
23.16 Get Command Line Arguments
23.17 Get Active Source File Name
23.18 PrevFileName() Function
23.19 CurrentDir() Function
23.20 ExeFileName() Function
23.21 ChDir() Function
23.22 ExeFolder() Function
23.23 Version() Function
23.24 Shutdown() Function
23.25 NofProcessors() Function
24 Eval() and Debugging 149
24.1 Try/Catch/Done
24.2 Eval() Function
24.3 Raise() Function
24.4 Assert() Function
25 Demo Programs 152
25.1 Language Shell
25.2 Main Menu
26 ODBC Functions 156
26.1 odbc_init() Function
26.2 odbc_drivers() Function
26.3 odbc_datasources() Function
26.4 odbc_close() Function
26.5 Print List of ODBC Drivers
26.6 Print List of ODBC Data Sources
vi

26.7 odbc_connect() Function
26.8 odbc_disconnect() Function
26.9 Open and Close Connection
26.10 odbc_execute() Function
26.11 odbc_colcount() Function
26.12 odbc_fetch() Function
26.13 odbc_getdata() Function
26.14 Execute Query and Print Result
26.15 odbc_tables() Function
26.16 odbc_columns() Function
26.17 odbc_autocommit() Function
26.18 odbc_commit() Function
26.19 odbc_rollback() Function
26.20 Transactions and Using Commit and Rollback
26.21 Save and Restore images
27 MySQL Functions 165
27.1 MySQL_Info() Function
27.2 MySQL_Init() Function
27.3 MySQL_Error() Function
27.4 MySQL_Connect() Function
27.5 MySQL_Close() Function
27.6 MySQL_Query() Function
27.7 Create Database
27.8 Create Table and Insert Data
27.9 MySQL_Insert_ID() Function
27.10 MySQL_Result() Function
27.11 MySQL_Next_Result() Function
27.12 Print Query Result
27.13 MySQL_Columns() Function
27.14 MySQL_Result2() Function
27.15 MySQL_Escape_String() Function
27.16 Save Image inside the database
27.17 Restore Image From The Database
27.18 MySQL_AutoCommit() Function
27.19 MySQL_Commit() Function
27.20 MySQL_Rollback() Function
27.21 Transaction Example
28 SQLite Functions 175
28.1 sqlite_init() function
28.2 sqlite_open() function
28.3 sqlite_execute() function
28.4 sqlite_close() function
28.5 Example
29 PostgreSQL Functions 178
29.1 Loading the library
29.2 Examples
29.3 RingPostgreSQL Constants
29.4 RingPostgreSQL Functions
30 Security and Internet Functions
30.1 MD5() Function
30.2 SHA1() Function
vii

30.3 SHA256() Function
30.4 SHA512() Function
30.5 SHA384() Function
30.6 SHA224() Function
30.7 Encrypt() Function
30.8 Decrypt() Function
30.9 Encryption and Decryption Example
30.10 File Hash
30.11 Randbytes() Function
30.12 Large Files Hash
30.13 Download() Function
30.14 SendEmail() Function
31 Object Oriented Programming (OOP)
31.1 Classes and Objects
31.2 Access Objects Using Braces
31.3 Composition
31.4 Setter and Getter
31.5 Private Attributes and Methods
31.6 Operator Overloading
31.7 Inheritance
31.8 Dynamic Attributes
31.9 Packages
31.10 Printing Objects
31.11 Find() and List of Objects
31.12 Sort() and List of Objects
31.13 Using Self.Attribute and Self.Method()
31.14 Using This.Attribute and This.Method()
31.15 Using This in the class region as Self
31.16 Default value for object attributes
32 Functional Programming 210
32.1 Pure Functions
32.2 First-class Functions
32.3 Higher-order Functions
32.4 Anonymous and Nested Functions
32.5 Equality of functions
33 Reection and Meta-programming
33.1 locals() Function
33.2 globals() Function
33.3 functions() Function
33.4 cfunctions() Function
33.5 islocal() Function
33.6 isglobal() Function
33.7 isfunction() Function
33.8 iscfunction() Function
33.9 packages() Function
33.10 ispackage() Function
33.11 classes() Function
33.12 isclass() Function
33.13 packageclasses() Function
33.14 ispackageclass() Function
33.15 classname() Function
viii

33.16 objectid() Function
33.17 isobject() Function
33.18 attributes() Function
33.19 methods() Function
33.20 isattribute() Function
33.21 isprivateattribute() Function
33.22 ismethod() Function
33.23 isprivatemethod() Function
33.24 addattribute() Function
33.25 addmethod() Function
33.26 getattribute() function
33.27 setattribute() function
33.28 mergemethods() Function
33.29 packagename() Function
34 Declarative Programming using Nested Structures
34.1 Creating Objects inside Lists
34.2 Composition and Returning Objects and Lists by Reference
34.3 Executing code after the end of object access
34.4 Declarative Programming on the top of Object-Oriented
34.5 More beautiful Code
35 Natural Language Programming
35.1 History
35.2 Example
35.3 Change the Ring Keyword `And'
35.4 Change the Ring Operator `+'
35.5 Change the `=' operator to `is'
35.6 Using Eval() with our Natural Code
35.7 BraceStart and BraceEnd Methods
35.8 BraceExprEval Method
35.9 Real Natural Code
35.10 BraceError() Method
35.11 Clean Natural Code
36 Using the Natural Library
36.1 Natural Library - Demo Program
36.2 Dening Commands
36.3 Natural Library - Operators
36.4 Dening commands using classes
37 Scope Rules for Variables and Attributes
37.1 Three Scopes
37.2 Dening Variables and Variables Access
37.3 How Ring nd the variable?
37.4 Using Object.Attribute
37.5 The Self Object
37.6 How Ring Dene Variables and Attributes
37.7 Conict between Global Variables and Class Attributes
37.8 Conict between Class Attributes and Local Variables
37.9 Using Braces to access objects inside Class Methods
37.10 Accessing the class attributes from braces inside class methods
37.11 Creating a Class for each Window in GUI applications
37.12 Conict between self inside braces and self in the class region
37.13 Using braces to escape from the current object scope
ix

37.14 The For Loops uses the local scope
37.15 Summary of Scope Rules
38 Scope Rules for Functions and Methods
38.1 How Ring nd the Functions and Methods?
38.2 Example about Sharing Names between Functions and Methods
38.3 Calling a function sharing the name with a method in the current class
39 Syntax Flexibility 280
39.1 Change Language Keywords
39.2 Change Language Operators
39.3 Load Syntax Files
39.4 Using “()” around the function parameters
39.5 Using Semi-colon after and between statements
39.6 Using $ and @ in the start of the variable name
39.7 Using the `elseif' keyword as `but' in if statement
39.8 Using the `else' keyword as `other' in switch statement
39.9 Using the `end' keyword in different control structures
39.10 Using braces to start and end different control structures
39.11 Using `put' and `get' as `see' and `give'
39.12 Using `case' as `on' in switch statements
39.13 Using `def' as `func' in functions/methods denition
39.14 Using braces { } in Packages/Classes/Functions
39.15 Using `end' keyword after Packages/Classes/Functions
39.16 Using `endpackage'/'endclass'/'endfunc' keywords after Packages/Classes/Functions
39.17 Ignore new lines after keywords
40 Introduction to the Type Hints Library
40.1 Why Type Hints?
40.2 Example
40.3 User Types
40.4 Using Types inside Code
40.5 Rules
41 The Trace Library and the Interactive Debugger
41.1 Loading the Trace library
41.2 Trace All Events
41.3 Trace control ow between functions
41.4 Pass Error
41.5 Interactive Debugger
41.6 Execute Program Line by Line
41.7 BreakPoint
41.8 Disable BreakPoints
41.9 Using the Interactive Debugger
42 Embedding Ring in Ring 299
42.1 Embedding Ring in Ring without sharing the State
42.2 Serial Execution of Programs
42.3 ring_state_setvar()
42.4 ring_state_new() and ring_state_mainle()
42.5 Runtime Errors when Embedding Ring in Ring
42.6 ring_state_letokens() function
43 Stdlib Functions 305
43.1 Puts() function
x

43.2 Print() function
43.3 Print2Str() Function
43.4 GetString() function
43.5 GetNumber() function
43.6 AppPath() function
43.7 JustFilePath() function
43.8 JustFileName() function
43.9 Value() function
43.10 Times() function
43.11 Map() function
43.12 Filter() function
43.13 Split() function
43.14 SplitMany() function
43.15 Capitalized() function
43.16 IsSpecial() function
43.17 IsVowel() function
43.18 LineCount() function
43.19 Factorial() function
43.20 Fibonacci() function
43.21 IsPrime() function
43.22 Sign() function
43.23 List2File() function
43.24 File2List() function
43.25 StartsWith() function
43.26 EndsWith() function
43.27 GCD() function
43.28 LCM() function
43.29 SumList() function
43.30 ProdList() function
43.31 EvenOrOdd() function
43.32 Factors() function
43.33 IsPalindrome() function
43.34 IsLeapYear() function
43.35 BinaryDigits() function
43.36 MatrixMulti() function
43.37 MatrixTrans() function
43.38 DayOfWeek() function
43.39 Permutation() function
43.40 ReadLine() function
43.41 SubString() function
43.42 ChangeString() function
43.43 Sleep() function
43.44 IsMainSourceFile() function
43.45 MakeDir() function
43.46 Fsize() function
43.47 TrimAll() function
43.48 TrimLeft() function
43.49 TrimRight() function
43.50 EpochTime() function
43.51 SystemCmd() Function
43.52 ListAllFiles() Function
43.53 SystemSilent() Function
43.54 OSCreateOpenFolder() Function
43.55 OSCopyFolder() Function
xi

43.56 OSDeleteFolder() Function
43.57 OSCopyFile() Function
43.58 OSDeleteFile() Function
43.59 OSRenameFile() Function
43.60 List2Code() Function
43.61 Str2ASCIIList()
43.62 ASCIIList2Str()
43.63 IsListContainsItems()
43.64 IsBetween()
43.65 TimeInfo()
44 Stdlib Classes 326
44.1 StdBase Class
44.2 String Class
44.3 List Class
44.4 Stack Class
44.5 Queue Class
44.6 HashTable Class
44.7 Tree Class
44.8 Math Class
44.9 DateTime Class
44.10 File Class
44.11 System Class
44.12 Debug Class
44.13 DataType Class
44.14 Conversion Class
44.15 ODBC Class
44.16 MySQL Class
44.17 SQLite Class
44.18 PostgreSQL Class
44.19 Security Class
44.20 Internet Class
45 Desktop, WebAssembly and Mobile Development using RingQt
45.1 The First GUI Application
45.2 The Events Loop
45.3 Using Layout
45.4 Using the QTextEdit Class
45.5 Using the QListWidget Class
45.6 Using QTreeView and QFileSystemModel
45.7 Using QTreeWidget and QTreeWidgetItem
45.8 Using QComboBox Class
45.9 Creating Menubar
45.10 Context Menu
45.11 Creating Toolbar
45.12 Creating StatusBar
45.13 Using QDockWidget
45.14 Using QTabWidget
45.15 Using QTableWidget
45.16 Using QProgressBar
45.17 Using QSpinBox
45.18 Using QSlider
45.19 Using QDateEdit
45.20 Using QDial
xii

45.21 Using QWebView
45.22 Using QCheckBox
45.23 Using QRadioButton and QButtonGroup
45.24 Adding Hyperlink to QLabel
45.25 QVideoWidget and QMediaPlayer
45.26 Using QFrame
45.27 Display Image using QLabel
45.28 Menubar and StyleSheet Example
45.29 QLineEdit Events and QMessageBox
45.30 Other Widgets Events
45.31 Using the QTimer Class
45.32 Using QProgressBar and Timer
45.33 Display Scaled Image using QLabel
45.34 Using the QFileDialog Class
45.35 Drawing using QPainter
45.36 Printing using QPrinter
45.37 Using QPrintPreviewDialog
45.38 Creating More than one Window
45.39 Playing Sound
45.40 Using the QColorDialog Class
45.41 Using qLCDNumber Class
45.42 Movable Label Example
45.43 QMessagebox Example
45.44 Using QInputDialog Class
45.45 Dialog Functions
45.46 KeyPress and Mouse Move Events
45.47 Moving Objects using the Mouse
45.48 Inheritance from GUI Classes
45.49 Using QDesktopWidget Class
45.50 Rotate Text
45.51 Change Focus
45.52 Regular Expressions
45.53 Simple Client and Server Example
45.54 Dynamic Objects
45.55 Weight History Application
45.56 Notepad Application
45.57 The Cards Game
45.58 Classes and their Methods to use the default events
45.59 Methods to use Events with Events Filter
45.60 The Difference between Qt and RingQt
45.61 RingQt Classes and their Qt Documentation
45.62 New Classes names - Index Start from 1
45.63 Creating Reports using the WebLib and the GUILib
46 Using the Form Designer 460
46.1 The Designer Windows
46.2 The Toolbox
46.3 The Properties
46.4 Running Forms
46.5 Events Code
46.6 Keyboard Shortcuts
46.7 Menubar Designer
46.8 Window Flags
46.9 Entering Items
xiii

46.10 Using Layouts
46.11 More Samples and Tests
47 Graphics Programming using RingQt3D
47.1 Drawing Cube
47.2 Drawing Torus
47.3 Drawing Sphere
47.4 Drawing Cylinder
47.5 Drawing Cone
47.6 Drawing Plane
47.7 Texture
47.8 Key Press
47.9 Object Picker
47.10 Frame Action
47.11 Text 2D
47.12 Extruded Text
47.13 Model
47.14 Model Texture
47.15 Draw Ofce
47.16 Many Objects
47.17 Camera
47.18 Scence
48 Objects Library for RingQt Application
48.1 Library Usage with GUI Applications
48.2 Example
48.3 openWindowAndLink() Function
48.4 openWindowInPackages() Function
48.5 Objects Library Source Code
49 Multi-language Applications
49.1 Using String2Constant
49.2 Form Designer Translation
49.3 Forms Translation
50 Building RingQt Applications for Mobile
50.1 Download Requirements
50.2 Update the Android SDK
50.3 Install Qt for Android
50.4 Using Ring2EXE
50.5 The Qt project for your Ring application
50.6 Comments about developing for Android using RingQt
51 Building RingQt Applications for WebAssembly
51.1 Download Requirements
51.2 Using Ring2EXE
51.3 The Qt project for your Ring application
51.4 Comments about developing for WebAssembly using RingQt
51.5 Dialogs
51.6 Online Applications
52 Web Development (CGI Library)
52.1 Congure the Apache web server
52.2 Setting the shebang line
52.3 Grant Ring les execution permission
xiv

52.4 Ring CGI Hello World Program
52.5 Hello World Program using the Web Library
52.6 Web Library Features
52.7 HTTP Get Example
52.8 HTTP POST Example
52.9 Upload Files
52.10 Cookies
52.11 URL Encode
52.12 Templates
52.13 HTML Special Characters
52.14 Hash Functions
52.15 Random Image
52.16 HTML Lists
52.17 HTML Tables
52.18 Gradient
52.19 Generating Pages using Objects
52.20 HtmlPage Class
52.21 Using Bootstrap Library using Functions
52.22 Using Bootstrap Library using Objects
52.23 CRUD Example using MVC
52.24 Users registration and Login
52.25 Database, ModelBase & ControllerBase classes
52.26 WebLib API
52.27 Application Class
52.28 Page Class
52.29 ScriptFunctions Class
52.30 StyleFunctions Class
52.31 WebPage Class
52.32 HtmlPage Class
53 Deploying Web Applications in the Cloud
53.1 Introduction
53.2 Usage
53.3 Ring source code les and permissions
53.4 Hello World program
53.5 Application Database
53.6 Deploying after updates
53.7 Local Tests
54 Graphics and 2D Games programming using RingAllegro
54.1 Drawing, Animation and Input
54.2 Using TrueType Fonts
54.3 Playing Sound Files
54.4 Scaling and Rotating Images
54.5 Display Transparent Image
54.6 Using Threads
55 Demo Project - Game Engine for 2D Games
55.1 Project Layers
55.2 Graphics Library bindings
55.3 Interface to graphics library
55.4 Game Engine Classes
55.5 Games Layer
55.6 Game Class
xv

55.7 GameObject Class
55.8 Sprite Class
55.9 Text Class
55.10 Animate Class
55.11 Sound Class
55.12 Map Class
55.13 Using the Game Engine - Creating the Game Window
55.14 Using the Game Engine - Drawing Text
55.15 Using the Game Engine - Moving Text
55.16 Using the Game Engine - Playing Sound
55.17 Using the Game Engine - Animation
55.18 Using the Game Engine - Animation and Functions
55.19 Using the Game Engine - Sprite - Automatic Movement using Keyboard
55.20 Using the Game Engine - Sprite - Keypress event
55.21 Using the Game Engine - Sprite - Mouse event
55.22 Using the Game Engine - Sprite - State event
55.23 Using the Game Engine - Animate - Events
55.24 Using the Game Engine - Map
55.25 Using the Game Engine - Map Events
55.26 Using the Game Engine - Object and Drawing
55.27 Stars Fighter Game
55.28 Flappy Bird 3000 Game
55.29 Super Man 2016 Game
56 Building Games For Android
56.1 Download Requirements and Update the Android SDK
56.2 Project Folder
56.3 Building the project
57 Developing Games using RingRayLib
57.1 Introduction
57.2 Basic Window
57.3 Input Keys
57.4 Input Mouse
57.5 3D Camera
57.6 3D Camera Free
57.7 Mouse Wheel
57.8 Input Multi-touch
57.9 Camera First Person
57.10 3D Picking
57.11 Full Screen
57.12 Two Cubes
57.13 Basic Shapes
57.14 Draw Ring
57.15 Bezier Lines
57.16 Collision Area
57.17 Following Eyes
57.18 Colors Palette
57.19 Rectangle Scaling
57.20 Music Playing
57.21 Sound Loading
57.22 Image Drawing
57.23 Image Generation
57.24 Texture Source
xvi

57.25 Geometric Shapes
57.26 Cubic Map
57.27 Functions
58 Using RingOpenGL and RingFreeGLUT for 3D Graphics
58.1 Samples Source (Authors)
58.2 What is RingOpenGL?
58.3 What is RingFreeGLUT?
58.4 The First Window using RingFreeGLUT
58.5 Drawing using RingOpenGL
58.6 The First Triangle
58.7 Window Resize Event
58.8 Triangle Rotation
58.9 Keyboard Events and Colors
58.10 The Camera
58.11 Mouse Events
58.12 Menu Events
58.13 Using Fonts
58.14 Frames Per Second
58.15 Make a Cube using RingOpenGL and RingFreeGLUT
59 Using RingOpenGL and RingAllegro for 3D Graphics
59.1 3D Cube and Texture
59.2 Many Cubes
59.3 TicTacToe 3D Game
59.4 More 3D Samples
60 The Gold Magic 800 Game
60.1 The Game Story
60.2 How to play?
60.3 What will you learn?
60.4 Screen Shots
60.5 Source Code
61 RingTilengine Extension 784
61.1 Getting Started
61.2 More Samples
61.3 Using LibSDL and Tilengine
61.4 Reference
62 Performance Tips 818
62.1 Introduction
62.2 Creating Lists
62.3 Arithmetic Operations
62.4 Using len() and For Loops
62.5 Calling Functions and Methods
63 Command Line Options 824
63.1 Printing Tokens
63.2 Printing Rules
63.3 Printing Intermediate Code
63.4 Printing Final Intermediate Code
63.5 CGI Support
63.6 No Run
63.7 Printing Instruction Operation Code
xvii

63.8 Performance
63.9 Generate Object File
63.10 Generate Embedded Object File
64 Distributing Ring Applications (Manual)
64.1 Distributing Applications for Microsoft Windows
64.2 Protecting the Source Code
64.3 The les ring.ring and ring.ringo
64.4 Creating Windows Installer
64.5 Using C/C++ Compiler and Linker
64.6 Distributing Applications and Games for Mobile
65 Distributing Ring Applications using Ring2EXE
65.1 Using Ring2EXE
65.2 How Ring2EXE works?
65.3 Example
65.4 Options
65.5 Building standalone console application
65.6 Distributing RingAllegro Applications
65.7 Distributing RingQt Applications
65.8 Distributing Applications for Mobile using RingQt
65.9 Distributing Applications for WebAssembly using RingQt
65.10 Building the Cards Game for Mobile using RingQt
65.11 Building the Weight History Application for Mobile using RingQt
65.12 Building the Form Designer for Mobile using RingQt
65.13 Creating the Qt resource le using Folder2qrc
65.14 Important Information about Ring2EXE
66 The Ring Package Manager (RingPM)
66.1 Features
66.2 Discovering Packages
66.3 Updating the RingPM Registry
66.4 Installing Packages
66.5 Printing List of Installed Packages
66.6 Run Package
66.7 Update Package
66.8 Remove Package
66.9 Deleting All Packages
66.10 Creating New Package
66.11 The Package Description File
66.12 Create Package in the Current Folder
66.13 The RingPM Registry File
67 Using ZeroLib 862
67.1 Introduction
67.2 Z() function
67.3 ZeroBasedList Class
67.4 ZeroBasedString Class
67.5 Source Code
68 FoxRing Functions Reference
68.1 FoxRing functions
68.2 frAbs() function
68.3 frAsc() function
68.4 frAddBs() function
xviii

68.5 frAt() function
68.6 frAtC() function
68.7 frChr() function
68.8 frEmpty() function
68.9 frFile() function
68.10 frFileToStr() function
68.11 frStr() function
68.12 frSetIfEmpty() function
68.13 frSpace() function
68.14 frInList() function
68.15 frForcePath() function
68.16 frAllTrim() function
68.17 frLTrim() function
68.18 frJustDrive() function
68.19 frJustExt() function
68.20 frJustStem() function
68.21 frRTrim() function
68.22 frJustPath() function
68.23 frForceExt() function
68.24 frALines() function
68.25 frJustFName() function
68.26 frPadL() function
68.27 frPadR() function
68.28 frProper() function
68.29 frReplicate() function
68.30 frLen() function
68.31 frStuff() function
68.32 frSubStr() function
68.33 frStrTran() function
68.34 frListToString() function
68.35 frInt() function
68.36 frStringToList() function
68.37 frIIf() function
68.38 frVal() function
68.39 frBetween() function
68.40 frSetSeparatorTo() function
68.41 frTransform() function
68.42 frVarType() function
68.43 Example
69 BigNumber Library 880
69.1 Loading the library
69.2 Examples
69.3 BigNumber Functions
69.4 BigNumber Class
69.5 Library Source Code
70 Using RingLibCurl 883
70.1 Get Request
70.2 Post Request
70.3 Facebook Login
70.4 Save Output to String
70.5 Get Stock Data From Yahoo
xix

71 RingLibCurl Functions Reference
71.1 Introduction
71.2 Reference
72 RingSockets Extension 896
72.1 TCP Server
72.2 TCP Client
72.3 Functions
72.4 Constants
73 Threads Extension 898
73.1 Creating Threads
73.2 More Examples
73.3 Reference
74 RingLibUI Extension 902
74.1 Hello World
74.2 Say Hello
74.3 Control Gallery
74.4 Say Something
74.5 Using the Menubar
74.6 Drawing Sample
74.7 Draw Gradient
74.8 Histogram
74.9 Text Drawing
74.10 More Drawing Samples
75 Using RingZip 944
75.1 Create Zip File
75.2 Extract Zip File
75.3 Print Files in Zip le
75.4 Using RingZip Classes
75.5 Zip Class Reference
75.6 ZipEntry Class Reference
76 RingLibZip Functions Reference
76.1 Introduction
76.2 Reference
77 RingMurmurHash Functions Reference
77.1 MurmurHash1 functions
77.2 MurmurHash2 functions
77.3 MurmurHash3 functions
77.4 Example
78 RingConsoleColors Functions Reference
78.1 Introduction
78.2 Reference
79 RingAllegro Functions Reference
79.1 Introduction
79.2 Reference
80 Using RingLibSDL 972
80.1 Create Window
xx

80.2 Display Image
80.3 Switch between two images
80.4 Draw Rectangle
80.5 Display PNG Images
80.6 Use TTF Fonts
80.7 Display Transparent Images
80.8 Close Window Event
80.9 Mouse Events
80.10 Play Sound
81 RingLibSDL Functions Reference
81.1 Introduction
81.2 Reference
82 Using RingLibuv 1004
82.1 First Application using RingLibuv
82.2 The Events Loop
82.3 Server Example
82.4 Client Example
82.5 Server Example Using Classes
82.6 Client Example Using Classes
82.7 Threads Example
82.8 Threads Example - Using Classes
83 RingLibuv Functions Reference
83.1 Introduction
83.2 Reference
84 RingFreeGLUT Functions Reference
84.1 Introduction
84.2 Reference
85 RingStbImage Functions Reference
85.1 Introduction
85.2 Constants
85.3 Functions
86 RingOpenGL (OpenGL 3.2) Functions Reference
86.1 Introduction
86.2 Reference
87 RingQt Classes Reference
87.1 AbstractAxis Class
87.2 AbstractBarSeries Class
87.3 CodeEditor Class
87.4 QAbstractAspect Class
87.5 QAbstractButton Class
87.6 QAbstractCameraController Class
87.7 QAbstractItemView Class
87.8 QAbstractPrintDialog Class
87.9 QAbstractScrollArea Class
87.10 QAbstractSeries Class
87.11 QAbstractSlider Class
87.12 QAbstractSocket Class
87.13 QAbstractSpinBox Class
xxi

87.14 QAction Class
87.15 QAllEvents Class
87.16 QApp Class
87.17 QAreaLegendMarker Class
87.18 QAreaSeries Class
87.19 QAspectEngine Class
87.20 QAxBase Class
87.21 QAxObject Class
87.22 QAxWidget Class
87.23 QAxWidget2 Class
87.24 QBarCategoryAxis Class
87.25 QBarLegendMarker Class
87.26 QBarSeries Class
87.27 QBarSet Class
87.28 QBitmap Class
87.29 QBluetoothAddress Class
87.30 QBluetoothDeviceDiscoveryAgent Class
87.31 QBluetoothDeviceInfo Class
87.32 QBluetoothHostInfo Class
87.33 QBluetoothLocalDevice Class
87.34 QBluetoothServer Class
87.35 QBluetoothServiceDiscoveryAgent Class
87.36 QBluetoothServiceInfo Class
87.37 QBluetoothSocket Class
87.38 QBluetoothTransferManager Class
87.39 QBluetoothTransferReply Class
87.40 QBluetoothTransferRequest Class
87.41 QBluetoothUuid Class
87.42 QBoxLayout Class
87.43 QBoxPlotLegendMarker Class
87.44 QBoxPlotSeries Class
87.45 QBoxSet Class
87.46 QBrush Class
87.47 QBuffer Class
87.48 QButtonGroup Class
87.49 QByteArray Class
87.50 QCalendarWidget Class
87.51 QCamera Class
87.52 QCameraImageCapture Class
87.53 QCameraLens Class
87.54 QCameraSelector Class
87.55 QCameraViewnder Class
87.56 QCandlestickLegendMarker Class
87.57 QCandlestickModelMapper Class
87.58 QCandlestickSeries Class
87.59 QCandlestickSet Class
87.60 QCategoryAxis Class
87.61 QChar Class
87.62 QChart Class
87.63 QChartView Class
87.64 QCheckBox Class
87.65 QChildEvent Class
87.66 QClipboard Class
87.67 QColor Class
xxii

87.68 QColorDialog Class
87.69 QComboBox Class
87.70 QCompleter Class
87.71 QCompleter2 Class
87.72 QCompleter3 Class
87.73 QConeGeometry Class
87.74 QConeMesh Class
87.75 QCoreApplication Class
87.76 QCuboidMesh Class
87.77 QCullFace Class
87.78 QCursor Class
87.79 QCylinderMesh Class
87.80 QDate Class
87.81 QDateEdit Class
87.82 QDateTime Class
87.83 QDateTimeAxis Class
87.84 QDateTimeEdit Class
87.85 QDepthTest Class
87.86 QDesktopServices Class
87.87 QDesktopWidget Class
87.88 QDial Class
87.89 QDialog Class
87.90 QDiffuseSpecularMaterial Class
87.91 QDir Class
87.92 QDirModel Class
87.93 QDockWidget Class
87.94 QDrag Class
87.95 QDragEnterEvent Class
87.96 QDragLeaveEvent Class
87.97 QDragMoveEvent Class
87.98 QDropEvent Class
87.99 QEffect Class
87.100QEntity Class
87.101QEvent Class
87.102QExtrudedTextMesh Class
87.103QFile Class
87.104QFile2 Class
87.105QFileDevice Class
87.106QFileDialog Class
87.107QFileInfo Class
87.108QFileSystemModel Class
87.109QFirstPersonCameraController Class
87.110QFont Class
87.111QFontDialog Class
87.112QFontMetrics Class
87.113QForwardRenderer Class
87.114QFrame Class
87.115QFrame2 Class
87.116QFrame3 Class
87.117QFrameAction Class
87.118QGeoAddress Class
87.119QGeoAreaMonitorInfo Class
87.120QGeoAreaMonitorSource Class
87.121QGeoCircle Class
xxiii

87.122QGeoCoordinate Class
87.123QGeoPositionInfo Class
87.124QGeoPositionInfoSource Class
87.125QGeoRectangle Class
87.126QGeoSatelliteInfo Class
87.127QGeoSatelliteInfoSource Class
87.128QGeoShape Class
87.129QGoochMaterial Class
87.130QGradient Class
87.131QGraphicsScene Class
87.132QGraphicsVideoItem Class
87.133QGraphicsView Class
87.134QGridLayout Class
87.135QGuiApplication Class
87.136QHBarModelMapper Class
87.137QHBoxLayout Class
87.138QHBoxPlotModelMapper Class
87.139QHCandlestickModelMapper Class
87.140QHPieModelMapper Class
87.141QHXYModelMapper Class
87.142QHeaderView Class
87.143QHorizontalBarSeries Class
87.144QHorizontalPercentBarSeries Class
87.145QHorizontalStackedBarSeries Class
87.146QHostAddress Class
87.147QHostInfo Class
87.148QIODevice Class
87.149QIcon Class
87.150QImage Class
87.151QInputAspect Class
87.152QInputDialog Class
87.153QJsonArray Class
87.154QJsonDocument Class
87.155QJsonObject Class
87.156QJsonParseError Class
87.157QJsonValue Class
87.158QKeySequence Class
87.159QLCDNumber Class
87.160QLabel Class
87.161QLayout Class
87.162QLegend Class
87.163QLegendMarker Class
87.164QLineEdit Class
87.165QLineSeries Class
87.166QLinearGradient Class
87.167QListView Class
87.168QListWidget Class
87.169QListWidgetItem Class
87.170QLocale Class
87.171QLogValueAxis Class
87.172QLogicAspect Class
87.173QMainWindow Class
87.174QMaterial Class
87.175QMatrix4x4 Class
xxiv

87.176QMdiArea Class
87.177QMdiSubWindow Class
87.178QMediaObject Class
87.179QMediaPlayer Class
87.180QMediaPlaylist Class
87.181QMenu Class
87.182QMenuBar Class
87.183QMesh Class
87.184QMessageBox Class
87.185QMetalRoughMaterial Class
87.186QMimeData Class
87.187QMorphPhongMaterial Class
87.188QMovie Class
87.189QMutex Class
87.190QMutexLocker Class
87.191QNetworkAccessManager Class
87.192QNetworkProxy Class
87.193QNetworkReply Class
87.194QNetworkRequest Class
87.195QNmeaPositionInfoSource Class
87.196QNode Class
87.197QObject Class
87.198QObjectPicker Class
87.199QOpenGLBuffer Class
87.200QOpenGLContext Class
87.201QOpenGLDebugLogger Class
87.202QOpenGLFramebufferObject Class
87.203QOpenGLFunctions Class
87.204QOpenGLFunctions_3_2_Core Class
87.205QOpenGLPaintDevice Class
87.206QOpenGLShader Class
87.207QOpenGLShaderProgram Class
87.208QOpenGLTexture Class
87.209QOpenGLTimerQuery Class
87.210QOpenGLVersionProle Class
87.211QOpenGLVertexArrayObject Class
87.212QOpenGLWidget Class
87.213QOrbitCameraController Class
87.214QPageSetupDialog Class
87.215QPaintDevice Class
87.216QPainter Class
87.217QPainter2 Class
87.218QPainterPath Class
87.219QPen Class
87.220QPerVertexColorMaterial Class
87.221QPercentBarSeries Class
87.222QPhongMaterial Class
87.223QPicture Class
87.224QPieLegendMarker Class
87.225QPieSeries Class
87.226QPieSlice Class
87.227QPixmap Class
87.228QPixmap2 Class
87.229QPlainTextEdit Class
xxv

87.230QPlaneMesh Class
87.231QPoint Class
87.232QPointF Class
87.233QPointLight Class
87.234QPolarChart Class
87.235QPrintDialog Class
87.236QPrintPreviewDialog Class
87.237QPrintPreviewWidget Class
87.238QPrinter Class
87.239QPrinterInfo Class
87.240QProcess Class
87.241QProgressBar Class
87.242QPushButton Class
87.243QQmlEngine Class
87.244QQmlError Class
87.245QQuaternion Class
87.246QQuickView Class
87.247QQuickWidget Class
87.248QRadioButton Class
87.249QRect Class
87.250QRegion Class
87.251QRegularExpression Class
87.252QRegularExpressionMatch Class
87.253QRegularExpressionMatchIterator Class
87.254QRenderAspect Class
87.255QRenderPass Class
87.256QScatterSeries Class
87.257QSceneLoader Class
87.258QScreen Class
87.259QScrollArea Class
87.260QScrollBar Class
87.261QSerialPort Class
87.262QSerialPortInfo Class
87.263QSize Class
87.264QSkyboxEntity Class
87.265QSlider Class
87.266QSphereMesh Class
87.267QSpinBox Class
87.268QSplashScreen Class
87.269QSplineSeries Class
87.270QSplitter Class
87.271QSqlDatabase Class
87.272QSqlDriver Class
87.273QSqlDriverCreatorBase Class
87.274QSqlError Class
87.275QSqlField Class
87.276QSqlIndex Class
87.277QSqlQuery Class
87.278QSqlRecord Class
87.279QStackedBarSeries Class
87.280QStackedWidget Class
87.281QStandardPaths Class
87.282QStatusBar Class
87.283QString2 Class
xxvi

87.284QStringList Class
87.285QStringRef Class
87.286QSurfaceFormat Class
87.287QSystemTrayIcon Class
87.288QTabBar Class
87.289QTabWidget Class
87.290QTableView Class
87.291QTableWidget Class
87.292QTableWidgetItem Class
87.293QTcpServer Class
87.294QTcpSocket Class
87.295QTechnique Class
87.296QTest Class
87.297QText2DEntity Class
87.298QTextBlock Class
87.299QTextBrowser Class
87.300QTextCharFormat Class
87.301QTextCodec Class
87.302QTextCursor Class
87.303QTextDocument Class
87.304QTextEdit Class
87.305QTextStream Class
87.306QTextStream2 Class
87.307QTextStream3 Class
87.308QTextStream4 Class
87.309QTextStream5 Class
87.310QTextToSpeech Class
87.311QTextureLoader Class
87.312QTextureMaterial Class
87.313QThread Class
87.314QThreadPool Class
87.315QTime Class
87.316QTimer Class
87.317QToolBar Class
87.318QToolButton Class
87.319QTorusMesh Class
87.320QTransform Class
87.321QTreeView Class
87.322QTreeWidget Class
87.323QTreeWidgetItem Class
87.324QUrl Class
87.325QUuid Class
87.326QVBarModelMapper Class
87.327QVBoxLayout Class
87.328QVBoxPlotModelMapper Class
87.329QVCandlestickModelMapper Class
87.330QVPieModelMapper Class
87.331QVXYModelMapper Class
87.332QValueAxis Class
87.333QVariant Class
87.334QVariant2 Class
87.335QVariant3 Class
87.336QVariant4 Class
87.337QVariant5 Class
xxvii

87.338QVariantDouble Class
87.339QVariantFloat Class
87.340QVariantInt Class
87.341QVariantString Class
87.342QVector2D Class
87.343QVector3D Class
87.344QVector4D Class
87.345QVectorQVoice Class
87.346QVideoWidget Class
87.347QVideoWidgetControl Class
87.348QViewport Class
87.349QVoice Class
87.350QWebEnginePage Class
87.351QWebEngineView Class
87.352QWebView Class
87.353QWebView Class
87.354QWidget Class
87.355QWindow Class
87.356QXYLegendMarker Class
87.357QXYSeries Class
87.358QXmlStreamAttribute Class
87.359QXmlStreamAttributes Class
87.360QXmlStreamEntityDeclaration Class
87.361QXmlStreamEntityResolver Class
87.362QXmlStreamNamespaceDeclaration Class
87.363QXmlStreamNotationDeclaration Class
87.364QXmlStreamReader Class
87.365QXmlStreamWriter Class
87.366Qt3DCamera Class
87.367Qt3DWindow Class
87.368RingCodeHighlighter Class
88 Low Level Functions 1377
88.1 callgc() function
88.2 varptr() function
88.3 space() function
88.4 nullpointer() function
88.5 object2pointer() function
88.6 pointer2object() function
88.7 ispointer() function
88.8 ptrcmp() function
88.9 setpointer() function
88.10 getpointer() function
88.11 pointer2string() function
88.12 memcpy() function
88.13 ringvm_cfunctionslist() function
88.14 ringvm_functionslist() function
88.15 ringvm_classeslist() function
88.16 ringvm_packageslist() function
88.17 ringvm_memorylist() function
88.18 ringvm_calllist() function
88.19 ringvm_leslist() function
88.20 ringvm_settrace()
88.21 ringvm_tracedata()
xxviii

88.22 ringvm_traceevent()
88.23 ringvm_tracefunc()
88.24 ringvm_scopescount()
88.25 ringvm_evalinscope()
88.26 ringvm_passerror()
88.27 ringvm_hideerrormsg()
88.28 ringvm_callfunc()
88.29 Example - Using the Trace Functions
88.30 Example - The Trace Library
88.31 ringvm_see() function
88.32 ringvm_give() function
88.33 ringvm_info() function
89 Tutorial: Ring Extensions in C/C++
89.1 Hello World
89.2 Build the extension on different platforms
89.3 Sum Two Numbers
89.4 Say Hello
89.5 Sum List of Numbers
89.6 Increment List Items
89.7 Filter List Items
89.8 Replicate List Items
89.9 Generate List
89.10 Display List
89.11 Update Table
89.12 Create Table
90 Extension using the C/C++ languages
90.1 ring_ext.h
90.2 ring_ext.c
90.3 Module Organization
90.4 Function Structure
90.5 Check Parameters Count
90.6 Display Error Message
90.7 Check Parameters Type
90.8 Get Parameters Values
90.9 Return Value
90.10 Function Prototype
90.11 Sin() Function Implementation
90.12 Fopen() and Fclose() Functions Implementation
90.13 Ring API - List Functions
90.14 Ring API - String Functions
90.15 MySQL_Columns() Function Implementation
90.16 Dynamic/Shared Libraries (DLL/So/Dylib) and LoadLib() function
90.17 Using RING_API_RETMANAGEDCPOINTER()
91 Embedding Ring Language in C/C++ Programs
91.1 Ring State
91.2 Ring State Functions
91.3 Ring State Variables
92 Code Generator for wrapping C/C++ Libraries
92.1 Using the tool
92.2 Conguration le
92.3 Using the function prototype
xxix

92.4 Adding code to the generated code
92.5 Prex for Functions Names
92.6 Generate function to wrap structures
92.7 Determine Structure Members Types
92.8 Dening Constants
92.9 Register New Functions
92.10 Writing comments in the conguration le
92.11 Executing code during code generation
92.12 Enum and Numbers
92.13 Filtering using Expressions
92.14 Constants Type
92.15 Conguration le for the Allegro Library
92.16 Threads Support
92.17 Code Generator Rules for Wrapping C++ Classes
92.18 Using conguration le that wrap C++ Library
92.19 Conguration le for the Qt Framework
92.20 Static Methods
92.21 Loading Files
92.22 Managed Classes
92.23 Conguration Files Examples
93 Create your rst extension
93.1 Location
93.2 Steps to create the extension
93.3 Testing the extension
94 Language Design 1466
94.1 Why Ring?
94.2 Designed for a Clear Goal
94.3 Simple
94.4 Trying to be natural
94.5 Encourage Organization
94.6 Data Representation
94.7 Compact Syntax
94.8 Dene Natural Statements
94.9 Dene Declarative Languages
94.10 Transparent Implementation
94.11 Visual Implementation
94.12 Smart Garbage Collector
94.13 No Global Interpreter (VM) Lock - No GIL
94.14 Fast Enough For Many Applications
95 What is new in Ring 1.1? 1478
95.1 List of changes and new features
95.2 Better Natural Language Programming Support
95.3 Generate/Execute Ring Object Files (*.ringo)
95.4 Syntax Flexibility and different styles for I/O and Control Structures
95.5 New Functions and Changes
95.6 StdLib functions and classes written in Ring
95.7 RingLibSDL
95.8 Demo Project - Game Engine for 2D Games
95.9 RingSQLite
95.10 Better Code Generator for Extensions
95.11 Using Self.Attribute in the Class Region to dene new attributes
xxx

95.12 Using This.Attribute in nested Braces inside the Class Methods
95.13 Better Documentation
96 What is new in Ring 1.2? 1488
96.1 List of changes and new features
96.2 New Functions
96.3 Better Functions
96.4 Better Ring Notepad
96.5 Better RingQt
96.6 Objects Library for RingQt
96.7 RingLibCurl
96.8 Better Call Command
96.9 Using NULL instead of NULLPointer()
96.10 Display Warnings Option
96.11 Better Quality
97 What is new in Ring 1.3? 1494
97.1 List of changes and new features
97.2 Better RingQt
97.3 Better Ring Notepad
97.4 Ring mode for Emacs Editor
97.5 Better StdLib
97.6 Better Loop|Exit Command
97.7 New Functions
97.8 Return Self by Reference
97.9 Using `<' and `:' operators as `from' keyword
97.10 Embedding Ring in Ring without sharing the State
97.11 RingZip Library
97.12 Form Designer
98 What is new in Ring 1.4? 1508
98.1 List of changes and new features
98.2 Change: Basic Extensions are separated from RingVM
98.3 The Natural Library
98.4 New Style is added to Ring Notepad
98.5 RingREPL
98.6 Convert between Numbers and Bytes
98.7 Better StdLib
98.8 Better WebLib
98.9 Better RingQt
98.10 Qt Class Convertor
98.11 What is new in Ring 1.4.1?
99 What is new in Ring 1.5? 1521
99.1 List of changes and new features
99.2 Video-Music-Player Application
99.3 Windows StartUp Manager Application
99.4 Calculator Application
99.5 Better Ring Notepad
99.6 Better StdLib
99.7 Better WebLib
99.8 Better RingQt
99.9 Better Objects Library
99.10 RingFreeGLUT Extension
99.11 RingOpenGL Extension
xxxi

99.12 Better Code Generator for Extensions
99.13 Better Documentation Generator for Extensions
99.14 Ring VM - Tracing Functions
99.15 Trace Library and Interactive Debugger
99.16 More Syntax Flexibility
99.17 Type Hints Library
99.18 Better Quality
99.19 What is new in Ring 1.5.1?
99.20 What is new in Ring 1.5.2?
99.21 What is new in Ring 1.5.3?
99.22 What is new in Ring 1.5.4?
100What is new in Ring 1.6? 1567
100.1 List of changes and new features
100.2 Employee Application
100.3 New Tool: Ring2EXE
100.4 Better Ring For Android
100.5 New Tool: Folder2qrc
100.6 Better Scripts for building Ring
100.7 RingConsoleColors Extension
100.8 RingMurmurHash Extension
100.9 Better Ring Notepad
100.10Better RingQt
100.11Better StdLib
100.12Better RingVM
100.13Better RingREPL
100.14Using Tab instead of char(9)
100.15Using CR as Carriage return
100.16Using the ! operator as not
100.17Using && and || operators
100.18Using ? to print expression then new line
101What is new in Ring 1.7? 1578
101.1 List of changes and new features
101.2 New Command: Load Package
101.3 ringvm_see() and ringvm_give() functions
101.4 ring_state_new() and ring_state_mainle() functions
101.5 Better Trace Library
101.6 Better Ring Notepad
101.7 Better RingQt
101.8 Better Ring2EXE
101.9 Better RingZip
101.10Better Documentation
101.11Better Ring VM
101.12RingLibuv Extension
102What is new in Ring 1.8? 1586
102.1 List of changes and new features
102.2 Better Performance
102.3 Find in les Application
102.4 String2Constant Application
102.5 StopWatch Application
102.6 More 3D Samples
102.7 Compiling on Manjaro Linux
xxxii

102.8 Using This in the class region as Self
102.9 Default value for object attributes is NULL
102.10The For Loops uses the local scope
102.11Merge binary characters
102.12FoxRing Library
102.13Better Form Designer
102.14Better Cards Game
102.15Better RingQt
102.16Better Code Generator For Extensions
102.17Better Ring Compiler and VM
102.18Notes to extensions creators
103What is new in Ring 1.9? 1600
103.1 List of changes and new features
103.2 New Game : Gold Magic 800
103.3 More Games
103.4 Better Ring Notepad
103.5 Better StdLib
103.6 BigNumber Library
103.7 RingPostgreSQL Extension
103.8 Deploying Web applications in the Cloud
103.9 Better RingQt
103.10Better Memory Management
103.11Better Code Generator for Extensions
103.12More Improvements
104What is new in Ring 1.10?
104.1 List of changes and new features
104.2 Chess Game
104.3 Minesweeper Game
104.4 Knight Tour Game
104.5 Game of Life Game
104.6 Pong Game
104.7 Snakes And Ladder Game
104.8 More Games
104.9 Ring Extension for Visual Studio Code
104.10The Ring Package Manager (RingPM)
104.11Better Tests
104.12More Improvements
105What is new in Ring 1.11?
105.1 List of changes and new features
105.2 More 3D Samples
105.3 Checkers Game
105.4 Sokoban Game
105.5 Maze Game
105.6 Snake Game
105.7 Sudoku Game
105.8 Desktop Screen Shot Application
105.9 Text To Speech Application
105.10RingRayLib Extension
105.11ZeroLib Library
105.12StdLib - More Functions
105.13Better RingQt
xxxiii

105.14Better Performance
105.15Better Documentation
105.16More Improvements
106What is new in Ring 1.12?
106.1 List of changes and new features
106.2 Go Game
106.3 ASCII Table application
106.4 BMI Calculator application
106.5 Calendar application
106.6 Julian Day Calendar application
106.7 Tutorial: Number to Words
106.8 Load Again Command
106.9 ring_state_letokens() function
106.10Generate Embedded Ring Object File
106.11Better RingRayLib
106.12More Improvements
107What is new in Ring 1.13?
107.1 List of changes and new features
107.2 New Book by Apress
107.3 Ring for WebAssembly
107.4 Better Threads Support
107.5 Laser Game
107.6 Magic Balls Game
107.7 Money Boxes Game
107.8 Matching Game
107.9 Pairs Game
107.10Word Game
107.11Tetris Game
107.12Escape Game
107.13Hassouna Course Samples
107.14Ring support in SpaceVim
107.15Better RingQt
107.16Better RingRayLib
107.17RingStbImage Extension
107.18More Low Level Functions
107.19Better Organization
107.20More Improvements
108What is new in Ring 1.14?
108.1 List of changes and new features
108.2 MyCoffee (Web Application)
108.3 Web Development Samples
108.4 More Samples
108.5 Erlang B Formula
108.6 Customers Form
108.7 RingTilengine Extension
108.8 RingLibui Extension
108.9 RingSockets Extension
108.10RingThreads Extension
108.11Better RingOpenSSL
108.12More Functions
108.13Better Functions
xxxiv

108.14Better Performance For Strings
108.15Better Handling For Numbers
108.16Using CLOC (Count Lines of Code)
108.17More Improvements
109Using Other Code Editors
109.1 Using Notepad++
109.2 Using Geany
109.3 Using Atom
109.4 Using Sublime Text 2
109.5 Using Visual Studio IDE
109.6 Using Emacs Editor
109.7 Visual Studio Code
109.8 SpaceVim
110Frequently Asked Questions (FAQ)
110.1 Why do we need Yet Another Programming Language (YAPL)?
110.2 What is the Ring Architecture?
110.3 What about Memory Management in Ring?
110.4 What about Data Representation in Ring?
110.5 Why is Ring weakly typed?
110.6 What are the advantages to using Ring over Lisp or Smalltalk?
110.7 Why is Ring largely focussed on UI creation?
110.8 Is Ring some sort of an improvement of PHP?
110.9 What are the advantages of using Ring over native C or C++?
110.10What is the difference between Ring and Python? And is Ring Open Source?
110.11What are the advantages to using Ring over Perl, PHP, Python or Ruby?
110.12What are the advantages to using Ring over Tcl or Lua?
110.13What are the advantages to using Ring over C# or Java?
110.14The documentation says functional programming is supported, but then this happens?
110.15Why the ability to dene your own languages Instead of just handing over the syntax so you can parse
it using whatever code you like?
110.16Why you can specify the number of loops you want to break out of?
110.17Why Ring uses `See', `Give', `But' and `Ok' Keywords?
110.18What is the philosophy behind data types in Ring?
110.19What about the Boolean values in Ring?
110.20What is the goal of including the “Main” function in Ring?
110.21Why the list index start from 1 in Ring?
110.22Why Ring is not case-sensitive?
110.23Why the Assignment operator uses Deep Copy?
110.24Is there constructor methods in Ring?
110.25What happens when we create a new object?
110.26Can we use the attributes by accessing the Getter and Setter methods?
110.27Why should a search of global names be made while dening the class attributes?
110.28Why Ring doesn't avoid the conict between Global Variables and Class Attributes Names?
110.29Where can I write a program and execute it?
110.30How to get the le size using ftell() and fseek() functions?
110.31How to get the current source le path?
110.32What about predened parameters or optional parameters in functions?
110.33How to print keys or values only in List/Dictionary?
110.34Why I get a strange result when printing nl with lists?
110.35Could you explain the output of the StrCmp() function?
110.36How to use many source code les in the project?
110.37Why this example use the GetChar() twice?
xxxv

110.38How to use NULL and ISNULL() function?
110.39How to print lists that contains objects?
110.40How to insert an item to the rst position in the list?
110.41How to print new lines and other characters?
110.42Why we don't use () after the QApp class name?
110.43Why the window title bar is going outside the screen?
110.44How to create an array of buttons in GUI applications?
110.45How to Close a window then displaying another one?
110.46How to create a Modal Window?
110.47How can I disable maximize button and resize window?
110.48How to use SQLite using ODBC?
110.49Can I connect to dbase/harbour database?
110.50Why setClickEvent() doesn't see the object methods directly?
110.51Why I get Calling Function without denition Error?
110.52Can Ring work on Windows XP?
110.53How to extend RingQt and add more classes?
110.54How to add Combobox and other elements to the cells of a QTableWidget?
110.55How to perform some manipulations on selected cells in QTableWidget?
110.56Which of 3 coding styles are commonly used or recommended by the community?
111Building From Source Code
111.1 Building using Microsoft Windows
111.2 Building using Ubuntu Linux
111.3 Building using Fedora Linux
111.4 Building using MacOS X
111.5 Building using CMake
112How to contribute? 1754
112.1 Special thanks to contributors
112.2 Documentation
112.3 Testing
112.4 Samples
112.5 Applications
112.6 Editors Support
112.7 Libraries in Ring
112.8 Extensions in C/C++
112.9 Compiler and Virtual Machine (VM)
113Language Specication 1757
113.1 Language Keywords
113.2 Language Functions
113.3 Compiler Errors
113.4 Runtime Errors
113.5 Environment Errors
113.6 Language Grammar
113.7 Virtual Machine (VM) Instructions
114Resources 1776
114.1 Ring Language Website
114.2 Source Code
114.3 Ring Team
xxxvi

CHAPTER
ONE
APPLICATIONS DEVELOPED IN A FEW HOURS
Ring is a new programming language that focuses on the Natural Language Programming and Declarative Program-
ming paradigms and will let you think different about programming and how to solve your problems in a better way.
In little days after the rst release we got thousands of downloads and many developers started learning and using the
language. Their feedback are the secret behind the language progress and success. They said that Ring is powerful,
beautiful and easy to learn, Some of them provided good examples about what can be done using Ring in a few hours.
They are very happy with the language productivity.
1.1
“I like Smalltalk very much but now I like Ring better!”
, Gal Zsolt (Hungary)
“I nd the language and its syntax very natural and easy to follow.”
, Bhudda (United States)
“Very nice approach for a new language.”
, Matth Moestl (Austria)
“Very interesting! I will keep an eye on it.!”
, Eslipak (Argentina)
“I'd like to see some benchmarks. Otherwise, at rst glance, it looks really promising.”
, Alex Deva (Sweden)
“Excellent”
, Liju Sankar (United States)
“I wish you the best with this project.”
, David O'Neil (United States)
“Just fantastic.”
1

Ring Documentation, Release 1.14
, Jose Antonio (Mexico)
“This looks like it was developed by some very competent people.”
, Jim Clack (United States)
“The Ring programming language seems pretty interesting so far.”
, Eric Johnson (United States)
“Thank you for this awesome language and wonderful ready to use Qt binding.”
, Martial FAESSEL
“I think it's great what he does for the community of developers and novice programming.”
, Marino Esteban
“Ring is just awesome. The language is so cool and uent. I am sure it's going to be BIG.”
, Ahmed Zain
“What a proud, really wish you Eng. Mahmoud Samir and Your Team moving forward ^_^ and from now ,
considered me a big fan of the Ring programming language.”
, Zainab Mahmoud
“Well guys I love this language and it appears that you have created perfect language.”
, Moemen Ghulmi
“Good work Mahmoud, I've installed ring pl, and it's very perfect language.”
, Ahmed Omar (Egypt)
“Thanks for this great startup programming language. I wish you best of luck.”
, Elkhouaja Khalid
“Congratulations! I am very happy and I wish you Success and good luck.”
, Abobasmla Hassan
“Good Features of multi-use language on the Web, Mobile and Desktop.”
, Abdelrhman Haider
“Very interesting effort.”
, Giannakakis Kostas (Greece)
1.1. Quotes about Ring 2

Ring Documentation, Release 1.14
“I am too lazy to open comment window and write message. But in your case I must say (Perfect) Really,
create new remarkable language like your Ring is really perfect job. Even create editor for your language in
your language with only few rows. . . Even noticed in rosettacode.org ! I read your previous articles and I tried
these examples a few days ago and I will continue. I love Ring. P.S.: Anders Hejlsberg, Niklaus Wirth, Bjarne
Stroustrup, Ada Lovelace Hall of fame is waiting. . . .”
, Martin Nedopil (Czech Republic )
“Ring seems very attractive to me through its very easy design and the Qt bindings. I like its declarative
approach and the generous documentation.”
, Shalok Shalom (Austria)
“Ring (and plenty of extension library + Qt) is wonderful.”
, Kovacs Attila (Hungary)
“Since two days I'm trying Ring and I'm really impressed, in add to power commands and easy use, it's really
very efcient and very fast. Each day I hope to nd the couple of the year PWCT+RING . . . Maybe for my
Christmas gift!!!! HO HO HO HO Continue your fantastic job and congratulations.”
, Jose Le Roux (France)
“There are 3 different styles, it looks like Python and C”
, 64remy
“I was taking a tour around Rosettacode and have found Ring. I like the syntax a lot. It's clean and easy to
understand. It looks like a very clean BASIC dialect without sigils. I can say that this is the easiest and the
most BASIC-like language I've ever tried.”
, Tomaaz
“Thanks for your effort. I took a quick look and found it interesting. You are trying to follow more or less like
Clipper with simple command and no rigid declaration rules. Good.”
, Anand Gupta
“Thanks for this wonderful language”
, Vinod kc (India)
“Very enlightening. good job!”
, Southmountain (United States)
“The thing I liked was the loop exiting”
, Leon de boer (Australia)
“An outstanding and easy language to program with.”
, Kenneth Burgo (Philippines)
1.1. Quotes about Ring 3

Ring Documentation, Release 1.14
“I chose your language as I feel I can understand it better than other languages”
, Harry Singh
“I like the totality of the language, far more features than expected and the freedom of expressiveness is
unique.”
, Evikone
“Thank you very much Mahmoud! I am using ring for many experiments and so far I love it. I really want to
continue using ring and contribute what I can.”
, John (SienSystem)
“Sir, Very Good”
, Kamlesh Patel
“That's more than a “cool” syntax, the example of writing free-form text between curly-brackets such that
each word calls a function. Which could be interesting (A syntax like that would be nice for declaring text
styles)”
, LaurieCheers
“If you browse around you see they have listed 160 contributors. This year they have entered Top 100 in the
TIOBE index. Lot of effort seem to have been made to make this language pop out and catch the attention of
masses.”
, Htuhola
“I like the idea of The Ring being in ANSI C it's an impressive creation, and a lot of skill went into it”
, Garry Taylor
“Very innovative language! Syntactically clean”
, CodeProject Member
“The author must be commended for the readily-obvious hard work and effort that has gone into creating a
rich ecosystem for his language. It seems that the language is quite extensive as well. I would nd it useful to
see a BNF grammar and concise coverage of its semantics.”
, Xx-Leninist-1917-Xx (Reddit)
“I can see the AI of the future using this technology to solve computational problems for. . . .. the humans.”
, Cryptonite (United States)
“I like your programming language, I like you are going to develop mobile app using RingQt and also I
appreciate your web library.”
, Domenico D'Oria (Italy)
1.1. Quotes about Ring 4

Ring Documentation, Release 1.14
“Congratulations for the great work with this new programming language.”
, Kenny Silva (Venezuela)
“Ring is an amazingly full-featured language and so well documented (the bane of most newer languages out
there!)”
, Alex McCullie
” I found the language yesterday, and liked the Qt bindings, as they give a declarative way to create a
QtWidgets GUI.”
, Cochise Cesar
“Ring does look intriguing, and I'll be reading more of the documentation soon”
, Jamie Cooper
“I was recently considering designing my own dynamically-typed, prototypical language and then developing a
means to compile it into C/C++. However, last night I was surng the web and noticed a little-known language
called “Ring” which you've recently created. I began reading the Motivation section in Wikibooks to see why
the language was designed and implemented, and I was shocked to see that someone else had created a
language with the same intention and need as myself. I mean, it's mind-blowing that someone would have
addressed every issue I have with the currently accepted languages. It's crazy to think it's only been around
for a year and yet, it's already, practically a batteries-included language.”
, Gedalya (YouTube)
“Thank you Mr. Mahmoud for all the wonderful work, whenever I dive in the Source code I see the great
effort, further development more excellence, God will reward you with what you wish”
, Azzedine Ramal
“What a great joy to nd this surprisingly genius language !!!. It was a total joy to go through the
documentation and look at the samples in Rosetta code. Marvelous work. I would even leave my fortune to the
development of this language. Keep the good work going and wishing this language will go viral. ps: Thanks
for keeping array index to start with 1. It means a lot.”
, Nehemiah Jacob (Sydney, Australia)
“I nd it very interesting. Especially the fact that it is cross platform makes it something to keep an eye on.”
, Boudewijn Lutgerink
“The language I like the most. Efcient, simple, easy, exible and wonderful language.”
, Roshan Ali
“I like variety. The richer the toolbox, the more appropriate the tool.”
, Jonathan Day (Quora)
1.1. Quotes about Ring 5

Ring Documentation, Release 1.14
“I greatly appreciated your work and congratulations on what has been achieved.”
, Umberto Meglio (Italy)
“Thanks a lot I just found Ring two days ago and I decided to learn it, it is amazing, the samples are helping a
lot.”
, Zaraki Ken
“Extraordinary. well done sir”
, RugbyLeague (CodeProject Member - United Kingdom)
“The Ring language is pleasant. You get ahead very quickly.”
, Neskuk (CodeProject Member - Switzerland)
“I'm happy to use your language.”
, Akhil Reddy
“I am enjoying using the Ring Programming language.”
, Gabriel Wendt
“I'm loving this language!”
, Pablo Prieto
“Ring Notepad is a an example of the power of Ring. It is like NotePad++ with built in form design capability,
drag and drop, object attributes etc. It is a marvelous application”
, Bert Mariani (Italy)
“Ring is the language that offers the greatest potential for converting programmers frustrated with the
amount of time it takes to develop apps in C/C++, C# and other OOP-based languages. Considering the extent
to which Ring has evolved since the rst release in 2016, the Ring team has proven itself worthy of a very high
achievement award in the world of programming languages. The extent to which Ring has simplied the
development database apps, web apps and GUI apps is a great credit to the Ring team. Ring's implementation
of OOP and GUI based apps is far superior to C++ and C#. Another major achievement of the Ring team is
the ease at which programmers can get on-line access to Ring documentation, compared to on-line C++ and
C# documentation. The Ring Game Engine is truly elegant and it's designer (s) deserve lots of credit for such
an impressive bit of software.”
, L Godioleskky
“Strongly speaking, it is a strong and new game programming language.”
, IsVowel (Japan)
“The language seems to have some interesting features, specially the use of braces to access object elds and
methods.”
1.1. Quotes about Ring 6

Ring Documentation, Release 1.14
, Nuaua (Reddit)
“The code that implements the Ring VM actually looks quite nice. There is a bunch of test code – great!”
, Peterrey (Reddit)
“Ring seems promising. It rst appeared in 2016 although it's concept is older. It is meant to be portable and
can be embedded in C/C++ projects”
, Wim ten Brink (Quora - Top Writer (2018))
“Interesting alternative to Lua.”
, djxtc (Sourceforge)
“Ring is a serious thing in the programming language landscape. One shoud understand its foundation before
she can shape an opinion worth considering. There are several innovations outthere with a clear commitment
from its designer to simplicity, exibility and learnability. Natural language as its imagined by Ring opens a
window for an unlimited set of applications otherwise impossible to think about. One can built an interactive
chatbot based on a rich domain specic language in a matter of hours not months. Combined with a smart yet
effective implementation of a declarative programming paradigm, Ring empowers the creation of any kind of
programming language on top of it, with any set of syntax. Even the language keywords can be overwritten to
serve one's own keywords in any human language not only english. Ring is a disruption, a big intellectual step
forward but also a beautiful reincarnation of several legacy ideas and best practices from other old languages
like Basic, Lisp and others. Those ideas ar e a humanity heritage that new visionaries like Mahmoud S. Fayed,
the Ring designer, but also Rick Hickey, the Clojure designer, are trying to callback in today's world of
complex programmability. An other dimension of Ring, which formed one of its basic motivations, relates to
visual programming. Software is a uid and evolutionary creature and textual code is not accessible to the
most of common humans. The promise of visual programming is to empower people, enhance
understandability and invite business users to the arena of software development more intuitively. Ring was
made by design with an objective of having a programming language capable of better supporting the visual
paradigm. Gamication is a rst-class citizen in the language. This is a tremendous advantage compared to
other general-purpose programming languages. Ring supports a large number of gaming libraries and open a
large window of capabilities to use, not only in gaming but also in business and education applications. The
best way to a ssesing the power of Ring is to looking into it and reecting about the number of problems it is
capable to solve.”
, Mansour Ayouni (Tunisia)
“I have only known ring-lang for few weeks, really love features and visions of ring: bracket access, class
region, declarative and natural programming. It's simple and beautiful the way ring deal with these
paradigms. I think it's really great work what you're done, and doing. I want to develop ethereum client in
ring language, not only but it's style. It'll have natural and declarative code on it's main part. Furthermore, It
will be fantastic if there is “natural language -> evm bytecode” compiler, maybe ring have the solution”
, Asta
“The language looks great!”
, Eric Hawk
“You put a lot of work in the Ring and you're a great programmer. I saw your examples in 3D I've looked at
1.1. Quotes about Ring 7

Ring Documentation, Release 1.14
part of your project, it's really great”
, Rafal Jopek
“Looks like a big project and an impressive piece of work”
, Rochus Keller (PhD From ETH Zurich, Switzerland)
“I see Ring a very useful and easy in PROGRAMMING IN REGIONAL LANGUAGE. I tried to program in
my mother language Hindi ( India) using UNICODE It is working. No other language give me such an easy
platform.”
, Negi Manoj (India)
“I'm glad I could help improve the Ring language. It has good and yet easy to understand design and
architecture. I believe it has big potential ahead.”
, Mounir IDRASSI (Creator of VeraCrypt)
“What I like most about Ring Lang is its ease to create complex applications in WebAssembly.”
, Luis Lozad
1.2
It will fetch stock data from Yahoo and draw various types of charts.
1.2. FetchStockData Application 8

Ring Documentation, Release 1.14
1.3
A small but very nice tool to shorten urls using the Google shortener API.
1.3. Google API Shortener Application 9

Ring Documentation, Release 1.14
1.4
An application to play multi-media les.
1.4. Video-Music-Player Application 10

Ring Documentation, Release 1.14
1.5
An implementation for the Fifteen Puzzle game.
1.5. Fifteen Puzzle Game 11

Ring Documentation, Release 1.14
1.6
Simple implementation for the Analog Clock.
1.6. Analog Clock 12

Ring Documentation, Release 1.14
1.7
An implementation for the popular Squares Puzzle game.
1.8
The next samples are developed in a few hours and we will introduce them through this book.
The next screen shot for he Ring Notepad application
1.7. Squares Puzzle Game 13

Ring Documentation, Release 1.14
The next screen shot for the Cards GameThe next screen shot for the Cards Game (Android)
1.8. Samples in this book 14

Ring Documentation, Release 1.14
The next screen shot from the Web Development chapter
1.8. Samples in this book 15

Ring Documentation, Release 1.14
The next screen shots for simple 2D Games that we will present in the Game Engine Chapter.
Stars Fighter Game
Flappy Bird 3000 Game
1.8. Samples in this book 16

Ring Documentation, Release 1.14
Super Man 2016 Game
1.8. Samples in this book 17

Ring Documentation, Release 1.14
The next screen shot for the TicTacToe 3D Game
Screen Shot:
1.8. Samples in this book 18

Ring Documentation, Release 1.14
The next screen shot for the Gold Magic 800 GameThe next screen shot from the RingQt3D chapter
1.8. Samples in this book 19

Ring Documentation, Release 1.14
1.9
The language comes with better support for Natural Language Programming and Declarative Programming. The inno-
vation comes in supporting these paradigms with new practical techniques on the top of Object-Oriented Programming
and Functional Programming. No need to know anything about (Compilers and Parsing). You get the language con-
structs ready for use to create domain-specic languages in a fraction of time.
Articles:-
•
https://www.codeproject.com/Articles/1200766/Using-the-Natural-Language-Programming-Library-NLP
•
https://www.codeproject.com/Articles/1138605/Natural-Language-Programming-in-the-Ring-Programmi
•
https://www.codeproject.com/Articles/1222105/The-declarative-approach-of-the-Ring-programming-l
•
https://www.codeproject.com/Articles/1137388/Syntax-Flexibility-in-the-Ring-Programming-Languag
•
https://www.codeproject.com/Articles/1089887/The-Ring-Programming-Language
1.9. Innovative 20

Ring Documentation, Release 1.14
1.10
Many of the Ring libraries (StdLib, WebLib, Natural Library, Games Engine, etc.) and the Ring IDE (Ring Notepad,
Form Designer, etc.) are written in the Ring language itself. Ring is ready for use in production and increase the
developers productivity.
Check the Form Designer source code :
We can run the Form Designer as Android application!
1.10. Practical 21

Ring Documentation, Release 1.14
Also we can run it in the Web Browser as a web application using WebAssembly
1.10. Practical 22

CHAPTER
TWO
INTRODUCTION
Welcome to the Ring programming language!
Ring is an Innovative and practical general-purpose multi-paradigm language that can be embedded in C/C++ projects,
extended using C/C++ code and/or used as standalone language. The supported programming paradigms are Impera-
tive, Procedural, Object-Oriented, Functional, Meta programming, Declarative programming using nested structures,
and Natural programming. The language is portable (Windows, Linux, macOS, Android, etc.) and can be used to cre-
ate Console, GUI, Web, Games and Mobile applications. The language is designed to be Simple, Small, Flexible and
Fast. Its Dynamic Language that compile the source code to byte code then execute it by the Ring Virtual Machine,
which is integrated with the Ring Compiler in one program.
In this chapter we are going to discuss the goals behind the language design and implementation.
2.1
In Nov. 2011, I started to think about creating a new version of the
software from scratch.
I was interested in creating multi-platform edition of the software beside adding support for Web & Mobile develop-
ment.
What I was looking for is a programming language that can be used to build the development environment, provides
multi-platform support, more productivity, better performance, can be used for components scripting and developing
different kinds of applications.
Instead of using a mix of programming languages, I decided to use one programming language.
I looked at many programming languages, but I discovered that I need a different language that comes with new ideas
and intelligent implementation.
23

Ring Documentation, Release 1.14
2.2
Ring is an innovative programming language that comes with better support for Natural Language Programming and
Declarative Programming. The innovation comes in supporting these paradigms with new practical techniques on the
top of Object-Oriented Programming and Functional Programming.
Also Ring is inuenced by the next programming languages
•
•
•
•
•
•
•
•
•
2.3
In Sept. 2013 I started the design and the implementation of the Ring programming language. After 21 months of
development, In May 2015 the language Compiler & Virtual Machine were ready for use!
After that I spent three months testing the language again, trying to discover any bug to x, writing better tests, by
the end of August 2015, all know bugs were xed, Writing many tests and testing automation helped a lot in getting a
stable product.
In September 12, 2015, most of the documentation was written. Before releasing the language I started the marketing
by writing a post in Arabic language about it to my facebook prole page asking for contributors interested in the
language idea after reading a short description, In the same day I got a lot of emails from developers and friends
interested to contribute!
Ring 1.0 is released on January 25, 2016
Ring 1.1 is released on October 6, 2016
Ring 1.2 is released on January 25, 2017
Ring 1.3 is released on May 15, 2017
Ring 1.4 is released on June 29, 2017
Ring 1.5 is released on August 21, 2017
Ring 1.6 is released on November 30, 2017
Ring 1.7 is released on January 25, 2018
Ring 1.8 is released on June 25, 2018
Ring 1.9 is released on October 6, 2018
Ring 1.10 is released on January 25, 2019
Ring 1.11 is released on September 15, 2019
2.2. Ring and other languages 24

Ring Documentation, Release 1.14
Ring 1.12 is released on January 25, 2020
Ring 1.13 is released on September 15, 2020
Ring 1.14 is released on January 25, 2021
2.4
The Ring language comes with the next features
Tip:The language is ready for production!
•
•
•
•
•
•
•
•
•
•
•
•
•
•A small language
–The compiler + The Virtual Machine (20,000 lines of C code)
–The other 500,000 lines of code are related to libraries!
•
•
•
•
•
•
•
•
•
•
•
2.4. Features 25

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
–Encapsulation
–Setter/Getter (optional)
–private state (optional)
–Instantiation
–Polymorphism
–Composition
–Inheritance (Single Inheritance)
–Operator Overloading
–Packages
•
•
•
•
•
•
•
•
•
•
2.4. Features 26

Ring Documentation, Release 1.14
•
•
•
•
•
–HTTP Get
–HTTP Post
–File upload
–Cookies
–URL Encode
–HTML Templates
–HTML Special Characters
–HTML Generation using Functions
–HTML Generation using Classes
–CRUD Example (using MVC)
–Users Example (Register, Login and Check)
•
•
•
•
•Comes with code generator (Written in Ring) to quickly wrap C/C++ Libraries
–Used to Support Allegro by creating RingAllegro
–Used to Support LibSDL by creating RingLibSDL
–Used to Support Qt by creating RingQt
•
•
•
•
•
•
•
•
•
•
•
•
2.4. Features 27

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
2.5
The Ring Programming Language
http://ring-lang.net/
Version 1.14
The MIT License (MIT)
Copyright (c) Mahmoud Fayed
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documen-
tation les (the “Software”), to deal in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PAR-
TICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFT-
WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2.5. License 28

CHAPTER
THREE
USING RING NOTEPAD
In this chapter we will learn about using Ring Notepad to write and execute Ring programs quickly
Ring Notepad is just a simple application developed using the Ring language.
3.1
When we run the Ring Notepad we get the next dockable windows
• *.ring) quickly.
•
•
•
•
•
•
29

Ring Documentation, Release 1.14
3.2
At rst we will type the source code
see"Hello, World!"
As in the next image
Then we will click on the “Save” button from the toolbar (or press CTRL+S)Determine the source code le name and location.
For example type : hello
This will create a new source code le called : hello.ring
3.2. Creating and running your rst Console Application 30

Ring Documentation, Release 1.14
To run the program click on “Debug (Run then wait!)” button from the toolbarThe next screen shot present the application during the runtime
Press Enter to continue and return to the Ring Notepad.
3.2. Creating and running your rst Console Application 31

Ring Documentation, Release 1.14
3.3
cation
To learn how to create GUI applications using Ring check the “Desktop, WebAssembly and Mobile development using
RingQt” chapter.
Source Code:
load"guilib.ring"
newqApp {
newqWidget() {
resize(400,400)
setWindowTitle("Hello, World!")
show()
}
exec()
}
In Ring notepad we have a special button to run GUI applications without displaying the console window.
3.3. Creating and running your rst GUI/WebAssembly/Mobile Application 32

Ring Documentation, Release 1.14
The next screen shot present the application during the runtime
3.3. Creating and running your rst GUI/WebAssembly/Mobile Application 33

Ring Documentation, Release 1.14
3.4
To learn how to support Ring in your web server and how to create web applications check the “Web Development
(CGI Library)” chapter.
Note:You need to support the Ring language in your web server to be able to run the next example.
Tip:For Windows users, Ring comes with Apache Web server! Using Ring Notepad we can run any web application
from any folder directly without doing any conguration.
Source Code:
#!ring -cgi
load"weblib.ring"
importSystem.Web
newPage {
text("Hello, World!")
}
We can run the application in any web browser or in the browser that are embedded in Ring Notepad.
We can run the web application using the Web icon.
3.4. Creating and running your rst Web Application 34

Ring Documentation, Release 1.14
3.5
To learn about creating 2D Games using Ring check the “Demo Project - Game Engine for 2D Games” chapter.
Source Code:
load"gameengine.ring"
funcmain
oGame NewGame
{
titleMy First Game"
sprite
{
type
x=400=400=100=100
fileimages/player.png"
transparent true
Animate= false
Move= true
Scaled= true
}
}
We can run the application as any GUI application.
3.5. Creating and running your rst Desktop/Mobile Game 35

Ring Documentation, Release 1.14
3.6
The idea of the Main File ToolBar is to determine the main le in the project When the project contains many source
code les
Using this feature we can run the project (Main File) at any time while opening other les in the project without the
need to switch to the Main File to run the project.
To quickly use this feature
(Open the project main le)
Press Ctrl+Shift+M to set the current source code le as the main le
Open and modify other source code les in the project
To run the project (Main File) at any time press Ctrl+Shift+F5 (GUI) or Ctrl+Shift+D (Console)
Screen Shots:
3.6. The Main File in the Project 36

Ring Documentation, Release 1.14
3.7
From this menu we can create, open and save the source code les.
Another feature in this menu is “Print to PDF”
3.7. The File Menu 37

Ring Documentation, Release 1.14
3.8
From the Edit menu we can Cut, Copy and Paste text.
Also we can change the font and the colors.
We can Go to a specic line or use the Find and Replace window to nd and replace text.
Also We can set the Tab Width (Number of Spaces)
Starting from Ring 1.8 we have the (Find in Files) option.
Starting from Ring 1.11 we have the (Insert Text, Lower Case, Upper Case & Capitalize) options.
3.8. The Edit Menu 38

Ring Documentation, Release 1.14
3.9
From this menu we can show/hide the dockable windows
Also we can change the Style of the Ring Notepad
Common Styles are (Fusion White and Modern Black)
Also we can quickly show/hide group of dockable windows based on the context
3.9. The View Menu 39

Ring Documentation, Release 1.14
3.10
From this menu we can run the programs
Also we can set the Main le in the project
3.10. The Program Menu 40

Ring Documentation, Release 1.14
3.11
From this menu we can quickly open common links in the browser
3.12
From this menu we can run the Form Designer in separate window
Also we can run the REPL (Read-Eval-Print-Loop) application
3.13
From this menu we can build an executable le for the application
Also we can prepare the application for distribution
3.11. The Browser Menu 41

Ring Documentation, Release 1.14
3.14
From this menu we can get the help les (CHM & PDF)
3.14. The Help Menu 42

CHAPTER
FOUR
GETTING STARTED - FIRST STYLE
4.1
The next program prints the Hello World message on the screen (std-out).
see"Hello World"
4.2
to run the program, save the code in a le, for example : hello.ring then from the command line or terminal, run it
using Ring
ring hello.ring
4.3
Using Ring2EXE we can create executable le for our application
ring2exe hello.ringstatic
4.4
Since the Ring language is not case-sensitive, the same program can be written in different styles
Tip:It's better to select one style and use it in all of the program source code
SEE"Hello World"
See"Hello World"
43

Ring Documentation, Release 1.14
4.5
Using Ring we can write multi-line literal, see the next example
See"
Hello
Welcometothe Ring programming language
How are you?
"
Also you can use the nl variable to insert new line and you can use the + operator to concatenate strings
As we have NL for new lines, we have Tab and CR (Carriage return) too!
Note:nl value means a new line and the actual codes that represent a newline is different between operating systems
See"Hello"Welcome to the Ring programming language"
nlHow are you?"
4.6
You can get the input from the user using the give command
See"What is your name?
GivecName
See"Hello
4.7
You don't need to use `;' or press ENTER to separate statements. The previous program can be written in one line.
See"What is your name? givecNamesee"Hello
4.8
It's common to print new line after printing an expression, We can use the ? operator to do that!
Example:
?Hello, World!"
forx to10
?
next
Output:
4.5. Multi-Line literals 44

Ring Documentation, Release 1.14
Hello, World!
1
2
3
4
5
6
7
8
9
10
4.9
We can write one line comments and multi-line comments
The comment starts with # or //
Multi-lines comments are written between /* and*/
/*
Program Name : My first program using Ring
Date :.09.09
Author : Mahmoud Fayed
*/
See"What is your name? # print message on screen
givecName # get input from the user
see"Hello # say hello!
//See"Bye!"
Note:Using // to comment a lines of code is just a code style.
4.9. Writing Comments 45

CHAPTER
FIVE
GETTING STARTED - SECOND STYLE
5.1
The next program prints the Hello World message on the screen (std-out).
put"Hello World"
5.2
to run the program, save the code in a le, for example : hello.ring then from the command line or terminal, run it
using Ring
ring hello.ring
5.3
Using Ring2EXE we can create executable le for our application
ring2exe hello.ringstatic
5.4
Since the Ring language is not case-sensitive, the same program can be written in different styles
Tip:It's better to select one style and use it in all of the program source code
PUT"Hello World"
Put"Hello World"
46

Ring Documentation, Release 1.14
5.5
Using Ring we can write multi-line literal, see the next example
Put"
Hello
Welcometothe Ring programming language
How are you?
"
Also you can use the nl variable to insert new line and you can use the + operator to concatenate strings
As we have NL for new lines, we have Tab and CR (Carriage return) too!
Note:nl value means a new line and the actual codes that represent a newline is different between operating systems
Put"Hello"Welcome to the Ring programming language"
nlHow are you?"
5.6
You can get the input from the user using the get command
Put"What is your name?
GetcName
Put"Hello
5.7
You don't need to use `;' or press ENTER to separate statements. The previous program can be written in one line.
Put"What is your name? getcNameput"Hello
5.8
We can write one line comments and multi-line comments
The comment starts with # or //
Multi-lines comments are written between /* and*/
/*
Program Name : My first program using Ring
Date :.09.09
Author : Mahmoud Fayed
*/
(continues on next page)
5.5. Multi-Line literals 47

Ring Documentation, Release 1.14
(continued from previous page)
Put"What is your name? # print message on screen
getcName # get input from the user
put"Hello # say hello!
//Put"Bye!"
Note:Using // to comment a lines of code is just a code style.
5.8. Writing Comments 48

CHAPTER
SIX
GETTING STARTED - THIRD STYLE
6.1
The next program prints the Hello World message on the screen (std-out).
load"stdlib.ring"
print("Hello World")
6.2
to run the program, save the code in a le, for example : hello.ring then from the command line or terminal, run it
using Ring
ring hello.ring
6.3
Using Ring2EXE we can create executable le for our application
ring2exe hello.ringstatic
The -static option will avoid the need to ring.dll|ring.so|ring.dylib
But since the stdlib.ring load libraries like (LibCurl, OpenSSL, MySQL, etc)
You will need these libraries!
To avoid the need to these libraries (If you don't need stdlib classes)
Use stdlibcore.ring instead of stdlib.ring as in the next example
load"stdlibcore.ring"
print("Hello World")
Using stdlibcore.ring You can access the stdlib functions but not the stdlib classes.
if you want to use stdlib.ring and distribute your application
49

Ring Documentation, Release 1.14
ring2exe hello.ringdistallruntimenoqtnoallegro
6.4
Since the Ring language is not case-sensitive, the same program can be written in different styles
Tip:It's better to select one style and use it in all of the program source code
LOAD"stdlib.ring"
PRINT("Hello World")
Load"stdlib.ring"
Print("Hello World")
6.5
Using Ring we can write multi-line literal, see the next example
Load"stdlib.ring"
Print("
Hello
Welcometothe Ring programming language
How are you?
")
Also you can use the to insert new line and you can use #{variable_name} to insert variables values.
Load"stdlib.ring"
Print(Hello Welcome to the Ring programming language How are you?")
6.6
You can get the input from the user using the getstring() function
Load"stdlib.ring"
Print("What is your name?)
cName
Print("Hello #{cName}")
6.4. Not Case-Sensitive 50

Ring Documentation, Release 1.14
6.7
You don't need to use `;' or press ENTER to separate statements. The previous program can be written in one line.
Load"stdlib.ring"
Print("What is your name?) cName=getstring() print("Hello #{cName}")
6.8
We can write one line comments and multi-line comments
The comment starts with # or //
Multi-lines comments are written between /* and*/
/*
Program Name : My first program using Ring
Date :.09.09
Author : Mahmoud Fayed
*/
Load"stdlib.ring"
Print("What is your name?) # print message on screen
cName=GetString() # get input from the user
print("Hello #{cName}") # say hello!
//"Bye!")
Note:Using // to comment a lines of code is just a code style.
6.7. No Explicit End For Statements 51

CHAPTER
SEVEN
VARIABLES
To create a new variable, you just need to determine the variable name & value. The value will determine the variable
type and you can change the value to switch between the types using the same variable name.
Syntax:
<Variable Name>Value>
Tip:The operator `=' is used here as an Assignment operator and the same operator can be used in conditions, but
for testing equality of expressions.
Note:The Variable will contains the real value (not a reference). This means that once you change the variable value,
the old value will be removed from memory (even if the variable contains a list or object).
7.1
Ring is a dynamic programming language that uses.
xHello" # x is a string
seex
x # x is a number (int)
seex
x.2 # x is a number (double)
seex
x1,2,3,4] # x is a list
seex # print list items
x # x is a string contains date
seex
x # x is a string contains time
seex
x true # x is a number (logical value = 1)
seex
x false # x is a number (logical value = 0)
seex
52

Ring Documentation, Release 1.14
7.2
We can use the assignment operator `=' to copy variables. We can do that to copy values like strings & numbers. Also,
we can copy complete lists & objects. The assignment operator will do a complete duplication for us. This operation
called
list=1,2,3,"four","five"]
list2 list
list=]
See # print the first list - no items to print
See"********"
Seelist2 # print the second list - contains 5 items
7.3
The language can automatically convert between numbers and strings.
Rules:
<NUMBER> STRING>->NUMBER>
<STRING>NUMBER>-> STRING>
Note:The same operator `+' can be used as an arithmetic operator or for string concatenation.
Example:
x # x is a number
y20" # y is a string
sum # sum is a number (y will be converted to a number)
MsgSum = # Msg is a string (sum will be converted to a string)
seeMsg
7.2. Deep Copy 53

CHAPTER
EIGHT
OPERATORS
In this chapter we will introduce the operators provided by the Ring programming language.
8.1
The next table presents all of the arithmetic operators provided by the Ring language. Assume variable X=50 and
variable Y=10 then:
OperatorDescriptionExampleResult
+ Add x+y 60
- Subtract x-y 40
* Multipliesx*y 500
/ Divide x/y 5
% Modulus x%y 0
++ Incrementx++ 51
- - Decrementx- - 49
8.2
The next table presents all of the relational operators provided by the Ring language. Assume variable X=50 and
variable Y=10 then:
OperatorDescription ExampleResult
= Equal x = y False
!= Not Equal x != y True
> Greater than x > y True
< Less than x < y False
>= Greater or Equalx >= y True
<= Less than or Equalx <= y False
54

Ring Documentation, Release 1.14
8.3
The next table presents all of the logical operators provided by the Ring language. Assume variable X=True and
variable Y=False then:
OperatorDescriptionExampleResult
and Logical ANDx and yFalse
or Logical ORx or y True
not Logical Notnot x False
Another style
OperatorDescriptionExampleResult
&& Logical ANDx && y False
|| Logical ORx || y True
! Logical Not! x False
8.4
The next table presents all of the bitwise operators provided by the Ring language. Assume variable X=8 and variable
Y=2 then:
OperatorDescription ExampleResult
& Binary AND x & y 0
| Binary OR x | y 10
^ Binary XOR x ^ y 10
~ Binary Ones Complement~x -9
<< Binary Left Shift x << y 32
>> Binary Right Shift x >> y 2
8.5
The next table presents all of the assignment operators provided by the Ring language.
Assume variable X=8 then:
OperatorDescription ExampleResult
= Assignment x = 10 x=10
+= Add AND assignment x += 5 x=13
-= Subtract AND assignmentx -= 3 x=5
*= Multiply AND assignmentx *= 2 x=16
/= Divide AND assignment x /= 3 x=2.67
%= Modulus AND assignment x %= 2 x=0
<<= Left shift AND assignmentx <<= 2x=32
>>= Right shift AND assignmentx >>= 2x=2
&= Bitwise AND assignment x &= 4 x=0
|= Bitwise OR and assignmentx |= 3 x=11
^= Bitwise XOR and assignmentx ^= 4 x=12
8.3. Logical Operators 55

Ring Documentation, Release 1.14
8.6
Operator Description
:literal using : before identier mean literal
Start:End create list contains items from start to end
[list items]dene list items
list[index]access list item
obj.name using the dot operator to access object members (attributes/methods).
obj {stmts}execute statements with direct access to object attributes & methods
func(para,. . . )call function using parameters separated by comma
? <expr> Print expression then new line
8.7
The next table present operators from higher precedence (Evaluated rst) to lower precedence.
Operator
. [] () {}
- ~ :Literal [list items]
++ - -
Start:End
* / %
+ -
<< >>
&
| ^
< > <= >=
= !=
not !
and or && ||
Assignment = += -= *= /= %=>>= <<= &= ^= |=
?
Example:
See3+5*4 # prints 23
8.6. Misc Operators 56

CHAPTER
NINE
CONTROL STRUCTURES - FIRST STYLE
In this chapter we are going to learn about the control structures provided by the Ring programming language.
9.1
•
Syntax:
ifExpression
Block of statements
butExpression
Block of statements
else
Block of statements
ok
Example:
see"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
ifnOption see"Enter your name : givenamesee"Hello
butnOption see"Sample : using if statement"
butnOption bye
else "bad option..."
ok
•
Syntax:
switchExpression
onExpression
Block of statements
other
Block of statements
off
57

Ring Documentation, Release 1.14
Example:
See"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
SwitchnOption
On1See"Enter your name : GivenameSee"Hello
On2See"Sample : using switch statement"
On3Bye
Other "bad option..."
Off
9.2
•
Syntax:
whileExpression
Block of statements
end
Example:
While
See"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
SwitchnOption
On1
See"Enter your name :
Givename
See"Hello
On2
See"Sample : using while loop"
On3
Bye
Other
See"bad option..."
Off
End
•
9.2. Looping 58

Ring Documentation, Release 1.14
Syntax:
foridentifier=expression toexpression stepexpression]
Block of statements
next
Example:
# print numbers from 1 to 10
forx to10seex next
Example:
# Dynamic loop
See"Start : givenStart
See"End : givenEnd
See"Step : givenStep
Forx tonEndStepnStep
seex
Next
Example:
# print even numbers from 0 to 10
forx to10step2
seex
next
Example:
# print even numbers from 10 to 0
forx to0step-2
seex
next
•
Syntax:
foridentifierin /String[stepexpression]
Block of statements
next
Example:
aList:10 # create list contains numbers from 1 to 10
forxinaListseex next# print numbers from 1 to 10
9.2. Looping 59

Ring Documentation, Release 1.14
9.3
We can use the Step option with For in to skip number of items in each iteration
Example:
aList:10 # create list contains numbers from 1 to 10
# print odd items inside the list
forxinaListstep2
seex
next
9.4
When we use (For in) we get items by reference.
This means that we can read/edit items inside the loop.
Example:
aList:5 # create list contains numbers from 1 to 5
# replace list numbers with strings
forxinaList
switchx
on1one"
on2two"
on3three"
on4four"
on5five"
off
next
seeaList # print the list items
9.5
Syntax:
do
Block of statements
againexpression
Example:
x
do
seex
x++
againx=
9.3. Using The Step option with For in 60

Ring Documentation, Release 1.14
9.6
Used to go outside one or more of loops.
Syntax:
exit[expression] # inside loop
Example:
forx to10
seex
ifx exit
next
9.7
The next example presents how to use the exit command to exit from two loops in one jump.
Example:
forx to10
fory to10
see"x=""
ifx andy
exit2 # exit from 2 loops
ok
next
next
9.8
Used to jump to the next iteration in the loop.
Syntax:
loop[expression] # inside loop
Example:
forx to10
ifx
see"Number Three"
loop
ok
seex
next
9.6. Exit Command 61

Ring Documentation, Release 1.14
9.9
The logical operators and/or follow the.
If the rst argument of the AND operator is zero, then there is no need to evaluate the second argument and the result
will be zero.
If the rst argument of the OR operator is one, then there is no need to evaluate the second argument and the result
will be one.
Example:
/*output
**nice
**nice
**great
*/
x
if(x andnice())and(y andnice())
see"great"
ok
funcnicesee"nice" return1
Example:
# No output
x
if(x andnice())and(y andnice())
see"great"
ok
funcnicesee"nice" return1
Example:
/*output
**nice
**great
*/
x
if(x andnice())or(y andnice())
see"great"
ok
funcnicesee"nice" return1
9.9. Short-circuit evaluation 62

Ring Documentation, Release 1.14
9.10
•
•
•
•
•
•
Example:
# output = message from the if statement
if5 # 5 evaluates to true because its not zero (0).
see"message from the if statement"
ok
9.10. Comments about evaluation 63

CHAPTER
TEN
CONTROL STRUCTURES - SECOND STYLE
In this chapter we are going to learn about the second style of control structures provided by the Ring programming
language.
10.1
•
Syntax:
ifExpression
Block of statements
elseifExpression
Block of statements
else
Block of statements
end
Example:
put"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
ifnOption put"Enter your name : getnameput"Hello
elseifnOption put"Sample : using if statement"
elseifnOption bye
else "bad option..."
end
•
Syntax:
switchExpression
caseExpression
Block of statements
else
(continues on next page)
64

Ring Documentation, Release 1.14
(continued from previous page)
Block of statements
end
Example:
Put"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
SwitchnOption
Case1Put"Enter your name : GetnamePut"Hello
Case2Put"Sample : using switch statement"
Case3Bye
Else "bad option..."
End
10.2
•
Syntax:
whileExpression
Block of statements
end
Example:
While
Put"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
SwitchnOption
Case1
Put"Enter your name :
Getname
Put"Hello
Case2
Put"Sample : using while loop"
Case3
Bye
Else
(continues on next page)
10.2. Looping 65

Ring Documentation, Release 1.14
(continued from previous page)
Put"bad option..."
End
End
•
Syntax:
foridentifier=expression toexpression stepexpression]
Block of statements
end
Example:
# print numbers from 1 to 10
forx to10putx end
Example:
# Dynamic loop
Put"Start : getnStart
Put"End : getnEnd
Put"Step : getnStep
Forx tonEndStepnStep
Putx
End
Example:
# print even numbers from 0 to 10
forx to10step2
Putx
end
Example:
# print even numbers from 10 to 0
forx to0step-2
putx
end
•
Syntax:
foridentifierin /String[stepexpression]
Block of statements
end
Example:
aList:10 # create list contains numbers from 1 to 10
forxinaListputx end# print numbers from 1 to 10
10.2. Looping 66

Ring Documentation, Release 1.14
10.3
try
Block of statements
catch
Block of statements
end
10.3. Exceptions 67

CHAPTER
ELEVEN
CONTROL STRUCTURES - THIRD STYLE
In this chapter we are going to learn about the third style of control structures provided by the Ring programming
language.
11.1
•
Syntax:
ifExpression {
Block of statements
elseifExpression
Block of statements
else
Block of statements
}
Example:
Load"stdlib.ring"
print("
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
")
nOption
ifnOption
print("Enter your name :)
name
print("Hello #{name} ")
elseifnOption
print("Sample : using if statement ")
elseifnOption
bye
else
print("bad option... ")
}
68

Ring Documentation, Release 1.14
•
Syntax:
switchExpression {
caseExpression
Block of statements
else
Block of statements
}
Example:
Load"stdlib.ring"
print("
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
")
nOption
switchnOption {
case1
print("Enter your name :)
name
print("Hello #{name} ")
case2
print("Sample : using switch statement ")
case3
Bye
else
print("bad option... ")
}
11.2
•
Syntax:
whileExpression {
Block of statements
}
Example:
Load"stdlib.ring"
While {
print("
(continues on next page)
11.2. Looping 69

Ring Documentation, Release 1.14
(continued from previous page)
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
")
nOption
switchnOption {
case1
print("Enter your name :)
name
print("Hello #{name} ")
case2
print("Sample : using switch statement ")
case3
Bye
else
print("bad option... ")
}
}
•
Syntax:
foridentifier=expression toexpression stepexpression]
Block of statements
}
Example:
# print numbers from 1 to 10
load"stdlib.ring"
forx to10
print("#{x} ")
}
Example:
load"stdlib.ring"
# Dynamic loop
print("Start :) nStart
print("End :) nEnd
print("Step :) nStep
forx tonEndstepnStep {
print("#{x} ")
}
Example:
load"stdlib.ring"
(continues on next page)
11.2. Looping 70

Ring Documentation, Release 1.14
(continued from previous page)
# print even numbers from 0 to 10
forx to10step2
print("#{x} ")
}
Example:
load"stdlib.ring"
# print even numbers from 10 to 0
forx to0step-2
print("#{x} ")
}
•
Syntax:
foridentifierin /String[stepexpression]
Block of statements
}
Example:
load"stdlib.ring"
aList:10 # create list contains numbers from 1 to 10
forxinaList { print("#{x} ") } # print numbers from 1 to 10
Example:
load"stdlib.ring"
aList:10 # create list contains numbers from 1 to 10
# print odd items inside the list
forxinaListstep2
print("#{x} ")
}
When we use (For in) we get items by reference.
This means that we can read/edit items inside the loop.
Example:
load"stdlib.ring"
aList:5 # create list contains numbers from 1 to 5
# replace list numbers with strings
forxinaList {
switchx {
case1one"
case2two"
case3three"
case4four"
case5five"
}
(continues on next page)
11.2. Looping 71

Ring Documentation, Release 1.14
(continued from previous page)
}
print(aList) # print the list items
11.3
try{
Block of statements
catch
Block of statements
}
11.3. Exceptions 72

CHAPTER
TWELVE
GETTING INPUT
We can get input from the keyboard using
•
•
•
12.1
Syntax:
GiveVariableName
Example:
See"Enter the first number : GivenNum1
See"Enter the second number : GivenNum2
See"Sum :
Output:
Enter the first number :
Enter the second number :
Sum :
12.2
We can get one character from the standard input using the GetChar() function
Syntax:
GetChar()-->
Example:
While
See"
Main Menu
(1) Say Hello
(continues on next page)
73

Ring Documentation, Release 1.14
(continued from previous page)
(2)Exit
"
Option
GetChar() GetChar() # End of line
# the previous two lines can be replaced with the next line
# Give Option
ifOption
see"Enter your name : givecName
see"Hello
else
bye
ok
End
12.3
We can get input from the keyboard using the Input() function
Syntax:
Input(nCount)--> string
The function will wait until nCount characters (at least) are read
Example:
See"Enter message (30 characters) :30)
See"Message :
12.3. Input() Function 74

CHAPTER
THIRTEEN
FUNCTIONS - FIRST STYLE
In this chapter we are going to learn about the next topics :-
•
•
•
•
•
•
•
•
13.1
To dene new function
Syntax:
func<function_name>parameters]
Block of statements
Note:No keyword is required to end the function denition.
Example:
funchello
see"Hello from function"
75

Ring Documentation, Release 1.14
13.2
To call function without parameters, we type the function name then ()
Tip:We can call the function before the function denition and the function code.
Example:
hello()
funchello
see"Hello from function"
Example:
first() second()
funcfirst see"message from the first function"
funcsecondsee"message from the second function"
13.3
To declare the function parameters, after the function name type the list of parameters as a group of identiers separated
by comma.
Example:
funcsum x,y
seex+y+nl
13.4
To send parameters to function, type the parameters inside () after the function name
Syntax:
funcname(parameters)
Example:
/*output
**8
**3000
*/
sum(3,5) sum(1000,2000)
funcsum x,yseex+y+nl
13.2. Call Functions 76

Ring Documentation, Release 1.14
13.5
Using the Ring programming language, the Main Function is optional, when it's dened, it will be executed after the
end of other statements.
if no other statements comes alone, the main function will be the rst
Example:
# this program will print the hello world message first then execute the main function
See"Hello World!"
funcmain
see"Message from the main function"
13.6
The Ring programming language uses
Variables dened inside functions (including function parameters) are local variables. Variables dened outside func-
tions (before any function) are global variables.
Inside any function we can access the variables dened inside this function beside the global variables.
Example:
# the program will print numbers from 10 to 1
x # x is a global variable.
funcmain
fort to10 # t is a local variable
mycounter() # call function
next
funcmycounter
seex # print the global variable value
x-- # decrement
Note:Using the main function before the for loop declare the t variable as a local variable, It's recommended to use
the main functions instead of typing the instructions directly to set the scope of the new variables to local.
13.5. Main Function 77

Ring Documentation, Release 1.14
13.7
The function can return a value using the Return command.
Syntax:
Return[Expression]
Tip:the Expression after the return command is optional and we can use the return command to end the function
execution without returning any value.
Note:if the function doesn't return explicit value, it will return NULL (empty string = “” ).
Example:
ifnovalue() NULL
See"the function doesnt return a value"
ok
funcnovalue
13.8
The Ring programming language support
Example:
seefact(5) # output = 120
funcfact xifx return1else x*fact(x-1) ok
13.7. Return Value 78

CHAPTER
FOURTEEN
FUNCTIONS - SECOND STYLE
In this chapter we are going to learn about the next topics :-
•
•
•
•
•
•
•
•
14.1
To dene new function
Syntax:
def<function_name>parameters]
Block of statements
[end]
Note:the keyword `end' is optional.
Example:
defhello
put"Hello from function"
end
79

Ring Documentation, Release 1.14
14.2
To call function without parameters, we type the function name then ()
Tip:We can call the function before the function denition and the function code.
Example:
hello()
defhello
put"Hello from function"
end
Example:
first() second()
deffirst put"message from the first function"
defsecondput"message from the second function"
14.3
To declare the function parameters, after the function name type the list of parameters as a group of identiers separated
by comma.
Example:
defsum x,y
putx+y+nl
end
14.4
To send parameters to function, type the parameters inside () after the function name
Syntax:
funcname(parameters)
Example:
/*output
**8
**3000
*/
sum(3,5) sum(1000,2000)
defsum x,yputx+y+nl
14.2. Call Functions 80

Ring Documentation, Release 1.14
14.5
Using the Ring programming language, the Main Function is optional, when it's dened, it will be executed after the
end of other statements.
if no other statements comes alone, the main function will be the rst
Example:
# this program will print the hello world message first then execute the main function
put"Hello World!"
defmain
put"Message from the main function"
end
14.6
The Ring programming language uses
Variables dened inside functions (including function parameters) are local variables. Variables dened outside func-
tions (before any function) are global variables.
Inside any function we can access the variables dened inside this function beside the global variables.
Example:
# the program will print numbers from 10 to 1
x # x is a global variable.
defmain
fort to10 # t is a local variable
mycounter() # call function
end
end
defmycounter
putx # print the global variable value
x-- # decrement
end
Note:Using the main function before the for loop declare the t variable as a local variable, It's recommended to use
the main functions instead of typing the instructions directly to set the scope of the new variables to local.
14.5. Main Function 81

Ring Documentation, Release 1.14
14.7
The function can return a value using the Return command.
Syntax:
Return[Expression]
Tip:the Expression after the return command is optional and we can use the return command to end the function
execution without returning any value.
Note:if the function doesn't return explicit value, it will return NULL (empty string = “” ).
Example:
ifnovalue() NULL
put"the function doesnt return a value"
end
defnovalue
14.8
The Ring programming language support
Example:
putfact(5) # output = 120
deffact xifx return1else x*fact(x-1) end
14.7. Return Value 82

CHAPTER
FIFTEEN
FUNCTIONS - THIRD STYLE
In this chapter we are going to learn about the next topics :-
•
•
•
•
•
•
•
•
15.1
To dene new function
Syntax:
func<function_name>parameters]{]
Block of statements
[}]
Example:
load"stdlib.ring"
funchello {
print("Hello from function ")
}
83

Ring Documentation, Release 1.14
15.2
To call function without parameters, we type the function name then ()
Tip:We can call the function before the function denition and the function code.
Example:
load"stdlib.ring"
hello()
funchello {
print("Hello from function ")
}
Example:
load"stdlib.ring"
first() second()
funcfirst { print("message from the first function ") }
funcsecond { print("message from the second function ") }
15.3
To declare the function parameters, after the function name type the list of parameters as a group of identiers separated
by comma.
Example:
load"stdlib.ring"
funcsum(x,y) {
print(x+y)
}
15.4
To send parameters to function, type the parameters inside () after the function name
Syntax:
funcname(parameters)
Example:
15.2. Call Functions 84

Ring Documentation, Release 1.14
/*output
**8
**3000
*/
load"stdlib.ring"
sum(3,5) sum(1000,2000)
funcsum(x,y) { print(x+y) }
15.5
Using the Ring programming language, the Main Function is optional, when it's dened, it will be executed after the
end of other statements.
if no other statements comes alone, the main function will be the rst
Example:
# this program will print the hello world message first then execute the main function
load"stdlib.ring"
print("Hello, World! ")
funcmain {
print("Message from the main function ")
}
15.6
The Ring programming language uses
Variables dened inside functions (including function parameters) are local variables. Variables dened outside func-
tions (before any function) are global variables.
Inside any function we can access the variables dened inside this function beside the global variables.
Example:
# the program will print numbers from 10 to 1
load"stdlib.ring"
x # x is a global variable.
funcmain {
fort to10 # t is a local variable
mycounter() # call function
}
}
funcmycounter {
(continues on next page)
15.5. Main Function 85

Ring Documentation, Release 1.14
(continued from previous page)
print("#{x} ") # print the global variable value
x-- # decrement
}
Note:Using the main function before the for loop declare the t variable as a local variable, It's recommended to use
the main functions instead of typing the instructions directly to set the scope of the new variables to local.
15.7
The function can return a value using the Return command.
Syntax:
Return[Expression]
Tip:the Expression after the return command is optional and we can use the return command to end the function
execution without returning any value.
Note:if the function doesn't return explicit value, it will return NULL (empty string = “” ).
Example:
load"stdlib.ring"
ifnovalue() NULL{
print("the function doesnt return a value ")
}
funcnovalue { }
15.8
The Ring programming language support
Example:
load"stdlib.ring"
print( fact(5) ) # output = 120
funcfact(x) {ifx return1else x*fact(x-1) } }
15.7. Return Value 86

CHAPTER
SIXTEEN
PROGRAM STRUCTURE
In this chapter we will learn about using many source code les in the same project.
16.1
Each source code le may contains the next sections (in the same order).
Source Code File Sections
Load Files
Statements and Global Variables
Functions
Packages and Classes
The application maybe one or more of les.
16.2
To include another source le in the project, just use the load command.
Syntax:
Load"filename.ring"
Note:The Load command is executed directly by the compiler in the parsing stage
Tip:if you don't know the le name until the runtime, or you need to use functions to get the le path, just use eval().
Example:
# File : Start.ring
Load"sub.ring"
sayhello("Mahmoud")
87

Ring Documentation, Release 1.14
# File : sub.ring
funcsayhello cName
see"Hello
16.3
Using the `load' command we can use many ring source les in the same project
But all of these les will share the same global scope
We have also the “Load Package” command
Using “Load Package” we can load a library (*.ring le) in new global scope
This is very useful to create libraries that avoid conicts in global variables
Example:
File: loadpackage.ring
x
?Hello, World!"
loadpackagetestloadpackage.ring"
?
test()
File: testloadpackage.ring
?Hello from testloadpackage.ring"
x
test()
functest
?
Output:
Hello, World!
Hello from testloadpackage.ring
1000
100
1000
16.3. Load Package 88

Ring Documentation, Release 1.14
16.4
Ring 1.12 comes with the Load Again command
Using this command we can load the Ring source le which contains constants more than one time.
This is useful when using Ring source les for translations through global constants.
Example:
The next function is part from a project which support Arabic and English languages
The les english.ring and arabic.ring contains constants for translation
One of these les is loaded in the start of the program
Loading the same le again using the (Load) command is not possible
Because the (Load) command load the same source le only for the rst time and ignore next times.
So we have to use the (Load Again) command.
Where we can use these les again during the runtime as in the next code
funcsetLang nLanguage
ifC_ENV_DEFAULT_LANG
return
ok
C_ENV_DEFAULT_LANG
# Change the language
switchnLanguage
onC_TRANSLATION_ENGLISH
load "translation/english.ring"
onC_TRANSLATION_ARABIC
load "translation/arabic.ring"
off
16.4. Load Again 89

CHAPTER
SEVENTEEN
LISTS
In this chapter we are going to learn how to deal with lists.
17.1
We can create new lists by dening the list items inside square bracts.
Example:
aList1,2,3,4,5]
Also we can create new lists using the : operator
Example:
aList:5
aList2a":"z"
Example:
aList:1
aList2z":"a"
Also we can create lists using the list() function
Syntax:
list=list(size)
To create 2D list
list=list(nRows,nCols)
Example (1)
aList list(10) # aList contains 10 items
Example (2)
aList list(5,4) # Create 2D List contains 5 rows and 4 columns
Note:the list index start from 1
90

Ring Documentation, Release 1.14
17.2
To add new items to the list, we can use the Add() function.
Syntax:
Add(List,Item)
Example:
aList"one","two"]
add(aList,"three")
seeaList
Also we can do that using the + operator.
Syntax:
List+
Example:
aList:10 # create list contains numbers from 1 to 10
aList # add number 11 to the list
seeaList # print the list
17.3
We can get the list size using the len() function
Syntax:
Len(List)
Example:
aList:20 seelen(aList) # print 20
17.4
To delete an item from the list, we can use the del() function
Syntax:
del(list,index)
Example:
aList"one","two","other","three"]
Del(aList,3) # delete item number three
seeaList # print one two three
17.2. Add Items 91

Ring Documentation, Release 1.14
17.5
To get an item from the list, we uses the next syntax
List[Index]
Example:
aList"Cairo","Riyadh"]
see"Egypt :[1]
"KSA :[2]
17.6
To set the value of an item inside the list, we can use the next syntax
List[Index]
Example:
aList list(3)# create list contains three items
aList[1]one"[2]two"[3]three"
seeaList
17.7
To nd an item inside the list we can use the nd() function
Syntax:
Find(List,ItemValue)-->
Find(List,ItemValue,nColumn)--> innColumn, returns the Item Index
Find(List,ItemValue,nColumn,cAttribute)-->
Example:
aList"one","two","three","four","five"]
seefind(aList,"three") # print 3
Example:
mylist["one",1],
["two",2],
["three",3]]
seefind(mylist,"two",1) # print 2
seefind(mylist,2,2) # print 2
Also we can use the binarysearch() function to search in sorted list.
Syntax:
17.5. Get List Item 92

Ring Documentation, Release 1.14
BinarySearch(List,ItemValue)-->
BinarySearch(List,ItemValue,nColumn)--> innColumn, returns the Item Index
Example:
aList"one","two","three","four","five"]
aList
seebinarysearch(aList,"three")
Output:
five
four
one
three
two
4
17.8
We can sort the list using the sort() function.
Syntax:
Sort(List)--> List
Sort(List,nColumn)--> ListbasedonnColumn
Sort(List,nColumn,cAttribute)--> ListbasedonObject Attribute
Example:
aList10,12,3,5,31,15]
aList seeaList# print 3 5 10 12 15 31
We can sort list of strings
Example:
mylist"mahmoud","samir","ahmed","ibrahim","mohammed"]
seemylist # print list before sorting
mylist # sort list
see"list after sort"+nl
seemylist # print ahmed ibrahim mahmoud mohammed samir
We can sort a list based on a specic column.
Example:
aList"mahmoud",15000]
["ahmed",
["samir",
["mohammed",
["ibrahim",11000
aList21)
seeaList2
17.8. Sort 93

Ring Documentation, Release 1.14
Output:
ahmed
14000
ibrahim
11000
mahmoud
15000
mohammed
12000
samir
16000
17.9
We can reverse a list using the reverse() function.
Syntax:
Reverse(List)--> List
Example:
aList10,20,30,40,50]
aList
seeaList # print 50 40 30 20 10
17.10
To insert an item in the list we can use the insert() function.
Syntax:
Insert(List,Index,Item)
The inserted item will be AFTER the Index
Example:
aList"A","B","D","E"]
insert(aList,2,"C") # Inserts AFTER Index 2, "C" into Position 3
seeaList # print A B C D E
17.9. Reverse 94

Ring Documentation, Release 1.14
17.11
The list may contain other lists
Example:
aList10,20,30]100,1000,5000]
aList2
"one","two",
[3,4],
[20,30],"three",
"four",
"five",[100,200,300]
]
]
seeaList[2] # print 10 20 30
seeaList[4][3] # print 5000
seeaList2[5][2] # print four
seeaList2[5][4][3] # print 300
17.12
We can copy lists (including nested lists) using the Assignment operator.
Example:
aList
"one","two",
[3,4],
[20,30],"three",
"four",
"five",[100,200,300]
]
]
aList2 # Copy aList to aList2
aList2[5]other" # modify item number five
seeaList2[5] # print other
seeaList[5] # print three four five 100 200 300
17.13
Lists are
Example:
aList1,2,3,4,5]
seeaList[10] # print 5
seemylist() # print 10 20 30 40 50
funcduplicatelist
(continues on next page)
17.11. Nested Lists 95

Ring Documentation, Release 1.14
(continued from previous page)
nMax list)
forx tonMax
list+list[x]
next
return
funcmylistreturn[10,20,30,40,50]
17.14
We can use the list and the list items while we are dening the list for the rst time.
Example:
aList1,2,3,4,5][1][1]
seeaList # print 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Example:
x,, x
? # print 1 2 1 2
? # print 3
?[1] # print 1
?[2] # print 2
?[3] # print 1 2
Output:
1
2
1
2
3
1
2
1
2
17.15
Lists are passed to functions by reference, This means that the called function will work on the same list and can
modify it.
Example:
funcmain
aList1,2,3,4,5] # create list, local in function main
myfunc(aList) # call function, pass list by reference
seeaList # print 1 2 3 4 5 6 7 8 9 10
funcmyfunclist
list+6,7,8,9,10]
17.14. Using Lists during denition 96

Ring Documentation, Release 1.14
17.16
Instead of using numbers to determine the item index when we get item value or set item value, We can access items
using string index if the item is a list contains two items and the rst item is a string.
Example:
aList"one",1]"two",2]"three",3]
seeaList["one"]
aList["two"]
aList["three"] # print 1 2 3
This type of lists can be dened in a better syntax using the : and = operators.
Example:
aList
seeaList["one"]
aList["two"]
aList["three"] # print 1 2 3
seeaList[1] # print one 1
Tip:using : before identier (one word) means literal
Note:using = inside list denition create a list of two items where the rst item is the left side and the second item is
the right side.
We can add new items to the list using the string index
Example:
aList]
aList["Egypt"]Cairo"
aList["KSA"]Riyadh"
seeaList["Egypt"] # print Cairo
aList["KSA"] # print Riyadh
17.17
This type of lists is very good for passing parameters to functions Where the order of parameters will not be important
(we can change the order).
Also some parameters maybe optional.
Example:
myconnect (myserver.com"
:usernamemahmoud"password"
funcmyconnect mypara
# print connection details
(continues on next page)
17.16. Access List Items by String Index 97

Ring Documentation, Release 1.14
(continued from previous page)
see"User Name :[:username]
"Password :[:password]
"Server :[:server]
"Port :[:port]
17.18
Passing Arguments or Parmameters to a Function in an array format
Example:
myList5,7,3,9] ### list with args or parms in an array
result
See"Sum result:+n
funcsum(aList)
acc
sizeList
fori tosizeList
SeeaList[i]nl
acc[i]
next
returnacc
17.19
Return Parameters from a Function in an Array or Hash Format
Example:
sudoku2,9,0],
[0,0,1],
[0,0,0]
aOutput
See"Return Array: T/F:+[1]"+[2]"+
˓→aOutput[3]nl
aOutput
See"Return Hash.: T/F:+[:lValue]"+[:nRow]"
˓→"+[:nCol]nl
###----------------------------------
### isSolvedSoduku - Return ARRAY
FuncmyFunctionArray(sudoku)
forRow to9
forCol to9
ifsudoku[Row][Col]
//----------------------------
(continues on next page)
17.18. Passing Parameters or Argumnents Using List Array 98

Ring Documentation, Release 1.14
(continued from previous page)
//ReturnArray with
return[False, Row, Col]
ok
next
next
return[True, Row, Col]
###----------------------------------
### isSolvedSoduku - Return HASH
FuncmyFunctionHash(sudoku)
forRow to3
forCol to3
ifsudoku[Row][Col]
//---------------------------------
//ReturnHash Table with
return[ False,
:nRow
:nCol
]
ok
next
next
return[ False, :nRow
###-----------------------------
17.20
A Multi-Dimensional Array of any size can be built using recursion in a Function
Example:
###---------------------------------------------------------
### Create Array -- Dimensions Any Size: 3D, 4D, 5D etc
dimList4,3,4]
bList
###---------------------------------------------------------
### Populate the arrays using a counter 1 , 4x4x4 = 256 , 2x3x4x5x6 = 720
Counter
forCol=1 todimList[1]
forRow=1 todimList[2]
forDep=1 todimList[3]
blist[Col][Row][Dep]
Counter++
next
next
next
(continues on next page)
17.20. Creating a Multi-Dimensional Array using List 99

Ring Documentation, Release 1.14
(continued from previous page)
###-----------------------------------------------
### Print the array elements in block format
forCol=1 todimList[1]
forRow=1 todimList[2]
forDep=1 todimList[3]
SeebList[Col][Row][Dep] See"
next
Seenl
next
Seenl
next
###===========================
### FUNCTIONS
###-----------------------------------------------------------------------
### Recursive Create a Dimension Array
### Call by passing an array of dimesions: dimList = [2,3,4,5]
### Drop the first entry every iteration call, making newParms
###
### Example:
### dimList = [4,2,3,2] <<< Number and size of dimensions in array
˓→format
### bList = createDimList(dimList) <<< Call using the array as input
funccreateDimList(dimArray)
sizeList
newParms]
fori tosizeList
Add(newParms, dimArray[i])
next
alist list(dimArray[1])
ifsizeList
returnaList
ok
fortinalist
t
next
returnalist
17.20. Creating a Multi-Dimensional Array using List 100

Ring Documentation, Release 1.14
17.21
We can swap the list items using the Swap() function.
Example:
aList:one,:two,:four,:three]
seeaList
seecopy(" *",50)
swap(aList,3,4)
seeaList
Output
one
two
four
three
**************************************************
one
two
three
four
17.21. Swap Items 101

CHAPTER
EIGHTEEN
STRINGS
In this chapter we are going to learn about strings creation and manipulation.
18.1
Syntax:
cStrThis is a string"
cStr2Anothertring
cStr3
cStr4another"string
18.2
We can get the string length (letters count inside a string) using the len() function
Syntax:
len(string)--> stringlength
Example:
cStrHow are you?"
seecStr
see"String size :
18.3
Syntax:
lower(string)--> stringletterstolowercase
upper(string)--> stringletterstoUPPERcase
Example:
cStrWelcome To The Ring Programming Language"
seecStr
102

Ring Documentation, Release 1.14
18.4
We can access a letter inside a string by the letter index
Syntax:
string[index]--> get letter
string[index] # set string letter
Example:
# print user name letter by letter (each letter in new line)
See"Hello, Enter your name : givecName
forx tolen(cName)
seenl[x]
next
We can use for in to get string letters.
Example:
# print user name letter by letter (each letter in new line)
See"Hello, Enter your name : givecName
forxincName
seenl
next
We can modify the string letters
Example:
# convert the first letter to UPPER case
See"Enter your name : givecName
cName[1][1])
see"Hello
18.5
We can get a specied number of characters from a string using the Left() function.
The starting position is 1.
Syntax:
Left(string,count)
Example:
seeleft("Hello World!",5) # print Hello
18.4. Access String Letters 103

Ring Documentation, Release 1.14
18.6
We can get a specied number of characters from a string using the Right() function.
The starting position is the last character on the right.
Syntax:
Right(string,count)
Example:
seeRight("Hello World!",6) # print World!
18.7
We can remove all leading and trailing spaces from a string using the Trim() function.
Syntax:
trim(string)
Example:
cMsg
seetrim(cMsg) # print Welcome
18.8
We can duplicate a string more than one time using the copy() function.
Syntax:
copy(string,nCount)--> stringreplicated nCount times
Example
seecopy(" ***hello***",3) # print***hello******hello******hello***
18.9
We can count the number of lines inside a string using the Lines() function.
Syntax:
lines(string)--> string
Example:
18.6. Right() Function 104

Ring Documentation, Release 1.14
cStrHello
How are you?
are you fine?"
seelines(cStr) # print 3
18.10
We can work on sub strings inside a string using the substr() function. Using Substr() we can
•
•
•
•
18.11
Syntax:
substr(string,substring)--> in
Example:
cStrWelcome to the Ring programming language"
seesubstr(cStr,"Ring") # print 16
18.12
Syntax:
substr(string,position)--> Getsubstring starting frompositionto
Example:
cStrWelcome to the Ring programming language"
nPos"Ring") # nPos = 16
seesubstr(cStr,nPos) # print Ring programming language
18.13
Syntax:
substr(string,position,count)--> Getcharacters starting fromposition
Example:
18.10. Substr() Function 105

Ring Documentation, Release 1.14
cStrWelcome to the Ring programming language"
nPos"Ring") # nPos = 16
seesubstr(cStr,nPos,4) # print Ring
18.14
Syntax:
substr(string,substring,newsubstring)--> string(Matchcase)
substr(string,substring,newsubstring,1)--> string(Ignorecase)
Example:
cStrWelcome to the New programming language"
seesubstr(cStr,"New","Ring") # print Welcome to the Ring programming language
seesubstr(cStr,"new","Ring",1)+ # print Welcome to the Ring programming language
18.15
We can compare between two strings using the strcmp() function.
Syntax:
strcmp(cString1,cString2)--> ifcString1
value ifcString1
value ifcString1
Example:
seestrcmp("hello","hello")
strcmp("abc","bcd")
strcmp("bcd","abc")
Output:
0
-1
1
18.16
We can convert string lines to list items using the str2list() function. Also we can convert the list to a string using
list2str() function.
Syntax:
str2list(string)--> listcontains thestringlines
list2str(list)--> stringcontains thelistitems
Example:
18.14. Transform Substring To Another Substring 106

Ring Documentation, Release 1.14
/*output:
**Items :
**Item : Hello
**Item : How are you
**Item : are you fine
**Item :ok
**list2Str result
**How are you
**are you fine
**ok
**Done
*/
mystrHello
How are you
are you fine
ok"
mylist
see"Items :
forxinmylist
see"Item :
next
newstr
see"list2Str result =
ifmystr
seenlDone"
else
seenlError!"
ok
18.17
From Ring 1.0 we can create binary strings and do operations on these strings.
Starting from Ring 1.8, we can get individual characters from these strings and merge them together using the `+'
operator.
Example:
cStrWelcome"
?[1][2][5]
v[1][2][5]
?
?
c1[1]
?
aList1,2,3]
cStr"
foriteminaList
cStr=
next
(continues on next page)
18.17. Merge binary characters 107

Ring Documentation, Release 1.14
(continued from previous page)
?All String"
?
?First Part"
n1[1][2][3][4]
?
?Second Part"
n2[5][6][7][8]
?
?Third Part"
n3[9][10][11][12]
?
?All String"
cString[1][2][3][4]
cStr[5][6][7][8]
cStr[9][10][11][12]
?
?[1])
?[2])
Output:
Weo
Weo
3
W
All String
12
First Part
4
Second Part
4 }
Third Part
4
All String
12
1
1
18.17. Merge binary characters 108

CHAPTER
NINETEEN
DATE AND TIME
In this chapter we are going to learn about the date and time functions.
19.1
Syntax:
Clock()--> fromprogram start
Example:
See"Calculate performance"
t1
forx to1000000next
seeclock()
19.2
Return how many clocks in one second
Syntax:
clockspersecond()--> inone second
Example:
# Wait 1 second
t
whileclock()= end
109

Ring Documentation, Release 1.14
19.3
We can get the system time using the Time() function.
Example:
See"Time :
19.4
We can get the date using the Date() function.
Syntax:
Date()--> Stringrepresent the datedd/mm/yyyy"
Example:
See"Date : # Date : 24/05/2015
19.5
We can print the date and the time information using the TimeList() function.
Syntax:
TimeList()--> Listcontains the time anddate information.
The next table presents the list items
19.3. Time() Function 110

Ring Documentation, Release 1.14
indexvalue
1 abbreviated weekday name
2 full weekday name
3 abbreviated month name
4 full month name
5 Date & Time
6 Day of the month
7 Hour (24)
8 Hour (12)
9 Day of the year
10 Month of the year
11 Minutes after hour
12 AM or PM
13 Seconds after the hour
14 Week of the year (sun-sat)
15 day of the week
16 date
17 time
18 year of the century
19 year
20 time zone
21 percent sign
Example:
/*Output:
**Sun abbreviated weekday name
**Sunday full weekday name
**May abbreviated month name
**May full month name
**05/24/15:58:38
**24
**0924)
**0912)
**144
**05
**58
**AM AM orPM
**38
**21-sat)
**0
**05/24/15
**09:58:38
**15
**2015
**Arab Standard Time time zone
**%
*/
SeeTimeList()
Example:
See"Day Name :[2] # Sunday
19.5. TimeList() Function 111

Ring Documentation, Release 1.14
Example:
See"Month Name :[4] # May
19.6
Syntax:
AddDays(cDate,nDays)--> fromcDateandafter nDays
Example:
cDate
seecDate # 24/05/2015
cDate10)
seecDate # 03/06/2015
19.7
Syntax:
DiffDays(cDate1,cDate2)-->
Example:
cDate1
seecDate1 # 24/05/2015
cDate210)
seecDate2 # 03/06/2015
see"DiffDays = # -10
see"DiffDays = # 10
19.8
Syntax:
EpochTime( cDate, cTime )-->
Example:
###-------------------------------------------------------------
# EpochTime()
# Example --- EpochSec = EpochTime( Date(), Time() )
# Call Format: EpochSec = EpochTime( "15/07/2016", "10:15:30" )
# EpochSec = 1468577730
#---------------------------------------------------------------
FuncEpochTime(Date, Time)
arrayDate/")
(continues on next page)
19.6. AddDays() Function 112

Ring Documentation, Release 1.14
(continued from previous page)
arrayTime:")
Year[3][2][1]
Hour[1][2][3]
cDate1"/"+"/"+
cDate201/01/"
DayOfYear
### Formula
tm_sec *1
tm_min *60
tm_hour *3600
tm_yday *86400
tm_year
tm_year1) *31536000
tm_year2) *86400
tm_year3) *86400
tm_year4) *86400
### Result
EpochSec
tm_year1
returnEpochSec
19.8. EpochTime() Function 113

CHAPTER
TWENTY
CHECK DATA TYPE AND CONVERSION
In this chapter we are going to learn about the functions that can be used for
•
•
•
20.1
The next functions can be used to check the data type
•
•
•
•
•
20.2
Using the IsString() function we can know if the value is a string or not
Syntax:
IsString(value)--> ifthe value is a string 0if
Example:
seeisstring(5) # print 0
isstring("hello") # print 1
114

Ring Documentation, Release 1.14
20.3
Using the IsNumber() function we can know if the value is a number or not
Syntax:
IsNumber(value)--> ifthe value is a number or0if
Example:
seeisnumber(5) # print 1
isnumber("hello") # print 0
20.4
Using the IsList() function we can know if the value is a list or not
Syntax:
IsList(value)--> ifthe value is alist 0if
Example:
seeislist(5) # print 0
islist("hello") # print 0
islist([1,3,5]) # print 1
20.5
We can know the type of a value using the Type() Function.
Syntax:
Type(value)--> String
Example:
seeType(5) # print NUMBER
Type("hello") # print STRING
Type([1,3,5]) # print LIST
20.6
We can check the value to know if it's null or not using the IsNULL() function
Syntax:
IsNULL(value)--> ifthe value isNULL 0if
Example:
20.3. IsNumber() Function 115

Ring Documentation, Release 1.14
seeisnull(5) # print 0
isnull("hello") # print 0
isnull([1,3,5]) # print 0
isnull("") # print 1
isnull("NULL") # print 1
20.7
The next functions can be used to check character
•
•
•
•
•
•
•
•
•
•
•
20.8
We can test a character or a string using the IsAlNum() Function
Syntax:
IsAlNum(value)--> ifthe value is digit/letter or0if
Example:
seeisalnum("Hello") # print 1
isalnum("123456") # print 1
isalnum("ABCabc123") # print 1
isalnum("How are you") # print 0 because of spaces
20.7. Check Character 116

Ring Documentation, Release 1.14
20.9
We can test a character or a string using the IsAlpha() Function
Syntax:
IsAlpha(value)--> ifthe value is a letter or0if
Example:
seeisalpha("Hello") # print 1
isalpha("123456") # print 0
isalpha("ABCabc123") # print 0
isalpha("How are you") # print 0
20.10
We can test a character or a string using the IsCntrl() Function
Syntax:
IsCntrl(value)--> ifthe value is a control character (no printing position)
or0if
Example:
Seeiscntrl("hello") # print 0
iscntrl(nl) # print 1
20.11
We can test a character or a string using the IsDigit() Function
Syntax:
IsDigit(value)--> ifthe value is a digit or0if
Example:
seeisdigit("0123456789") # print 1
isdigit("0123a") # print 0
20.12
We can test a character or a string using the IsGraph() Function
Syntax:
IsGraph(value)--> ifthe value can be printed (Except space) or0if
Example:
20.9. IsAlpha() Function 117

Ring Documentation, Release 1.14
seeisgraph("abcdef") # print 1
isgraph("abc def") # print 0
20.13
We can test a character or a string using the IsLower() Function
Syntax:
IsLower(value)--> ifthe value is lowercase letter or0if
Example:
seeislower("abcDEF") # print 0
islower("ghi") # print 1
20.14
We can test a character or a string using the IsPrint() Function
Syntax:
IsPrint(value)--> ifthe value occupies a printing position or0if
Example:
seeisprint("Hello") # print 1
isprint("Nice to see you") # print 1
isprint(nl) # print 0
20.15
We can test a character or a string using the IsPunct() Function
Syntax:
IsPunct(value)--> ifthe value is a punctuation character or0if
Example:
seeispunct("hello") # print 0
ispunct(",") # print 1
20.13. IsLower() Function 118

Ring Documentation, Release 1.14
20.16
We can test a character or a string using the IsSpace() Function
Syntax:
IsSpace(value)--> ifthe value is a white-space or0if
Example:
seeisspace(") # print 1
isspace("test") # print 0
20.17
We can test a character or a string using the IsUpper() Function
Syntax:
IsUpper(value)--> ifthe value is an uppercase alphabetic letter or0if
Example:
seeisupper("welcome") # print 0
isupper("WELCOME") # print 1
20.18
We can test a character or a string using the IsXdigit() Function
Syntax:
IsXdigit(value)--> ifthe value is a hexdecimal digit character or0if
Example:
seeisxdigit("0123456789abcdef") # print 1
isxdigit("123z") # print 0
20.19
The next functions can be used for conversion
•
•
•
•
•
20.16. IsSpace() Function 119

Ring Documentation, Release 1.14
•
•
•
20.20
We can convert strings to numbers using the Number() function or the + operator.
Syntax:
Number(string)-->
0 string--->
Example:
seenumber("5") # print 10
see010" # print 12
20.21
We can convert numbers to strings using the String() function or the + operator.
Syntax:
String(number)--> String
""--> String
Example:
see (5) # print 55
see"" # print 102
20.22
We can get the ASCII code for a letter using the Ascii() function
Syntax:
Ascii(character)-->
Example:
Seeascii("m") # print 109
ascii("M") # print 77
20.20. Number() Function 120

Ring Documentation, Release 1.14
20.23
We can convert the ASCII code to character using the Char() function.
Syntax:
Char(ASCII Code)-->
Example:
Seechar(109) # print m
char(77) # print M
20.24
We can convert decimal to hexadecimal using the Hex() function.
Syntax:
Hex(decimal)-->
Example:
Seehex(10) # print a
hex(200) # print c8
20.25
We can convert hexadecimal to decimal using the Dec() function
Syntax:
Dec(hexadecimal)-->
Example:
Seedec("a") # print 10
dec("c8") # print 200
20.26
We can convert string characters to hexadecimal characters using the Str2hex() function.
Syntax:
Str2hex(string)--> string
Example:
Seestr2hex("hello") # print 68656c6c6f
20.23. Char() Function 121

Ring Documentation, Release 1.14
20.27
We can convert hexadecimal characters to string using the Hex2str() function
Syntax:
Hex2Str(Hexadecimal string)--> string
Example:
Seehex2str("68656c6c6f") # print hello
20.27. Hex2str() Function 122

CHAPTER
TWENTYONE
MATHEMATICAL FUNCTIONS
In this chapter we are going to learn about the mathematical functions
21.1
The Ring programming language comes with the next mathematical functions
Function Description
sin(x) Returns the sine of an angle of x radians
cos(x) Returns the cosine of an angle of x radians
tan(x) Returns the tangent of an angle of x radians
asin(x) Returns the principal value of the arc sine of x, expressed in radians
acos(x) Returns the principal value of the arc cosine of x, expressed in radians
atan(x) Returns the principal value of the arc tangent of x, expressed in radians
atan2(y,x) Returns the principal arc tangent of y/x, in the interval [-pi,+pi] radians
sinh(x) Returns the hyperbolic sine of x radians
cosh(x) Returns the hyperbolic cosine of x radians
tanh(x) Returns the hyperbolic tangent of x radians
exp(x) Returns the value of e raised to the xth power
log(x) Returns the natural logarithm of x (the base of e)
log(x,b) Returns the logarithm of x to the base of b
log10(x) Returns the common logarithm (base-10 logarithm) of x
ceil(x) Returns the smallest integer value greater than or equal to x
oor(x) Returns the largest integer value less than or equal to x
fabs(x) Returns the absolute value of x.
pow(x,y) Returns x raised to the power of y
sqrt(x) Returns the square root of x
random(x) Returns a random number in the range [0,x]
srandom(x) Initialize random number generator
unsigned(n,n,c)Perform operation using unsigned numbers
decimals(n) Determine the decimals digits after the point in oat/double numbers
123

Ring Documentation, Release 1.14
21.2
See"Mathematical Functions"
See"Sin(0) =0)
See"Sin(90) radians =90)
See"Sin(90) degree =90 *3.14/180)
See"Cos(0) =0)
See"Cos(90) radians =90)
See"Cos(90) degree =90 *3.14/180)
See"Tan(0) =0)
See"Tan(90) radians =90)
See"Tan(90) degree =90 *3.14/180)
See"asin(0) =0)
See"acos(0) =0)
See"atan(0) =0)
See"atan2(1,1) =1,1)
See"sinh(0) =0)
See"sinh(1) =1)
See"cosh(0) =0)
See"cosh(1) =1)
See"tanh(0) =0)
See"tanh(1) =1)
See"exp(0) =0)
See"exp(1) =1)
See"log(1) =1)
See"log(2) =2)
See"log10(1) =1)
See"log10(2) =2)
See"log10(10) =10)
See"Ceil(1.12) =1.12)
See"Ceil(1.72) =1.72)
See"Floor(1.12) =1.12)
See"Floor(1.72) =1.72)
See"fabs(1.12) =1.12)
See"fabs(1.72) =1.72)
See"pow(2,3) =2,3)
see"sqrt(16) =16)
Program Output:
Mathematical Functions
Sin(0)
Sin(90) radians.89
Sin(90) degree.00
Cos(0)
Cos(90) radians0.45
Cos(90) degree.00
(continues on next page)
21.2. Example 124

Ring Documentation, Release 1.14
(continued from previous page)
Tan(0)
Tan(90) radians2.00
Tan(90) degree.77
asin(0)
acos(0).57
atan(0)
atan2(1,1).79
sinh(0)
sinh(1).18
cosh(0)
cosh(1).54
tanh(0)
tanh(1).76
exp(0)
exp(1).72
log(1)
log(2).69
log10(1)
log10(2).30
log10(10)
Ceil(1.12)
Ceil(1.72)
Floor(1.12)
Floor(1.72)
fabs(1.12).12
fabs(1.72).72
pow(2,3)
sqrt(16)
21.3
The Random() function generate a random number and we can set the maximum value (optional).
Syntax:
Random(x)--> inthe range0,x]
Example:
forx to20
see"Random number :
"Random number Max (100) :100)
next
Program Output:
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
(continues on next page)
21.3. Random() Function 125

Ring Documentation, Release 1.14
(continued from previous page)
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
Random number :
Random number Max (100) :
21.4
The SRandom() function initialize random number generator.
Syntax:
SRandom(x)
21.5
We can use unsigned numbers using the Unsigned() function.
Syntax:
Unsigned(nNum1,nNum2,cOperator)-> onnNum1,nNum2
Example:
21.4. SRandom() Function 126

Ring Documentation, Release 1.14
seeoat_hash("hello")
# Jenkins hash function - https://en.wikipedia.org/wiki/Jenkins_hash_function
funcoat_hash cKey
h
forxincKey
h"+")
h10,"<<"),"+")
r6,">>")
h"^")
next
h3,"<<"),"+")
h11,">>"),"^")
h15,"<<"),"+")
returnh
Output:
3372029979.00
21.6
We can determine the decimals numbers count after the point in oat/double numbers using the decimals() function.
Syntax:
Decimals(nDecimalsCount)
Example:
x.1234567890123
ford to14
decimals(d)
seex
next
Output:
1
1.1
1.12
1.123
1.1235
1.12346
1.123457
1.1234568
1.12345679
1.123456789
1.1234567890
1.12345678901
1.123456789012
1.1234567890123
1.12345678901230
21.6. Decimals() Functions 127

Ring Documentation, Release 1.14
21.7
We can use _ between numbers digits.
Example:
x
seetype(x)+nl
seex+1+nl
Output:
NUMBER
100000001
21.8
We can use the `f' letter after numbers.
Example:
x = 19.99f
see type(x) + nl
Output:
NUMBER
21.9
We can write Hexadecimal number by preceding with “0x” or “0X”
Example:
x
? # 16
x
? # 255
x
? # 10
? # 65535
? # 10+1 = 11
21.7. Using _ in numbers 128

CHAPTER
TWENTYTWO
FILES
In this chapter we are going to learn about les functions.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
129

Ring Documentation, Release 1.14
•
•
•
•
•
22.1
We can read the le content using the Read() function
Syntax:
Read(cFileName)--> Stringcontains the file content
Example:
seeread("myfile.txt")
The read function can read binary les too
Example:
seeread("myapp.exe")
22.2
We can write string to le using the Write() function
The write function can write binary data to binary les.
Syntax:
Write(cFileName,cString) # write string cString to file cFileName
Example:
# copy file
cFile"ring.exe")
write("ring2.exe",cFile)
22.3
We can get the folder contents (les & sub folders) using the Dir() function.
Syntax:
Dir(cFolderPath)--> Listcontains files
This function returns a list and each list item is a list of two items
•
22.1. Read() Function 130

Ring Documentation, Release 1.14
•
Example:
see"Testing DIR()
mylist"C:\myfolder")
forxinmylist
ifx[2]
see"Directory :[1]
else
see"File :[1]
ok
next
see"Files count :
22.4
We can rename les using the Rename() function
Syntax:
Rename(cOldFileName,cNewFileName)-->0) , Error (-1) )
Example:
rename("file.txt","help.txt")
22.5
We can delete a le using the Remove() function
Syntax:
Remove(cFileName)
Example:
remove("test.txt")
22.6
We can open a le using the Fopen() function
Syntax:
Fopen(cFileName,cMode)-->
22.4. Rename() Function 131

Ring Documentation, Release 1.14
ModeDescription
“r” Reading (The le must exist)
“w” Writing (create empty le / overwrite)
“a” Appends (create le if it doesn't exist)
“r+”update (reading/writing)
“w+”Create empty le (reading/writing)
“a+”reading & appending
22.7
When we open a le using fopen() function, we can close it using the Fclose() function
Syntax:
Fclose(file handle)
22.8
We can ushes the output buffer of a stream using the Fush() function
Syntax:
Fflush(file handle)
22.9
We can open another le using the same le handle and at the same time close the old le
Syntax:
Freopen(cFileName,cMode,file handle)-->
Example:
freopen("myprogoutput.txt","w+",stdout)
see"welcome"
forx to10
seex
next
/*
**Read : https://en.wikipedia.org/wiki/Device_file #Device_files
**Thenextcode isnotportable, we can use iswindows() before
**using itandwe can write special code foreach operating system.
*/
freopen("CON","w",stdout) # For Microsoft Windows
see"Done" # print to stdout again
Output:
22.7. Fclose() Function 132

Ring Documentation, Release 1.14
# Output to stdout
Done
# Output to file : myprogoutput.txt
welcome
1
2
3
4
5
6
7
8
9
10
22.10
The function Temple() creates a temp. le (binary).
The le will be deleted automatically when the stream is closed
Syntax:
TempFile()-->
22.11
We can generate temp. le name using the Tempname() function
The generated name will be different from the name of any existing le
Syntax:
Tempname()--> string
22.12
We can set the le position of the stream using the Fseek() function
Syntax:
Fseek(file handle, nOffset, nWhence)--> ifsuccessful
The next table presents the nWhence values
ValueDescription
0 Beginning of le
1 Current position
2 End of le
22.10. Temple() Function 133

Ring Documentation, Release 1.14
22.13
We can know the current le position of a stream using the Ftell() function
Syntax:
Ftell(file handle)-->
22.14
We can set the le position to the beginning of the le using the Rewind() function
Syntax:
Rewind(file handle)
22.15
We can get handle to the current le position using the Fgetpos() function
Syntax:
Fgetpos(file handle)-->
22.16
We can set the current le position using the Fsetpos() function
Syntax:
Fsetpos(file handle,position handle)
22.17
We can clear the EOF error and the error indicators of a stream using the clearerr() function
Syntax:
Clearerr(file handle)
22.13. Ftell() Function 134

Ring Documentation, Release 1.14
22.18
We can test the end-of-le indicator using the Feof() function
Syntax:
Feof(file handle)--> ifEOFand0if
22.19
We can test the error indicator of a given stream using the Ferror() function
Syntax:
Ferror(file handle)--> iferrorand0if
22.20
We can print error message to the stderr using the Perror() function
Syntax:
Perror(cErrorMessage)
22.21
We can get the next character from the stream using the Fgetc() function
Syntax:
Fgetc(file handle)--> orEOF
22.22
We can read new line from the stream using the Fgets() function
Syntax:
Fgets(file handle,nSize)--> string
The function stop when nSize characters are read, new line character is read or EOF.
22.18. Feof() Function 135

Ring Documentation, Release 1.14
22.23
We can write a character to the stream using the Fputc() function
Syntax:
Fputc(file handle,cChar)
22.24
We can write a string to the stream using the Fputs() function
Syntax:
Fputs(file handle,cString)
22.25
We can push a character to the stream using the Ungetc() function
The character will be available for the next read
Syntax:
Ungetc(file handle,character)
22.26
We can read data from a stream using the Fread() function
Syntax:
Fread(file handle,nSize)
22.27
We can write data to a stream using the Fwrite() function
Syntax:
Fwrite(file handle,cString)
22.23. Fputc() Function 136

Ring Documentation, Release 1.14
22.28
We can check if a le exists using the Fexists() function
Syntax:
Fexists(cFileName)--> ifthe file exists
Example:
seefexists("b:\mahmoud \appsinging.exe")
fexists("b:\mahmoud \appsinging2.exe")
Output:
1
0
22.29
Syntax:
Direxists(cDirPath) ---> returns 1 if the directory exists
Example:
?"b: ing")
direxists("b: ingin2")
Output:
1
0
22.30
We can get the type a given path (le or directory) using the Getpathtype() function
Syntax:
Getpathtype(cPath) ---> 0 if the path doesnt exists
1 if it corresponds to existing file
2 if it corresponds to existing directory
-1 if the path exists but has
an unknown type (e.g. a pipe)
Example:
?"b: ingining.exe")
Getpathtype("b: ing")
Getpathtype("b: ingin2")
Output:
22.28. Fexists() Function 137

Ring Documentation, Release 1.14
1
2
0
22.31
The next program test some of the le functions
See"testing file functions"
See"open file"
fp../tests/scripts/s65.ring","r")
See"reopen"
fp../tests/scripts/s78.ring","r",fp)
See"close file"
fclose(fp)
see"temp file"
fp
fclose(fp)
see"temp name"
seetempname()
remove(exefolder()../tests/scripts/mytest2.txt")
write(exefolder()../tests/scripts/tests1.txt","hello")
rename(exefolder()../tests/scripts/test1.txt",exefolder()
"../tests/scripts/mytests2.txt")
see"print file"
fp../samples/fromdoc/filefuncs.ring","r")
r
whileisstring(r)
seer
r
end
fclose(fp)
seenl+"print line from the file"
fp../samples/fromdoc/filefuncs.ring","r")
r33)
seer
fclose(fp)
fp../tests/scripts/test78.txt","w+")
fseek(fp,0,2) # goto end of file
fputc(fp,"t")
fputc(fp,"e")
fputc(fp,"s")
fputc(fp,"t")
fputs(fp,"tests2")
fclose(fp)
see"print file"
seeread(exefolder()../tests/scripts/test78.txt")
(continues on next page)
22.31. Example 138

Ring Documentation, Release 1.14
(continued from previous page)
fp../tests/scripts/test78.txt","r")
see"testing ungetc()
forx to3
r
seer
ungetc(fp,r)
next
fclose(fp)
see"testing fread()
fp"rb")
r100)
seer
fclose(fp)
see"testing fwrite()
fp../tests/scripts/test1.txt","wb")
fwrite(fp,r)
fclose(fp)
The next example print part of the content of a binary le
see"Testing: fread()""+nlnl
fp"rb")
r800)
forn1 tolen(r)
ifisprint(substr(r, n,))
seesubstr(r, n,)
else
see"."
ok
### 80 char per line
ifn
seenl
ok
next
fclose(fp)
22.32
The next functions to convert between Numbers and Bytes.
•
•
•
•
•
•
Example:
22.32. Numbers and Bytes 139

Ring Documentation, Release 1.14
see"Test Int2Bytes() and Bytes2Int() - Value : 77"
r77)
see"Int Size :
seer
seeBytes2Int(r)
see"Test Float2Bytes() and Bytes2Float() - Value 77.12"
r77.12)
see"Float Size :
seer
seeBytes2Float(r)
see"Test Double2Bytes() and Bytes2Double() - Value 9999977.12345"
r9999977.12345)
see"Double Size :
seer
decimals(5)
seeBytes2Double(r)
22.32. Numbers and Bytes 140

CHAPTER
TWENTYTHREE
SYSTEM FUNCTIONS
In this chapter we are going to learn about the system functions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
141

Ring Documentation, Release 1.14
23.1
We can execute system commands using the system() function
Syntax:
System(cCommand)
Example:
System("myapp.exe") # Run myapp.exe
System("ls") # print list of files
23.2
We can get environment variables using the Get() function
Syntax:
SysGet(cVariable)
Example:
seesysget("path") # print system path information
23.3
We can set environment variables using the SysSet() function
SysSet(cVariable, cValue) ---> Returns 1 for success and return 0 for failure
23.4
We can delete an environment variables using the SysUnset() function
SysUnset(cVariable) ---> Returns 1 for success and return 0 for failure
23.5
We can check if the operating system is MSDOS or not using the IsMSDOS() function
Syntax:
IsMSDOS()--> ifthe operating system is MS-DOS, Returns ifitsot
23.1. System() Function 142

Ring Documentation, Release 1.14
23.6
We can check if the operating system is Windows or not using the IsWindows() function
Syntax:
IsWindows()--> ifthe operating system is Windows, Returns ifit&#3627409170;sot
23.7
We can check if the operating system is Windows 64bit or not using the IsWindows64() function
Syntax:
IsWindows64()--> ifthe operating system is Windows64, Returns ifit&#3627409170;s
˓→not
23.8
We can check if the operating system is Unix or not using the IsUnix() function
Syntax:
IsUnix()--> ifthe operating system is Unix, Returns ifit&#3627409170;sot
23.9
We can check if the operating system is macOS or not using the IsMacOSX() function
Syntax:
IsMacOSX()--> ifthe operating system is Mac OS X, Returns ifit&#3627409170;sot
23.10
We can check if the operating system is Linux or not using the IsLinux() function
Syntax:
IsLinux()--> ifthe operating system is Linux, Returns ifit&#3627409170;sot
23.6. IsWindows() Function 143

Ring Documentation, Release 1.14
23.11
We can check if the operating system is FreeBSD or not using the IsFreeBSD() function
Syntax:
IsFreeBSD()--> ifthe operating system is FreeBSD, Returns ifitsot
23.12
We can check if the operating system is Android or not using the IsAndroid() function
Syntax:
IsAndroid()--> ifthe operating system is Android, Returns ifitsot
23.13
see"IsMSDOS() -->
see"IsWindows() -->
see"IsWindows64() -->
see"IsUnix() -->
see"IsMacOSX() -->
see"IsLinux() -->
see"IsFreeBSD() -->
see"IsAndroid() -->
Output:
IsMSDOS()->
IsWindows()->
IsWindows64()->
IsUnix()->
IsMacOSX()->
IsLinux()->
IsFreeBSD()->
IsAndroid()->
23.14
We can detect the architecture of the Ring executable using the GetArch() function
Syntax:
GetArch() ---> cString (The name of the architecture of the Ring executable)
Possible values are:
23.11. IsFreeBSD() Function 144

Ring Documentation, Release 1.14
x86
x64
arm64
arm
unknown
Example:
switchgetarch()
on"x86"
?x86 32bit architecture"
on"x64"
?x64 64bit architecture"
on"arm64"
?ARM64 64bit architecture"
on"arm"
?ARM 32bit architecture"
other
?Unknown architecture"
off
23.15
We can get the windows new line string using the Windowsnl() function.
Syntax:
WindowsNL()--> stringcontains CR+LF13)10)
Example:
cStr"input.txt")
ifiswindows()
cStr
ok
aList
# to do - list items processing using "for in"
cStr
ifiswindows()
cStr
ok
write("ouput.txt",cStr)
23.15. Windowsnl() Function 145

Ring Documentation, Release 1.14
23.16
We can get the command line arguments passed to the ring script using the sysargv variable.
The sysargv variable is a list contains the command line parameters.
Example
seecopy("=",30)
see"Command Line Parameters"
see"Size :
seesysargv
seecopy("=",30)
iflen(sysargv) return
nStart[3]
nEnd[4]
forx tonEnd
seex
next
Output
b:\mahmoud\apps\ring>ring tests\syspara.ring
==============================
Command Line Parameters
Size :
ring
tests\syspara.ring
1
10
==============================
1
2
3
4
5
6
7
8
9
10
23.17
We can get the active source le name (*.ring) using the lename() function
Syntax:
filename()--> Stringcontains the active source file name.
Example:
see"Active Source File Name :
Output:
23.16. Get Command Line Arguments 146

Ring Documentation, Release 1.14
Active Source File Name : tests\filename.ring
Example:
ifsysargv[2]
see"Im the main program file!"
# we can run tests here!
else
see"Im a sub file in a program"
ok
23.18
Using the PrevFileName() function we can get the previous active source le name.
The previous le would be the le of the caller function, Or the le of the function that we called before calling
PrevFileName().
Syntax:
prevfilename()--> Stringcontains the previous source file name.
Example:
The next function in stdlib.ring uses the PrevFileName() to know if the le of the caller function is the main source
le of the program or not.
FuncIsMainSourceFile
ifPrevFileName()[2]
return
ok
return
23.19
Return the path of the current directory
Syntax:
CurrenDir()--> Stringcontains the path of the currect directory
23.20
Return the Ring executable le name
Syntax:
exefilename()--> Stringcontains the Ring executable file name
23.18. PrevFileName() Function 147

Ring Documentation, Release 1.14
23.21
Change the current directory
Syntax:
ChDir(cNewPath)
23.22
Return the Ring executable le path
Syntax:
exefolder()--> Stringcontains the Ring executable path
23.23
Return the Ring version
Syntax:
version()--> Stringcontains the Ring version
Output:
1.14
23.24
Close the application
Syntax:
shutdown(nStatus)-->
23.25
We can detect the number of processors using the NofProcessors() Function
Syntax:
NofProcessors() ---> nProcessors
Example:
?
23.21. ChDir() Function 148

CHAPTER
TWENTYFOUR
EVAL() AND DEBUGGING
In this chapter we are going to learn about
•
•
•
•
24.1
Syntax:
Try
Statements...
Catch
Statements...
Done
The statements in the Try block will be executed, if any error happens then the statements in the catch block will be
executed.
Inside the catch block we can use the variable cCatchError to get the error message
Example:
Try
see5/0
Catch
see"Catch!"
Done
Output:
Catch!
Error (R1) : Canntivideyero
149

Ring Documentation, Release 1.14
24.2
We can execute code during the runtime from string using the Eval() function
Syntax:
Eval(cCode)
Example:
Eval("nOutput = 5+2 *5
See"5+2*5 =
Eval("for x = 1 to 10 see x + nl next")
Eval("func test seemessage from test!)
test()
Output:
5+2*5
1
2
3
4
5
6
7
8
9
10
messagefromtest!
We can use the Return command to return a value
Example:
seeEval("return 5 *5")
Output:
25
24.3
We can raise an exception using the Raise() function
Syntax:
Raise(cErrorMessage)
The function will display the error message then end the execution of the program.
We can use Try/Catch/Done to avoid exceptions generated by raise() function.
Example:
24.2. Eval() Function 150

Ring Documentation, Release 1.14
nMode
ifnMode ornMode
raise("Error : nMode not in the range 1:4")
ok
Output:
Line not the range:4
Inraiseinfile tests\raise.ring
Example:
try
testmode(6)
catch
see"avoid raise!"
done
testmode(-1)
functestmode nMode
ifnMode ornMode
raise("Error : nMode not in the range 1:4")
ok
Output:
avoid raise!
Line not the range:4
InraiseInfunction testmode() infile tests\raise2.ring
calledfromline infile tests\raise2.ring
24.4
We can use the Assert() function to test conditions before executing the code
If the test fail the program will be terminated with an error message contains the assert condition.
Syntax:
Assert( condition )
Example:
x
assert( x)
assert( x
Output:
Line!
Inassertinfile tests\assert.ring
24.4. Assert() Function 151

CHAPTER
TWENTYFIVE
DEMO PROGRAMS
In this chapter we will see simple demo programs
•
•
25.1
We can create simple interactive programming environment using the next program
while
seenlcode:>
givecCode
try
eval(cCode)
catch
seecCatchError
done
end
Output:
code:> see"hello world"
hello world
code:> forx to10seex next
1
2
3
4
5
6
7
8
9
10
code:> functestsee"Hello from test"
code:>
Hellofromtest
code:> bye
152

Ring Documentation, Release 1.14
25.2
Example:
# Demo Program
while
see"
Main Menu
===========
[1]
[2]
[3]
[4]
[5]Exit
"
# we can use Switch-ON-Other-OFF instead of IF-BUT-ELSE-OK
SwitchnMenu
On1
On2
On3
On4
see"Enter Number : givex
see"Output :
Try
seeFact(number(x))
Catch
see"Error in parameters!"
Done
On"5"return
Other "bad option"
Off
end
funcsayhello
see"Enter your name ? givefname
see"Hello
funcsum
see"number 1 : givenum1see"number 2 : givenum2
see"Sum : see0
funcstars
forx to10
seespace(8)
fory toxsee"*"next nl
next
funcfact xifx return1else x*fact(x-1) ok
(continues on next page)
25.2. Main Menu 153

Ring Documentation, Release 1.14
(continued from previous page)
funcspace x y" fort=1tox y= next y
Output:
Main Menu
===========
[1]
[2]
[3]
[4]
[5]Exit
1
Enter your name
Hello Mahmoud Fayed
Main Menu
===========
[1]
[2]
[3]
[4]
[5]Exit
2
number
number
Sum :
Main Menu
===========
[1]
[2]
[3]
[4]
[5]Exit
3
*
**
***
****
*****
******
*******
********
*********
**********
Main Menu
===========
(continues on next page)
25.2. Main Menu 154

Ring Documentation, Release 1.14
(continued from previous page)
[1]
[2]
[3]
[4]
[5]Exit
4
Enter Number :
Output :
Main Menu
===========
[1]
[2]
[3]
[4]
[5]Exit
5
25.2. Main Menu 155

CHAPTER
TWENTYSIX
ODBC FUNCTIONS
This chapter contains the ODBC functions provided by the Ring programming language.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Before using the next function load the odbclib.ring library
load"odbclib.ring"
# Use ODBC functions
26.1
We can create ODBC Handle using the odbc_init() function
Syntax:
odbc_init()-->
156

Ring Documentation, Release 1.14
26.2
We can get a list of ODBC drivers using the odbc_drivers() function
Syntax:
odbc_drivers(ODBC Handle)--> Listof Drivers
26.3
We can get a list of ODBC data sources using the odbc_datasources() function
Syntax:
odbc_datasources(ODBC Handle)--> Listof Data sources
26.4
After the end of using ODBC functions we can free resources using ODBC_Close() function
Syntax:
odbc_close(ODBC Handle)
26.5
The next example print a list of ODBC drivers.
See"ODBC test 1"
oODBC
See"Drivers
seeodbc_drivers(oODBC)
odbc_close(oODBC)
Output:
ODBC test
Drivers
Microsoft Access-Treiber ( *.mdb)=0
DriverdoMicrosoft Paradox (*.db )=0
DriverdoMicrosoft Excel(*.xls)=0
Microsoft Text Driver ( *.txt;*.csv)=0
Driver da Microsoft para arquivos texto ( *.txt;*.csv)=0
Microsoft dBase-Treiber ( *.dbf)=0
SQL Server=60
Microsoft Excel Driver ( *.xls)=0
DriverdoMicrosoft dBase (*.dbf)=0
Microsoft Paradox-Treiber ( *.db )=0
Microsoft ODBCforOracle=120
Microsoft Text-Treiber ( *.txt;*.csv)=0
(continues on next page)
26.2. odbc_drivers() Function 157

Ring Documentation, Release 1.14
(continued from previous page)
Microsoft Excel-Treiber ( *.xls)=0
Microsoft Access Driver ( *.mdb)=0
DriverdoMicrosoft Access (*.mdb)=0
Microsoft Paradox Driver ( *.db )=0
Microsoft dBase Driver ( *.dbf)=0
Microsoft Access Driver ( *.mdb,*.accdb)=3
Microsoft Excel Driver ( *.xls,*.xlsx,*.xlsm,*.xlsb)=3
Microsoft Access Text Driver ( *.txt,*.csv)=3
SQL Server Native Client.0=1
SQL Server Native Client.0=1
Microsoft Access dBASE Driver ( *.dbf,*.ndx,*.mdx)=3
Microsoft Access Paradox Driver ( *.db)=3
MySQL ODBC.3=1
MySQL ODBC.3=1
ODBC Driver forSQL Server=1
Lianja ODBC Driver=60
Microsoft Visual FoxPro Driver=1
Microsoft Visual FoxPro-Treiber=1
Driver para o Microsoft Visual FoxPro=1
Microsoft FoxPro VFP Driver ( *.dbf)=1
26.6
The next example print a list of ODBC data sources.
See"ODBC test 2"
pODBC
See"Data Sources
seeodbc_datasources(pODBC)
odbc_close(pODBC)
Output:
ODBC test
Data Sources
Excel Files *.xls,*.xlsx,*.xlsm,*.xlsb)
MS Access Database *.mdb,*.accdb)
Customer *.mdb)
IdCardData *.mdb)
MyProjectData2 *.mdb)
MyData *.mdb)
MonprojetData *.mdb)
dBASE Files *.dbf,*.ndx,*.mdx)
myvfpdata
FACTORYDATA *.mdb)
TRAININGSYSDATA *.mdb)
RVCSYSDATASQLDB.0
PWCTRVCDATA *.mdb)
MyCompany *.mdb)
HCS *.mdb)
HCS2 *.mdb,*.accdb)
MyProjectData *.mdb)
Xtreme Sample Database *.mdb)
Lianja_Southwind
(continues on next page)
26.6. Print List of ODBC Data Sources 158

Ring Documentation, Release 1.14
(continued from previous page)
Visual FoxPro Database
Visual FoxPro Tables
26.7
We can connect to the database using the odbc_connect() function.
Syntax:
odbc_connect(ODBC Handle, cConnectionString)
26.8
We can close the connection to the database using the odbc_disconnect() function.
Syntax:
odbc_disconnect(ODBC Handle)
26.9
The next example connect to the database then close the connection
See"ODBC test 3"
pODBC
See"Connect to database"
seeodbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
See"disconnect"
odbc_disconnect(pODBC)
See"Close database..."
odbc_close(pODBC)
Output:
ODBC test
Connecttodatabase
1
disconnect
Close database...
26.7. odbc_connect() Function 159

Ring Documentation, Release 1.14
26.10
We can execute SQL Statements on the database using the odbc_execute() function.
Syntax:
odbc_execute(ODBC Handle, cSQLStatement)
26.11
We can get columns count in the query result using the odbc_colcount() function.
Syntax:
odbc_colcount(ODBC Handle)-->
26.12
We can fetch a row from the query result using the odbc_fetch() function.
Syntax:
odbc_fetch(ODBC Handle)
26.13
We can get column value from the fetched row using the odbc_getdata() function.
Syntax:
odbc_getdata(ODBC Handle, nColumnNumber)-->
26.14
The next example execute query then print the query result.
See"ODBC test 4"
pODBC
See"Connect to database"
seeodbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
See"Select data"
seeodbc_execute(pODBC,"select *from person")
nMax
See"Columns Count :
whileodbc_fetch(pODBC)
See"Row data:"
forx tonMax
seeodbc_getdata(pODBC,x)
(continues on next page)
26.10. odbc_execute() Function 160

Ring Documentation, Release 1.14
(continued from previous page)
next
end
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
26.15
We can get a list of tables inside the database using the odbc_tables() function.
We can access the result of this function as we get any query result.
Syntax:
odbc_tables(ODBC Handle)
Example:
See"ODBC test - Get Database Tables"
pODBC
See"Connect to database"
odbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
See"Select data"
odbc_tables(pODBC)
nMax
See"Columns Count :
whileodbc_fetch(pODBC)
forx tonMax
seeodbc_getdata(pODBC,x)
ifx= see" ok
next
Seenl
end
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
Output:
ODBC test GetDatabase Tables
Connecttodatabase
Select data
Columns Count :
.\test NULL- NULL
.\test NULL- NULL
.\test NULL- NULL
.\test NULL- NULL
Close database...
26.15. odbc_tables() Function 161

Ring Documentation, Release 1.14
26.16
We can get a list of columns inside the table using the odbc_columns() function.
Syntax:
odbc_columns(ODBC Handle, cTableName)
Example:
See"ODBC test - Get Table Columns"
pODBC
See"Connect to database"
odbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
See"Get Columns inside the Person Table"
odbc_columns(pODBC,"person")
whileodbc_fetch(pODBC)
seeodbc_getdata(pODBC,4)
end
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
Output:
ODBC test GetTable Columns
Connecttodatabase
GetColumns inside the Person Table
FIRST
LAST
STREET
CITY
STATE
ZIP
HIREDATE
MARRIED
AGE
SALARY
NOTES
Close database...
26.17
We can enable or disable the auto commit feature using the odbc_autocommit() function.
Syntax:
odbc_autocommit(ODBC Handle, lStatus) # lStatus can be True or False
26.16. odbc_columns() Function 162

Ring Documentation, Release 1.14
26.18
We can commit updates to the database using the odbc_commit() function.
Syntax:
odbc_commit(ODBC Handle)
26.19
We can rollback updates to the database using the odbc_rollback() function.
Syntax:
odbc_rollback(ODBC Handle)
26.20
Example:
See"ODBC Test - Transactions and using Commit and Rollback"
pODBC
See"Connect to database"
seeodbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
see"insert data..."
odbc_autocommit(pODBC,0)
forx to10000
odbc_execute(pODBC,"insert into tel values (",mahmoud)")
next
forx to15000
odbc_execute(pODBC,"insert into tel values (",samir)")
next
odbc_commit(pODBC)
forx to20000
odbc_execute(pODBC,"insert into tel values (",fayed)")
next
ODBC_ROLLBACK(pODBC)
odbc_execute(pODBC,"insert into tel values (",fayed)")
odbc_commit(pODBC)
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
Output:
ODBC Test andusing CommitandRollback
Connecttodatabase
1
insert data...
Close database...
26.18. odbc_commit() Function 163

Ring Documentation, Release 1.14
26.21
The next example save an image inside the database
See"ODBC test - Save image in the database"
pODBC
See"Connect to database"
seeodbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
see"Read Image File..."
cFile"tests\mahmoud.jpg"))
see"size+nl
see"Save image in the database..."
stmtinsert into tel values (20000,mahmoud,");"
odbc_execute(pODBC,stmt)
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
The next example restore the image from the database
See"ODBC Test - Restore image from the database"
pODBC
See"Connect to database"
seeodbc_connect(pODBC,"DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
See"Select data"
seeodbc_execute(pODBC,"select *from tel where id = 20000")
nMax
See"Columns Count :
ifodbc_fetch(pODBC)
See"Write image file"
write("tests\great.jpg",hex2str( odbc_getdata(pODBC,3) ) )
ok
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
26.21. Save and Restore images 164

CHAPTER
TWENTYSEVEN
MYSQL FUNCTIONS
In this chapter we are going to learn about the MySQL functions provided by the Ring programming language.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Before using the next function load the mysqllib.ring library
load"mysqllib.ring"
# Use MySQL functions
27.1
We can get the MySQL Client version using the MySQL_Info() function.
Syntax:
MySQL_Info()--> stringcontains the MySQL Client version
Example:
165

Ring Documentation, Release 1.14
see"MySQL Client Version :
Output:
MySQL Client Version :.1.5
27.2
We can start using MySQL Client through the MySQL_Init() function.
Syntax:
MySQL_Init()-->
27.3
We can get the error message from the MySQL Client using the MySQL_Error() function.
Syntax:
MySQL_Error(MySQL Handle)--> string
27.4
We can connect to the MySQL database server using the MySQL_Connect() function.
Syntax:
MySQL_Connect(MySQL Handle, cServer, cUserName, cPassword)-->
27.5
We can close the connection to the MySQL database using the MySQL_Close() function
Syntax:
MySQL_Close(MySQL Handle)
27.2. MySQL_Init() Function 166

Ring Documentation, Release 1.14
27.6
We can execute SQL queries using the MySQL_Query() function
Syntax:
MySQL_Query(MySQL Handle, cSQLQuery)
27.7
The next example connect to MySQL Server then create new database.
See"MySQL Test - Create Database"
con
See"Connect"
ifmysql_connect(con,"localhost","root","root")
see"Cannt connect"
see"Error :
mysql_close(con)
bye
ok
See"Create Database..."
mysql_query(con,"CREATE DATABASE mahdb")
See"Close Connection"
mysql_close(con)
Output:
MySQL Test
Connect
Create Database...
Close Connection
27.8
The next example create new table and insert records
funcmain
see"Create Table and Insert Records"
con
see"Connect"
ifmysql_connect(con,localhost",root",root","mahdb")
system_error(con)
ok
see"Drop table"
ifmysql_query(con,DROP TABLE IF EXISTS Employee") system_error(con) ok
(continues on next page)
27.6. MySQL_Query() Function 167

Ring Documentation, Release 1.14
(continued from previous page)
see"Create table"
ifmysql_query(con,CREATE TABLE Employee(Id INT, Name TEXT, Salary INT)")
system_error(con) ok
see"Insert data"
ifmysql_query(con,INSERT INTO Employee VALUES(1,&#3627409170;Mahmoud&#3627409170;,15000)")
system_error(con) ok
ifmysql_query(con,INSERT INTO Employee VALUES(2,&#3627409170;Samir&#3627409170;,16000)")
system_error(con) ok
ifmysql_query(con,INSERT INTO Employee VALUES(3,&#3627409170;Fayed&#3627409170;,17000)")
system_error(con) ok
see"Close connection"
mysql_close(con)
funcsystem_error con
seemysql_error(con) mysql_close(con) bye
Output:
Create TableandInsert Records
Connect
Drop table
Create table
Insert data
Close connection
27.9
We can get the inserted row id using the MySQL_Insert_ID() function
Syntax:
MySQL_Insert_ID()-->
Example:
con
see"connect to database"
mysql_connect(con,"localhost","root","root","mahdb")
see"drop table"
mysql_query(con,DROP TABLE IF EXISTS Customers")
see"create table"
mysql_query(con,CREATE TABLE Customers(Id INT PRIMARY KEY AUTO_INCREMENT, Name TEXT)
˓→")
see"insert record"
mysql_query(con,INSERT INTO Customers(Name) VALUES(&#3627409170;Mahmoud&#3627409170;)")
see"insert record"
mysql_query(con,INSERT INTO Customers(Name) VALUES(&#3627409170;Samir&#3627409170;)")
see"insert record"
mysql_query(con,INSERT INTO Customers(Name) VALUES(&#3627409170;Fayed&#3627409170;)")
see"insert record"
(continues on next page)
27.9. MySQL_Insert_ID() Function 168

Ring Documentation, Release 1.14
(continued from previous page)
mysql_query(con,INSERT INTO Customers(Name) VALUES(Test 2015)")
see"inserted row id :
see"close database"
mysql_close(con)
Output:
connecttodatabase
drop table
create table
insert record
insert record
insert record
insert record
inserted row id :
close database
27.10
We can get the query result (data without column names) using the MySQL_Result() function.
Syntax:
MySQL_Result(MySQL Handle)--> Listcontains the query result
27.11
We can move to the next query result using the MySQL_Next_Result() function. We use this function when we have
multiple SQL statements in the same query.
Syntax:
MySQL_Next_Result(MySQL Handle)
27.12
The next example execute a query on the database then print the result.
con
see"Connect to database"
mysql_connect(con,localhost",root",root","mahdb")
see"Execute Query"
mysql_query(con,SELECT Name FROM Employee WHERE Id=1;"+
"SELECT Name FROM Employee WHERE Id=3")
see"Print Result"
seemysql_result(con)
mysql_next_result(con)
seemysql_result(con)
(continues on next page)
27.10. MySQL_Result() Function 169

Ring Documentation, Release 1.14
(continued from previous page)
see"close database"
mysql_close(con)
Output:
Connecttodatabase
Execute Query
Print Result
Mahmoud
Fayed
close database
27.13
We can get a list of columns names using the MySQL_Columns() function.
Syntax:
MySQL_Columns(MySQL Handle)--> Listcontains columns information
Example:
con
see"Connect to database"
mysql_connect(con,localhost",root",root","mahdb")
see"Execute Query"
mysql_query(con,SELECT *FROM Employee")
see"Result"
seemysql_columns(con)
see"Close database"
mysql_close(con)
Output:
Connecttodatabase
Execute Query
Result
Id
11
3
32768
Name
65535
252
16
Salary
11
3
32768
Close database
27.13. MySQL_Columns() Function 170

Ring Documentation, Release 1.14
27.14
Instead of using MySQL_Result() to get the result data without columns names, we can use the MySQL_Result2() to
get all of the column names then the query result in one list.
Syntax:
MySQL_Result2(MySQL Handle)--> List(query result starts with columns names)
Example:
con
see"Connect to database"
mysql_connect(con,localhost",root",root","mahdb")
see"Execute Query"
mysql_query(con,SELECT *FROM Employee")
see"Print Result"
seemysql_result2(con)
see"Close database"
mysql_close(con)
Output:
Connecttodatabase
Execute Query
Print Result
Id
Name
Salary
1
Mahmoud
15000
2
Samir
16000
3
Fayed
17000
Close database
27.15
We can store binary data and special characters in the database after processing using MySQL_Escape_String() func-
tion
Syntax:
MySQL_Escape_String(MySQL Handle, cString)--> Stringafter processing
27.14. MySQL_Result2() Function 171

Ring Documentation, Release 1.14
27.16
Example:
See"Read file"
cFile"tests\mahmoud.jpg")
con
See"Connect to database..."
mysql_connect(con,localhost",root",root","mahdb")
See"Escape string..."
cFile
stmtINSERT INTO photo(id, data) VALUES(1,")"
See"Insert data..."
mysql_query(con,stmt)
See"Close database..."
mysql_close(con)
Output:
Read file
Connecttodatabase...
Escapestring...
Insert data...
Close database...
27.17
Example:
con
See"Connect to database..."
mysql_connect(con,localhost",root",root","mahdb")
See"Read data from database..."
mysql_query(con,"SELECT data FROM photo WHERE id=1")
See"Write new file"
result
write("tests\mahmoud2.jpg",result[1][1])
See"Close database..."
mysql_close(con)
Output:
Connecttodatabase...
Read datafromdatabase...
Writenewfile
Close database...
27.16. Save Image inside the database 172

Ring Documentation, Release 1.14
27.18
We can enable or disable the auto commit feature using the MySQL_AutoCommit() function.
Syntax:
MySQL_AutoCommit(MySQL Handle, lStatus) # lstatus can be True/False
27.19
We can commit updates to the database using the MySQL_Commit() function.
Syntax:
MySQL_Commit(MySQL Handle)
27.20
We can rollback updates to the database using the MySQL_Rollback() function.
Syntax:
MySQL_Rollback(MySQL Handle)
27.21
The next example presents the usage of MySQL_Autocommit(), MySQL_Commit() & MySQL_RollBack() functions.
Example:
funcmain
con
see"Connect"
ifmysql_connect(con,localhost",root",root","mahdb")
system_error(con) ok
see"Drop table"
ifmysql_query(con,DROP TABLE IF EXISTS Employee2")
system_error(con) ok
see"Create table"
ifmysql_query(con,CREATE TABLE Employee2(Id INT, Name TEXT, Salary INT)")
system_error(con) ok
see"Insert data"
ifmysql_query(con,INSERT INTO Employee2 VALUES(1,Mahmoud,15000)")
system_error(con) ok
ifmysql_query(con,INSERT INTO Employee2 VALUES(2,Samir,16000)")
(continues on next page)
27.18. MySQL_AutoCommit() Function 173

Ring Documentation, Release 1.14
(continued from previous page)
system_error(con) ok
ifmysql_query(con,INSERT INTO Employee2 VALUES(3,Fayed,17000)")
system_error(con) ok
mysql_autocommit(con, False)
mysql_query(con,INSERT INTO Employee2 VALUES(4,Ahmed,5000)")
mysql_query(con,INSERT INTO Employee2 VALUES(5,Ibrahim,50000)")
mysql_query(con,INSERT INTO Employee2 VALUES(6,Mohammed,50000)")
See"Save transaction (y/n) givenChoice
ifupper(nChoice)Y"
mysql_commit(con)
else
mysql_rollback(con)
ok
see"Close connection"
mysql_close(con)
funcsystem_error con
seemysql_error(con)
mysql_close(con)
bye
Output:
Connect
Drop table
Create table
Insert data
Save transaction (y/n) y
Close connection
27.21. Transaction Example 174

CHAPTER
TWENTYEIGHT
SQLITE FUNCTIONS
In this chapter we will learn about using the SQLite database in the Ring programming language.
Before using the next function load the sqlitelib.ring library
load"sqlitelib.ring"
# Use SQLite functions
28.1
Syntax:
sqlite_init()-->
28.2
Syntax:
sqlite_open(SQLite Object,cFileName)
28.3
Syntax:
sqlite_execute(SQLite Object,cSQLStatement)
28.4
Syntax:
sqlite_close(SQLite Object)
175

Ring Documentation, Release 1.14
28.5
The next code create a SQLite database, add new records then display the data.
load"sqlitelib.ring"
oSQLite
sqlite_open(oSQLite,"mytest.db")
sql
CREATE TABLE COMPANY (
ID INT PRIMARY KEY NOT ,
NAME TEXT NOT ,
AGE INT NOT ,
ADDRESS CHAR(50),
SALARY REAL );
"
sqlite_execute(oSQLite,sql)
sql
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,Mahmoud,Jeddah,.00
(2,Ahmed,Jeddah,.00
(3,Mohammed,,Egypt.00
(4,Ibrahim,Egypt,.00
"
sqlite_execute(oSQLite,sql)
aResult"select *from COMPANY")
forxinaResult
fortinx
?[2]
next
next
?" *",50)
forxinaResult
?[:name]
next
sqlite_close(oSQLite)
Output:
1
Mahmoud
29
Jeddah
20000.0
2
Ahmed
27
Jeddah
15000.0
3
Mohammed
31
(continues on next page)
28.5. Example 176

Ring Documentation, Release 1.14
(continued from previous page)
Egypt
20000.0
4
Ibrahim
24
Egypt
65000.0
**************************************************
Mahmoud
Ahmed
Mohammed
Ibrahim
28.5. Example 177

CHAPTER
TWENTYNINE
POSTGRESQL FUNCTIONS
In this chapter we will learn about using the PostgreSQL database in the Ring programming language.
29.1
Before using the next function load the postgresqllib.ring library
load"postgresqllib.ring"
# Use PostgreSQL functions
29.2
Example (1):
load"postgresqllib.ring"
conninfouser=postgres password=sa dbname = postgres"
exit_nicely funcconn {
PQfinish(conn)
shutdown(1)
}
conn
if(PQstatus(conn)=
fputs(stderr,Connection to database failed:+PQerrorMessage(conn))
callexit_nicely(conn)
ok
resselect *from pg_database")
ifPQresultStatus(res)=
fputs(stderr,Select failed:
PQclear(res)
exit_nicely(conn)
ok
nFields
fori tonFields
?-1)
(continues on next page)
178

Ring Documentation, Release 1.14
(continued from previous page)
next
?" *",60)
fori toPQntuples(res)
forj=1tonFields
seePQgetvalue(res, i-1, j-1)
next
seenl
next
PQclear(res)
PQfinish(conn)
Output:
datname
datdba
encoding
datcollate
datctype
datistemplate
datallowconn
datconnlimit
datlastsysoid
datfrozenxid
datminmxid
dattablespace
datacl
************************************************************
postgres 10 6 English_United States.1252
English_United States.1252 f t -1 12937 549 1 1663
template1 10 6 English_United States.1252 English_United States.1252
t t -1 12937 549 1 1663 {=c/postgres,postgres=CTc/postgres}
template0 10 6 English_United States.1252 English_United States.1252
t f -1 12937 549 1 1663 {=c/postgres,postgres=CTc/postgres}
mahdb 10 6 English_United States.1252 English_United States.1252
f t -1 12937 549 1 1663
Example(2):
load"postgresqllib.ring"
conninfouser=postgres password=sa dbname = mahdb"
exit_nicely funcconn {
PQfinish(conn)
shutdown(1)
}
conn
if(PQstatus(conn)=
fputs(stderr,Connection to database failed:+PQerrorMessage(conn))
callexit_nicely(conn)
ok
(continues on next page)
29.2. Examples 179

Ring Documentation, Release 1.14
(continued from previous page)
res
DROP DATABASE mahdb;
")
ifPQresultStatus(res)=
fputs(stderr,Remove failed:
PQclear(res)
ok
PQclear(res)
resCREATE DATABASE mahdb;")
ifPQresultStatus(res)=
fputs(stderr,Create database failed:
PQclear(res)
ok
res
CREATE TABLE COMPANY (
ID INT PRIMARY KEY NOT ,
NAME TEXT NOT ,
AGE INT NOT ,
ADDRESS CHAR(50),
SALARY REAL );
")
ifPQresultStatus(res)=
fputs(stderr,Create Table failed:
PQclear(res)
ok
PQclear(res)
res
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,Mahmoud,Jeddah,.00
(2,Ahmed,Jeddah,.00
(3,Mohammed,,Egypt.00
(4,Ibrahim,Egypt,.00
")
ifPQresultStatus(res)=
fputs(stderr,Insert Table failed:
PQclear(res)
ok
PQclear(res)
res
select*fromCOMPANY
")
ifPQresultStatus(res)=
fputs(stderr,Select failed:
PQclear(res)
callexit_nicely(conn)
ok
nFields
fori tonFields
(continues on next page)
29.2. Examples 180

Ring Documentation, Release 1.14
(continued from previous page)
?-1)
next
?" *",60)
fori toPQntuples(res)
forj=1tonFields
seePQgetvalue(res, i-1, j-1)
next
seenl
next
PQclear(res)
PQfinish(conn)
Output:
id
name
age
address
salary
************************************************************
1 Mahmoud 31 Jeddah 10
2 Ahmed 27 Jeddah 20
3 Mohammed 31 Egypt 30
4 Ibrahim 24 Egypt 40
29.3
The next constants are dene by the RingPostgreSQL Library
CONNECTION_STARTED
CONNECTION_MADE
CONNECTION_AWAITING_RESPONSE
CONNECTION_AUTH_OK
CONNECTION_SSL_STARTUP
CONNECTION_SETENV
CONNECTION_OK
PQPING_OK
PQPING_REJECT
PQPING_NO_RESPONSE
PQPING_NO_ATTEMPT
PGRES_EMPTY_QUERY
PGRES_COMMAND_OK
PGRES_TUPLES_OK
PGRES_COPY_OUT
PGRES_COPY_IN
PGRES_BAD_RESPONSE
PGRES_NONFATAL_ERROR
PGRES_FATAL_ERROR
(continues on next page)
29.3. RingPostgreSQL Constants 181

Ring Documentation, Release 1.14
(continued from previous page)
PGRES_COPY_BOTH
PGRES_SINGLE_TUPLE
PG_DIAG_SEVERITY
PG_DIAG_SQLSTATE
PG_DIAG_MESSAGE_PRIMARY
PG_DIAG_MESSAGE_DETAIL
PG_DIAG_MESSAGE_HINT
PG_DIAG_STATEMENT_POSITION
PG_DIAG_INTERNAL_POSITION
PG_DIAG_INTERNAL_QUERY
PG_DIAG_CONTEXT
PG_DIAG_SCHEMA_NAME
PG_DIAG_TABLE_NAME
PG_DIAG_COLUMN_NAME
PG_DIAG_DATATYPE_NAME
PG_DIAG_CONSTRAINT_NAME
PG_DIAG_SOURCE_FILE
PG_DIAG_SOURCE_LINE
PG_DIAG_SOURCE_FUNCTION
29.4
The next functions are dene by the RingPostgreSQL Library
Reference :
PGconn*PQconnectdbParams(const char **keywords,
const char**values,int expand_dbname);
PGconn*PQconnectdb(const char *conninfo)
PGconn*PQsetdbLogin(const char *pghost,const char *pgport,
const char*pgoptions,const char *pgtty,
const char*dbName,const char *login,const char *pwd)
PGconn*PQsetdb(char*pghost,char*pgport,char*pgoptions,
char*pgtty,char*dbName)
PGconn*PQconnectStartParams(const char **keywords,
const char**values,int expand_dbname)
PGconn*PQconnectStart(const char *conninfo)
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
PQconninfoOption *PQconndefaults(void)
PQconninfoOption *PQconninfo(PGconn *conn)
PQconninfoOption *PQconninfoParse(const char *conninfo, char**errmsg)
void PQfinish(PGconn *conn)
void PQreset(PGconn *conn)
int PQresetStart(PGconn *conn)
PostgresPollingStatusType PQresetPoll(PGconn *conn)
PGPing PQpingParams(const char **keywords,const char **values,
int expand_dbname)
PGPing PQping(const char *conninfo)
char*PQdb(const PGconn *conn)
char*PQuser(const PGconn *conn)
char*PQpass(const PGconn *conn)
char*PQhost(const PGconn *conn)
char*PQport(const PGconn *conn)
(continues on next page)
29.4. RingPostgreSQL Functions 182

Ring Documentation, Release 1.14
(continued from previous page)
char*PQtty(const PGconn *conn)
char*PQoptions(const PGconn *conn)
ConnStatusType PQstatus(const PGconn *conn)
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
const char*PQparameterStatus(const PGconn *conn, const char *paramName)
int PQprotocolVersion(const PGconn *conn)
int PQserverVersion(const PGconn *conn)
char*PQerrorMessage(const PGconn *conn)
int PQsocket(const PGconn *conn)
int PQbackendPID(const PGconn *conn)
int PQconnectionNeedsPassword(const PGconn *conn)
int PQconnectionUsedPassword(const PGconn *conn)
int PQsslInUse(const PGconn *conn)
const char*PQsslAttribute(const PGconn *conn, const char *attribute_name)
const char**PQsslAttributeNames(const PGconn *conn)
void*PQsslStruct(const PGconn *conn, const char *struct_name)
void*PQgetssl(const PGconn *conn)
PGresult*PQexec(PGconn*conn, const char *command);
PGresult*PQexecParams(PGconn *conn,const char *command,int nParams,
const Oid*paramTypes,const char **paramValues,
const int*paramLengths,const int *paramFormats,int resultFormat)
PGresult*PQprepare(PGconn *conn,const char *stmtName,
const char*query,int nParams,const Oid *paramTypes)
PGresult*PQexecPrepared(PGconn *conn,const char *stmtName,
int nParams,const char **paramValues,
const int*paramLengths,const int *paramFormats,int resultFormat)
PGresult*PQdescribePrepared(PGconn *conn, const char *stmtName)
PGresult*PQdescribePortal(PGconn *conn, const char *portalName)
ExecStatusType PQresultStatus(const PGresult *res)
char*PQresStatus(ExecStatusType status)
char*PQresultErrorMessage(const PGresult *res)
char*PQresultErrorField(const PGresult *res, int fieldcode)
void PQclear(PGresult *res)
int PQntuples(const PGresult *res)
int PQnfields(const PGresult *res)
char*PQfname(const PGresult *res,int column_number)
int PQfnumber(const PGresult *res,const char*column_name)
Oid PQftable(const PGresult *res,int column_number)
int PQftablecol(const PGresult *res,int column_number)
int PQfformat(const PGresult *res,int column_number)
Oid PQftype(const PGresult *res,int column_number)
int PQfmod(const PGresult *res,int column_number)
int PQfsize(const PGresult *res,int column_number)
int PQbinaryTuples(const PGresult *res)
char*PQgetvalue(const PGresult *res,int row_number,int column_number)
int PQgetisnull(const PGresult *res,int row_number,int column_number)
int PQgetlength(const PGresult *res,int row_number,int column_number)
int PQnparams(const PGresult *res)
Oid PQparamtype(const PGresult *res, int param_number)
void PQprint(FILE *fout,const PGresult *res,const PQprintOpt *po)
char*PQcmdStatus(PGresult *res)
char*PQcmdTuples(PGresult *res)
Oid PQoidValue(const PGresult *res)
char*PQoidStatus(const PGresult *res)
char*PQescapeLiteral(PGconn *conn, const char *str, size_t length)
char*PQescapeIdentifier(PGconn *conn, const char *str, size_t length)
size_t PQescapeStringConn(PGconn *conn,char*to,
(continues on next page)
29.4. RingPostgreSQL Functions 183

Ring Documentation, Release 1.14
(continued from previous page)
const char*from, size_t length,int *error)
size_t PQescapeString(char *to, const char*from, size_t length)
unsigned char*PQescapeByteaConn(PGconn *conn,
const unsigned char *from,size_t from_length,size_t *to_length)
unsigned char*PQescapeBytea(const unsigned char *from,
size_t from_length,size_t *to_length)
unsigned char*PQunescapeBytea(const unsigned char *from, size_t*to_length)
int PQsendQuery(PGconn *conn, const char *command)
int PQsendQueryParams(PGconn *conn,const char *command,
int nParams,const Oid *paramTypes,const char **paramValues,
const int*paramLengths,const int *paramFormats,int resultFormat)
int PQsendPrepare(PGconn *conn,const char *stmtName,
const char*query,int nParams,const Oid *paramTypes)
int PQsendQueryPrepared(PGconn *conn,const char *stmtName,
int nParams,const char **paramValues,
const int*paramLengths,const int *paramFormats,int resultFormat)
int PQsendDescribePrepared(PGconn *conn, const char *stmtName)
int PQsendDescribePortal(PGconn *conn, const char *portalName)
PGresult*PQgetResult(PGconn *conn)
int PQconsumeInput(PGconn *conn)
int PQisBusy(PGconn *conn)
int PQsetnonblocking(PGconn *conn, int arg)
int PQisnonblocking(const PGconn *conn)
int PQflush(PGconn *conn)
int PQsetSingleRowMode(PGconn *conn)
PGcancel*PQgetCancel(PGconn *conn)
void PQfreeCancel(PGcancel *cancel)
int PQcancel(PGcancel *cancel, char*errbuf, int errbufsize)
int PQrequestCancel(PGconn *conn)
PGresult*PQfn(PGconn*conn,int fnid,int *result_buf,
int*result_len,int result_is_int,const PQArgBlock *args,int nargs)
PGnotify*PQnotifies(PGconn *conn)
int PQputCopyData(PGconn *conn,const char *buffer,int nbytes)
int PQputCopyEnd(PGconn *conn,const char *errormsg)
int PQgetCopyData(PGconn *conn,char**buffer,int async)
int PQgetline(PGconn *conn,char*buffer,int length)
int PQgetlineAsync(PGconn *conn,char*buffer,int bufsize)
int PQputline(PGconn *conn,const char *string)
int PQputnbytes(PGconn *conn,const char *buffer,int nbytes)
int PQendcopy(PGconn *conn)
int PQclientEncoding(const PGconn *conn)
char*pg_encoding_to_char(int encoding_id)
int PQsetClientEncoding(PGconn *conn, const char *encoding)
void PQtrace(PGconn *conn, FILE*stream)
void PQuntrace(PGconn *conn)
void PQfreemem(void *ptr)
void PQconninfoFree(PQconninfoOption *connOptions)
char*PQencryptPasswordConn(PGconn *conn, const char *passwd,
const char*user, const char *algorithm)
char*PQencryptPassword(const char *passwd, const char *user)
PGresult*PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
PGresult*PQcopyResult(const PGresult *src, int flags)
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
int PQsetvalue(PGresult *res, int tup_num, int field_num,
char*value, int len)
void*PQresultAlloc(PGresult *res, size_t nBytes)
(continues on next page)
29.4. RingPostgreSQL Functions 184

Ring Documentation, Release 1.14
(continued from previous page)
int PQlibVersion(void)
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn,
PQnoticeReceiver proc,void *arg)
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn,
PQnoticeProcessor proc,void *arg)
void PQinitOpenSSL(int do_ssl, int do_crypto)
void PQinitSSL(int do_ssl)
int PQisthreadsafe(void)
29.4. RingPostgreSQL Functions 185

CHAPTER
THIRTY
SECURITY AND INTERNET FUNCTIONS
This chapter contains the security and internet functions provided by the Ring programming language for Hashing,
Encryption & Decryption.
Before using the next functions load the openssllib.ring library
load"openssllib.ring"
# Use OpenSSL functions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Before using the next functions load the internetlib.ring library
load"internetlib.ring"
# Use the Internet functions
•
•
186

Ring Documentation, Release 1.14
30.1
We can calculate the MD5 hash using the MD5() Function
Syntax:
MD5(cString)--> Stringcontains the MD5 hash of the stringcString
Example:
see"md5(happy) ="happy")
"md5(Hello) ="Hello")
Output:
md5(happy) = 56ab24c15b72a457069c5ea42fcfc640
md5(Hello) = 8b1a9953c4611296a827abf8c47804d7
30.2
We can calculate the SHA1 hash using the SHA1() Function
Syntax:
SHA1(cString)--> Stringcontains the SHA1 hash of the stringcString
Example:
see"sha1(hello) :"hello")
"sha1(apple) :"apple")
Output:
sha1(hello) : aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
sha1(apple) : d0be2dc421be4fcd0172e5afceea3970e2f3d940
30.3
We can calculate the SHA256 hash using the SHA256() Function
Syntax:
SHA256(cString)--> Stringcontains the SHA256 hash of the stringcString
Example:
see"sha256(hello) :"hello")
"sha256(apple) :"apple")
Output:
sha256(hello) : 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
sha256(apple) : 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
30.1. MD5() Function 187

Ring Documentation, Release 1.14
30.4
We can calculate the SHA512 hash using the SHA512() Function
Syntax:
SHA512(cString)--> Stringcontains the SHA512 hash of the stringcString
Example:
see"sha512(hello) :"hello")
"sha512(apple) :"apple")
"sha512(hello world) :"hello world")
Output:
sha512(hello) : 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673c
a72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043
sha512(apple) : 844d8779103b94c18f4aa4cc0c3b4474058580a991fba85d3ca698a0bc9e52
c5940feb7a65a3a290e17e6b23ee943ecc4f73e7490327245b4fe5d5efb590feb2
sha512(hello world) : 309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca8
6d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f
30.5
We can calculate the SHA384 hash using the SHA384() Function
Syntax:
SHA384(cString)--> Stringcontains the SHA384 hash of the stringcString
Example:
see"sha384(hello) :"hello")
"sha384(apple) :"apple")
"sha384(hello world) :"hello world")
Output:
sha384(hello) : 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa
90125a3c79f90397bdf5f6a13de828684f
sha384(apple) : 3d8786fcb588c93348756c6429717dc6c374a14f7029362281a3b21dc10250
ddf0d0578052749822eb08bc0dc1e68b0f
sha384(hello world) : fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcb
b83578b3e417cb71ce646efd0819dd8c088de1bd
30.4. SHA512() Function 188

Ring Documentation, Release 1.14
30.6
We can calculate the SHA224 hash using the SHA224() Function
Syntax:
SHA224(cString)--> Stringcontains the SHA224 hash of the stringcString
Example:
see"sha224(hello) :"hello")
"sha224(apple) :"apple")
"sha224(hello world) :"hello world")
Output:
sha224(hello) : ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193
sha224(apple) : b7bbfdf1a1012999b3c466fdeb906a629caa5e3e022428d1eb702281
sha224(hello world) : 2f05477fc24bb4faefd86517156dafdecec45b8ad3cf2522a563582b
30.7
We can use the Encrypt() function to encrypts the data using the Blowsh algorithm.
Syntax:
Encrypt(cString, cKey, cIV)--> string
30.8
We can use the Decrypt() function to decrypt the data encrypted using the Encrypt() function.
Syntax:
Decrypt(cCipher, cKey, cIV)--> string
30.9
The next example demonstrates how to use the Encrypt() and Decrypt() functions.
These functions use the Blowsh algorithm.
See"Enter a string : givecStr
list=:15="" forxin cKey= next
list=:8" forxin cIV= next
cStr
See"Cipher Text :
"Plain Text :
We can write the same example using normal for loop
30.6. SHA224() Function 189

Ring Documentation, Release 1.14
See"Enter a string : givecStr
cKey="" # 16 bytes
forx to15
cKey=
next
cIV"
forx to8
cIV=
next
cStr
See"Cipher Text :
"Plain Text :
Also we can write the password and the IV directly using strings
See"Enter a string : givecStr
# Note: Dont use simple password in real applications!
cKey1234567890@#$%^&"
cIV87654321"
cStr
See"Cipher Text :
"Plain Text :
30.10
The next example demonstrates how to calculate the hash functions for les
cStr"myapp.exe")
see"Size :
"md5 :
"sha1 :
"sha256 :
"sha224 :
"sha384 :
"sha512 :
Output:
Size : 58079876
md5 : 762eee15d8d2fd73b71ea52538b28667
sha1 : 9212c0c7258bad89a62bd239e1358a9276a9d070
sha256 : 7d6724e69b6c553da749ba31b6185dddc965129b64d9e9bf3de88f67df3b1cdc
sha224 : 5a9c8a7d662bce4f880ba94f90a79362b672528b9efd5abc718c7a3d
sha384 : 18e23f973abedbeb3981c423f12aeadecf96f9c6fb28aeabe3be4c484f8540afcc3861b
b370ce2b59cf3c99c130b856b
sha512 : da3d5e997d06f8b2a7a9964b77f7d82eedb76b245c611082c1639f83f51d83880bcd08f
cd53dcab1167bdca0b82fec5071971ac17c76479d76985ced4ab0d18e
30.10. File Hash 190

Ring Documentation, Release 1.14
30.11
We can generate a string of pseudo-random bytes using the Randbytes() function.
Syntax:
Randbytes(nSize)--> Stringcontains random bytes (bytes count
Example:
salt32)
passwordSecretPassWord@$%123"
seesalt
seesha256("test"
30.12
These functions compute the hash of large les/data without the need to load all of the content in a single string.
md5init() -> MD5_CTX
md5update (MD5_CTX, string) -> 1 for success or 0 for failure
md5final (MD5_CTX) -> string
sha1init() -> SHA_CTX
sha1update (SHA_CTX, string) -> 1 for success or 0 for failure
sha1final (SHA_CTX) -> string
sha224init() -> SHA224_CTX
sha224update (SHA224_CTX, string) -> 1 for success or 0 for failure
sha224final (SHA224_CTX) -> string
sha256init() -> SHA256_CTX
sha256update (SHA256_CTX, string) -> 1 for success or 0 for failure
sha256final (SHA256_CTX) -> string
sha384init() -> SHA384_CTX
sha384update (SHA384_CTX, string) -> 1 for success or 0 for failure
sha384final (SHA384_CTX) -> string
sha512init() -> SHA512_CTX
sha512update (SHA512_CTX, string) -> 1 for success or 0 for failure
sha512final (SHA512_CTX) -> string
30.13
Syntax:
Download(cURL)--> Stringcontains the server response
Example:
30.11. Randbytes() Function 191

Ring Documentation, Release 1.14
cStr="http://doublesvsoop.sourceforge.net/")
seecStr
write("download.txt",cStr)
30.14
Syntax:
SendEmail(cSMTPServer,cEmail,cPassword,cSender,cReceiver,cCC,cTitle,cContent)
Example:
See"Send email..."
sendemail("smtp://smtp.gmail.com:587",
"[email protected]",
"password",
"[email protected]",
"[email protected]",
"[email protected]",
"Sending email from Ring",
"Hello
How are you?
Are you fine?
Thank you!
Greetings,
Mahmoud")
see"Done.."
30.14. SendEmail() Function 192

CHAPTER
THIRTYONE
OBJECT ORIENTED PROGRAMMING (OOP)
In this chapter we are going to learn how to use the Object-Oriented programming paradigm inside the Ring program-
ming language.
We will learn about
•
•
•
•
•
•
•
•
•
•
•
•
•
•
31.1
We can dene new classes using the next syntax
Syntax:
Class<ClassName> From|<|:Parent ClassName>]
[Attributes]
[Methods]
[Private
[Attributes]
[Methods]
]
193

Ring Documentation, Release 1.14
And we can create objects using the next syntax
Syntax:
New<Object Name>
[ andmethods }-->
Example:
Newpoint { x=10=20=30
ClassPoint x y zfuncprintseex
Note:We can use { } to access object data and methods.
Tip:we can declare the class attributes directly after the class name.
Output:
10
20
30
We can rewrite the same program in another style
Newpoint # create new object using the point class
{ # access the new object attributes and methods
x # set the x attribute to 10
y # set the y attribute to 20
z # set the z attribute to 30
print() # call the print method
} # end of object access
ClassPoint # define the Point class
x y z # the class contains three attributes x, y & z
funcprint # define the print method
seex # print the x attribute
y # print the y attribute
z # print the z attribute
Also we can write the same program in another way
P1 NewPoint
P1.x
P1.y
P1.z
P1.Print()
ClassPoint x y zfuncprintseex
Note:we can use the dot operator after the object name to access object members.
Also we can write the same program in another way
31.1. Classes and Objects 194

Ring Documentation, Release 1.14
newpoint { print() }
ClassPoint
x
funcprintseex
Note:we can set the default values for the class attributes when we declare them.
Also we can write the same program in another way
newpoint(10,20,30)
ClassPoint
x y z
funcinit p1,p2,p3 x=p1 y=p2 z=p3 print()
funcprintseex
Note:we can call the init method directly using () when we create new objects
Also we can write the same program in another way
newpoint(
ClassPoint x y z
funcinit aPara x[:x][:y][:z]
funcprintseex
Tip:using Hash for passing method parameters enable us to create optional parameters and change the order of
parameters when adding them to the Hash.
31.2
We can access the object at any time using braces { }
Inside the braces we can use the object attributes and methods directly
This can be done when we create the object using the New keyword or at any time using the next syntax
ObjectName { access object data andmethods }
Example:
See"Creating the Object"
o1 newPoint
See"Using the Object"
o1 {
x=5
y=15
z=25
print()
}
ClassPoint x y zfuncprintseex
31.2. Access Objects Using Braces 195

Ring Documentation, Release 1.14
We can use braces to access objects when we call functions or methods
Example:
o1 newPoint
print( o1 { x=10=20=30
funcprint object
seeobject.x
object.y
object.z
ClassPoint x y z
We can mix between using braces and the dot operator to access the object in the same expression.
Example:
o1 newPoint
O1 { x=10=20=30
ClassPoint x y z
funcprintseex
31.3
The object may contains other objects as attributes.
Using braces to access objects can be nested.
Example:
R1 NewRectangle
{
NameRectangle 1"
P1
{
X
Y
}
P2
{
X
Y
}
ColorBlue"
}
see"Name :
"Color:
(continues on next page)
31.3. Composition 196

Ring Documentation, Release 1.14
(continued from previous page)
"P1 : (",")"
"P2 : (",")"
ClassRectangle
name color
p1 newPoint
p2 newPoint
ClassPoint x y
Output:
Name : Rectangle
Color: Blue
P1 : (10,20)
P2 : (200,300)
31.4
We can dene methods to be used when we set and get object attributes.
Syntax:
ClassClassName
AttributeName
...
FuncSetAttributeName
...
FuncGetAttributeName
...
Example:
o1 newperson
o1.nameMahmoud" seeo1.name
o1 { nameAhmed" seename }
ClassPerson
name familyFayed"
funcsetname value
see"Message from SetName() Function!"
name
funcgetname
see"Message from GetName() Function!"
return"Mr.
Output:
31.4. Setter and Getter 197

Ring Documentation, Release 1.14
MessagefromSetName() Function!
MessagefromGetName() Function!
Mr. Mahmoud Fayed
MessagefromSetName() Function!
MessagefromGetName() Function!
Mr. Ahmed Fayed
31.5
We can dene private attributes and methods after the keyword private inside the class body
Example:
o1 newperson {
nameTest"
age
print()
o1.printsalary()
}
try
seeo1.salary
catch
seecCatchError
done
try
o1.increasesalary(1000)
catch
seecCatchError
done
ClassPerson
name age
funcprint
see"Name :
"Age :
funcprintsalary
see"Salary :
private
salary
funcincreasesalary x
salary=
Output:
Name : Test
Age :
Salary :
(continues on next page)
31.5. Private Attributes and Methods 198

Ring Documentation, Release 1.14
(continued from previous page)
Error (R27) : Using private attribute fromoutside theclass: salary
Error (R26) : Calling private method fromoutside theclass: increasesalary
31.6
We can add the operator method to our class to enable using operators with the class objects.
Syntax:
ClassClassName
...
Funcoperator cOperator,Para
...
The function operator takes two parameters, the rst represent the operator and the second represent the second pa-
rameter after the operator.
Example:
o1 newpoint { x"P1 :) }
o2 newpoint { x"P2 :) }
o3
o3.print("P1+P2 :)
classpoint x y
funcoperator cOperator,Para
result newpoint
switchcOperator
on"+"
result.x
result.y
on"-"
result.x
result.y
off
returnresult
funcprint cPoint
seecPointX :
Output:
P1 : X :
P2 : X :
P1+P2 : X :
The next example from the List class in the stdlib.ring
Funcoperator cOperator,Para
result new
(continues on next page)
31.6. Operator Overloading 199

Ring Documentation, Release 1.14
(continued from previous page)
switchcOperator
on"+"
ifisobject(para)
fortinPara.vValue
vValue
next
butislist(para)
fortinPara
vValue
next
ok
on"len"
returnlen( vValue )
on"[]"
return&vValue[para]
off
returnresult
The “len” operator is used with (for in) control structure.
The “[]” operator is used when we try to access the list items, In this case we use the & operator to return the item
values like strings an numbers by reference, so we can update it when we access the items.
Another Example
funcmain
See"----1"+nl
a1 newBigNumber(123"
a2 newBigNumber(456"
a3 newBigNumber(789"
Seenl+"----2"+nl
a1.print()
a2.print()
a3.print()
Seenl+"----3"+nl
a245"
Seenl+"----4"+nl
a2.print()
Seenl+"----5"+nl
a3
Seenl+"----6"+nl
a3.print()
Seenl+"----7"+nl
###==================================
FuncFuncAdd( num1, num2)
Sum ### Para.aData isNumber
Sum"Sum ### Para.adata isString
returnSum ### return to Class
###===================================
classBigNumber
### Variables
aData468"
(continues on next page)
31.6. Operator Overloading 200

Ring Documentation, Release 1.14
(continued from previous page)
### Functions INIT default values
funcinit aPara
?INIT aPara:
ifisString(aPara)
aData
else
aData"
ok
### Other Functions
funcoperator cOperator, Para
whatType
?+"WhatType-PARA:+
?+"Operator:+"PARA:"
ifwhatTypeSTRING"
dataInfo
?dataInfo String:
butwhatTypeNUMBER"
datinfo"
?dataInfo Number:
elsewhatTypeOBJECT"
dataInfo"
?dataInfo OBJECT:
ok
?dataInfo USING:
### Para.aData does NOT exist on first pass ( Object with member)
### Result isObject when assigned "self"
result
switchcOperator
on"+"
answer
?+"AnswerString - FunAdd aData, dataInfo:
### result = self, is Object, populate Object with aData member
result.aData
off
### Result = Self is Object
returnresult
funcprint
?+"ClassPrint aData:
31.7
We can create class from another class in the class denition using the keyword from.
Syntax:
Class<ClassName> From<ParentClassName>]
We can call a method in the parent class from the child class using the super object.
Syntax:
funcmethodname
...
(continues on next page)
31.7. Inheritance 201

Ring Documentation, Release 1.14
(continued from previous page)
super.methodname()
...
Example:
Funcmain
e1 newEmployee {
Nametest"
age
jobprogrammer"
salary
print()
}
ClassHuman
Name Age
funcprint
see"Name :Age :
ClassEmployeefromHuman
Job Salary
funcprint
super.print()
see"Job :Salary :
Output:
Name : test
Age :
Job : programmer
Salary :
31.8
We can write instructions after the class name to be executed when we create new objects
Example:
o1 newdynamicClass
seeo1.var5 # output 5
ClassDynamicClass
forx to10
cStrvar"
eval(cStr)
next
Tip:in the previous example var1, var2, . . . , var10 will be dened as attributes.
Tip:The problem with the previous example is that x and cStr will be dened as attributes too!
31.8. Dynamic Attributes 202

Ring Documentation, Release 1.14
Note:we can write class denitions inside a string then using eval() we can execute the string to dene the classes
31.9
We can create a package (a group of classes under a common name) using the next syntax
package PackageName
ClassClass1
...
ClassClass2
...
ClassClass3
...
...
Example
o1 newSystem.output.console
o1.print("Hello World")
Package System.Output
ClassConsole
FuncPrint cText
seecText
Note:we can use the dot operator as part of the package name
Instead of typing the long name PackageName.ClassName we can use the import command
When we import a package, we can use any class inside this package directly.
Example
importsystem.output
o1 newconsole {
print("Hello World")
}
Package System.Output
ClassConsole
FuncPrint cText
seecText
31.9. Packages 203

Ring Documentation, Release 1.14
31.10
We can print the object state (attributes and values) using the see command.
Example:
see point { x=10=20=30
classpoint x y z
Output:
x:.000000
y:.000000
z:.000000
31.11
We can use the nd() function to search inside a list of objects.
Syntax:
Find(List,ItemValue,nColumn,cAttribute)-->
Example:
myList1 newCompany {position=3="Mahmoud"="MHD"},
newCompany {position=2="Bert"="BRT"},
newCompany {position=1="Ring"="RNG"}
]
seefind(mylist1,"Bert",1,"name")
seefind(mylist1,"Ring",1,"name")
seefind(mylist1,"Mahmoud",1,"name")
seefind(mylist1,"RNG",1,"symbol")
seefind(mylist1,"MHD",1,"symbol")
seefind(mylist1,"BRT",1,"symbol")
seefind(mylist1,3,1,"position")
seefind(mylist1,1,1,"position")
see"Other"
seefind(mylist1,"test",1,"name")
seefind(mylist1,"test",0,"name")
seefind(mylist1,"test",5,"name")
classcompany position name symbol
Output:
2
3
1
3
1
2
1
3
(continues on next page)
31.10. Printing Objects 204

Ring Documentation, Release 1.14
(continued from previous page)
Other
0
0
0
31.12
We can sort a list of objects based on an object attribute using the Sort() function.
Syntax:
Sort(List,nColumn,cAttribute)--> ListbasedonObject Attribute
Example:
myList1
newCompany {position=3="Mahmoud"="MHD"},
newCompany {position=2="Bert"="BRT"},
newCompany {position=8="Charlie"="CHR"},
newCompany {position=6="Easy"="FEAS"},
newCompany {position=7="Fox"="EFOX"},
newCompany {position=5="Dog"="GDOG"},
newCompany {position=4="George"="DGRG"},
newCompany {position=1="Ring"="RNG"}
]
seesort(mylist1,1,"name")
seecopy(" *",70)
seesort(mylist1,1,"symbol")
seecopy(" *",70)
seesort(mylist1,1,"position")
classcompany position name symbol
Output:
position:.000000
name: Bert
symbol: BRT
position:.000000
name: Charlie
symbol: CHR
position:.000000
name: Dog
symbol: GDOG
position:.000000
name: Easy
symbol: FEAS
position:.000000
name: Fox
symbol: EFOX
position:.000000
name: George
symbol: DGRG
(continues on next page)
31.12. Sort() and List of Objects 205

Ring Documentation, Release 1.14
(continued from previous page)
position:.000000
name: Mahmoud
symbol: MHD
position:.000000
name: Ring
symbol: RNG
**********************************************************************
position:.000000
name: Bert
symbol: BRT
position:.000000
name: Charlie
symbol: CHR
position:.000000
name: George
symbol: DGRG
position:.000000
name: Fox
symbol: EFOX
position:.000000
name: Easy
symbol: FEAS
position:.000000
name: Dog
symbol: GDOG
position:.000000
name: Mahmoud
symbol: MHD
position:.000000
name: Ring
symbol: RNG
**********************************************************************
position:.000000
name: Ring
symbol: RNG
position:.000000
name: Bert
symbol: BRT
position:.000000
name: Mahmoud
symbol: MHD
position:.000000
name: George
symbol: DGRG
position:.000000
name: Dog
symbol: GDOG
position:.000000
name: Easy
symbol: FEAS
position:.000000
name: Fox
symbol: EFOX
position:.000000
name: Charlie
symbol: CHR
31.12. Sort() and List of Objects 206

Ring Documentation, Release 1.14
31.13
Inside the class region (After the class name and before any method) and the class methods we can use self.attribute
and self.method()
ClassPoint
self.x
self.y
self.z
funcprint
seeself.x
Note:using self.attribute in the class region to dene the class attribute protect the class attributes from conict with
global variables.
Tip:if you typed the class attributes with self.attribute and there are a global variable with the same name it will be
used and the attribute will not be dened.
Check the “Scope Rules” chapter to know about the conict between the global variable name and the attribute name
Whay this may happens?
Because
•
•
Note:Try to avoid the global variables, use the main function and start their names with $
Tip:In large programs protect your classes and dene their members using self.attribute
31.14
Inside class methods we have access to the object scope directly. we don't need to use Self.attribute or Self.method to
read/write attribute and call methods.
But we can use braces {} while we are inside methods to access another object, In this case the current object scope
will be changed while we are inside the brace.
How we can get access to our class attributes and methods while we are inside braces?
This can be done using This.Attribute and This.Method()
Example:
newpoint
classpoint
x=10=20=30
(continues on next page)
31.13. Using Self.Attribute and Self.Method() 207

Ring Documentation, Release 1.14
(continued from previous page)
print()
funcprint
newUI {
display(this.x,this.y,this.z)
}
ClassUI
funcdisplay x,y,z
seex
31.15
The class region is the region that comes after the class name and before any method.
We can use This in the class region as Self.
Example:
funcmain
o1 newprogram {
test()
}
?
classprogram
this.nameMy Application"
this.version1.0"
?
functest
?Name =
?Version =
Output
My Application
1.0
Name = My Application
Version = 1.0
name: My Application
version: 1.0
Note:When we use braces to change the current active object, Using This we can still point to the class.
Tip:The difference between This and Self is that Self point to the current active object that we can change using
braces.
Remember that in most cases we don't need to use This or Self in the class region
31.15. Using This in the class region as Self 208

Ring Documentation, Release 1.14
We can write
classprogram name version
Or
classprogram name="My Application"="1.0"
Note:We use This or Self in the class region just to avoid conict with global variables that are dened with the same
name.
31.16
The default value for object attributes is NULL
In Ring, the NULL value is just an empty string or a string that contains “NULL”
We can check for NULL values using the isNULL() function
Example:
oProgram newProgram
?
?
?
?
oProgram { name="My Application"="1.0"
?
?
?
classprogram
name
version
Output:
NULL
NULL
1
1
0
0
name: My Application
version: 1.0
31.16. Default value for object attributes 209

CHAPTER
THIRTYTWO
FUNCTIONAL PROGRAMMING
In previous chapters we learned about Functions and Recursion.
In this chapter we are going to learn about more Functional Programming (FP) concepts like
•
•
•
•
•
32.1
We can create pure functions (functions that doesn't change the state) by the help of the assignment operator to copy
variables (Lists & Objects) by value to create new variables instead of working on the original data that are passed to
the function by reference.
Example:
FuncMain
aList1,2,3,4,5]
aList2
see"aList"
seeaList
see"aList2"
seeaList2
FuncSquare aPara
a1 # copy the list
forxina1
x*=
next
returna1 # return new list
Output:
aList
1
2
3
4
(continues on next page)
210

Ring Documentation, Release 1.14
(continued from previous page)
5
aList2
1
4
9
16
25
32.2
Functions inside the Ring programming language are rst-class citizens, you can pass functions as parameters, return
them as value or store them in variables.
We can pass/return the function by typing the function name as literal like “FunctionName” or :FunctionName for
example.
We can pass/return functions using the variable that contains the function name.
We can call function from variables contains the function name using the Call command
Syntax:
CallVariable([Parameters])
Example:
FuncMain
see"before test2()"
f
see"after test2()"
callf()
FuncTest
see"Message from test!"
FuncTest2 f1
callf1()
See"Message from test2!"
returnf1
Output:
before test2()
Messagefromtest!
Messagefromtest2!
after test2()
Messagefromtest!
32.2. First-class Functions 211

Ring Documentation, Release 1.14
32.3
Higher-order functions are the functions that takes other functions as parameters.
Example:
FuncMain
times(5,:test)
FuncTest
see"Message from the test function!"
FuncTimes nCount,F
forx tonCount
CallF()
next
Output:
Messagefromthe test function!
Messagefromthe test function!
Messagefromthe test function!
Messagefromthe test function!
Messagefromthe test function!
32.4
Anonymous Functions are functions without names that can be passed as parameters to other functions or stored in
variables.
Syntax:
Func[Parameters]statements]
Example:
test(funcx,y {
see"hello"
see"Sum :+y)
} )
newgreat { f1() }
times(3, func{see"hello world"
functest x
callx(3,3)
see"wow!"
functimes n,x
fort=1ton
callx()
next
(continues on next page)
32.3. Higher-order Functions 212

Ring Documentation, Release 1.14
(continued from previous page)
Classgreat
funcf1
f2(func{see"Message from f1"
funcf2 x
callx()
Output:
hello
Sum :
wow!
Messagefromf1
hello world
hello world
hello world
Example:
FuncMain
aList1,2,3,4]
Map (aList ,funcx {
returnx*x
} )
seeaList
aList4,9,14,25]
Map(aList, :myfilter )
seeaList
aList11,12,13,14]
Map (aList ,funcx {
ifx%2=0
return"even"
else
return"odd"
ok
})
seeaList
Funcmyfilter x
ifx
return"True"
else
return"False"
ok
FuncMap aList,cFunc
forxinaList
x callcFunc(x)
next
Output:
1
4
9
16
False
(continues on next page)
32.4. Anonymous and Nested Functions 213

Ring Documentation, Release 1.14
(continued from previous page)
True
False
False
odd
even
odd
even
32.5
We can test if function = function or not using the `=' or `!=' operators
Example:
f1 func{see"hello"
f2 func{see"how are you?"
f3
callf1()
callf2()
callf3()
see(f1
see(f2
see(f1
Output:
hello
how are you?
hello
0
0
1
32.5. Equality of functions 214

CHAPTER
THIRTYTHREE
REFLECTION AND META-PROGRAMMING
Since the Ring programming language is a dynamic language, we can get answers about the program code and we can
modify our code during the runtime.
In this chapter we will learn about this and the available functions to use.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
215

Ring Documentation, Release 1.14
•
•
•
•
33.1
We can get a list of variables names in the current scope using the locals() function.
Syntax:
locals()-> listcontains the variables names inthe current scope
Example:
test("hello")
functest cMsg
seecMsg
x
y
z
seelocals()
Output:
hello
cmsg
x
y
z
33.2
We can get a list of variables names in the global scope using the globals() function.
Syntax:
globals()-> listcontains variables names inthe global scope
Example:
x=10=20=30
test()
functest
see"message from test()"
"Global Variables:"
seeglobals()
33.1. locals() Function 216

Ring Documentation, Release 1.14
Output:
messagefromtest()
Global Variables:
x
y
z
33.3
We can get a list of functions names written in the Ring language using the functions() function.
Syntax:
functions()-> listcontains functions names
Example:
seefunctions()
funcf1
see"f1"
funcf2
see"f2"
funcf3
see"f3"
Output:
f1
f2
f3
33.4
We can get a list of functions names written in the C language using the cfunctions() function.
Syntax:
cfunctions()-> listcontains functions names
Example:
aList
See"Count :
forxinaList
seex()"
next
Output:
33.3. functions() Function 217

Ring Documentation, Release 1.14
Count :
len()
add()
del()
get()
clock()
...
Note:The complete list is removed from the previous output.
33.5
&#3627408458;&#3627408466; &#3627408464;&#3627408462;&#3627408475; &#3627408464;&#3627408469;&#3627408466;&#3627408464;&#3627408472; &#3627408470;&#3627408467; &#3627408462; &#3627408483;&#3627408462;&#3627408479;&#3627408470;&#3627408462;&#3627408463;&#3627408473;&#3627408466; &#3627408470;&#3627408480; &#3627408465;&#3627408466;??????&#3627408475;&#3627408466;&#3627408465; &#3627408470;&#3627408475; &#3627408481;&#3627408469;&#3627408466; &#3627408473;&#3627408476;&#3627408464;&#3627408462;&#3627408473; &#3627408480;&#3627408464;&#3627408476;&#3627408477;&#3627408466; &#3627408476;&#3627408479; &#3627408475;&#3627408476;&#3627408481; &#3627408482;&#3627408480;&#3627408470;&#3627408475;&#3627408468; &#3627408481;&#3627408469;&#3627408466; &#3627408470;&#3627408480;&#3627408473;&#3627408476;&#3627408464;&#3627408462;&#3627408473;↼↽ &#3627408467;&#3627408482;&#3627408475;&#3627408464;&#3627408481;&#3627408470;&#3627408476;&#3627408475;◁
Syntax:
islocal(cVariableName)-> ifthe variable is defined inthe local scope
returns ifthe variable is notdefinedinthe local scope
Example:
test()
functest
x=10=20
seeislocal("x")
islocal("y")
islocal("z")
Output:
1
1
0
33.6
&#3627408458;&#3627408466; &#3627408464;&#3627408462;&#3627408475; &#3627408464;&#3627408469;&#3627408466;&#3627408464;&#3627408472; &#3627408470;&#3627408467; &#3627408462; &#3627408483;&#3627408462;&#3627408479;&#3627408470;&#3627408462;&#3627408463;&#3627408473;&#3627408466; &#3627408470;&#3627408480; &#3627408465;&#3627408466;??????&#3627408475;&#3627408466;&#3627408465; &#3627408470;&#3627408475; &#3627408481;&#3627408469;&#3627408466; &#3627408468;&#3627408473;&#3627408476;&#3627408463;&#3627408462;&#3627408473; &#3627408480;&#3627408464;&#3627408476;&#3627408477;&#3627408466; &#3627408476;&#3627408479; &#3627408475;&#3627408476;&#3627408481; &#3627408482;&#3627408480;&#3627408470;&#3627408475;&#3627408468; &#3627408481;&#3627408469;&#3627408466; &#3627408470;&#3627408480;&#3627408468;&#3627408473;&#3627408476;&#3627408463;&#3627408462;&#3627408473;↼↽ &#3627408467;&#3627408482;&#3627408475;&#3627408464;&#3627408481;&#3627408470;&#3627408476;&#3627408475;◁
Syntax:
isglobal(cVariableName)-> ifthe variable is defined inthe global scope
returns ifthe variable is notdefinedinthe global
˓→scope
Example:
x=10=20
test()
(continues on next page)
33.5. islocal() Function 218

Ring Documentation, Release 1.14
(continued from previous page)
functest
seeisglobal("x")
isglobal("y")
isglobal("z")
Output:
1
1
0
33.7
We can check if a Ring function is dened or not using the isfunction() function.
Syntax:
isfunction(cFunctionName)-> ifthe Ring function is defined
returns ifthe Ring function is notdefined
Example:
seeisfunction("f1")
isfunction("f2")
isfunction("f3")
funcf1
see"message from f1()"
funcf2
see"message from f2()"
Output:
1
1
0
33.8
We can check if a C function is dened or not using the iscfunction() function.
Syntax:
iscfunction(cFunctionName)-> ifthe C function is defined
returns ifthe C function is notdefined
Example:
seeiscfunction("len")
iscfunction("add")
iscfunction("test")
33.7. isfunction() Function 219

Ring Documentation, Release 1.14
Output:
1
1
0
33.9
We can get a list of packages names using the packages() function.
Syntax:
packages()-> listcontains packages names
Example:
Seepackages()
Package Package1
Classclass1
Funcf1
Package Package2
Classclass1
Funcf1
Package Package3
Classclass1
Funcf1
Package Package4
Classclass1
Funcf1
Output:
package1
package2
package3
package4
33.10
We can check if a package is dened or not using the ispackage() function.
Syntax:
ispackage(cPackageName)-> ifthe Package is defined
returns ifthe Package isnotdefined
Example:
33.9. packages() Function 220

Ring Documentation, Release 1.14
Seeispackage("package1")
ispackage("package4")
ispackage("package5")
ispackage("package3")
Package Package1
Classclass1
Funcf1
Package Package2
Classclass1
Funcf1
Package Package3
Classclass1
Funcf1
Package Package4
Classclass1
Funcf1
Output:
1
1
0
1
33.11
We can get a list of classes names using the classes() function.
Syntax:
classes()-> listcontains classes names
Example:
Seeclasses()
Classclass1
Funcf1
Classclass2
Funcf1
Classclass3
Funcf1
Output:
class1
class2
class3
33.11. classes() Function 221

Ring Documentation, Release 1.14
33.12
We can check if a class is dened or not using the isclass() function.
Syntax:
isclass(cClassName)-> iftheClassis defined
returns iftheClassisnotdefined
Example:
seeisclass("class4")
isclass("class3")
isclass("class2")
Classclass1
funcf1
classclass2
funcf1
classclass3
funcf1
Output:
0
1
1
33.13
We can get a list of classes names inside a package using the packageclasses() function.
Syntax:
packageclasses(cPackageName)-> listcontains classes names inside the package
Example:
see"classes in Package1"
seepackageclasses("Package1")
see"classes in Package2"
seepackageclasses("Package2")
Package Package1
Classclass1
Funcf1
Package Package2
Classclass1
Funcf1
Classclass2
Funcf1
Classclass3
funcf1
33.12. isclass() Function 222

Ring Documentation, Release 1.14
Output:
classesinPackage1
class1
classesinPackage2
class1
class2
class3
33.14
We can check if a class is dened inside package or not using the ispackageclass() function.
Syntax:
ispackageclass(cPackageName,cClassName)-> iftheClassis defined
returns iftheClassisnotdefined
Example:
seeispackageclass("package1","class1")
ispackageclass("package1","class2")
ispackageclass("package2","class1")
ispackageclass("package2","class2")
Package Package1
Classclass1
Funcf1
Package Package2
Classclass1
Funcf1
Classclass2
Funcf1
Classclass3
funcf1
Output:
1
0
1
1
33.15
We can know the class name of an object using the classname() function
Syntax:
classname(object)-> classname
Example:
33.14. ispackageclass() Function 223

Ring Documentation, Release 1.14
o1 newpoint
o2 newrect
seeclassname(o1) # print point
seeclassname(o2) # print rect
classpoint
classrect
33.16
We can know the object id using the objectid() function
Syntax:
objectid(object)->
Example:
o1 newpoint
seeobjectid(o1)
test(o1)
functest v
seeobjectid(v)
Classpoint x y z
Output:
021B5808
021B5808
33.17
We can check the variable to know if it's an object or not using the isobject() function
Syntax:
isobject(variable)-> True itsnbject,alsefts not
33.18
We can get the object attributes using the attributes() function
Syntax:
attributes(object)-> listcontains the object attributes
Example:
33.16. objectid() Function 224

Ring Documentation, Release 1.14
o1 newpoint
aList # we can use see attributes(o1)
fortinaListseetnext # print xyz
ClassPoint x y z
33.19
We can get the object methods using the methods() function
Syntax:
methods(object)-> listcontains the object methods
Example:
o1 newtest
aList
forxinaList
cCodeo1."+x+"()"
eval(cCode)
next
ClassTest
funcf1
see"hello from f1"
funcf2
see"hello from f2"
funcf3
see"hello from f3"
funcf4
see"hello from f4"
Output:
hellofromf1
hellofromf2
hellofromf3
hellofromf4
33.20
We can test if the object contains an attribute or not using the isattribute() function
Syntax:
isattribute(object,cAttributeName)-> True the object contains the
˓→attribute
Example:
33.19. methods() Function 225

Ring Documentation, Release 1.14
o1 newpoint
seeisattribute(o1,"x") # print 1
seeisattribute(o1,"t") # print 0
seeisattribute(o1,"y") # print 1
seeisattribute(o1,"z") # print 1
classpoint x y z
33.21
We can test if the object contains a private attribute or not using the isprivateattribute() function
Syntax:
isprivateattribute(object,cAttributeName)-> True the object
contains the private attribute
Example:
o1 newperson
seeisprivateattribute(o1,"name")
isprivateattribute(o1,"address")
isprivateattribute(o1,"phone")
isprivateattribute(o1,"job")
isprivateattribute(o1,"salary")
ClassPerson
name address phone
private
job salary
Output:
0
0
0
1
1
33.22
We can test if the object class contains a method or not using the ismethod() function
Syntax:
ismethod(object,cMethodName)-> True the objectclasscontains the method
Example:
33.21. isprivateattribute() Function 226

Ring Documentation, Release 1.14
o1 newpoint
seeismethod(o1,"print") # print 1
mylist]
mylist newpoint
seeismethod(mylist[1],"print") # print 1
classpoint x y z
funcprint
seex
33.23
We can test if the object class contains a private method or not using the isprivatemethod() function
Syntax:
isprivatemethod(object,cMethodName)-> True the objectclasscontains
the private method
Example:
o1 newTest
seeisprivatemethod(o1,"f1")
isprivatemethod(o1,"f2")
ClassTest
funcf1
see"message from f1()"
private
funcf2
see"message from f2()"
Output:
0
1
33.24
We can add an attribute (or a group of attributes) to the object state (not the class) using the addattribute() function
Syntax:
AddAttribute(object,cAttributeName|aAttributesList)
Example(1):
33.23. isprivatemethod() Function 227

Ring Documentation, Release 1.14
see point {x=10=20=30}
ClassPoint
AddAttribute(self,["x","y","z"])
Example(2):
o1 newpoint
addattribute(o1,"x")
addattribute(o1,"y")
addattribute(o1,"z")
seeo1 {x=10=20=30}
classpoint
Output:
x:.000000
y:.000000
z:.000000
33.25
We can add a method to the object class using the addmethod() function This method can be used with any object from
the same class.
Syntax:
AddMethod(Object,cNewMethodName,cMethodName|AnonymousFunction)
Example:
o1 newpoint { x=10=20=30
addmethod(o1,"print", func{seex
o1.print()
Classpoint
x y z
Output:
10
20
30
Instead of using anonymous function to add new method to the class, we can use the function name
Example:
o1 newpoint { x=10=20=30
myfunc func{seex
addmethod(o1,"print", myfunc )
addmethod(o1,"display", myfunc )
(continues on next page)
33.25. addmethod() Function 228

Ring Documentation, Release 1.14
(continued from previous page)
addmethod(o1,"show", myfunc )
o1.print()
o1.display()
o1.show()
Classpoint
x y z
Output:
10
20
30
10
20
30
10
20
30
Since we add the method to the class, any object from that class can use this method
Example:
o1 newpoint { x=10=20=30
o2 newpoint { x=100=200=300
o3 newpoint { x=50=150=250
addmethod(o1,"print", func{seex
o1.print()
o2.print()
o3.print()
Classpoint
x y z
Output:
10
20
30
100
200
300
50
150
250
33.25. addmethod() Function 229

Ring Documentation, Release 1.14
33.26
We can get the object attribute value using the getattribute() function
Syntax:
GetAttribute(oObject,cAttributeName)-->
Example:
o1 newpoint
seegetattribute(o1,"name")
getattribute(o1,"x")
getattribute(o1,"y")
getattribute(o1,"z")
ClassPoint
x=10=20=30
name3D-Point"
Output:
3D-Point
10
20
30
Example:
We can Find a Class List Member using GetAttribute() using a function ndclass() The Find uses the member name,
rather than the column number
myList
[newCompany {position=3="Mahmoud"="MHD"},
newCompany {position=2="Bert"="BRT"},
newCompany {position=1="Ring"="RNG"}
]
seemyList
seenl"====================="
fori tolen(myList)
see"Pos:+"+[i].position"+[i].name
"+[i].symbol"+
next
Seefindclass(myList,MHD",symbol")nl ### Specify Member class name
###---------------------------------------
funcfindclass classList, cValue, classMember
SeenlFindClass:"+
fori tolen(classList)
result[i], classMember )
(continues on next page)
33.26. getattribute() function 230

Ring Documentation, Release 1.14
(continued from previous page)
See"Result-Attr:"+nl
ifresult
j
ok
next
returnj
###--------------------------------------
classcompany position name symbol
Output:
Pos:
Pos:
Pos:
FindClass: MHD
Result-Attr:
Result-Attr:
Result-Attr:
1
33.27
We can set the object attribute value using the setattribute() function
Syntax:
SetAttribute(oObject,cAttributeName,Value)
Example:
o1 newperson
setattribute(o1,"cName","Mahmoud")
setattribute(o1,"nSalary",1000000)
setattribute(o1,"aColors",["white","blue","yellow"])
seeo1
seeo1.aColors
ClassPerson
cName
nSalary
aColors
Output:
cname: Mahmoud
nsalary:.000000
acolors:List...
(continues on next page)
33.27. setattribute() function 231

Ring Documentation, Release 1.14
(continued from previous page)
white
blue
yellow
33.28
We can share methods between classes without inheritance using the MergeMethods() function
This function merge class methods to another class.
Syntax:
MergeMethods(cClassNameDestination,cClassNameSource)
Example:
mergemethods("count","share")
mergemethods("count2","share")
o1 newcount { test() }
o1 newcount2 { test() }
ClassShare
funcone
see"one"
functwo
see"two"
functhree
see"three"
ClassDisplay
Funcprintline
seecopy(" *",20)
ClassCountfromDisplay
Functest
printline()
one()
two()
three()
printline()
ClassCount2fromDisplay
Functest
three()
two()
one()
printline()
Output:
********************
one
two
three
(continues on next page)
33.28. mergemethods() Function 232

Ring Documentation, Release 1.14
(continued from previous page)
********************
three
two
one
********************
33.29
We can know the package name of the latest sucessful import command using the packagename() function
Syntax:
packagename()-> import
Example:
load"weblib.ring"
importSystem.web
seepackagename() # system.web
33.29. packagename() Function 233

CHAPTER
THIRTYFOUR
DECLARATIVE PROGRAMMING USING NESTED STRUCTURES
In this chapter we are going to learn how to build declarative programming world using nested structures on the top of
object oriented.
We will learn about
•
•
•
•
34.1
We can create objects inside lists during list denition. Also we can add objects to the list at any time using the Add()
function or the + operator.
Example:
alist newpoint,newpoint,newpoint] # create list contains three objects
alist1,2,3] # add another item to the list
see"Item 4 is a list contains 3 items"
seealist[4]
add(alist ,newpoint)
alist newpoint
alist[5]
alist[6]
see"Object inside item 5"
seealist[5]
see"Object inside item 6"
seealist[6]
classpoint x y z
Output:
234

Ring Documentation, Release 1.14
Item listcontains
1
2
3
Object inside item
x:.000000
y:.000000
z:.000000
Object inside item
x:.000000
y:.000000
z:.000000
34.2
When we use composition and have object as one of the class attributes, when we return that object it will be returned
by reference.
if the caller used the assignment operator, another copy of the object will be created.
The caller can avoid using the assignment operator and use the returned reference directly to access the object.
The same is done also if the attribute is a list (not object).
Note:Objects and Lists are treated using the same rules. When you pass them to function they are passed by
reference, when you return them from functions they are returned by value except if it's an object attribute where a
return by reference will be done.
Example:
o1 newContainer
myobj # the assignment will create another copy
myobj.x
myobj.y
myobj.z
seeo1.aobjs[1] # print the object inside the container
seemyobj # print the copy
ClassContainer
aObjs]
funcaddobj
aobjs newpoint
returnaobjs[len(aobjs)] # return object by reference
Classpoint
x
y
z
Output:
x:.000000
y:.000000
z:.000000
(continues on next page)
34.2. Composition and Returning Objects and Lists by Reference 235

Ring Documentation, Release 1.14
(continued from previous page)
x:.000000
y:.000000
z:.000000
Example(2):
funcmain
o1 newscreen {
content[point()]
x
y
z
}
content[point()]
x
y
z
}
}
seeo1.content[1]
seeo1.content[2]
ClassScreen
content]
funcpoint
content newpoint
returnlen(content)
Classpoint
x
y
z
Output:
x:.000000
y:.000000
z:.000000
x:.000000
y:.000000
z:.000000
Example(3):
funcmain
o1 NewScreen {
point() { # access the object using reference
x
y
z
}
point() { # access the object using reference
x
y
z
}
}
(continues on next page)
34.2. Composition and Returning Objects and Lists by Reference 236

Ring Documentation, Release 1.14
(continued from previous page)
seeo1.content[1]
seeo1.content[2]
ClassScreen
content]
funcpoint
content newpoint
returncontent[len(content)] # return the object by reference
Classpoint x=10=20=30
Output:
x:.000000
y:.000000
z:.000000
x:.000000
y:.000000
z:.000000
34.3
We can access an object using { } to use object attributes and methods.
if the object contains a method called BraceEnd(), it will be executed before the end of the object access.
Example:
NewPoint {See"How are you?"
ClassPoint x y z
funcbraceend
see"Im fine, Thank you!"
Output:
How are you?
Imine,hankou!
34.4
The next features enable us to build and use declartive programming environment using nested structures on the top
of object oriented
•
•
•
•
Example:
34.3. Executing code after the end of object access 237

Ring Documentation, Release 1.14
# Declartive Programming (Nested Structures)
Screen()
{
point()
{
x
y
z
}
point()
{
x
y
z
}
}
# Functions and Classes
Funcscreenreturn screen
ClassScreen
content]
funcpoint
content newpoint
returncontent[len(content)]
funcbraceend
see"I have"
Classpoint
x=10=20=30
funcbraceend
seeself
Output:
x:.000000
y:.000000
z:.000000
x:.000000
y:.000000
z:.000000
I have!
34.4. Declarative Programming on the top of Object-Oriented 238

Ring Documentation, Release 1.14
34.5
We can get better results and a more beautiful code when we can avoid writing () after the method name when
the methods doesn't take parameters. This feature is not provided directly by the Ring language because there is a
difference between object methods and object attributes. We can get a similar effect on the syntax of the code when
we dene a getter method for the object attribute. For example instead of dening the point() method. we will dene
the point attribute then the getpoint() method that will be executed once you try to get the value of the point attribute.
since we write the variable name direcly without () we can write point instead of point() and the method getpoint()
will create the object and return the object reference for us.
Example:
newContainer
{
Point
{
x=10
y=20
z=30
}
}
ClassContainer
aObjs]
point
funcgetpoint
aObjs newPoint
returnaObjs[len(aObjs)]
ClassPoint x y z
funcbraceend
see"3D Point"
Output
3D Point
10
20
30
34.5. More beautiful Code 239

CHAPTER
THIRTYFIVE
NATURAL LANGUAGE PROGRAMMING
Using the Ring programming language, we can create Natural programming languages based on classes and objects.
35.1
In 2010, I developed a new programming language called Supernova (developed using PWCT). This language uses
a code that looks similar to Natural Language statements to create simple GUI applications. Now after ve years, In
the Ring programming language, we can get similar results, but now we have the ability to create/use code similar to
Natural language statements in any domain that we like or need.
The Ring programming language comes with the Supernova spirit, but with more generalization and with mix of other
languages spirits.
35.2
The next example presents how to create a class that dene two instructions
The rst instruction is : I want window
The second instruction is : Window title = <expr>
Also keywords that can be ignored like the `the' keyword
NewApp
{
I want window
The window titlehello world"
}
ClassApp
# Attributes for the instruction I want window
i want window
nIwantwindow
# Attributes for the instruction Window title
# Here we dont define the window attribute again
title
nWindowTitle
# Keywords to ignore, just give them any value
the=0
funcgeti
(continues on next page)
240

Ring Documentation, Release 1.14
(continued from previous page)
ifnIwantwindow
nIwantwindow++
ok
funcgetwant
ifnIwantwindow
nIwantwindow++
ok
funcgetwindow
ifnIwantwindow
nIwantwindow=
see"Instruction : I want window"
ok
ifnWindowTitle
nWindowTitle++
ok
funcsettitle cValue
ifnWindowTitle
nWindowTitle=0
see"Instruction : Window Title =
ok
Output:
Instruction : I want window
Instruction : Window Title
35.3
What if we want to connect between the two instructions using `and'
We have a problem because in Ring `and' is a keyword
We can change that using the ChangeRingKeyword command.
Syntax:
ChangeRingKeyword <oldkeyword>newkeyword>
Note:remember to restore the keyword again
Tip:The ChangeRingKeyword command is executed in the scanner stage by the compiler (before parsing).
Example:
ChangeRingKeyword and _and
New App
{
(continues on next page)
35.3. Change the Ring Keyword `And' 241

Ring Documentation, Release 1.14
(continued from previous page)
I want window and the window title = "hello world"
}
Class App
# Attributes for the instruction I want window
i want window
nIwantwindow = 0
# Attributes for the instruction Window title
# Here we dont define the window attribute again
title
nWindowTitle = 0
# Keywords to ignore, just give them any value
the=0 and=0
ChangeRingKeyword _and and
func geti
if nIwantwindow = 0
nIwantwindow++
ok
func getwant
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func settitle cValue
if nWindowTitle = 1
nWindowTitle=0
see "Instruction : Window Title = " + cValue + nl
ok
func getand
see "Using : and" + nl
Output:
Instruction : I want window
Using :and
Instruction : Window Title
35.3. Change the Ring Keyword `And' 242

Ring Documentation, Release 1.14
35.4
What if we want to dene a new behavior for any operator like the “+” operator.
We can do this change using the ChangeRingOperator command to hide operator (change it's name)
Then we can use the operator as identier that we can handle it's behaviour
Syntax:
ChangeRingOperator <oldoperator>newoperator>
Note:remember to restore the operator again
Tip:The ChangeRingOperator command is executed in the scanner stage by the compiler (before parsing).
Example:
ChangeRingOperator + _+
New App {
+
}
Class App
+
func get+
see "Plus operator"
ChangeRingOperator _+ +
Output:
Plus operator
35.5
Example:
ChangeRingKeyword and _and
ChangeRingOperator = is
New App
{
I want window and the window title is "hello world"
}
ChangeRingOperator is =
Class App
# Attributes for the instruction I want window
(continues on next page)
35.4. Change the Ring Operator `+' 243

Ring Documentation, Release 1.14
(continued from previous page)
i want window
nIwantwindow = 0
# Attributes for the instruction Window title
# Here we dont define the window attribute again
title
nWindowTitle = 0
# Keywords to ignore, just give them any value
the=0 and=0
ChangeRingKeyword _and and
func geti
if nIwantwindow = 0
nIwantwindow++
ok
func getwant
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func settitle cValue
if nWindowTitle = 1
nWindowTitle=0
see "Instruction : Window Title = " + cValue + nl
ok
35.6
Example:
func Main
cProgram = I want window and the window title is "hello world"
MyLanguage(cProgram)
Func MyLanguage cCode
# We add to the code the instructions that change keywords and operators
# Because Eval() uses a new Compiler Object (the original keywords and operatos).
cCode =
ChangeRingKeyword and _and
ChangeRingOperator = is
(continues on next page)
35.6. Using Eval() with our Natural Code 244

Ring Documentation, Release 1.14
(continued from previous page)
+ cCode
New App
{
eval(cCode)
}
Class App
# Attributes for the instruction I want window
i want window
nIwantwindow = 0
# Attributes for the instruction Window title
# Here we dont define the window attribute again
title
nWindowTitle = 0
# Keywords to ignore, just give them any value
the=0
ChangeRingKeyword and _and
and=0
ChangeRingKeyword _and and
func geti
if nIwantwindow = 0
nIwantwindow++
ok
func getwant
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func settitle cValue
if nWindowTitle = 1
nWindowTitle=0
see "Instruction : Window Title = " + cValue + nl
ok
35.6. Using Eval() with our Natural Code 245

Ring Documentation, Release 1.14
35.7
We can write code that will be executed before/after using { }
Example:
o1 newtest {
see"Hello"
}
o1 {}
classtest
funcbracestart
see"start"
funcbraceend
see"end"
Output:
start
Hello
end
start
end
35.8
The next example demonstrates how to use the “BraceExprEval” method to get expressions in Natural code.
Example:
newnatural {
create
}
classnatural
create=0
lkeyword false
funcbraceexpreval r
iflkeyword lkeyword= false
see"expr eval"
see"type: seenl
see"value : seerseenl
funcgetcreate
lkeyword true
see"create"
Output:
create
expr eval
type: NUMBER
value :
35.7. BraceStart and BraceEnd Methods 246

Ring Documentation, Release 1.14
35.9
The next example is a more advanced example
# Natural Code
newprogram {
Accept
}
# Natural Code Implementation
classprogram
# Keywords
Accept=0=0=0=0=0=0
# Execution
funcbraceexpreval x
value
funcgetnumbers
forx=1tovalue
see"Enter Number ("+x+") :" givenNumber
aNumbers
next
funcgetsum
nSUm
forxinaNumbers nSum+= next
see"The Sum :
private
value=0=[]
Output:
Enter Number (1) :3
Enter Number (2) :4
The Sum :
35.10
The next examples demonstrates how to use the “BraceError” method to handle errors when accessing the object using
braces {}.
Example:
funcmain
o1 newpoint {
x=10=20=30
TEST
SEEtest
}
classpoint x y z
funcbraceerror
see"Handle Error!"
SEE"Message :"
if( left(cCatchError,11)Error (R24)" and isattribute(self,
˓→"test")
(continues on next page)
35.9. Real Natural Code 247

Ring Documentation, Release 1.14
(continued from previous page)
see"add attribute"
addattribute(self,"test")
test
ok
see"done"
return
Output:
Handle Error!
Message :Error (R24) : Using uninitialized variable : test
add attribute
done
10
Example:
newpoint {
x=10=20=30
test()
see"mmm..."
}
classpoint x y z
funcbraceerror
see"Handle Error!"
see"Message :"
seeself
see"Done"
Output:
Handle Error!
Message :Error (R3) : Calling Function without definition: test
x:.000000
y:.000000
z:.000000
Done
mmm...
35.11
Instead of typing the literal as “literal” we can accept the words directly.
Example:
The next example accept hello world instead of “hello world”
But this example uses braceend() to check the end of the instruction
This means that this class process only one natural statement that end with literal.
ChangeRingKeyword and _and
New App
(continues on next page)
35.11. Clean Natural Code 248

Ring Documentation, Release 1.14
(continued from previous page)
{
I want window and the window title is hello world
}
Class App
# Attributes for the instruction I want window
i want window
nIwantwindow = 0
# Attributes for the instruction Window title
# Here we dont define the window attribute again
title is
nWindowTitle = 0
# Keywords to ignore, just give them any value
the=0 and=0
# Data
literal = ""
ChangeRingKeyword _and and
func geti
if nIwantwindow = 0
nIwantwindow++
ok
func getwant
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func gettitle
if nWindowTitle = 1
nWindowTitle=2
ok
func getis
if nWindowTitle = 2
nWindowTitle=3
ok
func braceend
if nWindowTitle = 3
see "Instruction : Window Title = " + literal + nl
nWindowTitle = 0
ok
func braceerror
c= substr(cCatchError,":")
(continues on next page)
35.11. Clean Natural Code 249

Ring Documentation, Release 1.14
(continued from previous page)
while c > 0
c= substr(cCatchError,":")
cCatchError=substr(cCatchError,c+1)
end
literal += substr(cCatchError,1)
35.11. Clean Natural Code 250

CHAPTER
THIRTYSIX
USING THE NATURAL LIBRARY
In this chapter we will learn how to use the Natural Library to quickly dene a language that contains a group of
commands.
To start using the library, We need to call naturallib.ring
load"naturallib.ring"
After loading the library, We can use the NaturalLanguage class that contains the next methods :-
•
•
•
•
•
•
•
36.1
We will write the natural code in a Text le, for example program.txt
File: program.txt
Welcome to the Ring programming language!
What you are reading now is not comments, I swear!
After many years of programming I decided to think different about
programming and solve the problems in a better way.
We are writing commands or code and the Ring language is reading
it to understand us! Sure, What you are seeing now is
just***part of the code - Not the Complete Program ***
You have to write little things before and after this
part to be able to run it!
It is the natural part of our code where we can write in English,
Arabic or any Natural Language Then we will tell the computer
through the Ring language what must happens! in a way that we can scale
for large frameworks and programs.
(continues on next page)
251

Ring Documentation, Release 1.14
(continued from previous page)
Just imagine what will happens to the world of programming once
we create many powerful frameworks using the Ring language that
uses this way (Natural Programming).
For example When we say Hello to the Machine, It can reply! and when we
say count from 1 to 5 it will understand us, Also if
we said count from 5 to 1 it will
understand us too! You can see the Output window!
This Goal is not new, but the Ring language comes
with an innovative solution to this problem.
Output:
Hello, Sir!
The Numbers!
1
2
3
4
5
I will count Again!
5
4
3
2
1
To execute the natural code, We have start.ring
In start.ring we dene the language and the commands.
File: start.ring
load"stdlib.ring"
load"naturallib.ring"
NewNaturalLanguage {
SetLanguageName(:MyLanguage)
SetCommandsPath(CurrentDir()+"/../command")
SetPackageName("MyLanguage.Natural")
UseCommand(:Hello)
UseCommand(:Count)
(continues on next page)
36.1. Natural Library - Demo Program 252

Ring Documentation, Release 1.14
(continued from previous page)
RunFile("program.txt")
}
We dened a language called MyLanguage, We have folder for the language commands.
Each command will dene a class that belong to the MyLanguage.Natural package.
We will dene two commands, Hello and Count.
So we must have two les for dening the commands in the CurrentDir()+”/../command” folder
File: hello.ring
DefineNaturalCommand.SyntaxIsKeyword([
:PackageMyLanguage.Natural",
:Keyword
:Function func{
See"Hello, Sir!"
}
])
File: count.ring
DefineNaturalCommand.SyntaxIsKeywordNumberNumber([
:PackageMyLanguage.Natural",
:Keyword
:Function func{
if isattribute(self,:count_times) {
AddAttribute(self,:count_times)
Count_Times
}
ifExpr(1)2) {
nStep1
else
nStep
}
ifCount_Times
seenl+"The Numbers!"
Count_Times++
else
seenlI will count Again!"nl
}
forx1) toExpr(2) stepnStep {
seenl+x+nl
}
CommandReturn(fabs(Expr(1)-Expr(2))+1)
}
])
36.1. Natural Library - Demo Program 253

Ring Documentation, Release 1.14
36.2
To dene new command we can use the DeneNaturalCommand object
This object provides the next methods :-
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
File: mylanguage.ring
load"stdlib.ring"
load"naturallib.ring"
MyLanguage NewNaturalLanguage {
SetLanguageName(:MyLanguage)
setCommandsPath(CurrentDir()+"/../command")
SetPackageName("MyLanguage.Natural")
UseCommand(:Hello)
UseCommand(:Count)
UseCommand(:Print)
UseCommand(:IWantWindow)
UseCommand(:WindowTitleIs)
UseCommand(:IWantButton)
}
Example (1)
In the next example we will dene the Print command.
36.2. Dening Commands 254

Ring Documentation, Release 1.14
We will use the SyntaxIsKeywordExpression() Method.
We pass list (as Hash) to the method. We determine the package name, the keyword and the function that will be
executed.
Inside this function we uses the Expr(nExprNumber) function to get the expression value that the user will write after
the keyword.
File: print.ring
DefineNaturalCommand.SyntaxIsKeywordExpression([
:PackageMyLanguage.Natural",
:Keyword
:Function func{
SeeExpr(1)
}
])
Usage:
load"mylanguage.ring"
MyLanguage.RunString(
printHello, World!"
)
Output:
Hello, World!
Example (2)
File: iwantwindow.ring
DefineNaturalCommand.SyntaxIsCommand([
:PackageMyLanguage.Natural",
:Commandi want window",
:Function func{
See"Command: I want window"
}
])
Usage:
load"mylanguage.ring"
MyLanguage.RunString(
i want window
)
Output:
Command: I want window
Example (3)
File: windowtitleis.ring
36.2. Dening Commands 255

Ring Documentation, Release 1.14
DefineNaturalCommand.SyntaxIsCommandString([
:PackageMyLanguage.Natural",
:Commandwindow title is",
:Function func{
See"Command: Window title is1)
}
])
Usage:
load"mylanguage.ring"
MyLanguage.RunString(
I want windowandthe window title isHello World"
)
Output:
Command: I want window
Command: Window title is Hello World
36.3
In the next example we uses the Count command without using operators
load"mylanguage.ring"
MyLanguage.RunString("
Hello
Count
Count
")
We can add more description
load"mylanguage.ring"
MyLanguage.RunString("
Hello, Please Count from1to5 from5to1
")
Also we can use operators like “(” and “)” around the instruction
load"mylanguage.ring"
MyLanguage {
SetOperators("()")
RunString("
Here we will play andwilltrysomething
that looks like Lisp Syntax
(count (count) (count))
Justforfun!
")
}
36.3. Natural Library - Operators 256

Ring Documentation, Release 1.14
36.4
This section is related to the implementation details.
When we dene new command, Each command is dened by the Natural Library as a class.
We have the choice to dene commands using the simple interface provided by the DeneNaturalCommand object or
by dening new class as in the next examples.
If we used DeneNaturalCommand (More Simple), The class will be dened during the runtime.
File: hello.ring
Package MyLanguage.Natural
classHello
funcAddAttributes_Hello
AddAttribute(self,:hello)
funcGetHello
See"Hello, Sir!"
File: count.ring
Package MyLanguage.Natural
classCount
funcGetcount
StartCommand()
CommandData()[:name]
CommandData()[:nExpr]
CommandData()[:aExpr]]
funcBraceExprEval_Count nValue
ifisCommand()andCommandData()[:name]
ifisNumber(nValue) {
CommandData()[:nExpr]++
CommandData()[:aExpr]
ifCommandData()[:nExpr]
Count_Execute()
}
}
}
funcAddAttributes_Count
AddAttribute(self,:count)
funcCount_Execute
if isattribute(self,:count_times) {
AddAttribute(self,:count_times)
Count_Times
}
ifExpr(1)2) {
nStep1
else
nStep
(continues on next page)
36.4. Dening commands using classes 257

Ring Documentation, Release 1.14
(continued from previous page)
}
ifCount_Times
seenl+"The Numbers!"
Count_Times++
else
seenlI will count Again!"nl
}
forx1) toExpr(2) stepnStep {
seenl+x+nl
}
CommandReturn(fabs(Expr(1)-Expr(2))+1)
36.4. Dening commands using classes 258

CHAPTER
THIRTYSEVEN
SCOPE RULES FOR VARIABLES AND ATTRIBUTES
In this chapter we will learn about scope rules and how Ring nd variables.
Also we will learn about conicts and how to solve/avoid them.
The next information are important once you start developing large applications using Ring
These application may uses
•
•
•
•
•
37.1
In Ring we have three scopes :-
(1)
(2)
(3)
37.2
(1)
(2)
but you still can access the global scope and the local scope.
(3)
still can access the global scope.
In this region (class region - after the class name and before methods) we have
•
•
•
259

Ring Documentation, Release 1.14
Note:Since the local scope in the class region point also to the object scope in this region, we can use nested braces
and still have access to the object scope of the class through the local scope.
Tip:You can create windows and controls as attibutes by dening them in this region.
Tip:In the class region if you created objects and used braces {} to access them then using self.attribute inside braces
will use the class (not the object that you access) because you have access to the class through the local scope.
(4)
37.3
1 - Search First in the Local Scope
if not found !
2 - Search in the Object Scope
if not found !
3 - Search in the public scope
if not found —-> Runtime Error
if found —-> Check if we can do optimization to avoid searching next time (Cache / Pointers for performance).
37.4
When we use object.attribute the search will be in the object attributes only.
I.e. no search will be done in the local scope or in the global scope for the object attribute.
Note:Using self.attribute will search for the rst self before searching for attributes.
37.5
The self object is a reference to the current object that we can use from the class methods.
When we are inside class method and use Self we mean the object that will be created from this class.
Inside the class methods if we used Braces { } this will change the current object scope and self will be changed also
inside braces to reference the object that we access using Braces.
Inside the Class Region (after the class name and before any method) we have access to the object through the object
scope and the local scope also. In this region using Self will always be a reference to the class object. if we used
Braces to change the object scope then used Self inside Braces, Also self will be a reference to the class object (not
the object that we already access using braces) because in the class region we have :-
37.3. How Ring nd the variable? 260

Ring Documentation, Release 1.14
•
•
•
And using Braces changes the object scope only (not the local scope) and when Ring search for variables it will search
in the Local Scope rst so it will nd self in the class that we are inside.
37.6
Ring will use the variable name in the Assignment operation
1 - Search using the variable name
2 - If not found —> Avoid the runtime error and dene the variable in the current scope
3 - If found —> Use the variable and don't dene anything in the current scope
•
•
•
37.7
Look at this example:
nametest"
o1 newperson
seeo1
classperson
name
address
phone
In the previous example we have a global variable called `name' inside the class person.
when we use the variable `name', Ring will start the search operation and will try to nd it.
if found —> Use it
if not found —> Dene new attribute
But the variable name is a global variable, so it will be found and used!
We will not have the attribute name! added to the object.
Solution (1) - Use the Main Function
funcmain
nametest"
o1 newperson
seeo1
classperson
name
(continues on next page)
37.6. How Ring Dene Variables and Attributes 261

Ring Documentation, Release 1.14
(continued from previous page)
address
phone
Solution (2) - Use special mark for global variable names like $
$nametest"
o1 newperson
seeo1
classperson
name
address
phone
Solution (3) - Use the AddAttribute() Method
nametest"
o1 newperson
seeo1
classperson
AddAttribute(self,"name")
address
phone
Solution (4) - Use self before the attribute name
nametest"
o1 newperson
seeo1
classperson
self.name
address
phone
So what is the best solution to this conict?
1 - Use the $ Mark for global variables
2 - Optional : Try to avoid global variables and use the Main function
In practice i do both of them.
The other solution
•
37.7. Conict between Global Variables and Class Attributes 262

Ring Documentation, Release 1.14
37.8
This conict may happen when we access the object using braces
Example:
funcmain
namenice"
o1 newperson {name="mahmoud"="Egypt"
seeo1
classperson
name
address
phone
In the previous example we have the local variable name.
The value of this variable will be set to “mahmoud” instead of the object attribute.
Solution (1) : Just use Self
funcmain
namenice"
o1 newperson {self.name="mahmoud"="Egypt"
seeo1
classperson
name
address
phone
Solution (2) : Change the Local variable name
funcmain
cNamenice"
o1 newperson {name="mahmoud"="Egypt"
seeo1
classperson
name
address
phone
Solution (3) : Change Braces and use the Dot operator
funcmain
namenice"
o1 newperson
o1.name"mahmoud"
o1.address"Egypt"
o1.phone
seeo1
classperson
name
address
phone
37.8. Conict between Class Attributes and Local Variables 263

Ring Documentation, Release 1.14
37.9
Remember that we have Three scopes (Local Scope, Object Scope and Global Scope) and when we are inside a class
method, we expect that we have access to the object attributes and methods and this is true until we use braces to
access another object attributes and methods because in this case our object scope will be switched to another object.
newpoint { test() }
classpoint
x=10=20
functest
seex # works fine
myobj newotherclass {
seename
seex # error !
}
classotherclass
nametest"
Output:
10
20
test
Line 8 Error (R24) : Using uninitialized variable : x
In method test() in file methodbraceerror.ring
called from line 5 in file methodbraceerror.ring
Now what we will do to solve the previous problem?
Solution (1) : Write the code that access the class attributes outside braces.
newpoint { test() }
classpoint
x=10=20
functest
seex # works fine
myobj newotherclass {
seename
}
seex # Outside braces - works fine
classotherclass
nametest"
Output:
10
20
test
10
20
Solution (2) : Don't Use Braces
37.9. Using Braces to access objects inside Class Methods 264

Ring Documentation, Release 1.14
newpoint { test() }
classpoint
x=10=20
functest
seex
myobj newotherclass
seemyobj.name
seex
classotherclass
nametest"
Solution (3) : Copy the self object
We may use this solution if we want to use braces and get access to the class attributes (Just Reading).
newpoint { test() }
classpoint
x=10=20
functest
oSelf
seex
myobj newotherclass {
seename
seeoself.x
}
classotherclass
nametest"
Output:
10
20
test
10
20
Now look at this line
oself
The problem with the previous line is that we will have a new copy from the object Because in Ring the assignment
operator copy lists and objects by value (not by reference).
When we access the new object attributes (reading) we don't have problems
But if we modied the object attributes (Then we will modify the copy!).
Note:We can use braces again with the copy
newpoint { test() }
classpoint
(continues on next page)
37.9. Using Braces to access objects inside Class Methods 265

Ring Documentation, Release 1.14
(continued from previous page)
x=10=20
functest
oSelf
seex
myobj newotherclass {
seename
oSelf {
seex
}
}
classotherclass
nametest"
In a GUI application, we may create a class contains the window objects as attributes to be able to access the controls
from different methods. Remember the previous information when you try to access objects using braces inside
methods because in this case you can't access the object attributes directly and if you copied the self object you will
work on a copy and the new controls that you create will be related to the copy and you can't access them.
37.10
ods
We access the class attributes directly from the class methods, also we have the choice to use the Self reference before
the attribute/method name. Using Braces {} inside class method change the active object scope and prevent us from
getting direct access to the class attributes. Also using Self will not help because the Self reference will be changed to
the object that we access using Braces.
In this case if you want to read an attribute you have to copy the Self object before using Braces and if you want to
modify an attribute you have to the copy from local variable to the object attribute after using Braces.
This case happens when you want to read/modify attribute insead braces.
ClassMyApp
oCon # Attribute
# some code here
FuncOpenDatabase
# some code here
newQSqlDatabase() {
oCon"QSQLITE") {
setDatabaseName("weighthistory.db")
open()
}
}
self.oCon
# some code here
In the previous example we want to create the connection object and save it inside the oCon attribute.
The object is an output from the addDatabase() method that we use after accessing the QSQLDatabase() object.
Inside braces we can't use the Self reference to use the object created from the MyApp class, Because the Self reference
here will be to the object that we access using Braces.
37.10. Accessing the class attributes from braces inside class methods 266

Ring Documentation, Release 1.14
We solved the problem in the previous example by creating a local variable called oCon then after Braces we copied
that variable to the oCon attribute.
The next code is another solution.
ClassMyApp
oCon # Attribute
# some code here
FuncOpenDatabase
# some code here
oCon newQSqlDatabase()
oCon"QSQLITE") {
setDatabaseName("weighthistory.db")
Open()
}
# some code here
The next code is a better solution.
ClassMyApp
oCon # Attribute
# some code here
FuncOpenDatabase
# some code here
newQSqlDatabase() {
this.oCon"QSQLITE") {
setDatabaseName("weighthistory.db")
Open()
}
}
# some code here
Note:We used this.attribute to access the class attribute (oCon) while we are inside Braces.
37.11
A good way for creating classes for windows is to dene the window directly after the class name
In this area you can use nested braces without problems to dene the window and the controls, and they will be
attributes that you can access from methods.
Example:
Load"guilib.ring"
newqApp
{
$ObjectNameoFirstWindow"
(continues on next page)
37.11. Creating a Class for each Window in GUI applications 267

Ring Documentation, Release 1.14
(continued from previous page)
oFirstWindow newFirstWindow
$ObjectNameoSecondWindow"
oSecondWindow newSecondWindow
exec()
}
ClassFirstWindow
win newqWidget() {
setgeometry(0,50,300,200)
setWindowTitle("First Window")
label1 newqLabel(win)
{
setgeometry(10,10,300,30)
setText("0")
}
btn1 newqPushButton(win)
{
move(100,100)
setText("Increment")
setClickEvent($ObjectName+".increment()")
}
show()
}
FuncIncrement
label1 {
setText("
}
ClassSecondWindow
win newqWidget() {
setgeometry(400,50,300,200)
setWindowTitle("Second Window")
label1 newqLabel(win)
{
setgeometry(10,10,300,30)
setText("0")
}
btn1 newqPushButton(win)
{
move(100,100)
setText("Decrement")
setClickEvent($ObjectName+".decrement()")
}
show()
}
FuncDecrement
label1 {
setText("
}
37.11. Creating a Class for each Window in GUI applications 268

Ring Documentation, Release 1.14
37.12
In the class region (after the class name and before any methods) we dene the attributes.
In this region we have access to the global scope and the local scope will point to the object scope.
Three Scopes
•
•
•
Look at this example
NewAccount {
seeaFriends
}
ClassAccount
nameMahmoud"
aFriends]
aFriends newFriend {
nameGal"
}
aFriends newFriend {
nameBert"
}
ClassFriend
name
Output:
name: NULL
name: NULL
The problem in the previous example is that the Class account contains an attribute called “name” and the Friend class
contains an attribue called “name” also.
If you tried using self.name inside braces you will get the same result!
NewAccount {
seeaFriends
}
ClassAccount
nameMahmoud"
aFriends]
aFriends newFriend {
self.nameGal"
}
aFriends newFriend {
self.nameBert"
}
ClassFriend
name
37.12. Conict between self inside braces and self in the class region 269

Ring Documentation, Release 1.14
So why using self.name inside braces doesn't solve this conict?
Because after the class region we have
•
•
•
When we use braces we change the object scope, so we have
•
•
•
Ring search in the local scope rst, so using self.name will use the Account class.
There are many solution
Solution (1) : Access the object through the list
NewAccount {
seeaFriends
}
ClassAccount
nameMahmoud"
aFriends]
aFriends newFriend
aFriends[len(aFriends)]
aFriends[len(aFriends)].nameGal"
}
aFriends newFriend
aFriends[len(aFriends)]
aFriends[len(aFriends)].nameBert"
}
ClassFriend
name
Solution (2) : Create Method in the friend class to set the name attribute.
NewAccount {
seeaFriends
}
ClassAccount
nameMahmoud"
aFriends]
aFriends newFriend {
setname("Gal")
}
aFriends newFriend {
setname("Bert")
}
ClassFriend
name
(continues on next page)
37.12. Conict between self inside braces and self in the class region 270

Ring Documentation, Release 1.14
(continued from previous page)
funcsetname cName
name
Solution (3) : Create a method in the account class to set the attribute
NewAccount {
seeaFriends
}
ClassAccount
nameMahmoud"
aFriends]
friend("Gal")
friend("Bert")
funcfriend cName
aFriends newFriend {
name
}
ClassFriend
name
Solution (4) : Declarative Programming
NewAccount {
namemahmoud"
friend {
nameGal"
}
friend {
nameBert"
}
seeaFriends
}
ClassAccount
name
aFriends]
friend
funcgetfriend
aFriends newFriend
returnaFriends[len(aFriends)]
ClassFriend
name
Output:
name: Gal
name: Bert
37.12. Conict between self inside braces and self in the class region 271

Ring Documentation, Release 1.14
37.13
Since braces change the current object scope to another object. we can use it to do some work without modifying the
class attributes and using the same variable names.
newpoint {x=10=20=30
classpoint x y z
funcstart
seeself# print the x y z values (10,20,30)
newLocal {
x
y
z
}
seeself# print the x y z values (10,20,30)
seex # will print 100
seey # will print 200
seez # will print 300
Self {# NO Advantage - Search is done in local scope first
seex # will print 100
seey # will print 200
seez # will print 300
}
seeself.x # will print 10
seeself.y # will print 20
seeself.z # will print 30
classLocal
Output:
x: 10.000000
y: 20.000000
z: 30.000000
x: 10.000000
y: 20.000000
z: 30.000000
100
200
300
100
200
300
10
20
30
37.13. Using braces to escape from the current object scope 272

Ring Documentation, Release 1.14
37.14
&#3627408454;&#3627408481;&#3627408462;&#3627408479;&#3627408481;&#3627408470;&#3627408475;&#3627408468; &#3627408467;&#3627408479;&#3627408476;&#3627408474; &#3627408453;&#3627408470;&#3627408475;&#3627408468; 1◁8˓ &#3627408484;&#3627408469;&#3627408466;&#3627408475; &#3627408481;&#3627408469;&#3627408466; &#3627408441;&#3627408476;&#3627408479; &#3627408447;&#3627408476;&#3627408476;&#3627408477; &#3627408465;&#3627408466;??????&#3627408475;&#3627408466;&#3627408480; &#3627408475;&#3627408466;&#3627408484; &#3627408470;&#3627408465;&#3627408466;&#3627408475;&#3627408481;&#3627408470;??????&#3627408466;&#3627408479; ↼&#3627408483;&#3627408462;&#3627408479;&#3627408470;&#3627408462;&#3627408463;&#3627408473;&#3627408466;↽ &#3627408470;&#3627408481; &#3627408484;&#3627408470;&#3627408473;&#3627408473; &#3627408465;&#3627408466;??????&#3627408475;&#3627408466; &#3627408470;&#3627408481; &#3627408470;&#3627408475; &#3627408481;&#3627408469;&#3627408466; &#3627408473;&#3627408476;&#3627408464;&#3627408462;&#3627408473; &#3627408480;&#3627408464;&#3627408476;&#3627408477;&#3627408466;◁
Example:
x
? # Print 10
test1()
? # Print 10
test2()
? # Print 10
functest1
forx to5
next
? # Print 6
functest2
list=:5
forxin
next
? # Print NULL (The "For In" loop will kill the reference after the
˓→loop)
Output:
10
6
10
NULL
10
37.15
&#3627408436;&#3627408481; ??????&#3627408479;&#3627408480;&#3627408481; &#3627408479;&#3627408466;&#3627408474;&#3627408466;&#3627408474;&#3627408463;&#3627408466;&#3627408479; &#3627408481;&#3627408469;&#3627408462;&#3627408481;
1 - Each programming language comes with it's scope rules based on the language goals
2 - Programming in the small is different than Programming in the Large
3 - Some programming language are designed for developing small programs while others are designed for large
programs
4 - In programming, If we have access to more than one scope - Then problems may come if we don't manage things
correctly
5 - It's always more secure to reduce the number of visible scopes
6 - Some programming languages force you to manage the scope in some way, while others not!
In Ring
1 - Special andvery simple&#3627408480;&#3627408464;&#3627408476;&#3627408477;&#3627408466; &#3627408479;&#3627408482;&#3627408473;&#3627408466;&#3627408480; &#3627408481;&#3627408469;&#3627408462;&#3627408481; &#3627408462;&#3627408479;&#3627408466; &#3627408465;&#3627408466;&#3627408480;&#3627408470;&#3627408468;&#3627408475;&#3627408466;&#3627408465; &#3627408467;&#3627408476;&#3627408479; &#3627408441;&#3627408473;&#3627408466;&#3627408485;&#3627408470;&#3627408463;&#3627408470;&#3627408473;&#3627408470;&#3627408481;&#3627408486; ??????&#3627408479;&#3627408480;&#3627408481; &#3627408481;&#3627408469;&#3627408466;&#3627408475; &#3627408454;&#3627408466;&#3627408464;&#3627408482;&#3627408479;&#3627408470;&#3627408481;&#3627408486;
2 - Ring is designed to support programming in the small and programming in the large.
37.14. The For Loops uses the local scope 273

Ring Documentation, Release 1.14
3 - The language provide the different programming paradigms that you may select from based on the project size.
Errors comes only if you selected a bad paradigm for the target project or you are using the paradigm in a way that is
not correct or at least not common.
4 - In Ring you have the choice, you can use global variables or avoid them. you can give them a special $ mark or
leave them. you can use object-oriented or stay with procedures. you can use the class region (after the class name
and before any method) just for attributes or use it for code too.
5 - Just read the next scope rules and think about them then use them in your favorite way.
Scope Rules:
1 - At any place in our program code we have only at maximum Three Scopes (Local Scope, Object Scope and Global
Scope).
2 - When Ring nd a variable it will search in the local scope rst then in the object scope then in the global scope.
3 - At any time inside procedures or methods you can use braces { } to access an object and change the current object
scope.
4 - In the class region (After the class name and before any method) this is a special region where both of the object
scope and the local scope point to the object scope. I.e. No local variables where each variable you dene in this
region will become an attribute.
5 - Before dening any variable (in any scope and in the class region too) a search process will be done to use the
variable if it's found.
6 - Functions and Methods parameters are dened automatically as local variables to these functions or methods.
7 - Using Object.Attribute will search in the object attributes only.
8 - Using Self.Attribute will lead to a search for Self rst then search in Self Attributes.
9 - The Self reference inside class region (after the class name and before any method) always point to the object scope
created from the class.
10- The Self reference inside methods will be changed when we uses Braces to be a reference to the object that we
access.
11- Writing variable names directly in the class region (after the class name and before any method) means using them
or dene then (in order).
12- Using self.attribute in the class region reduce search to the object scope (avoid conict with global scope).
From these rules you can understand all types of conicts and why you may have them and how to avoid them
Simple advices to avoid any conict and use the scope rules in a better way
1 - Try to avoid global variables
2 - Use the Main Function - This will help you to avoid global variables
3 - If you are going to use many global variables use the $ mark before the variable name
4 - In the class region if you don't respect the advice number three ($) then use self.attribute when you dene your
attributes
5 - You can use object.attribute and object.method() instead of object { attribute } and object { method() } if you don't
like changing the object scope.
6 - If you will use nested braces in a class - think about using the class region if possible because in this region you
will have access to the object that you access using { } + access to the class attributes
7 - If you are inside a class method and used nested braces you will change the object scope with each brace and you
will loss the access to the class attributes directly but you have access to the local scope before and after using brace
37.15. Summary of Scope Rules 274

Ring Documentation, Release 1.14
{ } , if you will read/modify the class attribute from braces then use This.Attribute because using `This' means (The
object created from this class) while using `Self' means (The object in the current object scope).
After understanding all of the previous points, You will master this topic.
37.15. Summary of Scope Rules 275

CHAPTER
THIRTYEIGHT
SCOPE RULES FOR FUNCTIONS AND METHODS
In this chapter we will learn about the scope rules for functions and methods.
You need to know the next information once you started using Ring for large applications.
These applications may contains and use
•
•
•
•
38.1
When you call a method or function, Ring will start a search process to nd this function
If found –> Call the function and store the function pointer in the cache so Ring can use it again with doing another
search.
If not found —> Runtime error message (That you can avoid using Try/Catch)
How the search process is done?
Search for functions/methods follow the next order
1 - Search in methods (if we are inside class method or object using braces {})
2 - Search in functions written by the programmer using Ring Code
3 - Search in functions written in C/C++ like standard Ring functions
This enable us to write clean code inside classes methods and avoid any conict with functions.
If we want to call a function with the same name as a method in the class we will need a wrapper function or we will
access a temp. object using { } then call that function there.
We can replace C/C++ Functions with Ring Functions.
We can replace Ring Functions with Ring Methods.
Note:Using self.method() is not necessary in any use case.
276

Ring Documentation, Release 1.14
Tip:We can use this.method() to escape from the current active scope that we access using braces {} and call a
method in the class that we are inside.
38.2
Look at the next example
funcmain
o1 newmyclass { test() test2() }
test2()
funcf1
see"f1 function"
funcf2
see"f2 function"
funcf3
see"f3 function"
functest2
myline()
see"test2 function"
newmyclass {
f1()
f2()
f3()
self.f3()
}
myobj newmyclass
myobj.f3()
myline()
funcmyline
seecopy("=",40)
Classmyclass
functest
myline()
see"test method"
f1()
f2()
f3()
myline()
funcf3
see"f3 method"
functest2
myline()
see"test2 method"
self {
f1()
(continues on next page)
38.2. Example about Sharing Names between Functions and Methods 277

Ring Documentation, Release 1.14
(continued from previous page)
f2()
f3()
}
myline()
Output:
========================================
test method
f1 function
f2 function
f3 method
========================================
========================================
test2 method
f1 function
f2 function
f3 method
========================================
========================================
test2 function
f1 function
f2 function
f3 method
f3 method
f3 method
========================================
38.3
class
In the previous example we have a function called f3() and we have a method called f3()
How we can call the f3() function from the test() method ?
Solution (1) : Change the current object scope to another object scope
In this solution we will have an empty class called local that we will use to change the current object scope.
funcmain
o1 newmyclass { test()}
funcf1
see"f1 function"
funcf2
see"f2 function"
funcf3
see"f3 function"
funcmyline
seecopy("=",40)
(continues on next page)
38.3. Calling a function sharing the name with a method in the current class 278

Ring Documentation, Release 1.14
(continued from previous page)
Classmyclass
functest
myline()
see"test method"
f1()
f2()
f3() # call f3() method
newlocal { f3() } # call f3() function
myline()
funcf3
see"f3 method"
classlocal
Output:
========================================
test method
f1 function
f2 function
f3 method
f3 function
========================================
38.3. Calling a function sharing the name with a method in the current class 279

CHAPTER
THIRTYNINE
SYNTAX FLEXIBILITY
In this chapter we will learn about some options that are provided automatically by the Ring compiler for syntax
exibility.
39.1
We can change any keyword using the ChangeRingKeyword command.
Note:Remember to restore the keyword again if the team will mix between styles in the same project.
Tip:The ChangeRingKeyword command is executed in the scanner stage by the compiler (before parsing).
Syntax:
ChangeRingKeyword <oldkeyword>newkeyword>
Example:
ChangeRingKeyword print
printwelcome"
ChangeRingKeyword printsee
see"Welcome"
Example:
ChangeRingKeyword function
ChangeRingKeyword print
ChangeRingKeyword endif
ChangeRingKeyword endfor
ChangeRingKeyword endwhile
x
whilex
printx =
fort to10
ift
(continues on next page)
280

Ring Documentation, Release 1.14
(continued from previous page)
printnumber three"
endif
endfor
x--
endwhile
test()
function test
printmessage from test"
ChangeRingKeyword functionfunc
ChangeRingKeyword printsee
ChangeRingKeyword endifok
ChangeRingKeyword endfornext
ChangeRingKeyword endwhileend
39.2
We can change any operator using the ChangeRingOperator command.
Note:Remember to restore the operator again if the team will mix between styles in the same project.
Tip:The ChangeRingOperartor command is executed in the scanner stage by the compiler (before parsing).
Syntax:
ChangeRingOperator <oldkeyword>newkeyword>
Example:
The next program hide the + operator by changing it to _+
changeringoperator + _+
changeringkeyword SEE PRINT
try
print 5 + 10
catch
print nl print "error" print nl
done
changeringoperator _+ +
The next program change the + operator to “plus”.
changeringoperator +
changeringkeyword PRINT
Print
(continues on next page)
39.2. Change Language Operators 281

Ring Documentation, Release 1.14
(continued from previous page)
changeringoperator plus
changeringkeyword PRINTSEE
39.3
You may store a group of ChangeRingKeyword and ChangeRingOperator commands in a le to use later in many
source les. You can't use the Load command to call these les because
•
(before parsing).
•
Solution: Use the LoadSyntax Command which is executed in the scanner phase.
Syntax:
LoadSyntax "syntaxfile.ring"
Example:
File : StyleBasicOn.ring
ChangeRingKeyword print
ChangeRingKeyword endif
ChangeRingKeyword endfor
ChangeRingKeyword endwhile
File : StyleBasicOff.ring
ChangeRingKeyword print see
ChangeRingKeyword endif ok
ChangeRingKeyword endfor next
ChangeRingKeyword endwhile end
File : UseStyleBasic.ring
LoadSyntax"stylebasicon.ring"
x
whilex
printx =
fort to10
ift
printnumber three"
endif
endfor
x--
endwhile
LoadSyntax"stylebasicoff.ring"
see"done"
39.3. Load Syntax Files 282

Ring Documentation, Release 1.14
Note:les called by the LoadSyntax command must contains ChangeRingKeyword and ChangeRingOperator com-
mands only.
Tip:les called by the LoadSyntax command doesn't support functions, packages and classes. just imperative
commands only.
Note:Using this feature you can create many styles that you can use in the same project and you can support Ring
translation to other languages like Arabic, French and so on.
Tip:The effect of LoadSyntax command is related to the current source code le only.
39.4
We can use () around the function parameters (optional).
Example:
hello()
sum(3,4)
funchello()
see"Hello"
funcsum(x,y)
seex+y+nl
Output:
Hello
7
Example:
myfunc funcx,y {seex
callmyfunc (3,4)
myfunc2 func(x,y) {seex+y+nl }
callmyfunc(3,4)
Output:
7
7
39.4. Using “()” around the function parameters 283

Ring Documentation, Release 1.14
39.5
In Ring we can use semi-colon after and between statements (optional).
Example:
# Using semi-colon is optional
see"Hello" see"How are you?" see"Welcome to Ring"
one() ; two() ; three() ;
funcone ;see"one"
functwo ;see"two"
functhree ;see"three"
Output:
Hello
How are you?
WelcometoRing
one
two
three
39.6
You can use any unicode character in the variable name also we can use $ and @ in the name.
This feature may help, for example we can start global variables with $ and the object attributes with @.
In other languages like Ruby this is the rule, In the Ring language this is just an option without any force from the
Compiler.
example:
$global_variable
newtest { hello() }
classtest
@instance_variable
funchello
local_variable
see"Global :global_variable
"Instance :instance_variable
"Local :
Output:
Global :
Instance :
Local :
39.5. Using Semi-colon after and between statements 284

Ring Documentation, Release 1.14
39.7
if you don't like the `but' keyword in if statement Then you can use the `elseif' keyword.
Example:
givex
ifx see"one"
elseifx=2see"two"
elseifx=3see"three"
elseifx=4see"four"
else "other"
ok
seenl
39.8
if you don't like the `other' keyword in switch statement Then you can use the `else' keyword.
Also you can replace `else' with `other' in if statement.
i.e. `other' keyword is the same as `else' keyword.
Example:
x
switchx
on10
see"10"
else
see"not 10"
end
Output:
not10
39.9
We can use the `end' keyword to close different control structures
•
•
•
•
•
Example:
39.7. Using the `elseif' keyword as `but' in if statement 285

Ring Documentation, Release 1.14
see"if statement.."
x
ifx
see"one"
elseifx=2
see"two"
elseifx=3
see"three"
end
see"for loop.."
fort to10
seet
end
seenl
see"switch..."
x
switchx
on1see"one"
on2see"two"
end
see"try catch..."
try
x
catch
see"catching error"
end
Output:
ifstatement..
one
for ..
12345678910
switch...
one
try ...
catching error
39.10
We can use braces { } to start and end different control structures
•
•
•
•
•
Example:
39.10. Using braces to start and end different control structures 286

Ring Documentation, Release 1.14
see"if statement.."
x
ifx
see"one"
elseifx=2
see"two"
elseifx=3
see"three"
}
see"for loop.."
fort to10
seet
}
seenl
see"switch..."
x
switchx {
on1see"one"
on2see"two"
}
see"try catch..."
try{
x
catch
see"catching error"
}
Output:
ifstatement..
one
for ..
12345678910
switch...
one
try ...
catching error
39.11
We can replace the `see' keyword with the `put' keyword.
Also we can replacew the `give' keyword with the `get' keyword.
Example:
put"Hello World"
put"Enter Your Name ? GetName
Put"Hello
39.11. Using `put' and `get' as `see' and `give' 287

Ring Documentation, Release 1.14
39.12
We can replace the `on' keyword with `case' keyword in the switch statement.
Example (1) :
forx=1to10
switchx
case1put"one"
case2put"two"
case3put"thre"
else "else"
end
end
Example (2) :
forx=1to10
switchx {
case1put"one"
case2put"two"
case3put"thre"
else "else"
}
}
39.13
We can use the `def' keyword as the `func' keyword to dene functions and methods.
Example:
one() two()
defoneput"one"
deftwoput"two"
39.14
Example:
load"stdlib.ring"
importmypackage
newmyclass {
myfunc()
}
package mypackage
{
classmyclass
{
(continues on next page)
39.12. Using `case' as `on' in switch statements 288

Ring Documentation, Release 1.14
(continued from previous page)
funcmyfunc
{
print("Hello, World! ")
}
}
}
39.15
Example:
importmypackage
newmyclass {
myfunc()
}
package mypackage
classmyclass
defmyfunc
put"Hello, World!"
end
end
end
39.16
ages/Classes/Functions
Example:
importmypackage
newmyclass { myfunc() }
package mypackage
classmyclass
funcmyfunc
see"welcome"
endfunc
endclass
endpackage
39.15. Using `end' keyword after Packages/Classes/Functions 289

Ring Documentation, Release 1.14
39.17
Starting from Ring 1.8 the compiler will ignore new lines after keywords that expect tokens after it
Example:
see
"
Hello, World!
"
test()
func
#======================#
Test
#======================#
?
"
Hellofromthe Test function
"
Output:
Hello, World!
Hello from the Test function
39.17. Ignore new lines after keywords 290

CHAPTER
FORTY
INTRODUCTION TO THE TYPE HINTS LIBRARY
In this chapter we will learn about the Type Hints Library
40.1
Using this library we can add the type information to the source code which will be very useful for tools like
•
•
Note:Ring is a dynamic language, No type checking will be done by the compiler.
40.2
The next example will use the Type Hints library
load"typehints.ring"
seesum(3,4)
seesayHello("Mahmoud");
intfuncsum(int x,int y) {
returnx+y ;
}
string sayHello(stringname) {
return"Hello
}
291

Ring Documentation, Release 1.14
40.3
The Type Hints library is very powerful and will support user types (Classes) automatically
Example:
load"typehints.ring"
importmypackage
test() { main([:one,:two,:three]) }
myclassfunctest() {
see"Testing User Types!"
return myclass
}
package mypackage {
publicclassmyclass {
public static void funcmain(listargs) {
see"welcome"
seeargs
}
}
}
40.4
Also you can use the types inside the code (not only the function prototype)
Example:
load"typehints.ring"
int sum3,4)
stringmsg"Mahmoud")
see"Sum =
intfuncsum(int x,int y) {
returnx+y ;
}
string sayHello(stringname) {
return"Hello
}
40.3. User Types 292

Ring Documentation, Release 1.14
40.5
•
•
The next types are dened by the library
# Low Level Types
char
unsigned
signed
int
short
long
float
double
void
# High Level Types
string
list
number
object
# Other
public
static
abstract
protected
override
40.5. Rules 293

CHAPTER
FORTYONE
THE TRACE LIBRARY AND THE INTERACTIVE DEBUGGER
In this chapter we will learn about the Trace Library and the Interactive Debugger
41.1
To start using the Trace library, We must load it rst!
load"tracelib.ring"
41.2
The next example demonstrates the Trace library usage to trace all events.
# Trace All Events
trace(:AllEvents)
see"Hello, world!"
see"Welcome"
see"How are you?"nl
mytest()
newmyclass { mymethod() }
funcmytest
see"Message from mytest"
classmyclass
funcmymethod
see"Message from mymethod"
294

Ring Documentation, Release 1.14
41.3
The next example demonstrates the Trace library usage to trace the control ow between functions.
Trace(:Functions)
test1()
functest1
see:test1
test2()
functest2
see:test2
seetest3()
functest3
see:test3
return"test 3 output"
41.4
The next example demonstrates the Trace library usage to pass an error!
Trace(:PassError)
test1()
functest1
x
see:test1
test2()# Runtime Error!
see"We can continue!"
41.5
The next example demonstrates the Trace library usage to use the Interactive Debugger
Trace(:Debugger)
test1()
see"good bye!"
functest1
x
see:test1
t
test2()# Runtime Error!
see"After Error!"nl
see"t = seetseenl
see"x = seexseenl
41.3. Trace control ow between functions 295

Ring Documentation, Release 1.14
41.6
The next example demonstrates the Trace library usage to execute the program line by line!
Trace(:LineByLine)
test1()
functest1
x
see:test1
t
test2()
see"After Error!"nl
see"t =
41.7
The next example demonstrates the Trace library usage to stop at a breakpoint!
test1()
functest1
x
see:test1
t
BreakPoint()
see"After breakpoint!"nl
see"t =
see"End of program!"
41.8
The next example demonstrates the Trace library usage and how to disable the Breakpoints!
NoBreakPoints()
test1()
functest1
x
see:test1
t
BreakPoint()
see"After breakpoint!"nl
see"t =
see"End of program!"
41.6. Execute Program Line by Line 296

Ring Documentation, Release 1.14
41.9
The next example uses a Breakpoint to open the Interactive Debugger!
load"tracelib.ring"
test1()
functest1
x
see:test1
t
BreakPoint()
see"After breakpoint!"nl
see"t =
see"End of program!"
Screen Shots:
We have the Interactive Debugger at the Breakpoint!
We can print the variables valuesWe can change the variables values then continue execution
41.9. Using the Interactive Debugger 297

Ring Documentation, Release 1.14
We can run the Interactive Debugger in the Output Window
41.9. Using the Interactive Debugger 298

CHAPTER
FORTYTWO
EMBEDDING RING IN RING
In this chapter we will learn about embedding Ring in Ring programs and applications.
42.1
From Ring 1.0 we already have functions for embedding Ring in the C language. Also we can execute Ring code
inside Ring programs using the eval() function. In this release we provide functions for embedding Ring in Ring
programs without sharing the state.
Advantages:
(1)
(2)
Example:
pState
ring_state_runcode(pState,"SeeHello, World!+nl")
ring_state_runcode(pState,"x = 10")
pState2
ring_state_runcode(pState2,"SeeHello, World!+nl")
ring_state_runcode(pState2,"x = 20")
ring_state_runcode(pState,"see x +nl")
ring_state_runcode(pState2,"see x +nl")
v1"x")
v2"x")
seev1[3]
seeV2[3]
ring_state_delete(pState)
ring_state_delete(pState2)
Output:
Hello, World!
Hello, World!
10
20
(continues on next page)
299

Ring Documentation, Release 1.14
(continued from previous page)
10
20
42.2
We can execute application after another application using ring_state_main()
Example:
chdir(exefolder()+"/../applications/formdesigner")
ring_state_main(&#3627409170;formdesigner.ring&#3627409170;)
chdir(exefolder()+"/../applications/cards")
ring_state_main(&#3627409170;cards.ring&#3627409170;)
42.3
Using ring_state_setvar() we can set variables value
The value could be (String, Number, List or C Pointer)
We need this function to quickly pass lists and C pointers to the Sub Ring Environment
Syntax:
ring_state_setvar(oState,cVariableName,Value)
Example:
load"guilib.ring"
myapp null
win null
funcmain
myapp newqApp {
win newqWidget() {
setWindowTitle("Advanced Example on using ring_state_setvar()
˓→")
move(100,100)
resize(600,400)
newqPushButton(win) {
setText("Test")
setClickEvent("Test()")
}
?????? &#3627408458;&#3627408466; &#3627408475;&#3627408466;&#3627408466;&#3627408465; &#3627408481;&#3627408469;&#3627408470;&#3627408480; &#3627408463;&#3627408466;&#3627408464;&#3627408462;&#3627408482;&#3627408480;&#3627408466; &#3627408482;&#3627408480;&#3627408470;&#3627408475;&#3627408468; &#3627408473;&#3627408476;&#3627408462;&#3627408465; &#3627409170;&#3627408468;&#3627408482;&#3627408470;&#3627408473;&#3627408470;&#3627408463;◁&#3627408479;&#3627408470;&#3627408475;&#3627408468;&#3627409170; &#3627408470;&#3627408475;
# the sub environment
# Will create timers by Qt and closing the window
# will not be enough to close the application
oFilter newqAllEvents(win)
oFilter.setCloseEvent("myapp.quit()")
win.installeventfilter(oFilter)
show()
}
(continues on next page)
42.2. Serial Execution of Programs 300

Ring Documentation, Release 1.14
(continued from previous page)
exec()
}
functest
pState
ring_state_runcode(pstate,"loadguilib.ring&#3627409170;")
ring_state_runcode(pState,"x = NULL")
# Pass String
ring_state_setvar(pState,"x","hello")
ring_state_runcode(pState,"? x")
# Pass Number
ring_state_setvar(pState,"x",100)
ring_state_runcode(pState,"? x")
# Pass List
ring_state_setvar(pState,"x",["one","two","three"])
ring_state_runcode(pState,"? x")
# Pass Object
?????? &#3627408458;&#3627408466; &#3627408464;&#3627408462;&#3627408475;&#3627409170;&#3627408481; &#3627408477;&#3627408462;&#3627408480;&#3627408480; &#3627408481;&#3627408469;&#3627408466; &#3627408453;&#3627408470;&#3627408475;&#3627408468; &#3627408450;&#3627408463;&#3627408471;&#3627408466;&#3627408464;&#3627408481; ↼&#3627408484;&#3627408470;&#3627408475;↽
# Because Objects store pointers to the Class Information
# And the class is related to the Parent Ring Environment
?????? &#3627408436;&#3627408475;&#3627408465; &#3627408481;&#3627408469;&#3627408466; &#3627408480;&#3627408482;&#3627408463; &#3627408453;&#3627408470;&#3627408475;&#3627408468; &#3627408466;&#3627408475;&#3627408483;&#3627408470;&#3627408479;&#3627408476;&#3627408475;&#3627408474;&#3627408466;&#3627408475;&#3627408481; &#3627408464;&#3627408462;&#3627408475;&#3627409170;&#3627408481; &#3627408462;&#3627408464;&#3627408464;&#3627408466;&#3627408480;&#3627408480; &#3627408470;&#3627408481;
# But we can pass C pointers like win.pObject
ring_state_setvar(pState,"x",win.pObject)
# Now we create the object again but using the same C pointer
# So we have access to the Same window in the parent Ring enviroment
ring_state_runcode(pState,"
newqWidget {
pObject
setwindowtitle(&#3627409170;Messageromheubingnvironment
˓→&#3627409170;)
}
")
ring_state_delete(pState)
42.4
&#3627408456;&#3627408480;&#3627408470;&#3627408475;&#3627408468; &#3627408479;&#3627408470;&#3627408475;&#3627408468;⌢&#3627408480;&#3627408481;&#3627408462;&#3627408481;&#3627408466;⌢&#3627408475;&#3627408466;&#3627408484;↼↽ &#3627408462;&#3627408475;&#3627408465; &#3627408479;&#3627408470;&#3627408475;&#3627408468;⌢&#3627408480;&#3627408481;&#3627408462;&#3627408481;&#3627408466;⌢&#3627408474;&#3627408462;&#3627408470;&#3627408475;??????&#3627408473;&#3627408466;↼↽ &#3627408484;&#3627408466; &#3627408464;&#3627408462;&#3627408475; &#3627408479;&#3627408482;&#3627408475; &#3627408453;&#3627408470;&#3627408475;&#3627408468; &#3627408477;&#3627408479;&#3627408476;&#3627408468;&#3627408479;&#3627408462;&#3627408474;&#3627408480; &#3627408467;&#3627408479;&#3627408476;&#3627408474; &#3627408453;&#3627408470;&#3627408475;&#3627408468; &#3627408477;&#3627408479;&#3627408476;&#3627408468;&#3627408479;&#3627408462;&#3627408474;&#3627408480;
But unlike ring_state_main(), Here we can control when to delete the Ring state!
This is important when we run GUI programs from GUI programs
Because they will share the GUI Library (RingQt), And In this case the caller will call
qApp.Exec()
So the sub program, will not stop and will return to the Main program
Here deleting the State of the sub programs will lead to a problem when we run the sub program events
So keeping the state is important for sub GUI programs hosted in GUI programs.
Example:
load"guilib.ring"
funcmain
(continues on next page)
42◁4◁ &#3627408479;&#3627408470;&#3627408475;&#3627408468;⌢&#3627408480;&#3627408481;&#3627408462;&#3627408481;&#3627408466;⌢&#3627408475;&#3627408466;&#3627408484;↼↽ &#3627408462;&#3627408475;&#3627408465; &#3627408479;&#3627408470;&#3627408475;&#3627408468;⌢&#3627408480;&#3627408481;&#3627408462;&#3627408481;&#3627408466;⌢&#3627408474;&#3627408462;&#3627408470;&#3627408475;??????&#3627408473;&#3627408466;↼↽ 301

Ring Documentation, Release 1.14
(continued from previous page)
newqApp {
win newqWidget() {
setWindowTitle("Test ring_state_mainfile()")
resize(400,400) move(100,100)
btn newqPushButton(Win) {
settext("test")
setclickevent("mytest()")
}
show()
}
exec()
}
funcmytest
pState
ring_state_mainfile(pState,"runprogram.ring")
# Here we dont delete the state if we will run GUI application
# So we can run the GUI application events
//
If you will use this feature, remember to update the previous example based on your application needs
So you can call ring_state_delete() at some point to avoid the memory leak!
42.5
Starting from Ring 1.8
When embedding Ring in Ring, the error in the hosted environment will not close the host
Example:
?Start the test!"
pState
ring_state_runcode(pState,"Let us try having an error")
ring_state_delete(pState)
?"
?End of test!"
Output:
Start the test!
Let us try having an error
Line 1 Error (R24) : Using uninitialized variable : x
in file Ring_EmbeddedCode
End of test!
42.5. Runtime Errors when Embedding Ring in Ring 302

Ring Documentation, Release 1.14
42.6
Starting from Ring 1.12 we have the ring_state_letokens() function
Using this function we can get all the tokens in the ring source code le.
C_FILENAMEtest_tokens.ring"
C_WIDTH
# write the file
write(C_FILENAME,
see"Hello, World!"
?*2+3
NameRing"
?
)
# Token Type
C_KEYWORD
C_OPERATOR
C_LITERAL
C_NUMBER
C_IDENTIFIER
C_ENDLINE
# Keywords List
aKEYWORDS"IF","TO","OR","AND","NOT","FOR","NEW","FUNC",
"FROM","NEXT","LOAD","ELSE","SEE","WHILE","OK","CLASS","RETURN","BUT",
"END","GIVE","BYE","EXIT","TRY","CATCH","DONE","SWITCH","ON","OTHER","OFF",
"IN","LOOP","PACKAGE","IMPORT","PRIVATE","STEP","DO","AGAIN","CALL","ELSEIF",
"PUT","GET","CASE","DEF","ENDFUNC","ENDCLASS","ENDPACKAGE",
"CHANGERINGKEYWORD","CHANGERINGOPERATOR","LOADSYNTAX"]
pState
aList
PrintTokens(aList)
ring_state_delete(pState)
funcPrintTokens aList
foraTokeninaList
switchaToken[1]
onC_KEYWORD
?"Keyword",C_WIDTH):[0+aToken[2]]
onC_OPERATOR
?"Operator",C_WIDTH):[2]
onC_LITERAL
?"Literal",C_WIDTH):[2]
onC_NUMBER
?"Number",C_WIDTH):[2]
onC_IDENTIFIER
?"Identifier",C_WIDTH):[2]
onC_ENDLINE
?EndLine"
off
next
funcWidth cText,nWidth
returncText+copy(",nWidth-len(cText))
42.6. ring_state_letokens() function 303

Ring Documentation, Release 1.14
Output:
EndLine
Keyword : SEE
Literal : Hello, World!
EndLine
Operator : ?
Number : 3
Operator : *
Number : 2
Operator : +
Number : 3
EndLine
Identifier : name
Operator : =
Literal : Ring
EndLine
Operator : ?
Identifier : name
EndLine
42.6. ring_state_letokens() function 304

CHAPTER
FORTYTHREE
STDLIB FUNCTIONS
In this chapter we are going to learn about functions in the stdlib.ring
Before using the functions in the library, We must load the library rst
load"stdlib.ring"
Instead of using stdlib.ring we can use stdlibcore.ring
Using stdlibcore.ring we can use the StdLib functions (Without Classes)
This is useful when developing standalone console applications
Because using stdlib.ring (functions & classes) will load libraries like RingLibCurl, RingOpenSSL, etc.
43.1
print the value then print new line (nl)
Syntax:
puts(expr)
Example:
Load"stdlib.ring"
Puts("Hello, World!")
43.2
print string - support , and
Also we can use #{variable_name} to insert variables values.
Syntax:
print(string)--> String
Example:
305

Ring Documentation, Release 1.14
print(" Hello, World How are you? Im fine!")
x=10=20
print(" x value = #{x} , y value = #{y} ")
43.3
Syntax:
print2Str(string)--> String
Example:
worldWorld!"
mystring"Hello, #{world} In Year#{2000+17}")
seemystring
Output:
Hello, World!
InYear
2017
43.4
Get input from the keyboard - return value as string
getstring()--> string
43.5
Get input from the keyboard - return value as number
getnumber()-->
43.6
Get the path of the application folder
Syntax:
AppPath()--> String
Example:
43.3. Print2Str() Function 306

Ring Documentation, Release 1.14
Load"stdlib.ring"
# Application Path
Puts("Test AppPath()")
SeeAppPath()
43.7
Get the path of the le, remove the le name.
Syntax:
JustFilePath(cFile)--> String
Example:
load"stdlib.ring"
seejustfilePath("b: ing\applicationsnotenote.ring")
Output:
b:\ring\applications\rnote\
43.8
Get the le, remove the le path.
Syntax:
JustFileName(cFile)--> String
Example:
load"stdlib.ring"
seejustfileName("b: ing\applicationsnotenote.ring")
Output:
rnote.ring
43.7. JustFilePath() function 307

Ring Documentation, Release 1.14
43.9
create a copy from a list or object
Syntax:
value(List)--> new
Example:
Load"stdlib.ring"
aList:10
del(value(aList),1) # delete first item
seeaList # print numbers from 1 to 10
43.10
Execute a Function nCount times
Syntax:
Times(nCount,function)
Example:
Load"stdlib.ring"
Puts("Test Times()")
Times ( func{see"Hello, World!"
43.11
Execute a Function on each list item
Syntax:
Map(alist,function)--> List
Example:
Load"stdlib.ring"
Puts("Test Map()")
SeeMap(:10, funcx {returnx*x } )
43.9. Value() function 308

Ring Documentation, Release 1.14
43.12
Execute a Function on each list item to lter items
Syntax:
Filter(alist,function)--> List
Example:
Load"stdlib.ring"
Puts("Test Filter()")
SeeFilter(:10 funcx {ifx= return } )
43.13
Convert string words to list items
Syntax:
Split(cstring,delimiter)--> List
Example:
Load"stdlib.ring"
Puts("Test Split()")
SeeSplit("one two three four five",")
43.14
Convert string words to list items. Allow many delimiters.
Syntax:
SplitMany(cstring,delimiters as string )-> List
Example:
Load"stdlib.ring"
Puts("Test SplitMany()")
SeeSplitMany("one,two,three,four and five","")
43.12. Filter() function 309

Ring Documentation, Release 1.14
43.15
Return a copy of a string with the rst letter capitalized
Syntax:
Capitalized(string)--> string
Example:
Load"stdlib.ring"
Puts("Test Capitalized()")
Seecapitalized("welcome to the Ring Programming Language")
43.16
Check whether a character is special or not
Syntax:
IsSpecial(char)--> True/False
Example:
Load"stdlib.ring"
Puts("Test Isspecial()")
See"Isspecial ="%")
43.17
Check whether a character is vowel or not
Syntax:
IsVowel(char)--> True/False
Example:
Load"stdlib.ring"
Puts("Test Isvowel()")
See"Isvowel ="c")
43.15. Capitalized() function 310

Ring Documentation, Release 1.14
43.18
Return the lines count in a text le.
Syntax:
LineCount(cFileName)-->
Example:
Load"stdlib.ring"
Puts("Test Linecount()")
See"the number of lines ="test.ring")
43.19
Return the factorial of a number
Syntax:
Factorial(number)-->
Example:
Load"stdlib.ring"
Puts("Test Factorial()")
see"6 factorial is :6)
43.20
Return the bonacci number
Syntax:
Fibonacci(number)-->
Example:
Load"stdlib.ring"
Puts("Test Fibonacci()")
see"6 Fibonacci is :6)
43.18. LineCount() function 311

Ring Documentation, Release 1.14
43.21
Check whether a number is prime or not
Syntax:
isprime(number)-->
Example:
Load"stdlib.ring"
Puts("Test Isprime()")
ifisPrime(16) see"16 is a prime number"
else "16 is not a prime number" ok
43.22
Returns an integer value indicating the sign of a number.
Syntax:
Sign(number)-->1
Example:
Load"stdlib.ring"
Puts("Test Sign()")
see"sign of 12 is =12)
43.23
Write list items to text le (each item in new line).
Syntax:
List2File(aList,cFileName)
Example:
Load"stdlib.ring"
# Test List2File
Puts("Test List2File()")
list2file(1:100,"myfile.txt")
43.21. IsPrime() function 312

Ring Documentation, Release 1.14
43.24
Read text le and convert lines to list items
Syntax:
File2List(cFileName)--> List
Example:
Load"stdlib.ring"
# Test File2List
Puts("Test File2List()")
seelen(file2list("myfile.txt"))
43.25
Returns true if the given string starts with the specied substring.
Leading white spaces are ignored.
Syntax:
StartsWith(string, substring)--> True/False
Example:
Load"stdlib.ring"
Puts("Test Startswith()")
seeStartswith("CalmoSoft",Calmo")
43.26
Returns true if the given string ends with the specied substring.
Trailing white spaces are ignored.
Syntax:
Endswith(string, substring)--> True/False
Example:
Load"stdlib.ring"
Puts("Test Endswith()")
seeendsWith("CalmoSoft",Soft")
43.24. File2List() function 313

Ring Documentation, Release 1.14
43.27
Finding of the greatest common divisor of two integers.
Syntax:
Gcd(number,number)-->
Example:
Load"stdlib.ring"
Puts("Test Gcd()")
seegcd (24,)
43.28
Compute the least common multiple of two integers.
Syntax:
lcm(number,number)-->
Example:
Load"stdlib.ring"
Puts("Test Lcm()")
seeLcm(24,36)
43.29
Compute the sum of a list of integers.
Syntax:
sumlist(list)-->
Example:
Load"stdlib.ring"
Puts("Test Sumlist()")
aList1,2,3,4,5]
seeSumlist(aList)
43.27. GCD() function 314

Ring Documentation, Release 1.14
43.30
Compute the product of a list of integers.
Syntax:
prodlist(list)-->
Example:
Load"stdlib.ring"
Puts("Test Prodlist()")
aList1,2,3,4,5]
seeProdlist(aList)
43.31
Test whether an integer is even or odd.
Result of test (1=odd 2=even).
Syntax:
evenorodd(number)--> or2
Example:
Load"stdlib.ring"
Puts("Test Evenorodd()")
nr
seeEvenorodd(nr)
43.32
Compute the factors of a positive integer.
Syntax:
factors(number)--> list
Example:
Load"stdlib.ring"
Puts("Test Factors()")
n
aList
see"Factors of
fori tolen(aList)
see""[i]
next
43.30. ProdList() function 315

Ring Documentation, Release 1.14
43.33
Check if a sequence of characters is a palindrome or not.
Syntax:
IsPalindrome(String)--> True/False
Example:
Load"stdlib.ring"
Puts("Test IsPalindrome()")
cStringradar"
seeIsPalindrome(cString)
43.34
Check whether a given year is a leap year in the Gregorian calendar.
Syntax:
Isleapyear(number)--> True/False
Example:
Load"stdlib.ring"
Puts("Test Isleapyear()")
year
ifIsleapyear(year) see"""
else """ ok
43.35
Compute the sequence of binary digits for a given non-negative integer.
Syntax:
binarydigits(number)--> string
Example:
Load"stdlib.ring"
Puts("Test Binarydigits()")
b
see"Binary digits of
43.33. IsPalindrome() function 316

Ring Documentation, Release 1.14
43.36
Multiply two matrices together.
Syntax:
Matrixmulti(List,List)--> List
Example:
Load"stdlib.ring"
# Multiply two matrices together.
Puts("Test Matrixmulti()")
A[1,2,3],4,5,6],7,8,9]]
B[1,0,0],0,1,0],0,0,1]]
seeMatrixmulti(A, B)
43.37
Transpose an arbitrarily sized rectangular Matrix.
Syntax:
Matrixtrans(List)--> List
Example:
Load"stdlib.ring"
# Transpose an arbitrarily sized rectangular Matrix.
Puts("Test Matrixtrans()")
matrix[78,19,30,12,36],49,10,65,42,50],30,93,24,78,10],39,68,27,64,29]]
seeMatrixtrans(matrix)
43.38
Return the day of the week of given date. (yyyy-mm-dd)
Syntax:
dayofweek(string)--> string
Example:
Load"stdlib.ring"
# Return the day of the week of given date.
Puts("Test Dayofweek()")
date2016-04-24"
see"Data :
43.36. MatrixMulti() function 317

Ring Documentation, Release 1.14
43.39
Generates all permutations of n different numerals.
Syntax:
permutation(list)
Example:
Load"stdlib.ring"
# Generates all permutations of n different numerals
Puts("Test Permutation()")
list=1,,,]
forperm to24
fori tolen(list)
see [i]
next
seenl
Permutation(list)
next
43.40
Read line from le
Syntax:
readline(fp)--> string
Example:
Load"stdlib.ring"
# Read a file line by line.
Puts("Test Readline()")
fp"test.ring","r")
while feof(fp)
SeeReadline(fp)end
fclose(fp)
43.41
Return a position of a substring starting from a given position in a string.
Syntax:
Substring(str,substr,npos)--> string
Example:
43.39. Permutation() function 318

Ring Documentation, Release 1.14
Load"stdlib.ring"
# Return a position of a substring starting from a given position in a string.
Puts("Test Substring()")
aabcxyzqweabc"
babc"
i
seesubstring(a,b,i)
43.42
Change substring from given position to a given position with another substring.
Syntax:
Changestring(cString, nPos1, nPos2, cSubstr)-->
Example:
Load"stdlib.ring"
# Change substring from given position for given position with a substring.
Puts("Test Changestring()")
seeChangestring("Rmasdg",2,5,"in") # Ring
43.43
Sleep for the given amount of time.
Syntax:
sleep(nSeconds)
Example:
Load"stdlib.ring"
Puts("Test Sleep()")
see"Wait 3 Seconds!"
Sleep(3)
seenl
43.42. ChangeString() function 319

Ring Documentation, Release 1.14
43.44
Check if the current le is the main source le
Syntax:
IsMainSourceFile()--> True/False
Example:
Load"stdlib.ring"
ifismainsourcefile()
# code
ok
43.45
Make Directory
Syntax:
MakeDir(String)
Example:
Load"stdlib.ring"
# Create Directory
puts("create Directory : myfolder")
makedir("myfolder")
43.46
The function return the le size in bytes.
Syntax:
FSize(File Handle)--> inBytes)
43.47
Remove all spaces and tabs characters from a string
Syntax:
TrimAll(cString)--> # Without Spaces and Tabs
43.44. IsMainSourceFile() function 320

Ring Documentation, Release 1.14
43.48
Remove all spaces and tabs characters from the left side of a string
Syntax:
TrimLeft(cString)--> # Without Spaces and Tabs from the left side
43.49
Remove all spaces and tabs characters from the right side of a string
Syntax:
TrimRight(cString)--> # Without Spaces and Tabs from the right side
43.50
Return the Epoch Time
Syntax:
EpochTime(cDate,cTime)-->
Example:
seeEpochTime( Date(), Time() )
43.51
We can execute system commands using the SystemCmd() function that outputs to a variable
Syntax:
SystemCmd(cCommand)
Example:
cYou"whoami") # User Name logged in is output a variable
cThem"dir c:\Users") # Directory List is output to a variable
43.48. TrimLeft() function 321

Ring Documentation, Release 1.14
43.52
Using this function we can quickly do a process on a group of les in a folder and it's sub folders.
Syntax:
ListAllFiles(cFolder,cExtension)--> Listof Files
Example:
aList"c:/ring/ringlibs","ring") #*.ring only
aList
seeaList
Example:
seelistallfiles("b:/ring/libraries/weblib","") # All Files
43.53
We can execute system commands using the SystemSilent() function to avoid displaying the output!
Syntax:
SystemSilent(cCommand)
43.54
Create folder then change the current folder to this new folder
Syntax:
OSCreateOpenFolder(cCommand)
43.55
Copy folder to the current folder
Parameters : The path to the parent folder and the folder name to copy
Syntax:
OSCopyFolder(cParentFolder,cFolderName)
Example
To copy the folder b:inginglibs\stdlib to the current folder
OSCopyFolder("b: inginglibs\","stdlib")
43.52. ListAllFiles() Function 322

Ring Documentation, Release 1.14
43.56
Delete Folder in the current Directory
Syntax:
OSDeleteFolder(cFolderName)
43.57
Copy File to the current directory
Syntax:
OSCopyFile(cFileName)
43.58
Delete File
Syntax:
OSDeleteFile(cFileName)
43.59
Rename File
Syntax:
OSRenameFile(cOldFileName,cNewFileName)
43.60
This function convert a Ring list during the runtime to Ring source code that we can save to source les.
The list may contains strings, numbers or sub lists.
Example:
load"stdlibcore.ring"
aList:10
?
Output:
[
1,2,3,4,5,6,7,8,9,10
]
43.56. OSDeleteFolder() Function 323

Ring Documentation, Release 1.14
43.61
Convert a string of bytes to a list of numbers where each item represent the ASCII code of one byte in the string.
Syntax:
Str2ASCIIList(String)--> Listof numbers
43.62
Convert a list of numbers where each item represent the ASCII code of one byte to a string of bytes.
Syntax:
ASCIIList2Str(Listof numbers)--> String
Example:
load"stdlibcore.ring"
cStrMmMm"
aList
?
cStr2
?
?
Output:
77
109
77
109
MmMm
4
43.63
Syntax:
IsListContainsItems(aParent,aChild)---> True/False
Example:
load"stdlibcore.ring"
aList1a":"z"
aList2:h,:l,:p,:u]
?
43.61. Str2ASCIIList() 324

Ring Documentation, Release 1.14
43.64
Syntax:
IsBetween(nNumber,nMin,nMax)---> True/False
Example:
load"stdlibcore.ring"
?1,3,4)
?1,-3,4)
?4,1,6)
?4,3,4)
43.65
Syntax:
TimeInfo(cInformation)---> String
The cInformation value could be
:hour_24
:hour_12
:minutes
:seconds
:time
:day_short
:day_long
:month_short
:month_long
:date_time
:day
:day_year
:month_year
:am_pm
:week_year
:day_week
:date
:year_century
:year
:time_zone
:percent_sign
Example:
load"stdlibcore.ring"
?
?
?
43.64. IsBetween() 325

CHAPTER
FORTYFOUR
STDLIB CLASSES
In this chapter we are going to learn about the classes in the stdlib.ring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
326

Ring Documentation, Release 1.14
44.1
Attributes:
•
Methods:
Method Description/Output
Init(x)Set vValue Attribute to x value
Print()Print vValue
PrintLn()Print vValue then New Line
Size() return number represent the size of vValue
Value()return vValue
Set(x) Call Init(x)
44.2
Parent Class : StdBase Class
Methods:
Method Description/Output
Init(String|Number|List)
Lower() New String - Lower case characters
Upper() New String - Upper case characters
Left(x) New String - contains x characters from the left
Right(x) New String - contains x characters from the right
Lines() Number - Lines count
Trim() New String - Remove Spaces
Copy(x) New String - repeat string x times
strcmp(cString) Compare string with cString
tolist() List (String Lines to String Items)
tole(cFileName) Write string to le
mid(nPos1,nPos2) New String - from nPos1 to nPos2
getfrom(nPos1) New String - from nPos1 to the end of the string
replace(cStr1,cStr2,lCase)New String - Replace cStr1 with cStr2 , lCase (True=Match Case)
split() List - Each Word as list item
startswith(substring)Return true if the start starts with a substring
endswith(substring) Return true if the start ends with a substring
Example:
Load"stdlib.ring"
See"Testing the String Class"
oString new ("Hello, World!")
oString.println()
oString.upper().println()
oString.lower().println()
oString.left(5).println()
(continues on next page)
44.1. StdBase Class 327

Ring Documentation, Release 1.14
(continued from previous page)
oString.right(6).println()
oString new ("Hi"Hello"
SeeoString.lines()
oString new (")
oString.println()
oString.trim().println()
oString new ("Hello!)
oString.copy(3).println()
seeoString.strcmp("Hello!)
seeoString.strcmp("Hello)
seeoString.strcmp("Hello!!)
oString new (["one","two","three"])
oString.print()
seeoString.lines()
oString new (1234)
oString.println()
oString new ("one"+nl+"two"+nl+"three")
aList
see"List Items" SeeaList
oString new (Welcome to the Ring programming language")
See"the - position :"the")
oString"Ring"))
oString.println()
oString.mid(1,4).println()
oString"Ring"," ***Ring***",true)
oString.println()
oString"ring"," ***Ring***",false)
oString.println()
oString1 new ("First")
oString2 new ("Second")
oString
oString.println()
oString *3
oString.println()
fortinostringseetnext
oString.tofile("test.txt")
oString new ("one two three")
seenl
seeostring.split()
oString {
set("Hello") println()
set("How are you?") println()
}
Output:
Testing theString
Hello, World!
HELLO, WORLD!
hello, world!
Hello
World!
2
Welcome
Welcome
Hello!!!
0
(continues on next page)
44.2. String Class 328

Ring Documentation, Release 1.14
(continued from previous page)
1
-1
one
two
three
4
1234
ListItems
one
two
three
the
Ring programming language
Ring
***Ring***programming language
****** Ring****** programming language
FirstSecond
FirstFirstFirst
FirstFirstFirst
one
two
three
Hello
How are you?
44.3
Parent Class : StdBase Class
Methods:
Method Description/Output
Init(String|List)
Add(Value) Add item to the list
Delete(nIndex) Delete item from the list
Item(nIndex) Get item from the list
First() Get the rst item in the list
Last() Get the last item in the list
Set(nIndex,Value) Set item value
FindInColumn(nCol,Value)Find item in a column
Sort() Sort items - return new list
Reverse() Reverse items - return new list
Insert(nIndex,Value) Inset Item after nIndex
example:
Load"stdlib.ring"
oList new (1,2,3]
oList.Add(4)
oList.print()
seeoList.item(1)
(continues on next page)
44.3. List Class 329

Ring Documentation, Release 1.14
(continued from previous page)
oList.delete(4)
oList.print()
seeoList.first()
seeoList.last()
oList { set(1,"one") set(2,"two") set(3,"three") print() }
seeoList.find("two")
oList.sort().print()
oList.reverse().print()
oList.insert(2,"nice")
oList.print()
oList new (1,"one"],[2,"two"],[3,"three"]
seecopy(" *",10)
oList.print()
see"Search two :2,"two")
see"Search 1 :1,1)
oList new (Egypt"USA"KSA"
forxinoList
seex
next
oList new (1,2,3,4]
oList5,6,7]
oList.print()
oList new ("one","two"]
oList2 new ("three","four"]
oList
oList.print()
output:
1
2
3
4
1
1
2
3
1
3
one
two
three
2
one
three
two
three
two
one
one
two
nice
three
**********
1
one
2
(continues on next page)
44.3. List Class 330

Ring Documentation, Release 1.14
(continued from previous page)
two
3
three
Search two :
Search
Egypt
USA
KSA
1
2
3
4
5
6
7
one
two
three
four
44.4
Parent Class : List Class
Methods:
Method Description/Output
Init(String|Number|List)
Push(Value) Push item to the stack
Pop() Pop item from the stack
Print() Print the stack items
example:
Load"stdlib.ring"
oStack new
oStack.push(1)
oStack.push(2)
oStack.push(3)
seeoStack.pop()
seeoStack.pop()
seeoStack.pop()
oStack.push(4)
seeoStack.pop()
oStack { push("one") push("two") push("three") }
oStack.print()
output:
3
2
1
(continues on next page)
44.4. Stack Class 331

Ring Documentation, Release 1.14
(continued from previous page)
4
three
two
one
44.5
Parent Class : List Class
Methods:
Method Description/Output
Init(String|Number|List)
Remove() Remove item from the Queue.
example:
Load"stdlib.ring"
oQueue new
oQueue.add(1)
oQueue.add(2)
oQueue.add(3)
seeoQueue.remove()
seeoQueue.remove()
seeoQueue.remove()
oQueue.add(4)
seeoQueue.remove()
oQueue { add("one") add("two") add("three") }
oQueue.print()
output:
1
2
3
4
one
two
three
44.6
Parent Class : List Class
Methods:
44.5. Queue Class 332

Ring Documentation, Release 1.14
Method Description/Output
Init(List)
Add(cKey,Value)Add item to the HashTable
Set(cKey,Value)Set item value using the Key
GetValue(cKey)Get item value using the Key
Contains(cKey)Check if the HashTable contains item using the Key
Index(cKey) Get the item index using the Key
example:
Load"stdlib.ring"
ohashtable new
See"Test the hashtable Class Methods"
ohashtable {
Add("Egypt","Cairo")
Add("KSA","Riyadh")
seeself["Egypt"]
seeself["KSA"]
seecontains("Egypt")
seecontains("USA")
seeindex("KSA")
print()
delete(index("KSA"))
seecopy(" *",60)
print()
}
output:
Test thehashtable Methods
Cairo
Riyadh
1
0
2
Egypt
Cairo
KSA
Riyadh
************************************************************
Egypt
Cairo
44.7
Data:
AttributeDescription
Data Node Value
ChildrenChildren List
Methods:
44.7. Tree Class 333

Ring Documentation, Release 1.14
Method Description/Output
set(value)Set the node value.
value() Get the node value.
Add(value)Add new child.
parent()Get the parent node.
print() Print the tree nodes.
example:
Load"stdlib.ring"
otree new
See"Test the tree Class Methods"
otree {
set("The first step") # set the root node value
seevalue()
Add("one")
Add("two")
Add("three") {
Add("3.1")
Add("3.2")
Add("3.3")
seechildren
}
seechildren
oTree.children[2]
Add("2.1") Add("2.2") Add("2.3") {
Add("2.3.1") Add("2.3.2") Add("test")
}
}
oTree.children[2].children[3].children[3].set("2.3.3")
}
seecopy(" *",60)
oTree.print()
output:
Test thetree Methods
The firststep
data:.1
parent:List...
children:List...
data:.2
parent:List...
children:List...
data:.3
parent:List...
children:List...
data: one
parent:List...
children:List...
data: two
parent:List...
children:List...
data: three
parent:List...
(continues on next page)
44.7. Tree Class 334

Ring Documentation, Release 1.14
(continued from previous page)
children:List...
************************************************************
one
two
2.1
2.2
2.3
2.3.1
2.3.2
2.3.3
three
3.1
3.2
3.3
44.8
Methods:
Method Description
sin(x) Returns the sine of an angle of x radians
cos(x) Returns the cosine of an angle of x radians
tan(x) Returns the tangent of an angle of x radians
asin(x) Returns the principal value of the arc sine of x, expressed in radians
acos(x) Returns the principal value of the arc cosine of x, expressed in radians
atan(x) Returns the principal value of the arc tangent of x, expressed in radians
atan2(y,x) Returns the principal arc tangent of y/x, in the interval [-pi,+pi] radians
sinh(x) Returns the hyperbolic sine of x radians
cosh(x) Returns the hyperbolic cosine of x radians
tanh(x) Returns the hyperbolic tangent of x radians
exp(x) Returns the value of e raised to the xth power
log(x) Returns the natural logarithm of x
log10(x) Returns the common logarithm (base-10 logarithm) of x
ceil(x) Returns the smallest integer value greater than or equal to x
oor(x) Returns the largest integer value less than or equal to x
fabs(x) Returns the absolute value of x.
pow(x,y) Returns x raised to the power of y
sqrt(x) Returns the square root of x
random(x) Returns a random number in the range [0,x]
unsigned(n,n,c)Perform operation using unsigned numbers
decimals(n) Determine the decimals digits after the point in oat/double numbers
example:
Load"stdlib.ring"
oMath newMath
See"Test the Math Class Methods"
See"Sin(0) =0)
(continues on next page)
44.8. Math Class 335

Ring Documentation, Release 1.14
(continued from previous page)
See"Sin(90) radians =90)
See"Sin(90) degree =90 *3.14/180)
See"Cos(0) =0)
See"Cos(90) radians =90)
See"Cos(90) degree =oMath. cos(90 *3.14/180)
See"Tan(0) =0)
See"Tan(90) radians =90)
See"Tan(90) degree =90 *3.14/180)
See"asin(0) =0)
See"acos(0) =0)
See"atan(0) =0)
See"atan2(1,1) =oMath. atan2(1,1)
See"sinh(0) =0)
See"sinh(1) =1)
See"cosh(0) =0)
See"cosh(1) =1)
See"tanh(0) =0)
See"tanh(1) =1)
See"exp(0) =0)
See"exp(1) =1)
See"log(1) =1)
See"log(2) =2)
See"log10(1) =1)
See"log10(2) =2)
See"log10(10) =10)
See"Ceil(1.12) =1.12)
See"Ceil(1.72) =1.72)
See"Floor(1.12) =1.12)
See"Floor(1.72) =1.72)
See"fabs(1.12) =1.12)
See"fabs(1.72) =1.72)
See"pow(2,3) =2,3)
see"sqrt(16) =16)
forx to20
see"Random number Max (100) :100)
next
x.1234567890123
ford to14
oMath.decimals(d)
seex
next
cKeyhello"
h
(continues on next page)
44.8. Math Class 336

Ring Documentation, Release 1.14
(continued from previous page)
forxincKey
h"+")
h10,"<<"),"+")
r6,">>")
h"^")
next
h3,"<<"),"+")
h11,">>"),"^")
h15,"<<"),"+")
see"Hash :
output:
Test the MathClassMethods
Sin(0)
Sin(90) radians.89
Sin(90) degree.00
Cos(0)
Cos(90) radians0.45
Cos(90) degree.00
Tan(0)
Tan(90) radians2.00
Tan(90) degree.77
asin(0)
acos(0).57
atan(0)
atan2(1,1).79
sinh(0)
sinh(1).18
cosh(0)
cosh(1).54
tanh(0)
tanh(1).76
exp(0)
exp(1).72
log(1)
log(2).69
log10(1)
log10(2).30
log10(10)
Ceil(1.12)
Ceil(1.72)
Floor(1.12)
Floor(1.72)
fabs(1.12).12
fabs(1.72).72
pow(2,3)
sqrt(16)
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
(continues on next page)
44.8. Math Class 337

Ring Documentation, Release 1.14
(continued from previous page)
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
Random number Max (100) :
1
1.1
1.12
1.123
1.1235
1.12346
1.123457
1.1234568
1.12345679
1.123456789
1.1234567890
1.12345678901
1.123456789012
1.1234567890123
1.12345678901230
Hash :.00000000000000
44.9
Methods:
Method Description/Output
clock() The number of clock ticks from program start.
time() Get the system time.
date() Get the date.
timelist() List contains the date and the time information.
adddays(cDate,nDays)Return Date from cDate and after nDays
diffdays(cDate1,cDate2)Return the Number of days (cDate1 - cDate2)
example:
Load"stdlib.ring"
oDateTime newdatetime
See"Test the datetime Class Methods"
See"Calculate performance"
t1
forx to1000000next
(continues on next page)
44.9. DateTime Class 338

Ring Documentation, Release 1.14
(continued from previous page)
seeoDateTime.clock()
See"Time :
See"Date :
SeeoDateTime.TimeList()
See"Month Name :[4]
cDate
seecDate
cDate10)
seecDate
cDate1
seecDate1
cDate210)
seecDate2
see"DiffDays =
see"DiffDays =
output:
Test the datetime ClassMethods
Calculate performance
85
Time ::53:35
Date :/08/2016
Wed
Wednesday
Aug
August
08/31/16:53:35
31
02
02
244
08
53
AM
35
35
3
08/31/16
02:53:35
16
2016
Arab Standard Time
%
Month Name : August31/08/2016
10/09/2016
31/08/2016
10/09/2016
DiffDays10
DiffDays
44.9. DateTime Class 339

Ring Documentation, Release 1.14
44.10
Methods:
Method Description/Output
read(cFileName) Read the le content
write(cFileName,cStr)Write string to le
dir(cFolderPath) Get the folder contents (les & sub folders)
rename(cOld,cNew) Rename les using the Rename() function
remove(cFileName) Delete a le using the Remove() function
open(cFileName,cMode)Open a le using the Fopen() function
close() Close le
ush() Flushes the output buffer of a stream
reopen(cFileName,cMode)Open another le using the same le handle
temple() Creates a temp. le (binary).
seek(noffset,nwhence)Set the le position of the stream
tell() Know the current le position of a stream
rewind() Set the le position to the beginning of the le
getpos() Get handle to the current le position
setpos(poshandle) Set the current le position
clearerr() Clear the EOF error and the error indicators of a stream
eof() Test the end-of-le indicator
error() Test the error indicator
perror(cErrorMessage)Print error message to the stderr
getc() Get the next character from the stream
gets(nsize) Read new line from the stream
putc(cchar) Write a character to the stream
puts(cStr) Write a string to the stream
ungetc(cchar) Push a character to the stream
fread(nsize) Read data from a stream
fwrite(cString) Write data to a stream
exists(cFileName) Check if a le exists
example:
Load"stdlib.ring"
ofile newfile
See"Test the file Class Methods"
seeofile.read(filename())
seenl
ofile.open(filename(),"r")
seeofile.gets(100)
ofile.close()
44.10. File Class 340

Ring Documentation, Release 1.14
44.11
Methods:
Method Description/Output
system() Execute system commands
sysget() Get environment variables
ismsdos() Check if the operating system is MSDOS or not
iswindows()Check if the operating system is Windows or not
iswindows64()Check if the operating system is Windows 64bit or not
isunix() Check if the operating system is Unix or not
ismacosx() Check if the operating system is macOS or not
islinux() Check if the operating system is Linux or not
isfreebsd()Check if the operating system is FreeBSD or not
isandroid()Check if the operating system is Android or not
windowsnl()Get the windows new line string
sysargv() Get the command line arguments passed to the ring script
lename() Get the active source le
example:
Load"stdlib.ring"
oSystem newSystem
See"Test the System Class Methods"
oSystem.system("dir")
seeoSystem.sysget("path")
seeoSystem.ismsdos()
seeoSystem.iswindows()
seeoSystem.iswindows64()
seeoSystem.isunix()
seeoSystem.ismacosx()
seeoSystem.islinux()
seeoSystem.isfreebsd()
seeoSystem.isandroid()
seeoSystem.windowsnl()
seeoSystem.sysargv()
seeoSystem.filename()
44.12
Methods:
Method Description/Output
eval(cCode) Execute code during the runtime from string.
raise(cError) Raise an exception.
assert(cCondition)Test condition before executing the code.
example:
44.11. System Class 341

Ring Documentation, Release 1.14
Load"stdlib.ring"
oDebug newDebug
See"Test the Debug Class Methods"
oDebug.eval("seeHello+nl")
try
x
oDebug.assert(x=11)
catch "assert" done
raise("Error!")
44.13
Methods:
Method Description/Output
isstring(vValue)We can know if the value is a string or not.
isnumber(vValue)We can know if the value is a number or not.
islist(vValue)We can know if the value is a list or not.
type(vValue) Know the type of a value
isnull(vValue)Check the value to know if it's null or not.
isalnum(vValue)1 if the value is digit/letter or 0 if not
isalpha(vValue)1 if the value is a letter or 0 if not
iscntrl(vValue)1 if the value is a control character (no printing position)
isdigit(vValue)1 if the value is a digit or 0 if not
isgraph(vValue)1 if the value can be printed (Except space) or 0 if not
islower(vValue)1 if the value is lowercase letter or 0 if not
isprint(vValue)1 if the value occupies a printing position or 0 if not
ispunct(vValue)1 if the value is a punctuation character or 0 if not
isspace(vValue)1 if the value is a white-space or 0 if not
isupper(vValue)1 if the value is an uppercase alphabetic letter or 0 if not
isxdigit(vValue)1 if the value is a hexdecimal digit character or 0 if not
example:
Load"stdlib.ring"
oDataType newDataType
See"Test the DataType Class Methods"
seeoDataType.isstring("test")
seeoDataType.isnumber(1)
seeoDataType.islist(1:3)
seeoDataType.type("test")
seeoDataType.isnull(null)
seeoDataType.isalnum("Hello") # print 1
oDataType.isalnum("123456") # print 1
oDataType.isalnum("ABCabc123") # print 1
oDataType.isalnum("How are you") # print 0 because of spaces
seeoDataType.isalpha("Hello") # print 1
oDataType.isalpha("123456") # print 0
oDataType.isalpha("ABCabc123") # print 0
oDataType.isalpha("How are you") # print 0
(continues on next page)
44.13. DataType Class 342

Ring Documentation, Release 1.14
(continued from previous page)
SeeoDataType.iscntrl("hello") # print 0
oDataType.iscntrl(nl) # print 1
seeoDataType.isdigit("0123456789") # print 1
oDataType.isdigit("0123a")
seeoDataType.isgraph("abcdef") # print 1
oDataType.isgraph("abc def") # print 0
seeoDataType.islower("abcDEF") # print 0
oDataType.islower("ghi") # print 1
seeoDataType.isprint("Hello") # print 1
oDataType.isprint("Nice to see you") # print 1
oDataType.isprint(nl) # print 0
seeoDataType.isprint("Hello") # print 1
seeoDataType.isupper("welcome") # print 0
oDataType.isupper("WELCOME") # print 1
seeoDataType.isxdigit("0123456789abcdef") # print 1
oDataType.isxdigit("123z") # print 0
Output:
Test the DataType ClassMethods
1
1
1
STRING
1
1
1
1
0
1
0
0
0
0
11
0
1
0
0
1
1
1
0
1
0
1
1
0
44.13. DataType Class 343

Ring Documentation, Release 1.14
44.14
Methods:
Method Description/Output
number(vValue)Convert strings to numbers.
string(vValue)Convert numbers to strings.
ascii(vValue)Get the ASCII code for a letter.
char(vValue)Convert the ASCII code to character.
hex(vValue) Convert decimal to hexadecimal.
dec(vValue) Convert hexadecimal to decimal.
str2hex(vValue)Convert string characters to hexadecimal characters.
hex2str(vValue)Convert hexadecimal characters to string.
example:
Load"stdlib.ring"
oConversion newconversion
See"Test the conversion Class Methods"
SeeoConversion.number("3")
SeeoConversion.string(3)5"
SeeoConversion.Ascii("m")
SeeoConversion.char(77)
seeoConversion.hex(162)
seeoConversion.dec("a2")
cHex"Hello")
seecHex
seeoConversion.hex2str(cHex)
Output:
Test the conversion Class Methods
8
35
109
M
a2
162
48656c6c6f
Hello
44.15
Methods:
44.14. Conversion Class 344

Ring Documentation, Release 1.14
Method Description/Output
drivers() Get a list of ODBC drivers.
datasources() Get a list of ODBC data sources.
close() Free resources.
connect(cConString)Connect to the database.
disconnect() Close the connection.
execute(cSQL) Execute SQL Statements
colcount() Get columns count in the query result
fetch() Fetch a row from the query result
getdata(nCol) Get column value from the fetched row
tables() Get a list of tables inside the database
columns(cTableName)Get a list of columns inside the table
autocommit(lStatus)Enable or disable the auto commit feature
commit() Commit updates to the database
rollback() Rollback updates to the database
example:
Load"stdlib.ring"
oodbc newodbc
See"Test the odbc Class Methods"
oODBC {
seedrivers()
seedatasources()
See"Connect to database"
seeconnect("DBQ=test.mdb;Driver={Microsoft Access Driver ( *.mdb)}")
See"Select data"
seeexecute("select *from person")
nMax
See"Columns Count :
whilefetch()
See"Row data:"
forx tonMax
seegetdata(x)
next
end
See"Close database..."
disconnect()
close()
}
44.15. ODBC Class 345

Ring Documentation, Release 1.14
44.16
Methods:
Method Description/Output
info() Return string contains the MySQL Client version.
error() Get the error message from the MySQL Client.
connect(cServer,cUser,cPass,cDatabase)Connect to the MySQL database server.
close() Close the connection to the MySQL database.
query(cQuery) Execute SQL queries.
insert_id() Get the inserted row id.
result() Get the query result (data without column names).
next_result() Move to the next query result.
columns() Get a list of columns names.
result2() Get all of the column names then the query result in one list.
escape_string(cStr) Before storing binary data and special characters in the database.
autocommit(lStatus) Enable or disable the auto commit feature.
commit() Commit updates to the database.
rollback() Rollback updates to the database.
example:
Load"stdlib.ring"
omysql newmysql
See"Test the MySQL Class Methods"
omysql {
seeinfo()
connect("localhost",root",root","mahdb")
see"Execute Query"
query("SELECT *FROM Employee")
see"Print Result"
seeresult2()
see"Close database"
close()
}
Output:
Test the MySQLClassMethods
5.5.30
Execute Query
Print Result
Id
Name
Salary
1
Mahmoud
15000
2
Samir
16000
3
Fayed
(continues on next page)
44.16. MySQL Class 346

Ring Documentation, Release 1.14
(continued from previous page)
17000
Close database
44.17
Methods:
Method Description/Output
open(cDatabase)Open Database.
close() Close Database.
errormessage()Get Error Message.
execute(cSQL)Execute Query.
example:
Load"stdlib.ring"
osqlite newsqlite
See"Test the sqlite Class Methods"
osqlite {
open("test.db")
sqlCREATE TABLE COMPANY("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"AGE INT NOT NULL,"
"ADDRESS CHAR(50),"
"SALARY REAL );"
execute(sql)
sqlINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
"VALUES (1,Mahmoud, 29,Jeddah, 20000.00 );
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
"VALUES (2,Ahmed, 27,Jeddah, 15000.00 );
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (3,Mohammed, 31,Egypt, 20000.00 );"
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (4,Ibrahim, 24,Egypt, 65000.00 );"
execute(sql)
aResult"select *from COMPANY")
forxinaResult
fortinx
seet[2]
next
next
seecopy(" *",50)
forxinaResult
seex["name"]
next
close()
}
44.17. SQLite Class 347

Ring Documentation, Release 1.14
Output:
Test the sqlite ClassMethods
1
Mahmoud
29
Jeddah
20000.0
2
Ahmed
27
Jeddah
15000.0
3
Mohammed
31
Egypt
20000.0
4
Ibrahim
24
Egypt
65000.0
**************************************************
Mahmoud
Ahmed
Mohammed
Ibrahim
44.18
Methods:
Method Description/Output
init(cConString)Open Database.
close() Close Database.
execute(cSQL)Execute Query.
example:
load"stdlib.ring"
oPostgreSQL newPostgreSQL("user=postgres password=sa dbname = mahdb")
See"Test the PostgreSQL Class Methods"
oPostgreSQL {
sqlCREATE TABLE COMPANY_TEST("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"AGE INT NOT NULL,"
"ADDRESS CHAR(50),"
"SALARY REAL );"
(continues on next page)
44.18. PostgreSQL Class 348

Ring Documentation, Release 1.14
(continued from previous page)
execute(sql)
sqlINSERT INTO COMPANY_TEST (ID,NAME,AGE,ADDRESS,SALARY)
"VALUES (1,Mahmoud, 29,Jeddah, 20000.00 );
"INSERT INTO COMPANY_TEST (ID,NAME,AGE,ADDRESS,SALARY)
"VALUES (2,Ahmed, 27,Jeddah, 15000.00 );
"INSERT INTO COMPANY_TEST (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (3,Mohammed, 31,Egypt, 20000.00 );"
"INSERT INTO COMPANY_TEST (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (4,Ibrahim, 24,Egypt, 65000.00 );"
execute(sql)
?"select *from COMPANY_TEST")
?" *",50)
close()
}
Output:
Test the PostgreSQL Class Methods
id
name
age
address
salary
1
Mahmoud
29
Jeddah
20000
2
Ahmed
27
Jeddah
15000
3
Mohammed
31
Egypt
20000
4
Ibrahim
24
Egypt
65000
**************************************************
44.18. PostgreSQL Class 349

Ring Documentation, Release 1.14
44.19
Methods:
Method Description/Output
md5(cString) Calculate the MD5 hash.
sha1(cString) Calculate the SHA1 hash.
sha256(cString) Calculate the SHA256 hash.
sha512(cString) Calculate the SHA512 hash.
sha384(cString) Calculate the SHA384 hash.
sha224(cString) Calculate the SHA224 hash.
encrypt(cString,cKey,cIV)Encrypts the data using the Blowsh algorithm.
decrypt(cString,cKey,cIV)Decrypt the data encrypted using the Encrypt() method.
randbytes(nSize) Generate a string of pseudo-random bytes.
example:
Load"stdlib.ring"
oSecurity newsecurity
See"Test the security Class Methods"
oSecurity {
seemd5("hello")
sha1("hello")"hello")
sha512("hello")"hello")
sha256("hello")
list=:15="" forxin cKey= next
list=:8" forxin cIV= next
cCipher"hello",cKey,cIV)
seecCipher
}
44.20
Methods:
•
•
example:
Load"stdlib.ring"
ointernet newinternet
See"Test the internet Class Methods"
ointernet {
seedownload("www.ring-lang.sf.net")
}
44.19. Security Class 350

CHAPTER
FORTYFIVE
DESKTOP, WEBASSEMBLY AND MOBILE DEVELOPMENT USING
RINGQT
In this chapter we will learn how to use the Qt framework classes in our Ring applications to create Desktop, We-
bAssembly and Mobile Applications.
45.1
In this example we will create an application to ask the user about his/her name. When the user type the name in the
textbox then click on “Say Hello” button, the textbox value will be updated by adding “Hello ” to the name.
load"guilib.ring"
oApp newqApp {
win1 newqWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
label1 newqLabel(win1) {
settext("What is your name ?")
setGeometry(10,20,350,30)
setalignment(Qt_AlignHCenter)
}
btn1 newqPushButton(win1) {
setGeometry(10,200,100,30)
settext("Say Hello")
setclickevent("pHello()")
}
btn1 newqPushButton(win1) {
setGeometry(150,200,100,30)
settext("Close")
setclickevent("pClose()")
}
lineedit1 newqLineEdit(win1) {
setGeometry(10,100,350,30)
}
show()
(continues on next page)
351

Ring Documentation, Release 1.14
(continued from previous page)
}
exec()
}
FuncpHello
lineedit1.settext(Hello
FuncpClose
oApp.quit()
Program Output:
At rst we type the name in the textbox
Then we click on the say hello button
45.1. The First GUI Application 352

Ring Documentation, Release 1.14
45.2
Qt uses Event-Driven and the events loop get the control when we call the exec() method from the qApp class.
Once we call exec(), The events loop starts, and the Widgets starts responding to the different events (Mouse, Key-
board, Timers, etc).
You get the control back again when an event is red and your callback function is called.
Once the execution of your callback function is done, the control go back again to the events loop.
Useful things to remember
(1)
(2)
(3)
Also when our callback function is busy with doing time consuming operations, we can call the ProcessEvents()
method from the qApp class to avoid stoping the GUI.
oApp.processevents()
We can avoid calling the exec() method, and create our main loop
It's not recommended to do that, It's just an option.
# Instead of calling the exec() method
while
oApp.processevents() # Respond to GUI Events
# More Thing to do, We have the control!
# .....
end
45.3
The next example is just an upgrade to the previous application to use the vertical layout.
Load"guilib.ring"
MyApp NewqApp {
win1 newqWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,400,130)
label1 newqLabel(win1) {
settext("What is your name ?")
setGeometry(10,20,350,30)
setalignment(Qt_AlignHCenter)
}
btn1 newqpushbutton(win1) {
setGeometry(10,200,100,30)
settext("Say Hello")
setclickevent("pHello()")
}
btn2 newqpushbutton(win1) {
(continues on next page)
45.2. The Events Loop 353

Ring Documentation, Release 1.14
(continued from previous page)
setGeometry(150,200,100,30)
settext("Close")
setclickevent("pClose()")
}
lineedit1 newqlineedit(win1) {
setGeometry(10,100,350,30)
}
layout1 newqVBoxLayout() {
addwidget(label1)
addwidget(lineedit1)
addwidget(btn1)
addwidget(btn2)
}
win1.setlayout(layout1)
show()
}
exec()
}
FuncpHello
lineedit1.settext(Hello
FuncpClose
MyApp.quit()
The application during the runtime!
45.4
In this example we will use the QTextEdit Class
Load"guilib.ring"
NewqApp {
win1 newqWidget() {
setwindowtitle("QTextEdit Class")
setGeometry(100,100,500,500)
(continues on next page)
45.4. Using the QTextEdit Class 354

Ring Documentation, Release 1.14
(continued from previous page)
newqtextedit(win1) {
setGeometry(10,10,480,480)
}
show()
}
exec()
}
During the runtime we can paste rich text in the qtextedit widget
45.4. Using the QTextEdit Class 355

Ring Documentation, Release 1.14
45.5
In this example we will use the QListWidget Class
Load"guilib.ring"
NewqApp {
win1 newqWidget() {
setGeometry(100,100,400,400)
list1 newqlistwidget(win1) {
setGeometry(150,100,200,200)
alist"one","two","three","four","five"]
forxinalist additem(x) next
setcurrentrow(3,2)
win1.setwindowtitle("Items Count :
}
btn1 newqpushbutton(win1) {
setGeometry(10,200,100,30)
settext("selected item")
setclickevent("pWork()")
}
btn2 newqpushbutton(win1) {
setGeometry(10,240,100,30)
settext("Delete item")
setclickevent("pWork2()")
}
show()
}
exec()
}
funcpWork
btn1.settext(string(list1.currentrow()))
funcpWork2
list1 {
takeitem(currentrow())
}
The application during the runtime
45.5. Using the QListWidget Class 356

Ring Documentation, Release 1.14
Another Example:
Load"guilib.ring"
NewqApp {
win1 newqWidget() {
setGeometry(100,100,500,400)
list1 newqlistwidget(win1) {
setGeometry(150,100,200,200)
alist"one","two","three","four","five"]
forxinalist additem(x) next
setcurrentrow(3,2)
win1.setwindowtitle("Items Count :
}
btn1 newqpushbutton(win1) {
setGeometry(10,200,100,30)
settext("selected item")
setclickevent("pWork()")
}
btn2 newqpushbutton(win1) {
setGeometry(10,240,100,30)
(continues on next page)
45.5. Using the QListWidget Class 357

Ring Documentation, Release 1.14
(continued from previous page)
settext("Delete item")
setclickevent("pWork2()")
}
show()
}
exec()
}
funcpWork
nbrOfItems
curItemNbr
curValue
win1.setwindowtitle(After Select - NbrOfItems:
"
btn1.settext(string(list1.currentrow() )
list1.item(list1.currentrow()).text() )
funcpWork2
list1 {
takeitem(currentrow())
nbrOfItems
curItemNbr
curValue
win1.setwindowtitle("After Delete - NbrOfItems:
""
}
45.6
In this example we will learn how to use the QTreeView widget to represent the File System
Load"guilib.ring"
NewqApp {
win1 NewqWidget() {
setwindowtitle("Using QTreeView and QFileSystemModel")
setGeometry(100,100,500,400)
Newqtreeview(win1) {
setGeometry(00,00,500,400)
oDir newQDir()
ofile newQFileSystemModel()
ofile.setrootpath(oDir.currentpath())
(continues on next page)
45.6. Using QTreeView and QFileSystemModel 358

Ring Documentation, Release 1.14
(continued from previous page)
setmodel(ofile)
}
show()
}
exec()
}
The application during the runtime
45.7
In this example we will learn about using the QTreeWidget and QTreeWidgetItem classes
Load"guilib.ring"
NewqApp {
win1 newqWidget() {
setwindowtitle("TreeWidget")
setGeometry(100,100,400,400)
(continues on next page)
45.7. Using QTreeWidget and QTreeWidgetItem 359

Ring Documentation, Release 1.14
(continued from previous page)
layout1 newqvboxlayout()
tree1 newqtreewidget(win1) {
setGeometry(00,00,400,400)
setcolumncount(1)
myitem newqtreewidgetitem()
myitem.settext(0,"The First Step")
addtoplevelitem(myitem)
forx to10
myitem2 newqtreewidgetitem()
myitem2.settext(0,"hello"+x)
myitem.addchild(myitem2)
fory to10
myitem3 newqtreewidgetitem()
myitem3.settext(0,"hello"+x)
myitem2.addchild(myitem3)
next
next
setheaderlabel("Steps Tree")
}
layout1.addwidget(tree1)
setlayout(layout1)
show()
}
exec()
}
The application during the runtime
45.7. Using QTreeWidget and QTreeWidgetItem 360

Ring Documentation, Release 1.14
45.8
In this example we will learn about using the QComboBox class
Load"guilib.ring"
NewqApp {
win1 newqWidget() {
setwindowtitle("Using QComboBox")
setGeometry(100,100,400,400)
NewQComboBox(win1) {
setGeometry(150,100,200,30)
alist"one","two","three","four","five"]
forxinaList additem(x,0) next
}
show()
}
exec()
}
The application during the runtime
45.8. Using QComboBox Class 361

Ring Documentation, Release 1.14
45.9
In this example we will learn about using the QMenuBar class
Load"guilib.ring"
MyApp NewqApp {
win1 newqWidget() {
setwindowtitle("Using QMenubar")
setGeometry(100,100,400,400)
menu1 newqmenubar(win1) {
sub1"File")
sub2"Edit")
sub3"Help")
sub1 {
oAction newqAction(win1) {
settext("New")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Open")
}
(continues on next page)
45.9. Creating Menubar 362

Ring Documentation, Release 1.14
(continued from previous page)
addaction(oAction)
oAction newqAction(win1) {
settext("Save")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Save As")
}
addaction(oAction)
addseparator()
oAction newqaction(win1) {
settext("Exit")
setclickevent("myapp.quit()")
}
addaction(oAction)
}
sub2 {
oAction newqAction(win1) {
settext("Cut")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Copy")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Paste")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
settext("Select All")
}
addaction(oAction)
}
sub3 {
oAction newqAction(win1) {
settext("Reference")
}
addaction(oAction)
sub4"Sub Menu")
sub4 {
oAction newqAction(win1) {
settext("Website")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Forum")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Blog")
}
addaction(oAction)
}
addseparator()
oAction newqAction(win1) {
(continues on next page)
45.9. Creating Menubar 363

Ring Documentation, Release 1.14
(continued from previous page)
settext("About")
}
addaction(oAction)
}
}
show()
}
exec()
}
The application during the runtime
45.10
Example:
load"guilib.ring"
newqApp {
win newqwidget() {
setwindowtitle("Context Menu")
resize(400,400)
myfilter newqAllEvents(win) {
setContextmenuEvent("mymenu()")
(continues on next page)
45.10. Context Menu 364

Ring Documentation, Release 1.14
(continued from previous page)
}
installeventfilter(myfilter)
show()
}
exec()
}
funcmymenu
newqMenu(win) {
oAction newqAction(win) {
settext("new")
SetCLickevent("See :New")
}
addaction(oAction)
oAction newqAction(win) {
settext("open")
SetCLickevent("See :Open")
}
addaction(oAction)
oAction newqAction(win) {
settext("save")
SetCLickevent("See :Save")
}
addaction(oAction)
oAction newqAction(win) {
settext("close")
SetCLickevent("See :Close")
}
addaction(oAction)
oCursor newqCursor()
exec(oCursor.pos())
}
45.11
In this example we will learn about using the QToolBar class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QToolbar")
setGeometry(100,100,600,400)
abtns
newqpushbutton(win1) { settext("Add") } ,
newqpushbutton(win1) { settext("Edit") } ,
newqpushbutton(win1) { settext("Find") } ,
newqpushbutton(win1) { settext("Delete") } ,
newqpushbutton(win1) { settext("Exit")
(continues on next page)
45.11. Creating Toolbar 365

Ring Documentation, Release 1.14
(continued from previous page)
setclickevent("win1.close()")
˓→}
]
tool1 newqtoolbar(win1) {
forxinabtns addwidget(x) addseparator() next
setmovable(true)
setGeometry(0,0,500,30)
setFloatable(true)
}
show()
}
exec()
}
The application during the runtime
45.11. Creating Toolbar 366

Ring Documentation, Release 1.14
45.12
In this example we will learn about using the QStatusBar class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QStatusbar")
setGeometry(100,100,400,400)
status1 newqstatusbar(win1) {
showmessage("Ready!",0)
}
setstatusbar(status1)
show()
}
exec()
}
The application during the runtime
45.12. Creating StatusBar 367

Ring Documentation, Release 1.14
45.13
In this example we will learn about using the QDockWidget class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QDockWidget")
setGeometry(100,100,400,400)
label1 newqlabel(win1) {
settext("Hello")
setGeometry(300,300,100,100)
}
label2 newqlabel(win1) {
settext("How are you ?")
setGeometry(100,100,100,100)
}
dock1 newqdockwidget(win1,0) {
setwidget(label1)
SetAllowedAreas(1)
}
dock2 newqdockwidget(win1,0) {
setwidget(label2)
SetAllowedAreas(2)
}
adddockwidget(Qt_LeftDockWidgetArea,dock1,Qt_Horizontal)
adddockwidget(Qt_LeftDockWidgetArea,dock2,Qt_Vertical)
show()
}
exec()
}
The application during the runtime
45.13. Using QDockWidget 368

Ring Documentation, Release 1.14
45.14
In this example we will learn about using the QTabWidget class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QTabWidget")
setGeometry(100,100,400,400)
page1 newqwidget() {
newqpushbutton(page1) {
settext("The First Page")
}
}
page2 newqwidget() {
newqpushbutton(page2) {
settext("The Second Page")
}
}
(continues on next page)
45.14. Using QTabWidget 369

Ring Documentation, Release 1.14
(continued from previous page)
page3 newqwidget() {
newqpushbutton(page3) {
settext("The Third Page")
}
}
tab1 newqtabwidget(win1) {
inserttab(0,page1,"Page 1")
inserttab(1,page2,"Page 2")
inserttab(2,page3,"Page 3")
setGeometry(100,100,400,400)
}
status1 newqstatusbar(win1) {
showmessage("Ready!",0)
}
setstatusbar(status1)
showMaximized()
}
exec()
}
The application during the runtime
45.14. Using QTabWidget 370

Ring Documentation, Release 1.14
45.15
In this example we will learn about using the QTableWidget class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,1100,370)
setwindowtitle("Using QTableWidget")
Table1 newqTableWidget(win1) {
setrowcount(10) setcolumncount(10)
setGeometry(0,0,800,400)
setselectionbehavior(QAbstractItemView_SelectRows)
forx to10
fory to10
item1 newqtablewidgetitem("R"+X+"C"+Y)
setitem(x-1,y-1,item1)
next
next
}
setcentralwidget(table1)
show()
}
exec()
}
The application during the runtime
45.15. Using QTableWidget 371

Ring Documentation, Release 1.14
45.16
In this example we will learn about using the QProgressBar class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,600,150)
setwindowtitle("Using QProgressBar")
forx to100step10
newqprogressbar(win1) {
setGeometry(100,x,350,30)
setvalue(x)
}
next
show()
}
exec()
}
The application during the runtime
45.17
In this example we will learn about using the QSpinBox class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,450,260)
setwindowtitle("Using QSpinBox")
newqspinbox(win1) {
setGeometry(50,100,350,30)
setvalue(50)
}
show()
(continues on next page)
45.16. Using QProgressBar 372

Ring Documentation, Release 1.14
(continued from previous page)
}
exec()
}
The application during the runtime
45.18
In this example we will learn about using the QSlider class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,500,400)
setwindowtitle("Using QSlider")
newqslider(win1) {
setGeometry(100,100,50,130)
settickinterval(50)
}
newqslider(win1) {
setGeometry(100,250,250,30)
settickinterval(50)
setorientation(Qt_Horizontal)
}
show()
}
(continues on next page)
45.18. Using QSlider 373

Ring Documentation, Release 1.14
(continued from previous page)
exec()
}
The application during the runtime
45.19
In this example we will learn about using the QDateEdit class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QDateEdit")
setGeometry(100,100,250,100)
newqdateedit(win1) {
setGeometry(20,40,220,30)
}
show()
}
exec()
}
45.19. Using QDateEdit 374

Ring Documentation, Release 1.14
The application during the runtime
45.20
In this example we will learn about using the QDial class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,450,500)
setwindowtitle("Using QDial")
newqdial(win1) {
setGeometry(100,100,250,300)
}
show()
}
exec()
}
The application during the runtime
45.20. Using QDial 375

Ring Documentation, Release 1.14
Another Example
Load"guilib.ring"
NewqApp {
win1 newqMainWindow()
{
setGeometry(100,100,450,500)
setwindowtitle("Using QDial")
button1 newQPushButton(win1){
setGeometry(100,350,100,30)
settext("Increment")
setClickEvent("pIncrement()")
}
button2 newQPushButton(win1){
setGeometry(250,350,100,30)
settext("Decrement")
setClickEvent("pDecrement()")
}
(continues on next page)
45.20. Using QDial 376

Ring Documentation, Release 1.14
(continued from previous page)
pdial newqdial(win1) {
setGeometry(100,50,250,300)
setNotchesVisible(true)
setValue(50)
SetValueChangedEvent("pDialMove()")
}
lineedit1 newqlineedit(win1) {
setGeometry(200,400,50,30)
setalignment(Qt_AlignHCenter)
settext(string(pdial.value()))
setreturnPressedEvent("pPress()")
}
show()
}
exec()
}
funcpIncrement
pdial{val=value()}
pdial.setvalue(val+1)
lineedit1{settext(string(val+1))}
funcpDecrement
pdial{val=value()}
pdial.setvalue(val-1)
lineedit1{settext(string(val-1))}
funcpPress
lineedit1{val=text()}
pdial.setvalue(number(val))
funcpDialMove
lineedit1.settext(""+pdial.value())
45.20. Using QDial 377

Ring Documentation, Release 1.14
45.21
In this example we will learn about using the QWebView class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QWebView")
myweb newqwebview(win1) {
setGeometry(10,10,600,600)
loadpage(newqurl("http://google.com"))
}
setcentralwidget(myweb)
showMaximized()
}
exec()
}
45.21. Using QWebView 378

Ring Documentation, Release 1.14
The application during the runtime
45.22
In this example we will learn about using the QCheckBox class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QCheckBox")
newqcheckbox(win1) {
setGeometry(100,100,100,30)
settext("New Customer!")
}
showMaximized()
}
exec()
}
The application during the runtime
45.22. Using QCheckBox 379

Ring Documentation, Release 1.14
Another Example:
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,400,300)
setwindowtitle("Using QCheckBox")
### 0-Unchecked 1-Checked
CheckBox newqcheckbox(win1) {
setGeometry(100,100,160,30)
settext("New Customer!")
setclickedEvent("HandleClickEvent()")
}
show()
}
exec()
}
FuncHandleClickEvent
ifCheckBox.isChecked()
CheckBox.settext("New Customer. Check 1-ON")
else
CheckBox.settext("New Customer. Check 0-OFF")
ok
45.22. Using QCheckBox 380

Ring Documentation, Release 1.14
45.23
In this example we will learn about using the QRadioButton and QButtonGroup classes
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QRadioButton")
newqradiobutton(win1) {
setGeometry(100,100,100,30)
settext("One")
}
newqradiobutton(win1) {
setGeometry(100,150,100,30)
settext("Two")
}
newqradiobutton(win1) {
setGeometry(100,200,100,30)
settext("Three")
}
group2 newqbuttongroup(win1) {
btn4 newqradiobutton(win1) {
setGeometry(200,150,100,30)
settext("Four")
}
btn5 newqradiobutton(win1) {
setGeometry(200,200,100,30)
settext("Five")
}
addbutton(btn4,0)
addbutton(btn5,0)
}
showMaximized()
}
exec()
}
The application during the runtime
45.23. Using QRadioButton and QButtonGroup 381

Ring Documentation, Release 1.14
45.24
In this example we will learn about creating Hyperlink using the QLabel class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QLabel - Hyperlink")
newqlabel(win1) {
setGeometry(100,100,100,30)
setopenexternallinks( true)
settext(<aref="http://google.com">Google</a>)
}
showMaximized()
}
exec()
}
The application during the runtime
45.24. Adding Hyperlink to QLabel 382

Ring Documentation, Release 1.14
45.25
In this example we will learn about using the QVideoWidget and QMediaPlayer classes to play a group of movies
from different positions at the same time
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QVideoWidget")
btn1 newqpushbutton(win1) {
setGeometry(0,0,100,30)
settext("play")
setclickevent("player.play() player2.play()
player3.play() player4.play()")
}
videowidget newqvideowidget(win1) {
setGeometry(50,50,600,300)
setstylesheet("background-color: black")
}
videowidget2 newqvideowidget(win1) {
setGeometry(700,50,600,300)
setstylesheet("background-color: black")
}
videowidget3 newqvideowidget(win1) {
setGeometry(50,370,600,300)
setstylesheet("background-color: black")
}
(continues on next page)
45.25. QVideoWidget and QMediaPlayer 383

Ring Documentation, Release 1.14
(continued from previous page)
videowidget4 newqvideowidget(win1) {
setGeometry(700,370,600,300)
setstylesheet("background-color: black")
}
player newqmediaplayer() {
setmedia(newqurl("1.mp4"))
setvideooutput(videowidget)
setposition(35 *60*1000)
}
player2 newqmediaplayer() {
setmedia(newqurl("2.mp4"))
setvideooutput(videowidget2)
setposition(23 *60*1000)
}
player3 newqmediaplayer() {
setmedia(newqurl("3.mp4"))
setvideooutput(videowidget3)
setposition(14.22 *60*1000)
}
player4 newqmediaplayer() {
setmedia(newqurl("4.avi"))
setvideooutput(videowidget4)
setposition(8 *60*1000)
}
showfullscreen()
}
exec()
}
The application during the runtime
45.25. QVideoWidget and QMediaPlayer 384

Ring Documentation, Release 1.14
45.26
In this example we will learn about using the QFrame class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Using QFrame")
forx to10
frame1 newqframe(win1,0) {
setGeometry(100,20+50 *x,400,30)
setframestyle(QFrame_Raised
}
next
showMaximized()
}
exec()
}
The application during the runtime
45.26. Using QFrame 385

Ring Documentation, Release 1.14
45.27
In this example we will learn about displaying an image using the QLabel widget
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QLabel - Display image")
newqlabel(win1) {
image newqpixmap("b:/mahmoud/photo/advice.jpg")
setpixmap(image)
setGeometry(0,0,image.width(),image.height())
(continues on next page)
45.27. Display Image using QLabel 386

Ring Documentation, Release 1.14
(continued from previous page)
}
showMaximized()
}
exec()
}
The application during the runtime
45.27. Display Image using QLabel 387

Ring Documentation, Release 1.14
45.28
In this example we will learn about creating menubar and setting the window stylesheet
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("Menubar")
menu1 newqmenubar(win1) {
sub1"File")
sub1 {
oAction newqAction(win1) {
settext("New")
setenabled(false)
}
addaction(oAction)
oAction newqAction(win1) {
settext("Open")
setcheckable(true)
setchecked(true)
setstatustip("open new file")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Save")
}
addaction(oAction)
oAction newqAction(win1) {
settext("Save As")
}
addaction(oAction)
addseparator()
oAction newqaction(win1)
oAction.settext("Exit")
oAction.setclickevent("myapp.quit()")
addaction(oAction)
}
}
status1 newqstatusbar(win1) {
showmessage("Ready!",0)
}
setmenubar(menu1)
setmousetracking(true)
setstatusbar(status1)
setStyleSheet("color: black; selection-color: black;
selection-background-color:white ;
background: QLinearGradient(x1:, y1:, x2:, y2:,
stop: #eef, stop: 1 #ccf);")
showmaximized()
}
exec()
(continues on next page)
45.28. Menubar and StyleSheet Example 388

Ring Documentation, Release 1.14
(continued from previous page)
}
The application during the runtime
45.29
In this example we will learn about using QLineEdit Events and displaying a Messagebox
Load"guilib.ring"
MyApp NewqApp {
win1 newqWidget() {
setwindowtitle("Welcome")
setGeometry(100,100,400,300)
label1 newqLabel(win1) {
settext("What is your name ?")
setGeometry(10,20,350,30)
setalignment(Qt_AlignHCenter)
}
btn1 newqpushbutton(win1) {
setGeometry(10,200,100,30)
settext("Say Hello")
setclickevent("pHello()")
}
btn1 newqpushbutton(win1) {
setGeometry(150,200,100,30)
settext("Close")
setclickevent("pClose()")
}
(continues on next page)
45.29. QLineEdit Events and QMessageBox 389

Ring Documentation, Release 1.14
(continued from previous page)
lineedit1 newqlineedit(win1) {
setGeometry(10,100,350,30)
settextchangedevent("pChange()")
setreturnpressedevent("penter()")
}
show()
}
exec()
}
FuncpHello
lineedit1.settext(Hello
FuncpClose
MyApp.quit()
FuncpChange
win1 { setwindowtitle( lineedit1.text() ) }
FuncpEnter
newqmessagebox(win1) {
setwindowtitle("Thanks")
settext("Hi
setstylesheet("background-color : white")
show()
}
The application during the runtime
45.29. QLineEdit Events and QMessageBox 390

Ring Documentation, Release 1.14
45.30
Each Qt signal can be used in RingQt, just add Set before the signal name and add event after the signal name to get
the method that can be used to determine the event code.
For example the QProgressBar class contains a signal named valueChanged() To use it just use the function setVal-
ueChangedEvent()
Example:
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QProgressBar valueChanged Event")
progress1 newqprogressbar(win1) {
setGeometry(100,100,350,30)
setvalue(10)
setvaluechangedevent("pChange()")
}
newqpushbutton(win1) {
setGeometry(10,10,100,30)
settext("increase")
setclickevent("pIncrease()")
}
showMaximized()
}
(continues on next page)
45.30. Other Widgets Events 391

Ring Documentation, Release 1.14
(continued from previous page)
exec()
}
funcpIncrease
progress1 { setvalue(value()+1) }
funcpchange
win1.setwindowtitle("value :
The application during the runtime
Another example for the stateChanged event of the QCheckBox class
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setwindowtitle("QCheckBox")
newqcheckbox(win1) {
setGeometry(100,100,100,30)
settext("New Customer!")
setstatechangedevent("pchange()")
}
showMaximized()
}
exec()
}
FuncpChange
newqMessageBox(Win1) {
setWindowTitle("Checkbox")
settext("State Changed!")
show()
}
The application during the runtime
45.30. Other Widgets Events 392

Ring Documentation, Release 1.14
45.31
In this example we will learn about using the QTimer class
Load"guilib.ring"
newqApp {
win1 newqwidget() {
setgeometry(100,100,200,70)
setwindowtitle("Timer")
label1 newqlabel(win1) {
setgeometry(10,10,200,30)
settext(thetime())
}
newqtimer(win1) {
setinterval(1000)
settimeoutevent("pTime()")
start()
}
show()
}
exec()
}
funcptime
label1.settext(thetime())
Functhetime
return"Time :
The application during the runtime
45.31. Using the QTimer Class 393

Ring Documentation, Release 1.14
45.32
In this example we will learn about using the “animated” QProgressBar class and Timer
###------------------------------------
### ProgressBar and Timer Example
Load"guilib.ring"
newqApp
{
win1 newqwidget()
{
setgeometry(100,100,400,100)
setwindowtitle("Timer and ProgressBar")
LabelMan newqlabel(win1)
{
setgeometry(10,10,200,30)
settext(theTime()) ### ==>> func
}
TimerMan newqtimer(win1)
{
setinterval(1000)
settimeoutevent("pTime()") ### ==>> func
start()
}
BarMan newqprogressbar(win1)
{
setGeometry(100,50,300,10) ### Position X y, Length, Thickness
setvalue(0) ### Percent filled
}
show()
}
exec()
}
funcpTime
LabelMan.settext(theTime()) ### ==>> func
Increment
ifBarMan.value()= ### ProgressBar start over.
BarMan.setvalue(0)
ok
(continues on next page)
45.32. Using QProgressBar and Timer 394

Ring Documentation, Release 1.14
(continued from previous page)
BarMan{ setvalue(value()
FunctheTime
return"Time :
45.33
In this example we will learn about displaying and scaling an image so that it looks “animated” using the QLabel
widget
Load"guilib.ring"
#----------------------------------------------------
# REQUIRES: image = "C:\RINGin\stock.jpg"
# imageStock: start dimensions for growing image
imageW
###----------------------------------------------------
### Window and Box Size dimensions
WinWidth
BoxWidth8080
###----------------------------------------------------
Newqapp {
win1 newqwidget() {
setgeometry(50,50, WinWidth,WinHeight)
setwindowtitle("Animated Image - Display Image Scaled and Resized")
imageStock newqlabel(win1) {
image newqpixmap("C: \RINGin\stock.jpg")
AspectRatio
imageW
imageH
### Size-H, Size-V, Aspect, Transform
setpixmap(image.scaled(imageW , imageH ,0,0))
(continues on next page)
45.33. Display Scaled Image using QLabel 395

Ring Documentation, Release 1.14
(continued from previous page)
PosLeft
PosTop
setGeometry(PosLeft,PosTop,imageW,imageH)
}
TimerMan newqtimer(win1) {
setinterval(100) ### interval 100 millisecs.
settimeoutevent("pTime()") ### ==>> func
start()
}
show()
}
exec()
}
###------------------------------------------------------
### Fuction TimerMan: calling interval 100 milliseconds
funcpTime
### Stop Timer when image is size of Window area
ifimageW
TimerMan.stop()
imageStock.clear() ### Will clear the image
ok
### Grow image
imageW=
imageH
### Scaled Image: Size-H, Size-V, Aspect, Transform
imageStock.setpixmap(image.scaled(imageW , imageH ,0,0))
### Center the image
PosLeft
PosTop
imageStock.setGeometry(PosLeft,PosTop,imageW,imageH)
45.34
Example
Load"guilib.ring"
Newqapp {
win1 newqwidget() {
setwindowtitle("open file")
setgeometry(100,100,400,400)
newqpushbutton(win1) {
setgeometry(10,10,200,30)
(continues on next page)
45.34. Using the QFileDialog Class 396

Ring Documentation, Release 1.14
(continued from previous page)
settext("open file")
setclickevent("pOpen()")
}
show()
}
exec()
}
FuncpOpen
newqfiledialog(win1) {
cName"open file","c: \","source files( *.ring)")
win1.setwindowtitle(cName)
}
The application during the runtime
45.35
In this example we will learn about drawing using the QPainter class
Load"guilib.ring"
Newqapp {
win1 newqwidget() {
setwindowtitle("Drawing using QPainter")
setgeometry(100,100,500,500)
label1 newqlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
newqpushbutton(win1) {
(continues on next page)
45.35. Drawing using QPainter 397

Ring Documentation, Release 1.14
(continued from previous page)
setgeometry(200,400,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
Funcdraw
p1 newqpicture()
color newqcolor() {
setrgb(0,0,255,255)
}
pen newqpen() {
setcolor(color)
setwidth(10)
}
newqpainter() {
begin(p1)
setpen(pen)
drawline(500,150,950,450)
drawline(950,550,500,150)
endpaint()
}
label1 { setpicture(p1) show() }
The application during the runtime
45.35. Drawing using QPainter 398

Ring Documentation, Release 1.14
45.36
In this example we will learn how to print to PDF le using QPrinter
Load"guilib.ring"
newqApp {
win1 newqwidget() {
setwindowtitle("Printer")
setgeometry(100,100,500,500)
myweb newqwebview(win1) {
setgeometry(100,100,1000,500)
loadpage(newqurl("http://google.com"))
}
newqpushbutton(win1) {
setGeometry(20,20,100,30)
settext("Print")
setclickevent("print()")
}
(continues on next page)
45.36. Printing using QPrinter 399

Ring Documentation, Release 1.14
(continued from previous page)
showmaximized()
}
exec()
}
funcprint
printer1 newqPrinter(0) {
setoutputformat(1) # 1 = pdf
setoutputfilename("test.pdf")
painter newqpainter() {
begin(printer1)
myfont newqfont("Times",50,-1,0)
setfont(myfont)
drawtext(100,100,"test")
printer1.newpage()
drawtext(100,100,"test2")
endpaint()
}
}
printer1 newqPrinter(0) {
setoutputformat(1)
setoutputfilename("test2.pdf")
myweb.print(printer1,ystem("test2.pdf"))
myweb.show()
}
system ("test.pdf")
45.37
In this example we will learn how to use the QPrintPreviewDialog class.
Example:
load"guilib.ring"
newqApp {
win1 newqwidget() {
setwindowtitle("Printer Preview Dialog")
setgeometry(100,100,800,880)
printer1 newqPrinter(0)
show()
oPreview newqPrintPreviewDialog(printer1) {
setParent(win1)
move(10,10)
setPaintrequestedevent("printPreview()")
exec()
}
}
exec()
}
funcprintPreview
(continues on next page)
45.37. Using QPrintPreviewDialog 400

Ring Documentation, Release 1.14
(continued from previous page)
printer1 {
painter newqpainter() {
begin(printer1)
myfont newqfont("Times",50,-1,0)
setfont(myfont)
drawtext(100,100,"Test - Page (1)")
printer1.newpage()
drawtext(100,100,"Test - Page (2)")
printer1.newpage()
myfont2 newqfont("Times",14,-1,0)
setfont(myfont2)
forx to30
drawtext(100,100+(20 *x),"Number :
next
endpaint()
}
}
Screen Shot:
45.37. Using QPrintPreviewDialog 401

Ring Documentation, Release 1.14
45.37. Using QPrintPreviewDialog 402

Ring Documentation, Release 1.14
45.38
The next example demonstrates how to create more than one window
Load"guilib.ring"
app1 newqapp {
win1 newqwidget() {
setwindowtitle("First")
setgeometry(100,100,500,500)
newqpushbutton(win1) {
setgeometry(100,100,100,30)
settext("close")
setclickevent("app1.quit()")
}
newqpushbutton(win1) {
setgeometry(250,100,100,30)
settext("Second")
setclickevent("second()")
}
showmaximized()
}
exec()
}
funcsecond
win2 newqwidget() {
setwindowtitle("Second")
setgeometry(100,100,500,500)
setwindowflags(Qt_dialog)
show()
}
The application during the runtime
45.38. Creating More than one Window 403

Ring Documentation, Release 1.14
45.39
Example:
Load"guilib.ring"
newqapp {
win1 newqwidget() {
setwindowtitle("play sound!") show()
}
newqmediaplayer() {
setmedia(newqurl("footstep.wav"))
setvolume(50) play()
}
exec()
}
45.40
Example:
Load"guilib.ring"
oApp newmyapp { start() }
ClassMyApp
oColor win1
Funcstart
(continues on next page)
45.39. Playing Sound 404

Ring Documentation, Release 1.14
(continued from previous page)
myapp newqapp
win1 newqMainWindow() {
setwindowtitle("Color Dialog")
setgeometry(100,100,400,400)
}
newqpushbutton(win1) {
setgeometry(10,10,100,30)
settext("Get Color")
setclickevent("oApp.pColor()")
}
win1.show()
myapp.exec()
FuncpColor
myobj newqcolordialog()
aColor
r=acolor[1]=acolor[2]=acolor[3]
win1.setstylesheet("background-color: rgb("+r+",+,")")
The application during the runtime
45.40. Using the QColorDialog Class 405

Ring Documentation, Release 1.14
45.41
In this example we will learn about using the qLCDNumber class
Load"guilib.ring"
NewqApp
{
win1 newqWidget()
{
setwindowtitle("LCD Number")
setgeometry(100,100,250,120)
newqLCDNumber(win1)
{
setgeometry(10,10,100,40)
display(100)
}
newqLCDNumber(win1)
{
setgeometry(10,60,100,40)
display(80)
}
show()
}
exec()
}
The application during the runtime
45.41. Using qLCDNumber Class 406

Ring Documentation, Release 1.14
45.42
Load"guilib.ring"
newqApp {
win1 newqWidget()
{
label1 newqLabel(win1)
{
setText("Welcome")
setgeometry(10,10,200,50)
setstylesheet("color: purple ; font-size: 30pt;")
}
newqTimer(win1)
{
setInterVal(10)
setTimeOutEvent("pMove()")
start()
}
setWindowTitle("Movable Label")
setgeometry(100,100,600,80)
setStyleSheet("background-color: white;")
show()
}
exec()
}
FuncpMove
label1
{
move(x()+1,y())
ifx()
move(10,y())
ok
}
The application during the runtime
45.42. Movable Label Example 407

Ring Documentation, Release 1.14
45.43
In this section we will learn how to check the output of the Message box
Load"guilib.ring"
newqApp {
win1 newqWidget()
{
label1 newqpushbutton(win1)
{
setText("Test")
setgeometry(10,10,200,50)
setstylesheet("color: purple ; font-size: 30pt;")
setclickevent("pWork()")
}
setWindowTitle("Messagebox")
setgeometry(100,100,600,80)
setStyleSheet("background-color: white;")
show()
}
exec()
}
funcpWork
newqmessagebox(win1)
{
setwindowtitle("messagebox title")
settext("messagebox text")
setInformativeText("Do you want to save your changes?")
setstandardbuttons(QMessageBox_Yes
˓→Close)
result
win1 {
ifresult
setwindowtitle("Yes")
butresult
setwindowtitle("No")
butresult
setwindowtitle("Close")
ok
}
}
The application during the runtime
45.43. QMessagebox Example 408

Ring Documentation, Release 1.14
45.44
In the next example we will learn about using the QInputDialog class
Load"guilib.ring"
NewQApp {
Win1 NewQWidget () {
SetGeometry(100,100,400,400)
SetWindowTitle("Input Dialog")
NewQPushButton(win1)
{
SetText ("Input Dialog")
SetGeometry(100,100,100,30)
SetClickEvent("pWork()")
}
Show()
}
exec()
}
FuncpWork
oInput NewQInputDialog(win1)
{
setwindowtitle("What is your name?")
setgeometry(100,100,400,50)
setlabeltext("User Name")
settextvalue("Mahmoud")
(continues on next page)
45.44. Using QInputDialog Class 409

Ring Documentation, Release 1.14
(continued from previous page)
lcheck
iflCheck win1.setwindowtitle(oInput.textvalue()) ok
}
The application during the runtime
45.45
We have the next functions
SetDialogIcon(cIconFile)
MsgInfo(cTitle,cMessage)
ConfirmMsg(cTitle,cMessage) --> lResult
InputBox(cTitle,cMessage) --> cValue
InputBoxInt(cTitle,cMessage) --> nValue
InputBoxNum(cTitle,cMessage) --> nValue
InputBoxPass(cTitle,cMessage) --> cValue
Example
load"guilib.ring"
newqApp
{
(continues on next page)
45.45. Dialog Functions 410

Ring Documentation, Release 1.14
(continued from previous page)
SetDialogIcon("notepad.png")
msginfo(:Ring,:Welcome)
seeconfirmMsg(:Ring,"Are you sure?")
seeInputBoxNum(:Ring,"Enter Number(double) :")
seeInputBox(:Ring,"Enter Value :")
seeInputBoxInt(:Ring,"Enter Number(int)")
seeInputBoxPass(:Ring,"Enter Password")nl
}
45.46
In this example we will learn how to use the Events Filter to know about KeyPress and Mouse Move Events
Load"guilib.ring"
newqApp {
win1 newqWidget()
{
setWindowTitle("Test using Event Filter!")
setGeometry(100,100,400,400)
setmousetracking(true)
myfilter newqallevents(win1)
myfilter.setKeyPressEvent("pWork()")
myfilter.setMouseButtonPressevent("pClick()")
myfilter.setmousemoveevent("pMove()")
installeventfilter(myfilter)
show()
}
exec()
}
funcpWork
win1.setwindowtitle(KeyPress!
funcpClick
newqmessagebox(win1) {
setgeometry(100,100,400,100)
setwindowtitle("click event!")
settext("x :
"
myfilter.getbutton() )
show()
}
funcpMove
win1.setwindowtitle("Mouse Move , X :
"
The application during the runtime
45.46. KeyPress and Mouse Move Events 411

Ring Documentation, Release 1.14
45.47
In the next example we will learn how to program movable objects where the user can move a label
Load "guilib.ring"
lPress = false
nX = 0
nY = 0
new qApp {
win1 = new qWidget()
{
setWindowTitle("Move this label!")
setGeometry(100,100,400,400)
setstylesheet("background-color:white;")
Label1 = new qLabel(Win1){
setGeometry(100,100,200,50)
setText("Welcome")
setstylesheet("font-size: 30pt")
myfilter = new qallevents(label1)
myfilter.setEnterevent("pEnter()")
(continues on next page)
45.47. Moving Objects using the Mouse 412

Ring Documentation, Release 1.14
(continued from previous page)
myfilter.setLeaveevent("pLeave()")
myfilter.setMouseButtonPressEvent("pPress()")
myfilter.setMouseButtonReleaseEvent("pRelease()")
myfilter.setMouseMoveEvent("pMove()")
installeventfilter(myfilter)
}
show()
}
exec()
}
Func pEnter
Label1.setStyleSheet("background-color: purple; color:white;font-size: 30pt;")
Func pLeave
Label1.setStyleSheet("background-color: white; color:black;font-size: 30pt;")
Func pPress
lPress = True
nX = myfilter.getglobalx()
ny = myfilter.getglobaly()
Func pRelease
lPress = False
pEnter()
Func pMove
nX2 = myfilter.getglobalx()
ny2 = myfilter.getglobaly()
ndiffx = nX2 - nX
ndiffy = nY2 - nY
if lPress
Label1 {
move(x()+ndiffx,y()+ndiffy)
setStyleSheet("background-color: Green;
color:white;font-size: 30pt;")
nX = nX2
ny = nY2
}
ok
The application during the runtime
45.47. Moving Objects using the Mouse 413

Ring Documentation, Release 1.14
45.47. Moving Objects using the Mouse 414

Ring Documentation, Release 1.14
45.47. Moving Objects using the Mouse 415

Ring Documentation, Release 1.14
45.48
Example :
Load"guilib.ring"
NewMyWindow()
newqApp { exec() }
classmywindowfromqwidget
Funcinit
super.init()
setwindowtitle("First Window")
setgeometry(100,100,400,400)
setstylesheet("background-color: purple;")
settooltip("my first window!")
show()
The application during the runtime
45.48. Inheritance from GUI Classes 416

Ring Documentation, Release 1.14
45.49
In the next example we will learn about using the QDesktopWidget class
Load"guilib.ring"
NewqApp {
win1 NewqWidget()
{
resize(400,400)
btn1 newqPushbutton(win1)
{
setText("Center")
move(100,100)
resize(100,30)
setClickEvent("pCenter()")
}
Show()
}
exec()
}
FuncpCenter
(continues on next page)
45.49. Using QDesktopWidget Class 417

Ring Documentation, Release 1.14
(continued from previous page)
oDesktop newqDesktopWidget()
oRect
win1.move((oRect.width()-win1.width())2-win1.Height())/2
win1.show()
The application during the runtime
45.50
The next example rotate text using a Timer.
Load"guilib.ring"
nAngle
Newqapp {
win1 newqwidget() {
setwindowtitle("Rotate Text")
resize(800,600)
label1 newqlabel(win1) {
settext("")
myfilter newqallevents(win1)
myfilter.setMouseButtonPressevent("pClick()")
installeventfilter(myfilter)
(continues on next page)
45.50. Rotate Text 418

Ring Documentation, Release 1.14
(continued from previous page)
}
newqtimer(win1) {
setinterval(50)
settimeoutevent("pTime()")
start()
}
pDraw()
L1 newqVBoxLayout() { AddWidget(Label1) } SetLayout(L1)
showMaximized()
}
exec()
}
FuncpDraw
p1 newqpicture()
color newqcolor() {
setrgb(0,0,255,255)
}
pen newqpen() {
setcolor(color)
setwidth(50)
}
painter newqpainter() {
begin(p1)
setpen(pen)
myfont
myfont.setpointsize(50)
setfont(myfont)
rotate(nAngle)
drawtext(350,0 *nAngle,"welcome")
drawtext(0,0 *nAngle,"welcome")
endpaint()
}
label1 {
setpicture(p1)
show()
}
FuncpClick
win1 { setwindowtitle("Click Event") }
FuncpTime
nAngle++
ifnAngle
nAngle
ok
pDraw()
The application during the runtime
45.50. Rotate Text 419

Ring Documentation, Release 1.14
45.51
The next example change the focus using the ENTER key.
load"guilib.ring"
newqApp {
win newqWidget() {
resize(600,600)
SetWindowTitle("Change Focus")
text1 newqLineEdit(win)
text2 newqLineEdit(win)
text3 newqLineEdit(win)
text4 newqLineEdit(win)
layout1 newqVBoxLayout() {
AddWidget(text1)
AddWidget(text2)
AddWidget(text3)
AddWidget(text4)
}
(continues on next page)
45.51. Change Focus 420

Ring Documentation, Release 1.14
(continued from previous page)
setLayout(Layout1)
aListtext1,text2,text3,text4]
oFilter newqallevents(win)
oFilter.setKeyPressEvent("pWork()")
installeventfilter(oFilter)
show()
}
exec()
}
funcpWork
nCode
ifnCode # ENTER Key
forx=1tolen(aList)
ifaList[x].HasFocus()
t+1
ift=1 ok
aList[t].SetFocus(0)
exit
ok
next
ok
45.52
The next example uses the Regular Expressions classes.
load"guilib.ring"
newqApp
{
see"Using Regular Expressions"
exp newqregularexpression() {
setPattern("\d\dw+")
seepattern()
match"33 one",0,0,0)
seematch.hasmatch()
match"3 one",0,0,0)
seematch.hasmatch()
match"welcome 11 one",0,0,0)
seematch.hasmatch()
matched0)
seematched
}
exp newqregularexpression() {
setPattern("^(\d\d)/(\d\d)/(\d\d\d\d)$")
seepattern()
match"08/12/1985",0,0,0)
seematch.hasmatch()
day1)
month2)
year3)
seeday
(continues on next page)
45.52. Regular Expressions 421

Ring Documentation, Release 1.14
(continued from previous page)
see"("1),"1)+)"
˓→nl
see"("2),"2)+)"
˓→nl
see"("3),"3)+)"
˓→nl
}
}
Output
Using Regular Expressions
\d\dw+
1
0
1
11
^(\d\d)/(\d\d)/(\d\d\d\d)$
1
08
12
1985
(0,2)
(3,5)
(6,10)
45.53
In this section we will learn about creating simple Client and Server Application
Load"guilib.ring"
newqApp {
oClient newClient { client() }
oServer newServer { server() }
exec()
}
ClassClient
win1 lineedit1 cOutput=""
oTcpSocket
funcclient
win1 newqwidget()
newqpushbutton(win1) {
setgeometry(50,50,100,30)
settext("connect")
setclickevent("oClient.Connect()")
}
(continues on next page)
45.53. Simple Client and Server Example 422

Ring Documentation, Release 1.14
(continued from previous page)
lineedit1 newqtextedit(win1) {
setGeometry(150,50,200,300)
}
win1 {
setwindowtitle("client")
setgeometry(10,100,400,400)
show()
}
funcconnect
cOutputConnect to host 127.0.0.1 port 9999"
lineedit1.settext(cOutput)
oTcpSocket newqTcpSocket(win1) {
setconnectedevent("oClient.pConnected()")
setreadyreadevent("oClient.pRead()")
connecttohost("127.0.0.1",9999,3,0)
waitforconnected(5000)
}
funcpConnected
cOutput=Connected!"
lineedit1.settext(cOutput)
funcpRead
cOutput=Ready Read!"
lineedit1.settext(cOutput)
cOutput=
lineedit1.settext(cOutput)
ClassServer
win1 lineedit1
oTcpServer oTcpClient
cOutput"
funcserver
win1 newqwidget()
lineedit1 newqtextedit(win1) {
setGeometry(150,50,200,300)
}
win1 {
setwindowtitle("Server")
setgeometry(450,100,400,400)
show()
}
oTcpServer newqTcpServer(win1) {
setNewConnectionEvent("oServer.pNewConnection()")
oHostAddress newqHostAddress()
oHostAddress.SetAddress("127.0.0.1")
listen(oHostAddress,9999)
(continues on next page)
45.53. Simple Client and Server Example 423

Ring Documentation, Release 1.14
(continued from previous page)
}
cOutputServer Started"
"listen to port 9999"
lineedit1.settext(cOutput)
FuncpNewConnection
oTcpClient
cOutput=Accept Connection"
lineedit1.settext(cOutput)
oTcpClient {
cStr"Hello from server to client!"+char(13)+char(10)
write(cStr,len(cStr))
flush()
waitforbyteswritten(300000)
close()
}
The application during the runtime
45.54
We may create objects in the runtime and add them to windows.
Example:
load"guilib.ring"
oFormDesigner newFormDesigner { start("oFormDesigner") }
(continues on next page)
45.54. Dynamic Objects 424

Ring Documentation, Release 1.14
(continued from previous page)
ClassFormDesigner
winToolBox winForm
aObjects]
funcstart cObjectName
oApp newqApp
winToolBox newqWidget()
winToolBox.setWindowTitle("ToolBox")
winToolBox.move(10,10)
winToolBox.resize(300,600)
btn newqPushButton(winToolBox)
btn.resize(300,30)
btn.setText("Create Button")
btn.setClickEvent(cObjectName+".pCreateButton()")
btn.show()
winToolBox.show()
winForm newqWidget() {
move(400,50)
setWindowTitle("Form Designer")
resize(600,600)
show()
}
oApp.exec()
funcpCreateButton
nCount
aObjects newMyButton(winForm)
{
nIndex
setText("Button"+
Move(30 *nIndex,30 *nIndex)
resize(100,30)
show()
}
ClassMyButtonfromqPushButton
nIndex
45.54. Dynamic Objects 425

Ring Documentation, Release 1.14
45.55
The next sample help in recording (Date, Time and Weight).
Load"guilib.ring"
MyApp newqApp
{
$ApplicationObjectoApp" # To be used when calling events
oApp newApp
exec()
oApp.CloseDatabase()
}
classApp
cDir/"
oCon
aIDs]
win1 newqWidget()
{
setWindowTitle("Weight History")
resize(600,600)
layoutButtons newqhboxlayout()
{
label1 newqLabel(win1) { setText("Weight") }
text1 newqlineedit(win1)
btnAdd newqpushbutton(win1) {
setText("Add")
setClickEvent($ApplicationObject+".AddWeight()")
}
btnDelete newqpushbutton(win1) {
setText("Delete")
setClickEvent($ApplicationObject+".Deleteweight()")
}
addwidget(label1)
addwidget(text1)
addwidget(btnAdd)
addwidget(btnDelete)
}
layoutData newqhboxlayout()
{
Table1 newqTableWidget(win1) {
setrowcount(0)
setcolumncount(3)
setselectionbehavior(QAbstractItemView_SelectRows)
setHorizontalHeaderItem(0, newQTableWidgetItem("Date"))
setHorizontalHeaderItem(1, newQTableWidgetItem("Time"))
setHorizontalHeaderItem(2, newQTableWidgetItem("Weight"))
setitemChangedEvent($ApplicationObject+".ItemChanged()")
setAlternatingRowColors( true)
horizontalHeader().setStyleSheet("color: blue")
verticalHeader().setStyleSheet("color: red")
}
addWidget(Table1)
}
(continues on next page)
45.55. Weight History Application 426

Ring Documentation, Release 1.14
(continued from previous page)
layoutClose newqhboxlayout()
{
btnclose newqpushbutton(win1) {
setText("Close")
setClickEvent("MyApp.Quit()")
}
addwidget(btnClose)
}
layoutMain newqvboxlayout()
{
addlayout(layoutButtons)
addLayout(LayoutData)
addLayout(layoutClose)
}
setlayout(layoutMain)
self.OpenDatabase()
self.ShowRecords()
show()
}
FuncOpenDatabase
lCreate False
if fexists(cDirweighthistory.db")
lCreate True
ok
newQSqlDatabase() {
this.oCon"QSQLITE") {
setDatabaseName("weighthistory.db")
Open()
}
}
iflCreate
newQSqlQuery( ) {
exec("create table weighthistory (id integer primary key,"+
""+
"")
delete()
}
ok
FuncCloseDatabase
oCon.Close()
FuncAddWeight
cWeight
AddRecord(cWeight)
FuncDeleteWeight
Table1 {
nRow
ifnRow=
nID[nROW+1]
newQSqlQuery( ) {
exec("delete from weighthistory where id =
}
Del(this.aIDs,nRow+1)
(continues on next page)
45.55. Weight History Application 427

Ring Documentation, Release 1.14
(continued from previous page)
removerow(nRow)
selectrow(nRow)
ok
}
FuncAddRecord cWeight
newQSqlQuery( ) {
cStrinsert into weighthistory (f_date,f_time,f_weight) values"+
"%f1,%f2,%f3)"
cDate
cTime
cStr"%f1",cDate)
cStr"%f2",cTime)
cStr"%f3",cWeight)
exec(cStr)
delete()
}
ShowRecords()
Table1.selectrow(table1.rowcount()-1)
FuncShowRecords
table1.setitemChangedEvent("")
aIDs]
query newQSqlQuery() {
exec("select *from weighthistory")
nRows
this.Table1.setrowcount(0)
whilemovenext()
this.table1 {
insertRow(nRows)
this.aIDs0).tostring()
forx to3
cStr
item newqTableWidgetItem(cStr)
setItem(nRows,x-1,item)
next
}
nRows++
end
delete()
}
table1.setitemChangedEvent($ApplicationObject+".ItemChanged()")
FuncItemChanged
nRow
ifnRow=
myitem0)
cDate
myitem1)
cTime
myitem2)
cWeight
newQSqlQuery( ) {
cStrupdate weighthistory set f_date =%f1%f2+
"f_weight =%f3[nROW+1]
(continues on next page)
45.55. Weight History Application 428

Ring Documentation, Release 1.14
(continued from previous page)
cStr"%f1",cDate)
cStr"%f2",cTime)
cStr"%f3",cWeight)
exec(cStr)
delete()
}
ok
The next screen shot for the application during the runtime
45.55. Weight History Application 429

Ring Documentation, Release 1.14
45.56
In the next example we will see simple Notepad developed using the RingQt
Load"guilib.ring"
cActiveFileName"
aTextColor0,0,0]
aBackColor255,255,255]
cFontMS Shell Dlg 2,14,-1,5,50,0,0,0,0,0"
cWebsitehttp://www.google.com"
oSearch NULL
oSearchValue NULL
oSearchCase NULL
oSearchFilter NULL
oReplaceValue NULL
lAskToSave false
MyApp NewqApp {
win1 newqMainWindow() {
setwindowtitle("Ring Notepad")
setGeometry(100,100,400,400)
aBtns
newqpushbutton(win1) {
setbtnimage(self,"image/new.png")
setclickevent("pNew()")
settooltip("New File")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/open.png")
setclickevent("pOpen()")
settooltip("Open File")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/save.png")
setclickevent("pSave()")
settooltip("Save")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/saveas.png")
setclickevent("pSaveAs()")
settooltip("Save As")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/cut.png")
setclickevent("pCut()")
settooltip("Cut")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/copy.png")
setclickevent("pCopy()")
settooltip("Copy")
} ,
newqpushbutton(win1) {
(continues on next page)
45.56. Notepad Application 430

Ring Documentation, Release 1.14
(continued from previous page)
setbtnimage(self,"image/paste.png")
setclickevent("pPaste()")
settooltip("Paste")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/font.png")
setclickevent("pFont()")
settooltip("Font")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/colors.jpg")
setclickevent("pColor()")
settooltip("Text Color")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/search.png")
setclickevent("pFind()")
settooltip("Find and Replace")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/print.png")
setclickevent("pPrint()")
settooltip("Print")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/debug.png")
setclickevent("pDebug()")
settooltip("Debug (Run then wait!)")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/run.png")
setclickevent("pRun()")
settooltip("Run the program")
} ,
newqpushbutton(win1) {
setbtnimage(self,"image/close.png")
setclickevent("pQuit()")
settooltip("Quit")
}
]
tool1"files") {
forxinaBtns addwidget(x) addseparator() next
}
menu1 newqmenubar(win1) {
sub1"File")
sub2"Edit")
sub3"View")
sub4"Help")
sub1 {
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+n"))
setbtnimage(self,"image/new.png")
settext("New")
setclickevent("pNew()")
}
(continues on next page)
45.56. Notepad Application 431

Ring Documentation, Release 1.14
(continued from previous page)
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+o"))
setbtnimage(self,"image/open.png")
settext("Open")
setclickevent("pOpen()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+s"))
setbtnimage(self,"image/save.png")
settext("Save")
setclickevent("pSave()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+e"))
setbtnimage(self,"image/saveas.png")
settext("Save As")
setclickevent("pSaveAs()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+p"))
setbtnimage(self,"image/print.png")
settext("Print to PDF")
setclickevent("pPrint()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+d"))
setbtnimage(self,"image/debug.png")
settext("Debug (Run then wait!)")
setclickevent("pDebug()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+r"))
setbtnimage(self,"image/run.png")
settext("Run")
setclickevent("pRun()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+F5"))
setbtnimage(self,"image/run.png")
settext("Run GUI Application (No Console)")
setclickevent("pRunNoConsole()")
}
addaction(oAction)
addseparator()
(continues on next page)
45.56. Notepad Application 432

Ring Documentation, Release 1.14
(continued from previous page)
oAction newqaction(win1) {
setShortcut(newQKeySequence("Ctrl+q"))
setbtnimage(self,"image/close.png")
settext("Exit")
setstatustip("Exit")
setclickevent("pQuit()")
}
addaction(oAction)
}
sub2 {
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+x"))
setbtnimage(self,"image/cut.png")
settext("Cut")
setclickevent("pCut()")
}
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+c"))
setbtnimage(self,"image/copy.png")
settext("Copy")
setclickevent("pCopy()")
}
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+v"))
setbtnimage(self,"image/paste.png")
settext("Paste")
setclickevent("pPaste()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+i"))
setbtnimage(self,"image/font.png")
settext("Font")
setclickevent("pFont()")
}
addseparator()
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+t"))
setbtnimage(self,"image/colors.jpg")
settext("Text Color")
setclickevent("pColor()")
}
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+b"))
setbtnimage(self,"image/colors.jpg")
settext("Back Color")
setclickevent("pColor2()")
}
addaction(oAction)
addseparator()
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+g"))
(continues on next page)
45.56. Notepad Application 433

Ring Documentation, Release 1.14
(continued from previous page)
settext("Go to line")
setclickevent("pGoto()")
}
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+f"))
setbtnimage(self,"image/search.png")
settext("Find and Replace")
setclickevent("pFind()")
}
addaction(oAction)
}
sub3 {
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+p"))
setbtnimage(self,"image/project.png")
settext("Project Files")
setclickevent("pProject()")
}
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+u"))
setbtnimage(self,"image/source.png")
setclickevent("pSourceCode()")
settext("Source Code")
}
addaction(oAction)
oAction newqAction(win1) {
setShortcut(newQKeySequence("Ctrl+w"))
setbtnimage(self,"image/richtext.png")
setclickevent("pWebBrowser()")
settext("Web Browser")
}
addaction(oAction)
}
sub4 {
sub5"Development Tools")
sub5 {
oAction newqAction(win1) {
settext("Programming Language")
setclickevent("pLang()")
}
addaction(oAction)
oAction newqAction(win1) {
settext("GUI Library")
setclickevent("pGUI()")
}
addaction(oAction)
}
addseparator()
oAction newqAction(win1) {
settext("About")
setclickevent("pAbout()")
}
addaction(oAction)
}
(continues on next page)
45.56. Notepad Application 434

Ring Documentation, Release 1.14
(continued from previous page)
}
setmenubar(menu1)
status1 newqstatusbar(win1) {
showmessage("Ready!",0)
}
setstatusbar(status1)
tree1 newqtreeview(win1) {
setclickedevent("pChangeFile()")
setGeometry(00,00,200,400)
oDir newQDir()
ofile newQFileSystemModel() {
setrootpath(oDir.currentpath())
myfiles newqstringlist()
myfiles.append(" *.ring")
myfiles.append(" *.rh")
setnamefilters(myfiles)
setNameFilterDisables( false)
}
setmodel(ofile)
myindex0)
forx toofile.columncount()
hidecolumn(x)
next
setcurrentindex(myindex)
setexpanded(myindex,true)
header().hide()
}
oDock1 newqdockwidget(win1,0) {
setGeometry(00,00,200,200)
setwindowtitle("Project Files")
setwidget(tree1)
}
textedit1 newqtextedit(win1) {
setCursorPositionChangedevent("pCursorPositionChanged()")
setLineWrapMode(QTextEdit_NoWrap)
setAcceptRichText(false)
setTextChangedEvent("lAskToSave = true")
}
oDock2 newqdockwidget(win1,0) {
setwidget(textedit1)
setwindowtitle("Source Code")
}
oWebBrowser newqWidget() {
setWindowFlags(Qt_SubWindow)
oWBLabel newqLabel(win1) {
setText("Website:)
}
oWBText newqLineEdit(win1) {
(continues on next page)
45.56. Notepad Application 435

Ring Documentation, Release 1.14
(continued from previous page)
setText(cWebSite)
setReturnPressedEvent("pWebGo()")
}
oWBGo newqPushButton(win1) {
setText("Go")
setClickEvent("pWebGo()")
}
oWBBack newqPushButton(win1) {
setText("Back")
setClickEvent("pWebBack()")
}
oWBLayout1 newqHBoxLayout() {
addWidget(oWBLabel)
addWidget(oWBText)
addWidget(oWBGo)
addWidget(oWBBack)
}
oWebView newqWebView(win1) {
loadpage(newqurl(cWebSite))
}
oWBlayout2 newqVBoxLayout() {
addLayout(oWBLayout1)
addWidget(oWebView)
}
setLayout(oWBLayout2)
}
oDock3 newqdockwidget(win1,0) {
setwidget(oWebBrowser)
setwindowtitle("Web Browser")
setFeatures(QDockWidget_DocWidgetClosable)
}
adddockwidget(1,oDock1,1)
adddockwidget(2,oDock2,2)
adddockwidget(2,oDock3,1)
setwinicon(self,"image/notepad.png")
showmaximized()
}
RestoreSettings()
exec()
}
funcpWebGo
cWebsite
oWebView.LoadPage( newqurl( cWebSite ) )
funcpWebBack
oWebView.Back()
funcpProject
oDock1.Show()
funcpSourceCode
oDock2.Show()
(continues on next page)
45.56. Notepad Application 436

Ring Documentation, Release 1.14
(continued from previous page)
funcpWebBrowser
oDock3.Show()
funcpChangeFile
myitem
ifofile.isdir(myitem)
return
ok
cActiveFileName
textedit1.settext(read(cActiveFileName))
textedit1.setfocus(0)
pCursorPositionChanged()
pSetActiveFileName()
funcpSetActiveFileName
oDock2.setWindowTitle("Source Code :
funcpCursorPositionChanged
status1.showmessage("+(textedit1.textcursor().blocknumber()+1)+
"(textedit1.textcursor().columnnumber()+1)
"0)
funcpGoto
oInput NewQInputDialog(win1)
{
setwindowtitle("Enter the line number?")
setgeometry(100,100,400,50)
setlabeltext("Line")
settextvalue("1")
exec()
nLine
oBlock-1)
oCursor
oCursor.setposition(oBlock.position(),0)
textedit1.settextcursor(oCursor)
}
funcpFind
ifisobject(oSearch)
oSearch.activatewindow()
return
ok
oSearch newqWidget()
{
newqLabel(oSearch)
{
setText("Find What :)
setgeometry(10,10,50,30)
}
oSearchValue newqlineedit(oSearch)
{
setgeometry(80,10,460,30)
setReturnPressedEvent("pFindValue()")
}
newqLabel(oSearch)
{
(continues on next page)
45.56. Notepad Application 437

Ring Documentation, Release 1.14
(continued from previous page)
setText("Replace with)
setgeometry(10,45,80,30)
}
oReplaceValue newqlineedit(oSearch)
{
setgeometry(80,45,460,30)
}
oSearchCase newqCheckbox(oSearch)
{
setText("Case Sensitive")
setgeometry(80,85,100,30)
}
newqPushButton(oSearch)
{
setText("Find/Find Next")
setgeometry(80,120,100,30)
setclickevent("pFindValue()")
}
newqPushButton(oSearch)
{
setText("Replace")
setgeometry(200,120,100,30)
setclickevent("pReplace()")
}
newqPushButton(oSearch)
{
setText("Replace All")
setgeometry(320,120,100,30)
setclickevent("pReplaceAll()")
}
newqPushButton(oSearch)
{
setText("Close")
setgeometry(440,120,100,30)
setclickevent("pSearchClose()")
}
setwinicon(oSearch,"image/notepad.png")
setWindowTitle("Find/Replace")
setStyleSheet("background-color:white;")
setFixedsize(550,160)
setwindowflags( Qt_CustomizeWindowHint
Qt_WindowTitleHint
oSearchFilter newqallevents(oSearch)
oSearchFilter.setKeyPressEvent("pSearchKeyPress()")
installeventfilter(oSearchFilter)
show()
}
FuncpReplace
oCursor
ifoCursor.HasSelection() false
newqMessagebox(oSearch)
{
SetWindowTitle("Replace")
(continues on next page)
45.56. Notepad Application 438

Ring Documentation, Release 1.14
(continued from previous page)
SetText("No Selection")
show()
}
return
ok
cValue
cSelected
ifoSearchCase.checkState()
cValue
cSelected
ok
ifcSelected=
newqMessagebox(oSearch)
{
SetWindowTitle("Replace")
SetText("No Match")
show()
}
return
ok
cValue
nStart
nEnd
cStr
cStr+cValue+substr(cStr,nEnd+1)
textedit1.setText(cStr)
returnpFindValue()
FuncpReplaceAll
cStr
cOldValue
cNewValue
ifoSearchCase.checkState()
# Not Case Sensitive
cStr true)
else
# Case Sensitive
cStr
ok
textedit1.setText(cStr)
newqMessagebox(oSearch)
{
SetWindowTitle("Replace All")
SetText("Operation Done")
show()
}
FuncpSearchClose
oSearch.close()
oSearch NULL
funcpSearchKeyPress
ifoSearchFilter.getKeyCode()
pSearchClose()
ok
funcpFindValue
(continues on next page)
45.56. Notepad Application 439

Ring Documentation, Release 1.14
(continued from previous page)
oCursor
nPosStart
cValue
cStr
cStr
ifoSearchCase.checkState()
cStr
ok
nPos
ifnPos
nPos=
oCursor
oCursor.setposition(nPos,0)
textedit1.settextcursor(oCursor)
oCursor
oCursor.setposition(nPos+len(cValue),1)
textedit1.settextcursor(oCursor)
return
else
newqMessagebox(oSearch)
{
SetWindowTitle("Search")
SetText("Cannot find :"
show()
}
return
ok
funcpNofileopened
NewqMessageBox(win1) {
setWindowTitle("Sorry")
setText("Save the file first!")
show()
}
funcpDebug
ifcActiveFileName Null pNofileopened() ok
cCodestart run
system(cCode)
funcpRun
ifcActiveFileName Null pNofileopened() ok
cCodestart ring
system(cCode)
funcpRunNoConsole
ifcActiveFileName Null pNofileopened() ok
cCodestart /b ring
system(cCode)
funcpSave
ifcActiveFileName NULL pSaveAs()ok
writefile(cActiveFileName,textedit1.toplaintext())
status1.showmessage("File :",0)
lAskToSave false
funcpSaveAs
(continues on next page)
45.56. Notepad Application 440

Ring Documentation, Release 1.14
(continued from previous page)
newqfiledialog(win1) {
cName"Save As","","source files( *.ring)")
ifcName= NULL
cActiveFileName
writefile(cActiveFileName,textedit1.toplaintext())
status1.showmessage("File :",0)
pSetActiveFileName()
lAskToSave false
ok
}
funcpPrint
status1.showmessage("Printing to File : RingDoc.pdf",0)
printer1 newqPrinter(0) {
setoutputformat(1) # 1 = pdf
setoutputfilename("RingDoc.pdf")
textedit1.print(printer1)
}
status1.showmessage("Done!",0)
system("RingDoc.pdf")
funcpCut
textedit1.cut()
status1.showmessage("Cut!",0)
funcpCopy
textedit1.copy()
status1.showmessage("Copy!",0)
funcpPaste
textedit1.paste()
status1.showmessage("Paste!",0)
funcpFont
oFontDialog newqfontdialog() {
aFont
}
textedit1.selectall()
cFont[1]
pSetFont()
FuncpSetFont
myfont newqfont("",0,0,0)
myfont.fromstring(cFont)
textedit1.setcurrentfont(myfont)
FuncpColor
newqcolordialog() { aTextColor
pSetColors()
FuncpColor2
newqcolordialog() { aBackColor
pSetColors()
FuncpSetColors
textedit1.setstylesheet("color: rgb("[1],"[2]
","[3]);"background-color: rgb("
˓→+ (continues on next page)
45.56. Notepad Application 441

Ring Documentation, Release 1.14
(continued from previous page)
aBackColor[1],"[2],"
aBackColor[3])")
funcpOpen
newqfiledialog(win1) {
cName"open file","c: \","source files( *.ring)")
ifcName= NULL
cActiveFileName
textedit1.settext(read(cActiveFileName))
ok
}
funcpNew
newqfiledialog(win1) {
cName"New file","","source files( *.ring)")
ifcName= NULL
write(cName,"")
cActiveFileName
textedit1.settext(read(cActiveFileName))
ok
}
FuncWriteFile cFileName,cCode
aCode
fp"wb")
forcLineinaCode
fwrite(fp,cLine+char(13)+char(10))
next
fclose(fp)
FuncMsgBox cTitle,cMessage
newqMessagebox(win1) {
setwindowtitle(cTitle)
setText(cMessage)
show()
}
FuncpLang
MsgBox("Programming Language",
"This application developed using the Ring programming language")
FuncpGUI
MsgBox("GUI Library",
"This application uses the Qt GUI Library through RingQt")
FuncpAbout
MsgBox("About",
"2016, Mahmoud Fayed <[email protected]>")
FuncpSaveSettings
cSettingsaTextColor = ["+aTextColor[1]+","+aTextColor[2]+
","+aTextColor[3]+"]"
"aBackColor = ["+aBackColor[1]+","+aBackColor[2]+
","+aBackColor[3]+"]"
"cFont =""
(continues on next page)
45.56. Notepad Application 442

Ring Documentation, Release 1.14
(continued from previous page)
"cWebSite =""
cSettings13)+char(10))
write("ringnotepad.ini",cSettings)
iflAsktoSave
newqmessagebox(win1)
{
setwindowtitle("Save Changes?")
settext("Some changes are not saved!")
setInformativeText("Do you want to save your changes?")
setstandardbuttons(QMessageBox_Yes
QMessageBox_No
result
win1 {
ifresult
pSave()
butresult
return
ok
}
}
ok
return
FuncpSetWebsite
oWebView { loadpage(newqurl(cWebSite)) }
oWBText { setText(cWebSite) }
FuncRestoreSettings
eval(read("ringnotepad.ini"))
pSetColors()
pSetFont()
pSetWebsite()
FuncpQuit
ifpSaveSettings()
myapp.quit()
ok
The application during the runtime
The next screen shot demonstrates the “File” menu
45.56. Notepad Application 443

Ring Documentation, Release 1.14
The next window for “search and replace”
The next screen shot demonstrates the application main window
45.56. Notepad Application 444

Ring Documentation, Release 1.14
Note:the functions pDebug(), pRun() and pRunNoConsole() in the previous sample are not portable! They are
written in this sample for MS-Windows and we can update them for other operating systems.
45.57
In the next example we will see a simple Cards game developed using RingQt
Each player get 5 cards, the cards are unknown to any one. each time one player click on one card to see it. if the card
is identical to another card the play get point for each card. if the card value is “5” the player get points for all visible
cards.
Load"guilib.ring"
nScale
app1 newqApp
mypic newQPixmap("cards.jpg")
mypic20,(124 *4)+1,79,124)
Player1EatPic80,(124 *4)+1,79,124)
Player2EatPic=160,(124 *4)+1,79,124)
aMyCards]
aMyValues]
forx1 to3
fory1 to12
temppic79 *y1)+1,(124 *x1)+1,79,124)
aMyCards
aMyValues+1)
(continues on next page)
45.57. The Cards Game 445

Ring Documentation, Release 1.14
(continued from previous page)
next
next
nPlayer1Score=0
do
Page1 newGame
Page1.Start()
againPage1.lnewgame
mypic.delete()
mypic2.delete()
Player1EatPic.delete()
Player2EatPic.delete()
fortinaMyCards
t.delete()
next
funcgui_setbtnpixmap pBtn,pPixmap
pBtn {
setIcon(newqicon(pPixmap.scaled(width(),height(),0,0)))
setIconSize(newQSize(width(),height()))
}
ClassGame
nCardsCount
win1 layout1 label1 label2 layout2 layout3 aBtns aBtns2
aCards nRole=1 list(nCardsCount) aStatus2
aValues aStatusValues
Player1EatPic Player2EatPic
lnewgame false
nDelayEat.5
nDelayNewGame
funcstart
win1 newqWidget() {
setwindowtitle("Five")
setstylesheet("background-color: White")
showfullscreen()
}
layout1 newqvboxlayout()
label1 newqlabel(win1) {
settext("Player (1) - Score :
setalignment(Qt_AlignHCenter
setstylesheet("color: White; background-color: Purple;
font-size:20pt")
setfixedheight(200)
}
closebtn newqpushbutton(win1) {
settext("Close Application")
setstylesheet("font-size: 18px ; color : white ;
(continues on next page)
45.57. The Cards Game 446

Ring Documentation, Release 1.14
(continued from previous page)
background-color: black ;")
setclickevent("Page1.win1.close()")
}
aCards
aValues
layout2 newqhboxlayout()
aBtns]
forx tonCardsCount
aBtns newqpushbutton(win1)
aBtns[x].setfixedwidth(79 *nScale)
aBtns[x].setfixedheight(124 *nScale)
gui_setbtnpixmap(aBtns[x],mypic2)
layout2.addwidget(aBtns[x])
aBtns[x].setclickevent("Page1.Player1click("+x+")")
next
layout1.addwidget(label1)
layout1.addlayout(layout2)
label2 newqlabel(win1) {
settext("Player (2) - Score :
setalignment(Qt_AlignHCenter
setstylesheet("color: white; background-color: red;
font-size:20pt")
setfixedheight(200)
}
layout3 newqhboxlayout()
aBtns2]
forx tonCardsCount
aBtns2 newqpushbutton(win1)
aBtns2[x].setfixedwidth(79 *nScale)
aBtns2[x].setfixedheight(124 *nScale)
gui_setbtnpixmap(aBtns2[x],mypic2)
layout3.addwidget(aBtns2[x])
aBtns2[x].setclickevent("Page1.Player2click("+x+")")
next
layout1.addwidget(label2)
layout1.addlayout(layout3)
layout1.addwidget(closebtn)
win1.setlayout(layout1)
app1.exec()
FuncPlayer1Click x
ifnRole andaStatus[x]
nPos100)+clock())%(len(aCards)-1))
gui_setbtnpixmap(aBtns[x],aCards[nPos])
del(aCards,nPos)
nRole
(continues on next page)
45.57. The Cards Game 447

Ring Documentation, Release 1.14
(continued from previous page)
aStatus[x]
aStatusValues[x][nPos]
del(aValues,nPos)
Player1Eat(x,aStatusValues[x])
checknewgame()
ok
FuncPlayer2Click x
ifnRole andaStatus2[x]
nPos100)+clock())%(len(aCards)-1))
gui_setbtnpixmap(aBtns2[x],aCards[nPos])
del(aCards,nPos)
nRole
aStatus2[x]
aStatusValues2[x][nPos]
del(aValues,nPos)
Player2Eat(x,aStatusValues2[x])
checknewgame()
ok
FuncPlayer1Eat nPos,nValue
app1.processEvents()
delay(nDelayEat)
lEat false
forx tonCardsCount
ifaStatus2[x] and(aStatusValues2[x] or
˓→nValue=5)
aStatus2[x]
gui_setbtnpixmap(aBtns2[x],Player1EatPic)
lEat True
nPlayer1Score++
ok
if(x= and(aStatus[x]) and
(aStatusValues[x] ornValue=5)
aStatus[x]
gui_setbtnpixmap(aBtns[x],Player1EatPic)
lEat True
nPlayer1Score++
ok
next
iflEat
nPlayer1Score++
gui_setbtnpixmap(aBtns[nPos],Player1EatPic)
aStatus[nPos]
label1.settext("Player (1) - Score :
˓→nPlayer1Score)
ok
FuncPlayer2Eat nPos,nValue
app1.processEvents()
delay(nDelayEat)
lEat false
forx tonCardsCount
(continues on next page)
45.57. The Cards Game 448

Ring Documentation, Release 1.14
(continued from previous page)
ifaStatus[x] and(aStatusValues[x] ornValue
˓→5)
aStatus[x]
gui_setbtnpixmap(aBtns[x],Player2EatPic)
lEat True
nPlayer2Score++
ok
if(x= and(aStatus2[x]) and
(aStatusValues2[x] ornValue=5
aStatus2[x]
gui_setbtnpixmap(aBtns2[x],Player2EatPic)
lEat True
nPlayer2Score++
ok
next
iflEat
nPlayer2Score++
gui_setbtnpixmap(aBtns2[nPos],Player2EatPic)
aStatus2[nPos]
label2.settext("Player (2) - Score :
˓→nPlayer2Score)
ok
Funcchecknewgame
ifisnewgame()
lnewgame true
ifnPlayer1Score
label1.settext("Player (1) Wins!!!")
ok
ifnPlayer2Score
label2.settext("Player (2) Wins!!!")
ok
app1.processEvents()
delay(nDelayNewGame)
win1.delete()
app1.quit()
ok
Funcisnewgame
fortinaStatus
ift
return
ok
next
fortinaStatus2
ift
return
ok
next
return
Funcdelay x
nTime *1000
(continues on next page)
45.57. The Cards Game 449

Ring Documentation, Release 1.14
(continued from previous page)
oTest newqTest
oTest.qsleep(nTime)
The application during the runtime
Note:in the previous screen shot the player get the card number `5' but his score is not increased because he opened
this card while no other cards are visible!
The next screen shot while running the game using a Mobile (Android)
45.57. The Cards Game 450

Ring Documentation, Release 1.14
Note:using Qt we can run the same application on other Mobile systems
45.58
The next table present the class name and the methods that we have to use the default events.
Class Name Methods to use the default Events
QPushButton SetClickEvent()
QAction SetClickEvent()
QLineEdit SetTextChangedEvent()
SetCursorPositionChangedEvent()
SetEditingFinishedEvent()
SetReturnPressedEvent()
SetSelectionChangedEvent()
SetTextEditedEvent()
QTextEdit SetCopyAvailableEvent()
SetCurrentCharFormatChangedEvent()
SetCursorPositionChangedEvent()
continues on next page
45.58. Classes and their Methods to use the default events 451

Ring Documentation, Release 1.14
Table 1 – continued from previous page
Class Name Methods to use the default Events
SetRedoAvailableEvent()
SetSelectionChangedEvent()
SetTextChangedEvent()
SetUndoAvailableEvent()
QListWidget SetCurrentItemChangedEvent()
SetCurrentRowChangedEvent()
SetCurrentTextChangedEvent()
SetItemActivatedEvent()
SetItemChangedEvent()
SetItemClickedEvent()
SetItemDoubleClickedEvent()
SetItemEnteredEvent()
SetItemPressedEvent()
SetItemSelectionChangedEvent()
QTreeView SetCollapseEvent()
SetExpandedEvent()
SetActivatedEvent()
SetClickedEvent()
SetDoubleClickedEvent()
SetEnteredEvent()
SetPressedEvent()
SetViewportEnteredEvent()
QTreeWidget SetCollapsedEvent()
SetExpandedEvent()
SetActivatedEvent()
SetClickedEvent()
SetDoubleClickedEvent()
SetEnteredEvent()
SetPressedEvent()
SetViewportEnteredEvent()
SetCurrentItemChangedEvent()
SetItemActivatedEvent()
SetItemChangedEvent()
SetItemClickedEvent()
SetItemCollapsedEvent()
SetItemDoubleClickedEvent()
SetItemEnteredEvent()
SetItemExpandedEvent()
SetItemPressedEvent()
SetItemSelectionChangedEvent()
QComboBox SetActivatedEvent()
SetCurrentIndexChangedEvent()
SetEditTextChangedEvent()
SetHighlightedEvent()
QTabWidget SetCurrentChangedEvent()
SetTabCloseRequestedEvent()
QTableWidget SetCellActivatedEvent()
SetCellChangedEvent()
SetCellClickedEvent()
continues on next page
45.58. Classes and their Methods to use the default events 452

Ring Documentation, Release 1.14
Table 1 – continued from previous page
Class Name Methods to use the default Events
SetCellDoubleClickedEvent()
SetCellEnteredEvent()
SetCellPressedEvent()
SetCurrentCellChangedEvent()
SetCurrentItemChangedEvent()
SetItemActivatedEvent()
SetItemChangedEvent()
SetItemClickedEvent()
SetItemDoubleClickedEvent()
SetItemEnteredEvent()
SetItemPressedEvent()
SetItemSelectionChangedEvent()
QProgressBar SetValueChangedEvent()
QSpinBox SetValueChangedEvent()
QSlider SetActionTriggeredEvent()
SetRangeChangedEvent()
SetSliderMovedEvent()
SetSliderPressedEvent()
SetSliderReleasedEvent()
SetValueChangedEvent()
QDial SetActionTriggeredEvent()
SetRangeChangedEvent()
SetSliderMovedEvent()
SetSliderPressedEvent()
SetSliderReleasedEvent()
SetValueChangedEvent()
QWebView SetLoadFinishedEvent()
SetLoadProgressEvent()
SetLoadStartedEvent()
SetSelectionChangedEvent()
SetTitleChangedEvent()
SetUrlChangedEvent()
QCheckBox SetStateChangedEvent()
SetClickedEvent()
SetPressedEvent()
SetReleasedEvent()
SetToggledEvent()
QRadioButton SetClickedEvent()
SetPressedEvent()
SetReleasedEvent()
SetToggledEvent()
QButtonGroup SetButtonClickedEvent()
SetButtonPressedEvent()
SetButtonReleasedEvent()
QVideoWidget SetBrightnessChangedEvent()
SetContrastChangedEvent()
SetFullScreenChangedEvent()
SetHueChangedEvent()
SetSaturationChangedEvent()
continues on next page
45.58. Classes and their Methods to use the default events 453

Ring Documentation, Release 1.14
Table 1 – continued from previous page
Class Name Methods to use the default Events
QTimer SetTimeoutEvent()
QTcpServer SetAcceptErrorEvent()
SetNewConnectionEvent()
QIODevice SetAboutToCloseEvent()
SetBytesWrittenEvent()
SetReadChannelFinishedEvent()
SetReadyReadEvent()
QAbstractSocket SetConnectedEvent()
SetDisconnectedEvent()
SetErrorEvent()
SetHostFoundEvent()
SetProxyAuthenticationRequiredEvent()
SetStateChangedEvent()
QTcpSocket SetConnectedEvent()
SetDisconnectedEvent()
SetErrorEvent()
SetHostFoundEvent()
SetProxyAuthenticationRequiredEvent()
SetStateChangedEvent()
SetAboutToCloseEvent()
SetBytesWrittenEvent()
SetReadChannelFinishedEvent()
SetReadyReadEvent()
QColorDialog SetColorSelectedEvent()
SetCurrentColorChangedEvent()
QNetworkAccessManagerSetFinishedEvent()
QThread SetStartedEvent()
SetFinishedEvent()
45.59
RingQt dene a new class called QAllEvents that help you in using Events Filter
The next table presents the methods that we have
Methods to get parametersClass Name
getKeyCode() –> Number QAllEvents
getx() –> Number
gety() –> Number
getglobalx() –> Number
getglobaly() –> Number
getbutton() –> Number
getbuttons() –> Number
The next table presents the methods that we have to use events.
45.59. Methods to use Events with Events Filter 454

Ring Documentation, Release 1.14
Method Name Class Name
setKeyPressEvent(cEvent) QAllEvents
setMouseButtonPressEvent(cEvent)
setMouseButtonReleaseEvent(cEvent)
setMouseButtonDblClickEvent(cEvent)
setMouseMoveEvent(cEvent)
setCloseEvent(cEvent)
setContextMenuEvent(cEvent)
setDragEnterEvent(cEvent)
setDragLeaveEvent(cEvent)
setDragMoveEvent(cEvent)
setDropEvent(cEvent)
setEnterEvent(cEvent)
setFocusInEvent(cEvent)
setFocusOutEvent(cEvent)
setKeyReleaseEvent(cEvent)
setLeaveEvent(cEvent)
setNonClientAreaMouseButtonDblClickEvent(cEvent)
setNonClientAreaMouseButtonPressEvent(cEvent)
setNonClientAreaMouseButtonReleaseEvent(cEvent)
setNonClientAreaMouseMoveEvent(cEvent)
setMoveEvent(cEvent)
setResizeEvent(cEvent)
setWindowActivateEvent(cEvent)
setWindowBlockedEvent(cEvent)
setWindowDeactivateEvent(cEvent)
setWindowStateChangeEvent(cEvent)
setWindowUnblockedEvent(cEvent)
45.60
(1)
Syntax:
Set<Event_Name>Event(cEventCode)
(2)
The next table present these little changes
45.60. The Difference between Qt and RingQt 455

Ring Documentation, Release 1.14
Class Name Qt Method NameRingQt Method Name
QWebView load loadpage
QMediaPlaylist load loadle
QMediaPlaylist next movenext
QPainter end endpaint
QPicture load loadle
QLineEdit end endtext
QDialog done donedialog
QTextDocument end enddoc
QTextBlock next nextblock
QSqlQuery next movenext
QImage load loadimage
QNetworkAccessManager get getvalue
QNetworkAccessManager put putvalue
QThread exit exitfromthread
QRegularExpressionMatchIteratornext nextitem
QCamera load loadcamera
45.61
Qt Documentation :
See the “RingQt Classes and Methods Reference” chapter for supported classes and methods.
45.62
We added new classes to RingQt - another version of classes where the class names doesn't start with the “q” letter
Also updated methods so the index start from 1 when we deal with the GUI controls like
•
•
•
•
These classes are inside guilib.ring under the package name : System.GUI
To use it
load"guilib.ring"
importSystem.GUI
This doesn't have any effect on our previous code, It's just another choice for better code that is consistent with Ring
rules.
Also the form designer is updated to provide us the choice between using classes where (index start from 0) or (index
start from 1)
Example (Uses the Form Designer)
(1)
45.61. RingQt Classes and their Qt Documentation 456

Ring Documentation, Release 1.14
(2)
45.63
The WebLib comes with a class called HtmlPage
Using this class we can create reports quickly using WebLib & GUILib together
Example:
load"stdlib.ring"
load"weblib.ring"
load"guilib.ring"
importSystem.Web
importSystem.GUI
newqApp {
open_window(:CustomersReportController)
exec()
}
classCustomersReportController fromWindowsControllerParent
oView newCustomersReportView
funcStart
CreateReport()
funcCreateReport
mypage newHtmlPage {
h1 { text("Customers Report") }
Table
{
style"100%")4)
TR
{
TD { WIDTH="10%"
text("Customers Count :
TD { text (100) }
}
}
Table
{
style"100%")26)
TR
{
style"100%")
stylegradient(24)
TD { text("Name
TD { text("Age"
TD { text("Country"
TD { text("Job"
TD { text("Company"
}
forx to100
TR
(continues on next page)
45.63. Creating Reports using the WebLib and the GUILib 457

Ring Documentation, Release 1.14
(continued from previous page)
{
TD { text("Test"
TD { text("30"
TD { text("Egypt"
TD { text("Sales"
TD { text("Future"
}
next
}
}
write("report.html",mypage.output())
funcPrintEvent
printer1 newqPrinter(0) {
setoutputformat(1)
setoutputfilename("report.pdf")
}
oView {
web.print(printer1, Method( :OpenPDF ) )
web.show()
}
funcOpenPDF
newQDesktopServices {
OpenURL(newqURL("report.pdf") )
}
classCustomersReportView
win newwindow() {
setwindowtitle("Report Window")
setgeometry(100,100,500,500)
web newwebview(win) {
setgeometry(100,100,1000,500)
loadpage(newqurl("file:///"+
currentdir()+"/report.html"))
}
newpushbutton(win) {
setGeometry(100,20,100,30)
settext("Print")
setclickevent(Method(:PrintEvent))
}
showMaximized()
}
Screen Shot:
45.63. Creating Reports using the WebLib and the GUILib 458

Ring Documentation, Release 1.14
45.63. Creating Reports using the WebLib and the GUILib 459

CHAPTER
FORTYSIX
USING THE FORM DESIGNER
In this chapter we will learn about using the Form Designer.
We can run the From Designer from Ring Notepad
From the Menubar in Ring Notepad - View Menu - We can Show/Hide the Form Designer window.
Also we can run the Form Designer in another window.
From the Ring Notepad - Tools Menu - Select the Form Designer.
460

Ring Documentation, Release 1.14
46.1
•
•
•
46.2
We have many buttons.
•
•
•
46.3
•
•
•
•
46.1. The Designer Windows 461

Ring Documentation, Release 1.14
46.4
When we save the form le (*.rform), The Form Designer will create two Ring les
•
•
For example, if the form le is helloworld.rform
The form designer will generate two les
•
•
To run the program, Open the controller class le then click the Run button (CTRL+F5)
Tip:When you open a form using Ring Notepad, the controller class will be opened automatically, So we can press
(CTRL+F5) or click on the Run button while the form designer window is active.
46.4. Running Forms 462

Ring Documentation, Release 1.14
46.5
(1)
(2) Then write the method code in the controller class.
46.5. Events Code 463

Ring Documentation, Release 1.14
In this example we write
funcCloseWindow
oView.win.close()
Where inside the controller class, We uses the oView object to access the form.
Another Example :
46.5. Events Code 464

Ring Documentation, Release 1.14
The Event Code
funcSayHello
oView {
LineEdit2.setText("Hello+
}
46.6
After selecting one or group of controls
•
•
•
•
46.7
From the Window properties we can open the Menubar Designer
46.6. Keyboard Shortcuts 465

Ring Documentation, Release 1.14
46.8
From the Window properties we can open the Window Flags window.
46.8. Window Flags 466

Ring Documentation, Release 1.14
46.9
For some controls like the List Widget we can enter items separated by comma `,'
46.10
(1)
(2)
(3)
46.11
Check the folder : ring/samples/UsingFormDesigner
Online :
46.9. Entering Items 467

CHAPTER
FORTYSEVEN
GRAPHICS PROGRAMMING USING RINGQT3D
In this chapter we will learn how to use Qt3D through many samples.
47.1
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCube newQCuboidMesh(oRootEntity) {
setXextent(2)
setYextent(2)
(continues on next page)
468

Ring Documentation, Release 1.14
(continued from previous page)
setZextent(3)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(3,,))
oCubeMaterial newQPhongMaterial(oCube)
oCubeMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Cube")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.1. Drawing Cube 469

Ring Documentation, Release 1.14
47.2
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oTorus newQTorusMesh(oRootEntity)
oTorus.setRadius(1.0)
oTorus.setMinorRadius(0.4)
oTorus.setRings(100)
oTorus.setSlices(20)
oTorusTransform newQTransform(oTorus)
oTorusTransform.setScale(2)
oTorusTransform.setTranslation( newQVector3D(3,,))
oTorusMaterial newQPhongMaterial(oTorus)
oTorusMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oTorusEntity newQEntity(oRootEntity)
oTorusEntity.addComponent(oTorus)
oTorusEntity.addComponent(oTorusMaterial)
oTorusEntity.addComponent(oTorusTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
(continues on next page)
47.2. Drawing Torus 470

Ring Documentation, Release 1.14
(continued from previous page)
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Torus")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.3
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
(continues on next page)
47.3. Drawing Sphere 471

Ring Documentation, Release 1.14
(continued from previous page)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oSphere newQSphereMesh(oRootEntity)
oSphere.setRadius(1.0)
oSphere.setRings(100)
oSphere.setSlices(20)
oSphereTransform newQTransform(oSphere)
oSphereTransform.setScale(2)
oSphereTransform.setTranslation( newQVector3D(3,,))
oSphereMaterial newQPhongMaterial(oSphere)
oSphereMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oSphereEntity newQEntity(oRootEntity)
oSphereEntity.addComponent(oSphere)
oSphereEntity.addComponent(oSphereMaterial)
oSphereEntity.addComponent(oSphereTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Sphere")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.3. Drawing Sphere 472

Ring Documentation, Release 1.14
47.4
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
(continues on next page)
47.4. Drawing Cylinder 473

Ring Documentation, Release 1.14
(continued from previous page)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCylinder newQCylinderMesh(oRootEntity)
oCylinder.setRadius(1)
oCylinder.setRings(100)
oCylinder.setSlices(20)
oCylinder.setLength(5)
oCylinderTransform newQTransform(oCylinder)
oCylinderTransform.setScale(2)
oCylinderTransform.setTranslation( newQVector3D(1,,))
oCylinderMaterial newQPhongMaterial(oCylinder)
oCylinderMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oCylinderEntity newQEntity(oRootEntity)
oCylinderEntity.addComponent(oCylinder)
oCylinderEntity.addComponent(oCylinderMaterial)
oCylinderEntity.addComponent(oCylinderTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Cylinder")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.4. Drawing Cylinder 474

Ring Documentation, Release 1.14
47.5
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
(continues on next page)
47.5. Drawing Cone 475

Ring Documentation, Release 1.14
(continued from previous page)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCone newQConeMesh(oRootEntity)
oCone.setRings(100)
oCone.setSlices(20)
oCone.setLength(5)
oConeTransform newQTransform(oCone)
oConeTransform.setScale(2)
oConeTransform.setTranslation( newQVector3D(1,,))
oConeMaterial newQPhongMaterial(oCone)
oConeMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oConeEntity newQEntity(oRootEntity)
oConeEntity.addComponent(oCone)
oConeEntity.addComponent(oConeMaterial)
oConeEntity.addComponent(oConeTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Cone")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.5. Drawing Cone 476

Ring Documentation, Release 1.14
47.6
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
(continues on next page)
47.6. Drawing Plane 477

Ring Documentation, Release 1.14
(continued from previous page)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oPlane newQPlaneMesh(oRootEntity)
oPlane.setHeight(5)
oPlane.setWidth(5)
oPlane.setmeshresolution( newqSize(10,10))
oPlaneTransform newQTransform(oPlane)
oPlaneTransform.setScale(2)
oPlaneTransform.setTranslation( newQVector3D(0,4,))
oPlaneMaterial newQPhongMaterial(oPlane)
oPlaneMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oPlaneEntity newQEntity(oRootEntity)
oPlaneEntity.addComponent(oPlane)
oPlaneEntity.addComponent(oPlaneMaterial)
oPlaneEntity.addComponent(oPlaneTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Plane")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.6. Drawing Plane 478

Ring Documentation, Release 1.14
47.7
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
(continues on next page)
47.7. Texture 479

Ring Documentation, Release 1.14
(continued from previous page)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCube newQCuboidMesh(oRootEntity) {
setXextent(2)
setYextent(2)
setZextent(3)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(3,,))
oTextureLoader newQTextureLoader(oCube);
oTextureLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oCubeMaterial newQTextureMaterial(oCube)
oCubeMaterial.setTexture(oTextureLoader)
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Adding Texture")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.7. Texture 480

Ring Documentation, Release 1.14
47.8
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oFilter newqallevents(oView)
oFilter.setKeyPressEvent("pKeyPress()")
oView.installeventfilter(oFilter)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
(continues on next page)
47.8. Key Press 481

Ring Documentation, Release 1.14
(continued from previous page)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCamController.setEnabled( False)
oCube newQCuboidMesh(oRootEntity) {
setXextent(2)
setYextent(2)
setZextent(3)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(3,,))
oTextureLoader newQTextureLoader(oCube);
oTextureLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oCubeMaterial newQTextureMaterial(oCube)
oCubeMaterial.setTexture(oTextureLoader)
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Moving Cube using the Keyboard")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
oContainer.setfocus(0)
exec()
}
funcpKeyPress
nKey
oX
oY
oZ
switchnKey
onQt_Key_Right
oX++
onQt_Key_Left
oX--
onQt_Key_Up
(continues on next page)
47.8. Key Press 482

Ring Documentation, Release 1.14
(continued from previous page)
oY++
onQt_Key_Down
oY--
off
oCubeTransform.setTranslation( newQVector3D(oX, oY, oZ))
47.9
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oFilter newqallevents(oView)
oFilter.setKeyPressEvent("pKeyPress()")
oView.installeventfilter(oFilter)
oInput newQInputAspect(oRootEntity)
(continues on next page)
47.9. Object Picker 483

Ring Documentation, Release 1.14
(continued from previous page)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCamController.setEnabled( False)
oCube newQCuboidMesh(oRootEntity) {
setXextent(2)
setYextent(2)
setZextent(3)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(3,,))
oTextureLoader newQTextureLoader(oCube);
oTextureLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oCubeMaterial newQTextureMaterial(oCube)
oCubeMaterial.setTexture(oTextureLoader)
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
oPicker newqObjectPicker(oCube) {
setclickedevent("pClick()")
}
oCubeEntity.addComponent(oPicker)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Object Picker - Click on the Cube")
resize(800,600)
(continues on next page)
47.9. Object Picker 484

Ring Documentation, Release 1.14
(continued from previous page)
setLayout(oLayout)
showMaximized()
}
oContainer.setfocus(0)
exec()
}
funcpKeyPress
nKey
oX
oY
oZ
switchnKey
onQt_Key_Right
oX++
onQt_Key_Left
oX--
onQt_Key_Up
oY++
onQt_Key_Down
oY--
off
oCubeTransform.setTranslation( newQVector3D(oX, oY, oZ))
funcpClick
msginfo("Event","Click")
oContainer.setfocus(0)
47.9. Object Picker 485

Ring Documentation, Release 1.14
47.10
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
(continues on next page)
47.10. Frame Action 486

Ring Documentation, Release 1.14
(continued from previous page)
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCamController.setEnabled( False)
oCube newQCuboidMesh(oRootEntity) {
setXextent(1)
setYextent(1)
setZextent(1)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(-5,5,5))
oTextureLoader newQTextureLoader(oCube);
oTextureLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oCubeMaterial newQTextureMaterial(oCube)
oCubeMaterial.setTexture(oTextureLoader)
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
nAngle=0=0.1
oFrameAction newqFrameAction(oRootEntity) {
settriggeredevent("pEvent()")
}
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Frame Action")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
(continues on next page)
47.10. Frame Action 487

Ring Documentation, Release 1.14
(continued from previous page)
funcpEvent
# Move the Cube
oX
oY
oZ
ifoX=
nSpeed=-0.1
butoX=10
nSpeed=0.1
ok
oCubeTransform.setTranslation(
newQVector3D(oX+nSpeed, oY+nSpeed, oZ+nSpeed))
# Rotate the Cube
nAngle+=5 ifnAngle=360=0 ok
oQ newQQuaternion(0,0,0,0)
oCubeTransform.setRotation(
oQ.fromAxisAndAngle(newQVector3D(0,,), nAngle))
47.10. Frame Action 488

Ring Documentation, Release 1.14
47.11
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oView.defaultframegraph().setclearcolor( newQColor() {setRGB(100,250,150,255)}
˓→)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCube newQCuboidMesh(oRootEntity) {
setXextent(2)
setYextent(2)
setZextent(3)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(0,,))
oTextureLoader newQTextureLoader(oCube);
oTextureLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/ring.bmp") )
oCubeMaterial newQTextureMaterial(oCube)
oCubeMaterial.setTexture(oTextureLoader)
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
(continues on next page)
47.11. Text 2D 489

Ring Documentation, Release 1.14
(continued from previous page)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
oText2DEntity newQText2DEntity(oRootEntity) {
setText("Ring programming language")
setWidth(400) setHeight(40)
setColor(newQColor() {setRGB(128,128,128,255)})
}
oText2DTransform newQTransform(oText2DEntity)
oText2DTransform.setScale(0.1)
oText2DTransform.setTranslation( newQVector3D(-10.5,5,))
oText2DEntity.addComponent(oText2DTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Text2D")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.11. Text 2D 490

Ring Documentation, Release 1.14
47.12
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oView.defaultframegraph().setclearcolor( newQColor() {setRGB(100,250,150,255)}
˓→)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oCube newQCuboidMesh(oRootEntity) {
setXextent(2)
setYextent(2)
setZextent(3)
}
oCubeTransform newQTransform(oCube)
oCubeTransform.setScale(2)
oCubeTransform.setTranslation( newQVector3D(0,,))
oTextureLoader newQTextureLoader(oCube);
oTextureLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/ring.bmp") )
oCubeMaterial newQTextureMaterial(oCube)
oCubeMaterial.setTexture(oTextureLoader)
oCubeEntity newQEntity(oRootEntity)
oCubeEntity.addComponent(oCube)
(continues on next page)
47.12. Extruded Text 491

Ring Documentation, Release 1.14
(continued from previous page)
oCubeEntity.addComponent(oCubeMaterial)
oCubeEntity.addComponent(oCubeTransform)
oTextEntity newQEntity(oRootEntity)
oTextMesh newQExtrudedTextMesh(oTextEntity) {
setText("Ring")
}
oTextTransform newQTransform(oTextEntity)
oTextTransform.setScale(3)
oTextTransform.setTranslation( newQVector3D(-5.5,4,))
oTextMaterial newQPhongMaterial(oTextEntity);
oTextMaterial.setDiffuse( newQColor() {setRGB(0,0,255,255)})
oTextEntity.addComponent(oTextMesh)
oTextEntity.addComponent(oTextTransform)
oTextEntity.addComponent(oTextMaterial)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Extruded Text")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.12. Extruded Text 492

Ring Documentation, Release 1.14
47.13
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oModel newqmesh(oRootEntity)
oModel.setsource(
newqURL("file:///"+currentdir()+"/assets/model/lucky_cat.obj") )
oModelTransform newQTransform(oModel)
oModelTransform.setScale(0.1)
oModelTransform.setTranslation( newQVector3D(0,,))
oQ newQQuaternion(0,0,0,0)
oModelTransform.setRotation(oQ.fromAxisAndAngle( newQVector3D(0,,),))
oModelMaterial newQPhongMaterial(oModel)
oModelMaterial.setDiffuse( newQColor() {setRGB(0,255,128,255)})
oModelEntity newQEntity(oRootEntity)
oModelEntity.addComponent(oModel)
oModelEntity.addComponent(oModelmaterial)
oModelEntity.addComponent(oModelTransform)
oView.setRootEntity(oRootEntity)
(continues on next page)
47.13. Model 493

Ring Documentation, Release 1.14
(continued from previous page)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Model (Obj File)")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.14
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
(continues on next page)
47.14. Model Texture 494

Ring Documentation, Release 1.14
(continued from previous page)
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oModel newqmesh(oRootEntity)
oModel.setsource(
newqURL("file:///"+currentdir()+"/assets/model/Robot.obj") )
oModelTransform newQTransform(oModel)
oModelTransform.setScale(0.5)
oModelTransform.setTranslation( newQVector3D(0,,))
oLoader newQTextureLoader(oModel)
oModelMaterial newQTextureMaterial(oModel)
oLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/Robot.jpg") )
oModelMaterial.setTexture(oLoader)
oModelEntity newQEntity(oRootEntity)
oModelEntity.addComponent(oModel)
oModelEntity.addComponent(oModelMaterial)
oModelEntity.addComponent(oModelTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Model Texture")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.14. Model Texture 495

Ring Documentation, Release 1.14
47.15
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
(continues on next page)
47.15. Draw Ofce 496

Ring Documentation, Release 1.14
(continued from previous page)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oModel newqmesh(oRootEntity)
oModel.setsource(
newqURL("file:///"+currentdir()+"/assets/model/Reception_Table.obj")
˓→)
oModelTransform newQTransform(oModel)
oModelTransform.setScale(1)
oModelTransform.setTranslation( newQVector3D(0,2.5,))
oModelMaterial newQPhongMaterial(oModel)
oModelMaterial.setDiffuse( newQColor() {setRGB(0,255,128,255)})
oModelEntity newQEntity(oRootEntity)
oModelEntity.addComponent(oModel)
oModelEntity.addComponent(oModelmaterial)
oModelEntity.addComponent(oModelTransform)
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Model (Obj File) - Office")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47◁15◁ &#3627408439;&#3627408479;&#3627408462;&#3627408484; &#3627408450;&#3627408467;??????&#3627408464;&#3627408466;497

Ring Documentation, Release 1.14
47.16
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
(continues on next page)
47.16. Many Objects 498

Ring Documentation, Release 1.14
(continued from previous page)
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oModel newqmesh(oRootEntity)
oModel.setsource(
newqURL("file:///"+currentdir()+"/assets/model/Robot.obj") )
oModelTransform newQTransform(oModel)
oModelTransform.setScale(0.2)
oModelTransform.setTranslation( newQVector3D(0,,))
oModelMaterial newQPhongMaterial(oModel)
oModelMaterial.setDiffuse( newQColor() {setRGB(0,100,0,0)})
oModelEntity newQEntity(oRootEntity)
oModelEntity.addComponent(oModel)
oLoader newQTextureLoader(oModel);
oModelMaterial newQTextureMaterial(oModel)
oLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oModelMaterial.setTexture(oLoader)
oModelEntity.addComponent(oModelMaterial)
oModelEntity.addComponent(oModelTransform)
forn to10
oTorus newQTorusMesh(oRootEntity)
oTorus.setRadius(1.0 *n)
oTorus.setMinorRadius(0.4 *n)
oTorus.setRings(100)
oTorus.setSlices(20)
oTorusTransform newQTransform(null)
oTorusTransform.setScale(2)
oTorusTransform.setTranslation( newQVector3D(5.0 *n,.0 *n,.0))
oTorusMaterial newQPhongMaterial(null);
oTorusMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oTorusEntity newQEntity(oRootEntity)
oTorusEntity.addComponent(oTorus)
oLoader newQTextureLoader(oTorus);
oTorusMaterial newQTextureMaterial(oTorus)
(continues on next page)
47.16. Many Objects 499

Ring Documentation, Release 1.14
(continued from previous page)
oLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oTorusMaterial.setTexture(oLoader)
oTorusEntity.addComponent(oTorusMaterial)
oTorusEntity.addComponent(oTorusTransform)
next
oView.setRootEntity(oRootEntity)
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oWidget {
setwindowtitle("Using Qt3D - Many Objects")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
47.16. Many Objects 500

Ring Documentation, Release 1.14
47.17
load"guilib.ring"
newqApp {
oView newQt3dwindow()
oWidget newQWidget()
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,.0)
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(0,,))
oLightEntity newQEntity(oRootEntity)
oLight newQPointLight(oLightEntity)
oLight.setColor(newQColor() { setRGB(255,255,255,255) })
oLight.setIntensity(1)
oLightEntity.addComponent(oLight)
oLightTransform newQTransform(oLightEntity)
oLightTransform.setTranslation(oCameraEntity.position())
oLightEntity.addComponent(oLightTransform)
oCamController newQFirstPersonCameraController(oRootEntity)
oCamController.setCamera(oCameraEntity)
oModel newqmesh(oRootEntity)
oModel.setsource(
newqURL("file:///"+currentdir()+"/assets/model/Robot.obj") )
oModelTransform newQTransform(oModel)
oModelTransform.setScale(0.2)
oModelTransform.setTranslation( newQVector3D(0,,))
oModelMaterial newQPhongMaterial(oModel)
oModelMaterial.setDiffuse( newQColor() {setRGB(0,100,0,0)})
oModelEntity newQEntity(oRootEntity)
oModelEntity.addComponent(oModel)
oLoader newQTextureLoader(oModel);
oModelMaterial newQTextureMaterial(oModel)
oLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oModelMaterial.setTexture(oLoader)
oModelEntity.addComponent(oModelMaterial)
(continues on next page)
47.17. Camera 501

Ring Documentation, Release 1.14
(continued from previous page)
oModelEntity.addComponent(oModelTransform)
forn to10
oTorus newQTorusMesh(oRootEntity)
oTorus.setRadius(1.0 *n)
oTorus.setMinorRadius(0.4 *n)
oTorus.setRings(100)
oTorus.setSlices(20)
oTorusTransform newQTransform(null)
oTorusTransform.setScale(2)
oTorusTransform.setTranslation( newQVector3D(5.0 *n,.0 *n,.0))
oTorusMaterial newQPhongMaterial(null);
oTorusMaterial.setDiffuse( newQColor() {setRGB(200,100,100,100)})
oTorusEntity newQEntity(oRootEntity)
oTorusEntity.addComponent(oTorus)
oLoader newQTextureLoader(oTorus);
oTorusMaterial newQTextureMaterial(oTorus)
oLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/gold.jpg") )
oTorusMaterial.setTexture(oLoader)
oTorusEntity.addComponent(oTorusMaterial)
oTorusEntity.addComponent(oTorusTransform)
next
oView.setRootEntity(oRootEntity)
btn1 newqPushButton(oWidget) {
setText("Move the Camera and the Robot") setClickEvent("pMove()")
}
oLayout newQVBoxLayout()
oLayout.AddWidget(oContainer)
oLayout.AddWidget(btn1)
oWidget {
setwindowtitle("Using Qt3D - Camera")
resize(800,600)
setLayout(oLayout)
showMaximized()
}
exec()
}
funcpMove
oCameraEntity.setPosition( newQVector3D(0,,.0))
oCameraEntity.setUpVector( newQVector3D(0,,))
oCameraEntity.setViewCenter( newQVector3D(20,,))
(continues on next page)
47.17. Camera 502

Ring Documentation, Release 1.14
(continued from previous page)
oModelTransform.setTranslation( newQVector3D(20,,))
oQ newQQuaternion(0,0,0,0)
oModelTransform.setRotation(oQ.fromAxisAndAngle( newQVector3D(1,,),))
47.18
load"guilib.ring"
newqApp {
oWidget newQWidget()
oView newQt3DWindow()
oView.defaultFrameGraph().setClearColor( newQColor() {setRGB(0,0,0,255)})
oContainer0)
oRootEntity newQEntity(oContainer)
oInput newQInputAspect(oRootEntity)
oView.registerAspect(oInput)
oCameraEntity
oCameraEntity.lens().setPerspectiveProjection(45.0,.0/9.0,.1,)
oCameraEntity.setPosition( newQVector3D(-13.34,6.43,.47))
oCameraEntity.setUpVector( newQVector3D(0.02,,))
oCameraEntity.setViewCenter( newQVector3D(-13.34,.05,.42))
(continues on next page)
47.18. Scence 503

Ring Documentation, Release 1.14
(continued from previous page)
oCameraController newQFirstPersonCameraController(oRootEntity)
oCameraController.setCamera(oCameraEntity)
oCameraController.setEnabled( False)
oLongRoomEntity newQEntity(oRootEntity)
oLongRoomModel newQMesh(oLongRoomEntity)
oLongRoomModel.setSource(
newqURL("file:///"+CurrentDir()+"/assets/model/Long_Room.obj") )
oLongRoomTransform newQTransform(oLongRoomEntity)
oLongRoomTransform.setScale(1)
oLongRoomTransform.setTranslation( newQVector3D(5,,))
oLongRoomLoader newQTextureLoader(oLongRoomModel)
oLongRoomMaterial newQTextureMaterial(oLongRoomModel)
oLongRoomLoader.setSource(
newQUrl("file:///"+currentdir()+"/assets/texture/croc.jpg") )
oLongRoomMaterial.setTexture(oLongRoomLoader)
oLongRoomEntity.addComponent(oLongRoomModel)
oLongRoomEntity.addComponent(oLongRoomMaterial)
oLongRoomEntity.addComponent(oLongRoomTransform)
oTableEntity newQEntity(oRootEntity)
oTableModel newQMesh(oTableEntity)
oTableModel.setSource(
newqURL("file:///"+CurrentDir()+"/assets/model/Reception_Table.obj")
˓→)
oTableTransform newQTransform(oTableEntity)
oTableTransform.setScale(0.3)
oTableTransform.setTranslation( newQVector3D(5,,))
oQ newQQuaternion(0,0,0,0)
oTableTransform.setRotation(oQ.fromAxisAndAngle( newQVector3D(0,,),180))
oTableModelMaterial newQPhongMaterial(oTableEntity)
oTableModelMaterial.setDiffuse( newQColor() {setRGB(255,255,255,255)})
oTableEntity.addComponent(oTableModel)
oTableEntity.addComponent(oTableModelmaterial)
oTableEntity.addComponent(oTableTransform)
oFirstLightEntity newQEntity(oRootEntity)
oFirstLight newQPointLight(oFirstLightEntity)
oFirstLight.setColor( newqColor() { setRGB(128,128,128,128) })
oFirstLight.setIntensity(1)
oFirstLightTransform newQTransform(oFirstLightEntity)
oFirstLightTransform.setTranslation( newQVector3D(5,,))
oFirstLightEntity.addComponent(oFirstLight)
oFirstLightEntity.addComponent(oFirstLightTransform)
(continues on next page)
47.18. Scence 504

Ring Documentation, Release 1.14
(continued from previous page)
aCats list(5)
forn to5
v *0.1
aCats[n]]
aCats[n][:oCatModelEntity] newQEntity(oRootEntity)
aCats[n][:oCatModel] newQMesh(aCats[n][:oCatModelEntity])
aCats[n][:oCatModel].setSource(
newqURL("file:///"+CurrentDir()+"/assets/model/Lucky_Cat.obj") )
aCats[n][:oCatModelMaterial] newQPhongMaterial(aCats[n][:oCatModel])
aCats[n][:oCatModelMaterial].setDiffuse(
newQColor() {setRGB(255,255,255,255)})
aCats[n][:oCatModelTransform] newQTransform(aCats[n][:oCatModelEntity])
aCats[n][:oCatModelTransform].setScale(0.01)
aCats[n][:oCatModelTransform].setTranslation(
newQVector3D(-5 *(v+v),,.2))
oQ newQQuaternion(0,0,0,0)
aCats[n][:oCatModelTransform].setRotation(
oQ.fromAxisAndAngle(
newQVector3D(0,,),))
aCats[n][:oCatModelEntity].addComponent(aCats[n][:oCatModel])
aCats[n][:oCatModelEntity].addComponent(aCats[n][:oCatModelmaterial])
aCats[n][:oCatModelEntity].addComponent(aCats[n][:oCatModelTransform])
next
oSecondLightEntity newQEntity(oRootEntity)
oSecondLight newQPointLight(oSecondLightEntity)
oSecondLight.setColor( newqColor() { setRGB(255,255,255,255) })
oSecondLight.setIntensity(1)
oSecondLightTransform newQTransform(oSecondLightEntity)
oSecondLightTransform.setTranslation( newQVector3D(-5,,.5))
oSecondLightEntity.addComponent(oSecondLight)
oSecondLightEntity.addComponent(oSecondLightTransform)
oRobotEntity newQEntity(oRootEntity)
oRobotModel newQMesh(oRobotEntity)
oRobotModel.setSource(
newqURL("file:///"+CurrentDir()+"/assets/model/Fat_Robot.obj") )
oRobotTransform newQTransform(oRobotEntity)
oRobotTransform.setScale(0.006)
robotX15
robotY2
robotZ
oRobotTransform.setTranslation( newQVector3D(-15,2,))
oQ newQQuaternion(0,0,0,0)
oRobotTransform.setRotation(
oQ.fromAxisAndAngle( newQVector3D(0,,),))
oRobotMaterial newQPhongMaterial(oRobotEntity)
oRobotMaterial.setDiffuse( newQColor() {setRGB(128,128,128,255)})
oRobotEntity.addComponent(oRobotModel)
(continues on next page)
47.18. Scence 505

Ring Documentation, Release 1.14
(continued from previous page)
oRobotEntity.addComponent(oRobotTransform)
oRobotEntity.addComponent(oRobotMaterial)
oView.setRootEntity(oRootEntity)
oWidget {
setwindowtitle("Using Qt3D - Scene")
showfullscreen()
}
oContainer.resize(oWidget.width(),oWidget.height())
oFilter newQAllEvents(oView)
oFilter.setKeyPressEvent("pKeyPress()")
oView.installeventfilter(oFilter)
oContainer.setfocus(0)
exec()
}
funcpKeyPress
nKey
nSpeed.1
cX
CY
cZ
cVCx
cVCy
cVCz
switchnKey
onQt_Key_Right
ifcX.8
robotX+=
oCameraEntity.setPosition(
newQVector3D(cX+0.1, cY, cZ))
oCameraEntity.setViewCenter(
newQVector3D(cVCx+nSpeed, cVCy, cVCz))
oRobotTransform.setRotation(
oQ.fromAxisAndAngle(newQVector3D(0,,),
˓→170))
ok
onQt_Key_Left
ifcX.8
robotX-=
oCameraEntity.setPosition(
newQVector3D(cX-0.1, cY, cZ))
oCameraEntity.setViewCenter(
newQVector3D(cVCx-nSpeed, cVCy, cVCz))
oRobotTransform.setRotation(
oQ.fromAxisAndAngle(newQVector3D(0,,),))
ok
onQt_Key_Down
ifrobotY3.5
robotY-=
(continues on next page)
47.18. Scence 506

Ring Documentation, Release 1.14
(continued from previous page)
oCameraEntity.setPosition(
newQVector3D(cX, cY, cZ))
oRobotTransform.setRotation(
oQ.fromAxisAndAngle(newQVector3D(0,,),))
ok
onQt_Key_Up
ifrobotY
robotY+=
oCameraEntity.setPosition(
newQVector3D(cX, cY, cZ))
oRobotTransform.setRotation(
oQ.fromAxisAndAngle(newQVector3D(0,,),))
ok
onQt_Key_Escape
oWidget.close()
off
oRobotTransform.setTranslation( newQVector3D(robotX, robotY, robotZ))
47.18. Scence 507

CHAPTER
FORTYEIGHT
OBJECTS LIBRARY FOR RINGQT APPLICATION
In this chapter we will learn about the objects library and using it in GUI applications.
Instead of using global variables for windows objects and connecting events to objects using the object name, the
Objects Library will manage a list of the GUI objects and will provide a more natural API to quickly create one or
many windows from the same class.
Also the Objects Library provide a way to quickly set methods to be executed when an event is red. Also the library
provide a natural interface to quickly use the parent or the caller windows from the child or sub windows and the other
way around.
The Objects Library is designed to be used with the MVC Design Pattern.
The Objects Library uses reection and meta-programming to add new methods to Controller classes to provide an
easy way for communication between these classes.
The Objects Library is called automatically by the GUILib
Also we can call it alone by using the next command
load"objectslib.ring"
The ObjectsLib provide functions like openObject(), lastObject() and a class called ObjectsParent
The GUILib provide a new specic API for GUI applications like openWindow(), lastWindow(), etc.
48.1
•
•
•
•
•
•
•
•
•
•
•
508

Ring Documentation, Release 1.14
•
•
48.2
In the next example we will create two types of windows.
•
•
•
•
•
load"guilib.ring"
newqApp {
openWindow( :MainWindowController )
exec()
}
classMainWindowController fromWindowsControllerParent
oView newMainWindowView
funcSubWindowAction
openWindow( :SubWindowController )
lastWindow().SetParentObject(self)
classMainWindowViewfromWindowsViewParent
win newqWidget() {
SetWindowTitle("Main Window")
btnSub newqPushButton(win) {
setText("Sub Window")
setClickEvent( Method( :SubWindowAction ) )
}
resize(400,400)
}
classSubWindowController fromWindowsControllerParent
oView newSubWindowView
funcSetMainWindowTitleAction
Parent().oView.win.SetWindowTitle("Message from the Sub Window")
oView.win.SetWindowTitle("Click Event Done!")
classSubWindowViewfromWindowsViewParent
win newqWidget() {
SetWindowTitle("Sub Window")
btnMsg newqPushButton(win) {
setText("Set Main Window Title")
setClickEvent( Method( :SetMainWindowTitleAction ) )
}
btnClose newqPushButton(win) {
Move(200,0)
setText("Close")
setClickEvent( Method( :CloseAction ) )
(continues on next page)
48.2. Example 509

Ring Documentation, Release 1.14
(continued from previous page)
}
resize(400,400)
}
The next screen shot after creating three sub windows.
The next screen shot after clicking on the button in each sub window.
48.2. Example 510

Ring Documentation, Release 1.14
48.3
We can use the openWindowAndLink() function to connect between the application windows, pass messages (call
methods) between the objects.
This function uses Meta-programming to dene dynamic methods in the Caller Class to use the dynamic objects of
other windows that we create.
Example : (Uses the Form Designer)
First Window
(1)
rstwindowView.ring
(2)
rstwindowController.ring
Second Window
48.3. openWindowAndLink() Function 511

Ring Documentation, Release 1.14
(1)
secondwindowView.ring
(2)
secondwindowController.ring
In the next code for example (from FirstWindowController.ring)
The openWindowAndLink() will create an object from the SecondWindowController Class
Then will add the SecondWindow() and IsSecondWindow() Methods to the FirstWindowController Class
Also will add the FirstWindow() and IsFirstWindow() Methods to the SecondWindowController Class
So the SendMessage() method in FirstWindowController class can use the SecondWindow() method to access the
object.
This is more simple than using lastWindow(), Parent() and SetParentObject() methods.
classfirstwindowController fromwindowsControllerParent
oView newfirstwindowView
funcOpenSecondWindow
openWindowAndLink(:SecondWindowController,self)
funcSendMessage
ifIsSecondWindow()
SecondWindow().setMessage("Message from the first window")
ok
funcsetMessage cMessage
oView.Label1.setText(cMessage)
48.4
The openWindowInPackages() function is the same as openWindow() but takes an extra list that determine the pack-
ages to import before opening the window.
Syntax:
openWindowInPackages(cClassName,aPackagesList)
Example:
The next example from the Form Designer source code, Open the Window Flags window using the openWindowIn-
Packages() function.
We determine the class name “WindowFlagsController” and the packages name.
The Window Flags window uses the FormDesigner and System.GUI packages.
openWindowInPackages(:WindowFlagsController,[
"formdesigner",
"System.GUI"
])
48.4. openWindowInPackages() Function 512

Ring Documentation, Release 1.14
48.5
The library source code is very simple, You can check the source code les
The source code for the Objects Library (can be used without GUILib)
•
•
The source code for the MVC classes in GUILib
•
•
48.5. Objects Library Source Code 513

CHAPTER
FORTYNINE
MULTI-LANGUAGE APPLICATIONS
There are many ways to create multi-language Ring application!
In this chapter we will learn about using the String2Constant tool
49.1
Starting from Ring 1.8 we have the String2Constant application
You will nd this tool in the ring/tools/string2constant folder
Using this tool we can convert the source code to be based on constants instead of string literals
Then we can store constants in separate source code les that we can translate to different languages
Where we can have special le for each language, like (English.ring, Arabic.ring and so on)
Using this simple tool, the Form Designer is translated to Arabic language too just as an example.
514

Ring Documentation, Release 1.14
49.2
You will nd the form designer application in the ring/applications/formdesigner folder
The les used for translation are stored in the ring/applications/formdesinger/translation folder
You will nd two les
•
•
You can check these les to get an idea about constants denition.
The next section from the English.ring le
49.2. Form Designer Translation 515

Ring Documentation, Release 1.14
T_LANGUAGEenglish"
T_LAYOUTDIRECTION # Left to Right
T_FORMDESIGNER_FORMDESIGNERForm Designer"
T_FORMDESIGNER_FORMTITLEForm1"
T_FORMDESIGNER_FILEFile"
T_FORMDESIGNER_NEWNew"
T_FORMDESIGNER_OPENOpen"
T_FORMDESIGNER_SAVESave"
T_FORMDESIGNER_SAVEASSave As"
T_FORMDESIGNER_CLOSEClose"
The form designer source code les will use these constants instead of typing the string literals
the next section from the formdesigner/mainwindow/formdesignerview.ring
# Create the Main Window and use the Mdi Area
win newqMainwindow() {
setWindowTitle(T_FORMDESIGNER_FORMDESIGNER) # "Form Designer"
setcentralWidget(this.oArea)
setLayoutDirection(T_LAYOUTDIRECTION)
}
•
•
•
49.3
After creating the form using the Form Designer, the View class will be generated.
We don't modify the view class, We just add the translation through the Controller class.
For example, we have the form le : ring/formdesigner/selobjects/selobjects.rform
49.3. Forms Translation 516

Ring Documentation, Release 1.14
And we add the translation through the Controller class using the next code
And we dene the constants in English.ring and Arabic.ring
classselobjectsController fromwindowsControllerParent
oView newselobjectsView {
ListObjects.setselectionmode(QAbstractItemView_MultiSelection)
win.setwindowmodality(2)
# Translation
win.setWindowTitle(T_FORMDESIGNER_SELOBJECTS_TITLE)
win.setLayoutDirection(T_LAYOUTDIRECTION)
labelobjects.setText(T_FORMDESIGNER_SELOBJECTS_OBJECTS)
btnSelect.setText(T_FORMDESIGNER_SELOBJECTS_SELECT)
btnClose.setText(T_FORMDESIGNER_SELOBJECTS_CLOSE)
}
49.3. Forms Translation 517

CHAPTER
FIFTY
BUILDING RINGQT APPLICATIONS FOR MOBILE
In this chapter we will learn about Building RingQt Applications for Mobile.
50.1
Check the next link :
Download
•
https://developer.android.com/sdk/index.html
•
http://developer.android.com/tools/sdk/ndk/index.html
•
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
50.2
Update the Android SDK to get the API and tools packages required for development
Tested using Android 4.4.2 (API 19)
•
(1)
ForExample : C:\Program Files (x86)\Java\jdk1.8.0_05
(2)
ForExample : C:\JavaAndroid\AndroidSDK
518

Ring Documentation, Release 1.14
50.3
•
https://download.qt.io/archive/qt/5.12/5.12.6/
•Run Qt Creator, Select Tools > Options > Android to add theAndroid NDK and SDK paths.
http://doc.qt.io/qtcreator/creator-developing-android.html
50.4
We can use Ring2EXE to quickly prepare Qt project for our application
Example:
ring2exe myapp.ring -dist -mobileqt
Note:We can use the Distribute Menu in Ring Notepad
Tip:The option ( Prepare Qt project for Mobile devices ) in the Distribute Menu
50.5
After using Ring2EXE or the Distribute Menu in Ring Notepad
•
Folder : target/mobile/qtproject
Project le : project.pro
•
This le (Ring Object File) is generated by the Ring compiler using
ring YourAppName.ring -go -norun
•
(1)
Or You can use any text editor (Notepad) and modify : project.qrc
(2)
Example
ifisandroid()
mypic newQPixmap(":/cards.jpg")
else
mypic newQPixmap("cards.jpg")
ok
50.3. Install Qt for Android 519

Ring Documentation, Release 1.14
50.6
(1)
This le load Ring Compiler/Virtual Machine and RingQt
Then get the Ring Object File during the runtime from the resources
Then run the Ring Object File (ringapp.ringo) using the Ring VM
Through main.cpp you can extract more les from the resources to temp. folder once you add them
(create projects with many les).
(2)
•
•
•
•
Just use Qt Classes through RingQt.
For database access use the QSqlDatabase Class
Note:All of the missing libraries ((LibCurl, OpenSSL & Allegro) can be compiled for Android, but they are not
included in this Qt project.
(3)
Example:
ifisandroid()
//
else
//otherplatforms
ok
(4) Sometimes you will nd that the button text/image is repeated in drawing ! it's Qt problem that you can avoid
using the next code.
if isandroid()
setStyleSheet("
border-style: outset;
border-width: 2px;
border-radius: 4px;
border-color: black;
padding: 6px;")
ok
(5)
This is the best way to get the expected user interface to avoid problems like (controls with small/extra size)
(6)
using main.cpp)
Example:
50.6. Comments about developing for Android using RingQt 520

Ring Documentation, Release 1.14
ifisandroid()
mypic newQPixmap(":/cards.jpg")
else
mypic newQPixmap("cards.jpg")
ok
Now RingQt comes with the AppFile() function to determine the le name
Example:
mypic newQPixmap(AppFile("cards.jpg")) # Desktop or Android
(7)
Just use the Distribute Menu in Ring Notepad and select (Generate Ring Object File)
Then copy the YourAppName.ringo le to target/mobile/qtproject folder and accept replacing les.
(8)
Then when you use Ring2EXE or Ring Notepad (Distribute - Prepare Qt project for Mobile devices) the resource le
will be used
See ring/applications/cards game as an example.
50.6. Comments about developing for Android using RingQt 521

CHAPTER
FIFTYONE
BUILDING RINGQT APPLICATIONS FOR WEBASSEMBLY
In this chapter we will learn about Building RingQt Applications for WebAssembly.
51.1
Check the next link :
Tested using
•
•
emsdk install sdk-fastcomp-1.39.7-64bit
emsdk activate sdk-fastcomp-1.39.7-64bit
Check Emscripten installation
em++-version
Output
emcc (Emscripten gcc/clang-like replacement) 1.39.7
(commit 24d88487f47629fac9d4acd231497a3a412bdee8)
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
51.2
We can use Ring2EXE to quickly prepare Qt project for our application
Example:
ring2exe myapp.ring -dist -webassemblyqt
Note:We can use the Distribute Menu in Ring Notepad
522

Ring Documentation, Release 1.14
Tip:The option ( Prepare Qt project for WebAssembly ) in the Distribute Menu
51.3
After using Ring2EXE or the Distribute Menu in Ring Notepad
•
Folder : target/webassembly/qtproject
Project le : project.pro
•
This le (Ring Object File) is generated by the Ring compiler using
ring YourAppName.ring -go -norun
•
(1)
Or You can use any text editor (Notepad) and modify : project.qrc
(2)
Example
ifisWebAssembly()
mypic newQPixmap(":/cards.jpg")
else
mypic newQPixmap("cards.jpg")
ok
51.4
(1)
This le load Ring Compiler/Virtual Machine and RingQt
Then get the Ring Object File during the runtime from the resources
Then run the Ring Object File (ringapp.ringo) using the Ring VM
Through main.cpp you can extract more les from the resources to temp. folder once you add them
(create projects with many les).
(2)
Example:
ifisWebAssembly()
//
else
//otherplatforms
ok
51.3. The Qt project for your Ring application 523

Ring Documentation, Release 1.14
(3)
using main.cpp)
Example:
ifisWebAssembly()
mypic newQPixmap(":/cards.jpg")
else
mypic newQPixmap("cards.jpg")
ok
Now RingQt comes with the AppFile() function to determine the le name
Example:
mypic newQPixmap(AppFile("cards.jpg")) # Desktop, Android or WebAssembly
(4)
Just use the Distribute Menu in Ring Notepad and select (Generate Ring Object File)
Then copy the YourAppName.ringo le to target/webassembly/qtproject folder and accept replacing les.
(5)
Then when you use Ring2EXE or Ring Notepad (Distribute - Prepare Qt project for WebAssembly) the resource le
will be used
See ring/applications/cards game as an example.
(6)
(7)
(8)
(9)
(10)
Tip:We can use special functions for Uploading/Downloading les (See FileContent sample)
51.5
See the folder: ring/samples/UsingQtWASM
Folders:
•
•
•
•
51.5. Dialogs 524

Ring Documentation, Release 1.14
51.6
•
•
•
•
•
•
51.6. Online Applications 525

CHAPTER
FIFTYTWO
WEB DEVELOPMENT (CGI LIBRARY)
In this chapter we will learn about developing Web applications using a CGI Library written in the Ring language.
52.1
In this section we will learn about using Ring with the Apache HTTP Server. We can also use Ring with any web
server that supports CGI.
Note:If you are developing your application using Ring Notepad then there's no need to congure Apache manually.
52.1.1
Here we will use the XAMPP application that has Apache web server already been included. You can download
XAMPP package from this link
XAMPP :
Install then open the conguration le from the XAMPP application or search for it in the following locations based
on your operating system.
For Windows:
xampp\apache\conf\httpd.conf
For Linux:
/opt/lampp/etc/httpd.conf
For macOS:
/Applications/XAMPP/xamppfiles/etc/httpd.conf
Search for the next line and make sure that it's not commented
LoadModule cgi_module modules/mod_cgi.so
Search for : AddHandler cgi-script
Then add “.ring” to the supported cgi extensions
Example
526

Ring Documentation, Release 1.14
AddHandler cgi-script .cgi .ring
Example
AddHandler cgi-script .cgi .pl .asp .ring
Restart/Start the server using XAMPP “Manage Servers” or “Services” section
Create your web applications in a directory supported by the web server.
For Windows:
xampp\htdocs\mywebapplicationfolder
For Linux:
/opt/lampp/htdocs/mywebapplicationfolder
For macOS:
Open XAMPP application then go to "Volumes" section
Mount the "/opt/lampp" volume
Open Finder then you will find it mounted as an IP address under "Locations" on the
˓→left menu
52.2
&#3627408441;&#3627408476;&#3627408479; &#3627408453;&#3627408470;&#3627408475;&#3627408468; ??????&#3627408473;&#3627408466;&#3627408480; &#3627408481;&#3627408476; &#3627408479;&#3627408482;&#3627408475; &#3627408477;&#3627408479;&#3627408476;&#3627408477;&#3627408466;&#3627408479;&#3627408473;&#3627408486; &#3627408482;&#3627408475;&#3627408465;&#3627408466;&#3627408479; &#3627408438;&#3627408442;&#3627408444; &#3627408484;&#3627408466; &#3627408475;&#3627408466;&#3627408466;&#3627408465; &#3627408481;&#3627408476; &#3627408480;&#3627408466;&#3627408481; &#3627408481;&#3627408469;&#3627408466; &#3627408480;&#3627408469;&#3627408466;&#3627408463;&#3627408462;&#3627408475;&#3627408468; &#3627408473;&#3627408470;&#3627408475;&#3627408466; &#3627408481;&#3627408476; &#3627408473;&#3627408476;&#3627408464;&#3627408462;&#3627408481;&#3627408466; &#3627408481;&#3627408469;&#3627408466; &#3627408466;&#3627408485;&#3627408466;&#3627408464;&#3627408482;&#3627408481;&#3627408462;&#3627408463;&#3627408473;&#3627408466; ??????&#3627408473;&#3627408466; &#3627408476;&#3627408467; &#3627408453;&#3627408470;&#3627408475;&#3627408468;◁ &#3627408454;&#3627408476;˓
&#3627408444;&#3627408475;&#3627408480;&#3627408470;&#3627408465;&#3627408466; &#3627408481;&#3627408469;&#3627408466; &#3627408480;&#3627408476;&#3627408482;&#3627408479;&#3627408464;&#3627408466; &#3627408464;&#3627408476;&#3627408465;&#3627408466; ??????&#3627408473;&#3627408466; ↼*◁&#3627408479;&#3627408470;&#3627408475;&#3627408468;↽˓ &#3627408436;&#3627408465;&#3627408465; &#3627408475;&#3627408466;&#3627408485;&#3627408481; &#3627408473;&#3627408470;&#3627408475;&#3627408466; &#3627408462;&#3627408480; &#3627408481;&#3627408469;&#3627408466; &#3627408483;&#3627408466;&#3627408479;&#3627408486; ??????&#3627408479;&#3627408480;&#3627408481; &#3627408473;&#3627408470;&#3627408475;&#3627408466; &#3627408470;&#3627408475; &#3627408481;&#3627408469;&#3627408466; ??????&#3627408473;&#3627408466;.
For Windows:
#!ring -cgi
For Linux:
#!/usr/bin/ring -cgi
For macOS:
#!/usr/local/bin/ring -cgi
Note:Change the previous line based on the path to ring executable in your machine
52.2. Setting the shebang line 527

Ring Documentation, Release 1.14
52.3
In linux and Mac operating systems ring les cannot be run properly using CGI until we grant them executable
permission. You can do that using the properties section of your prefered File manager or you can do it using Terminal
as follow:
sudo chmod +x ringAppFile.ring
Note:If you are developing your application using Ring Notepad then this step will be done automatically.
52.4
The next program is the Hello World program
For Windows:
#!ring -cgi
See "content-type: text/html" +nl+nl+
"Hello World!" + nl
For Linux:
#!/usr/bin/ring -cgi
See "content-type: text/html" +nl+nl+
"Hello World!" + nl
For macOS:
#!/usr/local/bin/ring -cgi
See "content-type: text/html" +nl+nl+
"Hello World!" + nl
52.5
We can use the web library to write CGI Web applications quickly
Example (1) :
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
Text("Hello World!")
}
52.3. Grant Ring les execution permission 528

Ring Documentation, Release 1.14
Example (2) :
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
WebPage()
{
Text("Hello World!")
}
Tip:the difference between ex. 1 and ex. 2 is using WebPage() function to return the page object instead of creating
the object using new statement.
52.6
The next features are provided by the Web library to quickly create web applications.
•
•
•
•
•
•
•
•
•
52.7
The Page User Interface
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
TitleTest HTTP Get"
divstart([
boxstart()
text(Test HTTP GET"
newline()
boxend()
divstart(["600px","550px")
StyleGradient(21))
(continues on next page)
52.6. Web Library Features 529

Ring Documentation, Release 1.14
(continued from previous page)
divstart([:style"100px","100%")
stylecolor("black")58)])
formstart("ex5.ring")
tablestart(["65%","90%")
stylemarginleft("35%")
stylemargintop("30%"))
rowstart([])
cellstart([])
text (Name :
cellend()
cellstart([])
cTextboxStyle"5%")
StyleWidth("250px")
StyleColor("black")
StyleBackColor("white")
textbox([Name", :style
cellend()
rowend()
rowstart([])
cellstart([])
text (Address :
cellend()
cellstart([])
textbox([Address", :style]
cellend()
rowend()
rowstart([])
cellstart([])
text (Phone :
cellend()
cellstart([])
textbox([Phone", :style)
cellend()
rowend()
rowstart([])
cellstart([])
text (Age :
cellend()
cellstart([])
textbox([Age", :style)
cellend()
rowend()
rowstart([])
cellstart([])
text (City:
cellend()
cellstart([])
listbox([City", :items"Cairo","Riyadh","Jeddah"],
:style"5%")"400px")
cellend()
rowend()
rowstart([])
cellstart([])
text (Country :
cellend()
cellstart([])
combobox([Country",
(continues on next page)
52.7. HTTP Get Example 530

Ring Documentation, Release 1.14
(continued from previous page)
:items"Egypt","Saudi Arabia","USA"],
:style"5%")
stylewidth("400px")+
stylecolor("black")+
stylebackcolor("white")+
stylefontsize("14px"))
cellend()
rowend()
rowstart([])
cellstart([])
text (Note :
cellend()
cellstart([])
editbox([Notes",
:style"5%")
stylesize("400px","100px")+
stylecolor("black")+
stylebackcolor("white") ,
:valuewrite comments here..."
cellend()
rowend()
rowstart([])
cellstart([])
cellend()
cellstart([])
submit([Send""5%"))
cellend()
rowend()
tableend()
formend()
divend()
divend()
divend()
}
Screen Shot:
52.7. HTTP Get Example 531

Ring Documentation, Release 1.14
The Response
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
divstart(["800px","500px"))
boxstart()
text (HTTP GET Response"
boxend()
(continues on next page)
52.7. HTTP Get Example 532

Ring Documentation, Release 1.14
(continued from previous page)
divstart([+stylewidth("10%")+
stylecolor("black")+stylegradient(58))
newline()
text (Name :
newline() newline()
text (Address :
newline() newline()
text (Phone :
newline() newline()
text (Age :
newline() newline()
text (City :
newline() newline()
text (Country :
newline() newline()
text (Note :
newline() newline()
divend()
divstart([+stylewidth("90%")+
stylecolor("black")+stylegradient(47))
divstart(["1%"))
newline()
divend()
divstart(["95%"))
newline()
text ( aPageVars["Name"]
newline() newline()
text ( aPageVars["Address"]
newline() newline()
text ( aPageVars["Phone"]
newline() newline()
text ( aPageVars["Age"]
newline() newline()
text ( aPageVars["City"]
newline() newline()
text (aPageVars["Country"]
newline() newline()
text ( aPageVars["Notes"]
newline() newline()
divend()
divend()
divend()
}
Screen Shot:
52.7. HTTP Get Example 533

Ring Documentation, Release 1.14
52.8
The Page User Interface
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text(Post Test")
newline()
boxend()
divstart([=StyleFloatLeft()+StyleWidth("100px"))
newline()
text(Number1 :
text(Number2 :
divend()
formpost("ex7.ring")
divstart([+StyleWidth("200px"))
newline()
textbox([Number1") newline() newline()
textbox([Number2") newline() newline()
submit([Send"
divend()
formend()
}
Screen Shot:
52.8. HTTP POST Example 534

Ring Documentation, Release 1.14
The Response
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text(Post Result"
newline()
boxend()
divstart([+styleWidth("200px"))
newline()
text(Number1 :["Number1"]
newline() newline()
text(Number2 :["Number2"]
newline() newline()
text(Sum :0["Number1"]["Number2"]
newline()
divend()
}
Screen Shot:
52.8. HTTP POST Example 535

Ring Documentation, Release 1.14
52.9
The Page User Interface
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
Newpage
{
boxstart()
text(Upload File"
newline()
boxend()
forx to3 next
formupload("ex9.ring")
text(Customer Name :
textbox([custname")
newline() newline()
divstart(["90px"))
uploadfile("file") newline() newline()
uploadfile("file2") newline() newline()
submit([Send")
divend()
formend()
}
Screen Shot:
52.9. Upload Files 536

Ring Documentation, Release 1.14
The Response
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
cUploadPathC:/Apache2.2/htdocs/ringapp/upload/"
cUploadFolder/ringapp/upload/"
Newpage
{
boxstart()
text(Upload Result"
newline()
boxend()
newline()
divstart([="100px"))
text(Name :["custname"]
newline()
divend()
ifaPageVars["file"]=13)
getuploadedfile(self,"file")
ok
ifaPageVars["file2"]=13)
getuploadedfile(self,"file2")
ok
}
Funcgetuploadedfile oObj,cFile
# here we use object.property
# instead of object { } to avoid executing braceend method
(continues on next page)
52.9. Upload Files 537

Ring Documentation, Release 1.14
(continued from previous page)
cFileName
write(cFileName,aPageVars[cFile])
system("chmod a+x+cFileName)
oObj.newline()
oObj.text(File+cFileName+"
oObj.newline()
imageURL
oObj.link([Download")
oObj.newline()
oObj.image(
oObj.newline()
Screen Shot:
52.9. Upload Files 538

Ring Documentation, Release 1.14
52.9. Upload Files 539

Ring Documentation, Release 1.14
52.10
The Page User Interface
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
Newpage
{
boxstart()
text(Cookie Test"
newline()
boxend()
newline()
link([ex11.ring", :titleUse Cookies")
cookie("custname","Mahmoud Fayed")
cookie("custage",28)
}
Screen Shot:
The Response
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text(Cookies Values"
newline()
boxend()
link([ex10.ring", :titleback")
newline()
divstart([:style="float:left;width:200px"])
text(Name :["custname"]
newline()
text(Age :["custage"]
newline()
divend()
}
52.10. Cookies 540

Ring Documentation, Release 1.14
Screen Shot:
52.11
The Page User Interface
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text(URLEncode"
newline()
boxend()
link([ex5.ring?Name="+URLEncode("- *{Mahmoud}*-")+
"&Address=Egypt&Phone=123456&Age=28&Notes=Programmer",
:titleTest URL Encode")
}
Screen Shot:
Screen Shot:
52.11. URL Encode 541

Ring Documentation, Release 1.14
52.12
Using Templates we can write Ring code inside HTML les
Syntax:
<%= Ring Expression %>
<% Ring Statements %>
The HTML Code
<h1>Listing Numbers</h1>
<table>
<tr>
<th> <%= myheader.cColumn1 %> </th>
<th> <%= myheader.cColumn2 %> </th>
<th></th>
<th></th>
<th></th>
</tr>
<% for x in aNumbers %>
<tr>
<td> <%= x.nValue %> </td>
<td> <%= x.nSquare %> </td>
</tr>
<% next %>
</table>
The Ring Code
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
(continues on next page)
52.12. Templates 542

Ring Documentation, Release 1.14
(continued from previous page)
NewNumbersController { start() }
ClassNumbersController
MyHeader aNumbers
FuncStart
MyHeader NewHeader
{
cColumn1Number"Square"
}
aNumbers list(20)
forx tolen(aNumbers)
aNumbers[x] newnumber
{
nValue *x
}
next
cTemp"mynumbers.html",self)
NewPage
{
boxstart()
text(Test Templates"
newline()
boxend()
html(cTemp)
}
ClassHeader cColumn1 cColumn2
ClassNumber nValue nSquare
Screen Shot:
52.12. Templates 543

Ring Documentation, Release 1.14
52.12. Templates 544

Ring Documentation, Release 1.14
52.13
The text() function display HTML special characters.
If you want to write html code, use the html() function.
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text("HTML Special Characters")
newline()
boxend()
text(
<html>
<body>
<p>hello world"/p>
</body>
</html>
)
}
Screen Shot:
52.14
The Page User Interface
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text(Hash Test")
newline()
boxend()
divstart(["100px"))
(continues on next page)
52.13. HTML Special Characters 545

Ring Documentation, Release 1.14
(continued from previous page)
newline()
text(Value :
newline() newline()
divend()
formpost("ex16.ring")
divstart(["300px"))
newline()
textbox([Value")
newline() newline()
submit([Send")
divend()
formend()
}
Screen Shot:
The Response
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
NewPage
{
boxstart()
text(Hash Result"
newline()
boxend()
divstart(["100%"))
newline()
text(Value :["Value"]
newline()
text(MD5 :["Value"]) )
newline()
text(SHA1 :["Value"]) )
newline()
text(SHA256 :["Value"]) )
newline()
text(SHA224 :["Value"]) )
newline()
(continues on next page)
52.14. Hash Functions 546

Ring Documentation, Release 1.14
(continued from previous page)
text(SHA384 :["Value"]) )
newline()
text(SHA512 :["Value"]) )
newline()
divend()
}
Screen Shot:
52.15
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
cUploadPathC:/Apache2.2/htdocs/ringapp/upload/"
NewPage
{
boxstart()
text(Random Test")
newline()
boxend()
divstart(["400px"))
newline()
aList
iflen(aList)
nIndex
ifnindex ok
cItemupload/"[nIndex][1]
newline()
image(
else
text("No images!") newline()
ok
divend()
}
Screen Shot:
52.15. Random Image 547

Ring Documentation, Release 1.14
52.16
The next example print a list contains numbers from 1 to 10
Then print a list from Ring List.
Finally we have a list of buttons and when we press on a button we get a message contains the clicked button number.
To start the list we uses the ulstart() function.
To end the list we uses the ulend() function.
We uses listart() and liend() to determine the list item.
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
FuncMain
NewPage
{
ulstart([])
forx to10
listart([])
text(x)
liend()
next
ulend()
list2ul(["one","two","three","four","five"])
ulstart([])
forx to10
(continues on next page)
52.16. HTML Lists 548

Ring Documentation, Release 1.14
(continued from previous page)
listart([])
cFuncNamebtn"+x+"()"
button([])
script(scriptfuncalert(cFuncName, string(x)))
liend()
next
ulend()
}
Screen Shot:
52.16. HTML Lists 549

Ring Documentation, Release 1.14
52.16. HTML Lists 550

Ring Documentation, Release 1.14
52.17
In this example we will learn how to generate HTML tables using the tablestart(), tableend(), rowstart(), rowend()
,headerstart(), headerend(), cellstart() and cellend() functions.
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
FuncMain
NewPage
{
divstart(["400px","500px")
style(styletable()"t01"))
tablestart(["100%"))
rowstart([])
headerstart([]) text("Number") headerend()
headerstart([]) text("square") headerend()
rowend()
forx to10
rowstart([])
cellstart([]) text(x) cellend()
cellstart([]) text(x *x) cellend()
rowend()
next
tableend()
divend()
}
Screen Shot:
52.17. HTML Tables 551

Ring Documentation, Release 1.14
52.18
In this example we will learn how to use the StyleGradient() function.
The function takes the style number as input (range from 1 to 60).
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
FuncMain
NewPage
{
boxstart()
text("StyleGradient() Function")
boxend()
forx to60
divstart([center"
:style
stylesize(string(100/60 *6)+"%","50px")
stylegradient(x))
h3(x)
divend()
next
}
Screen Shot:
52.18. Gradient 552

Ring Documentation, Release 1.14
52.19
Instead of using functions/methods to generate HTML pages, we can use an object for each element in the page.
This choice means more beautiful code but slower.
The fastest method is to print HTML code directly, then using functions then using templates then using objects
(slower).
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
FuncMain
WebPage()
{
TitleUsing objects to create the Web Page content"
h1 { text("welcome") }
link
{
TitleGoogle"
Linkhttp://www.google.com"
}
div
{
iddiv1"
style30)"50%","50%")
text("Outer Div")
div
{
iddiv2"
colorwhite"
backgroundcolorgreen"
width50%"
height50%"
marginleft5%"
margintop5%"
text("Inner Div")
}
}
div
{
iddiv3"
colorblack"
backgroundcolorsilver"
width100%"
height100%"
text("Form")
form
{
methodPOST"
Actionhelloworld.ring"
Table
{
style"100%")24)
TR
{
(continues on next page)
52.19. Generating Pages using Objects 553

Ring Documentation, Release 1.14
(continued from previous page)
TD { WIDTH="10%""Name :
TD { Input { typetext"
}
TR
{
TD { WIDTH="10%""Email :
TD { Input { typetext"
}
TR
{
TD { WIDTH="10%""Password :
TD { Input { typepassword"
}
TR
{
TD { WIDTH="10%""Notes") }
TD { TextArea { width="100%"
text("type text here...") } }
}
TR
{
TD { WIDTH="10%""Gender") }
TD {
select
{
width100%"
option { text("Male") }
option { text("Female") }
}
}
}
TR
{
TD { WIDTH="10%""Role") }
TD
{
select
{
multiplemultiple"
width100%"
option { text("student") }
option { text("admin") }
}
}
}
}
Input { typesubmit"send"
Image { src="upload/profile1.jpg"="profile"}
Input { typecheckbox"Old Member"} text("old member")
Input { typerange"=1=100}
Input { typenumber"=1=100}
Input { typeradio"="black"="one"
valueone"} text("one")
}
}
div
(continues on next page)
52.19. Generating Pages using Objects 554

Ring Documentation, Release 1.14
(continued from previous page)
{
colorwhite"
backgroundcolorblue"
width100%"
UL
{
LI { TEXT("ONE") }
LI { TEXT("TWO") }
LI { TEXT("THREE") }
}
}
div
{
audio
{
srchorse.ogg"
typeaudio/ogg"
}
video
{
width
height
srcmovie.mp4"
typevideo/mp4"
}
Input
{
typecolor"
value#ff0000"
onchangeclickColor(0, -1, -1, 5)"
}
}
}
Screen Shot:
52.19. Generating Pages using Objects 555

Ring Documentation, Release 1.14
52.19. Generating Pages using Objects 556

Ring Documentation, Release 1.14
52.20
Using this class we can create HTML documents without printing the output to the standard output
So instead of using the WebLib in Web Applications only
We can use it in Console/GUI/Mobile Applications too
Example:
load"stdlib.ring"
load"weblib.ring"
importSystem.Web
(continues on next page)
52.20. HtmlPage Class 557

Ring Documentation, Release 1.14
(continued from previous page)
funcmain
mypage newHtmlPage {
h1 { text("Customers Report") }
Table
{
style"100%")4)
TR
{
TD { WIDTH="10%""Customers Count :
TD { text (100) }
}
}
Table
{
style"100%")26)
TR
{
style"100%")24)
TD { text("Name
TD { text("Age"
TD { text("Country"
TD { text("Job"
TD { text("Company"
}
forx to100
TR
{
TD { text("Test"
TD { text("30"
TD { text("Egypt"
TD { text("Sales"
TD { text("Future"
}
next
}
}
write("report.html",mypage.output())
52.21
The next example uses the Bootstrap JavaScript Library when generating the HTML page.
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
FuncMain
newBootstrapPage {
divstart([ class=container")
(continues on next page)
52.21. Using Bootstrap Library using Functions 558

Ring Documentation, Release 1.14
(continued from previous page)
divstart([ class=jumbotron")
h1("Bootstrap Page")
divend()
divstart([ class=)
divstart([ class=col-sm-4")
h3("Welcome to the Ring programming language")
p([Using a scripting language is very fun!")
divend()
divstart([ class=col-sm-4")
h3("Welcome to the Ring programming language")
p([using a scripting language is very fun!")
divend()
divstart([ class=col-sm-4")
h3("Welcome to the Ring programming language")
p([using a scripting language is very fun!")
divend()
divend()
divend()
}
Screen Shot:
52.21. Using Bootstrap Library using Functions 559

Ring Documentation, Release 1.14
52.22
The next example uses the Bootstrap JavaScript Library when generating the HTML page.
Instead of using functions to generate the HTML elements, we will use objects.
#!ring -cgi
Load"weblib.ring"
ImportSystem.Web
FuncMain
BootStrapWebPage()
{
div
{
classname
div
{
classname
H1 { text("Bootstrap Page") }
}
div
{
classname
forx to3
div
{
classnamecol-sm-4"
H3 { html("Welcome to the Ring programming language") }
P { html("Using a scripting language is very fun!") }
}
next
}
div
{
classname
div
{
classnamecol-sm-4"
Button
{
classnamebtn btn-info btn-lg"
datatoggle=modal"
datatarget#myModal"
text("Open Large Modal")
}
}
div
{
classnamecol-sm-4"
Button { classnamebtn btn-default btn-lg""default") }
Button { classnamebtn btn-primary btn-md""primary") }
Button { classnamebtn btn-sucess btn-sm""sucess") }
Button { classnamebtn btn-info btn-xs""info") }
Button { classnamebtn btn-warning""warning") }
Button { classnamebtn btn-danger""danger") }
Button { classnamebtn btn-link""link") }
(continues on next page)
52.22. Using Bootstrap Library using Objects 560

Ring Documentation, Release 1.14
(continued from previous page)
}
div
{
classnamecol-sm-4"
Button { classnamebtn btn-default btn-block""default") }
Button { classnamebtn btn-primary btn-block""primary") }
Button { classnamebtn btn-sucess btn-block""sucess") }
Button { classnamebtn btn-info btn-block""info") }
Button { classnamebtn btn-warning btn-block""warning") }
Button { classnamebtn btn-danger btn-block""danger") }
Button { classnamebtn btn-link btn-block""link") }
}
div
{
classnamecol-sm-4"
div { classnamebtn-group"
button { classname="btn btn-primary""one") }
button { classname="btn btn-primary""two") }
button { classname="btn btn-primary""three") }
}
}
div
{
classnamecol-sm-4"
div { classnamebtn-group btn-group-lg"
button { classname="btn btn-primary""one") }
button { classname="btn btn-primary""two") }
button { classname="btn btn-primary""three") }
}
}
div
{
classnamecol-sm-4"
div {
classnamebtn-group-vertical btn-group-lg"
button { classname="btn btn-primary""one") }
button { classname="btn btn-primary""two") }
button { classname="btn btn-primary""three") }
}
}
}
div { classname="modal fade"="myModal"="dialog"
div { classnamemodal-dialog modal-lg"
div { classname="modal-content"
div { classname="modal-header"
button { classname="close"="modal"
html("&times")
}
h4 { classname="modal-title"
text("Modal Header")
}
}
div { classnamemodal-body"
p { text("This is a large model.") }
}
div { classname="modal-footer"
button { classnamebtn btn-default"="modal"
(continues on next page)
52.22. Using Bootstrap Library using Objects 561

Ring Documentation, Release 1.14
(continued from previous page)
text("close")
}
}
}
}
}
}
}
Screen Shot:
52.23
The next example uses the weblib.ring & datalib.ring.
The datalib.ring contains classes for creating database applications using MVC pattern.
In this example we create an object from the SalaryController class then call the Routing method.
We dene the website variable to contains the basic url of the page.
When we create the SalaryModel class from the ModelBase class, the salary table will be opened and the columns
data will be dened as attributes in the model class.
The SalaryView class create an object from the SalaryLanguageEnglish class to be used for translation.
52.23. CRUD Example using MVC 562

Ring Documentation, Release 1.14
The method AddFuncScript is used to call the form for adding/modifying record data.
The method FormViewContent is used to determine the controls in the form when we add or modify a record.
#!ring -cgi
Load"weblib.ring"
Load"datalib.ring"
ImportSystem.Web
websiteex24.ring"
NewSalaryController { Routing() }
ClassSalaryModelfromModelBase
ClassSalaryController FromControllerBase
ClassSalaryViewFromViewBase
oLanguage newSalaryLanguageEnglish
FuncAddFuncScript oPage,oController
return oPage.scriptfuncajax("myadd",oController.cMainURL+
oController.cOperation+"=add","mysubpage")
FuncFormViewContent oController,oTranslation,oPage
return[
[[2],textbox",name",
oController.oModel.Name, oPage.stylewidth("100%"),
[[3],textbox",salary",
oController.oModel.Salary, oPage.stylewidth("50%")
]
ClassSalaryLanguageEnglish
cTitleSalary Table"
cBackback"
aColumnsTitles"ID","Name","Salary"]
cOptionsOptions"
cSearchSearch"
comboitems"Select Option...","Edit","Delete"]
cAddRecordAdd Record"
cEditRecordEdit Record"
cRecordDeletedRecord Deleted!"
aMovePages"First","Prev","Next","Last"]
cPagePage"
cOfof"
cRecordsCountRecords Count"
cSaveSave"
temp newpage
cTextAlign
cNoRecordsNo records!"
Screen Shot:
52.23. CRUD Example using MVC 563

Ring Documentation, Release 1.14
52.23. CRUD Example using MVC 564

Ring Documentation, Release 1.14
52.24
We have the users classes (Model, View & Controller) to deal with the users data like username & email.
The next code is stored in ex25_users.ring
ClassUsersModelfromModelBase
cSearchColumnusername"
ClassUsersController FromControllerBase
aColumnsNames"id","username","email"]
FuncUpdateRecord
oModel.id[cRecID]
oModel.updatecolumn("username", aPageVars[:username]
oModel.updatecolumn("email", aPageVars[:email]
oView.UpdateView(self)
ClassUsersViewfromViewBase
oLanguage newUsersLanguageEnglish
FuncAddFuncScript oPage,oController
return oPage.scriptfunc("myadd",oPage.scriptredirection("ex26.ring"))
FuncFormViewContent oController,oTranslation,oPage
return[
[oTranslation.aColumnsTitles[2],"textbox","username",
oController.oModel.UserName,oPage.stylewidth("100%")],
[oTranslation.aColumnsTitles[3],"textbox","email",
oController.oModel.Email,oPage.stylewidth("50%")]
]
ClassUsersLanguageEnglish
cTitleUsers Table"
cBackback"
aColumnsTitles"ID","User Name","Email"]
cOptionsOptions"
cSearchSearch"
comboitems"Select Option...","Edit","Delete"]
cAddRecordAdd Record"
cEditRecordEdit Record"
cRecordDeletedRecord Deleted!"
aMovePages"First","Prev","Next","Last"]
cPagePage"
cOfof"
cRecordsCountRecords Count"
cSaveSave"
temp newpage
cTextAlign
cNoRecordsNo records!"
In the le ex25.ring we load ex25_users.ring then create an object from UsersController class.
Using the created object, we call the routing method.
#!ring -cgi
Load"weblib.ring"
(continues on next page)
52.24. Users registration and Login 565

Ring Documentation, Release 1.14
(continued from previous page)
Load"datalib.ring"
Load"ex25_users.ring"
ImportSystem.Web
websiteex25.ring"
NewUsersController { Routing() }
Screen Shot:
See the next code for the registration page
#!ring -cgi
Load"weblib.ring"
Load"datalib.ring"
ImportSystem.Web
websiteex26.ring"
newpage {
boxstart()
text(Register")
newline()
boxend()
divstart([:style6)"100%","95%"))
link([back""white")])
newline()
divstart([="500","160")52))
formpost("ex27.ring")
tablestart(["2%")"2%")
stylewidth("90%"))
rowstart([])
cellstart([:style"20%")30)])
text("User Name")
(continues on next page)
52.24. Users registration and Login 566

Ring Documentation, Release 1.14
(continued from previous page)
cellend()
cellstart(["80%"))
textbox([:nameusername", :style"100%")])
cellend()
rowend()
rowstart([])
cellstart([30)])
text("Password")
cellend()
cellstart([])
textbox([:namepassword"password"])
cellend()
rowend()
rowstart([])
cellstart([30)])
text("Email")
cellend()
cellstart([])
textbox([:nameemail""100%")])
cellend()
rowend()
rowstart([])
cellstart([30)])
cellend()
cellstart([30)])
submit([:valueRegister")
cellend()
rowend()
tableend()
formend()
divend()
divend()
}
Screen Shot:
52.24. Users registration and Login 567

Ring Documentation, Release 1.14
The Registration response
#!ring -cgi
Load"weblib.ring"
Load"datalib.ring"
Load"ex25_users.ring"
ImportSystem.Web
oUser newUsersModel
oUser.Connect()
ifoUser.findwith("username",aPageVars["username"])
newpage {
text("The user name is already registered")
}
return
ok
ifoUser.findwith("email",aPageVars["email"])
newpage {
text("This email is already registered")
}
return
ok
aPageVars["salt"]32))
aPageVars["pwhash"]["password"]+aPageVars["salt"])
aPageVars["sessionid"]32))
oUser.Insert()
newpage {
cookie("sessionid",aPageVars["sessionid"])
(continues on next page)
52.24. Users registration and Login 568

Ring Documentation, Release 1.14
(continued from previous page)
text("New User Created!")
newline()
text("User Name :["username"])
newline()
}
oUser.Disconnect()
See the next code for the Login page
#!ring -cgi
Load"weblib.ring"
Load"datalib.ring"
ImportSystem.Web
websiteex28.ring"
newpage {
boxstart()
text(Login")
newline()
boxend()
divstart([:style6)"100%","95%"))
link([back""white")])
newline()
divstart([="500","130")52))
formpost("ex29.ring")
tablestart(["2%")"2%")
stylewidth("90%"))
rowstart([])
cellstart([:style"20%")30)])
text("User Name")
cellend()
cellstart(["80%"))
textbox([:nameusername", :style"100%")])
cellend()
rowend()
rowstart([])
cellstart([30)])
text("Password")
cellend()
cellstart([])
textbox([:namepassword"password"])
cellend()
rowend()
rowstart([])
cellstart([30))
cellend()
cellstart([])
submit([:valueLogin")
cellend()
rowend()
tableend()
formend()
divend()
divend()
}
52.24. Users registration and Login 569

Ring Documentation, Release 1.14
Screen Shot:
The response page
#!ring -cgi
Load"weblib.ring"
Load"datalib.ring"
Load"ex25_users.ring"
ImportSystem.Web
oUser newUsersModel
oUser.Connect()
lResult"username",aPageVars["username"])
newpage {
iflResult
ifsha256(aPagevars["password"]+oUser.Salt)
text ("Correct Password!")
aPageVars["sessionid"]32))
oUser.UpdateColumn("sessionid",aPageVars["sessionid"])
cookie("sessionid",aPageVars["sessionid"])
else
text ("Bad password!")
ok
else
text("Bad User Name!")
ok
}
oUser.Disconnect()
The next code for checking if the user needs to login or not
52.24. Users registration and Login 570

Ring Documentation, Release 1.14
#!ring -cgi
Load"weblib.ring"
Load"datalib.ring"
Load"ex25_users.ring"
ImportSystem.Web
oUser newUsersModel
oUser.Connect()
lResult"sessionid",aPageVars["sessionid"])
newpage {
iflResult
text("User Name :
else
text("Please Login First!")
ok
}
oUser.Disconnect()
52.25
In this section we will see some code from datalib.ring
The next code presents the Database, ModelBase & ControllerBase classes
ImportSystem.Web
ClassDatabase
cServerlocalhost"
cUserNameroot"
cPasswordroot"
cDatabasemahdb"
FuncConnect
con
mysql_connect(con, cServer, cUserName, cPassWord,cDatabase)
FuncDisconnect
mysql_close(con)
FuncQuery cQuery
mysql_query(con,cQuery)
FuncQueryResult
returnmysql_result(con)
FuncQueryResultWithColumns
# return columns names + query result
returnmysql_result2(con)
(continues on next page)
52.25. Database, ModelBase & ControllerBase classes 571

Ring Documentation, Release 1.14
(continued from previous page)
FuncQueryValue
aResult
ifislist(aResult) andlen(aResult)=
aResult[1]
iflen(aResult)=
returnaResult[1]
ok
ok
return0
FuncEscapeString x
ifisstring(x)
returnMySQL_Escape_String(con,x)
else
returnMySQL_Escape_String(con, string(x))
ok
Private
con NULL
ClassModelBasefromDatabase
cTableName"
cSearchColumnname"
aColumns]
aQueryResult]
ID
# set table name from class name
classname
ifright(classname,5)
cTablename-5)
ok
FuncInsert
cValues"
forxinaColumns
cValues="[x]),"
Next
cValues-1) # remove last comma
cColumns"
forxinaColumns
cColumns=,"
next
cColumns-1)
query("insert into("+cColumns+") values ("
cValues)"
FuncUpdate nID
cStr"
forxinaColumns
cStr="[x])
# the space after comma is necessary
Next
cStr-2)
(continues on next page)
52.25. Database, ModelBase & ControllerBase classes 572

Ring Documentation, Release 1.14
(continued from previous page)
query("update
FuncUpdateColumn cColumn,cValue
query("update"
EscapeString(cValue)
FuncCount cValue
query("SELECT count( *) FROM
"+cSearchColumn+""%")
returnqueryValue()
FuncRead nStart,nRecordsPerPage
query("SELECT *FROM++","
EscapeString(nRecordsPerPage) )
aQueryResult
FuncSearch cValue,nStart,nRecordsPerPage
query("SELECT *FROM++"+cSearchColumn+""
EscapeString(cValue)%"
","
aQueryResult
FuncFind nID
query("select *from
aResult[1]
# move the result from the array to the object attributes
ID
cCode"
forx tolen(aResult)
cCode=[x-1]"[x]))"
next
eval(cCode)
FuncFindWith cColumn,cValue
query("select *from+cColumn+""
EscapeString(cValue)"
aResult
iflen(aResult)
aResult[1]
else
return0
ok
# move the result from the array to the object attributes
ID[1]
cCode"
forx tolen(aResult)
cCode=[x-1]"[x]))"
next
eval(cCode)
return1
(continues on next page)
52.25. Database, ModelBase & ControllerBase classes 573

Ring Documentation, Release 1.14
(continued from previous page)
FuncDelete ID
query("delete from
FuncClear
cCode"
forxinaColumns
cCode="
next
eval(cCode)
FuncLoadModel
# create the columns array
query("SELECT *FROM+")
aQueryResult[1]
forx tolen(aQueryResult)
aColumns[x]))
next
# create attribute for each column
forxinaColumns
addattribute(self,x)
next
FuncConnect
Super.Connect()
ifnLoadModel
nLoadModel
LoadModel()
ok
private
nLoadModel
ClassControllerBase
nRecordsPerPage
nRecordsCount
nPagesCount
nActivePage
# Dynamic creation of oView = new tablenameView and oModel = new tablename.Model
classname
ifright(classname,10)
tablename-10)
cCodeoView = new+"View"
cCode=oModel = new+"Model"
eval(cCode)
oModel.connect()
ok
cSearchNamesearchname"
(continues on next page)
52.25. Database, ModelBase & ControllerBase classes 574

Ring Documentation, Release 1.14
(continued from previous page)
cPartpart"
cPageErrorThe page number is not correct"
cLastlast"
cOperationoperation"
cRecIDrecid"
aColumnsNames"id"]
fortinoModel.aColumns
aColumnsNames
next
cMainURL?"
funcRouting
switch aPageVars[cOperation]
on showtable()
on:add addrecord()
on:save saverecord()
on:delete deleterecord()
on:edit editrecord()
on:update updaterecord()
off
funcShowTable
nRecordsCount[cSearchName]
nPagesCount
ifaPageVars[cPart]
aPageVars[cPart] string(nPagesCount)
ok
nActivePage[cPart])
ifnActivePage ok
if( nActivePage andnRecordsCount
ErrorMsg(cPageError)
return
ok
nStart-1) *nRecordsPerPage
ifaPageVars[cSearchName] NULL
oModel.Read( nStart,nRecordsPerPage )
else
oModel.Search( aPageVars[cSearchName],nStart,nRecordsPerPage )
ok
oView.GridView(self)
funcAddRecord
oModel.clear()
oView.FormViewAdd(Self,:save, false)# false mean dont include record id
(continues on next page)
52.25. Database, ModelBase & ControllerBase classes 575

Ring Documentation, Release 1.14
(continued from previous page)
funcSaveRecord
oModel.Insert()
oView.SaveView(self)
funcEditRecord
oModel.Find( aPageVars[cRecID]
oView.FormViewEdit(Self,:update, true)# true mean include record id
funcUpdateRecord
oModel.update( aPageVars[cRecID]
oView.UpdateView(self)
funcDeleteRecord
oModel.Delete( aPageVars[cRecID]
oView.DeleteView()
funcbraceend
oModel.Disconnect()
52.26
In this section we will see the web library functions, classes and methods.
Function ParametersDescription
LoadVars None Save the request parameters and cookies to aPageVars List
WebPage None Create new object from the WebPage Class
BootStrapWebPageNone Create new object from the BootStrapWebPage Class
HTMLSpecialCharscString Encode Special characters to HTML equivalent
Template cFile,oObjectExecute Ring Code in cFile after accessing oObject using {}
Alert cMessage Generate HTML Web Page that display cMessage using JavaScript Alert()
HTML2PDF cString Generate and Display PDF File from HTML String (cString)
The Package System.Web contains the next classes
Class Name Description
Application Contains methods for Encoding, Decoding, Cookies & More.
Page Contains methods to generate HTML pages.
ScriptFunctions Contains methods to generate some JavaScript Functions.
StyleFunctions Contains methods to generate CSS.
PageBuffer Generate HTML Page in memory (don't print the output).
HTML2PDF Generate PDF File from HTML code.
BootStrapPage Using BootStrap Library.
WebPage Generate page using objects for each element.
HtmlPage Like WebPage but doesn't print the output to stdout.
BootStrapWebPage Generate page using objects, using BootStrap Library.
continues on next page
52.26. WebLib API 576

Ring Documentation, Release 1.14
Table 1 – continued from previous page
Class Name Description
ObjsBase Parent Class for page objects.
NewObjectsFunctionsMethods to create new objects in the page or element.
H1 Wraps HTML H1.
H2 Wraps HTML H2.
H3 Wraps HTML H3.
H4 Wraps HTML H4.
H5 Wraps HTML H5.
H6 Wraps HTML H6.
P Wraps HTML P.
Link Wraps HTML link.
NewLine Wraps HTML NewLine.
Div Wraps HTML Div.
Form Wraps HTML Form.
Input Wraps HTML Input.
TextArea Wraps HTML TextArea.
Select Wraps HTML Select.
Option Wraps HTML Option.
Image Wraps HTML Image.
UL Wraps HTML UL.
LI Wraps HTML LI.
Table Wraps HTML Table.
TR Wraps HTML TR.
TD Wraps HTML TD.
TH Wraps HTML TH.
Audio Wraps HTML Audio.
Video Wraps HTML Video.
Nav Wraps HTML Nav.
Span Wraps HTML Span.
Button Wraps HTML Button.
52.27
Method Parameters Description
DecodeStringcString Decode request parameters
Decode cString Decode multipart/form-data
GetFileNameaArray,cVar Get File Name in aArray using cVar
SetCookie name,value,expires,path,domain,secureSet Cookie
Cookie name,value Set Cookie using name and value only
GetCookiesNone Get Cookies
URLEncode cString URL Encode
ScriptLibsNone Add JavaScript Libraries like BootStrap
Print None Print Page Content
Style cStyle Add cStyle to page CSS content
StartHTML None Add HTTP Header to page content
The method DecodeString is used to get HTTP request parameters.
The methods Decode and GetFileName are used for uploading les.
52.27. Application Class 577

Ring Documentation, Release 1.14
The methods SetCookie, Cookie & GetCookies are used for adding and reading cookies.
The methods StartHTML, ScriptsLibs, Style & Print are used for page structure and JS/CSS support.
The method URLEncode is used to encode a URL to be used in HTML pages.
52.28
Method Parameters Description
text x add HTMLSpecialChars(x) to page content (accept strings and numbers)
html cString add html code to page content
h1 x add x to page content between <h1> and </h1>
h2 x add x to page content between <h2> and </h2>
h3 x add x to page content between <h3> and </h3>
h4 x add x to page content between <h4> and </h4>
h5 x add x to page content between <h5> and </h5>
h6 x add x to page content between <h6> and </h6>
p aPara HTML <p> </p>, uses aPara List as Hash to get attributes
NewLine None add <br /> to page content
AddAttributesaPara Convert aPara list as hash to HTML element attributes
Link aPara HTML <a href> and </a>, uses aPara List as Hash to get attributes
Image aPara HTML <img>, uses aPara List as Hash to get attributes
Button aPara HTML <input type=”button”>, uses aPara List as Hash to get attributes
ButtonLinkaPara HTML <input type=”button”>, uses link attribute to navigate to link
Textbox aPara HTML <input type=”text”>, uses aPara List as Hash to get attributes
Editbox aPara HTML <textarea> and </textarea>, uses aPara to get attributes
Combobox aPara HTML <select>, uses items attribute as list for <option>
Listbox aPara HTML <select multiple='multiple'>, uses items attribute for <option>
ulstart aPara HTML <ul>
ulend aPara HTML </ul>
listart aPara HTML <li>
liend aPara HTML </li>
List2UL aList Generate HTML <ul> including items from Ring List items
DivStart aPara HTML <div>, uses aPara List as Hash to get attributes
NavStart aPara HTML <nav>, uses aPara List as Hash to get attributes
SpanStart aPara HTML <span>, uses aPara List as Hash to get attributes
BoxStart None Generate Div with black background to be used as page header
DivEnd None HTML </div>
NavEnd None HTML </nav>
SpanEnd None HTML </span>
BoxEnd None HTML </div>, the same as divend()
FormStart cAction HTML <form>, with cAction as the action attribute or an empty value
FormPost cAction HTML <form method=”post”> , with cAction as the action attribute
FormEnd None HTML </form>
Submit aPara HTML <input type=”submit”>
Hidden cName,cValueHTML <input type=”hidden”>
FormUploadx HTML Form, method=”post” enctype=”multipart/form-data” and x = action
UploadFilex HTML <input type=”le”> and name = x
Video aPara HTML <video>
Audio aPara HTML <audio>
continues on next page
52.28. Page Class 578

Ring Documentation, Release 1.14
Table 2 – continued from previous page
Method Parameters Description
GetColor aPara Select Color
Radio aPara HTML <input type=”radio”>
Checkbox aPara HTML <input type=”checkbox”>
Spinner aPara HTML <input type=”number”>
Slider aPara HTML <input type=”range”>
TableStartaPara HTML <table>
TableEnd None HTML </table>
RowStart aPara HTML <tr>
RowEnd None HTML </tr>
CellStart aPara HTML <td>
CellEnd None HTML </td>
HeaderStartaPara HTML <th>
HeaderEnd None HTML </th>
aPara in the page methods is a list contains attributes and values. Using aPara we can set values for the next attributes
classname id name align style dir value onclick oncontextmenu ondblclick
onmousedown onmouseenter onmouseleave onmousemove onmouseover onmouseout
onmouseup onkeydown onkeypress onkeyup onabort onbeforeunload onerror
onhashchange onload onpageshow onpagehide onresize onscroll onunload
onblur onchange onfocus onfocusin onfocusout oninput oninvalid onreset
onsearch onselect onsubmit ondrag ondragend ondragenter ondragleave
ondragover ondragstart ondrop oncopy oncut onpaste onafterprint
onbeforeprint oncanplay oncanplaythrough ondurationchange onemptied
onended onloadeddata onloadedmetadata onloadstart onpause onplay
onplaying onprogress onratechange onseeked onseeking onstalled onsuspend
ontimeupdate onvolumechange onwaiting animationend animationiteration
animationstart transitionend onmessage onopen onmousewheel ononline
onoffline onpostate onshow onstorage ontoggle onwheel ontouchcancel
ontouchend ontouchmove ontouchstart color opacity background backgroundattachment
backgroundcolor backgroundimage backgroundposition backgroundrepeat backgroundclip
backgroundorigin backgroundsize border borderbottom borderbottomcolor
borderbottomleftradius borderbottomrightradius borderbottomstyle borderbottomwidth
bordercolor borderimage borderimageoutset borderimagerepeat borderimageslice
borderimagesource borderimagewidth borderleft borderleftcolor borderleftstyle
borderleftwidth borderradius borderright borderrightcolor borderrightstyle
borderrightwidth borderstyle bordertop bordertopcolor bordertopleftradius
bordertoprightradius bordertopstyle bordertopwidth borderwidth boxdecorationbreak
boxshadow bottom clear clip display float height left margin marginbottom marginleft
marginright margintop maxheight maxwidth minheight minwidth overflow overflowx
overflowy padding paddingbottom paddingleft paddingright paddingtop position
right top visibility width verticalalign zindex aligncontent alignitems alignself
flex flexbasis flexdirection flexflow flexgrow flexshrink flexwrap justifycontent
order hangingpunctuation hyphens letterspacing linebreak lineheight overflowwrap
tabsize textalign textalignlast textcombineupright textindent textjustify
texttransform whitespace wordbreak wordspacing wordwrap textdecoration
textdecorationcolor textdecorationline textdecorationstyle textshadow
textunderlinepositionfontfacefontfeaturevalues font fontfamily fontfeaturesettings
fontkerning fontlanguageoverride fontsize fontsizeadjust fontstretch fontstyle
fontsynthesis fontvariant fontvariantalternates fontvariantcaps fontvarianteastasian
fontvariantligatures fontvariantnumeric fontvariantposition fontweight direction
textorientation unicodebidi writingmode bordercollapse borderspacing captionside
emptycells tablelayout counterincrement counterreset liststyle liststyleimage
liststyleposition liststyletypekeyframes animation animationdelay animationdirection
(continues on next page)
52.28. Page Class 579

Ring Documentation, Release 1.14
(continued from previous page)
animationduration animationfillmode animationiterationcount animationname
animationplaystate animationtimingfunction backfacevisibility perspective
perspectiveorigin transform transformorigin transformstyle transition
transitionproperty transitionduration transitiontimingfunction transitiondelay
boxsizing content cursor imemode navdown navindex navleft navright navup
outline outlinecolor outlineoffset outlinestyle outlinewidth resize textoverflow
breakafter breakbefore breakinside columncount columnfill columngap columnrule
columnrulecolor columnrulestyle columnrulewidth columnspan columnwidth columns
widows orphans pagebreakafter pagebreakbefore pagebreakinside marks quotes
filter imageorientation imagerendering imageresolution objectfit objectposition
mask masktype mark markafter markbefore phonemes rest restafter restbefore
voicebalance voiceduration voicepitch voicepitchrange voicerate voicestress
voicevolume marqueedirection marqueeplaycount marqueespeed marqueestyle datatoggle
dataride datatarget dataslideto dataslide datadismiss dataplacement datacontent
datatrigger dataspy dataoffset dataoffsettop
52.29
This class contains methods for adding JavaScript code to the generated web page.
The class methods are merged to the Page class, so we can use the next methods with page objects directly.
Method Parameters Description
Script cCode Add cCode string between <script> and </script>
ScriptRedirec-
tion
cURL set window.location to cURL
ScriptFunc cFuncName,cCode Dene function cFuncName that contains cCode
ScriptFuncAlertcFuncName,cMsg Dene function cFuncName that uses alert() to print
cMsg
ScriptFuncAjaxcFuncName,cLink,cDiv Dene function cFuncName that load cLink in cDiv
ScriptFuncCleancFuncName,cDiv Dene function cFuncName that clear the cDiv
ScriptFuncSe-
lect
cF,aL,cD,cR,cGR,cFC,nTO,cL1,cL2Used to Edit/Delete Grid Record
ScriptScroll-
Fixed
cDiv,nSize Set cDiv as Fixed Div with Size = nSize
52.30
This class contains methods for adding CSS to the generated web page.
Like ScriptFunctions Class, The StyleFunctions class methods are merged to the Page class, so we can use the next
methods with page objects directly.
52.29. ScriptFunctions Class 580

Ring Documentation, Release 1.14
Method Parameters Description
StyleFloatLeft None Return oat: left ;
StyleFloatRight None Return oat: right ;
StyleSizeFull None Return width: 100% ; height: 100% ;
Stylecolor x Return ” color: ” + x + ” ; “
Stylebackcolor x Return ” background-color: ” + x + ” ;”
StyleTextCenter None Return “text-align: center ;”
StyleTextRight None Return “text-align: right ;”
StyleTextLeft None Return “text-align: left ;”
StyleSize x,y Return ” width: ” + x + ” ; height: ” + y + ” ;”
StyleWidth x Return ” width: ” + x + ” ;”
StyleHeight x Return ” height: ” + x + ” ;”
StyleTop x Return ” top: ” + x + ” ;”
StyleLeft x Return ” Left: ” + x + ” ;”
StylePos x,y Return ” top: ” + x + ” ;” + ” Left: ” + y + ” ;”
StyleHorizontalCenterNone Return ” margin-right:auto ; margin-left:auto; “
StyleMarginTop x Return ” margin-top: ” + x + ” ;”
StyleMarginRight x Return ” margin-right: ” + x + ” ;”
StyleMarginLeft x Return ” margin-left: ” + x + ” ;”
StyleDivCenter nWidth,nHeightCreate Div in the center of the page
StyleAbsolute None Return ” position:absolute ;”
StyleFixed None Return ” position:xed ;”
StyleZIndex x Return ” z-index: ” + x + ” ;”
StyleFontSize x Return ” font-size: ” + x + ” ;”
StyleGradient x Generate Gradient (x values from 1 to 60)
StyleTable None Set table properties
StyleTableRows id Set different color to even and odd rows in the table
StyleTableNoBorderNone Return ” border-style: none;”
52.31
We use braces to access the active WebPage object attributes
Each one of these attribute will return a new object to access again using braces.
52.31. WebPage Class 581

Ring Documentation, Release 1.14
AttributeDescription
H1 Wraps HTML H1.
H2 Wraps HTML H2.
H3 Wraps HTML H3.
H4 Wraps HTML H4.
H5 Wraps HTML H5.
H6 Wraps HTML H6.
P Wraps HTML P.
Link Wraps HTML link.
NewLineWraps HTML NewLine.
Div Wraps HTML Div.
Form Wraps HTML Form.
Input Wraps HTML Input.
TextAreaWraps HTML TextArea.
SelectWraps HTML Select.
OptionWraps HTML Option.
Image Wraps HTML Image.
UL Wraps HTML UL.
LI Wraps HTML LI.
Table Wraps HTML Table.
TR Wraps HTML TR.
TD Wraps HTML TD.
TH Wraps HTML TH.
Audio Wraps HTML Audio.
Video Wraps HTML Video.
Nav Wraps HTML Nav.
Span Wraps HTML Span.
ButtonWraps HTML Button.
52.32
The same as the WebPage class with the next changes
(1)
(2)
Syntax:
output()--> string
52.32. HtmlPage Class 582

CHAPTER
FIFTYTHREE
DEPLOYING WEB APPLICATIONS IN THE CLOUD
In this chapter we will learn about deploying Ring Web Applications in the Cloud using Heroku
53.1
We created a new project and tutorial to explain how to deploy Ring web applications in the Cloud using Heroku
Demo :
Project :
Heroku Website :
583

Ring Documentation, Release 1.14
53.2
To use this project and deploy it on Heroku
(1)
(2)
Example : testring
Note (You have to select a unique name for your application)
(3)
md MyApp
(4)
cd MyApp
(5)
git clone https://github.com/ring-lang/RingWebAppOnHeroku .
(6)
heroku login
(7)
change testring to your application name
heroku git:remote -a testring
(8)
heroku buildpacks:add --index 1 https://github.com/ring-lang/heroku-buildpack-apt
heroku buildpacks:add --index 2 https://github.com/ring-lang/heroku-buildpack-ring
(9)
git push heroku master
(10)
heroku open
53.3
To be able to run your new Ring scripts, Set the permission of the le to be executable using Git
For example, if you created a le : myscript.ring
git update-index --chmod=+x myscript.ring
git commit -m "Update file permission"
53.2. Usage 584

Ring Documentation, Release 1.14
If you are using TortoiseGit, From windows explorer, select the le
Right click —> Properties —> Git —> Executable (+x)
Then commit and deploy!
53.4
le : ringapp/helloworld.ring
To run it :
#!/app/runring.sh -cgi
see"content-type: text/html"nl+nl
see"Hello, World!"
le : ringapp/helloworld2.ring
To run it :
#!/app/runring.sh -cgi
load"weblib.ring"
importSystem.Web
newpage {
text("Hello, World!")
}
53.5
When you depoly the application, Everything will works directly!
No change is required, but in practice, You will need to update the next les to use your database
There are two scripts to interact with the database (We are using PostgreSQL in the cloud)
You will need to update the connection string in these les if you will use another database
•
•
In your practical projects, You can write better code (To be able to change the database)
Also you can create conguration le (To write the connection string in one place)
Database service :
53.4. Hello World program 585

Ring Documentation, Release 1.14
53.6
Just use Git and commit then push to heroku
le: build.bat contains the next commands for quick tests
git add .
git commit -m "Update RingWebAppOnHeroku"
git push heroku master
heroku open
53.7
Local tests using Ring Notepad on Windows (Using local Apache Web Server)
Replace the rst line in the le : ringapp/index.ring with
#!ring -cgi
Then run it from Ring Notepad (Ctrl+F6)
53.6. Deploying after updates 586

CHAPTER
FIFTYFOUR
GRAPHICS AND 2D GAMES PROGRAMMING USING RINGALLEGRO
In this chapter we will learn how to use the allegro game programming library in our Ring applications.
We have the le gamelib.ring that load the DLL library that contains wrappers for the Allegro functions
Load"allegro.rh"
ifiswindows()
LoadLib("ring_allegro.dll")
butismacosx()
LoadLib("libringallegro.dylib")
else
LoadLib("libringallegro.so")
ok
The le gamelib.ring uses the Load instruction to execute the le allegro.rh which is a ring source code le con-
tains constants to be used in our programs. Then using the function LoadLib() we can load the DLL library
“ring_allegro.dll”.
To write portable code we can change the gamelib.ring to check the platform before loading the DLL/So le.
54.1
The next example uses the Allegro library for drawing, moving objects on the screen and getting input from the
keyboard and the mouse.
Load"gamelib.ring"
al_init()
al_init_image_addon()
display640,480)
al_show_native_message_box(display,Hello",Welcome",
"Using Allegro from the Ring programming language",
"",);
al_clear_to_color(al_map_rgb(0,0,255))
BOUNCER_SIZE
bouncer_x
bouncer_y
bouncer
al_set_target_bitmap(bouncer)
(continues on next page)
587

Ring Documentation, Release 1.14
(continued from previous page)
al_clear_to_color(al_map_rgb(255,0,255))
forx to30
bouncer_x=
bouncer_y=
al_set_target_bitmap(al_get_backbuffer(display))
al_clear_to_color(al_map_rgb(0,0,0))
al_draw_bitmap(bouncer, bouncer_x, bouncer_y,)
al_draw_bitmap(bouncer,+bouncer_x,200+)
al_flip_display()
al_rest(0.1)
next
al_clear_to_color(al_map_rgb(255,255,255))
image"man2.jpg")
al_draw_bitmap(image,200,200,0)
al_flip_display()
al_rest(2)
event_queue
al_register_event_source(event_queue, al_get_display_event_source(display))
ev
timeout
al_init_timeout(timeout,.06)
FPS
timer1.0
al_register_event_source(event_queue, al_get_timer_event_source(timer))
al_start_timer(timer)
redraw true
SCREEN_W
SCREEN_H
BOUNCER_SIZE
bouncer_x.0.0
bouncer_y.0.0
bouncer_dx4.0
bouncer_dy.0
al_install_mouse()
al_register_event_source(event_queue, al_get_mouse_event_source())
al_install_keyboard()
al_register_event_source(event_queue, al_get_keyboard_event_source())
KEY_UP
KEY_DOWN
KEY_LEFT
KEY_RIGHT
Key false,false,false,false]
while
al_init_timeout(timeout,.06)
al_wait_for_event_until(event_queue, ev, timeout)
switchal_get_allegro_event_type(ev)
onALLEGRO_EVENT_DISPLAY_CLOSE
(continues on next page)
54.1. Drawing, Animation and Input 588

Ring Documentation, Release 1.14
(continued from previous page)
exit
onALLEGRO_EVENT_TIMER
# Animation
ifbouncer_x orbouncer_x
bouncer_dxbouncer_dx
ok
ifbouncer_y orbouncer_y
bouncer_dybouncer_dy
ok
bouncer_x=
bouncer_y=
# Keyboard
ifkey[KEY_UP] andbouncer_y=.0
bouncer_y=.0
ok
ifkey[KEY_DOWN] andbouncer_y=.0
bouncer_y=.0
ok
ifkey[KEY_LEFT] andbouncer_x=.0
bouncer_x=.0
ok
ifkey[KEY_RIGHT] andbouncer_x=.0
bouncer_x=.0
ok
redraw true
onALLEGRO_EVENT_MOUSE_AXES
bouncer_x
bouncer_y
onALLEGRO_EVENT_MOUSE_ENTER_DISPLAY
bouncer_x
bouncer_y
onALLEGRO_EVENT_MOUSE_BUTTON_UP
exit
onALLEGRO_EVENT_KEY_DOWN
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] true
onALLEGRO_KEY_DOWN
key[KEY_DOWN] true
onALLEGRO_KEY_LEFT
key[KEY_LEFT] true
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] true
off
onALLEGRO_EVENT_KEY_UP
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] false
onALLEGRO_KEY_DOWN
key[KEY_DOWN] false
onALLEGRO_KEY_LEFT
(continues on next page)
54.1. Drawing, Animation and Input 589

Ring Documentation, Release 1.14
(continued from previous page)
key[KEY_LEFT] false
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] false
onALLEGRO_KEY_ESCAPE
exit
off
off
ifredrawandal_is_event_queue_empty(event_queue)
redraw false
al_clear_to_color(al_map_rgb(0,0,0))
al_draw_bitmap(bouncer, bouncer_x, bouncer_y,)
al_flip_display()
ok
callgc()
end
al_destroy_timer(timer)
al_destroy_allegro_event(ev)
al_destroy_allegro_timeout(timeout)
al_destroy_event_queue(event_queue)
al_destroy_bitmap(bouncer)
al_destroy_bitmap(image)
al_destroy_display(display)
Note:In the previous example we used the function callgc() which is a Ring function to force calling the Garbage
collector inside the While/End loop.
Program Output:
At rst the program display a messagebox
54.1. Drawing, Animation and Input 590

Ring Documentation, Release 1.14
Then we see two rectangles are moving on the screen
54.1. Drawing, Animation and Input 591

Ring Documentation, Release 1.14
Then we see an image displayed on the screen
54.1. Drawing, Animation and Input 592

Ring Documentation, Release 1.14
Finally we have one rectangle, and we see it moving all of the time on the screen but we can control it using the Mouse
and/or the Keyboard
54.1. Drawing, Animation and Input 593

Ring Documentation, Release 1.14
54.2
In this example we will see how to use TrueType Fonts*.ttf in our Games using Allegro
Load"gamelib.ring"
al_init()
al_init_font_addon()
al_init_ttf_addon()
display800,600)
al_clear_to_color(al_map_rgb(0,0,255))
font"pirulen.ttf",14,0
al_draw_text(font, al_map_rgb(255,255,255),,,ALLEGRO_ALIGN_LEFT,
"Welcome to the Ring programming language")
al_flip_display()
al_rest(2)
al_destroy_display(display)
Screen Shot:
54.2. Using TrueType Fonts 594

Ring Documentation, Release 1.14
54.3
The next example play a sound le
Load"gamelib.ring"
al_init()
al_install_audio()
al_init_acodec_addon()
al_reserve_samples(1)
samplefootstep.wav"
sampleid
al_play_sample(sample,.0,.0,1.0,ALLEGRO_PLAYMODE_LOOP,sampleid)
display640,480)
al_clear_to_color(al_map_rgb(0,0,255))
al_flip_display()
al_rest(10)
(continues on next page)
54.3. Playing Sound Files 595

Ring Documentation, Release 1.14
(continued from previous page)
al_destroy_allegro_sample_id(sampleid)
al_destroy_sample(sample)
al_destroy_display(display)
al_exit()
54.4
The next example display and rotate an image
Load"gamelib.ring"
al_init()
al_init_image_addon()
display640,480)
al_set_target_bitmap(al_get_backbuffer(display))
al_clear_to_color(al_map_rgb(255,255,255))
image"man2.jpg")
al_draw_rotated_bitmap(image,0,0,250,250,150,0)
al_draw_scaled_bitmap(image,0,0,250,250,20,20,400,400,0)
al_flip_display()
al_rest(2)
al_destroy_bitmap(image)
al_destroy_display(display)
Screen Shot:
54.4. Scaling and Rotating Images 596

Ring Documentation, Release 1.14
54.5
The next example display image with white background on another image
Load"gamelib.ring"
al_init()
al_init_image_addon()
display640,480)
imageback"palace.jpg")
al_draw_bitmap(imageback,0,0,0)
image"man4.png")
al_convert_mask_to_alpha(image,al_map_rgb(255,255,255))
al_draw_bitmap(image,0,0,0)
al_flip_display()
al_rest(10)
al_destroy_bitmap(image)
al_destroy_display(display)
54.5. Display Transparent Image 597

Ring Documentation, Release 1.14
Screen Shot:
54.6
In this example we will learn how to use threads from the Allegro library
Load"gamelib.ring"
o1 newmythreads
FuncMain
al_init()
fork to5
al_create_thread("o1.thread1()")
al_create_thread("o1.thread2()")
al_create_thread("o1.thread3()")
next
al_rest(2)
ClassMythreads
(continues on next page)
54.6. Using Threads 598

Ring Documentation, Release 1.14
(continued from previous page)
cAppNameThreads Application"
FuncThread1
forx to5
seex
next
SeeThread(1)pplicationame
FuncThread2
forx to5
see*****
next
SeeThread(2)pplicationame
FuncThread3
forx to5
see!!!!
next
SeeThread(3)pplicationame
Output:
1
2
3
4
5
Thread(1) : Application Name : Threads Application
***** 1
***** 2
***** 3
***** 4
***** 5
Thread(2) : Application Name : Threads Application
!!!!1
!!!!2
!!!!3
!!!!4
!!!!5
Thread(3) : Application Name : Threads Application
1
2
3
4
5
Thread(1) : Application Name : Threads Application
!!!!1
!!!!2
!!!!3
!!!!4
!!!!5
Thread(3) : Application Name : Threads Application
***** 1
***** 2
***** 3
***** 4
***** 5
(continues on next page)
54.6. Using Threads 599

Ring Documentation, Release 1.14
(continued from previous page)
Thread(2) : Application Name : Threads Application
***** 1
***** 2
***** 3
***** 4
***** 5
Thread(2) : Application Name : Threads Application
!!!!1
!!!!2
!!!!3
!!!!4
!!!!5
Thread(3) : Application Name : Threads Application
1
2
3
4
5
Thread(1) : Application Name : Threads Application
***** 1
***** 2
***** 3
***** 1
***** 4
***** 2
!!!!1
***** 5
***** 3
1
!!!!2
Thread(2) : Application Name : Threads Application
1
***** 4
!!!!1
2
!!!!3
!!!!4
***** 5
!!!!2
3
2
!!!!5
Thread(2) : Application Name : Threads Application
!!!!3
4
3
Thread(3) : Application Name : Threads Application
!!!!4
5
4
!!!!5
Thread(1) : Application Name : Threads Application
5
Thread(3) : Application Name : Threads Application
Thread(1) : Application Name : Threads Application
54.6. Using Threads 600

CHAPTER
FIFTYFIVE
DEMO PROJECT - GAME ENGINE FOR 2D GAMES
In this chapter we will learn about using the different programming paradigms in the same project.
We will create a simple Game Engine for 2D Games.
You can use the Engine directly to create 2D Games for Desktop or Mobile.
55.1
The project contains the next layers
•
•
•
•
55.2
We already have RingAllegro to use the Allegro game programming library and we have RingLibSDL to use the
LibSDL game programming library.
Both of RingAllegro and RingLibSDL are created using the C language with the help of the Ring code generator for
extensions.
Each of them is over 10,000 lines of C code which is generated after writing simple conguration les (That are
processed by the code generator).
Each conguration le determines the functions names, structures information and constants then the generator process
this conguration le to produce the C code and the library that can be loaded from Ring code.
Using RingAllegro and RingLibSDL is very similar to using Allegro and LibSDL from C code where you have the
same functions but we can build on that using the Ring language features
•
•
601

Ring Documentation, Release 1.14
55.3
In this layer we have gl_allegro.ring and gl_libsdl.ring
Each library provides the same functions to be used with interacting with the Graphics Library.
This layer hides the details and the difference between RingAllegro and RingLibSDL.
You have the same functions, Just use it and you can switch between Allegro and LibSDL at anytime.
Why ?
Allegro is very simple, we can use it to quickly create 2D games for Windows, Linux and MacOS X.
In Ring 1.0 we started by supporting Allegro.
Also LibSDL is very powerful and popular, very easy to use for Mobile Development.
Ring 1.1 comes with support for LibSDL so we can quickly create games for Mobile.
Note:We can use just one library for Desktop and Mobile development.
•
ring
•
55.4
The Engine comes with the next classes
•
•
•
•
•
•
•
•
•
•
55.3. Interface to graphics library 602

Ring Documentation, Release 1.14
55.5
In this layer we create our games using the Game Engine classes
The classes are designed to be used through Declarative Programming.
In our games we will use the next classes
•
•
•
•
•
•
Note:Other classes in the engine are for internal use by the engine.
We will introduce some examples and three simple games :-
•
•
•
55.6
The next table present the class attributes.
AttributesDescription
FPS Number determines how many times the draw() method will be called per second.
FixedFPSNumber determines how many times the animate() method will be called per second.
Title String determines the window title of the game.
Icon String determines the window icon (le name)
aObjectsList contains all objects in the game
shutdownTrue/False value to end the game loop
The next table present the class methods.
Method Description
refresh() Delete objects.
settitle(cTitle)Set the window title using a string parameter.
shutdown()Close the application.
nd(cName)Find an object using the object name
remove(nID)Remove an object using the object ID
The next table present a group of keywords dened by the class.
55.5. Games Layer 603

Ring Documentation, Release 1.14
KeywordDescription
sprite Create new Sprite object and add it to the game objects.
text Create new Text object and add it to the game objects.
animateCreate new Animate object and add it to the game objects.
sound Create new Sound object and add it to the game objects.
map Create new Map object and add it ot the game objects.
55.7
The next table present the class attributes.
AttributesDescription
enabledTrue/False determine the state of the object (Active/Not Active)
x Number determine the x position of the object.
y Number determine the y position of the object.
width Number determine the width of the object.
height Number determine the height of the object.
nIndex Number determine the ID of the object.
name String represent the object name.
animateTrue/False to animate the object or not.
move True/False to move the object using the keyboard or not.
Scaled True/False to scale the object image or not.
draw Function to be called when drawing the object.
state Function to be called for object animation.
keypressFunction to be called when a key is pressed.
mouse Function to be called when a mouse event happens.
The next table present the class methods.
Method Description
keyboard(oGame,nkey) Check Keyboard Events
mouse(oGame,nType,aMouseList)Check Mouse Events
rgb(r,g,b) Return new color using the RGB (Red, Green and Blue) Values.
55.8
Parent Class : GameObject Class
The next table present the class attributes.
AttributesDescription
image String determine the image le name.
point Number determine the limit of automatic movement of the object.
directionNumber determine the direction of movement.
nstep Number determine the increment/decrement during movement.
type Number determine the object type in the game (Optional).
transparentTrue/False value determine if the image is transparent.
55.7. GameObject Class 604

Ring Documentation, Release 1.14
The next table present the class methods.
Method Description
Draw(oGame)Draw the object
55.9
Parent Class : Sprite Class
The next table present the class attributes.
AttributesDescription
size Number determine the font size
font String determine the font le name
text String determine the text to be displayed
color Number determine the color
The next table present the class methods.
Method Description
Draw(oGame)Draw the object
55.10
Parent Class : Sprite Class
The next table present the class attributes.
AttributesDescription
frames Number determine the number of frames
frame Number determine the active frame
framewidthNumber determine the frame width.
animate True/False determine using animate or not.
scaled True/False determine scaling image or not.
The next table present the class methods.
Method Description
Draw(oGame)Draw the object
55.9. Text Class 605

Ring Documentation, Release 1.14
55.11
Parent Class : GameObject Class
The next table present the class attributes.
AttributesDescription
le String determine the sound le name.
once True/False determine to play the le one time or not (loop).
The next table present the class methods.
Method Description
playsound()Play the sound le
55.12
Parent Class : Sprite Class
The next table present the class attributes.
AttributesDescription
aMap List determine the map content using numbers.
aImages List determine the image used for each number in the map.
BlockWidthNumber determine the block width (default = 32).
BlockHeightNumber determine the block height (default = 32).
Animate True/False determine the animation status.
The next table present the class methods.
Method Description
getvalue(x,y)Return the item value in the Map according to the visible part
55.13
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
} # Start the Events Loop
Note:if you want to dene global variables, this must be before load “gameengine.ring” because this instruction will
give the control to the game engine.
55.11. Sound Class 606

Ring Documentation, Release 1.14
Screen Shot:
55.14
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
text {
x=50
animate false
size
filefonts/pirulen.ttf"
textgame development using ring is very fun!"
color0,0,0)
}
} # Start the Events Loop
Screen Shot:
55.14. Using the Game Engine - Drawing Text 607

Ring Documentation, Release 1.14
55.15
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
text {
x=50
animate false
size
filefonts/pirulen.ttf"
textgame development using ring is very fun!"
color0,0,0) # Color = black
}
text {
x=150
# Animation Part =====================================
animate true # Use Animation
(continues on next page)
55.15. Using the Game Engine - Moving Text 608

Ring Documentation, Release 1.14
(continued from previous page)
direction # Increase y
point # Continue until y=400
nStep # Each time y+= 3
#=====================================================
size
filefonts/pirulen.ttf"
textwelcome to the real world!"
color0,0,255) # Color = Blue
}
} # Start the Events Loop
Screen Shot:
55.15. Using the Game Engine - Moving Text 609

Ring Documentation, Release 1.14
55.16
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
text {
x=50
animate false
size
filefonts/pirulen.ttf"
textgame development using ring is very fun!"
color0,0,0) # Color = black
}
text {
x=150
# Animation Part ======================================
animate true # Use Animation
direction # Increase y
point # Continue until y=400
nStep # Each time y+= 3
#======================================================
size
filefonts/pirulen.ttf"
textwelcome to the real world!"
color0,0,255) # Color = Blue
}
Sound { # Play Sound
filesound/music1.wav" # Sound File Name
}
} # Start the Events Loop
55.17
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
animate {
fileimages/fire.png"
x
y
framewidth
height
nStep # Used for delay
transparent true
state funcoGame,oSelf { # Called by engine each frame
(continues on next page)
55.16. Using the Game Engine - Playing Sound 610

Ring Documentation, Release 1.14
(continued from previous page)
oSelf {
nStep--
ifnStep
nStep
ifframe # we have 13 frames in animation
frame++ # move to next frame
else
oGame.remove(oself.nIndex) # remove object
ok
ok
}
}
}
} # Start the Events Loop
55.17. Using the Game Engine - Animation 611

Ring Documentation, Release 1.14
55.18
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
forx to700step50
fory to500step50
showfire(oGame,x,y)
next
next
} # Start the Events Loop
funcshowfire oGame,nX,nY
oGame {
animate {
fileimages/fire.png"
x
y
framewidth
height
nStep # Used for delay
transparent true
state funcoGame,oSelf { # Called by engine each frame
oSelf {
nStep--
ifnStep
nStep
ifframe # we have 13 frames in animation
frame++ # move to next frame
else
frame=1
ok
ok
}
}
}
}
55.18. Using the Game Engine - Animation and Functions 612

Ring Documentation, Release 1.14
55.19
Keyboard
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
sprite
{
type # Just for our usage
x=400=400=100=100
fileimages/player.png"
transparent true
Animate= false
Move= true # we can move it using keyboard arrows
Scaled= true
}
} # Start the Events Loop
55.19. Using the Game Engine - Sprite - Automatic Movement using Keyboard 613

Ring Documentation, Release 1.14
55.20
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
sprite
{
type # Just for our usage
x=400=400=100=100
fileimages/player.png"
transparent true
Animate= false
Move= false # Custom Movement
Scaled= true
keypress funcoGame,oSelf,nKey {
oSelf {
SwitchnKey
(continues on next page)
55.20. Using the Game Engine - Sprite - Keypress event 614

Ring Documentation, Release 1.14
(continued from previous page)
onKEY_LEFT
x=
onKEY_RIGHT
x=
onKEY_UP
y=
onKEY_DOWN
y=
off
}
}
}
} # Start the Events Loop
55.21
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
sprite
{
type # Just for our usage
x=400=400=100=100
fileimages/player.png"
transparent true
Animate= false
Move= false # Custom Movement
Scaled= true
keypress funcoGame,oSelf,nKey {
oSelf {
SwitchnKey
onKEY_LEFT
x=
onKEY_RIGHT
x=
onKEY_UP
y=
onKEY_DOWN
y=
off
}
}
mouse funcoGame,oSelf,nType,aMouseList {
ifnType
oSelf {
x[GE_MOUSE_X]
y[GE_MOUSE_Y]
}
ok
}
(continues on next page)
55.21. Using the Game Engine - Sprite - Mouse event 615

Ring Documentation, Release 1.14
(continued from previous page)
}
} # Start the Events Loop
55.22
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
sprite
{
type # Just for our usage
x=400=400=100=100
fileimages/player.png"
transparent true
Animate= false
Move= false # Custom Movement
Scaled= true
keypress funcoGame,oSelf,nKey {
oSelf {
SwitchnKey
onKEY_LEFT
x=
onKEY_RIGHT
x=
onKEY_UP
y=
onKEY_DOWN
y=
off
}
}
mouse funcoGame,oSelf,nType,aMouseList {
ifnType
oSelf {
x[GE_MOUSE_X]
y[GE_MOUSE_Y]
}
ok
}
state funcoGame,oSelf {
oself {
ifx ok
ify ok
ifx-width
x= ok
ify-height
y=ogame.height ok
}
}
}
(continues on next page)
55.22. Using the Game Engine - Sprite - State event 616

Ring Documentation, Release 1.14
(continued from previous page)
} # Start the Events Loop
55.23
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
animate {
fileimages/fbbird.png"
x
y
framewidth
scaled true
height
width
nStep
transparent true
state funcoGame,oSelf {
oSelf {
# Animation
nStep--
ifnStep
nStep
ifframe
frame++
else
frame=1
ok
ok
# Move Down
y=
ify=550 ok
}
}
keypress funcogame,oself,nKey {
oself {
ifnkey
y=
ify<=0=0 ok
ok
}
}
(continues on next page)
55.23. Using the Game Engine - Animate - Events 617

Ring Documentation, Release 1.14
(continued from previous page)
mouse funcogame,oself,nType,aMouseList {
ifnType
cFunc
callcFunc(oGame,oSelf,Key_Space)
ok
}
}
} # Start the Events Loop
Screen Shot:
55.23. Using the Game Engine - Animate - Events 618

Ring Documentation, Release 1.14
55.24
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
Map {
blockwidth
blockheight
aMap
[0,0,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,1,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0]
]
aImages"images/fbwall.png",
"images/fbwallup.png",
"images/fbwalldown.png"]
state funcoGame,oSelf {
oSelf {
x=
ifx ok
}
}
}
} # Start the Events Loop
Screen Shot:
55.24. Using the Game Engine - Map 619

Ring Documentation, Release 1.14
55.25
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
Map {
blockwidth
blockheight
aMap
[0,0,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,1,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0],
(continues on next page)
55.25. Using the Game Engine - Map Events 620

Ring Documentation, Release 1.14
(continued from previous page)
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0]
]
aImages"images/fbwall.png",
"images/fbwallup.png",
"images/fbwalldown.png"]
state funcoGame,oSelf {
oSelf {
x=
ifx ok
}
}
mouse funcogame,oself,nType,aMouseList {
ifnType
oSelf {
mX[GE_MOUSE_X]
mY[GE_MOUSE_Y]
nValue
nRow
nCol
SwitchnValue
On1[nRow][nCol]
On2[nRow][nCol]
On3[nRow][nCol]
On0[nRow][nCol]
Off
}
ok
}
}
} # Start the Events Loop
Screen Shot:
55.25. Using the Game Engine - Map Events 621

Ring Documentation, Release 1.14
55.26
We can use the Object keyword (dened by the game engine) to create objects from the GameObject class.
Example:
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
Object {
x=300=200
draw funcoGame,oSelf {
oSelf {
fort to210
gl_draw_circle(x,y,t,
gl_map_rgb(t*random(255),
t*2,t*3),1)
next
(continues on next page)
55.26. Using the Game Engine - Object and Drawing 622

Ring Documentation, Release 1.14
(continued from previous page)
}
}
state funcoGame,oSelf {
oSelf {
ifx=
x+=
else
x=0
ok
}
}
keypress funcoGame,oSelf,nKey {
oSelf {
SwitchnKey
onKEY_LEFT
x=
onKEY_RIGHT
x=
onKEY_UP
y=
onKEY_DOWN
y=
off
}
}
}
} # Start the Events Loop
Screen Shot:
55.26. Using the Game Engine - Object and Drawing 623

Ring Documentation, Release 1.14
Example:
Load"gameengine.ring" # Give control to the game engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
Object {
x=300=200
draw funcoGame,oSelf {
oSelf {
fort to210
gl_draw_rectangle(x+t,y+t,
x+t*2,y+t *2,
gl_map_rgb(t*random(255),
t*2,t*3),1)
gl_draw_rectangle(x+t *2,y+t *2,
x-t*2,y-t *2,
gl_map_rgb(t*random(255),
t*2,t*3),1)
next
}
(continues on next page)
55.26. Using the Game Engine - Object and Drawing 624

Ring Documentation, Release 1.14
(continued from previous page)
}
keypress funcoGame,oSelf,nKey {
oSelf {
SwitchnKey
onKEY_LEFT
x=
onKEY_RIGHT
x=
onKEY_UP
y=
onKEY_DOWN
y=
off
}
}
}
} # Start the Events Loop
Screen Shot:
55.26. Using the Game Engine - Object and Drawing 625

Ring Documentation, Release 1.14
55.27
The Stars Fighter source code
# The Ring Standard Library
# Game Engine for 2D Games
# 2016, Mahmoud Fayed <[email protected]>
oGameState NULL
load"gameengine.ring"
funcmain
oGame NewGame
while
oGameState newGameState
oGame {
titleStars Fighter!"
sprite
{
fileimages/menu1.jpg"
x=0=800 trueanimate false
keypress funcogame,oself,nKey {
ifnkey ornKey
ogame.shutdown()
butnKey
oGameState.startplay= true
ogame.shutdown= true
ok
}
mouse funcogame,oself,nType,aMouseList {
ifnType
oGameState.startplay= true
ogame.shutdown= true
ok
}
}
text {
animate false
size
filefonts/pirulen.ttf"
textStars Fighter"
x=50
}
text {
animate false
size
filefonts/pirulen.ttf"
textVersion 1.0"
x=100
}
text {
animate false
(continues on next page)
55.27. Stars Fighter Game 626

Ring Documentation, Release 1.14
(continued from previous page)
size
filefonts/pirulen.ttf"
text(C) 2016, Mahmoud Fayed"
x=140
}
text {
animate false
size
filefonts/pirulen.ttf"
textPress Space to start"
x=470
}
text {
animate false
size
filefonts/pirulen.ttf"
textPress Esc to Exit"
x=510
}
Sound {
filesound/music1.wav"
}
}
ifoGameState.startplay
oGame.refresh()
playstart(oGame)
oGame.refresh()
ok
end
funcplaystart oGame
oSound NewSound {
filesound/music2.wav"
}
while
play(oGame)
ifogame.shutdown true oGameState.value
exit
ok
ogame.refresh()
end
oSound.Delete()
funcplay oGame
oGame
{
FPS
FixedFPS
titleStars Fighter!"
sprite
(continues on next page)
55.27. Stars Fighter Game 627

Ring Documentation, Release 1.14
(continued from previous page)
{
fileimages/stars.jpg"
x
y
point370
direction
type
state funcogame,oself {
oself {
ifx350
direction
point
butx anddirection
direction
point370
ok
}
}
}
sprite
{
fileimages/player.png"
transparent true
type
x400=100=100
animate= falsemove= trueScaled= true
mouse funcogame,oself,nType,aMouseList {
if ( aMouseList[GE_MOUSE_X]= and
aMouseList[GE_MOUSE_X]=+oSelf.width and
aMouseList[GE_MOUSE_Y]= and
aMouseList[GE_MOUSE_Y]=+oSelf.height )
ifnType
ifaMouseList[1] # left
oSelf.X=
else
oSelf.X=
ok
ifaMouseList[2] # up
oSelf.Y=
else
oSelf.Y=
ok
ok
else
ifnType
cFunc
callcFunc(oGame,oSelf,Key_Space)
ok
ok
}
keypress funcoGame,oself,nkey {
ifnkey
ogame {
sprite {
(continues on next page)
55.27. Stars Fighter Game 628

Ring Documentation, Release 1.14
(continued from previous page)
type
fileimages/rocket.png"
transparent true
x
y
width
height
point30
nstep
direction
state funcoGame,oSelf {
forxinoGame.aObjects
ifx.type
ifoself.x= andoself.y= and
oself.x= and
oself.y=
showfire(oGame,x.x+40,x.y+40)
ogame.remove(x.nindex)
oGameState.score+=10
oGameState.enemies--
checkwin(oGame)
exit
ok
ok
next
}
}
}
butnkey ornKey
ok
}
state funcoGame,oSelf {
oself {
ifx ok
ify ok
ifx-width x= ok
ify-height y=ogame.screen_h-height ok
}
}
}
forg tooGameState.enemies
sprite
{
type
fileimages/enemy.png"
transparent true
x *random(50) yg width=100=100
animate= trueScaled= true
direction
state funcoGame,oSelf {
oself {
ifx ok
ify ok
ifx-width x= ok
ify-height y=ogame.screen_h-height ok
}
ifrandom(100)
(continues on next page)
55.27. Stars Fighter Game 629

Ring Documentation, Release 1.14
(continued from previous page)
ogame {
sprite {
type
fileimages/rocket2.png"
transparent true
x
y+
width
height
point+30
nstep
direction
state funcoGame,oSelf {
x[oGameState.playerindex]
ifoself.x= andoself.y= and
oself.x= and
oself.y=
ifoGameState.value
oGameState.value-=10
ok
ogame.remove(oself.nindex)
checkgameover(oGame)
ok
}
}
}
ok
}
}
next
text {
size
filefonts/pirulen.ttf"
textDestroy All Enemies!"
nstep
color
x=50
direction
point
}
text {
animate false
point
size
filefonts/pirulen.ttf"
textScore :
x=10
state funcoGame,oSelf { oSelf { textScore :
}
text {
animate false
point
size
filefonts/pirulen.ttf"
textEnergy :
x=50
state funcoGame,oSelf { oSelf { textEnergy :
(continues on next page)
55.27. Stars Fighter Game 630

Ring Documentation, Release 1.14
(continued from previous page)
}
text {
animate false
point
size
filefonts/pirulen.ttf"
textLevel :
x=90
}
}
funccheckwin ogame
ifoGameState.gameresult return
ifoGameState.enemies
oGameState.gameresult true
oGame {
ifoGameState.level
text {
point
size
filefonts/pirulen.ttf"
textLevel Completed!"
nStep
x=10
state funcogame,oself {
ifoself.y=
ogame.shutdown true
oGameState.level++
oGameState.enemies
oGameState.gameresult false
ok
}
}
else
text {
point
size
nStep
filefonts/pirulen.ttf"
textYou Win !!!"
x=10
state funcogame,oself {
ifoself.y=
ogame.shutdown true
oGameState.value
ok
}
}
ok
}
ok
funccheckgameover ogame
ifoGameState.gameresult return
ifoGameState.value=
oGameState.gameresult true
(continues on next page)
55.27. Stars Fighter Game 631

Ring Documentation, Release 1.14
(continued from previous page)
oGame {
text {
point
size
nStep
filefonts/pirulen.ttf"
textGame Over !!!"
x=10
state funcogame,oself {
ifoself.y=
ogame.shutdown true
ok
}
}
}
showfire(oGame,oGame.aObjects[oGameState.PlayerIndex].x+40,
oGame.aObjects[oGameState.PlayerIndex].y+40)
oGame.aObjects[oGameState.PlayerIndex].enabled false
oGame.remove(oGameState.PlayerIndex)
ok
funcshowfire oGame,nX,nY
oGame {
animate {
fileimages/fire.png"
x
y
framewidth
height
nStep
transparent true
state funcoGame,oSelf {
oSelf {
nStep--
ifnStep
nStep
ifframe
frame++
else
frame=1
oGame.remove(oself.nIndex)
ok
ok
}
}
}
}
classgamestate
score
level
enemies
value
playerindex
gameresult false
(continues on next page)
55.27. Stars Fighter Game 632

Ring Documentation, Release 1.14
(continued from previous page)
startplay= false
Screen Shot:
55.28
The Flappy Bird 3000 Game source code
# The Ring Standard Library
# Game Engine for 2D Games
# 2016, Mahmoud Fayed <[email protected]>
oGameState NULL
Load"gameengine.ring"
funcmain
oGame NewGame
(continues on next page)
55.28. Flappy Bird 3000 Game 633

Ring Documentation, Release 1.14
(continued from previous page)
while
oGameState NewGameState
oGame {
titleFlappy Bird 3000"
sprite
{
fileimages/fbback.png"
x=0=800 trueanimate false
keypress funcogame,oself,nKey {
ifnkey ornKey
ogame.shutdown()
butnKey
oGameState.startplay= true
ogame.shutdown= true
ok
}
mouse funcogame,oself,nType,aMouseList {
ifnType
cFunc
callcFunc(oGame,oSelf,Key_Space)
ok
}
}
text {
animate false
size
filefonts/pirulen.ttf"
textFlappy Bird 3000"
x=50
}
text {
animate false
size
filefonts/pirulen.ttf"
textVersion 1.0"
x=100
}
text {
animate false
size
filefonts/pirulen.ttf"
text(C) 2016, Mahmoud Fayed"
x=140
}
text {
animate false
size
filefonts/pirulen.ttf"
textTo Win Get Score = 3000"
x=270
}
text {
(continues on next page)
55.28. Flappy Bird 3000 Game 634

Ring Documentation, Release 1.14
(continued from previous page)
animate false
size
filefonts/pirulen.ttf"
textPress Space to start"
x=470
}
text {
animate false
size
filefonts/pirulen.ttf"
textPress Esc to Exit"
x=510
}
animate {
fileimages/fbbird.png"
x
y
framewidth
scaled true
height
width
nStep
transparent true
animate true
direction
state funcoGame,oSelf {
oSelf {
nStep--
ifnStep
nStep
ifframe
frame++
else
frame=1
ok
ok
ifx==0 ok
ify==0 ok
ifx== ok
ify=550 ok
}
}
}
Sound {
filesound/music2.wav"
}
}
ifoGameState.startplay
oGame.refresh()
playstart(oGame)
oGame.refresh()
ok
end
(continues on next page)
55.28. Flappy Bird 3000 Game 635

Ring Documentation, Release 1.14
(continued from previous page)
funcplaystart oGame
oGame {
FPS
FixedFPS
TitleFlappy Bird 3000"
Sprite {
fileimages/fbback.png"
x=0=800 trueanimate false
keypress funcogame,oself,nKey {
ifnkey ornKey
ogame.shutdown()
ok
}
}
Map {
blockwidth
blockheight
aMap
[0,0,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,1,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0]
]
newmap(aMap)
aImages"images/fbwall.png","images/fbwallup.png",
"images/fbwalldown.png"]
state funcoGame,oSelf {
ifoGameState.gameresult false
px[3].x
py[3].y
oSelf {
x=
ifx
x
newmap(aMap)
ok
nCol0)
ifnCol=11 ornCol=15 ornCol=19 ornCol=23 ornCol=27
ifnCol=
oGameState.lastcol
oGameState.Score=
oGame { Sound {
once true
filesound/sfx_point.wav"
} }
checkwin(oGame)
ok
ok
}
ifoSelf.getvalue(px+40,py)= or
(continues on next page)
55.28. Flappy Bird 3000 Game 636

Ring Documentation, Release 1.14
(continued from previous page)
oSelf.getvalue(px+40,py+40)= or
oSelf.getvalue(px,py)= or
oSelf.getvalue(px,py+40)=
oGameState.gameresult true
oGame {
text {
point
size
nStep
filefonts/pirulen.ttf"
textGame Over !!!"
x=10
state funcogame,oself {
ifoself.y=
ogame.shutdown true
ok
ifoself.y
ogame {
Sound {
once true
filesound/sfx_die.wav"
}
}
ok
}
}
Sound {
once true
filesound/sfx_hit.wav"
}
}
ok
ok
}
}
animate {
fileimages/fbbird.png"
x
y
framewidth
scaled true
height
width
nStep
transparent true
state funcoGame,oSelf {
oSelf {
nStep--
ifnStep
nStep
ifframe
frame++
else
frame=1
ok
ok
(continues on next page)
55.28. Flappy Bird 3000 Game 637

Ring Documentation, Release 1.14
(continued from previous page)
}
if oGameState.playerwin
oGameState.down-
ifoGameState.down
oGameState.down
oself {
y=
ify=550 ok
}
ok
ok
}
keypress funcogame,oself,nKey {
ifoGameState.gameresult false
oself {
ifnkey
y=
oGameState.down
ify<=0=0 ok
ok
}
ok
}
mouse funcogame,oself,nType,aMouseList {
ifnType
cFunc
callcFunc(oGame,oSelf,Key_Space)
ok
}
}
text {
animate false
point
size
filefonts/pirulen.ttf"
textScore :
x=10
state funcoGame,oSelf {
oSelf { textScore :
}
}
}
funcnewmap aMap
aV
[1,1,3,0,0,2,1,1],
[1,3,0,0,0,2,1,1],
[1,1,1,3,0,2,1,1],
[1,1,1,3,0,0,0,0],
[0,0,0,0,2,1,1,1],
[0,0,2,1,1,1,1,1],
[0,0,0,2,1,1,1,1],
[1,1,1,3,0,2,1,1],
(continues on next page)
55.28. Flappy Bird 3000 Game 638

Ring Documentation, Release 1.14
(continued from previous page)
[1,1,1,1,1,3,0,0],
[3,0,0,2,1,1,1,1],
[3,0,0,2,3,0,0,2]
]
forx to24step4
aVar[10)+1)
fory to8
aMap[y][x][y]
next
next
funccheckwin ogame
ifoGameState.score
oGameState.gameresult true
oGameState.playerwin true
oGame {
text {
point
size
nStep
filefonts/pirulen.ttf"
textYou Win !!!"
x=10
state funcogame,oself {
ifoself.y=
ogame.shutdown true
oGameState.value
ok
}
}
}
ok
ClassGameState
down
gameresult false
Score
startplay= false
lastcol
playerwin false
Screen Shot:
55.28. Flappy Bird 3000 Game 639

Ring Documentation, Release 1.14
55.29
The Super Man 2016 Game source code
# The Ring Standard Library
# Game Engine for 2D Games
# 2016, Mahmoud Fayed <[email protected]>
oGameState NULL
Load"gameengine.ring"
funcmain
oGame NewGame
while
oGameState newGameState
oGame {
(continues on next page)
55.29. Super Man 2016 Game 640

Ring Documentation, Release 1.14
(continued from previous page)
titleSuper Man 2016"
sprite
{
fileimages/superman.jpg"
x=0=800 trueanimate false
keypress funcogame,oself,nKey {
ifnkey ornKey
ogame.shutdown()
butnKey
oGameState.startplay= true
ogame.shutdown= true
ok
}
mouse funcogame,oself,nType,aMouseList {
ifnType
oGameState.startplay= true
ogame.shutdown= true
ok
}
state funcogame,oself {
oself {
ifx500
x-=1
y-=1
width=1
height=4
ok
}
}
}
text {
animate false
size
filefonts/pirulen.ttf"
textSuper Man 2016"
x=30
}
text {
animate false
size
filefonts/pirulen.ttf"
textVersion 1.0"
x=80
}
text {
animate false
size
filefonts/pirulen.ttf"
text(C) 2016, Mahmoud Fayed"
x=120
}
text {
animate false
size
filefonts/pirulen.ttf"
textPress Space to start"
(continues on next page)
55.29. Super Man 2016 Game 641

Ring Documentation, Release 1.14
(continued from previous page)
x=470
}
text {
animate false
size
filefonts/pirulen.ttf"
textPress Esc to Exit"
x=510
}
animate {
fileimages/superman.png"
x
y
framewidth
scaled true
height
width
nStep
transparent true
animate true
direction
state funcoGame,oSelf {
oSelf {
nStep--
ifnStep
nStep
ifframe
frame++
else
frame=1
ok
ok
ifx==0 ok
ify==0 ok
ifx== ok
ify=550 ok
}
}
}
Sound {
filesound/music2.wav"
}
}
ifoGameState.startplay
oGame.refresh()
playstart(oGame)
oGame.refresh()
ok
end
funcplaystart oGame
oGame {
(continues on next page)
55.29. Super Man 2016 Game 642

Ring Documentation, Release 1.14
(continued from previous page)
FPS
FixedFPS
TitleSuper Man 2016"
Sprite {
fileimages/supermancity.jpg"
x=0=800 trueanimate false
}
Map {
blockwidth
blockheight
aMap
[0,0,0,4,4,4,0,0,0,1,0,0,0,1,4,4,0,1,0,0,0,0,4,4,0,1,4,
4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,0,1,0,0,0,1,0,3,3,3,5,3,3,3,3,0],
[0,0,4,0,4,0,4,0,0,1,0,0,0,3,4,4,4,1,0,0,0,0,4,4,0,1,4,
4,4,0,0,4,4,4,4,4,4,4,4,4,4,4,4,1,4,1,0,0,0,1,0,0,0,1,0,4,4,4,4,4,4,4,4,0],
[0,0,0,4,4,4,0,0,0,1,0,0,0,4,4,4,4,1,0,0,0,0,0,0,0,3,4,
4,4,0,0,4,0,0,0,0,0,0,4,2,0,0,4,1,4,1,4,2,4,1,0,2,0,1,0,4,4,4,4,4,4,4,4,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
0,0,0,0,4,4,4,4,4,4,4,4,1,0,0,4,1,4,1,4,1,4,1,0,1,0,1,0,2,2,2,2,2,2,2,2,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
0,0,0,0,2,0,0,0,0,0,2,0,3,0,0,0,1,4,1,4,1,4,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0,2,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,4,3,4,1,4,3,0,1,0,3,0,1,0,0,0,0,0,0,0,0],
[0,0,2,0,0,2,0,0,2,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,1,0,0,1,0,0,1,3,0,0,0,1,0,0,0,3,0,0,0,1,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0]
]
aImages"images/smwall.png","images/smwallup.png",
"images/smwalldown.png","images/smstar.png",
"images/smkey.png","images/smstar2.png"]
}
sprite {
type
animate false
fileimages/smhome.png"
x
y
width
height
transparent true
state funcoGame,oSelf {
oself {
x[2].x
ifx orx return
}
ifoGameState.gameresult oroGameState.DoorKey false
ifoGame.aObjects[oGameState.playerindex].x and
oGame.aObjects[oGameState.playerindex].y
oGameState.gameresult true
oGame {
sprite {
fileimages/smwin.jpg"
x=0=0=800=600
scaled trueanimate= false
(continues on next page)
55.29. Super Man 2016 Game 643

Ring Documentation, Release 1.14
(continued from previous page)
state funcogame,oself {
oself {
x-=5
y-=5
width=10
height=10
ifx300
ogame.shutdown true
ok
}
}
}
}
ok
}
}
animate {
fileimages/superman.png"
x
y
framewidth
scaled true
height
width
nStep
transparent true
state funcoGame,oSelf {
checkstarskeycol(oGame,oSelf)
if oGameState.playerwin
oself {
fileimages/superman.png"
height
width
fort=1to8
ifcheckwall2(oGame,oSelf,0,5,[2,1])
y=
else
exit
ok
next
ify=500 ok
}
ok
}
keypress funcogame,oself,nKey {
ifoGameState.gameresult false
oself {
ifnkey andcheckwall(oGame,oSelf,0,-40)
oGameState.value=
checkgameover(oGame)
fileimages/supermanup.png"
(continues on next page)
55.29. Super Man 2016 Game 644

Ring Documentation, Release 1.14
(continued from previous page)
height
dotransparent()
y=
oGameState.down
ify<=0=0 ok
butnkey andcheckwall(oGame,oSelf,0,40)
fileimages/supermandown.png"
dotransparent()
y=
ify>=500=500 ok
butnKey andcheckwall(oGame,oSelf,10,0)
fileimages/supermanright.png"
dotransparent()
x=
ifx=
ifoGame.aObjects[2].x4500
oGame.aObjects[2].x=
callenemystate(oGame)
else
ifx=
ifcheckwall(oGame,oSelf,10,0)
x=
ok
else
ifcheckwall(oGame,oSelf,-10,0)
x=
ok
ok
return
ok
x=400
ok
butnKey andcheckwall(oGame,oSelf,-10,0)
fileimages/supermanleft.png"
dotransparent()
x=
ifx=
x=
ifoGame.aObjects[2].x=
oGame.aObjects[2].x=
callenemystate(oGame)
x=
ok
ok
butnkey ornKey
ogame.shutdown()
ok
}
ok
}
mouse funcogame,oself,nType,aMouseList {
ifnType
oGameState.moveplayer TRUE
ButnType
oGameState.moveplayer FALSE
ok
ifoGameState.moveplayer TRUE
(continues on next page)
55.29. Super Man 2016 Game 645

Ring Documentation, Release 1.14
(continued from previous page)
ifaMouseList[GE_MOUSE_X] # left
cFunc
callcFunc(oGame,oSelf,Key_left)
else
cFunc
callcFunc(oGame,oSelf,Key_right)
ok
ifaMouseList[GE_MOUSE_Y] # up
cFunc
callcFunc(oGame,oSelf,Key_up)
else
cFunc
callcFunc(oGame,oSelf,Key_down)
ok
ok
}
}
addenemy(oGame,600)
addenemy(oGame,900)
addenemy(oGame,1550)
addenemy(oGame,2350)
addenemy(oGame,3350)
addenemy(oGame,3500)
addenemy(oGame,3670)
addenemy(oGame,3840)
text {
animate false
point
size
filefonts/pirulen.ttf"
textScore :
x=0
state funcoGame,oSelf {
oSelf { textScore :
}
}
text {
animate false
point
size
filefonts/pirulen.ttf"
textEnergy :
x=0
state funcoGame,oSelf { oSelf { textEnergy :
}
}
funcinlist nValue,aList
forxinaList
ifx
return
ok
next
(continues on next page)
55.29. Super Man 2016 Game 646

Ring Documentation, Release 1.14
(continued from previous page)
return
funccheckwall oGame,oself,diffx,diffy
alist1,2,3]
returncheckwall2(oGame,oself,diffx,diffy,aList)
funccheckwall2 oGame,oself,diffx,diffy,aList
xPos
yPos
nValue[2].getvalue(xPos,yPos)
nValue
nValue notnValue
ifnValue returnnValueok
xPos
yPos
nValue[2].getvalue(xPos,yPos)
nValue
nValue notnValue
ifnValue returnnValueok
xPos
yPos
nValue[2].getvalue(xPos,yPos)
nValue
nValue notnValue
ifnValue returnnValueok
xPos
yPos
nValue[2].getvalue(xPos,yPos)
nValue
nValue notnValue
ifnValue returnnValueok
returnnValue
funccheckopenwall oGame
ifoGameState.score
oGame.aObjects[2].aMap[3][10]
oGame.aObjects[2].aMap[4][10]
oGame.aObjects[2].aMap[5][10]
oGame.aObjects[2].aMap[6][10]
oGame.aObjects[2].aMap[7][10]
oGame.aObjects[2].aMap[8][10]
butoGameState.score
oGame.aObjects[2].aMap[3][18]
oGame.aObjects[2].aMap[4][18]
oGame.aObjects[2].aMap[5][18]
oGame.aObjects[2].aMap[6][18]
oGame.aObjects[2].aMap[7][18]
oGame.aObjects[2].aMap[8][18]
butoGameState.score
oGame.aObjects[2].aMap[1][44]
oGame.aObjects[2].aMap[2][44]
oGame.aObjects[2].aMap[3][44]
ok
(continues on next page)
55.29. Super Man 2016 Game 647

Ring Documentation, Release 1.14
(continued from previous page)
funccheckgameover ogame
ifoGameState.gameresult return
ifoGameState.value=
oGameState.value
oGameState.gameresult true
oGame {
text {
point
size
nStep
filefonts/pirulen.ttf"
textGame Over !!!"
x=10
state funcogame,oself {
ifoself.y=
ogame.shutdown true
ok
}
}
}
showfire(oGame,oGame.aObjects[oGameState.PlayerIndex].x+40,
oGame.aObjects[oGameState.PlayerIndex].y+40)
oGame.aObjects[oGameState.PlayerIndex].enabled false
oGame.remove(oGameState.PlayerIndex)
ok
funcshowfire oGame,nX,nY
oGame {
animate {
fileimages/fire.png"
x
y
framewidth
height
nStep
transparent true
state funcoGame,oSelf {
oSelf {
nStep--
ifnStep
nStep
ifframe
frame++
else
frame=1
oGame.remove(oself.nIndex)
ok
ok
}
}
}
}
funcaddenemy oGame,xPos
(continues on next page)
55.29. Super Man 2016 Game 648

Ring Documentation, Release 1.14
(continued from previous page)
oGame {
lbraceend false
sprite {
type
fileimages/smenemy.png"
transparent true
x10=100=100
animate= trueScaled= true
direction
temp
state funcoGame,oSelf {
oself {
x[2].x
ify ok
ify=100 ok
ifx orx return
}
ifrandom(10)
ifoGameState.gameresult return
ogame {
sprite {
type
fileimages/smrocket.png"
scaled true
transparent true
x
y+
width
height
point+30
nstep
direction
xvalue[2].x
temp
state funcoGame,oSelf {
oself { x[2].x }
x[oGameState.playerindex]
ifoself.x= andoself.y= and
oself.x= and
oself.y=
ifoGameState.value
oGameState.value-=1000
ok
ogame.remove(oself.nindex)
checkgameover(oGame)
ok
}
}
}
ok
}
}
}
ogame.lbraceend true
(continues on next page)
55.29. Super Man 2016 Game 649

Ring Documentation, Release 1.14
(continued from previous page)
funccheckstarskey oGame,oSelf,nValue,nRow,nCol
switchnValue
on4
oGame.aObjects[2].aMap[nRow][nCol]
oGameState.Score=
checkopenwall(oGame)
oGame { Sound {
once true
filesound/sfx_point.wav"
} }
on5
oGame.aObjects[2].aMap[nRow][nCol]
oGameState.DoorKey true
oGameState.Score=
checkopenwall(oGame)
oGame { Sound {
once true
filesound/sfx_point.wav"
} }
off
funccheckstarskeycol oGame,oSelf
nValue[2].getvalue(oSelf.x,oSelf.y)
nRow[2].getrow(oSelf.x,oSelf.y)
nCol[2].getcol(oSelf.x,oSelf.y)
checkstarskey(oGame,oSelf,nValue,nRow,nCol)
nValue[2].getvalue(oSelf.x+oSelf.width,oSelf.y+oSelf.height)
nRow[2].getrow(oSelf.x+oSelf.width,oSelf.y+oSelf.height)
nCol[2].getcol(oSelf.x+oSelf.width,oSelf.y+oSelf.height)
checkstarskey(oGame,oSelf,nValue,nRow,nCol)
nValue[2].getvalue(oSelf.x+oSelf.width,oSelf.y)
nRow[2].getrow(oSelf.x+oSelf.width,oSelf.y)
nCol[2].getcol(oSelf.x+oSelf.width,oSelf.y)
checkstarskey(oGame,oSelf,nValue,nRow,nCol)
nValue[2].getvalue(oSelf.x,oSelf.y+oSelf.height)
nRow[2].getrow(oSelf.x,oSelf.y+oSelf.height)
nCol[2].getcol(oSelf.x,oSelf.y+oSelf.height)
checkstarskey(oGame,oSelf,nValue,nRow,nCol)
funccallenemystate oGame
fortinoGame.aObjects
t {
iftype
callstate(oGame,t)
ok
}
next
ClassGameState
down
gameresult false
Score
startplay= false
(continues on next page)
55.29. Super Man 2016 Game 650

Ring Documentation, Release 1.14
(continued from previous page)
lastcol
playerwin false
DoorKey false
playerindex
value
moveplayer false
Screen Shot:
55.29. Super Man 2016 Game 651

CHAPTER
FIFTYSIX
BUILDING GAMES FOR ANDROID
In this chapter we will learn about Building RingLibSDL Games for Mobile.
So we can create packages (*.apk) for the applications that are developed using Ring Game Engine for 2D Games.
56.1
•
https://developer.android.com/studio/index.html
•
https://developer.android.com/ndk/index.html
•
http://ant.apache.org/bindownload.cgi
•
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
•
Tested using Android 4.4.2 (API 19)
•
(1)
ForExample : C:\Program Files (x86)\Java\jdk1.8.0_05
(2)
ForExample : B:\mahmoud\Tools\Java-Android\adt-bundle-windows-x86-20140702\sdk
652

Ring Documentation, Release 1.14
56.2
Open the project folder : ring/extensions/android/ringlibsdl/project
You can add the source code (*.ring) and Images/Sound Files to the assets folder.
You will nd the Flappy Bird 3000 Game ready for building.
The execution starts from the start.ring le
load"game2.ring"
56.2. Project Folder 653

Ring Documentation, Release 1.14
56.3
Move to the ring/extensions/android/ringlibsdl/project folder
We can build using the next command (We need to do this for one time only).
ndk-build
Then we can create the package (*.apk) using the next command.
ant debug
We can write a batch le for building the project (le: build.bat)
rem You will need to modify this batch file based on your environment
set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.8.0_05
set ANDROID_HOME=B:\mahmoud\Tools\JavaAndroid\adt-bundle-windows-x86-20140702\sdk
set NDK_ROOT=B:\mahmoud\Tools\JavaAndroid\android-ndk-r10c
set path=%path%;B:\mahmoud\Tools\JavaAndroid\android-ndk-r10c
set path=%path%;B:\mahmoud\Tools\JavaAndroid\apache-ant-1.9.4in
ndk-build
56.3. Building the project 654

CHAPTER
FIFTYSEVEN
DEVELOPING GAMES USING RINGRAYLIB
In this chapter we will learn how to use the RingRayLib extension.
57.1
RingRayLib is an extension for the RayLib game programming library.
Also RayGUI functions are supported by this extension.
57.2
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - basic window")
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RED)
DrawText("Congrats! You created your first window!",,,, WHITE)
EndDrawing()
end
CloseWindow()
Screen Shot:
655

Ring Documentation, Release 1.14
57.3
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - keyboard input")
ballPosition/2, screenHeight/2)
SetTargetFPS(60)
while!WindowShouldClose()
ifIsKeyDown(KEY_RIGHT) ballPosition.x= ok
ifIsKeyDown(KEY_LEFT) ballPosition.x= ok
ifIsKeyDown(KEY_UP) ballPosition.y= ok
ifIsKeyDown(KEY_DOWN) ballPosition.y= ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("move the ball with arrow keys",,,, DARKGRAY)
DrawCircleV(ballPosition,, MAROON)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.3. Input Keys 656

Ring Documentation, Release 1.14
57.4
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - mouse input")
ballPosition100,)
ballColor
SetTargetFPS(60)
while!
ballPosition
ifIsMouseButtonPressed(MOUSE_LEFT_BUTTON)
ballColor
butIsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)
ballColor
butIsMouseButtonPressed(MOUSE_RIGHT_BUTTON)
ballColor
ok
BeginDrawing()
ClearBackground(BLACK)
DrawCircleV(ballPosition,, ballColor)
(continues on next page)
57.4. Input Mouse 657

Ring Documentation, Release 1.14
(continued from previous page)
DrawText("move ball with mouse and click mouse button to change color
˓→",
10,,, YELLOW)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.5
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - 3d camera mode")
camera
0,,,/
0,,/
0,,,/
45,/-of-view Y
CAMERA_PERSPECTIVE)/
cubePosition0,,)
(continues on next page)
57.5. 3D Camera 658

Ring Documentation, Release 1.14
(continued from previous page)
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
DrawCube(cubePosition,,,, RED)
DrawCubeWires(cubePosition,,,, MAROON)
DrawGrid(10,)
EndMode3D()
DrawText("Welcome to the third dimension!",,,, DARKGRAY)
DrawFPS(10,)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.5. 3D Camera 659

Ring Documentation, Release 1.14
57.6
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - 3d camera free")
camera
10,,,/
0,,/
0,,,/
45,/-of-view Y
CAMERA_PERSPECTIVE)/
cubePosition0,,)
SetCameraMode(camera, CAMERA_FREE)/
SetTargetFPS(60)
while!WindowShouldClose()
UpdateCamera(camera)
ifIsKeyDown("Z") camera.target,,) ok
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
DrawCube(cubePosition,,,, RED)
DrawCubeWires(cubePosition,,,, MAROON)
DrawGrid(10,)
EndMode3D()
DrawRectangle(,,,, Fade(SKYBLUE,.5))
DrawRectangleLines(,,,, BLUE)
DrawText("Free camera default controls:",,,, BLACK)
DrawText("- Mouse Wheel to Zoom in-out",,,, DARKGRAY)
DrawText("- Mouse Wheel Pressed to Pan",,,, DARKGRAY)
DrawText("- Alt + Mouse Wheel Pressed to Rotate",,,,
˓→DARKGRAY)
DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom",
40,,, DARKGRAY)
DrawText("- Z to zoom to (0, 0, 0)",,,, DARKGRAY)
EndDrawing()
end
CloseWindow()
57.6. 3D Camera Free 660

Ring Documentation, Release 1.14
Screen Shot:
57.7
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - input mouse wheel")
boxPositionY/2
scrollSpeed
SetTargetFPS(60)
while!WindowShouldClose()
boxPositionY= *scrollSpeed)
BeginDrawing()
ClearBackground(RAYWHITE)
DrawRectangle(screenWidth/2, boxPositionY,,, MAROON)
DrawText("Use mouse wheel to move the cube up and down!",,,, GRAY)
DrawText("Box position Y:+boxPositionY,,,, LIGHTGRAY)
EndDrawing()
(continues on next page)
57.7. Mouse Wheel 661

Ring Documentation, Release 1.14
(continued from previous page)
end
CloseWindow()
Screen Shot:
57.8
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - input multitouch")
ballPosition-100,100)
ballColor
touchCounter
touchPosition0,0)
MAX_TOUCH_POINTS
SetTargetFPS(60)
while!WindowShouldClose()
ballPosition
(continues on next page)
57.8. Input Multi-touch 662

Ring Documentation, Release 1.14
(continued from previous page)
ballColor
ifIsMouseButtonDown(MOUSE_LEFT_BUTTON) ballColor ok
ifIsMouseButtonDown(MOUSE_MIDDLE_BUTTON) ballColor ok
ifIsMouseButtonDown(MOUSE_RIGHT_BUTTON) ballColor ok
ifIsMouseButtonPressed(MOUSE_LEFT_BUTTON) touchCounter ok
ifIsMouseButtonPressed(MOUSE_MIDDLE_BUTTON) touchCounter ok
ifIsMouseButtonPressed(MOUSE_RIGHT_BUTTON) touchCounter ok
iftouchCounter-- ok
BeginDrawing()
ClearBackground(RAYWHITE)
fori toMAX_TOUCH_POINTS-1
touchPosition
iftouchPosition.x=&=
DrawCircleV(touchPosition,, ORANGE)
DrawText(""+,
touchPosition.y,, BLACK)
ok
next
DrawCircleV(ballPosition, *3), ballColor)
DrawText("move ball with mouse and click mouse button to change color",
10,,, DARKGRAY)
DrawText("touch the screen at multiple locations to get multiple balls",
10,,, DARKGRAY)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.8. Input Multi-touch 663

Ring Documentation, Release 1.14
57.9
load "raylib.ring"
MAX_COLUMNS = 20
screenWidth = 800
screenHeight = 450
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person
˓→")
camera = Camera3d(
4, 2, 4,
0, 1, 0,
0, 1, 0,
60,
CAMERA_PERSPECTIVE
)
heights = list(MAX_COLUMNS)
positions = list(MAX_COLUMNS)
for item in positions item = vector3(0,0,0) next
colors = list(MAX_COLUMNS)
for item in colors item = BLACK next
for i = 1 to MAX_COLUMNS
heights[i] = GetRandomValue(1, 12)
positions[i] = Vector3(GetRandomValue(-15, 15),
(continues on next page)
57.9. Camera First Person 664

Ring Documentation, Release 1.14
(continued from previous page)
heights[i]/2, GetRandomValue(-15, 15) )
colors[i] = RAYLibColor(GetRandomValue(20, 255),
GetRandomValue(10, 55), 30, 255 )
next
SetCameraMode(camera, CAMERA_FIRST_PERSON)
SetTargetFPS(60)
while !WindowShouldClose()
UpdateCamera(camera)
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
DrawPlane(Vector3( 0, 0, 0 ), Vector2(32, 32 ), LIGHTGRAY) // Draw ground
DrawCube(Vector3( -16, 2.5, 0 ), 1, 5, 32, BLUE) // Draw a blue wall
DrawCube(Vector3( 16, 2.5, 0 ), 1, 5, 32, LIME) // Draw a green wall
DrawCube(Vector3( 0, 2.5, 16 ), 32, 5, 1, GOLD) // Draw a yellow wall
for i = 1 to MAX_COLUMNS
DrawCube(positions[i], 2, heights[i], 2, colors[i])
DrawCubeWires(positions[i], 2, heights[i], 2, MAROON)
next
EndMode3D()
DrawRectangle( 10, 10, 220, 70, Fade(SKYBLUE, 0.5f))
DrawRectangleLines( 10, 10, 220, 70, BLUE)
DrawText("First person camera default controls:", 20, 20, 10, BLACK)
DrawText("- Move with keys: W, A, S, D", 40, 40, 10, DARKGRAY)
DrawText("- Mouse move to look around", 40, 60, 10, DARKGRAY)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.9. Camera First Person 665

Ring Documentation, Release 1.14
57.10
load "raylib.ring"
screenWidth = 800
screenHeight = 450
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking")
camera = Camera3D(
10, 10, 10,
0, 0, 0 ,
0, 1, 0 ,
45,
CAMERA_PERSPECTIVE
)
cubePosition = Vector3( 0, 1, 0 )
cubeSize = Vector3( 2, 2, 2 )
ray = Ray(0,0,0,0,0,0)
collision = false
SetCameraMode(camera, CAMERA_FREE)
SetTargetFPS(60)
while !WindowShouldClose()
(continues on next page)
57.10. 3D Picking 666

Ring Documentation, Release 1.14
(continued from previous page)
UpdateCamera(camera)
if IsMouseButtonPressed(MOUSE_LEFT_BUTTON)
if !collision
ray = GetMouseRay(GetMousePosition(), camera)
collision = CheckCollisionRayBox(ray,
BoundingBox( cubePosition.x - cubeSize.x/2,
cubePosition.y - cubeSize.y/2, cubePosition.z - cubeSize.z/2,
cubePosition.x + cubeSize.x/2, cubePosition.y + cubeSize.y/2,
cubePosition.z + cubeSize.z/2 ) )
else collision = false
ok
ok
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
if collision
DrawCube(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z, RED)
DrawCubeWires(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z,
˓→MAROON)
DrawCubeWires(cubePosition, cubeSize.x + 0.2f,
cubeSize.y + 0.2f, cubeSize.z + 0.2f, GREEN)
else
DrawCube(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z, GRAY)
DrawCubeWires(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z,
˓→DARKGRAY)
ok
DrawRay(ray, MAROON)
DrawGrid(10, 1)
EndMode3D()
DrawText("Try selecting the box with mouse!", 240, 10, 20, DARKGRAY)
if collision DrawText("BOX SELECTED",
(screenWidth - MeasureText("BOX SELECTED", 30)) / 2,
screenHeight*0.1f, 30, GREEN) ok
DrawFPS(10, 10)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.10. 3D Picking 667

Ring Documentation, Release 1.14
57.11
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,Full Screen")
ToggleFullScreen()
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(DARKBLUE)
DrawText("Count from 1 to 10",,,, Yellow)
fort to10
DrawText("Number:,+(30 *t),, WHITE)
next
EndDrawing()
end
CloseWindow()
Screen Shot:
57.11. Full Screen 668

Ring Documentation, Release 1.14
57.12
load "raylib.ring"
screenWidth = 800
screenHeight = 450
InitWindow(screenWidth, screenHeight, "raylib [core] example - Two Cubes")
camera = Camera3D(
10, 10, 10,
0, 0, 0 ,
0, 1, 0 ,
45,
CAMERA_PERSPECTIVE
)
cubePosition1 = Vector3( 0, 1, 4 )
cubePosition2 = Vector3( 0, 1, -4 )
cubeSize = Vector3( 2, 2, 2 )
ray = Ray(0,0,0,0,0,0)
collision1 = false
(continues on next page)
57.12. Two Cubes 669

Ring Documentation, Release 1.14
(continued from previous page)
collision2 = false
SetCameraMode(camera, CAMERA_FREE)
SetTargetFPS(60)
while !WindowShouldClose()
UpdateCamera(camera)
if IsMouseButtonPressed(MOUSE_LEFT_BUTTON)
if !collision1
ray = GetMouseRay(GetMousePosition(), camera)
collision1 = CheckCollisionRayBox(ray,
BoundingBox( cubePosition1.x -
cubeSize.x/2, cubePosition1.y - cubeSize.y/2,
cubePosition1.z - cubeSize.z/2,
cubePosition1.x + cubeSize.x/2,
cubePosition1.y + cubeSize.y/2,
cubePosition1.z + cubeSize.z/2 ) )
else
collision1 = false
ok
if !collision2
ray = GetMouseRay(GetMousePosition(), camera)
collision2 = CheckCollisionRayBox(ray,
BoundingBox( cubePosition2.x -
cubeSize.x/2, cubePosition2.y - cubeSize.y/2,
cubePosition2.z - cubeSize.z/2,
cubePosition2.x + cubeSize.x/2,
cubePosition2.y + cubeSize.y/2,
cubePosition2.z + cubeSize.z/2 ) )
else
collision2 = false
ok
ok
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
if collision1
DrawCube(cubePosition1, cubeSize.x,
cubeSize.y, cubeSize.z, RED)
DrawCubeWires(cubePosition1, cubeSize.x,
cubeSize.y, cubeSize.z, MAROON)
DrawCubeWires(cubePosition1, cubeSize.x +
0.2f, cubeSize.y + 0.2f,
cubeSize.z + 0.2f, GREEN)
collision1 = true
else
DrawCube(cubePosition1, cubeSize.x,
(continues on next page)
57.12. Two Cubes 670

Ring Documentation, Release 1.14
(continued from previous page)
cubeSize.y, cubeSize.z, GRAY)
DrawCubeWires(cubePosition1, cubeSize.x,
cubeSize.y, cubeSize.z, DARKGRAY)
collision1 = false
ok
if collision2
DrawCube(cubePosition2, cubeSize.x,
cubeSize.y, cubeSize.z, RED)
DrawCubeWires(cubePosition2, cubeSize.x,
cubeSize.y, cubeSize.z, MAROON)
DrawCubeWires(cubePosition2, cubeSize.x +
0.2f, cubeSize.y + 0.2f,
cubeSize.z + 0.2f, GREEN)
collision2 = true
else
DrawCube(cubePosition2, cubeSize.x,
cubeSize.y, cubeSize.z, GRAY)
DrawCubeWires(cubePosition2, cubeSize.x,
cubeSize.y, cubeSize.z, DARKGRAY)
collision2 = false
ok
DrawRay(ray, MAROON)
DrawGrid(10, 1)
EndMode3D()
DrawText("Try selecting the box with mouse!", 240, 10,
20, DARKGRAY)
if collision1 or collision2
DrawText("BOX SELECTED",
(screenWidth - MeasureText("BOX SELECTED", 30)) / 2,
screenHeight*0.1f, 30, GREEN)
ok
DrawFPS(10, 10)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.12. Two Cubes 671

Ring Documentation, Release 1.14
57.13
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [shapes] example - basic shapes drawing
˓→")
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("some basic shapes available on raylib",,,, DARKGRAY)
DrawCircle(screenWidth/4,,, DARKBLUE)
DrawRectangle(screenWidth/4 *2,,,, RED)
DrawRectangleLines(screenWidth/4 *2,,,, ORANGE)
DrawRectangleGradientH(screenWidth/4 *2,,,, MAROON, GOLD)
DrawTriangle(Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,), VIOLET)
(continues on next page)
57.13. Basic Shapes 672

Ring Documentation, Release 1.14
(continued from previous page)
DrawPoly(Vector2(screenWidth/4 *3,),,,, BROWN)
DrawCircleGradient(screenWidth/4,,, GREEN, SKYBLUE)
DrawLine(18,, screenWidth,, BLACK)
DrawCircleLines(screenWidth/4,,, DARKBLUE)
DrawTriangleLines(Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,), DARKBLUE)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.14
load"raylib.ring"
screenWidth
InitWindow(screenWidth, screenHeight,raylib [shapes] example - draw ring")
center)/2, GetScreenHeight()/2
(continues on next page)
57.14. Draw Ring 673

Ring Documentation, Release 1.14
(continued from previous page)
innerRadius
startAngle
drawRing true drawRingLines false drawCircleLines false
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RAYWHITE)
DrawLine(500,,, GetScreenHeight(), Fade(LIGHTGRAY,.6))
DrawRectangle(500,, GetScreenWidth(),
GetScreenHeight(), Fade(LIGHTGRAY,.3))
ifdrawRing DrawRing(center, innerRadius, outerRadius,
startAngle, endAngle, segments, Fade(MAROON,.3)) ok
ifdrawRingLines DrawRingLines(center, innerRadius,
outerRadius, startAngle, endAngle,
segments, Fade(BLACK,.4)) ok
ifdrawCircleLines DrawCircleSectorLines(center, outerRadius,
startAngle, endAngle, segments, Fade(BLACK,.4)) ok
startAngle,,,
"StartAngle", startAngle,450,, true)
endAngle,,,
"EndAngle", endAngle,450,, true)
innerRadius,,,
"InnerRadius", innerRadius,,, true)
outerRadius,,,
"OuterRadius", outerRadius,,, true)
segments,,,
"Segments", segments,,, true)
drawRing,,,
"Draw Ring", drawRing)
drawRingLines,,,
"Draw RingLines", drawRingLines)
drawCircleLines,,,
"Draw CircleLines", drawCircleLines)
ifsegments=
DrawText("MODE: MANUAL",,,, MAROON)
else
DrawText("MODE: AUTO",,,, DARKGRAY)
ok
DrawFPS(10,)
EndDrawing()
end
CloseWindow()
57.14. Draw Ring 674

Ring Documentation, Release 1.14
Screen Shot:
Screen Shot (2):
57.14. Draw Ring 675

Ring Documentation, Release 1.14
57.15
load"raylib.ring"
screenWidth
screenHeight
SetConfigFlags(FLAG_MSAA_4X_HINT)
InitWindow(screenWidth, screenHeight,raylib [shapes] example - cubic-bezier lines")
start0,0)
endvec
SetTargetFPS(60)
while(!WindowShouldClose())
if(IsMouseButtonDown(MOUSE_LEFT_BUTTON))
start
else(IsMouseButtonDown(MOUSE_RIGHT_BUTTON))
endvec
ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("USE MOUSE LEFT-RIGHT CLICK to DEFINE LINE START and END POINTS",
15,,, GRAY)
DrawLineBezier(start, endvec,.0, RED)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.15. Bezier Lines 676

Ring Documentation, Release 1.14
57.16
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [shapes] example - collision area")
//
boxA, GetScreenHeight()/2,,
boxASpeedX
//
boxB/2, GetScreenHeight()/2,,
boxCollision
boxCollision,0,0,0/
screenUpperLimit/
pause false //
collision false //
SetTargetFPS(60)
while!WindowShouldClose()
(continues on next page)
57.16. Collision Area 677

Ring Documentation, Release 1.14
(continued from previous page)
// if paused
if(notpause) boxA.x= ok
// onx screen limits
if(((boxA.x= or(boxA.x=))
boxASpeedX *(-1) ok
//-controlled-box (box02)
boxB.x/2
boxB.y/2
// notgo out of move area limits
if((boxB.x=
boxB.x
else(boxB.x=) boxB.x ok
if((boxB.y=
boxB.y
else(boxB.y= ok
//
collision
//Getcollision rectangle (only oncollision)
if(collision) boxCollision ok
//
if(IsKeyPressed(KEY_SPACE)) pause notpauseok
BeginDrawing()
ClearBackground(RAYWHITE)
ifcollision true
color
else
color
ok
DrawRectangle(0,, screenWidth, screenUpperLimit, color)
DrawRectangleRec(boxA, GOLD)
boxB.x/2
boxB.y/2
collision
DrawRectangleRec(boxB, BLUE)
boxCollision
if(collision) true
//
DrawRectangleRec(boxCollision, LIME)
//
DrawText("COLLISION!", GetScreenWidth()/2
MeasureText("COLLISION!",)/2,
screenUpperLimit/2,, BLACK)
(continues on next page)
57.16. Collision Area 678

Ring Documentation, Release 1.14
(continued from previous page)
//
DrawText("Collision Area:
string(boxCollision.width*boxCollision.height),
GetScreenWidth()/2,
screenUpperLimit,, BLACK)
ok
DrawFPS(10,)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.17
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [shapes] example - following eyes")
scleraLeftPosition/2, GetScreenHeight()/2
(continues on next page)
57.17. Following Eyes 679

Ring Documentation, Release 1.14
(continued from previous page)
scleraRightPosition/2, GetScreenHeight()/2
scleraRadius
irisLeftPosition/2, GetScreenHeight()/2
irisRightPosition/2, GetScreenHeight()/2
irisRadius
angle.0
dx.0.0.0.0
SetTargetFPS(60)
while!WindowShouldClose()
irisLeftPosition
irisRightPosition
// notinside the left eye sclera
if!CheckCollisionPointCircle(irisLeftPosition,
scleraLeftPosition, scleraRadius)
dx
dy
angle
dxx *cos(angle)
dyy *sin(angle)
irisLeftPosition.x
irisLeftPosition.y
ok
// notinside the right eye sclera
if!CheckCollisionPointCircle(irisRightPosition,
scleraRightPosition, scleraRadius)
dx
dy
angle
dxx *cos(angle)
dyy *sin(angle)
irisRightPosition.x
irisRightPosition.y
ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawCircleV(scleraLeftPosition, scleraRadius, LIGHTGRAY)
DrawCircleV(irisLeftPosition, irisRadius, BROWN)
DrawCircleV(irisLeftPosition,, BLACK)
DrawCircleV(scleraRightPosition, scleraRadius, LIGHTGRAY)
DrawCircleV(irisRightPosition, irisRadius, DARKGREEN)
(continues on next page)
57.17. Following Eyes 680

Ring Documentation, Release 1.14
(continued from previous page)
DrawCircleV(irisRightPosition,, BLACK)
DrawFPS(10,)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.18
load "raylib.ring"
MAX_COLORS_COUNT = 21 // Number of colors available
screenWidth = 800
screenHeight = 450
colors = list(MAX_COLORS_COUNT)
colorNames = list(MAX_COLORS_COUNT)
colorsRecs = list(MAX_COLORS_COUNT)
colorState = list(MAX_COLORS_COUNT)
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette")
colors = [
(continues on next page)
57.18. Colors Palette 681

Ring Documentation, Release 1.14
(continued from previous page)
DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN,
GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW,
GREEN, SKYBLUE, PURPLE, BEIGE ]
colorNames = [
"DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE",
"DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN",
"LIGHTGRAY", "PINK", "YELLOW", "GREEN", "SKYBLUE", "PURPLE", "BEIGE" ]
for i = 1 to MAX_COLORS_COUNT
colorsRecs[i] = new Rectangle(0,0,0,0)
next
for i = 1 to MAX_COLORS_COUNT
colorState[i] = 0
next
// Fills colorsRecs data (for every rectangle)
for i = 1 to MAX_COLORS_COUNT
colorsRecs[i].x = 20 + 100 *((i-1)%7) + 10*((i-1)%7)
colorsRecs[i].y = 80 + 100 *floor((i-1)/7) + 10*floor((i-1)/7)
colorsRecs[i].width = 100
colorsRecs[i].height = 100
next
mousePoint = Vector2( 0.0, 0.0 )
SetTargetFPS(60)
// Main game loop
while !WindowShouldClose()
mousePoint = GetMousePosition()
for i = 1 to MAX_COLORS_COUNT
if (CheckCollisionPointRec(mousePoint,
colorsRecs[i])) colorState[i] = 1
else colorState[i] = 0 ok
next
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("raylib colors palette", 28, 42, 20, BLACK)
DrawText("press SPACE to see all colors",
GetScreenWidth() - 180,
GetScreenHeight() - 40, 10, GRAY)
for i = 1 to MAX_COLORS_COUNT // Draw all rectangles
if colorState[i]
cstate = 0.6
else
cstate = 1.0
ok
(continues on next page)
57.18. Colors Palette 682

Ring Documentation, Release 1.14
(continued from previous page)
DrawRectangleRec(colorsRecs[i], Fade(colors[i], cstate))
if (IsKeyDown(KEY_SPACE) || colorState[i])
DrawRectangle(colorsRecs[i].x,
colorsRecs[i].y + colorsRecs[i].height - 26,
colorsRecs[i].width, 20, BLACK)
DrawRectangleLinesEx(colorsRecs[i], 6,
Fade(BLACK, 0.3f))
DrawText(colorNames[i], colorsRecs[i].x +
colorsRecs[i].width - MeasureText(colorNames[i],
10) - 12, colorsRecs[i].y +
colorsRecs[i].height - 20, 10, colors[i])
ok
next
EndDrawing()
end
CloseWindow()
Screen Shot:
57.18. Colors Palette 683

Ring Documentation, Release 1.14
57.19
load "raylib.ring"
MOUSE_SCALE_MARK_SIZE = 12
screenWidth = 800
screenHeight = 450
InitWindow(screenWidth, screenHeight,
"raylib [shapes] example - rectangle scaling mouse")
rec = Rectangle( 100, 100, 200, 80 )
mousePosition = Vector2( 0,0 )
mouseScaleReady = false
mouseScaleMode = false
SetTargetFPS(60)
while !WindowShouldClose()
mousePosition = GetMousePosition()
if (CheckCollisionPointRec(mousePosition, rec) and
CheckCollisionPointRec(mousePosition,
Rectangle(rec.x + rec.width - MOUSE_SCALE_MARK_SIZE,
rec.y + rec.height - MOUSE_SCALE_MARK_SIZE,
MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE )))
mouseScaleReady = true
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
mouseScaleMode = true ok
else mouseScaleReady = false ok
if (mouseScaleMode)
mouseScaleReady = true
rec.width = (mousePosition.x - rec.x)
rec.height = (mousePosition.y - rec.y)
if (rec.width < MOUSE_SCALE_MARK_SIZE)
rec.width = MOUSE_SCALE_MARK_SIZE ok
if (rec.height < MOUSE_SCALE_MARK_SIZE)
rec.height = MOUSE_SCALE_MARK_SIZE ok
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON))
mouseScaleMode = false ok
ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("Scale rectangle dragging from bottom-right corner!",
10, 10, 20, GRAY)
(continues on next page)
57.19. Rectangle Scaling 684

Ring Documentation, Release 1.14
(continued from previous page)
DrawRectangleRec(rec, Fade(GREEN, 0.5f))
if (mouseScaleReady)
DrawRectangleLinesEx(rec, 1, RED)
DrawTriangle(Vector2( rec.x + rec.width -
MOUSE_SCALE_MARK_SIZE, rec.y + rec.height ),
Vector2( rec.x + rec.width, rec.y + rec.height ),
Vector2( rec.x + rec.width, rec.y + rec.height -
MOUSE_SCALE_MARK_SIZE ), RED)
ok
EndDrawing()
end
CloseWindow()
Screen Shot:
57.19. Rectangle Scaling 685

Ring Documentation, Release 1.14
57.20
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,
"raylib [audio] example - music playing (streaming)")
InitAudioDevice()
music"guitar_noodling.ogg")
PlayMusicStream(music)
timePlayed.0
pause false
SetTargetFPS(60)
while!WindowShouldClose()
UpdateMusicStream(music)
ifIsKeyPressed(KEY_SPACE)
StopMusicStream(music)
PlayMusicStream(music)
ok
ifIsKeyPressed(KEY_P)
pausepause
ifpause
PauseMusicStream(music)
else
ResumeMusicStream(music)
ok
ok
timePlayed *400
iftimePlayed
StopMusicStream(music)
ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("MUSIC SHOULD BE PLAYING!",,,, LIGHTGRAY)
DrawRectangle(200,,,, LIGHTGRAY)
DrawRectangle(200,, timePlayed,, MAROON)
DrawRectangleLines(200,,,, GRAY)
(continues on next page)
57.20. Music Playing 686

Ring Documentation, Release 1.14
(continued from previous page)
DrawText("PRESS SPACE TO RESTART MUSIC",,,, LIGHTGRAY)
DrawText("PRESS P TO PAUSE/RESUME MUSIC",,,, LIGHTGRAY)
EndDrawing()
end
UnloadMusicStream(music)
CloseAudioDevice()
CloseWindow()
Screen Shot:
57.21
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,
"raylib [audio] example - sound loading and playing")
InitAudioDevice()
fxWav"sound.wav")
(continues on next page)
57.21. Sound Loading 687

Ring Documentation, Release 1.14
(continued from previous page)
fxOgg"tanatana.ogg")
SetTargetFPS(60)
while!WindowShouldClose()
ifIsKeyPressed(KEY_SPACE) PlaySound(fxWav) ok
ifIsKeyPressed(KEY_ENTER) PlaySound(fxOgg) ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("Press SPACE to PLAY the WAV sound!",,,,
˓→LIGHTGRAY)
DrawText("Press ENTER to PLAY the OGG sound!",,,,
˓→LIGHTGRAY)
EndDrawing()
end
UnloadSound(fxWav)
UnloadSound(fxOgg)
CloseAudioDevice()
CloseWindow()
Screen Shot:
57.21. Sound Loading 688

Ring Documentation, Release 1.14
57.22
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,
"raylib [textures] example - image drawing")
cat"cat.png")
ImageCrop( cat, Rectangle(,,,
ImageFlipHorizontal( cat)
ImageResize( cat,,)
parrots"parrots.png")
ImageDraw( parrots, cat, Rectangle(,, cat.width, cat.height ),
Rectangle(,, cat.width *1.5, cat.height *1.5
ImageCrop( parrots, Rectangle(,, parrots.width, parrots.height
UnloadImage(cat)
font"custom_jupiter_crash.png")
ImageDrawTextEx(parrots, Vector2(,
"PARROTS & CAT", font.baseSize,2, WHITE)
UnloadFont(font);
texture
UnloadImage(parrots)
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RAYWHITE)
DrawTexture(texture, screenWidth/2/2,
screenHeight/2/2, WHITE)
DrawRectangleLines(screenWidth/2/2,
screenHeight/2/2,
texture.width, texture.height, DARKGRAY)
DrawText("We are drawing only one texture from various images composed!",
240,,, DARKGRAY)
DrawText("Source images have been cropped, scaled,"+
"",
190,,, DARKGRAY)
EndDrawing()
end
UnloadTexture(texture)
(continues on next page)
57.22. Image Drawing 689

Ring Documentation, Release 1.14
(continued from previous page)
CloseWindow()
Screen Shot:
57.23
load"raylib.ring"
NUM_TEXTURES
textures list(7)
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,
"raylib [textures] example - procedural images generation")
verticalGradient
horizontalGradient
radialGradient
screenHeight,.0, WHITE, BLACK)
checked
32,, RED, BLUE)
whiteNoise.5)
perlinNoise,,.0)
cellular)
(continues on next page)
57.23. Image Generation 690

Ring Documentation, Release 1.14
(continued from previous page)
textures[NUM_TEXTURES]
textures[1]
textures[2]
textures[3]
textures[4]
textures[5]
textures[6]
textures[7]
UnloadImage(verticalGradient)
UnloadImage(horizontalGradient)
UnloadImage(radialGradient)
UnloadImage(checked)
UnloadImage(whiteNoise)
UnloadImage(perlinNoise)
UnloadImage(cellular)
currentTexture
SetTargetFPS(10)
while!WindowShouldClose()
ifIsMouseButtonPressed(MOUSE_LEFT_BUTTON)|
currentTexture++
ifcurrentTexture ok
ok
BeginDrawing()
ClearBackground(RAYWHITE)
DrawTexture(textures[currentTexture],,, WHITE)
DrawRectangle(30,,,, Fade(SKYBLUE,.5))
DrawRectangleLines(30,,,, Fade(WHITE,.5))
DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL TEXTURES",
40,,, WHITE)
switch(currentTexture)
on1"VERTICAL GRADIENT",,,, RAYWHITE)
on2"HORIZONTAL GRADIENT",,,, RAYWHITE)
on3"RADIAL GRADIENT",,,, LIGHTGRAY)
on4"CHECKED",,,, RAYWHITE)
on5"WHITE NOISE",,,, RED)
on6"PERLIN NOISE",,,, RAYWHITE)
on7"CELLULAR",,,, RAYWHITE)
off
EndDrawing()
end
fori toNUM_TEXTURES
UnloadTexture( textures[i]
next
(continues on next page)
57.23. Image Generation 691

Ring Documentation, Release 1.14
(continued from previous page)
CloseWindow()
Screen Shot:
57.24
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,
"raylib [textures] examples - texture source and destination rectangles")
//
//
scarfy"RingLogo.png")/
frameWidth
frameHeight
// tousefordrawing)
sourceRec.0,.0, frameWidth, frameHeight )
//
destRec/2, screenHeight/2, frameWidth *2, frameHeight*2
(continues on next page)
57.24. Texture Source 692

Ring Documentation, Release 1.14
(continued from previous page)
///scale point)
//selativeoestinationectangleize
origin
rotation
SetTargetFPS(60)
while!WindowShouldClose()
rotation+1
BeginDrawing()
ClearBackground(RAYWHITE)
DrawTexturePro(scarfy, sourceRec, destRec,
origin, rotation, WHITE)
DrawLine(destRec.x,, destRec.x, screenHeight, GRAY)
DrawLine(0, destRec.y, screenWidth, destRec.y, GRAY)
DrawText("(c) Scarfy sprite by Eiden Marsal",
screenWidth, screenHeight,, GRAY)
EndDrawing()
end
UnloadTexture(scarfy)/
CloseWindow()
Screen Shot:
57.24. Texture Source 693

Ring Documentation, Release 1.14
57.25
load"raylib.ring"
FOVY_PERSPECTIVE.0
WIDTH_ORTHOGRAPHIC.0
screenWidth
screenHeight
(continues on next page)
57.25. Geometric Shapes 694

Ring Documentation, Release 1.14
(continued from previous page)
InitWindow(screenWidth, screenHeight,
"raylib [models] example - geometric shapes")
camera.0,.0,.0,
0.0,.0,.0,
0.0,.0,.0,
FOVY_PERSPECTIVE, CAMERA_PERSPECTIVE
)
SetTargetFPS(60)
while!WindowShouldClose()
ifIsKeyPressed(KEY_SPACE)
ifcamera.type
camera.fovy
camera.type
else
camera.fovy
camera.type
ok
ok
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
DrawCube(Vector3(-4.0,.0,.0),.0,.0,.0, RED)
DrawCubeWires(Vector3(-4.0,.0,.0),.0,.0,.0, GOLD)
DrawCubeWires(Vector3(-4.0,.0,2.0),.0,.0,.0, MAROON)
DrawSphere(Vector3(-1.0,.0,2.0),.0, GREEN)
DrawSphereWires(Vector3(.0,.0,.0),.0,,, LIME)
DrawCylinder(Vector3(4.0,.0,2.0),.0,.0,.0,, SKYBLUE)
DrawCylinderWires(Vector3(4.0,.0,2.0),.0,.0,.0,, DARKBLUE)
DrawCylinderWires(Vector3(4.5,1.0,.0),.0,.0,.0,, BROWN)
DrawCylinder(Vector3(1.0,.0,4.0),.0,.5,.0,, GOLD)
DrawCylinderWires(Vector3(1.0,.0,4.0),.0,.5,.0,, PINK)
DrawGrid(10,.0)
EndMode3D()
DrawText("Press Spacebar to switch camera type",,
GetScreenHeight(),, DARKGRAY)
ifcamera.type
DrawText("ORTHOGRAPHIC",,,, BLACK)
else
(continues on next page)
57.25. Geometric Shapes 695

Ring Documentation, Release 1.14
(continued from previous page)
ifcamera.type
DrawText("PERSPECTIVE",,,, BLACK)
ok
ok
DrawFPS(10,)
EndDrawing()
end
CloseWindow()
Screen Shot:
57.26
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,
"raylib [models] example - cubesmap loading and drawing")
camera.0,.0,.0,
0.0,.0,.0,
0.0,.0,.0,
(continues on next page)
57.26. Cubic Map 696

Ring Documentation, Release 1.14
(continued from previous page)
45.0,
image"cubicmap.png")
cubicmap
mesh.0,.0,.0
model
texture"cubicmap_atlas.png")
setmodelmaterialtexture(model,0,MAP_DIFFUSE,texture)
mapPosition16.0,.0,8.0
UnloadImage(image)
SetCameraMode(camera, CAMERA_ORBITAL)
SetTargetFPS(60)
while!WindowShouldClose()
UpdateCamera(camera)
BeginDrawing()
ClearBackground(RAYWHITE)
BeginMode3D(camera)
DrawModel(model, mapPosition,.0, WHITE)
EndMode3D()
DrawTextureEx(cubicmap, Vector2( screenWidth
cubicmap.width*4,
0.0,.0, WHITE)
DrawRectangleLines(screenWidth *4
20,, cubicmap.width *4,
cubicmap.height*4, GREEN)
DrawText("cubicmap image used to",,,, GRAY)
DrawText("generate map 3d model",,,, GRAY)
DrawFPS(10,)
EndDrawing()
end
UnloadTexture(cubicmap)
UnloadTexture(texture)
UnloadModel(model)
CloseWindow()
Screen Shot:
57.26. Cubic Map 697

Ring Documentation, Release 1.14
57.27
void InitWindow(int width, int height, const char *title)
bool WindowShouldClose(void)
void CloseWindow(void)
bool IsWindowReady(void)
bool IsWindowMinimized(void)
bool IsWindowResized(void)
bool IsWindowHidden(void)
void ToggleFullscreen(void)
void UnhideWindow(void)
void HideWindow(void)
void SetWindowIcon(Image image)
void SetWindowTitle(const char *title)
void SetWindowPosition(int x, int y)
void SetWindowMonitor(int monitor)
void SetWindowMinSize(int width, int height)
void SetWindowSize(int width, int height)
void*GetWindowHandle(void)
int GetScreenWidth(void)
int GetScreenHeight(void)
int GetMonitorCount(void)
int GetMonitorWidth(int monitor)
int GetMonitorHeight(int monitor)
int GetMonitorPhysicalWidth(int monitor)
int GetMonitorPhysicalHeight(int monitor)
const char*GetMonitorName(int monitor)
const char*GetClipboardText(void)
void SetClipboardText(const char *text)
(continues on next page)
57.27. Functions 698

Ring Documentation, Release 1.14
(continued from previous page)
void ShowCursor(void)
void HideCursor(void)
bool IsCursorHidden(void)
void EnableCursor(void)
void DisableCursor(void)
void ClearBackground(Color color)
void BeginDrawing(void)
void EndDrawing(void)
void BeginMode2D(Camera2D camera)
void EndMode2D(void)
void BeginMode3D(Camera3D camera)
void EndMode3D(void)
void BeginTextureMode(RenderTexture2D target)
void EndTextureMode(void)
Ray GetMouseRay(Vector2 mousePosition, Camera3D camera)
Vector2 GetWorldToScreen(Vector3 position, Camera3D camera)
Matrix GetCameraMatrix(Camera3D camera)
void SetTargetFPS(int fps)
int GetFPS(void)
float GetFrameTime(void)
double GetTime(void)
int ColorToInt(Color color)
Vector4 ColorNormalize(Color color)
Vector3 ColorToHSV(Color color)
Color ColorFromHSV(Vector3 hsv)
Color GetColor(int hexValue)
Color Fade(Color color, float alpha)
void SetConfigFlags(unsigned char flags)
void SetTraceLogLevel(int logType)
void SetTraceLogExit(int logType)
void SetTraceLogCallback(TraceLogCallback callback)
void TraceLog(int logType, const char *text)
void TakeScreenshot(const char *fileName)
int GetRandomValue(int min, int max)
bool FileExists(const char *fileName)
bool IsFileExtension(const char *fileName, const char *ext)
const char*GetExtension(const char *fileName)
const char*GetFileName(const char *filePath)
const char*GetFileNameWithoutExt(const char *filePath)
const char*GetDirectoryPath(const char *fileName)
const char*GetWorkingDirectory(void)
char**GetDirectoryFiles(const char *dirPath, int*count)
void ClearDirectoryFiles(void)
bool ChangeDirectory(const char *dir)
bool IsFileDropped(void)
char**GetDroppedFiles(int *count)
void ClearDroppedFiles(void)
long GetFileModTime(const char *fileName)
void StorageSaveValue(int position, int value)
int StorageLoadValue(int position)
void OpenURL(const char *url)
bool IsKeyPressed(int key)
bool IsKeyDown(int key)
bool IsKeyReleased(int key)
bool IsKeyUp(int key)
int GetKeyPressed(void)
void SetExitKey(int key)
(continues on next page)
57.27. Functions 699

Ring Documentation, Release 1.14
(continued from previous page)
bool IsGamepadAvailable(int gamepad)
bool IsGamepadName(int gamepad, const char *name)
const char*GetGamepadName(int gamepad)
bool IsGamepadButtonPressed(int gamepad, int button)
bool IsGamepadButtonDown(int gamepad, int button)
bool IsGamepadButtonReleased(int gamepad, int button)
bool IsGamepadButtonUp(int gamepad, int button)
int GetGamepadButtonPressed(void)
int GetGamepadAxisCount(int gamepad)
float GetGamepadAxisMovement(int gamepad, int axis)
bool IsMouseButtonPressed(int button)
bool IsMouseButtonDown(int button)
bool IsMouseButtonReleased(int button)
bool IsMouseButtonUp(int button)
int GetMouseX(void)
int GetMouseY(void)
Vector2 GetMousePosition(void)
void SetMousePosition(int x, int y)
void SetMouseOffset(int offsetX, int offsetY)
void SetMouseScale(float scaleX, float scaleY)
int GetMouseWheelMove(void)
int GetTouchX(void)
int GetTouchY(void)
Vector2 GetTouchPosition(int index)
void SetGesturesEnabled(unsigned int gestureFlags)
bool IsGestureDetected(int gesture)
int GetGestureDetected(void)
int GetTouchPointsCount(void)
float GetGestureHoldDuration(void)
Vector2 GetGestureDragVector(void)
float GetGestureDragAngle(void)
Vector2 GetGesturePinchVector(void)
float GetGesturePinchAngle(void)
void SetCameraMode(Camera3D camera, int mode)
void UpdateCamera(Camera3D *camera)
void SetCameraPanControl(int panKey)
void SetCameraAltControl(int altKey)
void SetCameraSmoothZoomControl(int szKey)
void SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey,
int upKey, int downKey)
void DrawPixel(int posX, int posY, Color color)
void DrawPixelV(Vector2 position, Color color)
void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color)
void DrawLineV(Vector2 startPos, Vector2 endPos, Color color)
void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color)
void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color)
void DrawLineStrip(Vector2 *points, int numPoints, Color color)
void DrawCircle(int centerX, int centerY, float radius, Color color)
void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle,
int segments, Color color)
void DrawCircleSectorLines(Vector2 center, float radius, int startAngle,
int endAngle, int segments, Color color)
void DrawCircleGradient(int centerX, int centerY, float radius,
Color color1, Color color2)
void DrawCircleV(Vector2 center, float radius, Color color)
void DrawCircleLines(int centerX, int centerY, float radius, Color color)
void DrawRing(Vector2 center, float innerRadius, float outerRadius,
(continues on next page)
57.27. Functions 700

Ring Documentation, Release 1.14
(continued from previous page)
int startAngle, int endAngle, int segments, Color color)
void DrawRingLines(Vector2 center, float innerRadius, float outerRadius,
int startAngle, int endAngle, int segments, Color color)
void DrawRectangle(int posX, int posY, int width, int height, Color color)
void DrawRectangleV(Vector2 position, Vector2 size, Color color)
void DrawRectangleRec(Rectangle rec, Color color)
void DrawRectanglePro(Rectangle rec, Vector2 origin,
float rotation, Color color)
void DrawRectangleGradientV(int posX, int posY, int width,
int height, Color color1, Color color2)
void DrawRectangleGradientH(int posX, int posY, int width,
int height, Color color1, Color color2)
void DrawRectangleGradientEx(Rectangle rec, Color col1,
Color col2, Color col3, Color col4)
void DrawRectangleLines(int posX, int posY, int width,
int height, Color color)
void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color)
void DrawRectangleRounded(Rectangle rec, float roundness,
int segments, Color color)
void DrawRectangleRoundedLines(Rectangle rec, float roundness,
int segments, int lineThick, Color color)
void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color)
void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color)
void DrawTriangleFan(Vector2 *points, int numPoints, Color color)
void DrawPoly(Vector2 center, int sides, float radius,
float rotation, Color color)
void SetShapesTexture(Texture2D texture, Rectangle source)
bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2)
bool CheckCollisionCircles(Vector2 center1, float radius1,
Vector2 center2, float radius2)
bool CheckCollisionCircleRec(Vector2 center, float radius,
Rectangle rec)
Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2)
bool CheckCollisionPointRec(Vector2 point, Rectangle rec)
bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius)
bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1,
Vector2 p2, Vector2 p3)
Image LoadImage(const char *fileName)
Image LoadImageEx(Color *pixels, int width, int height)
Image LoadImagePro(void *data, int width, int height, int format)
Image LoadImageRaw(const char *fileName, int width, int height,
int format, int headerSize)
void ExportImage(Image image, const char *fileName)
void ExportImageAsCode(Image image, const char *fileName)
Texture2D LoadTexture(const char *fileName)
Texture2D LoadTextureFromImage(Image image)
TextureCubemap LoadTextureCubemap(Image image, int layoutType)
RenderTexture2D LoadRenderTexture(int width, int height)
void UnloadImage(Image image)
void UnloadTexture(Texture2D texture)
void UnloadRenderTexture(RenderTexture2D target)
Color*GetImageData(Image image)
Vector4*GetImageDataNormalized(Image image)
int GetPixelDataSize(int width, int height, int format)
Image GetTextureData(Texture2D texture)
Image GetScreenData(void)
void UpdateTexture(Texture2D texture, const void *pixels)
(continues on next page)
57.27. Functions 701

Ring Documentation, Release 1.14
(continued from previous page)
Image ImageCopy(Image image)
void ImageToPOT(Image *image, Color fillColor)
void ImageFormat(Image *image, int newFormat)
void ImageAlphaMask(Image *image, Image alphaMask)
void ImageAlphaClear(Image *image, Color color, float threshold)
void ImageAlphaCrop(Image *image, float threshold)
void ImageAlphaPremultiply(Image *image)
void ImageCrop(Image *image, Rectangle crop)
void ImageResize(Image *image, int newWidth, int newHeight)
void ImageResizeNN(Image *image, int newWidth,int newHeight)
void ImageResizeCanvas(Image *image, int newWidth, int newHeight,
int offsetX, int offsetY, Color color)
void ImageMipmaps(Image *image)
void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp)
Color*ImageExtractPalette(Image image, int maxPaletteSize, int *extractCount)
Image ImageText(const char *text, int fontSize, Color color)
Image ImageTextEx(Font font, const char *text, float fontSize,
float spacing, Color tint)
void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec)
void ImageDrawRectangle(Image *dst, Rectangle rec, Color color)
void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color)
void ImageDrawText(Image *dst, Vector2 position, const char *text,
int fontSize, Color color)
void ImageDrawTextEx(Image *dst, Vector2 position, Font font,
const char*text, float fontSize, float spacing, Color color)
void ImageFlipVertical(Image *image)
void ImageFlipHorizontal(Image *image)
void ImageRotateCW(Image *image)
void ImageRotateCCW(Image *image)
void ImageColorTint(Image *image, Color color)
void ImageColorInvert(Image *image)
void ImageColorGrayscale(Image *image)
void ImageColorContrast(Image *image, float contrast)
void ImageColorBrightness(Image *image, int brightness)
void ImageColorReplace(Image *image, Color color, Color replace)
Image GenImageColor(int width, int height, Color color)
Image GenImageGradientV(int width, int height, Color top, Color bottom)
Image GenImageGradientH(int width, int height, Color left, Color right)
Image GenImageGradientRadial(int width, int height, float density,
Color inner, Color outer)
Image GenImageChecked(int width, int height, int checksX, int checksY,
Color col1, Color col2)
Image GenImageWhiteNoise(int width, int height, float factor)
Image GenImagePerlinNoise(int width, int height, int offsetX,
int offsetY, float scale)
Image GenImageCellular(int width, int height, int tileSize)
void GenTextureMipmaps(Texture2D *texture)
void SetTextureFilter(Texture2D texture, int filterMode)
void SetTextureWrap(Texture2D texture, int wrapMode)
void DrawTexture(Texture2D texture, int posX, int posY, Color tint)
void DrawTextureV(Texture2D texture, Vector2 position, Color tint)
void DrawTextureEx(Texture2D texture, Vector2 position,
float rotation, float scale, Color tint)
void DrawTextureRec(Texture2D texture, Rectangle sourceRec,
Vector2 position, Color tint)
void DrawTextureQuad(Texture2D texture, Vector2 tiling, Vector2 offset,
Rectangle quad, Color tint)
(continues on next page)
57.27. Functions 702

Ring Documentation, Release 1.14
(continued from previous page)
void DrawTexturePro(Texture2D texture, Rectangle sourceRec,
Rectangle destRec, Vector2 origin, float rotation, Color tint)
void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo,
Rectangle destRec, Vector2 origin, float rotation, Color tint)
Font GetFontDefault(void)
Font LoadFont(const char *fileName)
Font LoadFontEx(const char *fileName, int fontSize,
int*fontChars, int charsCount)
Font LoadFontFromImage(Image image, Color key, int firstChar)
CharInfo*LoadFontData(const char *fileName, int fontSize,
int*fontChars, int charsCount, int type)
Image GenImageFontAtlas(CharInfo *chars, int charsCount,
int fontSize, int padding, int packMethod)
void UnloadFont(Font font)
void DrawFPS(int posX, int posY)
void DrawText(const char *text, int posX, int posY, int fontSize, Color color)
void DrawTextEx(Font font, const char *text, Vector2 position,
float fontSize, float spacing, Color tint)
void DrawTextRec(Font font, const char *text, Rectangle rec,
float fontSize, float spacing, bool wordWrap, Color tint)
void DrawTextRecEx(Font font, const char *text, Rectangle rec,
float fontSize, float spacing, bool wordWrap, Color tint,
int selectStart, int selectLength, Color selectText, Color selectBack)
int MeasureText(const char *text, int fontSize)
Vector2 MeasureTextEx(Font font, const char *text,
float fontSize, float spacing)
int GetGlyphIndex(Font font, int character)
int GetNextCodepoint(const char *text, int*count)
bool TextIsEqual(const char *text1, const char *text2)
unsigned int TextLength(const char *text)
unsigned int TextCountCodepoints(const char *text)
const char*TextFormat(const char *text)
const char*TextSubtext(const char *text, int position, int length)
const char*TextReplace(char *text, const char *replace, const char *by)
const char*TextInsert(const char *text, const char *insert, int position)
const char*TextJoin(const char **textList, int count, const char *delimiter)
const char**TextSplit(const char *text, char delimiter, int *count)
void TextAppend(char *text, const char *append, int*position)
int TextFindIndex(const char *text, const char *find)
const char*TextToUpper(const char *text)
const char*TextToLower(const char *text)
const char*TextToPascal(const char *text)
int TextToInteger(const char *text)
void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color)
void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis,
float rotationAngle, Color color)
void DrawCube(Vector3 position, float width, float height, float length, Color color)
void DrawCubeV(Vector3 position, Vector3 size, Color color)
void DrawCubeWires(Vector3 position, float width, float height,
float length, Color color)
void DrawCubeWiresV(Vector3 position, Vector3 size, Color color)
void DrawCubeTexture(Texture2D texture, Vector3 position,
float width, float height, float length, Color color)
void DrawSphere(Vector3 centerPos, float radius, Color color)
void DrawSphereEx(Vector3 centerPos, float radius, int rings,
int slices, Color color)
void DrawSphereWires(Vector3 centerPos, float radius, int rings,
(continues on next page)
57.27. Functions 703

Ring Documentation, Release 1.14
(continued from previous page)
int slices, Color color)
void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom,
float height, int slices, Color color)
void DrawCylinderWires(Vector3 position, float radiusTop,
float radiusBottom, float height, int slices, Color color)
void DrawPlane(Vector3 centerPos, Vector2 size, Color color)
void DrawRay(Ray ray, Color color)
void DrawGrid(int slices, float spacing)
void DrawGizmo(Vector3 position)
Model LoadModel(const char *fileName)
Model LoadModelFromMesh(Mesh mesh)
void UnloadModel(Model model)
Mesh*LoadMeshes(const char *fileName, int*meshCount)
void ExportMesh(Mesh mesh, const char *fileName)
void UnloadMesh(Mesh *mesh)
Material*LoadMaterials(const char *fileName, int*materialCount)
Material LoadMaterialDefault(void)
void UnloadMaterial(Material material)
void SetMaterialTexture(Material *material, int mapType, Texture2D texture)
void SetModelMeshMaterial(Model *model, int meshId, int materialId)
ModelAnimation*LoadModelAnimations(const char *fileName, int*animsCount)
void UpdateModelAnimation(Model model, ModelAnimation anim, int frame)
void UnloadModelAnimation(ModelAnimation anim)
bool IsModelAnimationValid(Model model, ModelAnimation anim)
Mesh GenMeshPoly(int sides, float radius)
Mesh GenMeshPlane(float width, float length, int resX, int resZ)
Mesh GenMeshCube(float width, float height, float length)
Mesh GenMeshSphere(float radius, int rings, int slices)
Mesh GenMeshHemiSphere(float radius, int rings, int slices)
Mesh GenMeshCylinder(float radius, float height, int slices)
Mesh GenMeshTorus(float radius, float size, int radSeg, int sides)
Mesh GenMeshKnot(float radius, float size, int radSeg, int sides)
Mesh GenMeshHeightmap(Image heightmap, Vector3 size)
Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)
BoundingBox MeshBoundingBox(Mesh mesh)
void MeshTangents(Mesh *mesh)
void MeshBinormals(Mesh *mesh)
void DrawModel(Model model, Vector3 position, float scale, Color tint)
void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis,
float rotationAngle, Vector3 scale, Color tint)
void DrawModelWires(Model model, Vector3 position, float scale, Color tint)
void DrawModelWiresEx(Model model, Vector3 position,
Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)
void DrawBoundingBox(BoundingBox box, Color color)
void DrawBillboard(Camera3D camera, Texture2D texture,
Vector3 center, float size, Color tint)
void DrawBillboardRec(Camera3D camera, Texture2D texture,
Rectangle sourceRec, Vector3 center, float size, Color tint)
bool CheckCollisionSpheres(Vector3 centerA, float radiusA,
Vector3 centerB, float radiusB)
bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2)
bool CheckCollisionBoxSphere(BoundingBox box, Vector3 centerSphere, float
˓→radiusSphere)
bool CheckCollisionRaySphere(Ray ray, Vector3 spherePosition, float sphereRadius)
bool CheckCollisionRaySphereEx(Ray ray, Vector3 spherePosition,
float sphereRadius, Vector3 *collisionPoint)
bool CheckCollisionRayBox(Ray ray, BoundingBox box)
(continues on next page)
57.27. Functions 704

Ring Documentation, Release 1.14
(continued from previous page)
RayHitInfo GetCollisionRayModel(Ray ray, Model *model)
RayHitInfo GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3)
RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight)
char*LoadText(const char *fileName)
Shader LoadShader(const char *vsFileName, const char *fsFileName)
Shader LoadShaderCode(char *vsCode, char*fsCode)
void UnloadShader(Shader shader)
Shader GetShaderDefault(void)
Texture2D GetTextureDefault(void)
int GetShaderLocation(Shader shader, const char *uniformName)
void SetShaderValue(Shader shader, int uniformLoc,
const void*value, int uniformType)
void SetShaderValueV(Shader shader, int uniformLoc,
const void*value, int uniformType, int count)
void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat)
void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture)
void SetMatrixProjection(Matrix proj)
void SetMatrixModelview(Matrix view)
Matrix GetMatrixModelview(void)
Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size)
Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size)
Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size)
Texture2D GenTextureBRDF(Shader shader, int size)
void BeginShaderMode(Shader shader)
void EndShaderMode(void)
void BeginBlendMode(int mode)
void EndBlendMode(void)
void BeginScissorMode(int x, int y, int width, int height)
void EndScissorMode(void)
void InitVrSimulator(void)
void CloseVrSimulator(void)
void UpdateVrTracking(Camera3D *camera)
void SetVrConfiguration(VrDeviceInfo info, Shader distortion)
bool IsVrSimulatorReady(void)
void ToggleVrMode(void)
void BeginVrDrawing(void)
void EndVrDrawing(void)
void InitAudioDevice(void)
void CloseAudioDevice(void)
bool IsAudioDeviceReady(void)
void SetMasterVolume(float volume)
Wave LoadWave(const char *fileName)
Wave LoadWaveEx(void *data, int sampleCount, int sampleRate,
int sampleSize, int channels)
Sound LoadSound(const char *fileName)
Sound LoadSoundFromWave(Wave wave)
void UpdateSound(Sound sound, const void *data, int samplesCount)
void UnloadWave(Wave wave)
void UnloadSound(Sound sound)
void ExportWave(Wave wave, const char *fileName)
void ExportWaveAsCode(Wave wave, const char *fileName)
void PlaySound(Sound sound)
void PauseSound(Sound sound)
void ResumeSound(Sound sound)
void StopSound(Sound sound)
bool IsSoundPlaying(Sound sound)
void SetSoundVolume(Sound sound, float volume)
(continues on next page)
57.27. Functions 705

Ring Documentation, Release 1.14
(continued from previous page)
void SetSoundPitch(Sound sound, float pitch)
void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
Wave WaveCopy(Wave wave)
void WaveCrop(Wave *wave, int initSample, int finalSample)
float*GetWaveData(Wave wave)
Music LoadMusicStream(const char *fileName)
void UnloadMusicStream(Music music)
void PlayMusicStream(Music music)
void UpdateMusicStream(Music music)
void StopMusicStream(Music music)
void PauseMusicStream(Music music)
void ResumeMusicStream(Music music)
bool IsMusicPlaying(Music music)
void SetMusicVolume(Music music, float volume)
void SetMusicPitch(Music music, float pitch)
void SetMusicLoopCount(Music music, int count)
float GetMusicTimeLength(Music music)
float GetMusicTimePlayed(Music music)
AudioStream InitAudioStream(unsigned int sampleRate,
unsigned int sampleSize, unsigned int channels)
void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount)
void CloseAudioStream(AudioStream stream)
bool IsAudioBufferProcessed(AudioStream stream)
void PlayAudioStream(AudioStream stream)
void PauseAudioStream(AudioStream stream)
void ResumeAudioStream(AudioStream stream)
bool IsAudioStreamPlaying(AudioStream stream)
void StopAudioStream(AudioStream stream)
void SetAudioStreamVolume(AudioStream stream, float volume)
void SetAudioStreamPitch(AudioStream stream, float pitch)
void GuiEnable(void)
void GuiDisable(void)
void GuiLock(void)
void GuiUnlock(void)
void GuiState(int state)
void GuiFont(Font font)
void GuiFade(float alpha)
void GuiSetStyle(int control, int property, int value)
int GuiGetStyle(int control, int property)
bool GuiWindowBox(Rectangle bounds, const char *text)
void GuiGroupBox(Rectangle bounds, const char *text)
void GuiLine(Rectangle bounds, const char *text)
void GuiPanel(Rectangle bounds)
Rectangle GuiScrollPanel(Rectangle bounds, Rectangle content, Vector2 *scroll)
void GuiLabel(Rectangle bounds, const char *text)
bool GuiButton(Rectangle bounds, const char *text)
bool GuiLabelButton(Rectangle bounds, const char *text)
bool GuiImageButton(Rectangle bounds, Texture2D texture)
bool GuiImageButtonEx(Rectangle bounds, Texture2D texture,
Rectangle texSource, const char *text)
bool GuiToggle(Rectangle bounds, const char *text, bool active)
int GuiToggleGroup(Rectangle bounds, const char *text, int active)
bool GuiCheckBox(Rectangle bounds, const char *text, bool checked)
int GuiComboBox(Rectangle bounds, const char *text, int active)=
bool GuiDropdownBox(Rectangle bounds, const char *text,
int*active, bool editMode)
bool GuiSpinner(Rectangle bounds, int *value, int minValue,
(continues on next page)
57.27. Functions 706

Ring Documentation, Release 1.14
(continued from previous page)
int maxValue, bool editMode)
bool GuiValueBox(Rectangle bounds, int *value, int minValue,
int maxValue, bool editMode)
bool GuiTextBox(Rectangle bounds, char *text, int textSize, bool editMode)
bool GuiTextBoxMulti(Rectangle bounds, char *text, int textSize, bool editMode)
float GuiSlider(Rectangle bounds, const char *text, float value,
float minValue, float maxValue, bool showValue)
float GuiSliderBar(Rectangle bounds, const char *text, float value,
float minValue, float maxValue, bool showValue)
float GuiProgressBar(Rectangle bounds, const char *text, float value,
float minValue, float maxValue, bool showValue)
void GuiStatusBar(Rectangle bounds, const char *text)
void GuiDummyRec(Rectangle bounds, const char *text)
int GuiScrollBar(Rectangle bounds, int value, int minValue, int maxValue)
Vector2 GuiGrid(Rectangle bounds, float spacing, int subdivs)
bool GuiListView(Rectangle bounds, const char *text, int*active,
int*scrollIndex, bool editMode)
bool GuiListViewEx(Rectangle bounds, const char **text, int count,
int*enabled, int*active, int*focus, int*scrollIndex, bool editMode)
int GuiMessageBox(Rectangle bounds, const char *windowTitle,
const char*message, const char *buttons)
int GuiTextInputBox(Rectangle bounds, const char *windowTitle,
const char*message, char*text, const char *buttons)
Color GuiColorPicker(Rectangle bounds, Color color)
void GuiLoadStyle(const char *fileName)
void GuiLoadStyleProps(const int *props, int count)
void GuiLoadStyleDefault(void)
void GuiUpdateStyleComplete(void)
const char*GuiIconText(int iconId, const char *text)
57.27. Functions 707

CHAPTER
FIFTYEIGHT
USING RINGOPENGL AND RINGFREEGLUT FOR 3D GRAPHICS
In this chapter we will learn about using RingOpenGL
58.1
The samples in this chapter are based on C Tutorials
from
(1)
(2)
58.2
RingOpenGL contains the Ring binding to the OpenGL library
You can learn about OpenGL from :
RingOpenGL comes with support for the next versions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
708

Ring Documentation, Release 1.14
•
•
•
For example, if you want to use OpenGL 2.1 then load RingOpenGL 2.1 library
load"opengl21lib.ring"
58.3
RingFreeGLUT contains the Ring binding to the FreeGLUT library
You can learn about FreeGLUT from :
To use the RingFreeGLUT library, Just load the library
load"freeglut.ring"
58.4
Example:
load"freeglut.ring"
funcmain
glutInit()
glutInitDisplayMode(GLUT_SINGLE)
glutInitWindowSize(800,)
glutInitWindowPosition(100,)
glutCreateWindow("RingFreeGLUT - Test 1")
glutDisplayFunc(:displayCode)
glutMainLoop()
funcdisplaycode
Screen Shot
58.3. What is RingFreeGLUT? 709

Ring Documentation, Release 1.14
58.5
Example:
load"freeglut.ring"
load"opengl21lib.ring"
funcmain
glutInit()
glutInitDisplayMode(GLUT_SINGLE)
glutInitWindowSize(800,)
glutInitWindowPosition(100,)
glutCreateWindow("RingFreeGLUT - Test 2")
glutDisplayFunc(:displayCode)
glutMainLoop()
funcdisplaycode
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(0,255,0)
glBegin(GL_POLYGON)
(continues on next page)
58.5. Drawing using RingOpenGL 710

Ring Documentation, Release 1.14
(continued from previous page)
glVertex3f(0.0,.0,.0)
glVertex3f(0.5,.0,.0)
glVertex3f(0.5,.5,.0)
glVertex3f(0.0,.5,.0)
glEnd()
glColor3f(255,0,0)
glBegin(GL_POLYGON)
glVertex3f(0.0,.0,.0)
glVertex3f(0.5,.0,.0)
glVertex3f(-0.5,-,.0)
glVertex3f(0.0,1,.0)
glEnd()
glColor3f(0,0,255)
glBegin(GL_POLYGON)
glVertex3f(0.0,.0,.0)
glVertex3f(-0.5,.0,.0)
glVertex3f(-0.5,-.5,.0)
glVertex3f(0.0,0.5,.0)
glEnd()
glFlush()
Screen Shot
58.5. Drawing using RingOpenGL 711

Ring Documentation, Release 1.14
58.6
Example:
load"freeglut.ring"
load"opengl21lib.ring"
funcmain
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowSize(320,320)
glutInitWindowPosition(100,)
glutCreateWindow("RingFreeGLUT - Test 3")
glutDisplayFunc(:renderScene)
glutMainLoop()
funcrenderScene
glClear(GL_COLOR_BUFFER_BIT
glBegin(GL_TRIANGLES)
glVertex3f(-0.5,-0.5,0.0)
glVertex3f(0.5,0.0,0.0)
glVertex3f(0.0,0.5,0.0)
glEnd()
glutSwapBuffers()
Screen Shot
58.6. The First Triangle 712

Ring Documentation, Release 1.14
58.7
Example:
load"freeglut.ring"
load"opengl21lib.ring"
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 4")
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutMainLoop()
funcrenderScene
glClear(GL_COLOR_BUFFER_BIT
glBegin(GL_TRIANGLES)
glVertex3f(-2,-2,-5.0)
glVertex3f(2,0.0,-5.0)
glVertex3f(0.0,2,-5.0)
glEnd()
glutSwapBuffers()
funcchangesize
h
w
//
//
if(h)
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45,ratio,1,100)
(continues on next page)
58.7. Window Resize Event 713

Ring Documentation, Release 1.14
(continued from previous page)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
58.8
Example:
load"freeglut.ring"
load"opengl21lib.ring"
angle
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 5")
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutMainLoop()
funcrenderScene
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
glLoadIdentity()
//
gluLookAt(.0,.0,.0,
0.0,.0,.0,
0.0,.0,.0)
glRotatef(angle,.0,.0,.0)
glBegin(GL_TRIANGLES)
glVertex3f(-2.0,-2.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,.0)
glEnd()
angle+=0.1
glutSwapBuffers();
funcchangesize
(continues on next page)
58.8. Triangle Rotation 714

Ring Documentation, Release 1.14
(continued from previous page)
h
w
//
//
if(h)
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45,ratio,1,100)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
Screen Shot
58.8. Triangle Rotation 715

Ring Documentation, Release 1.14
58.9
Example:
load"freeglut.ring"
load"opengl21lib.ring"
angle
red=1.0
blue=1.0
green=1.0
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 6")
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
// newentries
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:processSpecialKeys)
glutMainLoop()
funcrenderScene
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
glLoadIdentity()
//
gluLookAt(.0,.0,.0,
0.0,.0,.0,
0.0,.0,.0)
glRotatef(angle,.0,.0,.0)
glColor3f(red,green,blue);
glBegin(GL_TRIANGLES)
glVertex3f(-2.0,-2.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,.0)
glEnd()
angle+=0.1
(continues on next page)
58.9. Keyboard Events and Colors 716

Ring Documentation, Release 1.14
(continued from previous page)
glutSwapBuffers();
funcchangesize
h
w
//
//
if(h)
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45,ratio,1,100)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
funcprocessNormalKeys
key
ifkey
shutdown()
ok
funcprocessSpecialKeys
key
switchkey
onGLUT_KEY_F1
red.0
green.0
blue.0
onGLUT_KEY_F2
red.0
green.0
blue.0
onGLUT_KEY_F3
red.0
green.0
blue.0
off
Screen Shot
58.9. Keyboard Events and Colors 717

Ring Documentation, Release 1.14
58.10
Example:
load"freeglut.ring"
load"opengl21lib.ring"
// forthe camera direction
angle=0.0
//sirection
lx=0.0
lz=-1.0
//
x=0.0
z=5.0
funcdrawSnowMan
glColor3f(1.0,.0,.0)
//
glTranslatef(0.00.75,.0)
glutSolidSphere(0.75,20,20)
//
glTranslatef(0.0,.0,.0)
glutSolidSphere(0.25,20,20)
//
glPushMatrix()
glColor3f(0.0,0.0,0.0)
(continues on next page)
58.10. The Camera 718

Ring Documentation, Release 1.14
(continued from previous page)
glTranslatef(0.05,.10,.18)
glutSolidSphere(0.05,10,10)
glTranslatef(-0.1,.0,.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
//
glColor3f(1.0,.5.5)
glutSolidCone(0.08,0.5,10,2)
funcchangeSize
w
h
//
//
ifh
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45.0, ratio,.1,.0);
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
funcprocessNormalKeys
key
ifkey
shutdown()
ok
funcrenderScene
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
(continues on next page)
58.10. The Camera 719

Ring Documentation, Release 1.14
(continued from previous page)
glLoadIdentity()
//
gluLookAt( x,.0, z,
x+lx,.0, z+lz,
0.0,.0,.0)
//
glColor3f(0.9,.9,.9)
glBegin(GL_QUADS)
glVertex3f(-100.0,.0,100.0)
glVertex3f(-100.0,.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,100.0)
glEnd()
//
fori3 to2
forj=-3 to2
glPushMatrix()
glTranslatef(i*10.0,0,j *10.0)
drawSnowMan()
glPopMatrix()
next
next
glutSwapBuffers()
funcprocessSpecialKeys
key
fraction.1
switchkey
onGLUT_KEY_LEFT
angle=.01
lx
lzcos(angle)
onGLUT_KEY_RIGHT
angle=.01
lx
lzcos(angle)
onGLUT_KEY_UP
x= *fraction
z= *fraction
onGLUT_KEY_DOWN
x= *fraction
z= *fraction
off
funcmain
// andcreate window
(continues on next page)
58.10. The Camera 720

Ring Documentation, Release 1.14
(continued from previous page)
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 7")
//
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:processSpecialKeys)
//
glEnable(GL_DEPTH_TEST)
//
glutMainLoop()
Screen Shot
Another Example:
load"freeglut.ring"
load"opengl21lib.ring"
// forthe camera direction
angle.0
//sirection
lx=0.0=-1.0
(continues on next page)
58.10. The Camera 721

Ring Documentation, Release 1.14
(continued from previous page)
//
x=0.0=5.0
//
//when no key is being presses
deltaAngle.0
deltaMove
funcchangeSize
w
h
//
//
ifh
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45.0, ratio,.1,.0)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
funcdrawSnowMan
glColor3f(1.0,.0,.0)
//
glTranslatef(0.00.75,.0)
glutSolidSphere(0.75,20,20)
//
glTranslatef(0.0,.0,.0)
glutSolidSphere(0.25,20,20)
//
glPushMatrix()
glColor3f(0.0,0.0,0.0)
glTranslatef(0.05,.10,.18)
glutSolidSphere(0.05,10,10)
glTranslatef(-0.1,.0,.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
(continues on next page)
58.10. The Camera 722

Ring Documentation, Release 1.14
(continued from previous page)
//
glColor3f(1.0,.5.5)
glRotatef(0.0,1.0,.0,.0)
glutSolidCone(0.08,0.5,10,2)
funccomputePos deltaMove
x= *lx*0.1
z= *lz*0.1
funccomputeDir deltaAngle
angle=
lx
lzcos(angle)
funcrenderScene
ifdeltaMove
computePos(deltaMove)
ok
ifdeltaAngle
computeDir(deltaAngle)
ok
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
glLoadIdentity()
//
gluLookAt( x,.0, z,
x+lx,.0, z+lz,
0.0,.0,.0)
//
glColor3f(0.9,.9,.9)
glBegin(GL_QUADS)
glVertex3f(-100.0,.0,100.0)
glVertex3f(-100.0,.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,100.0)
glEnd()
//
fori3 to2
forj=-3 to2
glPushMatrix()
glTranslatef(i*10.0,0,j *10.0)
drawSnowMan()
glPopMatrix()
(continues on next page)
58.10. The Camera 723

Ring Documentation, Release 1.14
(continued from previous page)
next
next
glutSwapBuffers()
funcpressKey
key
xx
yy
switchkey
onGLUT_KEY_LEFT
deltaAngle0.01
onGLUT_KEY_RIGHT
deltaAngle.01
onGLUT_KEY_UP
deltaMove.5
onGLUT_KEY_DOWN
deltaMove0.5
off
funcreleaseKey
key
switchkey
onGLUT_KEY_LEFT
deltaAngle.0
onGLUT_KEY_RIGHT
deltaAngle.0
onGLUT_KEY_UP
deltaMove
onGLUT_KEY_DOWN
deltaMove
off
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 8")
//
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutSpecialFunc(:pressKey)
// newentries
glutIgnoreKeyRepeat(1)
glutSpecialUpFunc(:releaseKey)
//
(continues on next page)
58.10. The Camera 724

Ring Documentation, Release 1.14
(continued from previous page)
glEnable(GL_DEPTH_TEST)
//
glutMainLoop()
58.11
Example:
load"freeglut.ring"
load"opengl21lib.ring"
// forthe camera direction
angle.0
//sirection
lx=0.0=-1.0
//
x=0.0=5.0
//
//when no key is being presses
deltaAngle.0
deltaMove.0
xOrigin1
funcchangeSize
w
h
//
//
ifh
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45.0, ratio,.1,.0)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
(continues on next page)
58.11. Mouse Events 725

Ring Documentation, Release 1.14
(continued from previous page)
funcdrawSnowMan
glColor3f(1.0,.0,.0)
//
glTranslatef(0.00.75,.0)
glutSolidSphere(0.75,20,20)
//
glTranslatef(0.0,.0,.0)
glutSolidSphere(0.25,20,20)
//
glPushMatrix()
glColor3f(0.0,0.0,0.0)
glTranslatef(0.05,.10,.18)
glutSolidSphere(0.05,10,10)
glTranslatef(-0.1,.0,.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
//
glColor3f(1.0,.5.5)
glRotatef(0.0,1.0,.0,.0)
glutSolidCone(0.08,0.5,10,2)
funccomputePos deltaMove
x= *lx*0.1
z= *lz*0.1
funcrenderScene
ifdeltaMove
computePos(deltaMove)
ok
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
glLoadIdentity()
//
gluLookAt( x,.0, z,
x+lx,.0, z+lz,
0.0,.0,.0)
//
glColor3f(0.9,.9,.9)
glBegin(GL_QUADS)
glVertex3f(-100.0,.0,100.0)
glVertex3f(-100.0,.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,100.0)
(continues on next page)
58.11. Mouse Events 726

Ring Documentation, Release 1.14
(continued from previous page)
glEnd()
//
fori3 to2
forj=-3 to2
glPushMatrix()
glTranslatef(i*10.0,0,j *10.0)
drawSnowMan()
glPopMatrix()
next
next
glutSwapBuffers()
funcprocessNormalKeys
key
ifkey
shutdown()
ok
funcpressKey
key
switchkey
onGLUT_KEY_UP
deltaMove.5
onGLUT_KEY_DOWN
deltaMove0.5
off
funcreleaseKey
key
switchkey
onGLUT_KEY_UP
deltaMove
onGLUT_KEY_DOWN
deltaMove
off
funcmouseMove
xx
yy
// truewhen the left button is down
ifxOrigin=
//
deltaAngle *0.001
//sirection
lx
lzcos(angle
ok
(continues on next page)
58.11. Mouse Events 727

Ring Documentation, Release 1.14
(continued from previous page)
funcmouseButton
button
state
xx
yy
// ifthe left button is pressed
ifbutton
//
ifstate
angle=
xOrigin1
else
//
xOrigin
ok
fflush(stdout)
ok
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 9")
//
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutIgnoreKeyRepeat(1)
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:pressKey)
glutSpecialUpFunc(:releaseKey)
// newfunctions
glutMouseFunc(:mouseButton)
glutMotionFunc(:mouseMove)
//
glEnable(GL_DEPTH_TEST)
//
glutMainLoop()
58.11. Mouse Events 728

Ring Documentation, Release 1.14
58.12
Example:
load"freeglut.ring"
load"opengl21lib.ring"
// forthe camera direction
angle.0
//sirection
lx=0.0=-1.0
//
x=0.0=5.0
//
//when no key is being presses
deltaAngle.0
deltaMove
xOrigin1
// forMenus
//forRingFreeGLUT foreach menu item
C_RED
C_GREEN
C_BLUE
C_ORANGE
C_FILL
C_LINE
C_SHRINK
C_NORMAL
//
fillMenu=
shrinkMenu=
mainMenu=0
colorMenu=0
// forthe nose
red.0=0.5=0.5
//
scale.0
//
menuFlag
funcchangeSize
w
h
//
(continues on next page)
58.12. Menu Events 729

Ring Documentation, Release 1.14
(continued from previous page)
//
ifh
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45.0, ratio,.1,.0)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
funcdrawSnowMan
glScalef(scale, scale, scale)
glColor3f(1.0,.0,.0)
//
glTranslatef(0.00.75,.0)
glutSolidSphere(0.75,20,20)
//
glTranslatef(0.0,.0,.0)
glutSolidSphere(0.25,20,20)
//
glPushMatrix()
glColor3f(0.0,0.0,0.0)
glTranslatef(0.05,.10,.18)
glutSolidSphere(0.05,10,10)
glTranslatef(-0.1,.0,.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
//
glColor3f(red, green, blue)
glRotatef(0.0,1.0,.0,.0)
glutSolidCone(0.08,0.5,10,2)
glColor3f(1.0,.0,.0)
funccomputePos deltaMove
x= *lx*0.1
z= *lz*0.1
(continues on next page)
58.12. Menu Events 730

Ring Documentation, Release 1.14
(continued from previous page)
funcrenderScene
ifdeltaMove
computePos(deltaMove)
ok
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
glLoadIdentity()
//
gluLookAt( x,.0, z,
x+lx,.0, z+lz,
0.0,.0,.0)
//
glColor3f(0.9,.9,.9)
glBegin(GL_QUADS)
glVertex3f(-100.0,.0,100.0)
glVertex3f(-100.0,.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,100.0)
glEnd()
//
fori3 to2
forj3 to2
glPushMatrix()
glTranslatef(i*10.0,.0, j *10.0)
drawSnowMan()
glPopMatrix()
next
next
glutSwapBuffers()
//----------------------------------
//
//----------------------------------
funcprocessNormalKeys
key
xx
yy
glutSetMenu(mainMenu)
switchkey
on27
glutDestroyMenu(mainMenu)
glutDestroyMenu(fillMenu)
glutDestroyMenu(colorMenu)
glutDestroyMenu(shrinkMenu)
shutdown()
(continues on next page)
58.12. Menu Events 731

Ring Documentation, Release 1.14
(continued from previous page)
ons
if menuFlag
glutChangeToSubMenu(2,"Shrink",shrinkMenu)
ok
onc
if menuFlag
glutChangeToSubMenu(2,"Color",colorMenu)
ok
off
ifkey
shutdown()
ok
funcpressKey
key
xx
yy
switchkey
onGLUT_KEY_UP
deltaMove.5
onGLUT_KEY_DOWN
deltaMove0.5
off
funcreleaseKey
key
switchkey
onGLUT_KEY_UP
deltaMove
onGLUT_KEY_DOWN
deltaMove
off
//----------------------------------
//
//----------------------------------
funcmouseMove
xx
yy
// truewhen the left button is down
ifxOrigin=
//
deltaAngle *0.001
//sirection
lx
(continues on next page)
58.12. Menu Events 732

Ring Documentation, Release 1.14
(continued from previous page)
lzcos(angle
ok
funcmouseButton
button
state
xx
yy
// ifthe left button is pressed
ifbutton
//
ifstate
angle=
xOrigin1
else
//
xOrigin
ok
ok
//----------------------------------
//
//----------------------------------
funcprocessMenuStatus
status
xx
yy
ifstatus
menuFlag
else
menuFlag
ok
funcprocessMainMenu
// to here
// forsubmenus
funcprocessFillMenu
option
switchoption
onC_FILL
glPolygonMode(GL_FRONT, GL_FILL)
onC_LINE
glPolygonMode(GL_FRONT, GL_LINE)
(continues on next page)
58.12. Menu Events 733

Ring Documentation, Release 1.14
(continued from previous page)
off
funcprocessShrinkMenu
option
switchoption
onC_SHRINK
scale.5
onC_NORMAL
scale.0
off
funcprocessColorMenu
option
switchoption
onC_RED
red.0
green.0
blue.0
onC_GREEN
red.0
green.0
blue.0
onC_BLUE
red.0
green.0
blue.0
onC_ORANGE
red.0
green.5
blue.5
off
funccreatePopupMenus
shrinkMenu
glutAddMenuEntry("Shrink",C_SHRINK)
glutAddMenuEntry("NORMAL",C_NORMAL)
fillMenu
glutAddMenuEntry("Fill",C_FILL)
glutAddMenuEntry("Line",C_LINE)
colorMenu
glutAddMenuEntry("Red",C_RED)
glutAddMenuEntry("Blue",C_BLUE)
glutAddMenuEntry("Green",C_GREEN)
glutAddMenuEntry("Orange",C_ORANGE)
(continues on next page)
58.12. Menu Events 734

Ring Documentation, Release 1.14
(continued from previous page)
mainMenu
glutAddSubMenu("Polygon Mode", fillMenu)
glutAddSubMenu("Color", colorMenu)
// tothe right button
glutAttachMenu(GLUT_RIGHT_BUTTON)
// toknowifthe menu is active
glutMenuStatusFunc(:processMenuStatus)
//----------------------------------
//
//----------------------------------
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 10")
//
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutIgnoreKeyRepeat(1)
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:pressKey)
glutSpecialUpFunc(:releaseKey)
// newfunctions
glutMouseFunc(:mouseButton)
glutMotionFunc(:mouseMove)
//
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
//
createPopupMenus()
//
glutMainLoop()
Screen Shot
58.12. Menu Events 735

Ring Documentation, Release 1.14
58.13
Example:
load"freeglut.ring"
load"opengl21lib.ring"
// forthe camera direction
angle.0
//sirection
lx=0.0=-1.0
//
x=0.0=5.0
//
//when no key is being presses
deltaAngle.0
deltaMove
xOrigin1
// forMenus
C_RED
C_GREEN
C_BLUE
C_ORANGE
C_FILL
C_LINE
(continues on next page)
58.13. Using Fonts 736

Ring Documentation, Release 1.14
(continued from previous page)
//
fillMenu= NULL
fontMenu= NULL
mainMenu= NULL
colorMenu= NULL
// forthe nose
red.0
blue=0.5
green=0.5
//
scale.0
//
menuFlag
//
font
C_INT_GLUT_BITMAP_8_BY_13
C_INT_GLUT_BITMAP_9_BY_15
C_INT_GLUT_BITMAP_TIMES_ROMAN_10
C_INT_GLUT_BITMAP_TIMES_ROMAN_24
C_INT_GLUT_BITMAP_HELVETICA_10
C_INT_GLUT_BITMAP_HELVETICA_12
C_INT_GLUT_BITMAP_HELVETICA_18
funcchangeSize
w
h
//
//
ifh
h
ok
ratio *1.0
//
glMatrixMode(GL_PROJECTION)
//
glLoadIdentity()
// tobe the entire window
glViewport(0,, w, h)
//
gluPerspective(45.0, ratio,.1,.0)
//GetBacktothe Modelview
glMatrixMode(GL_MODELVIEW)
funcdrawSnowMan
(continues on next page)
58.13. Using Fonts 737

Ring Documentation, Release 1.14
(continued from previous page)
glScalef(scale, scale, scale)
glColor3f(1.0,.0,.0)
//
glTranslatef(0.00.75,.0)
glutSolidSphere(0.75,20,20)
//
glTranslatef(0.0,.0,.0)
glutSolidSphere(0.25,20,20)
//
glPushMatrix()
glColor3f(0.0,0.0,0.0)
glTranslatef(0.05,.10,.18)
glutSolidSphere(0.05,10,10)
glTranslatef(-0.1,.0,.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
//
glColor3f(red, green, blue)
glRotatef(0.0,1.0,.0,.0)
glutSolidCone(0.08,0.5,10,2)
glColor3f(1.0,.0,.0)
funcrenderBitmapString x,y,z,font, string
glRasterPos3f(x, y,z)
forcin
glutBitmapCharacter(font,ascii(c))
next
funccomputePos deltaMove
x= *lx*0.1
z= *lz*0.1
funcrenderScene
ifdeltaMove
computePos(deltaMove)
ok
// andDepth Buffers
glClear(GL_COLOR_BUFFER_BIT
//
glLoadIdentity()
//
gluLookAt( x,.0, z,
x+lx,.0, z+lz,
0.0,.0,.0)
(continues on next page)
58.13. Using Fonts 738

Ring Documentation, Release 1.14
(continued from previous page)
//
glColor3f(0.9,.9,.9)
glBegin(GL_QUADS)
glVertex3f(-100.0,.0,100.0)
glVertex3f(-100.0,.0,.0)
glVertex3f(.0,.0,.0)
glVertex3f(.0,.0,100.0)
glEnd()
//
fori3 to2
forj3 to2
glPushMatrix()
glTranslatef(i*10.0,.0, j *10.0)
drawSnowMan()
number+3) *6+(j+3)
renderBitmapString(0.0,.5,.0,font ,""+number)
glPopMatrix()
next
next
glutSwapBuffers()
//----------------------------------
//
//----------------------------------
funcprocessNormalKeys
key
xx
yy
switchkey
on27
glutDestroyMenu(mainMenu)
glutDestroyMenu(fillMenu)
glutDestroyMenu(colorMenu)
glutDestroyMenu(fontMenu)
Shutdown()
off
funcpressKey
key
xx
yy
switchkey
onGLUT_KEY_UP
deltaMove.5
onGLUT_KEY_DOWN
deltaMove0.5
off
(continues on next page)
58.13. Using Fonts 739

Ring Documentation, Release 1.14
(continued from previous page)
funcreleaseKey
key
switchkey
onGLUT_KEY_UP
deltaMove
onGLUT_KEY_DOWN
deltaMove
off
//----------------------------------
//
//----------------------------------
funcmouseMove
xx
yy
// truewhen the left button is down
ifxOrigin=
//
deltaAngle *0.001
//sirection
lx
lzcos(angle
ok
funcmouseButton
button
state
xx
yy
// ifthe left button is pressed
ifbutton
//
ifstate
angle=
xOrigin1
else
//
xOrigin
ok
ok
//----------------------------------
//
//----------------------------------
(continues on next page)
58.13. Using Fonts 740

Ring Documentation, Release 1.14
(continued from previous page)
funcprocessMenuStatus
status
ifstatus
menuFlag
else
menuFlag
ok
funcprocessMainMenu
// to here
// forsubmenus
funcprocessFillMenu
option
switchoption
onC_FILL
glPolygonMode(GL_FRONT, GL_FILL)
onC_LINE
glPolygonMode(GL_FRONT, GL_LINE)
off
funcprocessFontMenu
option
switch(option) {
onC_INT_GLUT_BITMAP_8_BY_13
font
onC_INT_GLUT_BITMAP_9_BY_15
font
onC_INT_GLUT_BITMAP_TIMES_ROMAN_10
font
onC_INT_GLUT_BITMAP_TIMES_ROMAN_24
font
onC_INT_GLUT_BITMAP_HELVETICA_10
font
onC_INT_GLUT_BITMAP_HELVETICA_12
font
onC_INT_GLUT_BITMAP_HELVETICA_18
font
off
funcprocessColorMenu
option
switchoption
onC_RED
(continues on next page)
58.13. Using Fonts 741

Ring Documentation, Release 1.14
(continued from previous page)
red.0
green.0
blue.0
onC_GREEN
red.0
green.0
blue.0
onC_BLUE
red.0
green.0
blue.0
onC_ORANGE
red.0
green.5
blue.5
off
funccreatePopupMenus
fontMenu
glutAddMenuEntry("BITMAP_8_BY_13,C_INT_GLUT_BITMAP_8_BY_13 )
glutAddMenuEntry("BITMAP_9_BY_15",C_INT_GLUT_BITMAP_9_BY_15 )
glutAddMenuEntry("BITMAP_TIMES_ROMAN_10,C_INT_GLUT_BITMAP_TIMES_ROMAN_10 )
glutAddMenuEntry("BITMAP_TIMES_ROMAN_24",C_INT_GLUT_BITMAP_TIMES_ROMAN_24 )
glutAddMenuEntry("BITMAP_HELVETICA_10,C_INT_GLUT_BITMAP_HELVETICA_10 )
glutAddMenuEntry("BITMAP_HELVETICA_12",C_INT_GLUT_BITMAP_HELVETICA_12 )
glutAddMenuEntry("BITMAP_HELVETICA_18",C_INT_GLUT_BITMAP_HELVETICA_18 )
fillMenu
glutAddMenuEntry("Fill",C_FILL)
glutAddMenuEntry("Line",C_LINE)
colorMenu
glutAddMenuEntry("Red",C_RED);
glutAddMenuEntry("Blue",C_BLUE);
glutAddMenuEntry("Green",C_GREEN);
glutAddMenuEntry("Orange",C_ORANGE);
mainMenu
glutAddSubMenu("Polygon Mode", fillMenu)
glutAddSubMenu("Color", colorMenu)
glutAddSubMenu("Font",fontMenu)
// tothe right button
glutAttachMenu(GLUT_RIGHT_BUTTON)
// toknowifthe menu is active
glutMenuStatusFunc(:processMenuStatus)
//----------------------------------
//
//----------------------------------
(continues on next page)
58.13. Using Fonts 742

Ring Documentation, Release 1.14
(continued from previous page)
funcmain
// andcreate window
glutInit()
glutInitDisplayMode(GLUT_DEPTH
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test 11")
//
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutIgnoreKeyRepeat(1)
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:pressKey)
glutSpecialUpFunc(:releaseKey)
// newfunctions
glutMouseFunc(:mouseButton)
glutMotionFunc(:mouseMove)
//
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
//
createPopupMenus()
//
glutMainLoop()
Screen Shot
58.13. Using Fonts 743

Ring Documentation, Release 1.14
58.14
Example
load "freeglut.ring"
load "opengl21lib.ring"
// angle of rotation for the camera direction
angle = 0.0
// actual vector representing the cameras direction
lx=0.0 lz=-1.0
// XZ position of the camera
x=0.0 z=5.0
// the key states. These variables will be zero
//when no key is being presses
deltaAngle = 0.0
deltaMove = 0
xOrigin = -1
// Constant definitions for Menus
C_RED = 1
C_GREEN = 2
C_BLUE = 3
C_ORANGE = 4
C_FILL = 5
C_LINE = 6
// Pop up menu identifiers
fillMenu=NULL
fontMenu=NULL
mainMenu=NULL
colorMenu=NULL
// color for the nose
red = 1.0
blue=0.5
green=0.5
// scale of snowman
scale = 1.0
// menu status
menuFlag = 0
// default font
font = GLUT_BITMAP_TIMES_ROMAN_24
C_INT_GLUT_BITMAP_8_BY_13 = 7
C_INT_GLUT_BITMAP_9_BY_15 = 8
C_INT_GLUT_BITMAP_TIMES_ROMAN_10 = 9
C_INT_GLUT_BITMAP_TIMES_ROMAN_24 = 10
C_INT_GLUT_BITMAP_HELVETICA_10 = 11
C_INT_GLUT_BITMAP_HELVETICA_12 = 12
(continues on next page)
58.14. Frames Per Second 744

Ring Documentation, Release 1.14
(continued from previous page)
C_INT_GLUT_BITMAP_HELVETICA_18 = 13
// width and height of the window
h = 0
w = 0
// variables to compute frames per second
frame=0
time=0
timebase=0
s = ""
func changeSize
w = glutEventWidth()
h = glutEventHeight()
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if h = 0
h = 1
ok
ratio = w *1.0 / h
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION)
// Reset Matrix
glLoadIdentity()
// Set the viewport to be the entire window
glViewport(0, 0, w, h)
// Set the correct perspective.
gluPerspective(45.0, ratio, 0.1, 100.0)
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW)
func drawSnowMan
glScalef(scale, scale, scale)
glColor3f(1.0, 1.0, 1.0)
// Draw Body
glTranslatef(0.0 ,0.75, 0.0)
glutSolidSphere(0.75,20,20)
// Draw Head
glTranslatef(0.0, 1.0, 0.0)
glutSolidSphere(0.25,20,20)
// Draw Eyes
glPushMatrix()
glColor3f(0.0,0.0,0.0)
glTranslatef(0.05, 0.10, 0.18)
glutSolidSphere(0.05,10,10)
(continues on next page)
58.14. Frames Per Second 745

Ring Documentation, Release 1.14
(continued from previous page)
glTranslatef(-0.1, 0.0, 0.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
// Draw Nose
glColor3f(red, green, blue)
glRotatef(0.0,1.0, 0.0, 0.0)
glutSolidCone(0.08,0.5,10,2)
glColor3f(1.0, 1.0, 1.0)
func renderBitmapString x,y,z,font,string
glRasterPos3f(x, y,z)
for c in string
glutBitmapCharacter(font,ascii(c))
next
func renderStrokeFontString x,y,z,font,string
glPushMatrix()
glTranslatef(x, y,z)
glScalef(0.002, 0.002, 0.002)
for c in string
glutStrokeCharacter(font, Ascii(c));
next
glPopMatrix()
func restorePerspectiveProjection
glMatrixMode(GL_PROJECTION)
// restore previous projection matrix
glPopMatrix()
// get back to modelview mode
glMatrixMode(GL_MODELVIEW)
func setOrthographicProjection
// switch to projection mode
glMatrixMode(GL_PROJECTION)
// save previous matrix which contains the
//settings for the perspective projection
glPushMatrix()
// reset matrix
glLoadIdentity()
// set a 2D orthographic projection
gluOrtho2D(0, w, h, 0)
// switch back to modelview mode
glMatrixMode(GL_MODELVIEW)
(continues on next page)
58.14. Frames Per Second 746

Ring Documentation, Release 1.14
(continued from previous page)
func computePos deltaMove
x += deltaMove*lx*0.1
z += deltaMove*lz*0.1
func renderScene
if deltaMove
computePos(deltaMove)
ok
// Clear Color and Depth Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
// Reset transformations
glLoadIdentity()
// Set the camera
gluLookAt( x, 1.0, z,
x+lx, 1.0, z+lz,
0.0, 1.0, 0.0)
// Draw ground
glColor3f(0.9, 0.9, 0.9)
glBegin(GL_QUADS)
glVertex3f(-100.0, 0.0, -100.0)
glVertex3f(-100.0, 0.0, 100.0)
glVertex3f( 100.0, 0.0, 100.0)
glVertex3f( 100.0, 0.0, -100.0)
glEnd()
// Draw 9 SnowMen
for i = -3 to -1
for j = -3 to -1
glPushMatrix()
glTranslatef(i*10.0, 0.0, j*10.0)
drawSnowMan()
number = (i+3)*3+(j+3)
renderBitmapString(0.0, 0.5, 0.0,font ,""+number)
glPopMatrix()
next
next
// Code to compute frames per second
frame++
time=glutGet(GLUT_ELAPSED_TIME)
if time - timebase > 1000
s = "RingFreeGLUT - FPS: " + (frame *1000.0/(time-timebase))
timebase = time
frame = 0
ok
// Code to display a string (fps) with bitmap fonts
setOrthographicProjection()
(continues on next page)
58.14. Frames Per Second 747

Ring Documentation, Release 1.14
(continued from previous page)
glPushMatrix()
glLoadIdentity()
renderBitmapString(5,30,0,GLUT_BITMAP_HELVETICA_18,s)
glPopMatrix()
restorePerspectiveProjection()
glutSwapBuffers()
// -----------------------------------
// KEYBOARD
// -----------------------------------
func processNormalKeys
key = glutEventKey()
xx = glutEventX()
yy = glutEventY()
switch key
on 27
glutDestroyMenu(mainMenu)
glutDestroyMenu(fillMenu)
glutDestroyMenu(colorMenu)
glutDestroyMenu(fontMenu)
Shutdown()
off
func pressKey
key = glutEventKey()
xx = glutEventX()
yy = glutEventY()
switch key
on GLUT_KEY_UP
deltaMove = 0.5
on GLUT_KEY_DOWN
deltaMove = -0.5
off
func releaseKey
key = glutEventKey()
switch key
on GLUT_KEY_UP
deltaMove = 0
on GLUT_KEY_DOWN
deltaMove = 0
off
// -----------------------------------
(continues on next page)
58.14. Frames Per Second 748

Ring Documentation, Release 1.14
(continued from previous page)
// MOUSE
// -----------------------------------
func mouseMove
xx = glutEventX()
yy = glutEventY()
// this will only be true when the left button is down
if xOrigin >= 0
// update deltaAngle
deltaAngle = (xx - xOrigin) *0.001
// update cameras direction
lx = sin(angle + deltaAngle)
lz = -cos(angle + deltaAngle)
ok
func mouseButton
button = glutEventButton()
state = glutEventState()
xx = glutEventX()
yy = glutEventY()
// only start motion if the left button is pressed
if button = GLUT_LEFT_BUTTON
// when the button is released
if state = GLUT_UP
angle += deltaAngle
xOrigin = -1
else
// state = GLUT_DOWN
xOrigin = xx
ok
ok
// -----------------------------------
// MENUS
// -----------------------------------
func processMenuStatus
status = glutEventStatus()
if status = GLUT_MENU_IN_USE
menuFlag = 1
else
menuFlag = 0
ok
func processMainMenu
// nothing to do in here
(continues on next page)
58.14. Frames Per Second 749

Ring Documentation, Release 1.14
(continued from previous page)
// all actions are for submenus
func processFillMenu
option = glutEventValue()
switch option
on C_FILL
glPolygonMode(GL_FRONT, GL_FILL)
on C_LINE
glPolygonMode(GL_FRONT, GL_LINE)
off
func processFontMenu
option = glutEventValue()
switch (option) {
on C_INT_GLUT_BITMAP_8_BY_13
font = GLUT_BITMAP_8_BY_13
on C_INT_GLUT_BITMAP_9_BY_15
font = GLUT_BITMAP_9_BY_15
on C_INT_GLUT_BITMAP_TIMES_ROMAN_10
font = GLUT_BITMAP_TIMES_ROMAN_10
on C_INT_GLUT_BITMAP_TIMES_ROMAN_24
font = GLUT_BITMAP_TIMES_ROMAN_24
on C_INT_GLUT_BITMAP_HELVETICA_10
font = GLUT_BITMAP_HELVETICA_10
on C_INT_GLUT_BITMAP_HELVETICA_12
font = GLUT_BITMAP_HELVETICA_12
on C_INT_GLUT_BITMAP_HELVETICA_18
font = GLUT_BITMAP_HELVETICA_18
off
func processColorMenu
option = glutEventValue()
switch option
on C_RED
red = 1.0
green = 0.0
blue = 0.0
on C_GREEN
red = 0.0
green = 1.0
blue = 0.0
on C_BLUE
red = 0.0
green = 0.0
blue = 1.0
on C_ORANGE
red = 1.0
green = 0.5
(continues on next page)
58.14. Frames Per Second 750

Ring Documentation, Release 1.14
(continued from previous page)
blue = 0.5
off
func createPopupMenus
fontMenu = glutCreateMenu(:processFontMenu)
glutAddMenuEntry("BITMAP_8_BY_13 ",C_INT_GLUT_BITMAP_8_BY_13 )
glutAddMenuEntry("BITMAP_9_BY_15",C_INT_GLUT_BITMAP_9_BY_15 )
glutAddMenuEntry("BITMAP_TIMES_ROMAN_10 ",C_INT_GLUT_BITMAP_TIMES_ROMAN_10 )
glutAddMenuEntry("BITMAP_TIMES_ROMAN_24",C_INT_GLUT_BITMAP_TIMES_ROMAN_24 )
glutAddMenuEntry("BITMAP_HELVETICA_10 ",C_INT_GLUT_BITMAP_HELVETICA_10 )
glutAddMenuEntry("BITMAP_HELVETICA_12",C_INT_GLUT_BITMAP_HELVETICA_12 )
glutAddMenuEntry("BITMAP_HELVETICA_18",C_INT_GLUT_BITMAP_HELVETICA_18 )
fillMenu = glutCreateMenu(:processFillMenu)
glutAddMenuEntry("Fill",C_FILL)
glutAddMenuEntry("Line",C_LINE)
colorMenu = glutCreateMenu(:processColorMenu)
glutAddMenuEntry("Red",C_RED);
glutAddMenuEntry("Blue",C_BLUE);
glutAddMenuEntry("Green",C_GREEN);
glutAddMenuEntry("Orange",C_ORANGE);
mainMenu = glutCreateMenu(:processMainMenu)
glutAddSubMenu("Polygon Mode", fillMenu)
glutAddSubMenu("Color", colorMenu)
glutAddSubMenu("Font",fontMenu)
// attach the menu to the right button
glutAttachMenu(GLUT_RIGHT_BUTTON)
// this will allow us to know if the menu is active
glutMenuStatusFunc(:processMenuStatus)
// -----------------------------------
// MAIN
// -----------------------------------
func main
// init GLUT and create window
glutInit()
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test - 9 SnowMan")
// register callbacks
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
(continues on next page)
58.14. Frames Per Second 751

Ring Documentation, Release 1.14
(continued from previous page)
glutIgnoreKeyRepeat(1)
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:pressKey)
glutSpecialUpFunc(:releaseKey)
// here are the two new functions
glutMouseFunc(:mouseButton)
glutMotionFunc(:mouseMove)
// OpenGL init
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
// init Menus
createPopupMenus()
// enter GLUT event processing cycle
glutMainLoop()
Screen Shots:
The First screen shot
The Second screen shot
58.14. Frames Per Second 752

Ring Documentation, Release 1.14
58.15
Example:
load"freeglut.ring"
load"opengl21lib.ring"
//---------------------------------------------------------
//
//---------------------------------------------------------
rotate_y=0
rotate_x=0
//---------------------------------------------------------
//
//---------------------------------------------------------
funcdisplay
// andZ-buffer
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
//
glLoadIdentity()
// androtate_y
glRotatef( rotate_x,.0,.0,.0
glRotatef( rotate_y,.0,.0,.0
//Multi-colored side
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0.5,0.5,0.5 # P1 is red
(continues on next page)
58.15. Make a Cube using RingOpenGL and RingFreeGLUT 753

Ring Documentation, Release 1.14
(continued from previous page)
glColor3f(.0,.0,.0.5,.5,0.5 # P2 is green
glColor3f(.0,.0,.00.5,.5,0.5 # P3 is blue
glColor3f(.0,.0,.00.5,0.5,0.5 # P4 is purple
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,0.5,.5
glVertex3f(.5,.5,.5
glVertex3f(0.5,.5,.5
glVertex3f(0.5,0.5,.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,0.5,0.5
glVertex3f(.5,.5,0.5
glVertex3f(.5,.5,.5
glVertex3f(.5,0.5,.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(0.5,0.5,.5
glVertex3f(0.5,.5,.5
glVertex3f(0.5,.5,0.5
glVertex3f(0.5,0.5,0.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,.5,.5
glVertex3f(.5,.5,0.5
glVertex3f(0.5,.5,0.5
glVertex3f(0.5,.5,.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,0.5,0.5
glVertex3f(.5,0.5,.5
glVertex3f(0.5,0.5,.5
glVertex3f(0.5,0.5,0.5
glEnd()
glFlush()
glutSwapBuffers()
//---------------------------------------------------------
//
(continues on next page)
58.15. Make a Cube using RingOpenGL and RingFreeGLUT 754

Ring Documentation, Release 1.14
(continued from previous page)
//---------------------------------------------------------
funcspecialKeys
key
//
switchKey
onGLUT_KEY_RIGHT
rotate_y=
//
onGLUT_KEY_LEFT
rotate_y=
onGLUT_KEY_UP
rotate_x=
onGLUT_KEY_DOWN
rotate_x=
off
//
glutPostRedisplay()
//---------------------------------------------------------
//
//---------------------------------------------------------
funcmain
// andprocess user parameters
glutInit()
// truecolor window with Z-buffer
glutInitDisplayMode(GLUT_DOUBLE
//
glutCreateWindow("Awesome Cube")
//-buffer depth test
glEnable(GL_DEPTH_TEST)
//
glutDisplayFunc(:display)
glutSpecialFunc(:specialKeys)
// toGLUTforevents
glutMainLoop()
//Return OS
Screen Shot:
58.15. Make a Cube using RingOpenGL and RingFreeGLUT 755

Ring Documentation, Release 1.14
58.15. Make a Cube using RingOpenGL and RingFreeGLUT 756

CHAPTER
FIFTYNINE
USING RINGOPENGL AND RINGALLEGRO FOR 3D GRAPHICS
In this chapter we will learn about using RingOpenGL and RingAllegro
59.1
Source Code:
# Load Libraries
load"gamelib.ring" # RingAllegro Library
load"opengl21lib.ring" # RingOpenGL Library
#==============================================================
# To Support MacOS X
al_run_main()
funcal_game_start # Called by al_run_main()
main() # Now we call our main function
#==============================================================
funcmain
newGraphicsApp {
start()
}
classGraphicsAppfromGraphicsAppBase
TITLERing Cube"
bitmap texture
xrot.0
yrot.0
zrot.0
funcloadresources
bitmap"ring.bmp")
texture
funcdestroyResources
al_destroy_bitmap(bitmap)
(continues on next page)
757

Ring Documentation, Release 1.14
(continued from previous page)
funcdrawScene
w
ratio
glViewport(0,, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45,ratio,1,100)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_TEXTURE_2D)
glShadeModel(GL_SMOOTH)
glClearColor(0.0,.0,.0,.5)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glClear(GL_COLOR_BUFFER_BIT
glLoadIdentity()
glTranslatef(0.0,0.0,-5.0)
glRotatef(xrot,1.0,0.0,0.0)
glRotatef(yrot,0.0,1.0,0.0)
glRotatef(zrot,0.0,0.0,1.0)
glBindTexture(GL_TEXTURE_2D, texture)
glBegin(GL_QUADS)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
(continues on next page)
59.1. 3D Cube and Texture 758

Ring Documentation, Release 1.14
(continued from previous page)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glEnd()
xrot=.3
yrot=.2
zrot=.4
classGraphicsAppBase
display event_queue ev timeout
timer redraw true
FPS
SCREEN_W
SCREEN_H
KEY_UP
KEY_DOWN
KEY_LEFT
KEY_RIGHT
Key false,false,false,false]
TITLEGraphics Application"
funcstart
SetUp()
loadResources()
eventsLoop()
destroy()
funcsetup
al_init()
al_init_image_addon()
al_set_new_display_flags(ALLEGRO_OPENGL)
display
al_set_Window_title(display,TITLE)
al_clear_to_color(al_map_rgb(0,0,0))
event_queue
al_register_event_source(event_queue,
al_get_display_event_source(display))
ev
timeout
al_init_timeout(timeout,.06)
timer1.0
al_register_event_source(event_queue,
al_get_timer_event_source(timer))
(continues on next page)
59.1. 3D Cube and Texture 759

Ring Documentation, Release 1.14
(continued from previous page)
al_start_timer(timer)
al_install_mouse()
al_register_event_source(event_queue,
al_get_mouse_event_source())
al_install_keyboard()
al_register_event_source(event_queue,
al_get_keyboard_event_source())
funceventsLoop
while
al_init_timeout(timeout,.06)
al_wait_for_event_until(event_queue, ev, timeout)
switchal_get_allegro_event_type(ev)
onALLEGRO_EVENT_DISPLAY_CLOSE
exit
onALLEGRO_EVENT_TIMER
redraw true
onALLEGRO_EVENT_MOUSE_AXES
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_ENTER_DISPLAY
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_BUTTON_UP
exit
onALLEGRO_EVENT_KEY_DOWN
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] true
onALLEGRO_KEY_DOWN
key[KEY_DOWN] true
onALLEGRO_KEY_LEFT
key[KEY_LEFT] true
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] true
off
onALLEGRO_EVENT_KEY_UP
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] false
onALLEGRO_KEY_DOWN
key[KEY_DOWN] false
onALLEGRO_KEY_LEFT
key[KEY_LEFT] false
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] false
onALLEGRO_KEY_ESCAPE
exit
off
off
ifredrawandal_is_event_queue_empty(event_queue)
redraw false
drawScene()
al_flip_display()
ok
callgc()
(continues on next page)
59.1. 3D Cube and Texture 760

Ring Documentation, Release 1.14
(continued from previous page)
end
funcdestroy
destroyResources()
al_destroy_timer(timer)
al_destroy_allegro_event(ev)
al_destroy_allegro_timeout(timeout)
al_destroy_event_queue(event_queue)
al_destroy_display(display)
al_exit()
funcloadresources
funcdrawScene
funcdestroyResources
Screen Shot:
59.2
Source Code:
# Load Libraries
load"gamelib.ring" # RingAllegro Library
load"opengl21lib.ring" # RingOpenGL Library
#==============================================================
# To Support MacOS X
al_run_main()
(continues on next page)
59.2. Many Cubes 761

Ring Documentation, Release 1.14
(continued from previous page)
funcal_game_start # Called by al_run_main()
main() # Now we call our main function
#==============================================================
funcmain
newGraphicsApp {
start()
}
classGraphicsAppfromGraphicsAppBase
TITLEMany Cubes"
bitmap bitmap2 bitmap3
texture texture2 texture3
fps
xrot.0
yrot.0
zrot.0
nPerspective
funcloadresources
bitmap"sky1.jpg")
texture
bitmap2"sky2.jpg")
texture2
bitmap3"sky3.jpg")
texture3
funcdestroyResources
al_destroy_bitmap(bitmap)
al_destroy_bitmap(bitmap2)
al_destroy_bitmap(bitmap3)
funcdrawScene
prepare()
cubes()
rotate()
funcPrepare
w
ratio
glViewport(0,, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(-nPerspective,ratio,1,nPerspective)
glMatrixMode(GL_MODELVIEW)
(continues on next page)
59.2. Many Cubes 762

Ring Documentation, Release 1.14
(continued from previous page)
glLoadIdentity()
glEnable(GL_TEXTURE_2D)
glShadeModel(GL_SMOOTH)
glClearColor(0.0,.0,.0,.5)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glClear(GL_COLOR_BUFFER_BIT
funcCubes
cube(5,-3.4,-5,:sky1)
cube(0,-3,-5,:sky1)
cube(-5,-3,-5,:sky1)
cube(5,0.5,-5,:sky2)
cube(0,0.5,-5,:sky2)
cube(-5,0.5,-5,:sky2)
cube(5,4,-5,:sky3)
cube(0,4,-5,:sky3)
cube(-5,4,-5,:sky3)
funcRotate
xrot=.3 *5
yrot=.2 *5
zrot=.4 *5
nPerspective=.5
funccube(x,y,z,nTexture)
glLoadIdentity()
glTranslatef(x,y,z)
glRotatef(xrot,1.0,0.0,0.0)
glRotatef(yrot,0.0,1.0,0.0)
glRotatef(zrot,0.0,0.0,1.0)
drawcube(nTexture)
funcdrawcube(cTexture)
switchcTexture
on:sky1
glBindTexture(GL_TEXTURE_2D, texture)
on:sky2
glBindTexture(GL_TEXTURE_2D, texture2)
on:sky3
glBindTexture(GL_TEXTURE_2D, texture3)
off
glBegin(GL_QUADS)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
(continues on next page)
59.2. Many Cubes 763

Ring Documentation, Release 1.14
(continued from previous page)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glEnd()
classGraphicsAppBase
display event_queue ev timeout
timer redraw true
FPS
SCREEN_W
SCREEN_H
KEY_UP
KEY_DOWN
KEY_LEFT
KEY_RIGHT
Key false,false,false,false]
TITLEGraphics Application"
funcstart
SetUp()
loadResources()
eventsLoop()
destroy()
funcsetup
al_init()
(continues on next page)
59.2. Many Cubes 764

Ring Documentation, Release 1.14
(continued from previous page)
al_init_image_addon()
al_set_new_display_flags(ALLEGRO_OPENGL)
display
al_set_Window_title(display,TITLE)
al_clear_to_color(al_map_rgb(0,0,0))
event_queue
al_register_event_source(event_queue,
al_get_display_event_source(display))
ev
timeout
al_init_timeout(timeout,.06)
timer1.0
al_register_event_source(event_queue,
al_get_timer_event_source(timer))
al_start_timer(timer)
al_install_mouse()
al_register_event_source(event_queue,
al_get_mouse_event_source())
al_install_keyboard()
al_register_event_source(event_queue,
al_get_keyboard_event_source())
funceventsLoop
while
al_init_timeout(timeout,.06)
al_wait_for_event_until(event_queue, ev, timeout)
switchal_get_allegro_event_type(ev)
onALLEGRO_EVENT_DISPLAY_CLOSE
exit
onALLEGRO_EVENT_TIMER
redraw true
onALLEGRO_EVENT_MOUSE_AXES
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_ENTER_DISPLAY
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_BUTTON_UP
exit
onALLEGRO_EVENT_KEY_DOWN
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] true
onALLEGRO_KEY_DOWN
key[KEY_DOWN] true
onALLEGRO_KEY_LEFT
key[KEY_LEFT] true
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] true
off
onALLEGRO_EVENT_KEY_UP
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] false
onALLEGRO_KEY_DOWN
key[KEY_DOWN] false
(continues on next page)
59.2. Many Cubes 765

Ring Documentation, Release 1.14
(continued from previous page)
onALLEGRO_KEY_LEFT
key[KEY_LEFT] false
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] false
onALLEGRO_KEY_ESCAPE
exit
off
off
ifredrawandal_is_event_queue_empty(event_queue)
redraw false
drawScene()
al_flip_display()
ok
callgc()
end
funcdestroy
destroyResources()
al_destroy_timer(timer)
al_destroy_allegro_event(ev)
al_destroy_allegro_timeout(timeout)
al_destroy_event_queue(event_queue)
al_destroy_display(display)
al_exit()
funcloadresources
funcdrawScene
funcdestroyResources
Screen Shot:
59.2. Many Cubes 766

Ring Documentation, Release 1.14
59.3
Source Code:
# Load Libraries
load"gamelib.ring" # RingAllegro Library
load"opengl21lib.ring" # RingOpenGL Library
#==============================================================
# To Support MacOS X
al_run_main()
funcal_game_start # Called by al_run_main()
main() # Now we call our main function
#==============================================================
funcmain
newTicTacToe3D {
start()
}
classTicTacToe3DfromGameLogic
(continues on next page)
59.3. TicTacToe 3D Game 767

Ring Documentation, Release 1.14
(continued from previous page)
FPS
TITLETicTacToe 3D"
oBackground newGameBackground
oGameSound newGameSound
oGameCube newGameCube
oGameOver newGameOver
oGameInterface newGameInterface
funcloadresources
oGameOver.loadresources()
oGameSound.loadresources()
oBackGround.loadresources()
oGameCube.loadresources()
funcdestroyResources
oGameOver.destroyResources()
oGameSound.destroyResources()
oBackGround.destroyResources()
oGameCube.destroyResources()
funcdrawScene
oBackground.update()
oGameInterface.update(self)
funcMouseClickEvent
oGameInterface.MouseClickEvent(self)
classGameInterface
funcUpdate oGame
prepare()
cubes(oGame)
funcPrepare
w
ratio
glViewport(0,, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(-120,ratio,1,120)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_TEXTURE_2D)
glShadeModel(GL_SMOOTH)
glClearColor(0.0,.0,.0,.5)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
funcCubes oGame
oGame.oGameCube {
aGameMap
cube(35[1][1]
(continues on next page)
59.3. TicTacToe 3D Game 768

Ring Documentation, Release 1.14
(continued from previous page)
cube(35[1][2]
cube(535[1][3]
cube(5[2][1]
cube(5[2][2]
cube(55[2][3]
cube(5[3][1]
cube(5[3][2]
cube(55[3][3]
rotate()
}
funcMouseClickEvent oGame
oGame {
aBtn
nRow[1]
nCol[2]
ifnRow= andnCol=
ifaGameMap[nRow][nCol]
aGameMap[nRow][nCol]
ChangeActivePlayer()
CheckGameOver()
ok
ok
}
ClassGameLogicfromGraphicsAppBase
aGameMap
[
[
[
]
aGameButtons # x1,y1,x2,y2
[176,88,375,261], # [1,1]
[423,88,591,261], # [1,2]
[645,88,876,261], # [1,3]
[176,282,375,428], # [2,1]
[423,282,591,428], # [2,2]
[645,282,876,428], # [2,3]
[176,454,375,678], # [3,1]
[423,454,591,678], # [3,2]
[645,454,876,678] # [3,3]
]
cActivePlayer
funcpoint2button x,y
nRow
nCol
fort tolen(aGameButtons)
rect[t]
ifx=[1] andx=[3] and
y=[2] andy=[4]
switcht
on1
on2
(continues on next page)
59.3. TicTacToe 3D Game 769

Ring Documentation, Release 1.14
(continued from previous page)
on3
on4
on5
on6
on7
on8
on9
off
exit
ok
next
return[nRow,nCol]
funcChangeActivePlayer()
ifcActivePlayer
cActivePlayer
else
cActivePlayer
ok
funcCheckGameOver
aList
aGameMap[1][1],
aGameMap[1][2],
aGameMap[1][3],
aGameMap[2][1],
aGameMap[2][2],
aGameMap[2][3],
aGameMap[3][1],
aGameMap[3][2],
aGameMap[3][3]
]
foriteminaList
switchitem
on:x item
on:o item
on:n item
off
next
nStatus
ifnStatus
oGameOver {
SwitchnStatus
on1
on2
on3
off
}
refreshGame()
ok
funcrefreshGame
aGameMap
[
[
[
]
(continues on next page)
59.3. TicTacToe 3D Game 770

Ring Documentation, Release 1.14
(continued from previous page)
cActivePlayer
funcCheckWinner lst
//vertical check
forv=1to9step3
iflst[v]!=0 andlst[v+1]!=0 andlst[v+2]!=0
iflst[v]=lst[v+1] andlst[v+1]=lst[v+2]
returnlst[v]
ok
ok
next
//horzintal
forh=1to3
iflst[h]!=0 andlst[h+3]!=0 andlst[h+6]!=0
iflst[h]=lst[h+3] andlst[h+3]=lst[h+6]
returnlst[h]
ok
ok
next
//Cross
iflst[1]!=0 andlst[5]!=0 andlst[9]!=0
iflst[1]=lst[5] andlst[5]=lst[9] returnlst[1] ok
ok
iflst[3]!=0 andlst[5]!=0 andlst[7]!=0
iflst[3]=lst[5] andlst[5]=lst[7] returnlst[3] ok
ok
//tie
tie=true
fori=1to9
iflst[i]=0= false
next
iftie=true 3ok 0
classGameOver
font bitmap
funcloadresources
font"font/pirulen.ttf",54,0
bitmap"image/ballon.png")
funcdestroyResources
al_destroy_bitmap(bitmap)
al_destroy_font(font)
funcPlayer1Win oGame
showMsg(oGame,80,430,"Good job X you won!")
funcPlayer2Win oGame
showMsg(oGame,80,430,"Good job O you won!")
funcNoOneWin oGame
showMsg(oGame,150,430,"Oh no its a tie!")
funcShowMsg oGame,x,y,cMsg
(continues on next page)
59.3. TicTacToe 3D Game 771

Ring Documentation, Release 1.14
(continued from previous page)
oGame {
drawScene()
al_flip_display()
al_rest(0.3)
newdisplay
al_set_window_title(newdisplay,TITLE)
al_clear_to_color(al_map_rgb(255,255,255))
al_draw_bitmap(this.bitmap,200,50,1)
al_draw_text(this.font,
al_map_rgb(0,0,255), x,y,
ALLEGRO_ALIGN_LEFT,cMsg)
al_flip_display()
al_rest(2)
al_destroy_display(newdisplay)
al_set_target_backbuffer(display)
}
classGameCube
bitmap bitmap2 bitmap3
textureX textureO textureN
xrot.0
yrot.0
zrot.0
funcloadresources
bitmap"image/o.png")
textureO
bitmap2"image/x.png")
textureX
bitmap3"image/empty.png")
textureN
funcdestroyResources
al_destroy_bitmap(bitmap)
al_destroy_bitmap(bitmap2)
al_destroy_bitmap(bitmap3)
funccube(x,y,z,nTexture)
glLoadIdentity()
glTranslatef(x,y,z)
glRotatef(xrot,1.0,0.0,0.0)
glRotatef(yrot,0.0,1.0,0.0)
glRotatef(zrot,0.0,0.0,1.0)
setCubeTexture(nTexture)
drawCube()
funcsetCubeTexture cTexture
switchcTexture
on:x
glBindTexture(GL_TEXTURE_2D, textureX)
on:o
glBindTexture(GL_TEXTURE_2D, textureO)
on:n
glBindTexture(GL_TEXTURE_2D, textureN)
off
(continues on next page)
59.3. TicTacToe 3D Game 772

Ring Documentation, Release 1.14
(continued from previous page)
funcRotate
xrot=.3 *5
yrot=.2 *5
zrot=.4 *5
funcdrawcube
glBegin(GL_QUADS)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glEnd()
classGameBackground
nBackX
nBackY
nBackDiffx1
nBackDiffy1
nBackMotion
aBackMotionList
[1,1 # Down - Right
[ # Up
[1,1 # Down - Right
[ # Up
[1 # Down - Left
[ # Up
(continues on next page)
59.3. TicTacToe 3D Game 773

Ring Documentation, Release 1.14
(continued from previous page)
[1 # Down - Left
[ # Up
]
bitmap
funcUpdate
draw()
motion()
funcdraw
al_draw_bitmap(bitmap,nBackX,nBackY,1)
funcmotion
nBackX=
nBackY=
if(nBackY350) or(nBackY)
nBackMotion++
ifnBackMotion
nBackMotion
ok
nBackDiffx[nBackMotion][1]
nBackDiffy[nBackMotion][2]
ok
funcloadResources
bitmap"image/back.jpg")
funcdestroyResources
al_destroy_bitmap(bitmap)
classGameSound
sample sampleid
funcloadresources
samplesound/music1.wav"
sampleid
al_play_sample(sample,.0,.0,1.0,ALLEGRO_PLAYMODE_LOOP,sampleid)
funcdestroyResources
al_destroy_allegro_sample_id(sampleid)
al_destroy_sample(sample)
classGraphicsAppBase
display event_queue ev timeout
timer
redraw true
FPS
SCREEN_W
SCREEN_H
KEY_UP
KEY_DOWN
KEY_LEFT
(continues on next page)
59.3. TicTacToe 3D Game 774

Ring Documentation, Release 1.14
(continued from previous page)
KEY_RIGHT
Key false,false,false,false]
Mouse_X
Mouse_Y
TITLEGraphics Application"
PRINT_MOUSE_XY False
funcstart
SetUp()
loadResources()
eventsLoop()
destroy()
funcsetup
al_init()
al_init_font_addon()
al_init_ttf_addon()
al_init_image_addon()
al_install_audio()
al_init_acodec_addon()
al_reserve_samples(1)
al_set_new_display_flags(ALLEGRO_OPENGL)
display
al_set_window_title(display,TITLE)
al_clear_to_color(al_map_rgb(0,0,0))
event_queue
al_register_event_source(event_queue,
al_get_display_event_source(display))
ev
timeout
al_init_timeout(timeout,.06)
timer1.0
al_register_event_source(event_queue,
al_get_timer_event_source(timer))
al_start_timer(timer)
al_install_mouse()
al_register_event_source(event_queue,
al_get_mouse_event_source())
al_install_keyboard()
al_register_event_source(event_queue,
al_get_keyboard_event_source())
funceventsLoop
while
al_init_timeout(timeout,.06)
al_wait_for_event_until(event_queue, ev, timeout)
switchal_get_allegro_event_type(ev)
onALLEGRO_EVENT_DISPLAY_CLOSE
CloseEvent()
onALLEGRO_EVENT_TIMER
redraw true
onALLEGRO_EVENT_MOUSE_AXES
mouse_x
mouse_y
ifPRINT_MOUSE_XY
see"x =
see"y =
(continues on next page)
59.3. TicTacToe 3D Game 775

Ring Documentation, Release 1.14
(continued from previous page)
ok
onALLEGRO_EVENT_MOUSE_ENTER_DISPLAY
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_BUTTON_UP
MouseClickEvent()
onALLEGRO_EVENT_KEY_DOWN
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] true
onALLEGRO_KEY_DOWN
key[KEY_DOWN] true
onALLEGRO_KEY_LEFT
key[KEY_LEFT] true
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] true
off
onALLEGRO_EVENT_KEY_UP
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] false
onALLEGRO_KEY_DOWN
key[KEY_DOWN] false
onALLEGRO_KEY_LEFT
key[KEY_LEFT] false
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] false
onALLEGRO_KEY_ESCAPE
exit
off
off
ifredrawandal_is_event_queue_empty(event_queue)
redraw false
drawScene()
al_flip_display()
ok
callgc()
end
funcdestroy
destroyResources()
al_destroy_timer(timer)
al_destroy_allegro_event(ev)
al_destroy_allegro_timeout(timeout)
al_destroy_event_queue(event_queue)
al_destroy_display(display)
al_exit()
funcloadresources
funcdrawScene
funcdestroyResources
funcMouseClickEvent
exit # Exit from the Events Loop
(continues on next page)
59.3. TicTacToe 3D Game 776

Ring Documentation, Release 1.14
(continued from previous page)
funcCloseEvent
exit # Exit from the Events Loop
Screen Shot:
59.4
You will nd the samples in ring/samples/3D folder
The next screen shot for the Top-Down view - Many levels of cubes sample
59.4. More 3D Samples 777

Ring Documentation, Release 1.14
The next screen shot for the Camera SampleThe next screen shot for the Camera and background sample
Developer : Azzeddine Remmal
59.4. More 3D Samples 778

Ring Documentation, Release 1.14
59.4. More 3D Samples 779

CHAPTER
SIXTY
THE GOLD MAGIC 800 GAME
In this chapter we will learn about the Gold Magic 800 Game
The game is developed using Ring, RingAllegro and RingOpenGL
You will nd the game in ring/applications/goldmagic800 folder
60.1
Your friend discovered a unique and special box, created by the best wizard in the world 7000 years ago, when you
close this box and move it; you will nd a new gold under the box, it's an innite source of gold. The Box exists in
a special environment full of puzzles, no one can enter this environment because it's protected by the magic. Your
friend created a new robot using nanotechnology that can move the box using a remote control device. Your mission
is to solve all of these puzzles and get this box forever to be the richest people in the world.
60.2
The Gold Magic 800 is a puzzle game that will teach your unconscious mind to think like an entrepreneur.
The game is based on moving your box around to get gold score (=800) to open the First Door (Box Number 1) Then
directly put your box on the Door (this will open the next door), Then continue to put your box on all of the next doors
in the level, You need the score (800) only for the rst door, The next doors doesn't require this condition, but your
way of gold will be converted to a wall once you put the Box on any door, so select your path carefully.
60.3
1- Plan First
2- Move to your target directly then go to get the required resources
3- Look to the future when you evaluate the different solutions
4- Try to avoid mistakes, Also learn from them
5- Respect the Cost (800)
6- Focus and be careful
7- Be patient and Enjoy!
780

Ring Documentation, Release 1.14
60.4
We can select the level
The next screen shot for level (1)The Gold Magic 800 Level Editor
60.4. Screen Shots 781

Ring Documentation, Release 1.14
60.5
You will nd the Level Editor source code in this folder
https://github.com/ring-lang/ring/tree/master/applications/goldmagic800/editor
The user interface of the Level Editor is designed using the Ring Form Designer.
60.5. Source Code 782

Ring Documentation, Release 1.14
The next le contains the Level Editor Controller Class
https://github.com/ring-lang/ring/blob/master/applications/goldmagic800/editor/editorController.ring
You will nd the Game Engine source code in this folder
https://github.com/ring-lang/ring/tree/master/applications/goldmagic800
60.5. Source Code 783

CHAPTER
SIXTYONE
RINGTILENGINE EXTENSION
In this chapter we will learn about using the RingTilengine extension.
This extension provides complete support for Tilengine
The 2D retro graphics engine with raster effects
Tilengine URL:
Useful links (Original documentation for C programmers)
•
•
•
•
•
•
Useful tools
•
•
•
•
Support
•
61.1
Example (1):
load"tilengine.ring"
TLN_Init(400,,,,)
TLN_SetLoadPath("assets\sonic")
foreground"Sonic_md_fg1.tmx", NULL)
TLN_SetLayerTilemap(0, foreground)
TLN_CreateWindow(NULL,)
(continues on next page)
784

Ring Documentation, Release 1.14
(continued from previous page)
whileTLN_ProcessWindow()
TLN_DrawFrame(0)
end
TLN_DeleteTilemap(foreground)
TLN_Deinit()
Screen Shot:
61.2
Example (2):
load"tilengine.ring"
WIDTH
HEIGHT
frame
/*setup engine*/
TLN_Init(WIDTH, HEIGHT,,0,0)
/*loadlayer*/
tilemap"assets/sonic/Sonic_md_fg1.tmx", NULL)
/*setup the layer */
TLN_SetLayer(0, NULL, tilemap)
(continues on next page)
61.2. More Samples 785

Ring Documentation, Release 1.14
(continued from previous page)
TLN_SetBGColor(32,32,128)
/*mainloop*/
TLN_CreateWindow(NULL,)
whileTLN_ProcessWindow ()
/*scroll the layer, one pixel per frame */
TLN_SetLayerPosition (0, frame,)
/*rendertothe window*/
TLN_DrawFrame (0)
frame++
end
/*release resources */
TLN_DeleteTilemap(tilemap)
TLN_Deinit()
Screen Shot:
Example (3):
load"tilengine.ring"
/*engine init*/
TLN_Init(640,480,0,0,1)
/*loadresources*/
TLN_SetLoadPath("assets/color")
(continues on next page)
61.2. More Samples 786

Ring Documentation, Release 1.14
(continued from previous page)
background"beach.png")
palette
sp"beach.sqx")
sequencebeach")
/*setup*/
TLN_SetBGBitmap(background)
TLN_SetPaletteAnimation(0, palette, sequence, true)
/*mainloop*/
TLN_CreateWindow(NULL,)
TLN_DisableCRTEffect()
while(TLN_ProcessWindow())
TLN_DrawFrame(0)
end
TLN_DeleteBitmap(background)
TLN_DeleteSequencePack(sp)
TLN_Deinit()
Screen Shot:
Example (4):
load"tilengine.ring"
WIDTH
HEIGHT=
LAYER_FOREGROUND
LAYER_BACKGROUND
MAX_LAYER
(continues on next page)
61.2. More Samples 787

Ring Documentation, Release 1.14
(continued from previous page)
player_x16
player_y
/*basic setup*/
TLN_Init(WIDTH, HEIGHT, MAX_LAYER,1,0)
TLN_SetBGColor(0,,)
/*loadresources*/
TLN_SetLoadPath("assets/smw")
foreground"smw_foreground.tmx", NULL)
background"smw_background.tmx", NULL)
TLN_SetLayerTilemap(LAYER_FOREGROUND, foreground)
TLN_SetLayerTilemap(LAYER_BACKGROUND, background)
TLN_SetLayerPosition(LAYER_FOREGROUND,,48)
TLN_SetLayerPosition(LAYER_BACKGROUND,,80)
/*setup sprite*/
spriteset"smw_sprite")
TLN_SetSpriteSet(0, spriteset)
TLN_SetSpritePicture(0,)
TLN_SetSpritePosition(0, player_x, player_y)
/*setup animations */
seq_walking NULL, spriteset,walking",)
TLN_SetSpriteAnimation(0, seq_walking,)
/*mainloop*/
TLN_CreateWindow(NULL,)
whileTLN_ProcessWindow()
player_x=
ifplayer_x=
player_x16
ok
TLN_SetSpritePosition(0, player_x, player_y)
TLN_DrawFrame(0)
end
/*deinit*/
TLN_DeleteTilemap(foreground)
TLN_DeleteTilemap(background)
TLN_Deinit()
Screen Shot:
61.2. More Samples 788

Ring Documentation, Release 1.14
Example (5):
load"tilengine.ring"
HRES
VRES
LAYER_PROPS_FRONT
LAYER_FOREGROUND
LAYER_PROPS
LAYER_MIDDLEGROUND
LAYER_BACKGROUND
NUM_LAYERS
xworld
oldx1
TLN_Init(HRES, VRES, NUM_LAYERS,,)
/*loadassets*/
TLN_SetLogLevel(TLN_LOG_ERRORS)
TLN_SetLoadPath("assets/forest")
foreground"map.tmx",Main Layer")
middleground"middleground.png")
background"background.png")
atlas"atlas.png")
props_list"map.tmx", NULL)
/*setup layers*/
TLN_SetLayer(LAYER_FOREGROUND, NULL, foreground)
TLN_SetLayerBitmap(LAYER_MIDDLEGROUND, middleground)
(continues on next page)
61.2. More Samples 789

Ring Documentation, Release 1.14
(continued from previous page)
TLN_SetLayerBitmap(LAYER_BACKGROUND, background)
width
height
/*objects layer: add back objects (behind sprites) */
TLN_SetLayerObjects(LAYER_PROPS, props_list, NULL)
/*sync props layer positions tomain layer*/
TLN_SetLayerParent(LAYER_PROPS_FRONT, LAYER_FOREGROUND)
TLN_SetLayerParent(LAYER_PROPS, LAYER_FOREGROUND)
/*create sprite sequences */
idle NULL, atlas,player-idle/player-idle-",)
skip NULL, atlas,player-skip/player-skip-",)
/*setup main player sprite */
xplayer
yplayer
TLN_ConfigSprite(0, atlas,)
TLN_SetSpriteAnimation(0, idle,)
/*create window loop*/
TLN_CreateWindow(NULL,)
TLN_DisableCRTEffect()
whileTLN_ProcessWindow()
TLN_DrawFrame(0)
/*move/left main layer */
if(TLN_GetInput(INPUT_LEFT)&)
xworld=
elseif(TLN_GetInput(INPUT_RIGHT)&
xworld=
ok
/*updateonchange*/
ifxworld=
TLN_SetLayerPosition(LAYER_FOREGROUND, xworld,)
TLN_SetLayerPosition(LAYER_MIDDLEGROUND, xworld,)
TLN_SetLayerPosition(LAYER_BACKGROUND, xworld,)
TLN_SetSpritePosition(0, xplayer
oldx
ok
end
/*release resources */
TLN_DeleteTilemap(foreground)
TLN_DeleteBitmap(middleground)
TLN_CloseResourcePack()
TLN_DeleteSpriteset(atlas)
TLN_DeleteObjectList(props_list)
TLN_DeleteWindow()
TLN_Deinit()
Screen Shot:
61.2. More Samples 790

Ring Documentation, Release 1.14
Example (6):
load"tilengine.ring"
load"sin.ring"
WIDTH
HEIGHT
FIXED_BITS
LAYER_FOREGROUND
LAYER_BACKGROUND
MAX_LAYER
MAP_HORIZON
MAP_TRACK
MAX_MAP
road NULL
x NULL
y NULL
angle NULL
funcmain
/*setup engine*/
TLN_Init (WIDTH,HEIGHT, MAX_LAYER,,)
TLN_SetRasterCallback ("raster_callback()")
TLN_SetBGColor (0,0,0)
/*loadresources*/
TLN_SetLoadPath ("assets/smk")
road"track1.tmx", NULL)
horizon"track1_bg.tmx", NULL)
(continues on next page)
61.2. More Samples 791

Ring Documentation, Release 1.14
(continued from previous page)
/*startup display */
TLN_CreateWindow (NULL,)
x-136)
y336)
s
a0.2)
angle
BuildSinTable ()
/*mainloop*/
while(TLN_ProcessWindow ())
TLN_SetLayerTilemap (LAYER_FOREGROUND, horizon)
TLN_SetLayerTilemap (LAYER_BACKGROUND, horizon)
TLN_SetLayerPosition (LAYER_FOREGROUND, lerp(angle *2,,360,
˓→0,256),)
TLN_SetLayerPosition (LAYER_BACKGROUND, lerp(angle,,360,,
˓→256),)
TLN_ResetLayerMode (LAYER_BACKGROUND)
/*input*/
if(TLN_GetInput (INPUT_LEFT))
angle-=2
elseif(TLN_GetInput (INPUT_RIGHT))
angle+=2
ok
if(TLN_GetInput (INPUT_UP))
s=
if(s2))
s2)
ok
elseif(s=
s=
ok
if(TLN_GetInput (INPUT_DOWN))
s=
if(sint2fix(2))
sint2fix(2)
ok
elseif(s=a)
s=
ok
if(s=)
angle%360
if(angle)
angle=
ok
x=
y=
ok
(continues on next page)
61.2. More Samples 792

Ring Documentation, Release 1.14
(continued from previous page)
/*rendertowindow*/
TLN_DrawFrame (0)
end
/*deinit*/
TLN_DeleteTilemap (road)
TLN_DeleteTilemap (horizon)
TLN_DeleteWindow ()
TLN_Deinit ()
/*raster callback (virtual HBLANK) */
funcraster_callback
line
if(line)
TLN_SetLayerTilemap (LAYER_BACKGROUND, road)
TLN_SetLayerPosition (LAYER_BACKGROUND, fix2int(x), fix2int(y))
TLN_DisableLayer (LAYER_FOREGROUND)
elseif(line=)
s00.2)
s15.0)
s,HEIGHT, s0,s1)
scale
TLN_SetLayerTransform (LAYER_BACKGROUND, angle, WIDTH/2, HEIGHT,
˓→scale, scale)
ok
funclerp x,x0,x1,fx0,fx1
return(fx0) *((x)/((x1)
funcfloat2fix f returnf*(1<
funcint2fix i returni<
funcfix2int f returnf>
funcfix2float f returnf/(1<
Screen Shot:
61.2. More Samples 793

Ring Documentation, Release 1.14
Example (7):
load"tilengine.ring"
load"sin.ring"
WIDTH
HEIGHT
COLUMNS/8
/*layers*/
LAYER_FOREGROUND
LAYER_BACKGROUND
MAX_LAYER
frame
column list(COLUMNS)
/*entry point*/
funcmain
/*setup engine*/
TLN_Init (WIDTH,HEIGHT, MAX_LAYER,,)
TLN_SetRasterCallback ("raster_callback()")
TLN_SetBGColor (0,0,0)
/*loadresources*/
TLN_SetLoadPath ("assets/tf3")
foreground"tf3_bg2.tmx", NULL)
background"tf3_bg3.tmx", NULL)
(continues on next page)
61.2. More Samples 794

Ring Documentation, Release 1.14
(continued from previous page)
TLN_SetLayerTilemap (LAYER_FOREGROUND, foreground)
TLN_SetLayerTilemap (LAYER_BACKGROUND, background)
BuildSinTable ()
# Convert the Column List to Array of Integers
intArray" foritemincolumn intArray=
˓→next
TLN_SetLayerColumnOffset (LAYER_BACKGROUND, :intArray)
/*mainloop*/
TLN_CreateWindow (NULL,)
while(TLN_ProcessWindow ())
/*scroll*/
TLN_SetLayerPosition (LAYER_FOREGROUND, frame *3,)
TLN_SetLayerPosition (LAYER_BACKGROUND, frame,)
/*update column offset table */
forc=1toCOLUMNS
column[c] *5 *20,)
next
/*rendertowindow*/
TLN_DrawFrame (frame)
frame++
end
/*deinit*/
TLN_DeleteTilemap (foreground)
TLN_DeleteTilemap (background)
TLN_Deinit ()
funcraster_callback
/*raster callback (virtual HBLANK) */
line
TLN_SetLayerPosition (LAYER_FOREGROUND, frame *2, CalcSin((frame+line)<
˓→<1,))
TLN_SetLayerPosition (LAYER_BACKGROUND, frame
˓→<<1,),)
funclerp x,x0,x1,fx0,fx1
/*linear interploation */
return(fx0) *((x)/((x1)
Screen Shot:
61.2. More Samples 795

Ring Documentation, Release 1.14
Example (8):
load"tilengine.ring"
WIDTH
HEIGHT
sky
[0x1D,,],
[0x7F,,],
[0x0B,,],
[0xEB,,]
]
sky_hi_r
sky_hi_g
sky_hi_b
sky_lo_r
sky_lo_g
sky_lo_b
frame
xpos
speed
max_xpos
/*layers*/
LAYER_FOREGROUND
LAYER_BACKGROUND
MAX_LAYER
(continues on next page)
61.2. More Samples 796

Ring Documentation, Release 1.14
(continued from previous page)
/*entry point*/
funcmain
/*setup engine*/
TLN_Init (WIDTH, HEIGHT,,1,0)
TLN_SetBGColor (0,128,238)
TLN_SetRasterCallback ("raster_callback()")
/*loadresources*/
TLN_SetLoadPath ("assets/sotb")
foreground"SOTB_fg.tmx", NULL)
background"SOTB_bg.tmx", NULL)
TLN_SetLayerTilemap (LAYER_FOREGROUND, foreground)
TLN_SetLayerTilemap (LAYER_BACKGROUND, background)
spriteset"SOTB")
walk NULL, spriteset,walk",)
TLN_SetSpriteSet (0, spriteset)
TLN_SetSpritePosition (0,,160)
TLN_SetSpriteAnimation (0, walk,)
xpos
sky_hi_r[1][1]
sky_hi_g[1][2]
sky_hi_b[1][3]
sky_lo_r[2][1]
sky_lo_g[2][2]
sky_lo_b[2][3]
/*mainloop*/
TLN_CreateWindow (NULL,)
TLN_DisableCRTEffect()
while(TLN_ProcessWindow ())
{
if(xpos
{
xpos=
if(xpos=
{
TLN_DisableSpriteAnimation (0)
TLN_SetSpritePicture (0,)
}
}
/*sky gradient*/
if(frame>=300&<=900)
{
/*interpolate upper color */
sky_hi_r,900, sky[1][1], sky[3][1])
sky_hi_g,900, sky[1][2], sky[3][2])
sky_hi_b,900, sky[1][3], sky[3][3])
/*interpolate lower color */
(continues on next page)
61.2. More Samples 797

Ring Documentation, Release 1.14
(continued from previous page)
sky_lo_r,900, sky[2][1], sky[4][1])
sky_lo_g,900, sky[2][2], sky[4][2])
sky_lo_b,900, sky[2][3], sky[4][3])
}
TLN_SetLayerPosition (LAYER_FOREGROUND, xpos,)
/*rendertothe window*/
TLN_DrawFrame (frame)
frame++
}
/*release resources */
TLN_DeleteSequence(walk)
TLN_DeleteTilemap (foreground)
TLN_DeleteTilemap (background)
TLN_Deinit ()
funcraster_callback
line
pos
/*sky color*/
if(line)
{
//color newRGB
/*interpolate between upper andlower color*/
r,191, sky_hi_r, sky_lo_r)
g,191, sky_hi_g, sky_lo_g)
b,191, sky_hi_b, sky_lo_b)
TLN_SetBGColor (r, g ,b)
}
/*background layer */
pos1
if(line||||)
pos,96, xpos *0.7 *0.2
elseif(line)
pos/2
elseif(line|||)
pos208,232,xpos *1,xpos*2)
ok
if(pos=1)
TLN_SetLayerPosition (LAYER_BACKGROUND, pos,)
ok
/*foreground layer */
pos1
if(line)
pos
elseif(line)
pos *3
ok
if(pos=1)
TLN_SetLayerPosition (LAYER_FOREGROUND, pos,)
(continues on next page)
61.2. More Samples 798

Ring Documentation, Release 1.14
(continued from previous page)
ok
funclerp x,x0,x1,fx0,fx1
/*linear interploation */
return(fx0-fx0) *(x-x0)/(x1-x0))
Screen Shot:
Example (9):
load "tilengine.ring"
WIDTH = 400
HEIGHT = 240
MIN_SCALE = 50
MAX_SCALE = 200
/*RGB sky colors */
sky = [
[0x19, 0x54, 0x75],
[0x2C, 0xB0, 0xDC]
]
/*layers*/
LAYER_FOREGROUND = 0
LAYER_BACKGROUND = 1
MAX_LAYER = 2
xpos=0 ypos=0 scale=0
(continues on next page)
61.2. More Samples 799

Ring Documentation, Release 1.14
(continued from previous page)
/*entry point*/
func main
/*setup engine*/
TLN_Init (WIDTH, HEIGHT, MAX_LAYER,0,0)
TLN_SetBGColor (34,136,170)
TLN_SetRasterCallback ("raster_callback()")
/*load resources*/
TLN_SetLoadPath ("assets/fox")
foreground = TLN_LoadTilemap ("psycho.tmx", NULL)
background = TLN_LoadTilemap ("rolo.tmx", NULL)
TLN_SetLayerTilemap (LAYER_FOREGROUND, foreground)
TLN_SetLayerTilemap (LAYER_BACKGROUND, background)
/*initial values*/
xpos = 0
ypos = 192
scale = 100
/*main loop*/
TLN_CreateWindow (NULL, 0)
TLN_DisableCRTEffect()
while TLN_ProcessWindow ()
/*user input*/
if TLN_GetInput (INPUT_LEFT)
xpos-- ok
if TLN_GetInput (INPUT_RIGHT)
xpos++ ok
if TLN_GetInput (INPUT_UP) && ypos > 0
ypos-- ok
if TLN_GetInput (INPUT_DOWN)
ypos++ ok
if TLN_GetInput (INPUT_A) && scale < MAX_SCALE
scale += 1 ok
if TLN_GetInput (INPUT_B) && scale > MIN_SCALE
scale -= 1 ok
/*calculate scale factor from fixed point base */
fgscale = scale/100.0f
bgscale = lerp(scale, MIN_SCALE,MAX_SCALE, 0.75,1.5)
/*scale dependant lower clipping */
maxy = 640 - (240*100/scale)
if ypos > maxy
ypos = maxy
ok
/*update position */
bgypos = lerp(scale,MIN_SCALE,MAX_SCALE, 0,80)
TLN_SetLayerPosition (LAYER_FOREGROUND, xpos *2, ypos)
TLN_SetLayerPosition (LAYER_BACKGROUND, xpos, bgypos)
TLN_SetLayerScaling (LAYER_FOREGROUND, fgscale, fgscale)
TLN_SetLayerScaling (LAYER_BACKGROUND, bgscale, bgscale)
/*render to the window */
TLN_DrawFrame (0)
(continues on next page)
61.2. More Samples 800

Ring Documentation, Release 1.14
(continued from previous page)
end
/*release resources */
TLN_DeleteTilemap (foreground)
TLN_DeleteTilemap (background)
TLN_Deinit ()
/*sky color gradient with raster effect */
func raster_callback
line = TLN_GetScanLine()
if line <= 152
r = lerp (line, 0,152, sky[1][1], sky[2][1])
g = lerp (line, 0,152, sky[1][2], sky[2][2])
b = lerp (line, 0,152, sky[1][3], sky[2][3])
TLN_SetBGColor (r, g, b)
ok
/*linear interploation */
func lerp x,x0,x1,fx0,fx1
return (fx0) + ((fx1) - (fx0)) *((x) - (x0))/((x1) - (x0))
Screen Shot:
Example (10):
load "tilengine.ring"
WIDTH = 400
HEIGHT = 240
(continues on next page)
61.2. More Samples 801

Ring Documentation, Release 1.14
(continued from previous page)
sky = [
[0x1B, 0x00, 0x8B],
[0x00, 0x74, 0xD7],
[0x24, 0x92, 0xDB],
[0x1F, 0x7F, 0xBE]
]
/*layers*/
LAYER_FOREGROUND = 0
LAYER_BACKGROUND = 1
MAX_LAYER = 2
pos_foreground = 0
pos_background = list(6)
inc_background = list(6)
speed = 0
ypos = 0
color = list(3)
/*entry point*/
func main
/*setup engine*/
TLN_Init (WIDTH,HEIGHT, MAX_LAYER, 0, 1)
TLN_SetRasterCallback ("raster_callback()")
TLN_SetBGColor (0,128,238)
/*load resources*/
TLN_SetLoadPath ("assets/sonic")
foreground = TLN_LoadTilemap ("Sonic_md_fg1.tmx", NULL)
background = TLN_LoadTilemap ("Sonic_md_bg1.tmx", NULL)
TLN_SetLayerTilemap (LAYER_FOREGROUND, foreground)
TLN_SetLayerTilemap (LAYER_BACKGROUND, background)
sp = TLN_LoadSequencePack ("Sonic_md_seq.sqx")
sequence = TLN_FindSequence (sp, "seq_water")
/*assign color sequence to various entries in palette */
palette = TLN_GetLayerPalette (LAYER_BACKGROUND)
TLN_SetPaletteAnimation (TLN_GetAvailableAnimation(), palette, sequence, true)
/*compute increments for variable background scrolling speeds */
inc_background[1] = 0.562f
inc_background[2] = 0.437f
inc_background[3] = 0.375f
inc_background[4] = 0.625f
inc_background[5] = 1.0f
inc_background[6] = 2.0f
/*startup display */
TLN_CreateWindow (NULL, 0)
/*main loop*/
while TLN_ProcessWindow ()
if TLN_GetInput (INPUT_RIGHT)
speed += 0.02
if speed > 1.0
(continues on next page)
61.2. More Samples 802

Ring Documentation, Release 1.14
(continued from previous page)
speed = 1.0f
ok
elseif speed > 0.0
speed -= 0.02
if speed < 0.0
speed = 0.0f
ok
ok
if TLN_GetInput (INPUT_LEFT)
speed -= 0.02
if speed < -1
speed = -1
ok
elseif speed < 0
speed += 0.02
if speed > 0
speed = 0
ok
ok
/*scroll*/
pos_foreground += 3*speed
TLN_SetLayerPosition (LAYER_FOREGROUND, pos_foreground, ypos)
for c=1 to 6
pos_background[c] += (inc_background[c] *speed)
next
/*render to window */
TLN_DrawFrame (0)
end
/*deinit*/
TLN_DeleteTilemap (foreground)
TLN_DeleteTilemap (background)
TLN_DeleteSequencePack (sp)
TLN_Deinit ()
/*raster callback (virtual HBLANK) */
func raster_callback
line = TLN_GetScanLine()
pos =- 1
if line=0
pos = pos_background[1]
elseif line=32
pos = pos_background[2]
elseif line=48
pos = pos_background[3]
elseif line=64
pos = pos_background[4]
elseif line=112
pos = pos_background[5]
elseif line >= 152
pos = lerp (line, 152,224, pos_background[5], pos_background[6])
ok
(continues on next page)
61.2. More Samples 803

Ring Documentation, Release 1.14
(continued from previous page)
if pos != -1
TLN_SetLayerPosition (LAYER_BACKGROUND, pos, 0)
ok
/*background color gradients */
if line < 112
InterpolateColor (line, 0,112, sky[1], sky[2], color)
TLN_SetBGColor (color[1], color[2], color[3])
elseif line >= 144
InterpolateColor (line, 144,HEIGHT, sky[3], sky[4], color)
TLN_SetBGColor (color[1], color[2], color[3])
ok
func InterpolateColor v,v1,v2,color1,color2,result
result[1] = lerp (v, v1,v2, color1[1], color2[1])
result[2] = lerp (v, v1,v2, color1[2], color2[2])
result[3] = lerp (v, v1,v2, color1[3], color2[3])
/*linear interploation */
func lerp x,x0,x1,fx0,fx1
return (fx0) + ((fx1) - (fx0)) *((x) - (x0))/((x1) - (x0))
Screen Shot:
61.2. More Samples 804

Ring Documentation, Release 1.14
61.3
Example (11):
load"tilengine.ring"
load"libsdl.ring"
width
height
funcmain
# Start Tilengine
TLN_Init(width, height,,,)
# Start LibSDL
SDL_Init(SDL_INIT_EVERYTHING)
win"Using LibSDL and Tilengine",,, width,
˓→height, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL)
ren1, SDL_RENDERER_ACCELERATED
˓→RENDERER_PRESENTVSYNC )
# Create the Surface in LibSDL that will be used by Tilengine for Drawing
surface0, width, height,,,0,0,0)
# Get the Surface Pixels pointer from the Surface Structure
pixels
# Pass the Pixels pointer to Tilengine
TLN_SetRenderTarget(pixels, width *4)
# Using Tilengine
TLN_SetLoadPath("assets\sonic")
foreground"Sonic_md_fg1.tmx", NULL)
TLN_SetLayerTilemap(0, foreground)
# Using LibSDL Events Loop
oEvent
while
# Using Tilengine to Update the Frame
TLN_UpdateFrame(0)
# Draw Tilengine results using LibSDL
# ( Surface --> Texture --> Render)
tex
SDL_RenderCopy2(ren,tex)
SDL_DestroyTexture(tex)
# Draw Rectangle using LibSDL
rect
SDL_Set_SDL_Rect_x(rect,10)
SDL_Set_SDL_Rect_y(rect,10)
SDL_Set_SDL_Rect_w(rect,100)
SDL_Set_SDL_Rect_h(rect,100)
SDL_SetRenderDrawColor(ren,255,255,255,255)
SDL_RenderDrawRect(ren,rect)
SDL_Destroy_SDL_Rect(rect)
(continues on next page)
61.3. Using LibSDL and Tilengine 805

Ring Documentation, Release 1.14
(continued from previous page)
# Display Results using LibSDL
SDL_RenderPresent(ren)
# Check Events
SDL_PollEvent(oEvent)
switchSDL_Get_SDL_Event_Type(oEvent)
onSDL_Get_SDL_Quit()
exit
onSDL_Get_SDL_Keydown()
Key
˓→SDL_Event_key_Keysym_Sym(oEvent)
ifkey
˓→exit
off
end
# End of Tilengine Usage
TLN_Deinit()
# End of LibSDL Usage
SDL_DestroyWindow(win)
SDL_Quit()
Screen Shot:
61.3. Using LibSDL and Tilengine 806

Ring Documentation, Release 1.14
Example (12):
load"tilengine.ring"
load"libsdl.ring"
factor
width *factor
height *factor
funcmain
# Start Tilengine
TLN_Init(width, height,,,)
# Start LibSDL
SDL_Init(SDL_INIT_EVERYTHING)
win"Using LibSDL and Tilengine",,, width,
˓→height, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL)
ren1, SDL_RENDERER_ACCELERATED
˓→RENDERER_PRESENTVSYNC )
# Create the Surface in LibSDL that will be used by Tilengine for Drawing
surface0, width, height,,,0,0,0)
# Get the Surface Pixels pointer from the Surface Structure
(continues on next page)
61.3. Using LibSDL and Tilengine 807

Ring Documentation, Release 1.14
(continued from previous page)
pixels
# Pass the Pixels pointer to Tilengine
TLN_SetRenderTarget(pixels, width *4)
# Using Tilengine
TLN_SetLoadPath("assets\sonic")
foreground"Sonic_md_fg1.tmx", NULL)
TLN_SetLayerTilemap(0, foreground)
# Using LibSDL Events Loop
oEvent
while
# Using Tilengine to Update the Frame
TLN_UpdateFrame(0)
# Draw Tilengine results using LibSDL
# ( Surface --> Texture --> Render)
tex
rectSource
SDL_Set_SDL_Rect_x(rectSource,0)
SDL_Set_SDL_Rect_y(rectSource,0)
SDL_Set_SDL_Rect_w(rectSource,400)
SDL_Set_SDL_Rect_h(rectSource,220)
rectDest
SDL_Set_SDL_Rect_x(rectDest,0)
SDL_Set_SDL_Rect_y(rectDest,0)
SDL_Set_SDL_Rect_w(rectDest,width)
SDL_Set_SDL_Rect_h(rectDest,height)
SDL_RenderCopy(ren,tex,rectSource,rectDest)
SDL_Destroy_SDL_Rect(rectSource)
SDL_Destroy_SDL_Rect(rectDest)
SDL_DestroyTexture(tex)
# Draw Rectangle using LibSDL
rect
SDL_Set_SDL_Rect_x(rect,40)
SDL_Set_SDL_Rect_y(rect,5)
SDL_Set_SDL_Rect_w(rect,230)
SDL_Set_SDL_Rect_h(rect,200)
SDL_SetRenderDrawColor(ren,255,255,255,255)
SDL_RenderDrawRect(ren,rect)
SDL_Destroy_SDL_Rect(rect)
# Display Results using LibSDL
SDL_RenderPresent(ren)
# Check Events
SDL_PollEvent(oEvent)
switchSDL_Get_SDL_Event_Type(oEvent)
onSDL_Get_SDL_Quit()
exit
(continues on next page)
61.3. Using LibSDL and Tilengine 808

Ring Documentation, Release 1.14
(continued from previous page)
onSDL_Get_SDL_Keydown()
Key
˓→SDL_Event_key_Keysym_Sym(oEvent)
ifkey
˓→exit
off
end
# End of Tilengine Usage
TLN_Deinit()
# End of LibSDL Usage
SDL_DestroyWindow(win)
SDL_Quit()
Screen Shot:
61.4
Constants:
•
•
•
•
•
•
61.4. Reference 809

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
61.4. Reference 810

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
61.4. Reference 811

Ring Documentation, Release 1.14
•
•
•
•
•
•
Functions:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *TLN_GetErrorString(TLN_Error error)
•
•
61.4. Reference 812

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
uint8_t v1, uint8_t v2, uint8_t v3, bool blur, uint8_t glow_factor)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
sp, TLN_TileAttributes* attributes)
•
•
•
•
•
•
•
•
61.4. Reference 813

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
int dstcol)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
61.4. Reference 814

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
• *afne)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
61.4. Reference 815

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
frames)
•
•
name, int delay)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
61.4. Reference 816

Ring Documentation, Release 1.14
•
• *cCode)
• *cCode)
• *cCode)
•
• *TLN_GetSDLEvent(void)
61.4. Reference 817

CHAPTER
SIXTYTWO
PERFORMANCE TIPS
In this chapter we will learn more about the Ring performance.
62.1
Ring is designed to be a simple, small and exible language in the rst place, but also it is fast enough for many
applications.
Ring can do each of the next tasks in around 1 second using normal computers in the market during the last 5 years
(1)
(2)
(3)
(The worst case)
(4)
(5)
(6)
(7)
Also when we need more speed we can use C/C++ extensions!
Example:
?Create list contains 100,000 items"
aList:100000
?Do 1000 search operation - Find the last item (Worst Case!)"
c
fort to1000
find(alist,100000)
next
?Time:"
Output:
Create list contains 100,000 items
Do 1000 search operation - Find the last item (Worst Case!)
Time: 0.87 seconds
818

Ring Documentation, Release 1.14
Example:
load"guilib.ring"
funcmain
newqApp {
win newqWidget() {
move(100,100) resize(500,500)
setWindowTitle("Many Tree Items - Testing Performance")
tree=newqTreeWidget(win) {
blocksignals(True) setUpdatesEnabled(False)
root newqTreeWidgetItem()
root.setText(0,"The Root Node")
t1
fort to5000
oItem newqTreeWidgetItem()
oItem.settext(0,"Item
root.addchild(oItem)
next
cTime-t1)/clockspersecond()
setHeaderLabel("Creating 5000 nodes in
˓→")
addTopLevelItem(root)
expanditem(root)
blocksignals(False) setUpdatesEnabled( True)
}
oLayout newqVBoxLayout() {
addWidget(tree)
}
setLayout(oLayout)
show()
}
exec()
}
Output:
62.1. Introduction 819

Ring Documentation, Release 1.14
62.2
Example:
?Create the list using the Range operator"
t1
aList:1000000
?Time :-t1)/clockspersecond())"
?Create the list using the For loop"
t1
aList]
forx to1000000
aList
next
?Time :-t1)/clockspersecond())"
?Create the list using the list() function and the For loop"
t1
aList list(1000000)
forx to1000000
aList[x]
next
?Time :-t1)/clockspersecond())"
Output:
62.2. Creating Lists 820

Ring Documentation, Release 1.14
Create the list using the Range operator
Time : 0.48 seconds
Create the list using the For loop
Time : 0.79 seconds
Create the list using the list() function and the For loop
Time : 1.56 seconds
Note:Creating lists using the Range operator is faster than using the For loop or the list() function
62.3
Example:
?Using *operator"
t1
forx to1000000
out *2
next
?Time :-t1)/clockspersecond())"
?Using *= operator"
t1
forx to1000000
out
out*=
next
?Time :-t1)/clockspersecond())"
Output:
Using*operator
Time : 1.34 seconds
Using*= operator
Time : 0.47 seconds
Note:Using the*= operator is faster that using the * operator
62.4
Example:
aList:1000000
?Using len() in the For loop"
t1
forx tolen(aList)
next
?Time :-t1)/clockspersecond())"
(continues on next page)
62.3. Arithmetic Operations 821

Ring Documentation, Release 1.14
(continued from previous page)
?Using len() before the For loop"
t1
nMax
forx tonMax
next
?Time :-t1)/clockspersecond())"
Output:
Using len() in the For loop
Time : 5.50 seconds
Using len() before the For loop
Time : 0.24 seconds
Note:Using len() before the For loop is faster than using len() in the For loop.
62.5
Example:
?calling 100000 functions"
t1
forx to100000
test()
next
?Time :-t1)/clockspersecond())"
o1 newtest
?calling 100000 methods using the dot operator"
t1
forx to100000
o1.test()
next
?Time :-t1)/clockspersecond())"
?calling 100000 methods using braces
t1
forx to100000
o1 { test() }
next
?Time :-t1)/clockspersecond())"
functest
classtest
functest
Output:
62.5. Calling Functions and Methods 822

Ring Documentation, Release 1.14
calling 100000 functions
Time : 0.28 seconds
calling 100000 methods using the dot operator
Time : 0.36 seconds
calling 100000 methods using braces
Time : 1.19 seconds
Note:Calling functions is faster than calling methods but the difference is very small.
Note:Using the dot operator to call methods is faster than using braces.
62.5. Calling Functions and Methods 823

CHAPTER
SIXTYTHREE
COMMAND LINE OPTIONS
The ring language takes source code le (.ring) or the object le (.ringo) as input to execute, also the language provide
other options like
Option Description
-tokens Print a list of tokens in the source code le
-rules Print grammar rules applied on the tokens
-ic Print the intermediate byte code (before execution)
-icnal Print the nal byte code (after execution)
-cgi Print http response header before error messages
-norun Don't run the program after compiling
-ins Print instruction operation code before execution
-performancePrint clock before and after program execution
-go Generate Object File
-geo Generate embedded object le (C source code)
-w Display Warnings
63.1
Example:
FuncMain
See"Hello World"
forx to10
seex
next
test()
functest
see"welcome"
o1 newpoint { x=10=20=30
seeo1
classpoint x y z
Command:
ring test.ringtokensnorun
Output:
824

Ring Documentation, Release 1.14
===================================================
Tokens
===================================================
Keyword :FUNC
Identifier : main
EndLine
Keyword :SEE
Literal : Hello World
Operator :
Identifier : nl
EndLine
Keyword :FOR
Identifier : x
Operator :
Number :
Keyword :TO
Number :
EndLine
Keyword :SEE
Identifier : x
Operator :
Identifier : nl
EndLine
Keyword :NEXT
EndLine
Identifier : test
Operator : (
Operator : )
EndLine
Keyword :FUNC
Identifier : test
EndLine
Keyword :SEE
Literal : welcome
Operator :
Identifier : nl
EndLine
Identifier : o1
Operator :
Keyword :NEW
Identifier : point
Operator : {
Identifier : x
Operator :
Number :
Identifier : y
Operator :
Number :
Identifier : z
Operator :
Number :
Operator : }
EndLine
Keyword :SEE
Identifier : o1
EndLine
(continues on next page)
63.1. Printing Tokens 825

Ring Documentation, Release 1.14
(continued from previous page)
Keyword :CLASS
Identifier : point
Identifier : x
Identifier : y
Identifier : z
EndLine
===================================================
63.2
Command:
ring test.ringrulesnorun
Output:
===================================================
Grammar Rules Used by The Parser
===================================================
Rule : Program->
Line
Rule : Statement->FuncParaList]
Line
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->See
Line
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
(continues on next page)
63.2. Printing Rules 826

Ring Documentation, Release 1.14
(continued from previous page)
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->For= toExprstep]
Line
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->See
Line
Rule :Next-->Next
Line
Rule : Mixer>(Expr {,)
Line
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Rule : Statement->FuncParaList]
Line
(continues on next page)
63.2. Printing Rules 827

Ring Documentation, Release 1.14
(continued from previous page)
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->See
Line
Rule : Factor-> NewIdentifier {.
Rule : Mixer->{
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Assignment>=
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Assignment>=
(continues on next page)
63.2. Printing Rules 828

Ring Documentation, Release 1.14
(continued from previous page)
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Assignment>=
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Rule : BraceEnd->}
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Assignment>=
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
(continues on next page)
63.2. Printing Rules 829

Ring Documentation, Release 1.14
(continued from previous page)
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Line
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->See
Line
Rule : Statement->Class
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
Rule : Factor->]
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->
(continues on next page)
63.2. Printing Rules 830

Ring Documentation, Release 1.14
(continued from previous page)
===================================================
63.3
Command:
ring test.ringicnorun
Output:
===================================================
Byte Code - Before Execution by the VM
===================================================
PC OPCode Data
1 ReturnNull
2 Func main
3 NewLine 2
4 FuncExE
5 PushC Hello World
6 LoadA nl 0
7 PushV
8 SUM 0
9 Print
10 NewLine 3
11 ExitMark 29 28
12 LoadAFirst x
13 PushN 1.000000
14 BeforeEqual 0
15 Assignment
16 PushN 1.000000
17 StepNumber
18 JumpVarLENum x 10.000000 29
19 NewLine 4
20 FuncExE
21 LoadA x 0
22 PushV
23 LoadA nl 0
24 PushV
25 SUM 0
26 Print
27 NewLine 5
28 IncJump x 18
29 POPExitMark
30 POPStep
31 NewLine 6
32 LoadFunc test
33 Call 0
34 NoOperation
35 NewLine 8
36 PushV
37 FreeStack
38 ReturnNull
(continues on next page)
63.3. Printing Intermediate Code 831

Ring Documentation, Release 1.14
(continued from previous page)
39 Func test
40 NewLine 9
41 FuncExE
42 PushC welcome
43 LoadA nl 0
44 PushV
45 SUM 0
46 Print
47 NewLine 10
48 LoadA o1 0
49 AssignmentPointer
50 New point
51 SetScope
52 PushV
53 BraceStart
54 LoadA x 0 58
55 AssignmentPointer
56 PushN 10.000000
57 BeforeEqual 0
58 Assignment 0 0
59 FreeStack
60 LoadA y 0 64
61 AssignmentPointer
62 PushN 20.000000
63 BeforeEqual 0
64 Assignment 0 0
65 FreeStack
66 LoadA z 0 70
67 AssignmentPointer
68 PushN 30.000000
69 BeforeEqual 0
70 Assignment 0 0
71 FreeStack
72 LoadFunc ismethod
73 LoadA self 0
74 PushV
75 PushC braceend
76 Call
77 NoOperation
78 PushV
79 JumpZ 85
80 LoadFunc braceend
81 Call
82 NoOperation
83 PushV
84 FreeStack
85 BraceEnd
86 FreeStack
87 NewLine 11
88 FuncExE
89 LoadA o1 0
90 PushV
91 Print
92 NewLine 13
93 ReturnNull
94 Class point 006E8BC0
95 NewLabel
(continues on next page)
63.3. Printing Intermediate Code 832

Ring Documentation, Release 1.14
(continued from previous page)
96 LoadA x 0
97 PushV
98 FreeStack
99 LoadA y 0
100 PushV
101 FreeStack
102 LoadA z 0
103 PushV
104 FreeStack
105 ReturnNull
===================================================
63.4
Command:
ring test.ringicfinal
Output:
Hello World
1
2
3
4
5
6
7
8
9
10
welcome
x: 10.000000
y: 20.000000
z: 30.000000
===================================================
Byte Code - After Execution by the VM
===================================================
PC OPCode Data
1 ReturnNull
2 Func main
3 NewLine 2
4 FuncExE
5 PushC Hello World
6 PushP 007D3670 0
7 PushV
8 SUM 0
9 Print
10 NewLine 3
(continues on next page)
63.4. Printing Final Intermediate Code 833

Ring Documentation, Release 1.14
(continued from previous page)
11 ExitMark 29 28
12 LoadAFirst x
13 PushN 1.000000
14 BeforeEqual 0
15 Assignment
16 PushN 1.000000
17 StepNumber
18 JumpVarLPLENum x 10.000000 29
19 NewLine 4
20 FuncExE
21 PushPLocal x 0
22 PushV
23 PushP 007D3670 0
24 PushV
25 SUM 0
26 Print
27 NewLine 5
28 IncLPJump x 18
29 POPExitMark
30 POPStep
31 NewLine 6
32 LoadFuncP test
33 Call 0
34 NoOperation
35 NewLine 8
36 PushV
37 FreeStack
38 ReturnNull
39 Func test
40 NewLine 9
41 FuncExE
42 PushC welcome
43 PushP 007D3670 0
44 PushV
45 SUM 0
46 Print
47 NewLine 10
48 PushPLocal o1 0
49 AssignmentPointer
50 New point
51 SetScope
52 PushV
53 BraceStart
54 LoadA x 0 58
55 AssignmentPointer
56 PushN 10.000000
57 BeforeEqual 0
58 SetProperty 0 106
59 FreeStack
60 LoadA y 0 64
61 AssignmentPointer
62 PushN 20.000000
63 BeforeEqual 0
64 SetProperty 0 141
65 FreeStack
66 LoadA z 0 70
67 AssignmentPointer
(continues on next page)
63.4. Printing Final Intermediate Code 834

Ring Documentation, Release 1.14
(continued from previous page)
68 PushN 30.000000
69 BeforeEqual 0
70 SetProperty 0 176
71 FreeStack
72 LoadFunc ismethod
73 LoadA self 0
74 PushV
75 PushC braceend
76 Call
77 NoOperation
78 PushV
79 JumpZ 85
80 LoadFunc braceend
81 Call
82 NoOperation
83 PushV
84 FreeStack
85 BraceEnd
86 FreeStack
87 NewLine 11
88 FuncExE
89 PushPLocal o1 0
90 PushV
91 Print
92 NewLine 13
93 ReturnNull
94 Class point 007D8470
95 NewLabel
96 LoadA x 0
97 PushV
98 FreeStack
99 LoadA y 0
100 PushV
101 FreeStack
102 LoadA z 0
103 PushV
104 FreeStack
105 ReturnNull
106 LoadFunc ismethod
107 LoadA ring_gettemp_var 0
108 PushV
109 PushC setx
110 Call 0
111 NoOperation
112 PushV
113 JumpZ 132
114 NewLine 2
115 LoadA ring_gettemp_var 0
116 LoadMethod setx
117 LoadA ring_settemp_var 0
118 PushV
119 Call 0 1
120 AfterCallMethod
121 PushV
122 FreeStack
123 NewLine 3
124 LoadA ring_tempflag_var 0 128
(continues on next page)
63.4. Printing Final Intermediate Code 835

Ring Documentation, Release 1.14
(continued from previous page)
125 AssignmentPointer
126 PushN 0.000000
127 BeforeEqual 0
128 Assignment 0 0
129 FreeStack
130 NewLine 4
131 Jump 140
132 NewLine 5
133 PushP 007D37D8 0 137
134 AssignmentPointer
135 PushN 1.000000
136 BeforeEqual 0
137 Assignment 0 0
138 FreeStack
139 NewLine 6
140 Return
141 LoadFunc ismethod
142 LoadA ring_gettemp_var 0
143 PushV
144 PushC sety
145 Call 0
146 NoOperation
147 PushV
148 JumpZ 167
149 NewLine 2
150 LoadA ring_gettemp_var 0
151 LoadMethod sety
152 LoadA ring_settemp_var 0
153 PushV
154 Call 0 1
155 AfterCallMethod
156 PushV
157 FreeStack
158 NewLine 3
159 LoadA ring_tempflag_var 0 163
160 AssignmentPointer
161 PushN 0.000000
162 BeforeEqual 0
163 Assignment 0 0
164 FreeStack
165 NewLine 4
166 Jump 175
167 NewLine 5
168 PushP 007D37D8 0 172
169 AssignmentPointer
170 PushN 1.000000
171 BeforeEqual 0
172 Assignment 0 0
173 FreeStack
174 NewLine 6
175 Return
176 LoadFunc ismethod
177 LoadA ring_gettemp_var 0
178 PushV
179 PushC setz
180 Call 0
181 NoOperation
(continues on next page)
63.4. Printing Final Intermediate Code 836

Ring Documentation, Release 1.14
(continued from previous page)
182 PushV
183 JumpZ 202
184 NewLine 2
185 LoadA ring_gettemp_var 0
186 LoadMethod setz
187 LoadA ring_settemp_var 0
188 PushV
189 Call 0 1
190 AfterCallMethod
191 PushV
192 FreeStack
193 NewLine 3
194 LoadA ring_tempflag_var 0 198
195 AssignmentPointer
196 PushN 0.000000
197 BeforeEqual 0
198 Assignment 0 0
199 FreeStack
200 NewLine 4
201 Jump 210
202 NewLine 5
203 PushP 007D37D8 0 207
204 AssignmentPointer
205 PushN 1.000000
206 BeforeEqual 0
207 Assignment 0 0
208 FreeStack
209 NewLine 6
210 Return
===================================================
63.5
Command:
ring test.ringcgi
63.5. CGI Support 837

Ring Documentation, Release 1.14
63.6
Command:
ring test.ringnorun
63.7
Command:
ring test.ringins
Output:
===================================================
Operation : ReturnNull
PC :
Line Number :
SP (After) :
LineNumber
===================================================
.....
.....
.....
Tip:Output removed from the previous example because it's very large!
63.8
Command:
ring test.ringperformance
Output:
===================================================
Date :/09/15:56:17
Clock :
===================================================
Hello World
1
2
3
4
5
6
7
8
(continues on next page)
63.6. No Run 838

Ring Documentation, Release 1.14
(continued from previous page)
9
10
welcome
x:.000000
y:.000000
z:.000000
===================================================
Date :/09/15:56:17
Clock :
===================================================
63.9
You can generate object le (.ringo) from your source code le (.ring) using -go option
Tip:You will get one object le to use for distributing/running your application which may contains one or many
ring source les that you can keep or distribute based on the application (commercial or open source).
Command:
ring test.ringgo
To run the compiled object le
ring test.ringo
63.10
You can generate embedded object le (C source code) from your source code le (*.ring) using -geo option
Command:
ring test.ringgeo
This command will generate at least three les
test.c
ringappcode.c
ringappcode.h
More les could be generated based on the project size
The generated les will pass the byte code to Ring VM to be executed
63.9. Generate Object File 839

CHAPTER
SIXTYFOUR
DISTRIBUTING RING APPLICATIONS (MANUAL)
In this chapter we will learn about distributing Ring applications.
The next method is old and was used in Ring 1.5 and previous versions!
Starting from Ring 1.6 we have a nice tool called Ring2EXE
Using Ring2EXE we can distribute applications quickly for Windows, Linux and macOS
Check the Ring2EXE chapter for more information!
64.1
Step 1:
Copy c:ingin folder to be for example c:\myapp
Step 2:
Rename c:\myapping.exe to c:\myapp\myapp.exe
Step 3:
Create a file c:\myapping.ring
And write
Load"myapp.ring"
When you run myapp.exe the le ring.ring will be executed automatically
So your le myapp.ring will be called and executed
Or just rename myapp.ring to ring.ring
It's a fast way to distribute applications.
840

Ring Documentation, Release 1.14
64.2
Step 1:
Execute the next command
ring myapp.ring -go
This will generate one object le (myapp.ringo) from the project les (*.ring)
Step 2:
Rename myapp.ringo to ring.ringo
When you run the executable le (ring.exe) or (myapp.exe) the le ring.ringo will be executed.
64.3
Ring will run ring.ring or ring.ringo only when
(1)
(2)
We added the support to ring.ring (and ring.ringo) for a way to distribute Ring apps (before Ring2EXE)
64.4
There are many tools that you can use to distribute your application.
Check : nullsoft scriptable install system
URL :
64.5
Another method to distribute applications is to use a C/C++ compiler.
Ring can be embedded in C/C++ projects, We can create executable les using a C/C++ compiler by embedding the
Ring language in our project.
Check the “Embedding Ring Language in C/C++ Programs” chapter.
Using this way we will avoid using ring.ring or ring.ringo les.
64.2. Protecting the Source Code 841

Ring Documentation, Release 1.14
64.6
Ring can be embedded in a Qt projects or LibSDL projects to build Mobile applications and Games.
You can build the Qt project or the LibSDL project and get the Android package directly (*.apk)
Check Ring distributions for Mobile development using Qt or LibSDL.
64.6. Distributing Applications and Games for Mobile 842

CHAPTER
SIXTYFIVE
DISTRIBUTING RING APPLICATIONS USING RING2EXE
In this chapter we will learn about distributing Ring applications.
Starting from Ring 1.6 we have a nice tool called Ring2EXE (Written in Ring itself)
Using Ring2EXE we can distribute applications quickly for Windows, Linux, macOS, WebAssembly and Mobile
devices
Note:We can use the Distribute Menu in the Ring Notepad application (More Easy)
65.1
ring2exe filename.ring [Options]
This will set lename.ring as input to the program
The next les will be generated
filename.ringo (The Ring Object File - by Ring Compiler)
filename.c (The C Source code file
Contains the ringo file content
Will be generated by this program)
filename_buildvc.bat (Will be executed to build filename.c using Visual C/C++)
filename_buildgcc.bat (Will be executed to build filename.c using GNU C/C++)
filename_buildclang.bat (Will be executed to build filename.c using CLang C/C++)
filename.obj (Will be generated by the Visual C/C++ compiler)
filename.exe (Will ge generated by the Visual C/C++ Linker)
filename (Executable File - On Linux & MacOS X platforms)
65.2
At rst the Ring compiler will be used to generate the Ring object le (*.ringo)
If we have a C compiler (optional), This object le will be embedded inside a C source code le
Then using the C compiler and the Ring library (Contains the Ring Virtual Machine) the executable le
will be generated!
If we don't have a C compiler, the Ring executable will be copied and renamed to your application name
And your Ring object le (*.ringo) will become ring.ringo to be executed at startup of the executable le.
843

Ring Documentation, Release 1.14
So it's better and easy to have a C compiler on your machine to be used by Ring2EXE.
65.3
We have test.ring contains the next code
see"Hello, World!"
&#3627408455;&#3627408476; &#3627408463;&#3627408482;&#3627408470;&#3627408473;&#3627408465; &#3627408481;&#3627408469; &#3627408466;&#3627408485;&#3627408466;&#3627408464;&#3627408482;&#3627408481;&#3627408462;&#3627408463;&#3627408473;&#3627408466; ??????&#3627408473;&#3627408466; &#3627408467;&#3627408476;&#3627408479; &#3627408458;&#3627408470;&#3627408475;&#3627408465;&#3627408476;&#3627408484;&#3627408480;˓ &#3627408447;&#3627408470;&#3627408475;&#3627408482;&#3627408485; &#3627408476;&#3627408479; &#3627408474;&#3627408462;&#3627408464;&#3627408450;&#3627408454;
ring2exe test.ring
To run the program (Windows)
test
To run the program (Linux and macOS)
./test
65.4
˒&#3627408472;&#3627408466;&#3627408466;&#3627408477; . &#3627408439;&#3627408476;&#3627408475;&#3627409170;&#3627408481; &#3627408465;&#3627408466;&#3627408473;&#3627408466;&#3627408481;&#3627408466; &#3627408455;&#3627408466;&#3627408474;&#3627408477;◁ &#3627408441;&#3627408470;&#3627408473;&#3627408466;&#3627408480;
-static : Build Standalone Executable File
↼&#3627408439;&#3627408476;&#3627408475;&#3627409170;&#3627408481; &#3627408482;&#3627408480;&#3627408466; &#3627408479;&#3627408470;&#3627408475;&#3627408468;◁&#3627408465;&#3627408473;&#3627408473;▷&#3627408479;&#3627408470;&#3627408475;&#3627408468;◁&#3627408480;&#3627408476;▷&#3627408479;&#3627408470;&#3627408475;&#3627408468;◁&#3627408465;&#3627408486;&#3627408473;&#3627408470;&#3627408463;↽
-gui : Build GUI Application (Hide the Console Window)
-dist : Prepare application for distribution
-allruntime : Include all libraries in distribution
-mobileqt : Prepare Qt Project to distribute Ring Application for Mobile
-webassemblyqt : Prepare Qt Project to distribute Ring Application for the web
˓→(WebAssembly)
-noqt : Remove RingQt from distribution
-noallegro : Remove RingAllegro from distribution
-noopenssl : Remove RingOpenSSL from distribution
-nolibcurl : Remove RingLibCurl from distribution
-nomysql : Remove RingMySQL from distribution
-noodbc : Remove RingODBC from distribution
-nosqlite : Remove RingSQLite from distribution
-noopengl : Remove RingOpenGL from distribution
-nofreeglut : Remove RingFreeGLUT from distribution
-nolibzip : Remove RingLibZip from distribution
-noconsolecolors : Remove RingConsoleColors from distribution
-nomurmuhash : Remove RingMurmurHash from distribution
-nocruntime : Remove C Runtime from distribution
-qt : Add RingQt to distribution
-allegro : Add RingAllegro to distribution
-openssl : Add RingOpenSSL to distribution
-libcurl : Add RingLibCurl to distribution
-mysql : Add RingMySQL to distribution
-odbc : Add RingODBC to distribution
-sqlite : Add RingSQLite to distribution
-postgresql : Add RingPostgreSQL to distribution
-opengl : Add RingOpenGL to distribution
(continues on next page)
65.3. Example 844

Ring Documentation, Release 1.14
(continued from previous page)
-freeglut : Add RingFreeGLUT to distribution
-libzip : Add RingLibZip to distribution
-libuv : Add RingLibuv to distribution
-consolecolors : Add RingConsoleColors to distribution
-murmurhash : Add RingMurmurHash to distribution
-cruntime : Add C Runtime to distribution
65.5
Using the “-static” option we can build executable console application
So we don't have to use ring.dll, ring.so or ring.dylib
This avoid only the need to Ring dynamic link library
If you are using another libraries, You will need to include it with your application.
ring2exe test.ring -static
65.6
We have test2.ring contains the next code
# Just a simple program to test Ring2EXE Tool!
# Using RingAllegro
load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
}
To build the executable le and prepare for distributing the Game
We use “-dist” option and “-allruntime” to include all libraries
ring2exe test2.ring -dist -allruntime
After executing the previous command
On Windows we will have : target/windows folder
On Linux we will have : target/linux folder
On macOS we will have : target/macos folder
The previous command will add all of the Ring runtime libraries to our distribution
But we may need only RingAllegro, So it's better to use the next command
ring2exe test2.ring -dist -allegro -cruntime
65.5. Building standalone console application 845

Ring Documentation, Release 1.14
This will produce smaller size distribution and will avoid the runtime les that we don't need!
Also we could use the “-gui” option to hide the console window
So it's better to use the next command
ring2exe test2.ring -dist -gui -allegro -cruntime
65.7
We have test3.ring contains the next code
# Just a simple program to test Ring2EXE Tool!
# Using RingQt
load"guilib.ring"
newqApp {
newqWidget() {
setwindowtitle("Hello, World!")
resize(400,400)
show()
}
exec()
}
To build the executable le and prepare for distributing the GUI application
We use “-dist” option and “-allruntime” to include all libraries
ring2exe test3.ring -dist -allruntime
After executing the previous command
On Windows we will have : target/windows folder
On Linux we will have : target/linux folder
On macOS we will have : target/macos folder
The previous command will add all of the Ring runtime libraries to our distribution
But we may need only RingQt, So it's better to use the next command
ring2exe test3.ring -dist -qt -cruntime
This will produce smaller size distribution and will avoid the runtime les that we don't need!
Also we could use the “-gui” option to hide the console window
So it's better to use the next command
ring2exe test3.ring -dist -gui -qt -cruntime
65.7. Distributing RingQt Applications 846

Ring Documentation, Release 1.14
65.8
To prepare a Qt project for your RingQt application (test3.ring) use the “-mobileqt” option
Example :
ring2exe test3.ring -dist -mobileqt
After executing the previous command, We will have the Qt project in target/mobile/qtproject folder
The main project le will be project.pro which we can open using the Qt Creator IDE.
Also we will have the resource le : project.qrc
Another important le is our C++ main le : main.cpp
65.9
To prepare a Qt project (WebAssembly) for your RingQt application (myapp.ring) use the “-webassemblyqt” option
Example :
ring2exe myapp.ring -dist -webassemblyqt
After executing the previous command, We will have the Qt project in target/webassembly/qtproject folder
The main project le will be project.pro which we can open using the Qt Creator IDE.
Also we will have the resource le : project.qrc
Another important le is our C++ main le : main.cpp
65.10
For a better example, consider building an Android package for the Cards game that comes with the
Ring language in this folder : ring/application/cards
The Cards game folder contains three les
cards.ring : The Game source code
cards.jpg : The image le used by the game
project.qrc : Resource le to be used with the Qt project
The resource le contains the next content
<RCC>
<qresource>
<file>cards.ringo</file>
<file>cards.jpg</file>
</qresource>
</RCC>
We have two les in the resource le
The rst le is cards.ringo (The Ring Object File) and the second le is cards.jpg (The image le)
65.8. Distributing Applications for Mobile using RingQt 847

Ring Documentation, Release 1.14
As a start, Ring2EXE will generate this resource le in target/mobile/qtproject/project.qrc
But this le will contains only cards.ringo (That Ring2EXE will generate by calling Ring compiler)
We need to update this resource le to add the image le : cards.jpg
After this update, we copy the resource le to the main application folder
So when we use Ring2EXE again, Our updated resource le will be used!
Now to build the cards game for Mobile
(1)
ring2exe cards.ring -dist -mobileqt
(2)
(3)
How the Cards game will nd the image le ?
RingQt comes with a simple function : AppFile() that we can use to determine the les that we may
access on Desktop or Mobile platforms
The next code from cards.ring
mypic newQPixmap(AppFile("cards.jpg"))
So all what you need is using AppFile() function around your image les!
65.11
RingQt
Another example to distribute your application for Mobile Devices using Ring2EXE and Qt
consider building an Android package for the Weight History application that comes with the
Ring language in this folder : ring/application/weighthistory
The Weight History application folder contains four les
weighthistory.ring : The application source code
weighthistory.db : The SQLite database
project.qrc : The resource le for the Qt project
main.cpp : The main C++ source le for the Qt project
To build the Weight History application for Mobile
(1)
ring2exe weighthistory.ring -dist -mobileqt
(2)
(3)
The resource le (project.qrc) contains two les
65.11. Building the Weight History Application for Mobile using RingQt 848

Ring Documentation, Release 1.14
<RCC>
<qresource>
<file>weighthistory.ringo</file>
<file>weighthistory.db</file>
</qresource>
</RCC>
The rst le is weighthistory.ringo (Ring Object File - Generated by Ring2EXE by calling Ring compiler)
The database le : weighthistory.db
The main.cpp contains the next little update, To copy the database le from resources to a writable location
on the mobile device
QString path3 ;
path3 = path+"/weighthistory.db";
QFile::copy(":/weighthistory.db",path3);
You will need to do this with database les only!
When we use Ring2EXE, the tool will check for project.qrc and main.cpp, if they exist then your updated
les will be used in target/mobile/qtproject instead of the default version generated by Ring2EXE
So Use Ring2EXE to generate these les, Then copy them to your application folder when you update them.
65.12
To build the Form Designer application (ring/tools/formdesigner) for Mobile
(1)
ring2exe formdesigner.ring -dist -mobileqt
(2)
(3)
in the folder ring/application/formdesigner You will nd the resource le : project.qrc
It will be used automatically by Ring2EXE
<RCC>
<qresource>
<file>formdesigner.ringo</file>
<file>image/allevents.png</file>
<file>image/checkbox.png</file>
<file>image/close.png</file>
<file>image/combobox.bmp</file>
<file>image/datepicker.bmp</file>
<file>image/dial.png</file>
<file>image/formdesigner.png</file>
<file>image/frame.png</file>
<file>image/grid.bmp</file>
<file>image/hyperlink.png</file>
<file>image/image.png</file>
<file>image/label.png</file>
<file>image/layout.png</file>
(continues on next page)
65.12. Building the Form Designer for Mobile using RingQt 849

Ring Documentation, Release 1.14
(continued from previous page)
<file>image/lcdnumber.png</file>
<file>image/listview.png</file>
<file>image/lock.png</file>
<file>image/new.png</file>
<file>image/open.png</file>
<file>image/progressbar.png</file>
<file>image/project.png</file>
<file>image/pushbutton.png</file>
<file>image/radiobutton.png</file>
<file>image/save.png</file>
<file>image/saveas.png</file>
<file>image/select.png</file>
<file>image/slider.png</file>
<file>image/spinner.bmp</file>
<file>image/statusbar.png</file>
<file>image/tab.png</file>
<file>image/textarea.png</file>
<file>image/textfield.png</file>
<file>image/timer.png</file>
<file>image/toolbar.png</file>
<file>image/tree.bmp</file>
<file>image/videowidget.png</file>
<file>image/webview.png</file>
</qresource>
</RCC>
As we did in the Cards game, The Form Designer will use the AppFile() function to determine the name of the Image
les.
The next code from ring/tools/formdesigner/mainwindow/formdesignerview.ring
funcCreateToolBar
aBtns
newqtoolbutton(win) {
setbtnimage(self,AppFile("image/new.png"))
setclickevent(Method(:NewAction))
settooltip("New File")
} ,
newqtoolbutton(win) {
setbtnimage(self,AppFile("image/open.png"))
setclickevent(Method(:OpenAction))
settooltip("Open File")
} ,
newqtoolbutton(win) {
setbtnimage(self,AppFile("image/save.png"))
setclickevent(Method(:SaveAction))
settooltip("Save")
} ,
newqtoolbutton(win) {
setbtnimage(self,AppFile("image/saveas.png"))
setclickevent(Method(:SaveAsAction))
settooltip("Save As")
} ,
newqtoolbutton(win) {
setbtnimage(self,AppFile("image/close.png"))
setclickevent(Method(:ExitAction))
settooltip("Exit")
(continues on next page)
65.12. Building the Form Designer for Mobile using RingQt 850

Ring Documentation, Release 1.14
(continued from previous page)
}
]
tool1"files") {
forxinaBtns { addwidget(x) addseparator() }
}
From this example, We know that we can use sub folders for images.
65.13
When we have large RingQt project that contains a lot of images and les, We need to add these les to the resource
le (*.qrc ) when distributing applications for Mobile devices.
Instead of adding these les one by one, Ring 1.6 comes with a simple tool that save our time, It's called Folder2qrc.
Example:
folder2qrc formdesigner.ring
We determine the main source le while we are in the application folder, and Folder2qrc will check all of the les in
the current folder and sub folders, Then add them to the resource le after the mainle.ringo (In our example this will
be formdesigner.ringo)
The output le will be : project.qrc
You can open it and remove the les that you don't need in the resources!
65.14
•
for example, if you have target/windows folder then used
ring2exe test3.ring -dist -allruntime
The les in target/windows will be deleted before adding the les again
This is important when you prepare a distribution for Mobile devices
ring2exe test3.ring -dist -mobileqt
If you modied the resource le : project.qrc or the main le : main.cpp
Don't forget to copy them to the application folder!
So Ring2EXE can use the updated version if you tried the previous command again!
•
https://github.com/ring-lang/ring/blob/master/tools/ring2exe/ring2exe.ring
•
automatically to support new libraries
https://github.com/ring-lang/ring/blob/master/tools/ring2exe/libs
65.13. Creating the Qt resource le using Folder2qrc 851

CHAPTER
SIXTYSIX
THE RING PACKAGE MANAGER (RINGPM)
In this chapter we will learn about using the Ring Package Manager (RingPM)
RingPM is a tool for discovering, installing and updating Ring packages.
66.1
The Package Manager uses Semantic Versioning to check compatibility between packages
The Package Manager comes with the next options
Usage : ringpm [command]
Command : search [keywords...]
Command : refresh : Update the Registry (Packages List)
Command : install [ <packagename> [from <UserName>] [branch <branchname>] ]
Command : list [-u : check updates]
Command : run [packagename]
Command : update <packagename>
Command : remove <packagename>
Command : format : Delete All Packages
Command : new <packagename>
Command : package : Create package in the current folder
66.2
We can discover new packages using the Search command
Using this command we can search in the RingPM Registry (Packages Index)
The RingPM Registry is a local copy of all registred packages.
ringpm search [keywords...]
Example:
ringpm search notepad
Output:
Package : ringnotepad (Ring Notepad)
Package : notepadppeditorextension (Notepad++ Editor Extension package)
852

Ring Documentation, Release 1.14
To print all packages in the RingPM Registry, use the search command without keywords.
Example:
ringpm search
66.3
The RingPM Registry is a local copy of all registred packages.
We can update the local copy using the Refresh command
Example:
ringpm refresh
Output:
No updates to the Registry, Nothing to do!
Or
The Registry is updated from revision 110 (2019/01/13) to revision 112 (2019/01/15)
66.4
We can install new packages using the Install command
ringpm install [ <packagename> [from <UserName>] [branch <branchname>] ]
We can type only the package name to get the package information from the RingPM Registry or we can determine
the user name (GitHub) and the branch name of the github project (optional).
If the current folder is a package folder then we don't need to write the package name.
Example (1) :
ringpm install ringnotepad
Example (2) :
ringpm install goldmagic800
Example (3) :
ringpm install gameoflife
If the package is not added to the RingPM Registry, We can install it directly from the GitHub user
Example (4) :
ringpm install firstpackage from mahmoudfayed
To run the package after installation
66.3. Updating the RingPM Registry 853

Ring Documentation, Release 1.14
ringpm run firstpackage
To install a package in the current folder
Example (5) :
ringpm install
66.5
We can know the installed packages using the List command
ringpm list [-u : check updates]
Example
ringpm list
Output
(analogclock) : The AnalogClock Package [master] -- (1.0.0)
(androidringlibsdl) : The AndroidRingLibSDL Package [master] -- (1.0.0)
(androidringqt) : The AndroidRingQt Package [master] -- (1.0.0)
(atomeditorextension) : The AtomEditorExtension Package [master] -- (1.0.0)
(bignumber) : The BigNumber Package [master] -- (1.0.0)
(calculator) : The Calculator Package [master] -- (1.0.0)
(cards) : The Cards Package [master] -- (1.0.0)
(checkers) : The Checkers Package [master] -- (1.0.0)
(chess) : The Chess Package [master] -- (1.0.0)
....
To check for new updates
ringpm list -u
66.6
After installing a package, we can run it using the Run command.
ringpm run [packagename]
Example(1):
ringpm run ringnotepad
Example(2):
ringpm run goldmagic800
Example(3):
ringpm run gameoflife
66.5. Printing List of Installed Packages 854

Ring Documentation, Release 1.14
To run a package in the current folder
Example(4):
ringpm run
66.7
We can update a package using the Update command
ringpm update <packagename>
Example:
ringpm update ringnotepad
66.8
We can remove a package using the Remove command
ringpm remove <packagename>
Example:
ringpm remove ringnotepad
66.9
We can delete all packages using the Format command
Example:
ringpm format
66.10
We can create new package using the New command
ringpm new <packagename>
Example:
ringpm new myapp
This will create new folder called my myapp
The new folder will contains the next le
•
66.7. Update Package 855

Ring Documentation, Release 1.14
•
•
File : main.ring
# The Main File
load"lib.ring"
funcmain
?Hello, World!"
File : lib.ring
# The Library File
File : package.ring
aPackageInfo
:nameThe myapp Package",
:descriptionOur myapp package using the Ring programming language",
:foldermyapp",
:developer",
:email",
:licenseMIT License",
:version1.0.0",
:ringversion1.10",
:versions
[
:version1.0.0",
:branchmaster"
]
],
:libs
[
:name",
:version",
:providerusername"
]
],
:files
"lib.ring",
"main.ring"
],
:ringfolderfiles
],
:windowsfiles
],
:linuxfiles
],
:ubuntufiles
],
:fedorafiles
(continues on next page)
66.10. Creating New Package 856

Ring Documentation, Release 1.14
(continued from previous page)
],
:macosfiles
],
:windowsringfolderfiles
],
:linuxringfolderfiles
],
:ubunturingfolderfiles
],
:fedoraringfolderfiles
],
:macosringfolderfiles
],
:runring main.ring",
:windowsrun",
:linuxrun",
:macosrun",
:ubunturun",
:fedorarun",
:setup",
:windowssetup",
:linuxsetup",
:macossetup",
:ubuntusetup",
:fedorasetup",
:remove",
:windowsremove",
:linuxremove",
:macosremove",
:ubunturemove",
:fedoraremove"
]
66.11
The package description le contains the package information dened in the list aPackageInfo
Attribute Description
Name Package Name
Description Package Desciption
Folder The Folder Name (Will be created in ring/ringpm/packages)
Developer The Package Developer Name
Email The Package Developer Email
License The Package License
Version The Current Version of the Package (Latest Release)
continues on next page
66.11. The Package Description File 857

Ring Documentation, Release 1.14
Table 1 – continued from previous page
Attribute Description
RingVersion The Required Ring Language Version (Minimum Version)
Versions List of different versions provided by different branches in the GitHub project
Libs List of dependencies (Dened by name, version & GitHub user name)
Files List of les (will be installed in ring/ringpm/packages/[Folder]
RingFolderFiles List of les (will be installed in ring folder)
WindowsFiles Like (Files) but for Microsoft Windows Only
LinuxFiles Like (Files) but for Linux Only
MacOSFiles Like (Files) but for macOS Only
UbuntuFiles Like (Files) but for Ubuntu Only
FedoraFiles Like (Files) but for Fedora Only
WindowsRingFolderFilesLike (RingFolderFiles) but for Microsoft Windows Only
LinuxRingFolderFilesLike (RingFolderFiles) but for Linux Only
MacOSRingFolderFilesLike (RingFolderFiles) but for macOS Only
UbuntuRingFolderFilesLike (RingFolderFiles) but for Ubuntu Only
FedoraRingFolderFilesLike (RingFolderFiles) but for Fedora Only
Run System Command (Command prompt or Terminal) to run the package
WindowsRun Like (Run) but for Microsoft Windows Only
LinuxRun Like (Run) but for Linux Only
MacOSRun Like (Run) but for macOS Only
UbuntuRun Like (Run) but for Ubuntu Only
FedoraRun Like (Run) but for Fedora Only
Setup System Command (Command prompt or Terminal) after downloading the package les
WindowsSetup Like (Setup) but for Microsoft Windows Only
LinuxSetup Like (Setup) but for Linux Only
MacOSSetup Like (Setup) but for macOS Only
UbuntuSetup Like (Setup) but for Ubuntu Only
FedoraSetup Like (Setup) but for Fedora Only
Remove System Command (Command prompt or Terminal) before removing the package les
WindowsRemove Like (Remove) but for Microsoft Windows Only
LinuxRemove Like (Remove) but for Linux Only
MacOSRemove Like (Remove) but for macOS Only
UbuntuRemove Like (Remove) but for Ubuntu Only
FedoraRemove Like (Remove) but for Fedora Only
66.12
To create a package for an application that already exists, go to the application folder then type
ringpm package
This will create the package denition le (package.ring) and will add all of the application les to the package
denition.
Each RingPM package contains the package denition le (package.ring)
The package denition le is a list that describe the package information and les.
Example :
The package denition le for the Ring Notepad package
66.12. Create Package in the Current Folder 858

Ring Documentation, Release 1.14
aPackageInfo
:nameThe RingNotepad Package",
:descriptionOur RingNotepad package using the Ring programming language",
:folderringnotepad",
:developerMahmoud Fayed",
:[email protected]",
:licenseMIT License",
:version1.0.0",
:ringversion1.10",
:versions
[
:version1.0.0",
:branchmaster"
]
],
:libs
[
:namestdlib",
:version1.0",
:providerusername"
],
[
:nameringqt",
:version1.0",
:providerusername"
],
[
:namefindinfiles",
:version1.0",
:providerusername"
],
[
:nameformdesigner",
:version1.0",
:providerusername"
],
[
:namelibdepwin_apache",
:version1.0",
:providerusername"
]
],
:files
"main.ring",
"README.md"
],
:ringfolderfiles
"applications/rnote/batch/killwebserver.bat",
"applications/rnote/batch/run.bat",
"applications/rnote/batch/run2.bat",
"applications/rnote/image/back.jpg",
"applications/rnote/image/back2.jpg",
"applications/rnote/image/close.png",
"applications/rnote/image/colors.png",
"applications/rnote/image/copy.png",
"applications/rnote/image/cut.png",
"applications/rnote/image/debug.png",
(continues on next page)
66.12. Create Package in the Current Folder 859

Ring Documentation, Release 1.14
(continued from previous page)
"applications/rnote/image/font.png",
"applications/rnote/image/formdesigner.png",
"applications/rnote/image/new.png",
"applications/rnote/image/notepad.png",
"applications/rnote/image/open.png",
"applications/rnote/image/paste.png",
"applications/rnote/image/print.png",
"applications/rnote/image/project.png",
"applications/rnote/image/richtext.png",
"applications/rnote/image/run.png",
"applications/rnote/image/rungui.png",
"applications/rnote/image/save.png",
"applications/rnote/image/saveas.png",
"applications/rnote/image/search.png",
"applications/rnote/image/source.png",
"applications/rnote/image/undo.png",
"applications/rnote/image/web.png",
"applications/rnote/README.md",
"applications/rnote/rnote.ring",
"applications/rnote/rnoteactivefile.ring",
"applications/rnote/rnoteactivefolder.ring",
"applications/rnote/rnoteautocomplete.ring",
"applications/rnote/rnotebase.ring",
"applications/rnote/rnotecontroller.ring",
"applications/rnote/rnotedistribute.ring",
"applications/rnote/rnoteeditmenu.ring",
"applications/rnote/rnoteeditorevents.ring",
"applications/rnote/rnotefilemenu.ring",
"applications/rnote/rnotefiles.ring",
"applications/rnote/rnotefilestabs.ring",
"applications/rnote/rnotefind.ring",
"applications/rnote/rnotefindinfiles.ring",
"applications/rnote/rnoteformdesigner.ring",
"applications/rnote/rnotegoto.ring",
"applications/rnote/rnotehelp.ring",
"applications/rnote/rnotelists.ring",
"applications/rnote/rnotemainfiletoolbar.ring",
"applications/rnote/rnotemainwindow.ring",
"applications/rnote/rnotemode.ring",
"applications/rnote/rnoteoutputwindow.ring",
"applications/rnote/rnoteprogrammenu.ring",
"applications/rnote/rnoterun.ring",
"applications/rnote/rnotesettings.ring",
"applications/rnote/rnotestyle.ring",
"applications/rnote/rnotetabwidth.ring",
"applications/rnote/rnotetools.ring",
"applications/rnote/rnotetreeviewevents.ring",
"applications/rnote/rnoteviewmenu.ring",
"applications/rnote/rnotewebbrowser.ring"
],
:runring main.ring"
]
66.12. Create Package in the Current Folder 860

Ring Documentation, Release 1.14
66.13
The RingPM Registry is a local copy of all registred packages.
aPackagesRegistry
[ringpresentation",
:descriptionPowerpoint presentation for the Ring programming language",
:ProviderUserNameringpackages"
]
# ...
]
Each package is dened using a list that determine
•
•
•
We can register new packages by updating the registry le then sending a Pull Request
URL :
66.13. The RingPM Registry File 861

CHAPTER
SIXTYSEVEN
USING ZEROLIB
In this chapter we will learn how to use the ZeroLib library.
67.1
ZeroLib is a simple library written in Ring.
The library provideds classes for Lists and String where the index starts from 0.
67.2
Syntax:
Z(String|List) ---> New Object (ZeroBasedString|ZeroBasedList)
67.3
Simple class provide a List where the index starts from zero.
Methods:
Method Description/Output
Init(List)
Add(Value) Add item to the list
Insert(nIndex,Value) Inset Item after nIndex
Find(Value) Find item
Delete(nIndex) Delete item from the list
Item(nIndex) Get item from the list
First() Get the rst item in the list
Last() Get the last item in the list
Set(nIndex,Value) Set item value
FindInColumn(nCol,Value)Find item in a column
Sort() Sort items - return new list
Reverse() Reverse items - return new list
Swap(nIndex1,nIndex2)Swap two items
Example:
862

Ring Documentation, Release 1.14
load"zerolib.ring"
?Using List - Index start from 0"
List=1,2,3]
List.Add(4)
List.Add(5)
?List[0]
?List[1]
?List[2]
?List[3]
?List[4]
nIndex List.find(2)
?Find(2) =
List.delete(0)
?After deleting the first item : List[0]"
?Now List[0] = List[0]
Output:
UsingList- from0
1
2
3
4
5
Find(2)
After deleting the first item : List[0]
NowList[0]
67.4
Simple class provide a String where the index starts from zero.
Method Description/Output
Init(String|Number)
Lower() New String - Lower case characters
Upper() New String - Upper case characters
Left(x) New String - contains x characters from the left
Right(x) New String - contains x characters from the right
Lines() Number - Lines count
Trim() New String - Remove Spaces
Copy(x) New String - repeat string x times
strcmp(cString) Compare string with cString
tolist() List (String Lines to String Items)
tole(cFileName) Write string to le
mid(nPos1,nPos2) New String - from nPos1 to nPos2
getfrom(nPos1) New String - from nPos1 to the end of the string
replace(cStr1,cStr2,lCase)New String - Replace cStr1 with cStr2 , lCase (True=Match Case)
split() List - Each Word as list item
startswith(substring)Return true if the start starts with a substring
endswith(substring) Return true if the start ends with a substring
Example:
67.4. ZeroBasedString Class 863

Ring Documentation, Release 1.14
load"zerolib.ring"
?Using String - Index start from 0"
String=Welcome"
?String[0]
?String[1]
?String[2]
?String[3]
?String[4]
?String[5]
?String[6]
Output:
UsingString- from0
W
e
l
c
o
m
e
67.5
We can nd the library source code in this folder
URL :
67.5. Source Code 864

CHAPTER
SIXTYEIGHT
FOXRING FUNCTIONS REFERENCE
A class contains functions similar to FoxPro functions.
68.1
Function Name Description
frAbs() Returns the absolute value of the specied numeric expression.
frAddBs() Adds a backslash (if needed) to a path expression.
frALines() Creates an Array with the content of the specied string.
frAllTrim() Removes all leading and trailing spaces of the specied string.
frAsc() Returns the ANSI value for the leftmost character in a character expression.
frAt() Searches a character expression for the occurrence
of another character expression.
frAtC() Searches a character expression for the ocurrence of another character expression without
regard for the case of these two expressions.
frBetween() Determines whether the value of an expression is inclusively between the values of two
expressions of the same type.
frChr() Returns the character associated with the specied numeric ANSI code.
frEmpty() Determines whether an expression evaluates to empty.
frFile() Checks if a le exists on disk.
frFileToStr() Returns the contents of a le as a character string.
frForceExt() Returns a string with the old le name extension replaced by a new extension.
frForcePath() Returns a le name with a new path name substituted for the old one.
frIif() Returns one of two values depending on the value of a logical expression.
frInList() Determines whether an expression matches another expression in a list.
frInt() Evaluates a numeric expression and returns the integer portion of the expression.
frJustDrive() Returns the drive letter from a complete path.
frJustExt() Returns the characters of a le extension from a complete path.
frJustFName() Returns the le name portion of a complete path and le name.
frJustPath() Returns the path portion of a complete path and le name.
frJustStem() Returns the stem name (the le name before the extension)
from a complete path and le name.
frLen() Determines the number of characters in a character expression,
indicating the length of the expression.
frListToString()Creates a string with the string elements of an Array.
frLTrim() Removes all leading spaces or parsing characters from the
specied character expression.
frPadL() Returns a string from an expression, padded with spaces or characters to a
continues on next page
865

Ring Documentation, Release 1.14
Table 1 – continued from previous page
Function Name Description
specied length on the left side.
frPadR() Returns a string from an expression, padded with spaces or characters to a
specied length on the right side.
frProper() Returns from a character expression a string capitalized as
appropriate for proper names.
frReplicate() Returns a character string that contains a specied character
expression repeated a specied number of times.
frRTrim() Removes all trailing spaces or parsing characters from
the specied character expression.
frSetIfEmpty()Set a Value into a variable if the variable value is empty, null or zero.
frSetSeparatorTo()Species the character for the numeric place separator.
frSpace() Returns a character string composed of a specied number of spaces.
frStr() Returns the character equivalent of a numeric expression.
frStringToList()Creates a List with the content of the specied string.
frStrTran() Searches a character expression for a second character expression and
replaces each occurrence with a third character expression.
frStuff() Returns a new character string replaced by a specied number of
characteres in a character expression with another character expression.
frSubStr() Returns a character string from the given character expression,
starting at a specied position in the character
expression and continuing for a specied number of characters.
frTransform() Returns a character string from an expression in a
format determined by a format code.
frVal() Returns a numeric value from a character expression composed of numbers.
frVarType() Returns the data type of an expression.
68.2
*Syntax : lnReturnValue = frAbs(tnExpression)
*Description : Returns the absolute value of the specified numeric expression.
* :
*Arguments : <tnExpression>
* : Specifies the numeric expression whose absolute value frAbs()
* : returns.
*Returns : <lnReturnValue>
* : Returns the absolute value of the specified numeric expression.
68.3
*Syntax : lnReturnValue = frAsc(tcExpression)
*Description : Returns the ANSI value for the leftmost character in
* : a character expression.
*Arguments : <tcExpression>
* : Specifies the character expression containing the character
* : whose ANSI value frAsc()
* : returns. Any characters after the first character in
* : tcExpression are ignored by frAsc().
(continues on next page)
68.2. frAbs() function 866

Ring Documentation, Release 1.14
(continued from previous page)
*Returns : <lnReturnValue>
* : returns the position of the character in the character
* : table of the current code page.
* : Every character has a unique ANSI value in the
* : range from 0 to 255.
68.4
*Syntax : lcReturnValue = frAddBs(tcPath)
*Description : Adds a backslash (if needed) to a path expression.
* :
*Arguments : <tcPath>
* : Specifies the path name to which to add the backslash.
* :
*Returns : <lcReturnValue> The path with the backslash.
68.5
*Syntax : lnPos = frAt(tcToSearch, tcString, tnOccurrence)
*Description : Searches a character expression for the occurrence of
* : another character expression.
* : The search performed by frAt() is case-sensitive.
* :
*Arguments : <tcToSearch>
* : Specifies the character expression to search
* : for in <tcString>.
* : <tcString>
* : Specifies the character expression to search
* : for <tcToSearch>.
* : <tnOccurrence>
* : Specifies which occurrence, first, second, third,
* : and so on, of <tcToSearch> to search for
* : in <tcString>.
* : By default, frAt() searches for the first occurrence
* : of <tcToSearch> (tnOccurrence = 1).
*Returns : Numeric. frAt() returns an integer indicating the
* : position of the first character for a
* : character expression or memo field within another
* : character expression or memo field,
* : beginning from the leftmost character. If the
* : expression or field is not found, or if
* : <tnOccurrence> is greater than the number of
* : times <tcToSearch> occurs in <tcString>, frAt()
* : returns 0.
68.4. frAddBs() function 867

Ring Documentation, Release 1.14
68.6
*Syntax : lnPos = frAtC(tcToSearch, tcString, tnOccurrence)
*Description : Searches a character expression for the occurrence
* : of another character expression
* : without regard for the case of these two expressions.
* :
*Arguments : <tcToSearch>
* : Specifies the character expression to search
* : for in <tcString>.
* : <tcString>
* : Specifies the character expression to search
* : for <tcToSearch>.
* : <tnOccurrence>
* : Specifies which occurrence, first, second, third,
* : and so on, of <tcToSearch> to search for
* : in tcString.
* : By default, frAtC() searches for the first occurrence
* : of <tcToSearch> (tnOccurrence = 1).
*Returns : Numeric. frAtC() returns an integer indicating the
* : position of the first character for a
* : character expression or memo field within
* : another character expression or memo field,
* : beginning from the leftmost character. If the
* : expression or field is not found, or if
* : <tnOccurrence> is greater than the number of
* : times <tcToSearch> occurs in <tcString>, frAtC()
* : returns 0.
68.7
*Syntax : lcReturnValue = frChr(tnExpression)
*Description : Returns the character associated with the specified numeric
* : ANSI code.
*Arguments : <tnExpression>
* : Specifies a number between 0 and 255 whose equivalent ANSI
* : character frChr() returns.
*Returns : <lcReturnValue>
* : Returns a single character corresponding to the numeric
* : position of the character in the
* : character table of the current code page.
* :
*Remarks : tnExpression must be between 0 and 255
68.6. frAtC() function 868

Ring Documentation, Release 1.14
68.8
*Syntax : llReturnValue = frEmpty(tuExpression)
*Description : Determines whether an expression evaluates to empty.
* :
*Arguments : <tuExpression>
* : Specifies the expression that EMPTY() evaluates.
* : You can specify an expression with Character,
* : Numeric, or logical type.
* :
*Returns : <llReturnValue> Logical
68.9
*Syntax : llReturnValue = frFile(tcFileName, tnFlag)
*Description : Checks if the specified file exists on disk.
* :
*Arguments : <tcFileName>
* : Specifies the name of the file to check.
* : tcFileName must include
* : the file extension. You can include a path with
* : the file name to
* : search for a file in a directory or on a drive
* : other than the current directory or drive.
* :
* : <tnFlag>
* : tnFlag was included for future compatibility.
* : In this version, It always returns true whenever
* : the file exists on disk.
*Returns : <llReturnValue> Logical
* : True if file exists on disk.
* : False if file doesnt exist on disk.
68.10
*Syntax : lcReturnValue = frFileToStr(tcFileName)
*Description : Returns the contents of a file as a character string.
* :
*Arguments : <tcFileName>
* : Specifies the name of the file whose contents are
* : returned as a character
* : string. If the file is in a directory other than
* : the current default directory,
* : include a path with the file name.
* :
*Returns : <lcReturnValue>
* : A character string with the content of the specified file.
* :
68.8. frEmpty() function 869

Ring Documentation, Release 1.14
68.11
*Syntax : lcReturnValue = frStr(tnValue, tnLen, tnDec)
*Description : Returns the character equivalent of a numeric expression.
* :
*Arguments : <tnValue>
* : Specifies the numeric expression to evaluate.
* :
* : <tnLen>
* : Specifies the length of the character string returned.
* : If tnLen is 0, tnLen defaults to 10 characters.
* : If tnLen < 0 returns one string with same length as the number.
* : Note
* : If the expression contains a decimal point,
* : the length includes one character for
* : the decimal point and one character
* : for each digit in the character string.
* :
* : <tnDec>
* : Specifies the number of decimal places in the
* : character string returned.
* : To specify the number of decimal places using
* : tnDec, you must include nLength. If nDecimalPlaces is omitted,
* : the number of decimal places defaults to zero (0).
* :
*Returns : Character data type. frStr() returns a character string
* : equivalent to the specified numeric expression.
* : Depending on certain conditions, frStr() can return the following:
* : If you specify fewer decimal places than exist in tnValue,
* : the return value is rounded up. To round results to the nearest
* : decimal place instead of upward, include the ROUND( ) function.
* : For more information, see ROUND( ) Function.
* : If nExpression is an integer, and nLength is less than
* : the number of digits in nExpression, frStr( ) returns a string of
* : asterisks, indicating numeric overflow.
* : If nExpression contains a decimal point, and nLength is equal
* : to or less than the number of digits to the left of the decimal
* : point, frStr( ) returns a string of asterisks,
* : indicating numeric overflow.
* : If nLength is greater than the length of the value evaluated
* : by nExpression, frStr( ) returns a character string padded with
* : leading spaces.
* : If nExpression has Numeric or Float type, and nLength
* : is less than the number of digits in nExpression, and , frStr( )
* : returns a value using scientific notation.
68.11. frStr() function 870

Ring Documentation, Release 1.14
68.12
*Syntax : tuReturnValue = frSetIfEmpty(tuValue, tuNewValue)
*Description : Set a Value into a variable if the variable
* : value is empty, null or zero.
*Arguments : <tuValue>
* : The value to evaluate.
* :
* : <tuNewValue>
* : The value to set if tuValue is empty.
* :
*Returns : tuNewValue if tuValue is empty, otherwise
* : returns the original value.
*Remarks : This function doesnt exist in VFP.
68.13
*Syntax : lcReturnValue = frSpace(tnSpaces)
*Description : Returns a character string composed of a
* : specified number of spaces.
*Arguments : <tnSpaces>
* : Specifies the number of spaces that frSpace() returns.
* :
*Returns : <lcReturnValue>
* : Character
68.14
*Syntax : llReturnValue = frInList(tuExpression, taList)
*Description : Determines whether an expression matches another
* : expression in a set of expressions.
*Arguments : <tuExpression>
* : Specifies the expression frInList() searches for in the List.
* :
* : <taList>
* : Specifies the List of expressions to search.
* : You must include at least one element in the list.
* : The expressions in the list of expressions neednt to be
* : of the same data type.
* :
*Returns : <luReturnValue> Null or logical value.
68.12. frSetIfEmpty() function 871

Ring Documentation, Release 1.14
68.15
*Syntax : lcReturnValue = frForcePath(tcFileName, tcPath)
*Description : Returns a file name with a new path name
* : substituted for the old one.
*Arguments : <tcFileName>
* : Specifies the file name (with or without a path or extension),
* : which will get a new path.
* : <tcPath>
* : Specifies the new path for tcFileName.
* :
*Returns : <lcReturnValue>
* : Returns a file name with a new path name
* : substituted for the old one.
68.16
Syntax : lcReturnValue = frAllTrim(tcExpression, tcCharacter)
68.17
Syntax : lcRet = frLTrim(tcExpression, tcCharacter)
68.18
*Syntax : lcReturnValue = frJustDrive(tcPath)
*Description : Returns the drive letter from a complete path.
* :
*Arguments : <tcPath>
* : Specifies the complete path name for
* : which you want only the drive.
*Returns : <lcReturnValue>
* : Returns the drive letter from a complete path.
68.19
*Syntax : lcReturnValue = frJustExt(tcPath)
*Description : Returns the characters of a file extension
* : from a complete path.
*Arguments : <tcPath>
* : Specifies the name, which may include the full path,
* : of the file for which you want only the extension.
*Returns : <lcReturnValue>
* : Returns the drive characters of a file extension
* : from a complete path.
68.15. frForcePath() function 872

Ring Documentation, Release 1.14
68.20
*Syntax : lcReturnValue = frJustStem(tcPath)
*Description : Returns the stem name (the file name before the extension)
* : from a complete path and file name.
*Arguments : <tcPath>
* : Specifies the name (including path) of the file
* : for which you want only the stem.
*Returns : <lcReturnValue>
* : Returns the stem name of a file from a complete path.
68.21
Syntax : lcRet = frRTrim(tcExpression, tcCharacter)
68.22
Syntax : tcReturnValue = frJustPath(tcExpression)
68.23
Syntax : tcReturnValue = frForceExt(tcFileName, tcNewExtension)
68.24
Syntax : tnReturnValue = frALines(taList, tcExpression, tcSeparator)
68.25
Syntax : tcReturnValue = frJustFName(tcExpression)
68.26
Syntax : tcReturnValue = frPadL(tcString, tnLen, tcChar)
68.20. frJustStem() function 873

Ring Documentation, Release 1.14
68.27
Syntax : tcReturnValue = frPadR(tcString, tnLen, tcChar)
68.28
*Syntax : tcReturnValue = frProper(tcExpression)
*Description : Returns from a character expression a string
* : capitalized as appropriate for proper names.
*Arguments : <tcExpression>
* : Specifies the character expression from which
* : frProper() returns a capitalized character string.
*Returns : <tcReturnValue>
68.29
Syntax : tcReturnValue = frReplicate(tcString, tnTimes)
68.30
Syntax : tnReturnValue = frLen(tcString)
68.31
*Syntax : tcReturnValue = frStuff(tcExpression, tnStartRep,
tnCharRep, tcToReplace)
*Description : Returns a new character string replaced by a
* : specified number of characters in a character
* : expression with another character expression.
* :
*Arguments : <tcExpression>
* : Specify the character expression in which the replacement occurs.
* :
* : <tnStartRep>
* : Specify the position in <tcExpression> where the replacement begins.
* :
* : <tnCharRep>
* : Specifies the number of characters to be replaced.
* : If <tnCharRep> is 0, the replacement string
* : <tcToReplace> is inserted into <tcExpression>.
* :
* : <tcToReplace>
* : Specifies the replacement character expression.
* : If <tcToReplace> is an empty string, the number of
* : characters specified by <tnCharRep> are removed from <tcExpression>.
(continues on next page)
68.27. frPadR() function 874

Ring Documentation, Release 1.14
(continued from previous page)
* :
*Returns : Character
68.32
Syntax : tcReturnValue = frSubStr(tcString, tnInitialPosition, tnNumberBytes)
68.33
Syntax : tcReturnValue = frStrTran(tcString, tcOldString, tcNewString)
68.34
*Syntax : lcRet = frListToString(taList)
*Remarks : This function doesnt exist in VFP.
68.35
Syntax : lnInt = frInt(tnExpression)
68.36
*Syntax : laList = frStringToList(tcExpression)
*Remarks : This function doesnt exist in VFP.
68.37
*Syntax : luReturnValue = frIIf(tlExpression, tuReturnIfTrue, tuReturnIfFalse)
*Description : Returns one of two values depending on the
* : value of a logical expression.
*Arguments : <tlExpression>
* : Specifies the logical expression that frIIf() evaluates.
* :
* : <tuReturnTrue>, <tuReturnFalse>
* : If tlExpression evaluates to True, tuReturnIfTrue is
* : returned and tuReturnIfFalse is not evaluated.
* : If tlExpression evaluates to False or Null, tuReturnIfFalse is
* : returned and tuReturnIfTrue is not evaluated.
* :
*Returns : <luReturnValue> Defined by <tuReturnIfTrue> or <tuReturnIfFalse>
68.32. frSubStr() function 875

Ring Documentation, Release 1.14
68.38
*Syntax : luReturnValue = frVal(tcExpression)
*Description : Returns a numeric value from a character expression
* : composed of numbers
*Arguments : <tcExpression>
* : Specifies a character expression composed of up to 16 numbers.
* :
*Returns : <tnValue>
* : Return a numeric value.
68.39
*Syntax : luReturnValue = frBetween(tuTestValue, tuLowValue, tuHighValue)
*Description : Determines whether the value of an expression
* : is inclusively between the
* : values of two expressions of the same type.
* :
*Arguments : <tuTestValue>
* : Specifies an expression to evaluate.
* :
* : <tuLowValue>
* : Specifies the lower value in the range.
* :
* : <tuHighValue>
* : Specifies the higher value in the range.
* :
*Returns : <luReturnValue>
* : Returns a logical oder null value.
68.40
*Syntax : frSetSeparatorTo(tuExpression)
*Description : Specifies the character for the numeric place separator.
* :
*Arguments : <tuExpression>
* : Specifies the character for the numeric place separator.
* :
* : Use frSetSeparatorTo() to change the numeric place
* : separator from de default, for example space " " or a comma ",".
* : Issue frSetSeparatorTo(Null) to reset the value to its default.
* :
*Returns : None
68.38. frVal() function 876

Ring Documentation, Release 1.14
68.41
*Syntax : tcReturnValue = frTransform(tuExpression, tcFormatCodes)
*Description : Returns a character string from an expression in a
* : format determined by a format code.
*Arguments : <tuExpression>
* : Specifies the expression to format.
* :
* : <tcFormatCodes>
* : Specifies one or more format codes that determine how to
* : format the expression.
* :
*Returns : <tcReturnValue>
The following table lists the available format codes for tcFormatCodes.
--------------------------------------------------------------------------
Format Code Description
--------------------------------------------------------------------------
@! Converts an entire character string to uppercase.
@T Trims leading and trailing spaces from character values.
@B Left-justifies Numeric data within the display region.
@L Pads numeric and string data with leading zeros.
@C Appends CR to positive numeric values to indicate a credit.
@X Appends DB to negative numeric values to indicate a debit.
--------------------------------------------------------------------------
68.42
*Syntax : lcRet = frVarType(tuExpression)
*Description : Returns the data type of an expression.
* :
*Arguments : <tuExpression>
* : Expecifies the expression for which the data type is returned.
* : frVartype() returns a
* : single character indicating the data type of the expression.
* : The following table lists the characteres that frVarType()
* : returns for each data type.
* :
* : ------------------- -------------------------------------
* : Return Value Data Type
* : ------------------- -------------------------------------
* : C Character
* : N Numeric
* : A List
* : O Object
* : U Undefined type
* : ------------------- -------------------------------------
* :
*Returns : Character
68.41. frTransform() function 877

Ring Documentation, Release 1.14
68.43
Load "foxring.ring"
mf = new frFunctions
/*---------------------------------------------------------- */
*frProper() samples
/*---------------------------------------------------------- */
lcStr1 = "ring is a good language"
?mf.frProper(lcStr1)
?mf.frProper(Upper(lcStr1))
/*---------------------------------------------------------- */
*frStuff() samples
/*---------------------------------------------------------- */
lcStr1 = "abcdefghijklm"
lcStr2 = "12345"
// insert
?mf.frStuff(lcStr1, 4, 0, lcStr2)
// replace
?mf.frStuff(lcStr1, 4, 3, lcStr2)
// delete
?mf.frStuff(lcStr1, 4, 6, "")
// replace and insert
?mf.frStuff(lcStr1, 4, 1, lcStr2)
// replace and delete
?mf.frStuff(lcStr1, 4, 4, lcStr2)
// replace, delete rest
?mf.frStuff(lcStr1, 4, Len(lcStr1), lcStr2)
/*---------------------------------------------------------- */
?mf.frAbs(-45)
?mf.frAbs(10-30)
?mf.frAbs(30-10)
lcNumber1 = 40
lcNumber2 = 2
?mf.frAbs(lcNumber2-lcNumber1)
lcCompletFileName = "C:ing\docs\source\contribute.txt"
?mf.frFile(lcCompletFileName, Null)
if mf.frFile(lcCompletFileName, Null) {
?mf.frFileToStr(lcCompletFileName)
(continues on next page)
68.43. Example 878

Ring Documentation, Release 1.14
(continued from previous page)
else
?"File does not exist"
}
lcNewPath = "C:ing_2\docs\source\"
?mf.frJustExt(lcCompletFileName)
?mf.frJustDrive(lcCompletFileName)
?mf.frJustStem(lcCompletFileName)
?mf.frForcePath(lcCompletFileName, lcNewPath)
?mf.frTransform(" Ring is a good language ",
"@! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
?mf.frAllTrim(" Ring is a good language ", Null)
?mf._version
lnValue = 3125.54
?mf.frTransform(lnValue, "@B")+ "Euros"
?mf.frTransform(lnValue, "@C 9999,999,999,999.999")
mf.frSetSeparatorTo(" ")
?mf.frTransform(lnValue, "9999,999,999,999.999")
?mf.frInt(lnValue)
?mf.frForceExt("teste", "dbf")
// Format "@L" Added into frTransform() function
?mf.frTransform("123", "@L 999999")
?mf.frTransform(123, "@L 999999")
68.43. Example 879

CHAPTER
SIXTYNINE
BIGNUMBER LIBRARY
In this chapter we will learn about using the Big Number library.
69.1
Before using the next function load the bignumber.ring library
load"bignumber.ring"
# Use Big Number library functions
69.2
Using the BigNumber library we can do arithmetic operations on huge numbers.
Example:
load"bignumber.ring"
num162345678901234567891678345123456789" ### Big
num21237894567890123419871236545" ### Small
num364" ### Divide Small
num4765432"
num53" ### Power
?Add big numbers:"
a1 newBigNumber(num1) a1.Print()
a2 newBigNumber(num2) a2.Print()
a3
?Substract big numbers:"
a1 newBigNumber(num1) a1.Print()
a2 newBigNumber(num2) a2.Print()
a3
?Multiply big numbers:"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num2) a2.print()
a3 *a2 a3.print()
?Divide big numbers:"
(continues on next page)
880

Ring Documentation, Release 1.14
(continued from previous page)
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num2) a2.print()
a3
?Divide big numbers: by very small number"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num3) a2.print()
a3
?Power of big number:"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num5) a2.print()
a3
Output:
Add big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
62345680139129135781801764994693334
Substract big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
52345687663340000001554925252220244
Multiply big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
77177377243260150103462178714197454736432472780119682305154005
Divide big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
50364288
Divide big numbers: by very small number
62345678901234567891678345123456789
64
974151232831790123307474142554012
Power of big number:
62345678901234567891678345123456789
3
242336636261471172092347146031727004 (Output continue in next line)
371698195628343934238988256152289508 (Output continue in next line)
493964611043228971692389860897069
69.2. Examples 881

Ring Documentation, Release 1.14
69.3
The library contains the next functions
FuncAdd(num1,num2)
FuncSubtract(num1,num2)
FuncCompare(num1,num2)
FuncDivide(num1,num2)
FuncMultiply(num1,num2)
FuncPower(num1,num2)
FuncBinaryToDecimal(num1)
FuncDecimalToBinary(num1)
printBinaryDigits(binList)
printDecimalDigits(decList)
69.4
The library contains the next class
classBigNumber
funcinit aPara
funcoperator cOperator, Para
funcprint
funcvalue
69.5
You can see the library source code in : ring/libraries/bignumber folder
Source Code :
69.3. BigNumber Functions 882

CHAPTER
SEVENTY
USING RINGLIBCURL
In this chapter we will learn about using RingLibCurl
70.1
Example:
load"libcurl.ring"
curl
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,)
curl_easy_setopt(curl, CURLOPT_URL,http://ring-lang.sf.net")
curl_easy_perform(curl)
curl_easy_cleanup(curl)
70.2
Example:
load"libcurl.ring"
curl
cPostThispage=4&Number1=4&Number2=5"
curl_easy_setopt(curl, CURLOPT_URL,http://localhost/ringapp/index.ring?page=3")
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, cPostThis)
curl_easy_perform(curl)
curl_easy_cleanup(curl)
883

Ring Documentation, Release 1.14
70.3
Example:
load"libcurl.ring"
see"Enter Email : give$login_email
See"Enter Password : give$login_pass
curl
curl_easy_setopt(curl, CURLOPT_URL,https://www.facebook.com/login.php)
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,charset_test=j+
email=+urlencode($login_email)+&pass=+
urlencode($login_pass)+&login=Login)
curl_easy_setopt(curl, CURLOPT_POST,)
curl_easy_setopt(curl, CURLOPT_HEADER,)
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,)
curl_easy_setopt(curl, CURLOPT_COOKIEJAR,cookies.txt")
curl_easy_setopt(curl, CURLOPT_COOKIEFILE,cookies.txt")
curl_easy_setopt(curl, CURLOPT_USERAGENT,Mozilla/5.0 (Windows; U;"+
"")
curl_easy_setopt(curl, CURLOPT_REFERER,http://www.facebook.com")
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE)
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST,)
mylist NULL,Accept-Charset:tf-8)
curl_slist_append(mylist,Accept-Language:n-us,en;q=0.7,bn-bd;q=0.3)
curl_slist_append(mylist,Accept:ext/xml,application/xml,+
application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png, */*;q=0.5)
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, mylist)
curl_easy_setopt(curl, CURLOPT_COOKIESESSION, false)
curl_easy_perform(curl)
curl_easy_cleanup(curl)
FuncURLEncode cStr
cOut"
forxincStr
ifisalnum(x)
cOut=
butx
cOut=+"
else
cOut=%"+str2hex(x)
ok
next
returncOut
70.3. Facebook Login 884

Ring Documentation, Release 1.14
70.4
Example:
load"libcurl.ring"
curl
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,)
curl_easy_setopt(curl, CURLOPT_URL,http://ring-lang.sf.net")
cOutput
See"Output:"
seecOutput
curl_easy_cleanup(curl)
70.5
Example:
Load"libcurl.ring"
### Part 1 --- Get Crumb and Cookie -----------------------------------------
See"Start curl_easy_init():+
curl ### >>> HANDLE >>> 01006BD0 CURL 0
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,)
curl_easy_setopt(curl, CURLOPT_COOKIEJAR,cookies.txt")
curl_easy_setopt(curl, CURLOPT_COOKIEFILE,cookies.txt")
curl_easy_setopt(curl, CURLOPT_URL,https://finance.yahoo.com/quote/AMZN/
˓→history")
### HTML Data >>> STDOUT Window, Use curl_easy_perform_silent >>> String
cOutput ### GO Get Data >>> String
### Extract Crumb from data
### "CrumbStore":{"crumb":"abcdefghijk"},
ifcOutput= NULL
newStr1"CrumbStore":{"crumb":"&#3627409170;
˓→)
nPosS:"&#3627409170; ### Start of crumb -2
nPosE"}&#3627409170; ### End of crumb
nCount2 ### size of crumb
myCrumb2, nCount)
See"myCrumb.: |"+"|"nl
### UniCode "\u002F" replace it with "/"
(continues on next page)
70.4. Save Output to String 885

Ring Documentation, Release 1.14
(continued from previous page)
ifsubstr( myCrumb,\u002F")
myCrumb\u002F",/")
See"myCrumb2: |"+"|"+
ok
else
See"No Connectivity to Yahoo. Looking for Cookie and Crumb."nlnl
ok
### Part 2 --- Send URL with Crumb, and Cookie ---------------------------------------
˓→--
### Send URL+Crumb to Yahoo to fetch 1st stock history data,
$urlhttps://query1.finance.yahoo.com/v7/finance/download/AMZN"+
"?period1=1277856000&period2=1498777545&interval=1wk"
"&events=history&crumb="
curl_easy_setopt(curl, CURLOPT_URL,url);
cStr
SeecStr
curl_easy_cleanup(curl) ### REMEMBER to CLOSE CURL
Output:
myCrumb.:sEEeW97mxvN|
Date,Open,High,Low,Close,Adj Close,Volume
2010-07-05,110.650002,117.480003,109.000000,117.260002,117.260002,21000400
2010-07-12,117.809998,124.879997,117.320000,118.489998,118.489998,29407300
2010-07-19,118.379997,121.250000,105.800003,118.870003,118.870003,74252100
70.5. Get Stock Data From Yahoo 886

CHAPTER
SEVENTYONE
RINGLIBCURL FUNCTIONS REFERENCE
71.1
In this chapter we have a list of the supported functions by this extension
71.2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
887

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
71.2. Reference 888

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
71.2. Reference 889

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
71.2. Reference 890

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
71.2. Reference 891

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
71.2. Reference 892

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
71.2. Reference 893

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *curl_easy_init(void)
•
• *handle, CURLoption option, int)
• *handle, CURLoption option, const char*)
• *handle, CURLoption option, void*)
• *handle, CURLoption option, CURLLIST*)
•
• *curl_easy_perform_silent(CURL * easy_handle )
• *handle, CURLINFO info, char**urlp)
• *handle, CURLINFO info, long*codep)
• *handle, CURLINFO info, double*timep)
• *handle, CURLINFO info, CURLLIST**engine_list)
• *handle, CURLINFO info, struct curl_certinfo*chainp)
• *handle, CURLINFO info, struct curl_tlssessioninfo**session)
• *curl_version(void)
• *now )
71.2. Reference 894

Ring Documentation, Release 1.14
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char*, CURLformoption, const char*, CURLformoption)
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char*, CURLformoption, const char*,CURLformoption, const char*, CURLformoption)
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char*, CURLformoption, void*, CURLformoption)
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char*, CURLformoption, void*,CURLformoption, long , CURLformoption)
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char, CURLformoption, void *,CURLformoption, long , CURLformoption, const char, CURL-
formoption)
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char*, CURLformoption, const char*,CURLformoption, void * , CURLformoption, long ,
CURLformoption)
• **rstitem, struct curl_httppost**lastitem, CURLfor-
moption, const char*, CURLformoption, struct curl_forms [], CURLformoption)
•
• *curl_slist_append(CURLLIST * list, const char * string )
•
• *curl_easy_escape( CURL * curl , const char * string , int length )
• *curl_easy_unescape( CURL * curl , const char * url , int inlength , int * outlength )
71.2. Reference 895

CHAPTER
SEVENTYTWO
RINGSOCKETS EXTENSION
In this chapter we will learn about using the RingSockets extension.
72.1
Example (TCP Server Code):
load"sockets.ring"
sock0)
bind(sock,"127.0.0.1",5050)
listen(sock,5)
ns
send(ns,"Hello Client")
msg1024)
?Client Say >>
close(ns)
close(sock)
?socket connection closed"
72.2
Example (TCP Client Code):
load"sockets.ring"
sock
connect(sock,"127.0.0.1",5050)
send(sock,"Hello Server")
msg1024)
?Server Say >>
close(sock)
?socket connection closed"
896

Ring Documentation, Release 1.14
72.3
The next functions are provided by this extension
socket(nAddressFamily, nConnectionType) -> SocketHandle
bind(pSocketHandle, cHost , nPort)
listen(pSocketHandle, nBacklog)
accept(pSocketHandle) -> pConnectionHandle
send(pConnectionHandle|pSocketHandle,cMessage)
sendto(pSocketHandle,cMessage)
recv(pConnectionHandle|pSocketHandle,nBuffer) -> cData
recvfrom(pSocketHandle, nBuffer) -> cData
connect(pSocketHandle, cHost , nPort) -> return <0> if successful
close(pSocketHandle|pConnectionHandle)
gethostbyname(cHostName) -> cIPAddress
gethostbyaddr(cIPAddress) -> aListOfHostInfo
gethostname() -> cHostName
getservbyname(cName) -> nPort
getservbyport(nPort) -> cName
Example:
load"sockets.ring"
host"google.com")
?
line()
?
line()
?
line()
?"ftp")
line()
?21)
funcline"=",30)
72.4
Address Family:
AF_INET # mean use IPV4
AF_INET6 # ........ IPV6
Connection type:
SOCK_STREAM # mean use TCP Protocol
SOCK_DGRAM # ........ UDP ........
72.3. Functions 897

CHAPTER
SEVENTYTHREE
THREADS EXTENSION
In this chapter we will learn about using the Threads extension.
73.1
Example (1):
load"threads.ring"
funcmain
t
thrd_create(t,"Hello()")
res
thrd_join(t, :res)
funcHello
?Message from the Hello() function"
73.2
Example (2):
load"threads.ring"
funcmain
t
thrd_create(t,"Hello()")
res
thrd_join(t, :res)
t2
thrd_create(t2,"Hello2()")
res2
thrd_join(t2, :res2)
?done
(continues on next page)
898

Ring Documentation, Release 1.14
(continued from previous page)
funcHello
?Message from the Hello() function"
funcHello2
?Message from the Hello2() function"
Example (3):
load"threads.ring"
funcmain
nThreads
aList list(nThreads)
forx=1tonThreads
aList[x]
thrd_create(aList[x],"Hello("+x+")")
next
forx=1tonThreads
res=
thrd_join(aList[x],:res)
next
?Done
shutdown()
funcHello x
forr=1to100
?Message from the Hello("+x+") function"
next
Example (4):
load"threads.ring"
funcmain
nThreads
aList list(nThreads)
forx=1tonThreads
aList[x]
thrd_create(aList[x],"Hello("+x+")")
next
fork=1tonThreads
?***Before join: ***"
res
thrd_join(aList[K],:res)
?***After join: ***"
next
(continues on next page)
73.2. More Examples 899

Ring Documentation, Release 1.14
(continued from previous page)
?
funcHello x
forr=1to100
?("+r+") Message from the Hello("+x+") function"
next
73.3
Constants:
•
•
•
•
•
•
•
•
•
•
•
•
Functions:
• *mtx, int type)
• *mtx)
• *mtx)
• *mtx, const struct timespec*ts)
• *mtx)
• *mtx)
• *cond)
• *cond)
• *cond)
• *cond)
• *cond, mtx_t*mtx)
• *cond, mtx_t*mtx, const struct timespec*ts)
• *thr, const char*cEvent)
73.3. Reference 900

Ring Documentation, Release 1.14
•
•
•
•
• *res)
• *duration, struct timespec*remaining)
•
•
• *tss_get(tss_t key)
• *val)
73.3. Reference 901

CHAPTER
SEVENTYFOUR
RINGLIBUI EXTENSION
In this chapter we will learn about using the RingLibUI extension.
This extension provides complete support for Libui
Using this extension we can develop and distribute lightweight GUI Applications using Ring (Less than 1 MB)
Runtime les and their size (For Ring 1.14)
•
•
•
•
•
74.1
load"libui.ring"
oWindowHello, World",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
btn1"SayHello")
uiButtonOnClicked(btn1,"sayHello()")
btn2"Close")
uiButtonOnClicked(btn2,"closeApp()")
g) uiWindowSetChild(oWindow, g)
uiGridAppend(g, btn1,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, btn2,,,,,, uiAlignFill,, uiAlignFill)
uiControlShow( oWindow )
uiMain()
funcsayHello
uiMsgBox(oWindow,"Hi","Hello")
funccloseApp
uiQuit()
902

Ring Documentation, Release 1.14
Screen Shots:
74.1. Hello World 903

Ring Documentation, Release 1.14
74.2
load"libui.ring"
oWindowSay Hello",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
lbl1"Name:)
text1
btn1"SayHello")
uiButtonOnClicked(btn1,"sayHello()")
btn2"Close")
uiButtonOnClicked(btn2,"closeApp()")
lbl2"")
g) uiWindowSetChild(oWindow, g)
uiGridAppend(g, lbl1,,,,,, uiAlignCenter,, uiAlignCenter)
uiGridAppend(g, text1,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, btn1,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, btn2,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, lbl2,,,,,, uiAlignCenter,, uiAlignCenter)
(continues on next page)
74.2. Say Hello 904

Ring Documentation, Release 1.14
(continued from previous page)
uiControlShow( oWindow )
uiMain()
funcsayHello
uiLabelSetText(lbl2,"Hello
funccloseApp
uiQuit()
Screen Shot:
74.3
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
# Global Variables
slider NULL
spinbox NULL
pBar NULL
entryOpen NULL
entrySave NULL
# Main Window
(continues on next page)
74.3. Control Gallery 905

Ring Documentation, Release 1.14
(continued from previous page)
mainwin"libui Control Gallery",,,)
uiWindowOnClosing(mainwin,onClosing()")
tab
uiWindowSetChild(mainwin, tab)
uiWindowSetMargined(mainwin,)
uiTabAppend(tab,Basic Controls", makeBasicControlsPage())
uiTabSetMargined(tab,,)
uiTabAppend(tab,Numbers and Lists", makeNumbersPage())
uiTabSetMargined(tab,,)
uiTabAppend(tab,Data Choosers", makeDataChoosersPage())
uiTabSetMargined(tab,,)
uiControlShow(mainwin)
uiMain()
funconClosing
uiQuit()
funcmakeDataChoosersPage
hbox
uiBoxSetPadded(hbox,)
vbox
uiBoxSetPadded(vbox,)
uiBoxAppend(hbox, vbox,)
uiBoxAppend(vbox,
uiNewDatePicker(),
0)
uiBoxAppend(vbox,
uiNewTimePicker(),
0)
uiBoxAppend(vbox,
uiNewDateTimePicker(),
0)
uiBoxAppend(vbox,
uiNewFontButton(),
0)
uiBoxAppend(vbox,
uiNewColorButton(),
0)
uiBoxAppend(hbox,
uiNewVerticalSeparator(),
0)
vbox
uiBoxSetPadded(vbox,)
uiBoxAppend(hbox, vbox,)
(continues on next page)
74.3. Control Gallery 906

Ring Documentation, Release 1.14
(continued from previous page)
grid
uiGridSetPadded(grid,)
uiBoxAppend(vbox, grid,)
button"Open File")
entryOpen
uiEntrySetReadOnly(entryOpen,)
uiButtonOnClicked(button,onOpenFileClicked()")
uiGridAppend(grid, button,
0,,,,
0, uiAlignFill,, uiAlignFill)
uiGridAppend(grid, entryOpen,
1,,,,
1, uiAlignFill,, uiAlignFill)
button"Save File")
entrySave
uiEntrySetReadOnly(entrySave,)
uiButtonOnClicked(button,onSaveFileClicked()")
uiGridAppend(grid, button,
0,,,,
0, uiAlignFill,, uiAlignFill)
uiGridAppend(grid, entrySave,
1,,,,
1, uiAlignFill,, uiAlignFill)
msggrid
uiGridSetPadded(msggrid,)
uiGridAppend(grid, msggrid,
0,,,,
0, uiAlignCenter,, uiAlignStart)
button"Message Box")
uiButtonOnClicked(button,onMsgBoxClicked()")
uiGridAppend(msggrid, button,
0,,,,
0, uiAlignFill,, uiAlignFill)
button"Error Box")
uiButtonOnClicked(button,onMsgBoxErrorClicked()")
uiGridAppend(msggrid, button,
1,,,,
0, uiAlignFill,, uiAlignFill)
returnhbox
funcmakeNumbersPage
hbox
uiBoxSetPadded(hbox,)
group"Numbers")
uiGroupSetMargined(group,)
uiBoxAppend(hbox, group,)
vbox
uiBoxSetPadded(vbox,)
uiGroupSetChild(group, vbox)
(continues on next page)
74.3. Control Gallery 907

Ring Documentation, Release 1.14
(continued from previous page)
spinbox0,)
slider0,)
pbar
uiSpinboxOnChanged(spinbox,onSpinboxChanged()")
uiSliderOnChanged(slider,onSliderChanged()")
uiBoxAppend(vbox, spinbox,)
uiBoxAppend(vbox, slider,)
uiBoxAppend(vbox, pbar,)
ip
uiProgressBarSetValue(ip,1)
uiBoxAppend(vbox, ip,)
group"Lists")
uiGroupSetMargined(group,)
uiBoxAppend(hbox, group,)
vbox
uiBoxSetPadded(vbox,)
uiGroupSetChild(group, vbox)
cbox
uiComboboxAppend(cbox,Combobox Item 1")
uiComboboxAppend(cbox,Combobox Item 2")
uiComboboxAppend(cbox,Combobox Item 3")
uiBoxAppend(vbox, cbox,)
ecbox
uiEditableComboboxAppend(ecbox,Editable Item 1")
uiEditableComboboxAppend(ecbox,Editable Item 2")
uiEditableComboboxAppend(ecbox,Editable Item 3")
uiBoxAppend(vbox, ecbox,)
rb
uiRadioButtonsAppend(rb,Radio Button 1")
uiRadioButtonsAppend(rb,Radio Button 2")
uiRadioButtonsAppend(rb,Radio Button 3")
uiBoxAppend(vbox, rb,)
returnhbox
funcmakeBasicControlsPage
vbox
uiBoxSetPadded(vbox,)
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(vbox, hbox,)
uiBoxAppend(hbox,
uiNewButton("Button"),
0)
uiBoxAppend(hbox,
uiNewCheckbox("Checkbox"),
(continues on next page)
74.3. Control Gallery 908

Ring Documentation, Release 1.14
(continued from previous page)
0)
uiBoxAppend(vbox,
uiNewLabel("This is a label. Right now, labels can only span one line.
˓→"),
0)
uiBoxAppend(vbox,
uiNewHorizontalSeparator(),
0)
group"Entries")
uiGroupSetMargined(group,)
uiBoxAppend(vbox, group,)
entryForm
uiFormSetPadded(entryForm,)
uiGroupSetChild(group, entryForm)
uiFormAppend(entryForm,
"Entry",
uiNewEntry(),
0)
uiFormAppend(entryForm,
"Password Entry",
uiNewPasswordEntry(),
0)
uiFormAppend(entryForm,
"Search Entry",
uiNewSearchEntry(),
0)
uiFormAppend(entryForm,
"Multiline Entry",
uiNewMultilineEntry(),
1)
uiFormAppend(entryForm,
"Multiline Entry No Wrap",
uiNewNonWrappingMultilineEntry(),
1)
returnvbox
funconSpinboxChanged
s
uiSliderSetValue(slider, uiSpinboxValue(s));
uiProgressBarSetValue(pbar, uiSpinboxValue(s));
funconSliderChanged
s
uiSpinboxSetValue(spinbox, uiSliderValue(s));
uiProgressBarSetValue(pbar, uiSliderValue(s));
funconOpenFileClicked
filename
ifISNULL(filename)
(continues on next page)
74.3. Control Gallery 909

Ring Documentation, Release 1.14
(continued from previous page)
uiEntrySetText(entryOpen,(cancelled)")
return
ok
uiEntrySetText(entryOpen, filename)
uiFreeText(filename)
funconSaveFileClicked
filename
ifISNULL(filename)
uiEntrySetText(entrySave,(cancelled)")
return
ok
uiEntrySetText(entrySave, filename)
uiFreeText(filename)
funconMsgBoxClicked
uiMsgBox(mainwin,
"This is a normal message box.",
"More detailed information can be shown here.")
funconMsgBoxErrorClicked
uiMsgBoxError(mainwin,
"This message box describes an error.",
"More detailed information can be shown here.")
Screen Shot:
74.3. Control Gallery 910

Ring Documentation, Release 1.14
74.3. Control Gallery 911

Ring Documentation, Release 1.14
74.3. Control Gallery 912

Ring Documentation, Release 1.14
74.4
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
w"Hello",,,)
uiWindowSetMargined(w,)
b
uiBoxSetPadded(b,)
uiWindowSetChild(w, b)
e
uiMultilineEntrySetReadOnly(e,)
btn"Say Something")
uiButtonOnClicked(btn,saySomething()")
uiBoxAppend(b, btn,)
uiBoxAppend(b, e,)
uiTimer(1000,sayTime()")
uiWindowOnClosing(w,onClosing()")
uiControlShow(w)
uiMain()
funcsaySomething
uiMultilineEntryAppend(e,Saying something"+nl)
funcsayTime
uiMultilineEntryAppend(e, Time()+nl)
funconClosing
uiQuit()
Screen Shot:
74.4. Say Something 913

Ring Documentation, Release 1.14
74.5
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
# Create the Menubar
fileMenu"File")
newItemNew")
openItemOpen")
uiMenuAppendSeparator(fileMenu)
shouldQuitItemShould Quit")
quitItem
editMenu"Edit")
(continues on next page)
74.5. Using the Menubar 914

Ring Documentation, Release 1.14
(continued from previous page)
undoItemUndo")
uiMenuItemDisable(undoItem)
uiMenuAppendSeparator(editMenu)
checkItemCheck Me Test")
accelItemA&ccele&&rator T_es__t")
prefsItem
testMenu"Test")
enabledItemEnable Below Item")
uiMenuItemSetChecked(enabledItem,)
enableThisItemThis Will Be Enabled")
uiMenuItemOnClicked(enabledItem,enableItemTest(enableThisItem)")
forceCheckedItemForce Above Checked")
uiMenuItemOnClicked(forceCheckedItem,forceOn()")
forceUncheckedItemForce Above Unchecked")
uiMenuItemOnClicked(forceUncheckedItem,forceOff()")
uiMenuAppendSeparator(testMenu)
whatWindowItemWhat Window?")
uiMenuItemOnClicked(whatWindowItem,whatWindow()")
moreTestsMenu"More Tests")
quitEnabledItemQuit Item Enabled")
uiMenuItemSetChecked(quitEnabledItem,)
prefsEnabledItemPreferences Item
˓→Enabled")
uiMenuItemSetChecked(prefsEnabledItem,)
aboutEnabledItemAbout Item Enabled")
uiMenuItemSetChecked(aboutEnabledItem,)
uiMenuAppendSeparator(moreTestsMenu)
checkEnabledItemCheck Me Item Enabled
˓→")
uiMenuItemSetChecked(checkEnabledItem,)
multiMenu"Multi")
uiMenuAppendSeparator(multiMenu)
uiMenuAppendSeparator(multiMenu)
uiMenuAppendItem(multiMenu,Item && Item && Item")
uiMenuAppendSeparator(multiMenu)
uiMenuAppendSeparator(multiMenu)
uiMenuAppendItem(multiMenu,Item __ Item __ Item")
uiMenuAppendSeparator(multiMenu)
uiMenuAppendSeparator(multiMenu)
helpMenu"Help")
helpItemHelp")
aboutItem
uiMenuItemOnClicked(quitEnabledItem,enableItemTest(quitItem)")
uiMenuItemOnClicked(prefsEnabledItem,enableItemTest(prefsItem)")
uiMenuItemOnClicked(aboutEnabledItem,enableItemTest(aboutItem)")
uiMenuItemOnClicked(checkEnabledItem,enableItemTest(checkItem)")
# Create the Window
oWindowUsing the Menubar",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
(continues on next page)
74.5. Using the Menubar 915

Ring Documentation, Release 1.14
(continued from previous page)
uiControlShow( oWindow )
uiMain()
funcenableItemTest(data)
item
ifuiMenuItemChecked(item)
uiMenuItemEnable(data)
else
uiMenuItemDisable(data)
ok
funcforceOn
uiMenuItemSetChecked(enabledItem,)
funcforceOff
uiMenuItemSetChecked(enabledItem,)
funcwhatWindow
?menu item clicked on window
?
funccloseApp
uiQuit()
Screen Shot:
74.5. Using the Menubar 916

Ring Documentation, Release 1.14
74.6
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
Rectangle(0,, uiEventAreaWidth(), uiEventAreaHeight(), colorGray)
(continues on next page)
74.6. Drawing Sample 917

Ring Documentation, Release 1.14
(continued from previous page)
Rectangle(0,,,, colorWhite)
Rectangle(10,,,, colorRed)
Rectangle(30,,,, colorGreen)
Rectangle(60,,,, colorBlue)
# The Rectangle function is now part of RingLibUI as uiRectangle()
funcRectangle x,y,width,height,color
oContext
oBrush
oPath
uiDrawPathAddRectangle(oPath, x, y, width, height)
uiDrawPathEnd(oPath)
uiDrawFill(oContext, oPath, oBrush)
uiDrawFreePath(oPath)
funccloseApp
uiQuit()
Screen Shot:
74.6. Drawing Sample 918

Ring Documentation, Release 1.14
74.7
load"libui.ring"
oWindowDraw Gradient",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
uiRectangle(0,, nWidth, nHeight, colorBlue)
fory=0to255step2
customColor
uiRectangle(0, y, nWidth, y+1, customColor)
next
funccloseApp
uiQuit()
Screen Shot:
74.7. Draw Gradient 919

Ring Documentation, Release 1.14
74.8
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
datapoints list(10)
currentPoint1
//
xoffLeft *histogram margins */
yoffTop
xoffRight
yoffBottom
pointRadius
histogram NULL
(continues on next page)
74.8. Histogram 920

Ring Documentation, Release 1.14
(continued from previous page)
mainwin NULL
colorButton NULL
funcpointLocations width, height, xs, ys
xincr/ tomake the last point be at the end
yincr
fori to10
//getthe value of the point
n[i])
//=0 butn=0 toflip
n
xs[i] *i
ys[i] *n
next
funcconstructGraph width, height, extend
xs list(10)
ys list(10)
pointLocations(width, height, xs, ys)
path
uiDrawPathNewFigure(path, xs[1], ys[1])
fori to10
uiDrawPathLineTo(path, xs[i], ys[i])
next
ifextend
uiDrawPathLineTo(path, width, height)
uiDrawPathLineTo(path,, height)
uiDrawPathCloseFigure(path)
ok
uiDrawPathEnd(path)
returnpath
funcgraphSize clientWidth, clientHeight
graphWidth
graphHeight
return[graphWidth,graphHeight]
funchandlerDraw
//
Brush0)
setSolidBrush(brush, colorWhite,.0)
path
uiDrawPathAddRectangle(path,,, uiEventAreaWidth(), uiEventAreaHeight())
uiDrawPathEnd(path)
uiDrawFill(uiEventContext(), path, brush)
uiDrawFreePath(path)
//
aOut
graphWidth[1]
graphHeight[2]
sp
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_Thickness(sp,2)
(continues on next page)
74.8. Histogram 921

Ring Documentation, Release 1.14
(continued from previous page)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
//
setSolidBrush(brush, colorBlack,.0)
path
uiDrawPathNewFigure(path,
xoffLeft, yoffTop)
uiDrawPathLineTo(path,
xoffLeft, yoffTop
uiDrawPathLineTo(path,
xoffLeft
uiDrawPathEnd(path)
uiDrawStroke(uiEventContext(), path, brush, sp)
uiDrawFreePath(path)
//0,) is the top-left corner of the
˓→graph
m
uiDrawMatrixSetIdentity(m)
uiDrawMatrixTranslate(m, xoffLeft, yoffTop)
uiDrawTransform(uiEventContext(), m)
// getthe colorforthe graph itself andset up the brush
GraphR=0
GraphG=0
GraphB=0
GraphA=0
uiColorButtonColor(colorButton, :graphR,
:graphG,
:graphB,
:graphA)
uiSetBrushType(brush,uiDrawBrushTypeSolid)
uiSetBrushR(brush,graphR)
uiSetBrushG(brush,graphG)
uiSetBrushB(brush,graphB)
//->A below todifferent values forthe fillandstroke
// forthe graph below the graph line
path)
uiSetBrushA(brush, graphA)
uiDrawFill(uiEventContext(), path, brush)
uiDrawFreePath(path)
//
path)
uiSetBrushA(brush,graphA)
uiDrawStroke(uiEventContext(), path, brush, sp)
uiDrawFreePath(path)
//
ifcurrentPoint=1
xs list(10)
(continues on next page)
74.8. Histogram 922

Ring Documentation, Release 1.14
(continued from previous page)
ys list(10)
pointLocations(graphWidth, graphHeight, xs, ys)
path
uiDrawPathNewFigureWithArc(path,
xs[currentPoint], ys[currentPoint],
pointRadius,
0,.23,/
0)
uiDrawPathEnd(path)
// forthe histogram lines
uiDrawFill(uiEventContext(), path, brush)
uiDrawFreePath(path)
ok
funcinPoint x, y, xtest, ytest
// switch using a matrix
x=
y=
return(x=&
(x=&
(y=&
(y=
funchandlerMouseEvent
xs list(10)
ys list(10)
aOut
graphWidth[1]
graphHeight[2]
pointLocations(graphWidth, graphHeight, xs, ys)
e
eX
eY
fori=1to10
ifinPoint(eX, eY, xs[i], ys[i])
exit
ok
next
ifi/ not a point
i1
ok
currentPoint
uiAreaQueueRedrawAll(histogram)
funconDatapointChanged
uiAreaQueueRedrawAll(histogram)
funconColorChanged
uiAreaQueueRedrawAll(histogram);
funconClosing
(continues on next page)
74.8. Histogram 923

Ring Documentation, Release 1.14
(continued from previous page)
uiControlDestroy(uiControl(mainwin))
uiQuit()
return0
funcshouldQuit
uiControlDestroy(uiControl(mainwin))
funcmain
uiOnShouldQuit("shouldQuit()")
mainwin"Histogram Sample",,,)
uiWindowSetMargined(mainwin,)
uiWindowOnClosing(mainwin,onClosing()")
Brush0)
hbox
uiBoxSetPadded(hbox,)
uiWindowSetChild(mainwin, uiControl(hbox))
vbox
uiBoxSetPadded(vbox,)
uiBoxAppend(hbox, uiControl(vbox),)
srandom(clock());
fori=1to10
datapoints[i]0,)
uiSpinboxSetValue(datapoints[i], random())
uiSpinboxOnChanged(datapoints[i],onDatapointChanged()")
uiBoxAppend(vbox, uiControl(datapoints[i]),)
next
colorButton
setSolidBrush(brush, colorDodgerBlue,.0)
uiColorButtonSetColor(colorButton,
uiBrushR(brush),
uiBrushG(brush),
uiBrushB(brush),
uiBrushA(brush))
uiColorButtonOnChanged(colorButton,onColorChanged()")
uiBoxAppend(vbox, uiControl(colorButton),)
oAreaHandler"handlerDraw()","handlerMouseEvent()","","","
˓→")
histogram
uiBoxAppend(hbox, uiControl(histogram),)
uiControlShow(uiControl(mainwin))
uiMain()
Screen Shot:
74.8. Histogram 924

Ring Documentation, Release 1.14
74.9
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
# Global Variables
mainwin NULL
area NULL
handler NULL
fontButton NULL
alignment NULL
attrstr NULL
funcappendWithAttribute what, attr, attr2
nStart
nEnd
uiAttributedStringAppendUnattributed(attrstr, what)
uiAttributedStringSetAttribute(attrstr, attr, nStart, nEnd)
if!
uiAttributedStringSetAttribute(attrstr, attr2, nStart, nEnd)
ok
funcmakeAttributedString
attrstr"Drawing strings with libui is done with the
˓→uiAttributedString and uiDrawTextLayout objects."+nl+
(continues on next page)
74.9. Text Drawing 925

Ring Documentation, Release 1.14
(continued from previous page)
"uiAttributedString lets you have a variety of attributes:)
attr"Courier New")
appendWithAttribute("font family", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr18)
appendWithAttribute("font size", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr
appendWithAttribute("font weight", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr
appendWithAttribute("font italicness", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr
appendWithAttribute("font stretch", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr0.75,.25,.5,.75)
appendWithAttribute("text color", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr0.5,.5,.25,.5)
appendWithAttribute("text background color", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
attr
appendWithAttribute("underline style", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,,)
uiAttributedStringAppendUnattributed(attrstr,and)
attr
attr2.0,.0,.5,.
˓→0)
appendWithAttribute("underline color", attr, attr2)
uiAttributedStringAppendUnattributed(attrstr,.)
uiAttributedStringAppendUnattributed(attrstr,Furthermore, there are
˓→attributes allowing for)
attr
attr2,,,)
appendWithAttribute("special underlines for indicating spelling errors", attr,
˓→attr2)
uiAttributedStringAppendUnattributed(attrstr,)
uiAttributedStringAppendUnattributed(attrstr,and control over OpenType
˓→features such as ligatures (for instance,)
otf
uiOpenTypeFeaturesAdd(otf, ASCII(&#3627409170;l&#3627409170;), ASCII(&#3627409170;i&#3627409170;), ASCII(&#3627409170;g&#3627409170;), ASCII(&#3627409170;a&#3627409170;),)
attr
appendWithAttribute("afford", attr, NULL)
uiAttributedStringAppendUnattributed(attrstr,)
(continues on next page)
74.9. Text Drawing 926

Ring Documentation, Release 1.14
(continued from previous page)
uiOpenTypeFeaturesAdd(otf, ASCII(&#3627409170;l&#3627409170;), ASCII(&#3627409170;i&#3627409170;), ASCII(&#3627409170;g&#3627409170;), ASCII(&#3627409170;a&#3627409170;),)
attr
appendWithAttribute("afford", attr, NULL)
uiFreeOpenTypeFeatures(otf)
uiAttributedStringAppendUnattributed(attrstr,). ")
uiAttributedStringAppendUnattributed(attrstr,Use the controls opposite to
˓→the text to control properties of the text.")
funchandlerDraw
defaultfont
params
set_uiDrawTextLayoutParams_String(params,attrstr)
uiFontButtonFont(fontButton, defaultFont)
set_uiDrawTextLayoutParams_DefaultFont(params,defaultFont)
set_uiDrawTextLayoutParams_Width(params,uiEventAreaWidth())
set_uiDrawTextLayoutParams_Align(params,uiComboboxSelected(alignment))
textLayout
uiDrawText(uiEventContext(), textLayout,,)
uiDrawFreeTextLayout(textLayout)
uiFreeFontButtonFont(defaultFont)
funconFontChanged
uiAreaQueueRedrawAll(area)
funconComboboxSelected
uiAreaQueueRedrawAll(area)
funconClosing
uiControlDestroy(mainwin)
uiQuit()
funcshouldQuit
uiControlDestroy(mainwin)
funcmain
uiOnShouldQuit("shouldQuit()")
makeAttributedString()
mainwin"libui Text-Drawing Example",,,)
uiWindowSetMargined(mainwin,)
uiWindowOnClosing(mainwin,onClosing()")
hbox
uiBoxSetPadded(hbox,)
uiWindowSetChild(mainwin, hbox)
vbox
uiBoxSetPadded(vbox,)
uiBoxAppend(hbox, vbox,)
fontButton
uiFontButtonOnChanged(fontButton,onFontChanged()")
(continues on next page)
74.9. Text Drawing 927

Ring Documentation, Release 1.14
(continued from previous page)
uiBoxAppend(vbox, fontButton,)
form
uiFormSetPadded(form,)
uiBoxAppend(vbox, form,)
alignment
uiComboboxAppend(alignment,Left")
uiComboboxAppend(alignment,Center")
uiComboboxAppend(alignment,Right")
uiComboboxSetSelected(alignment,)/
uiComboboxOnSelected(alignment,onComboboxSelected()")
uiFormAppend(form,Alignment", alignment,)
oAreaHandler"handlerDraw()","","","","")
area
uiBoxAppend(hbox, area,)
uiControlShow(mainwin)
uiMain()
uiFreeAttributedString(attrstr)
Screen Shot:
74.9. Text Drawing 928

Ring Documentation, Release 1.14
74.9. Text Drawing 929

Ring Documentation, Release 1.14
74.10
Example (1):
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
(continues on next page)
74.10. More Drawing Samples 930

Ring Documentation, Release 1.14
(continued from previous page)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
source
sp
source
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
set_uiDrawStrokeParams_Thickness(sp,40.96)
path
uiDrawPathNewFigure(path,.8,.48)
uiDrawPathLineTo(path,.8.2,.4851.2)
uiDrawPathLineTo(path,.8.2.2,.48.2.2)
uiDrawPathEnd(path)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
path
uiDrawPathNewFigure(path,.8,.28)
uiDrawPathLineTo(path,.8.2,.2851.2)
uiDrawPathLineTo(path,.8.2.2,.28.2.2)
uiDrawPathEnd(path)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinBevel)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
path
uiDrawPathNewFigure(path,.8,.08)
uiDrawPathLineTo(path,.8.2,.0851.2)
uiDrawPathLineTo(path,.8.2.2,.08.2.2)
uiDrawPathEnd(path)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinRound)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
funccloseApp
uiQuit()
Screen Shot:
74.10. More Drawing Samples 931

Ring Documentation, Release 1.14
Example (2):
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
(continues on next page)
74.10. More Drawing Samples 932

Ring Documentation, Release 1.14
(continued from previous page)
source
sp
source
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
set_uiDrawStrokeParams_Thickness(sp,30)
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
path
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathEnd(path)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapRound)
path
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathEnd(path)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapSquare)
path
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathEnd(path)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
//
// tomatch the reference picture onthe cairo website
uiCrSourceRGBA(source,,.2,.2,)
set_uiDrawStrokeParams_Thickness(sp,2.56)
path
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathEnd(path)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
funccloseApp
uiQuit()
Screen Shot:
74.10. More Drawing Samples 933

Ring Documentation, Release 1.14
Example (3):
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
(continues on next page)
74.10. More Drawing Samples 934

Ring Documentation, Release 1.14
(continued from previous page)
source
sp
x.6
y.6
width.8
height.8
aspect.0
corner_radius
radius
degrees.0
source
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
set_uiDrawStrokeParams_Thickness(sp,30)
path
//
uiDrawPathNewFigureWithArc(path,
x
radius,
-90*degrees, uiPi,
0)
//
uiDrawPathArcTo(path,
x
radius,
0*degrees, uiPi,
0)
//
uiDrawPathArcTo(path,
x
radius,
90*degrees, uiPi,
0)
//
uiDrawPathArcTo(path,
x
radius,
180*degrees, uiPi,
0)
uiDrawPathCloseFigure(path)
uiDrawPathEnd(path)
uiCrSourceRGBA(source,.5,.5,,)
uiDrawFill(uiEventContext(), path, source)
uiCrSourceRGBA(source,.5,,,.5)
set_uiDrawStrokeParams_Thickness(sp,10)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
(continues on next page)
74.10. More Drawing Samples 935

Ring Documentation, Release 1.14
(continued from previous page)
funccloseApp
uiQuit()
Screen Shot:
Example (4):
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
source
(continues on next page)
74.10. More Drawing Samples 936

Ring Documentation, Release 1.14
(continued from previous page)
sp
source
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
path
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathNewFigure(path,.0,.0)
uiDrawPathLineTo(path,.0,.0)
uiDrawPathEnd(path)
set_uiDrawStrokeParams_Thickness(sp,30)
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapRound)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
funccloseApp
uiQuit()
Screen Shot:
Example (5):
74.10. More Drawing Samples 937

Ring Documentation, Release 1.14
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
source
sp
m
source
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
set_uiDrawStrokeParams_Thickness(sp,6)
path
uiDrawPathAddRectangle(path,,,,)
uiDrawPathNewFigureWithArc(path,
64,,
40,
0, *uiPi,
0)
uiDrawPathNewFigureWithArc(path,
192,,
40,
0,2 *uiPi,
1)
uiDrawPathEnd(path)
uicrsourcergba(source,,.7,,)
uiDrawFill(uiEventContext(), path, source)
uicrsourcergba(source,,,,)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
(continues on next page)
74.10. More Drawing Samples 938

Ring Documentation, Release 1.14
(continued from previous page)
uiDrawMatrixSetIdentity(m)
uiDrawMatrixTranslate(m,,)
uiDrawTransform(uiEventContext(), m)
path
uiDrawPathAddRectangle(path,,,,)
uiDrawPathNewFigureWithArc(path,
64,,
40,
0, *uiPi,
0)
uiDrawPathNewFigureWithArc(path,
192,,
40,
0,2 *uiPi,
1)
uiDrawPathEnd(path)
uicrsourcergba(source,,,.9,)
uiDrawFill(uiEventContext(), path, source)
uicrsourcergba(source,,,,)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
funccloseApp
uiQuit()
Screen Shot:
Example (6):
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
(continues on next page)
74.10. More Drawing Samples 939

Ring Documentation, Release 1.14
(continued from previous page)
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
source
sp
source
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
path
uiDrawPathNewFigure(path,.0,.6)
uiDrawPathLineTo(path,.4,.4)
uiDrawPathLineTo(path,.4.4,.4.0)
uiDrawPathBezierTo(path,.2,.4,.2,.0,.0,.0)
uiDrawPathCloseFigure(path)
uiDrawPathNewFigure(path,.0,.6)
uiDrawPathLineTo(path,.0.2,.6.2)
uiDrawPathLineTo(path,.0.251.2,.6.2.2)
uiDrawPathLineTo(path,.0.251.251.2,.6.2.251.2)
uiDrawPathCloseFigure(path)
uiDrawPathEnd(path)
set_uiDrawStrokeParams_Thickness(sp,10)
uicrsourcergba(source,,,,)
uiDrawFill(uiEventContext(), path, source)
uicrsourcergba(source,,,,)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
funccloseApp
uiQuit()
74.10. More Drawing Samples 940

Ring Documentation, Release 1.14
Screen Shot:
Example (7):
# Sample ported to Ring
# Based on original sample from : https://github.com/andlabs/libui
load"libui.ring"
oWindowDrawing Sample",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
oAreaHandler"draw()","","","","")
area
btnClose"Close Application")
uiButtonOnClicked(btnClose,"closeApp()")
hbox
uiBoxSetPadded(hbox,)
uiBoxAppend(hbox,btnClose,0)
uiBoxAppend(hbox,area,1)
uiWindowSetChild(oWindow, hbox)
uiControlShow( oWindow )
uiMain()
funcdraw
nWidth
source
sp
source
x=25.6=128.0
(continues on next page)
74.10. More Drawing Samples 941

Ring Documentation, Release 1.14
(continued from previous page)
x1=102.4=230.4
x2=153.6=25.6
x3=230.4=128.0
uicrsourcergba(source,,,,)
set_uiDrawStrokeParams_Cap(sp,uiDrawLineCapFlat)
set_uiDrawStrokeParams_Join(sp,uiDrawLineJoinMiter)
set_uiDrawStrokeParams_MiterLimit(sp,uiDrawDefaultMiterLimit)
set_uiDrawStrokeParams_NumDashes(sp,0)
set_uiDrawStrokeParams_DashPhase(sp,0)
path
uiDrawPathNewFigure(path, x, y)
uiDrawPathBezierTo(path, x1, y1, x2, y2, x3, y3)
uiDrawPathEnd(path)
set_uiDrawStrokeParams_Thickness(sp,10)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
uicrsourcergba(source,,.2,.2,.6)
set_uiDrawStrokeParams_Thickness(sp,6)
path
uiDrawPathNewFigure(path, x, y)
uiDrawPathLineTo(path, x1, y1)
uiDrawPathNewFigure(path, x2, y2)
uiDrawPathLineTo(path, x3, y3)
uiDrawPathEnd(path)
uiDrawStroke(uiEventContext(), path, source, sp)
uiDrawFreePath(path)
funccloseApp
uiQuit()
Screen Shot:
74.10. More Drawing Samples 942

Ring Documentation, Release 1.14
74.10. More Drawing Samples 943

CHAPTER
SEVENTYFIVE
USING RINGZIP
In this chapter we will learn about using RingZip
75.1
Example : Create myle.zip contains 4 les
load"ziplib.ring"
oZip"myfile.zip",w)
zip_addfile(oZip,"test.c")
zip_addfile(oZip,"zip.c")
zip_addfile(oZip,"zip.h")
zip_addfile(oZip,"miniz.h")
zip_close(oZip)
75.2
Example : Extract myle.zip to myfolder folder.
load"ziplib.ring"
zip_extract_allfiles("myfile.zip","myfolder")
75.3
Example : Print le names in the myle.zip
load"ziplib.ring"
oZip"myfile.zip",r)
forx=1tozip_filescount(oZip)
seezip_getfilenamebyindex(oZip,x)
next
zip_close(oZip)
944

Ring Documentation, Release 1.14
75.4
The RingZip library comes with two classes. The Zip class and the ZipEntry class.
Example (1):
load"ziplib.ring"
newZip {
setFileName("myfile.zip")
open("w")
newEntry() {
open("test.c")
writefile("test.c")
close()
}
close()
}
Example (2):
load"ziplib.ring"
newZip {
SetFileName("myfile.zip")
Open("w")
AddFile("test.c")
AddFile("zip.c")
AddFile("zip.h")
AddFile("miniz.h")
Close()
}
Example (3):
load"ziplib.ring"
newzip {
SetFileName("myfile.zip")
ExtractAllFiles("myfolder")
}
Example (4):
load"ziplib.ring"
newZip {
SetFileName("myfile.zip")
Open("r")
seeFilesCount()
Close()
}
Example (5):
load"ziplib.ring"
(continues on next page)
75.4. Using RingZip Classes 945

Ring Documentation, Release 1.14
(continued from previous page)
newZip {
SetFileName("myfile.zip")
Open("r")
forx tofilescount()
SeeGetFileNameByIndex(x)
next
Close()
}
75.5
Methods:
Method Description/Output
SetFileName(cName) Set the Zip le name
GetFileName() Return the Zip le name
Open(cMode) Open File, cMode = “a”, “w” or “r”
Close() Close the Zip File
AddFile(cFileName) Add le to the Zip le
ExtractAllFiles(cFolder)Extract all les from the Zip le
FilesCount() Return les count in the Zip le
GetFileNameByIndex(nIndex)Return le name in the Zip le by le index
NewEntry() Create new ZipEntry object
75.6
Methods:
Method Description/Output
Open(cFileName) Open new Entry
WriteFile(cFileName)Write File to the Entry
WriteString(cString)Write String to the Entry
Close() Close the Entry
75.5. Zip Class Reference 946

CHAPTER
SEVENTYSIX
RINGLIBZIP FUNCTIONS REFERENCE
76.1
In this chapter we have a list of the supported functions by this extension
76.2
• *zip_openle(const char*, const char*)
• *)
• *,int)
• *)
• *, size_t*)
• *cFile)
•
• *cFile, const char*cFolder)
•
• *)
• *zip_getlenamebyindex(ZIP_T*pZip,int index)
• *cZIPFile,const char*cFile)
947

CHAPTER
SEVENTYSEVEN
RINGMURMURHASH FUNCTIONS REFERENCE
Murmurhash extension is an extension written to implement a full implementation for the MurmurHash library.
77.1
uint32_t murmurhash1(string key, int seed, [bool return_type]);
uint32_t murmurhash1_aligned(string key, int seed, [bool return_type]);
77.2
uint32_t murmurhash2(string key, int seed, [bool return_type]);
uint32_t murmurhash2a(string key, int seed, [bool return_type]);
uint64_t murmurhash64a(string key, int seed, [bool return_type]);
uint64_t murmurhash64b(string key, int seed, [bool return_type]);
uint32_t murmurhash_neutral2(string key, int seed, [bool return_type]);
uint32_t murmurhash_aligned2(string key, int seed, [bool return_type]);
77.3
uint32_t murmurhash3_x86_32(string key, int seed, [bool return_type]);
list murmurhash3_x86_128(string key, int seed, [bool return_type]);
list murmurhash3_x64_128(string key, int seed, [bool return_type]);
The third optional parameter is to set the type of the returned value, this parameter accepts a bool value [ true, false ],
true will return a Hex value, while false will return a integer value.
948

Ring Documentation, Release 1.14
77.4
load "murmurhashlib.ring"
key = "Ring Language"
see murmurhash3_x86_32(key, 0, 0) + nl // Output: 1894444853
see murmurhash3_x86_32(key, 0, 1) + nl // Output: 70eaef35
77.4. Example 949

CHAPTER
SEVENTYEIGHT
RINGCONSOLECOLORS FUNCTIONS REFERENCE
78.1
In this chapter we have a list of the supported functions by this extension
78.2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
950

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
• *string)
78.2. Reference 951

CHAPTER
SEVENTYNINE
RINGALLEGRO FUNCTIONS REFERENCE
79.1
In this chapter we have a list of the supported functions by this extension
79.2
•
•
•
• *al_create_cong(void)
• *cong)
• *al_load_cong_le(const char*lename)
• *al_load_cong_le_f(ALLEGRO_FILE*le)
• *lename, const ALLEGRO_CONFIG*cong)
• *le, const ALLEGRO_CONFIG*cong)
• *cong, const char*name)
• *cong, const char*section, const char*comment)
• *al_get_cong_value(const ALLEGRO_CONFIG*cong,const char*section, const char*key)
• *cong,const char*section, const char*key, const char*value)
• *al_get_rst_cong_section(ALLEGRO_CONFIG const*cong,ALLEGRO_CONFIG_SECTION
**iterator)
• *al_get_next_cong_section(ALLEGRO_CONFIG_SECTION**iterator)
• *al_get_rst_cong_entry(ALLEGRO_CONFIG const*cong,char const*section, ALLE-
GRO_CONFIG_ENTRY **iterator)
• *al_get_next_cong_entry(ALLEGRO_CONFIG_ENTRY**iterator)
• *al_merge_cong(const ALLEGRO_CONFIG*cfg1,const ALLEGRO_CONFIG*cfg2)
• *master, const ALLEGRO_CONFIG*add)
• *al_create_display(int w, int h)
952

Ring Documentation, Release 1.14
• *display)
•
•
• *importance)
•
•
• *x, int*y)
•
•
•
• *al_get_display_event_source(ALLEGRO_DISPLAY*display)
• *al_get_backbuffer(ALLEGRO_DISPLAY*display)
•
•
•
• *display)
• *display)
• *display, int width, int height)
• *display)
• *display, int*x, int*y)
• *display, int x, int y)
• *display)
• *display, int ag, bool onoff)
• *display, int option)
• *display)
• *display)
• *display, const char*title)
• *display, ALLEGRO_BITMAP*icon)
• *display,int num_icons, ALLEGRO_BITMAP*icons[])
•
• *display)
• *display)
•
• *display, int option, int value)
• *display,int*min_w, int*min_h, int*max_w, int
*max_h)
79.2. Reference 953

Ring Documentation, Release 1.14
• *display,int min_w, int min_h, int max_w, int max_h)
• *al_create_event_queue(void)
• *queue)
• *queue,ALLEGRO_EVENT_SOURCE *source)
• *queue,ALLEGRO_EVENT_SOURCE
*source)
• *queue)
• *queue, ALLEGRO_EVENT*ret_event)
• *queue, ALLEGRO_EVENT*ret_event)
• *queue)
• *queue)
• *queue, ALLEGRO_EVENT*ret_event)
• *queue,ALLEGRO_EVENT *ret_event, oat
secs)
• *queue,ALLEGRO_EVENT*ret_event, ALLE-
GRO_TIMEOUT*timeout)
• *src)
• *src)
• *source)
• *source, intptr_t data)
• *al_fopen(const char*path, const char*mode)
• *al_fopen_interface(const ALLEGRO_FILE_INTERFACE*drv,const char*path, const char
*mode)
• *al_fopen_slice(ALLEGRO_FILE*fp, size_t initial_size, const char*mode)
• *f)
• *f, void*ptr, size_t size)
• *f, const void*ptr, size_t size)
• *f)
• *f)
• *f, int64_t offset, int whence)
• *f)
• *f)
• *f)
• *f, int c)
• *f)
• *f)
• *f, int c)
79.2. Reference 954

Ring Documentation, Release 1.14
• *f)
• *f)
• *f, int16_t w)
• *f, int16_t w)
• *f)
• *f)
• *f, int32_t l)
• *f, int32_t l)
• *al_fgets(ALLEGRO_FILE*f, char * const buf, size_t max)
• *al_fget_ustr(ALLEGRO_FILE*f)
• *f, char const*p)
• *al_fopen_fd(int fd, const char*mode)
• *al_make_temp_le(const char*template, ALLEGRO_PATH**ret_path)
• *le_interface
•
• *al_get_new_le_interface(void)
• *al_create_le_handle(const ALLEGRO_FILE_INTERFACE*drv,void*userdata)
• *al_get_le_userdata(ALLEGRO_FILE*f)
• *al_create_fs_entry(const char*path)
• *fh)
• *al_get_fs_entry_name(ALLEGRO_FS_ENTRY*e)
• *e)
• *e)
• *e)
• *e)
• *e)
• *e)
• *e)
• *e)
• *path)
• *path)
• *e)
• *al_read_directory(ALLEGRO_FS_ENTRY*e)
• *e)
• *al_get_current_directory(void)
• *path)
79.2. Reference 955

Ring Documentation, Release 1.14
• *path)
• *al_open_fs_entry(ALLEGRO_FS_ENTRY*e, const char*mode)
• *fs_interface)
•
• *al_get_fs_interface(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *al_get_display_mode(int index, ALLEGRO_DISPLAY_MODE*mode)
•
•
•
•
•
• *r, unsigned char*g, unsigned char*b)
• *r, oat*g, oat*b)
• *r, unsigned char*g, unsigned char*b, unsigned
char*a)
• *r, oat*g, oat*b, oat*a)
•
79.2. Reference 956

Ring Documentation, Release 1.14
•
• *al_lock_bitmap(ALLEGRO_BITMAP*bitmap,int format, int ags)
• *al_lock_bitmap_region(ALLEGRO_BITMAP*bitmap,int x, int y, int width,
int height, int format, int ags)
• *bitmap)
• *al_create_bitmap(int w, int h)
• *al_create_sub_bitmap(ALLEGRO_BITMAP*parent,int x, int y, int w, int h)
• *al_clone_bitmap(ALLEGRO_BITMAP*bitmap)
• *bitmap)
•
•
•
•
•
• *bitmap)
• *bitmap)
• *bitmap)
• *bitmap)
• *bitmap, int x, int y)
• *bitmap)
• *bitmap)
• *bitmap)
• *al_get_parent_bitmap(ALLEGRO_BITMAP*bitmap)
•
• *bitmap, oat dx, oat dy, int ags)
• *bitmap, ALLEGRO_COLOR tint,oat dx, oat dy, int
ags)
• *bitmap,oat sx, oat sy, oat sw, oat sh, oat dx, oat
dy, int ags)
• *bitmap,ALLEGRO_COLOR tint,oat sx, oat sy,
oat sw, oat sh, oat dx, oat dy,int ags)
•
• *bitmap,oat cx, oat cy, oat dx, oat dy, oat angle, int
ags)
• *bitmap,ALLEGRO_COLOR tint,oat cx, oat cy,
oat dx, oat dy, oat angle, int ags)
• *bitmap,oat cx, oat cy, oat dx, oat dy, oat
xscale, oat yscale,oat angle, int ags)
79.2. Reference 957

Ring Documentation, Release 1.14
• *bitmap,ALLEGRO_COLOR tint,oat cx,
oat cy, oat dx, oat dy, oat xscale, oat yscale,oat angle, int ags)
• *bitmap,oat sx, oat sy, oat sw,
oat sh,ALLEGRO_COLOR tint,oat cx, oat cy, oat dx, oat dy, oat xscale, oat yscale,oat angle, int
ags)
• *bitmap,oat sx, oat sy, oat sw, oat sh,oat dx, oat dy,
oat dw, oat dh, int ags)
• *bitmap,ALLEGRO_COLOR tint,oat sx, oat sy,
oat sw, oat sh,oat dx, oat dy, oat dw, oat dh, int ags)
• *al_get_target_bitmap(void)
•
•
• *bitmap)
• *display)
• *al_get_current_display(void)
• *op, int*src, int*dst)
• *op, int*src, int*dst,int*alpha_op, int*alpha_src, int*alpha_dst)
•
•
• *x, int*y, int*w, int*h)
•
•
• *bitmap, ALLEGRO_COLOR mask_color)
•
•
• *al_load_bitmap_f(ALLEGRO_FILE*fp, const char*ident)
• *lename, ALLEGRO_BITMAP*bitmap)
• *fp, const char*ident,ALLEGRO_BITMAP*bitmap)
•
•
•
•
•
•
• *joy)
• *joy)
• *al_get_joystick_name(ALLEGRO_JOYSTICK*joy)
• *al_get_joystick_stick_name(ALLEGRO_JOYSTICK*joy, int stick)
79.2. Reference 958

Ring Documentation, Release 1.14
• *al_get_joystick_axis_name(ALLEGRO_JOYSTICK*joy, int stick, int axis)
• *al_get_joystick_button_name(ALLEGRO_JOYSTICK*joy, int button)
• *joy, int stick)
• *joy)
• *joy, int stick)
• *joy)
• *joy, ALLEGRO_JOYSTICK_STATE*ret_state)
• *al_get_joystick_event_source(void)
•
•
•
• *ret_state)
• *state, int keycode)
• *al_keycode_to_name(int keycode)
•
• *al_get_keyboard_event_source(void)
• *al_malloc_with_context(size_t n,int line, const char*le, const char*func)
• *ptr, int line, const char*le, const char*func)
• *al_realloc_with_context(void*ptr, size_t n,int line, const char*le, const char*func)
• *al_calloc_with_context(size_t count, size_t n,int line, const char*le, const char*func)
• *memory_interface)
•
•
• *info)
•
•
•
•
•
•
• *ret_state)
• *state, int axis)
• *state, int button)
• *display, int x, int y)
•
•
79.2. Reference 959

Ring Documentation, Release 1.14
•
• *al_get_mouse_event_source(void)
• *al_create_mouse_cursor(ALLEGRO_BITMAP*bmp,int x_focus, int
y_focus)
• *cursor)
• *display, ALLEGRO_MOUSE_CURSOR *cursor)
• *display,ALLEGRO_SYSTEM_MOUSE_CURSOR
cursor_id)
• *ret_x, int*ret_y)
• *display)
• *display)
• *display)
•
• *al_create_path(const char*str)
• *al_create_path_for_directory(const char*str)
• *path)
• *al_clone_path(const ALLEGRO_PATH*path)
• *path, const ALLEGRO_PATH*tail)
• *head, ALLEGRO_PATH*tail)
• *al_get_path_drive(const ALLEGRO_PATH*path)
• *path)
• *al_get_path_component(const ALLEGRO_PATH*path, int i)
• *al_get_path_tail(const ALLEGRO_PATH*path)
• *al_get_path_lename(const ALLEGRO_PATH*path)
• *al_get_path_basename(const ALLEGRO_PATH*path)
• *al_get_path_extension(const ALLEGRO_PATH*path)
• *path, const char*drive)
• *path, const char*s)
• *path, int i, const char*s)
• *path, int i, const char*s)
• *path, int i)
• *path)
• *path, const char*lename)
• *path, char const*extension)
• *al_path_cstr(const ALLEGRO_PATH*path, char delim)
• *path)
• *state)
79.2. Reference 960

Ring Documentation, Release 1.14
• *state, int ags
•
•
•
•
•
• *al_get_standard_path(int id)
• *path)
• *app_name)
• *org_name)
• *al_get_app_name(void)
• *al_get_org_name(void)
• *al_get_system_cong(void)
• *al_create_thread(void)
•
• *thread)
• *thread, void**ret_value)
• *thread)
• *thread)
• *thread)
• *al_create_mutex(void)
• *al_create_mutex_recursive(void)
• *mutex)
• *mutex)
• *mutex)
• *al_create_cond(void)
• *cond)
• *cond, ALLEGRO_MUTEX*mutex)
• *cond, ALLEGRO_MUTEX*mutex,const ALLEGRO_TIMEOUT
*timeout)
• *cond)
• *cond)
•
• *timeout, double seconds)
•
• *al_create_timer(double speed_secs)
79.2. Reference 961

Ring Documentation, Release 1.14
• *timer)
• *timer)
• *timer)
• *timer)
• *timer)
• *timer, int64_t new_count)
• *timer, int64_t diff)
• *timer)
• *timer, double new_speed_secs)
• *al_get_timer_event_source(ALLEGRO_TIMER*timer)
• *dest, const ALLEGRO_TRANSFORM*src)
• *trans)
• *al_get_current_transform(void)
• *trans)
• *trans, oat tol)
• *trans)
• *trans, oat x, oat y,oat sx, oat sy, oat theta)
• *trans, oat x, oat y)
• *trans, oat theta)
• *trans, oat sx, oat sy)
• *trans, oat*x, oat*y)
• *trans, const ALLEGRO_TRANSFORM*other)
• *al_ustr_new(const char*s)
• *al_ustr_new_from_buffer(const char*s, size_t size)
• *us)
• *al_cstr(const ALLEGRO_USTR*us)
• *us, char*buffer, int size)
• *al_cstr_dup(const ALLEGRO_USTR*us)
• *al_ustr_dup(const ALLEGRO_USTR*us)
• *al_ustr_dup_substr(const ALLEGRO_USTR*us, int start_pos,int end_pos)
• *al_ustr_empty_string(void)
• *al_ref_cstr(ALLEGRO_USTR_INFO*info, const char*s)
• *al_ref_buffer(ALLEGRO_USTR_INFO*info, const char*s, size_t size)
• *al_ref_ustr(ALLEGRO_USTR_INFO*info, const ALLEGRO_USTR*us,int
start_pos, int end_pos)
• *us)
79.2. Reference 962

Ring Documentation, Release 1.14
• *us)
• *us, int index)
• *us, int*pos)
• *us, int*pos)
• *ub, int pos)
• *us, int*pos)
• *us, int*pos)
• *us1, int pos, const ALLEGRO_USTR*us2)
• *us, int pos, const char*s)
• *us, int pos, int32_t c)
• *us1, const ALLEGRO_USTR*us2)
• *us, const char*s)
• *us, int32_t c)
• *us, int pos)
• *us, int start_pos, int end_pos)
• *us, int start_pos)
• *us)
• *us)
• *us)
• *us1, const ALLEGRO_USTR*us2)
• *us1, const ALLEGRO_USTR*us2,int start_pos, int end_pos)
• *us1, const char*s)
• *us, int start_pos, int32_t c)
• *us1, int start_pos1, int end_pos1,const ALLEGRO_USTR
*us2)
• *us, int start_pos, int32_t c)
• *us, int end_pos, int32_t c)
• *us, int start_pos,const ALLEGRO_USTR*accept)
• *us, int start_pos,const char*accept)
• *us, int start_pos,const ALLEGRO_USTR*reject)
• *us, int start_pos,const char*reject)
• *haystack, int start_pos,const ALLEGRO_USTR*needle)
• *haystack, int start_pos,const char*needle)
• *haystack, int end_pos,const ALLEGRO_USTR*needle)
• *haystack, int end_pos,const char*needle)
• *us, int start_pos,const ALLEGRO_USTR*nd, const ALLE-
GRO_USTR*replace)
79.2. Reference 963

Ring Documentation, Release 1.14
• *us, int start_pos,const char*nd, const char*replace)
• *us1, const ALLEGRO_USTR*us2)
• *us1, const ALLEGRO_USTR*us2, int n)
• *us1, const ALLEGRO_USTR*us2)
• *us1, const ALLEGRO_USTR*us2)
• *us1, const char*s2)
• *us1, const ALLEGRO_USTR*us2)
• *us1, const char*s2)
• *al_ustr_new_from_utf16(uint16_t const*s)
• *us)
• *us, uint16_t*s,size_t n)
•
•
•
• *display)
• *bitmap)
• *bitmap)
•
•
• *bitmap, int*u, int*v)
• *display)
• *al_get_opengl_extension_list(void)
• *al_get_opengl_proc_address(const char*name)
• *bitmap)
• *bitmap, int*w, int*h)
• *bitmap, int*u, int*v)
• *bitmap)
• *bitmap)
• *extension);
•
•
• *display)
•
•
•
•
79.2. Reference 964

Ring Documentation, Release 1.14
•
•
•
• *al_create_voice(unsigned int freq,ALLEGRO_AUDIO_DEPTH depth, ALLE-
GRO_CHANNEL_CONF chan_conf)
• *voice)
• *voice)
• *stream,ALLEGRO_VOICE*voice)
• *mixer, ALLEGRO_VOICE*voice)
• *spl,ALLEGRO_VOICE
*voice)
• *voice)
• *voice)
• *voice)
• *voice)
• *voice, bool val)
• *voice)
• *voice, unsigned int val)
• *al_create_sample(void*buf, unsigned int samples,unsigned int freq, ALLE-
GRO_AUDIO_DEPTH depth,ALLEGRO_CHANNEL_CONF chan_conf, bool free_buf)
• *spl)
• *spl, oat gain, oat pan, oat speed,int loop, ALLE-
GRO_SAMPLE_ID*ret_id)
• *spl_id)
•
• *spl)
• *spl)
• *spl)
• *spl)
• *al_get_sample_data(const ALLEGRO_SAMPLE*spl)
• *al_create_sample_instance(ALLEGRO_SAMPLE*sample_data)
• *spl)
• *spl)
• *spl)
•
*spl)
• *spl)
• *spl)
79.2. Reference 965

Ring Documentation, Release 1.14
• *spl)
• *spl,unsigned int val)
• *spl)
• *spl,unsigned int val)
• *spl)
• *spl, oat val)
• *spl)
• *spl, oat val)
• *spl)
• *spl, oat val)
• *spl)
• *spl)
• *spl,ALLEGRO_PLAYMODE
val)
• *spl)
• *spl, bool val)
• *spl)
• *spl)
• *al_get_sample(ALLEGRO_SAMPLE_INSTANCE *spl)
• *spl, ALLEGRO_SAMPLE*data)
• *al_create_mixer(unsigned int freq,ALLEGRO_AUDIO_DEPTH depth, ALLE-
GRO_CHANNEL_CONF chan_conf)
• *mixer)
• *al_get_default_mixer(void)
• *mixer)
•
• *stream, ALLEGRO_MIXER*mixer)
• *spl,ALLEGRO_MIXER
*mixer)
• *stream, ALLEGRO_MIXER*mixer)
• *mixer)
• *mixer, unsigned int val)
• *mixer)
• *mixer)
• *mixer)
• *mixer, oat new_gain)
• *mixer)
79.2. Reference 966

Ring Documentation, Release 1.14
• *mixer, ALLEGRO_MIXER_QUALITY new_quality)
• *mixer)
• *mixer, bool val)
• *mixer)
• *mixer)
• *stream)
• *al_get_audio_stream_event_source(ALLEGRO_AUDIO_STREAM
*stream)
• *stream)
• *stream)
• *stream)
•
*stream)
• *stream)
• *stream)
• *stream)
• *stream, oat val)
• *stream)
• *stream, oat val)
• *stream)
• *stream, oat val)
• *stream)
• *stream, bool val)
• *stream)
• *stream,ALLEGRO_PLAYMODE val)
• *stream)
• *stream)
• *al_get_audio_stream_fragment(const ALLEGRO_AUDIO_STREAM*stream)
• *stream, void*val)
• *stream)
• *stream)
• *stream, double time)
• *stream)
• *stream)
• *stream,double start, double end)
• *al_load_sample(const char*lename)
• al_load_sample_f(ALLEGRO_FILEfp, const char*ident)
79.2. Reference 967

Ring Documentation, Release 1.14
• *al_load_audio_stream(const char*lename,size_t buffer_count, unsigned int
samples)
• al_load_audio_stream_f(ALLEGRO_FILEfp, const char*ident,size_t
buffer_count, unsigned int samples)
• *lename, ALLEGRO_SAMPLE*spl)
• *fp, const char*ident, ALLEGRO_SAMPLE*spl)
•
•
•
• *red, oat*green, oat*blue)
•
• *red, oat*green, oat*blue)
•
• *red, oat*green, oat*blue)
• *string)
• *string,oat*red, oat*green, oat*blue)
• *string)
• *name)
• *name, oat*r, oat*g, oat*b)
• *cyan, oat*magenta, oat*yellow, oat
*key)
• *hue, oat*saturation, oat*lightness)
• *hue, oat*saturation, oat*value)
• *al_color_rgb_to_name(oat r, oat g, oat b)
• *y, oat*u, oat*v)
•
• *red, oat*green, oat*blue)
•
•
•
• *al_load_font(char const*lename, int size, int ags)
• *f)
• *f)
• *f)
• *f, const char*str)
• *f, ALLEGRO_USTR const*ustr)
79.2. Reference 968

Ring Documentation, Release 1.14
• *font,ALLEGRO_COLOR color, oat x, oat y, int ags,char const
*text)
• *font,ALLEGRO_COLOR color, oat x, oat y, int ags,const
ALLEGRO_USTR*ustr)
• *font,ALLEGRO_COLOR color, oat x1, oat x2,oat
y, oat diff, int ags, const char*text)
• *font,ALLEGRO_COLOR color, oat x1, oat x2,oat
y, oat diff, int ags, const ALLEGRO_USTR*ustr)
• *f,char const*text,int*bbx, int*bby, int*bbw, int*bbh)
• *f,ALLEGRO_USTR const*ustr,int*bbx, int*bby, int
*bbw, int*bbh)
•
• *al_grab_font_from_bitmap(ALLEGRO_BITMAP*bmp,int ranges_n, const int ranges[])
• *al_load_bitmap_font(const char*fname)
• *al_create_builtin_font(void)
•
•
• *al_load_ttf_font(char const*lename, int size, int ags)
• *al_load_ttf_font_f(ALLEGRO_FILE*le,char const*lename, int size, int ags)
• *al_load_ttf_font_stretch(char const*lename, int w, int h,int ags)
• *al_load_ttf_font_stretch_f(ALLEGRO_FILE*le,char const*lename, int w, int h, int
ags)
•
•
•
•
• *al_open_memle(void*mem, int64_t size, const char*mode)
•
•
•
• *al_create_native_le_dialog(char const*initial_path,char const*title,char const
*patterns,int mode)
• *display,ALLEGRO_FILECHOOSER*dialog)
• *dialog)
• *al_get_native_le_dialog_path(const ALLEGRO_FILECHOOSER*dialog, size_t i)
• *dialog)
• *display,char const*title, char const*heading, char
const*text,char const*buttons, int ags)
• *al_open_native_text_log(char const*title, int ags)
79.2. Reference 969

Ring Documentation, Release 1.14
• *textlog)
•
•
•
•
•
•
•
•
thickness)
•
•
•
•
oat thickness)
•
color)
•
oat thickness,int num_points)
•
oat thickness)
•
color)
•
•
•
•
•
thickness)
•
GRO_COLOR color, oat thickness)
• *points, int points_stride, ALLEGRO_COLOR color,oat thickness, int
num_segments)
•
int start, int end, int type)
•
texture, const int* indices, int num_vtx, int type)
•
stride)
•
79.2. Reference 970

Ring Documentation, Release 1.14
• *al_create_shader(ALLEGRO_SHADER_PLATFORM platform)
• *shader, ALLEGRO_SHADER_TYPE type,const char
*source)
• *shader,ALLEGRO_SHADER_TYPE type, const
char*lename)
• *shader)
• *al_get_shader_log(ALLEGRO_SHADER*shader)
• *shader)
• *shader)
• *shader)
• *name,ALLEGRO_BITMAP *bitmap, int unit)
• *name,const ALLEGRO_TRANSFORM *matrix)
• *name, int i)
• *name, oat f)
• *name, bool b)
• *name,int num_components, const int*i, int num_elems)
• *name,int num_components, const oat*f, int num_elems)
• *al_get_default_shader_source(ALLEGRO_SHADER_PLATFORM plat-
form,ALLEGRO_SHADER_TYPE type)
79.2. Reference 971

CHAPTER
EIGHTY
USING RINGLIBSDL
In this chapter we will learn about using RingLibSDL to create games based on the LibSDL, SDLImage, SDLTTF and
SDLMixer libraries.
Tip:RingLibSDL is not distributed with the binary releases for desktop which uses RingAllegro
Note:To use RingLibSDL, Check ring/android/ringlibsdl folder.
80.1
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
SDL_Delay(2000)
SDL_DestroyWindow(win)
SDL_Quit()
80.2
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
ren1, SDL_RENDERER_ACCELERATED
˓→PRESENTVSYNC )
bmp"hello.bmp")
tex
SDL_FreeSurface(bmp)
SDL_RenderClear(ren)
SDL_RenderCopy2(ren,tex)
SDL_RenderPresent(ren)
(continues on next page)
972

Ring Documentation, Release 1.14
(continued from previous page)
SDL_Delay(2000)
SDL_DestroyTexture(tex)
SDL_DestroyRenderer(ren)
SDL_DestroyWindow(win)
SDL_Quit()
80.3
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
ren1, SDL_RENDERER_ACCELERATED
˓→PRESENTVSYNC )
bmp"hello.bmp")
tex
SDL_FreeSurface(bmp)
bmp"hello2.bmp")
tex2
SDL_FreeSurface(bmp)
forx to10 next
SDL_DestroyTexture(tex)
SDL_DestroyTexture(tex2)
SDL_DestroyRenderer(ren)
SDL_DestroyWindow(win)
SDL_Quit()
funcshowtex oTex
SDL_RenderClear(ren)
SDL_RenderCopy2(ren,oTex)
SDL_RenderPresent(ren)
SDL_Delay(200)
80.4
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
ren1, SDL_RENDERER_ACCELERATED
˓→PRESENTVSYNC )
SDL_RenderClear(ren)
rect
sdl_set_sdl_rect_x(rect,10)
sdl_set_sdl_rect_y(rect,10)
(continues on next page)
80.3. Switch between two images 973

Ring Documentation, Release 1.14
(continued from previous page)
sdl_set_sdl_rect_w(rect,100)
sdl_set_sdl_rect_h(rect,100)
SDL_SetRenderDrawColor(ren,255,255,255,255)
SDL_RenderDrawRect(ren,rect)
sdl_destroy_sdl_rect(rect)
SDL_RenderPresent(ren)
SDL_Delay(2000)
SDL_DestroyRenderer(ren)
SDL_DestroyWindow(win)
SDL_Quit()
80.5
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
ren1, SDL_RENDERER_ACCELERATED
˓→PRESENTVSYNC )
bmp"hello3.png")
tex
SDL_FreeSurface(bmp)
SDL_RenderClear(ren)
SDL_RenderCopy2(ren,tex)
SDL_RenderPresent(ren)
SDL_Delay(2000)
SDL_DestroyTexture(tex)
SDL_DestroyRenderer(ren)
SDL_DestroyWindow(win)
SDL_Quit()
80.6
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
ren1, SDL_RENDERER_ACCELERATED
˓→PRESENTVSYNC )
SDL_RenderClear(ren)
TTF_Init()
font"pirulen.ttf",)
color
sdl_set_sdl_color_r(color,0)
sdl_set_sdl_color_g(color,255)
sdl_set_sdl_color_b(color,0)
(continues on next page)
80.5. Display PNG Images 974

Ring Documentation, Release 1.14
(continued from previous page)
text"Welcome to the Ring language",color)
surface
SDL_BlitSurface(text, nullpointer(), surface, nullpointer())
SDL_UpdateWindowSurface(win)
SDL_Delay(2000)
SDL_Destroy_SDL_Color(color)
SDL_FreeSurface(text)
TTF_CloseFont(font)
SDL_DestroyRenderer(ren)
SDL_DestroyWindow(win)
SDL_Quit()
80.7
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
flags
IMG_Init(flags)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
ren1, SDL_RENDERER_ACCELERATED
˓→PRESENTVSYNC )
bmp"stars.jpg")
tex
SDL_FreeSurface(bmp)
SDL_RenderClear(ren)
SDL_RenderCopy(ren,tex,nullpointer(),nullpointer())
SDL_DestroyTexture(tex)
bmp"player.png")
# Image - Set Transparent color (white)
myformat
white,,)
SDL_SetColorKey(bmp, SDL_True, white)
tex
SDL_FreeSurface(bmp)
rect
sdl_set_sdl_rect_x(rect,0)
sdl_set_sdl_rect_y(rect,0)
sdl_set_sdl_rect_w(rect,100)
sdl_set_sdl_rect_h(rect,100)
SDL_RenderCopy(ren,tex,nullpointer(),rect)
SDL_SetTextureBlendMode(tex,2)
SDL_SetTextureAlphaMod(tex,255)
sdl_set_sdl_rect_x(rect,200)
sdl_set_sdl_rect_y(rect,200)
(continues on next page)
80.7. Display Transparent Images 975

Ring Documentation, Release 1.14
(continued from previous page)
sdl_set_sdl_rect_w(rect,100)
sdl_set_sdl_rect_h(rect,100)
SDL_RenderCopy(ren,tex,nullpointer(),rect)
SDL_DestroyTexture(tex)
SDL_Destroy_SDL_Rect(rect)
SDL_RenderPresent(ren)
SDL_Delay(2000)
SDL_DestroyRenderer(ren)
SDL_DestroyWindow(win)
SDL_Quit()
80.8
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
myevent
while
thevent
switchsdl_get_sdl_event_type(myevent)
onsdl_get_sdl_quit()
exit
onsdl_get_sdl_keydown()
Key
ifkey exit
off
end
SDL_DestroyWindow(win)
SDL_Quit()
80.9
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Mouse Events,,,,, SDL_WINDOW_SHOWN)
TTF_Init()
font"pirulen.ttf",)
color
(continues on next page)
80.8. Close Window Event 976

Ring Documentation, Release 1.14
(continued from previous page)
sdl_set_sdl_color_r(color,0)
sdl_set_sdl_color_g(color,255)
sdl_set_sdl_color_b(color,0)
surface
myevent
while
cMsg"
sdl_pollevent(myevent)
switchsdl_get_sdl_event_type(myevent)
onSDL_QUIT
exit
onSDL_KEYDOWN
Key
ifkey exit
onSDL_MOUSEBUTTONDOWN
ifsdl_get_Sdl_Event_button_button(myevent)
SDL_SETWINDOWTITLE(win,
butsdl_get_Sdl_Event_button_button(myevent)
˓→MIDDLE
SDL_SETWINDOWTITLE(win,
butsdl_get_Sdl_Event_button_button(myevent)
˓→RIGHT
SDL_SETWINDOWTITLE(win,
ok
onSDL_MOUSEMOTION
sdl_fillrect(surface,nullpointer(),0)
ifsdl_get_sdl_event_motion_xrel(myevent)
cMsg=
else
cMsg=
ok
ifsdl_get_sdl_event_motion_yrel(myevent)
cMsg=
else
cMsg=
ok
cMsg=
cMsg=
showmsg(cMsg)
off
end
SDL_Destroy_SDL_Color(Color)
TTF_CloseFont(font)
SDL_DestroyWindow(win)
SDL_Quit()
funcshowmsg mymsg
text
SDL_BlitSurface(text, nullpointer(), surface, nullpointer())
SDL_UpdateWindowSurface(win)
SDL_FreeSurface(text)
80.9. Mouse Events 977

Ring Documentation, Release 1.14
80.10
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
Mix_OpenAudio(, MIX_DEFAULT_FORMAT ,,)
Mix_AllocateChannels(4)
soundsound.wav"
Mix_VolumeChunk(sound,1)
Mix_PlayChannel(1,sound,0)
myevent
while
thevent
switchsdl_get_sdl_event_type(myevent)
onsdl_get_sdl_quit()
exit
onsdl_get_sdl_keydown()
Key
ifkey exit
off
end
Mix_FreeChunk( sound )
Mix_CloseAudio()
Mix_Quit()
SDL_DestroyWindow(win)
SDL_Quit()
80.10. Play Sound 978

CHAPTER
EIGHTYONE
RINGLIBSDL FUNCTIONS REFERENCE
81.1
In this chapter we have a list of the supported functions by this extension
81.2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
979

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 980

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 981

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 982

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 983

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 984

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 985

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
81.2. Reference 986

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *,SDL_Texture*)
•
•
•
•
•
•
•
• *name,const char*value)
• *name,const char*value,SDL_HintPriority priority)
•
• *SDL_GetError(void)
•
•
•
•
•
• *userdata)
•
•
81.2. Reference 987

Ring Documentation, Release 1.14
•
•
•
•
• *ver)
• *SDL_CreateWindow(const char * title,int x, int y,int w,int h,Uint32 ags)
• *window)
•
•
• *window)
•
• *extension)
• *value)
•
• *SDL_GL_GetCurrentWindow(void)
• *window,int*w,int*h)
• *SDL_GL_GetProcAddress(const char*proc)
•
• *path)
• *window,SDL_GLContext context)
•
•
•
• *window)
•
• *SDL_GetClosestDisplayMode(int displayIndex,SDL_DisplayMode
*mode,SDL_DisplayMode*closest)
• *mode)
• *SDL_GetCurrentVideoDriver(void)
• *mode)
• *rect)
•
•
•
• *SDL_GetWindowData(SDL_Window*window,const char*name)
• *window)
81.2. Reference 988

Ring Documentation, Release 1.14
• *window,SDL_DisplayMode*mode)
• *window)
• *SDL_GetWindowFromID(Uint32 id)
• *window,Uint16*red,Uint16*green,Uint16*blue)
• *window)
•
• *window,int*w,int*h)
• *window,int*w,int*h)
• *window,int*x,int*y)
• *window,int*w,int*h)
• *SDL_GetWindowSurface(SDL_Window*window)
• *SDL_GetWindowTitle(SDL_Window*window)
•
• *window)
• *window)
• *window)
• *window)
• *window,SDL_bool bordered)
• *window,oat brightness)
• *SDL_SetWindowData(SDL_Window*window,const char*name,void*userdata)
• *window,const SDL_DisplayMode*mode)
• *window,Uint32 ags)
• window,const Uint16 *red,const Uint16 *green,const Uint16
blue)
• *window,SDL_bool grabbed)
•
• *window,int w,int h)
• *window,const char*title)
• *messageboxdata,int*buttonid)
• *title,const char*message,SDL_Window*window)
• *window)
• *window)
• *window,const SDL_Rect*rects,int numrects)
• *driver_name)
•
• *SDL_CreateRenderer(SDL_Window*window,int index,Uint32 ags)
81.2. Reference 989

Ring Documentation, Release 1.14
• *SDL_CreateSoftwareRenderer(SDL_Surface*surface)
• *SDL_CreateTexture(SDL_Renderer*renderer,Uint32 format,int access,int w,int h)
• *SDL_CreateTextureFromSurface(SDL_Renderer*renderer,SDL_Surface*surface)
• *texture)
• *texture,oat*texw,oat*texh)
• *texture)
•
• *renderer,SDL_BlendMode*blendMode)
• *renderer,Uint8*r,Uint8*g,Uint8*b,Uint8*a)
• *info)
• *SDL_GetRenderTarget(SDL_Renderer*renderer)
• *SDL_GetRenderer(SDL_Window*window)
• *renderer,SDL_RendererInfo*info)
• *renderer,int*w,int*h)
• *texture,Uint8*alpha)
• *texture,SDL_BlendMode*blendMode)
• *texture,Uint8*r,Uint8*g,Uint8*b)
• *texture,const SDL_Rect*rect,void**pixels,int*pitch)
• *texture,int*format,int*access,int*w,int*h)
• *renderer)
• *renderer,SDL_Texture*texture,const SDL_Rect*srcrect,const
SDL_Rect*dstrect)
• *renderer,SDL_Texture*texture,const SDL_Rect*srcrect,const
SDL_Rect*dstrect,const double angle,const SDL_Point*center,const SDL_RendererFlip ip)
• *renderer,int x1,int y1,int x2,int y2)
• *renderer,const SDL_Point*points,int count)
• *renderer,int x, int y)
• *renderer,const SDL_Point*points,int count)
• *renderer,const SDL_Rect*rect)
• *renderer,const SDL_Rect*rects,int count)
• *renderer,const SDL_Rect*rect)
• renderer,const SDL_Rectrects,int count)
• *renderer,SDL_Rect*rect)
• *renderer,oat*scaleX,oat*scaleY)
• *renderer,SDL_Rect*rect)
• *renderer,const SDL_Rect*rect,Uint32 format,void*pixels,int
pitch)
81.2. Reference 990

Ring Documentation, Release 1.14
• *renderer,const SDL_Rect*rect)
• *renderer,oat scaleX,oat scaleY)
• *renderer,const SDL_Rect*rect)
• *renderer)
• *renderer,SDL_BlendMode blendMode)
• *renderer,Uint8 r,Uint8 g,Uint8 b,Uint8 a)
• *renderer,SDL_Texture*texture)
• *texture,Uint8 alpha)
• *texture,SDL_BlendMode blendMode)
• *texture,Uint8 r,Uint8 g,Uint8 b)
• *texture)
• *texture,const SDL_Rect*rect,const void*pixels,int pitch)
• *texture,const SDL_Rect*rect,const Uint8*Yplane,int Yp-
itch,const Uint8*Uplane,int Upitch,const Uint8*Vplane,int Vpitch)
• *SDL_AllocFormat(Uint32 pixel_format)
• *SDL_AllocPalette(int ncolors)
• *ramp)
• *format)
• *palette)
• *SDL_GetPixelFormatName(Uint32 format)
• *r,Uint8*g,Uint8*b)
• *r,Uint8*g,Uint8*b,Uint8*a)
•
•
•
• *bpp,Uint32*Rmask,Uint32*Gmask,Uint32
*Bmask,Uint32*Amask)
• *palette,const SDL_Color*colors,int rstcolor,int ncolors)
• *format,SDL_Palette*palette)
• *clip,SDL_Rect*result)
• *A,const SDL_Rect*B)
• *A,const SDL_Rect*B,SDL_Rect*result)
• *rect,int*X1,int*Y1,int*X2,int*Y2)
• *a,const SDL_Rect*b)
• *A,const SDL_Rect*B,SDL_Rect*result)
• *src,const SDL_Rect*srcrect,SDL_Surface*dst,SDL_Rect*dstrect)
• src,const SDL_Rectsrcrect,SDL_Surface*dst,SDL_Rect*dstrect)
81.2. Reference 991

Ring Documentation, Release 1.14
• *src,int src_pitch,Uint32
dst_format,void*dst,int dst_pitch)
• *SDL_ConvertSurface(SDL_Surface*src,const SDL_PixelFormat*fmt,Uint32 ags)
• *SDL_ConvertSurfaceFormat(SDL_Surface*src,Uint32 pixel_format,Uint32 ags)
• *SDL_CreateRGBSurface(Uint32 ags,int width,int height,int depth,Uint32 Rmask,Uint32
Gmask,Uint32 Bmask,Uint32 Amask)
• *pixels,int width,int height,int depth,int pitch,Uint32
Rmask,Uint32 Gmask,Uint32 Bmask,Uint32 Amask)
• *dst,const SDL_Rect*rect,Uint32 color)
• *dst,const SDL_Rect*rects,int count,Uint32 color)
• *surface)
• *surface,SDL_Rect*rect)
• *surface,Uint32*key)
• *surface,Uint8*alpha)
• *surface,SDL_BlendMode*blendMode)
• *surface,Uint8*r,Uint8*g,Uint8*b)
• *SDL_LoadBMP(const char*le)
• *SDL_LoadBMP_RW(SDL_RWops *src,int freesrc)
• *surface)
• *src,SDL_Rect*srcrect,SDL_Surface*dst,SDL_Rect*dstrect)
• *src,SDL_Rect*srcrect,SDL_Surface*dst,SDL_Rect*dstrect)
• *surface)
• *surface,const char*le)
• *surface,SDL_RWops*dst,int freedst)
• *surface,const SDL_Rect*rect)
• *surface,int ag,Uint32 key)
• *surface,Uint8 alpha)
• *surface,SDL_BlendMode blendMode)
• *surface,Uint8 r,Uint8 g,Uint8 b)
• *surface,SDL_Palette*palette)
• *surface,int ag)
•
• *window,SDL_SysWMinfo*info)
• *SDL_GetClipboardText(void)
•
• *text)
• *userdata)
81.2. Reference 992

Ring Documentation, Release 1.14
• *userdata)
•
• *userdata)
•
•
• *lter,void**userdata)
•
•
•
•
•
•
•
• *src)
• *events,int numevents,SDL_eventaction action,Uint32 minType,Uint32 max-
Type)
• *event)
•
• *event)
•
•
•
• *dst)
• *dst)
• *userdata)
• *event)
• *event,int timeout)
•
•
•
•
•
•
•
•
•
81.2. Reference 993

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
• *SDL_CreateCursor(const Uint8*data,const Uint8*mask,int w,int h,int hot_x,int hot_y)
• *cursor)
• *SDL_GetCursor(void)
• *SDL_GetDefaultCursor(void)
• *x,int * y)
•
• *x,int*y)
• *cursor)
•
•
• *joystick)
• *joystick)
• *joystick,int axis)
• *joystick,int ball,int*dx,int*dy)
• *joystick,int button)
•
• *joystick)
• *pchGUID)
• *pszGUID,int cbGUID)
• *joystick,int hat)
• *joystick)
• *SDL_JoystickName(SDL_Joystick*joystick)
• *SDL_JoystickNameForIndex(int device_index)
• *joystick)
• *joystick)
• *joystick)
• *joystick)
• *SDL_JoystickOpen(int device_index)
•
81.2. Reference 994

Ring Documentation, Release 1.14
•
• *mappingString)
• *lename)
• *rw,int freerw)
• *gamecontroller)
•
• *gamecontroller,SDL_GameControllerAxis axis)
• *pchString)
• *gamecon-
troller,SDL_GameControllerAxis axis)
• *gamecon-
troller,SDL_GameControllerButton button)
• *gamecontroller,SDL_GameControllerButton
button)
• *pchString)
• *SDL_GameControllerGetJoystick(SDL_GameController*gamecontroller)
• *SDL_GameControllerGetStringForAxis(SDL_GameControllerAxis axis)
• *SDL_GameControllerGetStringForButton(SDL_GameControllerButton button)
• *SDL_GameControllerMapping(SDL_GameController*gamecontroller)
• *SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid)
• *SDL_GameControllerName(SDL_GameController*gamecontroller)
• *SDL_GameControllerNameForIndex(int joystick_index)
•
•
•
•
• *haptic,int effect)
• *haptic,SDL_HapticEffect*effect)
• *haptic,int effect)
• *haptic)
• *SDL_HapticName(int device_index)
• *haptic,SDL_HapticEffect*effect)
• *haptic)
• *haptic)
• *haptic)
• *SDL_HapticOpen(int device_index)
• *SDL_HapticOpenFromJoystick(SDL_Joystick*joystick)
81.2. Reference 995

Ring Documentation, Release 1.14
• *SDL_HapticOpenFromMouse(void)
•
• *haptic)
• *haptic)
• *haptic)
• *haptic,oat strength,Uint32 length)
• *haptic)
• *haptic)
• *haptic,int effect,Uint32 iterations)
• *haptic,int autocenter)
• *haptic,int gain)
• *haptic)
• *haptic,int effect)
• *haptic)
• *haptic,int effect,SDL_HapticEffect*data)
• *joystick)
•
•
•
•
• *cvt,SDL_AudioFormat src_format,Uint8 src_channels,int
src_rate,SDL_AudioFormat dst_format,Uint8 dst_channels,int dst_rate)
•
• *cvt)
• *audio_buf)
•
•
•
•
•
•
•
• *SDL_LoadWAV_RW(SDL_RWops *src,int freesrc,SDL_AudioSpec*spec,Uint8**au-
dio_buf,Uint32*audio_len)
•
•
• dst,const Uint8src,Uint32 len,int volume)
81.2. Reference 996

Ring Documentation, Release 1.14
• *dst,const Uint8*src,SDL_AudioFormat format,Uint32 len,int volume)
• *desired,SDL_AudioSpec*obtained)
• *device,int iscapture,const SDL_AudioSpec*de-
sired,SDL_AudioSpec*obtained,int allowed_changes)
•
•
•
•
• *SDL_GetBasePath(void)
• *SDL_GetPrefPath(const char*org,const char*app)
• *SDL_AllocRW(void)
• *area)
• SDL_RWFromConstMem(const voidmem,int size)
• *SDL_RWFromFP(void*fp,SDL_bool autoclose)
• *SDL_RWFromFile(const char*le,const char*mode)
• *SDL_RWFromMem(void*mem,int size)
• *context)
• *context,void*ptr,size_t size,size_t maxnum)
• *context,Sint64 offset,int whence)
• *context)
• *context)
• *context,const void*ptr,size_t size,size_t num)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *dst,Uint16 value)
• *dst,Uint32 value)
• *dst,Uint64 value)
• *dst,Uint16 value)
• *dst,Uint32 value)
• *dst,Uint64 value)
• *dst,Uint8 value)
81.2. Reference 997

Ring Documentation, Release 1.14
• *SDL_LoadFunction(void*handle,const char*name)
• *SDL_LoadObject(const char*sole)
• *handle)
• *SDL_GetPlatform(void)
•
•
•
•
•
•
•
•
•
•
•
•
• *secs,int*pct)
•
•
•
• *IMG_Load(const char*le)
• *IMG_Load_RW(SDL_RWops*src, int freesrc)
• *IMG_LoadTyped_RW(SDL_RWops*src, int freesrc, char*type)
• *IMG_LoadCUR_RW(SDL_RWops *src)
• *IMG_LoadBMP_RW(SDL_RWops *src)
• *IMG_LoadPNM_RW(SDL_RWops *src)
• *IMG_LoadXPM_RW(SDL_RWops *src)
• *IMG_LoadXCF_RW(SDL_RWops *src)
• *IMG_LoadPCX_RW(SDL_RWops *src)
• *IMG_LoadGIF_RW(SDL_RWops *src)
• *IMG_LoadJPG_RW(SDL_RWops *src)
• *IMG_LoadTIF_RW(SDL_RWops*src)
• *IMG_LoadPNG_RW(SDL_RWops *src)
• *IMG_LoadTGA_RW(SDL_RWops *src)
• *IMG_LoadLBM_RW(SDL_RWops *src)
• *IMG_LoadXV_RW(SDL_RWops *src)
81.2. Reference 998

Ring Documentation, Release 1.14
• *IMG_ReadXPMFromArray(char**xpm)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
• *src)
•
•
•
• *TTF_OpenFont(const char*le, int ptsize)
• *TTF_OpenFontRW(SDL_RWops*src, int freesrc, int ptsize)
• *TTF_OpenFontIndex(const char*le, int ptsize, long index)
• *TTF_OpenFontIndexRW(SDL_RWops*src, int freesrc, int ptsize, long index)
• *font)
•
• *font)
• *font, int style)
• *font)
• *font, int outline)
• *font)
• *font, int hinting)
• *font)
• *font, int allowed)
• *font)
• *font)
• *font)
• *font)
• *font)
81.2. Reference 999

Ring Documentation, Release 1.14
• *font)
• *TTF_FontFaceFamilyName(const TTF_Font*font)
• *TTF_FontFaceStyleName(const TTF_Font*font)
• *font, Uint16 ch)
• *font, Uint16 ch, int*minx, int*maxx, int*miny, int*maxy, int*advance)
• *font, const char*text, int*w, int*h)
• *font, const char*text, int*w, int*h)
• *font, const Uint16*text, int*w, int*h)
• *TTF_RenderText_Solid(TTF_Font*font, const char*text, SDL_Color fg)
• *TTF_RenderUTF8_Solid(TTF_Font*font, const char*text,SDL_Color fg)
• *TTF_RenderUNICODE_Solid(TTF_Font*font, const Uint16*text,SDL_Color fg)
• *TTF_RenderGlyph_Solid(TTF_Font*font, Uint16 ch, SDL_Color fg)
• *TTF_RenderText_Shaded(TTF_Font*font, const char*text,SDL_Color fg, SDL_Color bg)
• *TTF_RenderUTF8_Shaded(TTF_Font*font, const char*text,SDL_Color fg, SDL_Color bg)
• *TTF_RenderUNICODE_Shaded(TTF_Font*font, const Uint16*text,SDL_Color fg,
SDL_Color bg)
• *TTF_RenderGlyph_Shaded(TTF_Font*font, Uint16 ch, SDL_Color fg,SDL_Color bg)
• *TTF_RenderText_Blended(TTF_Font*font, const char*text,SDL_Color fg)
• *TTF_RenderUTF8_Blended(TTF_Font*font, const char*text,SDL_Color fg)
• *TTF_RenderUNICODE_Blended(TTF_Font*font, const Uint16*text,SDL_Color fg)
• *TTF_RenderGlyph_Blended(TTF_Font*font, Uint16 ch, SDL_Color fg)
•
•
•
•
• *frequency, Uint16*format, int*channels)
•
• *Mix_GetChunkDecoder(int index)
• *Mix_LoadWAV(char*le)
• *Mix_LoadWAV_RW(SDL_RWops *src, int freesrc)
• *Mix_QuickLoad_WAV(Uint8*mem)
• *chunk)
•
•
• *chunk, int loops)
• *chunk, int loops, int ticks)
81.2. Reference 1000

Ring Documentation, Release 1.14
• *chunk, int loops, int ms)
• *chunk,int loops, int ms, int ticks)
•
•
•
•
•
•
•
• *Mix_GetChunk(int channel)
•
•
•
•
•
•
•
•
•
•
• *Mix_GetMusicDecoder(int index)
• *Mix_LoadMUS(const char*le)
• *music)
• *music, int loops)
• *music, int loops, int ms)
• *music, int loops, int ms, double position)
•
•
•
• *Mix_GetMusicHookData(void)
• *arg)
•
•
•
•
•
81.2. Reference 1001

Ring Documentation, Release 1.14
•
•
• *SDLNet_GetError(void)
• *area)
• *area)
• *area)
• *area)
• *address, const char*host, Uint16 port)
• *SDLNet_ResolveIP(IPaddress*address)
• *ip)
•
•
• *data, int len)
• *data, int maxlen)
•
•
• *address)
•
• *SDLNet_UDP_GetPeerAddress(UDPsocket sock, int channel)
• *packet)
• *packet)
• **packetV, int npackets)
• **packetV)
• *SDLNet_AllocPacket(int size)
• *packet, int size)
• *packet)
• **SDLNet_AllocPacketV(int howmany, int size)
• **packetV)
•
•
•
•
•
•
•
•
81.2. Reference 1002

Ring Documentation, Release 1.14
•
•
•
• *SDL_CreateThread(SDL_ThreadFunction fn,const char*name,void*data)
• *thread)
• *thread)
• SDL_GetThreadName(SDL_Threadthread)
•
•
• *SDL_TLSGet(SDL_TLSID id)
• *value,void*)
•
• *thread,int*status)
• *cond)
• *cond)
• *cond,SDL_mutex*mutex)
• *cond,SDL_mutex*mutex,Uint32 ms)
• *SDL_CreateCond(void)
• *SDL_CreateMutex(void)
• *SDL_CreateSemaphore(Uint32 initial_value)
• *cond)
• *mutex)
• *sem)
• *mutex)
• *sem)
• *sem)
• *sem)
• *sem)
• *sem,Uint32 ms)
• *mutex)
• *mutex)
81.2. Reference 1003

CHAPTER
EIGHTYTWO
USING RINGLIBUV
In this chapter we will learn about using RingLibuv
Note:To use RingLibuv, Check ring/extensions/ringlibuv folder.
Information from the library website:
Libuv is a multi-platform support library with a focus on asynchronous I/O.
Feature highlights
•
•
•
•
•
•
•
•
•
•
•
•
82.1
Example:
load"libuv.ring"
funcmain
myloop
uv_loop_init(myloop)
?Now quitting"
(continues on next page)
1004

Ring Documentation, Release 1.14
(continued from previous page)
uv_run(myloop, UV_RUN_DEFAULT)
uv_loop_close(myloop)
destroy_uv_loop_t(myloop)
Output:
Now quitting
82.2
Example:
load"libuv.ring"
counter
idler NULL
funcmain
idler
uv_idle_init(uv_default_loop(), idler)
uv_idle_start(idler,wait()")
?Idling..."
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
uv_loop_close(uv_default_loop());
destroy_uv_idle_t(idler)
funcwait
counter++
ifcounter=
uv_idle_stop(idler)
ok
Output:
Idling...
82.3
Example:
load"libuv.ring"
?Testing RingLibuv - Server Side"
DEFAULT_PORT
DEFAULT_BACKLOG
addr
server NULL
client NULL
myloop NULL
(continues on next page)
82.2. The Events Loop 1005

Ring Documentation, Release 1.14
(continued from previous page)
funcmain
myloop
server
uv_tcp_init(myloop, server)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_bind(server, addr,)
rnewconnection()")
ifr
?Listen error
return1
ok
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(server)
destroy_uv_sockaddr_in(addr)
funcnewconnection
?New Connection"
aPara
nStatus[2]
ifnStatus
?New connection error :
return
ok
client
uv_tcp_init(myloop, client)
ifuv_accept(server, client)
uv_read_start(client, uv_myalloccallback(),echo_read()")
ok
funcecho_read
aPara
nRead[2]
buf[3]
ifnRead
req
wrbuf
uv_write(req, client, wrbuf,,echo_write()")
?
messagemessage from the server to the client"
buf
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message",:char))
uv_write(req, client, buf,,echo_write()")
ok
funcecho_write
aPara
req[1]
Output:
When we run the client, We will see the message “New Connection”
Then the message “hello from the client”
Testing RingLibuv - Server Side
(continues on next page)
82.3. Server Example 1006

Ring Documentation, Release 1.14
(continued from previous page)
New Connection
hello from the client
82.4
Example:
load"libuv.ring"
?Testing RingLibuv - Client Side"
DEFAULT_PORT
DEFAULT_BACKLOG
addr
connect NULL
buffer null
socket null
funcmain
myloop
Socket
connect
uv_tcp_init(myloop, Socket)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_connect(connect,Socket, addr,connect()")
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(socket)
destroy_uv_connect_t(connect)
funcconnect
?Client: Start Connection"
aPara
req[1]
nStatus[2]
ifnStatus1
?Error : on_write_end
return
ok
buf
messagehello from the client"
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message",:char))
tcp
write_req
buf_count
uv_write(write_req, tcp, buf, buf_count,on_write_end()")
funcon_write_end
uv_read_start(socket, uv_myalloccallback(),echo_read()")
funcecho_read
aPara
nRead[2]
(continues on next page)
82.4. Client Example 1007

Ring Documentation, Release 1.14
(continued from previous page)
buf[3]
ifnRead
wrbuf
?
ok
Output:
We will run the client after the server
Testing RingLibuv - Client Side
Client: Start Connection
hello from the client
message from the server to the client
82.5
Example:
load"libuv.ring"
load"objectslib.ring"
?Testing RingLibuv - Server Side - Using Classes"
open_object(:MyServer)
classMyServerfromObjectControllerParent
DEFAULT_PORT
DEFAULT_BACKLOG
addr
server NULL
client NULL
myloop NULL
funcstart
myloop
server
uv_tcp_init(myloop, server)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_bind(server, addr,)
r
ifr
?Listen error
return1
ok
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(server)
destroy_uv_sockaddr_in(addr)
funcnewconnection
?New Connection"
aPara
(continues on next page)
82.5. Server Example Using Classes 1008

Ring Documentation, Release 1.14
(continued from previous page)
nStatus[2]
ifnStatus
?New connection error :
return
ok
client
uv_tcp_init(myloop, client)
ifuv_accept(server, client)
uv_read_start(client, uv_myalloccallback(),
Method(:echo_read))
ok
funcecho_read
aPara
nRead[2]
buf[3]
ifnRead
req
wrbuf
uv_write(req, client, wrbuf,, Method(:echo_write))
?
messagemessage from the server to the client"
buf
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message",:char))
uv_write(req, client, buf,, Method(:echo_write))
ok
funcecho_write
aPara
req[1]
Output:
When we run the client, We will see the message “New Connection”
Then the message “hello from the client”
Testing RingLibuv - Server Side - Using Classes
New Connection
hello from the client
82.6
Example:
load"libuv.ring"
load"objectslib.ring"
?Testing RingLibuv - Client Side - Using Classes"
open_object(:MyClient)
ClassMyClientfromObjectControllerParent
(continues on next page)
82.6. Client Example Using Classes 1009

Ring Documentation, Release 1.14
(continued from previous page)
DEFAULT_PORT
DEFAULT_BACKLOG
addr
connect NULL
buffer null
socket null
funcstart
myloop
Socket
connect
uv_tcp_init(myloop, Socket)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_connect(connect,Socket, addr, Method(:connect))
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(socket)
destroy_uv_connect_t(connect)
funcconnect
?Client: Start Connection"
aPara
req[1]
nStatus[2]
ifnStatus1
?Error : on_write_end
return
ok
buf
messagehello from the client"
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message",:char))
tcp
write_req
buf_count
uv_write(write_req, tcp, buf, buf_count, Method(:on_write_end))
funcon_write_end
uv_read_start(socket, uv_myalloccallback(), Method(:echo_
˓→read))
funcecho_read
aPara
nRead[2]
buf[3]
ifnRead
wrbuf
?
ok
Output:
We will run the client after the server
Testing RingLibuv - Client Side - Using Classes
Client: Start Connection
hello from the client
(continues on next page)
82.6. Client Example Using Classes 1010

Ring Documentation, Release 1.14
(continued from previous page)
message from the server to the client
82.7
Example:
load"libuv.ring"
?Testing RingLibuv - Threads"
funcmain
one_id
two_id
uv_thread_create(one_id,one()")
uv_thread_create(two_id,two()")
uv_thread_join(one_id)
uv_thread_join(two_id)
destroy_uv_thread_t(one_id)
destroy_uv_thread_t(two_id)
funcone
?Message from the First Thread!"
functwo
?Message from the Second Thread!"
Output:
Testing RingLibuv - Threads
Message from the First Thread!
Message from the Second Thread!
82.8
Example:
load"libuv.ring"
load"objectslib.ring"
?Testing RingLibuv - Threads - Using Classes"
open_object(:MyThreads)
classMyThreadsfromObjectControllerParent
funcStart
one_id
two_id
uv_thread_create(one_id, Method(:One))
uv_thread_create(two_id, Method(:Two))
uv_thread_join(one_id)
(continues on next page)
82.7. Threads Example 1011

Ring Documentation, Release 1.14
(continued from previous page)
uv_thread_join(two_id)
destroy_uv_thread_t(one_id)
destroy_uv_thread_t(two_id)
funcone
?Message from the First Thread!"
funcTwo
?Message from the Second Thread!"
Output:
Testing RingLibuv - Threads - Using Classes
Message from the First Thread!
Message from the Second Thread!
82.8. Threads Example - Using Classes 1012

CHAPTER
EIGHTYTHREE
RINGLIBUV FUNCTIONS REFERENCE
83.1
In this chapter we have a list of the supported functions by this extension
83.2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1013

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
83.2. Reference 1014

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *bufs, unsigned int nbufs, uv_write_cb cb)
• *bufs, unsigned int nbufs, uv_write_cb cb)
• bufs, unsigned int nbufs, uv_stream_t
send_handle, uv_write_cb cb)
• bufs, unsigned int nbufs, uv_stream_t
send_handle, uv_write_cb cb)
• *bufs, unsigned int nbufs)
•
•
•
•
•
•
•
•
•
• *handle,sockaddr*addr,unsigned int ags)
•
•
•
•
•
83.2. Reference 1015

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
uv_membership membership)
•
•
•
•
•
• *bufs, unsigned int nbufs, sockaddr * addr,
uv_udp_send_cb send_cb)
• *bufs, unsigned int nbufs, sockaddr *
addr, uv_udp_send_cb send_cb)
• *bufs, unsigned int nbufs, sockaddr * addr)
•
•
•
•
•
•
83.2. Reference 1016

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
• *bufs, unsigned int nbufs, int64_t offset,
uv_fs_cb cb)
•
• *bufs, unsigned int nbufs, int64_t offset,
uv_fs_cb cb)
•
•
•
•
•
•
•
•
•
•
•
•
•
cb)
•
uv_fs_cb cb)
•
•
•
•
•
•
83.2. Reference 1017

Ring Documentation, Release 1.14
•
cb)
•
•
•
•
•
•
• *bufs, unsigned int nbufs, int64_t offset,
uv_fs_cb cb)
•
• *bufs, unsigned int nbufs, int64_t offset,
uv_fs_cb cb)
•
•
•
•
•
•
•
•
•
•
•
•
cb)
•
length, uv_fs_cb cb)
•
•
•
•
•
•
•
cb)
•
•
83.2. Reference 1018

Ring Documentation, Release 1.14
•
•
•
ter_work_cb)
•
ter_work_cb)
•
node, const char * service, const struct addrinfo* hints)
•
node, const char * service, const struct addrinfo* hints)
•
•
addr, int ags)
•
* addr, int ags)
•
•
•
•
•
•
•
• *tid)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
83.2. Reference 1019

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
loc_func, uv_free_func free_func)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
83.2. Reference 1020

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
83.2. Reference 1021

CHAPTER
EIGHTYFOUR
RINGFREEGLUT FUNCTIONS REFERENCE
84.1
In this chapter we have a list of the supported functions by this extension
84.2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1022

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1023

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1024

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1025

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1026

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *)
• *)
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1027

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *font, int character)
84.2. Reference 1028

Ring Documentation, Release 1.14
• *font, int character)
• *font, int character)
• *font, int character)
• *font, char * string)
• *font, int character)
• *font, char*string)
• *font, char * string)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1029

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
• *)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1030

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *font)
•
• *glutGetModeValues(GLenum mode, int * size)
• *glutGetWindowData( void )
• *data)
• *glutGetMenuData( void )
• *data)
•
•
• *string )
• *string )
•
•
• *offset, double scale )
84.2. Reference 1031

Ring Documentation, Release 1.14
• *offset, double scale )
•
•
•
•
•
•
•
•
•
•
•
•
84.2. Reference 1032

CHAPTER
EIGHTYFIVE
RINGSTBIMAGE FUNCTIONS REFERENCE
85.1
In this chapter we have a list of the supported functions by this extension
Example:
# Load the library
load"stbimage.ring"
# Image Information
width=0=0=0
# Ring will Free cData automatically in the end of the program
cData"ring.jpg",:width,:height,:channels,STBI_rgb)
# Display the output
?Size (bytes):
?Width :
?Height:
?Channels:
Output:
Size (bytes):
Width :
Height:
Channels:
85.2
•
•
•
•
•
1033

Ring Documentation, Release 1.14
85.3
• *stbi_load_from_memory(stbi_uc const*buffer, int len,int*x, int*y, int*channels_in_le, int de-
sired_channels)
• *stbi_load(char const*lename, int*x, int*y, int*channels_in_le, int desired_channels)
• *stbi_load_from_le(FILE*f, int*x, int*y, int*channels_in_le, int desired_channels)
• *stbi_load_16_from_memory(stbi_uc const*buffer, int len, int*x, int*y, int*channels_in_le, int
desired_channels)
• *stbi_load_16(char const*lename, int*x, int*y, int*channels_in_le, int desired_channels)
• *stbi_load_from_le_16(FILE*f, int*x, int*y, int*channels_in_le, int desired_channels)
• *stbi_loadf_from_memory(stbi_uc const*buffer, int len, int*x, int*y, int*channels_in_le, int de-
sired_channels)
• *stbi_loadf(char const*lename, int*x, int*y, int*channels_in_le, int desired_channels)
• *stbi_loadf_from_le(FILE*f, int*x, int*y, int*channels_in_le, int desired_channels)
•
•
•
•
• *buffer, int len)
• *lename)
• *f)
• *stbi_failure_reason(void)
• *buffer, int len, int*x, int*y, int*comp)
• *buffer, int len)
• *lename,int*x,int*y,int*comp)
• *f,int*x,int*y,int*comp)
• *lename)
• *f)
•
•
•
•
• *stbi_zlib_decode_malloc_guesssize(const char*buffer, int len, int initial_size, int*outlen)
• *stbi_zlib_decode_malloc_guesssize_headerag(const char*buffer, int len, int initial_size, int*outlen, int
parse_header)
• *stbi_zlib_decode_malloc(const char*buffer, int len, int*outlen)
• *obuffer,int olen, const char*ibuffer, int ilen)
• *stbi_zlib_decode_noheader_malloc(const char*buffer, int len, int*outlen)
85.3. Functions 1034

Ring Documentation, Release 1.14
• *obuffer, int olen, const char*ibuffer, int ilen)
85.3. Functions 1035

CHAPTER
EIGHTYSIX
RINGOPENGL (OPENGL 3.2) FUNCTIONS REFERENCE
86.1
In this chapter we have a list of the supported functions by this extension
86.2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1036

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1037

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1038

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1039

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1040

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1041

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1042

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1043

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1044

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1045

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1046

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1047

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1048

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1049

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1050

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1051

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1052

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1053

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1054

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1055

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1056

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1057

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1058

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1059

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1060

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1061

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1062

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1063

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1064

Ring Documentation, Release 1.14
•
•
•
•
•
• *name)
•
•
•
GLubyte * bitmap)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1065

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
* data)
•
GLvoid * data)
•
•
•
•
der,GLsizei imageSize,const GLvoid * data)
•
height,GLint border,GLsizei imageSize,const GLvoid * data)
86.2. Reference 1066

Ring Documentation, Release 1.14
•
height,GLsizei depth,GLint border,GLsizei imageSize,const GLvoid * data)
•
mat,GLsizei imageSize,const GLvoid * data)
•
width,GLsizei height,GLenum format,GLsizei imageSize,const GLvoid * data)
•
set,GLsizei width,GLsizei height,GLsizei depth,GLenum format,GLsizei imageSize,const GLvoid * data)
•
type,const GLvoid * data)
•
format,GLenum type,const GLvoid * data)
•
•
•
•
•
•
•
•
width,GLsizei height)
•
•
width,GLint border)
•
width,GLsizei height,GLint border)
•
•
width,GLsizei height)
•
x,GLint y,GLsizei width,GLsizei height)
•
•
•
•
•
•
•
•
•
86.2. Reference 1067

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
• *bufs)
•
•
•
GLvoid * indices)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1068

Ring Documentation, Release 1.14
•
•
•
•
•
farVal)
•
•
•
•
•
•
•
•
• *length,GLint*size,GLenum
*type,GLchar*name)
• *length,GLint
*size,GLenum*type,GLchar*name)
• *count,GLuint*shaders)
• *name)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1069

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
• *params)
• *length,GLchar*infoLog)
•
•
•
•
umn,GLvoid * span)
• *params)
• *length,GLchar*infoLog)
• *length,GLchar*source)
• *glGetString(GLenum name)
•
•
•
•
•
•
•
•
•
•
• *params)
• *params)
86.2. Reference 1070

Ring Documentation, Release 1.14
• *name)
• *params)
• *params)
• *params)
• **pointer)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1071

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
vstride,GLint vorder,const GLoat * points)
•
v2,GLint vstride,GLint vorder,const GLdouble * points)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
dices,GLsizei primcount)
•
•
•
•
86.2. Reference 1072

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1073

Ring Documentation, Release 1.14
•
•
•
•
•
Val)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1074

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1075

Ring Documentation, Release 1.14
•
•
•
•
mat,GLenum type,const GLvoid * row,const GLvoid * column)
•
• **string,const GLint*length)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1076

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
format,GLenum type,const GLvoid * data)
•
der,GLenum format,GLenum type,const GLvoid * data)
•
depth,GLint border,GLenum format,GLenum type,const GLvoid * data)
•
•
•
•
•
type,const GLvoid * data)
•
height,GLenum format,GLenum type,const GLvoid * data)
•
width,GLsizei height,GLsizei depth,GLenum format,GLenum type,const GLvoid * data)
•
•
•
•
86.2. Reference 1077

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1078

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
86.2. Reference 1079

Ring Documentation, Release 1.14
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
• *v)
•
GLvoid * pointer)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
86.2. Reference 1080

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
GLint * view)
•
terY,GLdouble centerZ,GLdouble upX,GLdouble upY,GLdouble upZ)
• *gluNewNurbsRenderer(void)
• *gluNewQuadric(void)
•
•
•
order,GLenum type)
•
•
tKnots,GLint sStride,GLint tStride,GLoat* control,GLint sOrder,GLint tOrder,GLenum type)
•
•
start,GLdouble sweep)
•
•
•
proj,const GLint * view,GLdouble* winX,GLdouble* winY,GLdouble* winZ)
•
•
•
•
•
•
wOut,GLsizei hOut,GLenum typeOut,GLvoid* dataOut)
•
•
•
86.2. Reference 1081

Ring Documentation, Release 1.14
•
•
•
•
•
•
ble * proj,const GLint * view,GLdouble* objX,GLdouble* objY,GLdouble* objZ)
•
•
•
•
•
• *name)
• *name)
• *glewGetErrorString(GLenum error)
• *glewGetString(GLenum name)
86.2. Reference 1082

CHAPTER
EIGHTYSEVEN
RINGQT CLASSES REFERENCE
87.1
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1083

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
87.1. AbstractAxis Class 1084

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcolorChangedEvent(void)
• *getgridLineColorChangedEvent(void)
• *getgridLinePenChangedEvent(void)
• *getgridVisibleChangedEvent(void)
• *getlabelsAngleChangedEvent(void)
• *getlabelsBrushChangedEvent(void)
• *getlabelsColorChangedEvent(void)
• *getlabelsEditableChangedEvent(void)
• *getlabelsFontChangedEvent(void)
• *getlabelsVisibleChangedEvent(void)
• *getlinePenChangedEvent(void)
• *getlineVisibleChangedEvent(void)
• *getminorGridLineColorChangedEvent(void)
• *getminorGridLinePenChangedEvent(void)
• *getminorGridVisibleChangedEvent(void)
• *getreverseChangedEvent(void)
87.1. AbstractAxis Class 1085

Ring Documentation, Release 1.14
• *getshadesBorderColorChangedEvent(void)
• *getshadesBrushChangedEvent(void)
• *getshadesColorChangedEvent(void)
• *getshadesPenChangedEvent(void)
• *getshadesVisibleChangedEvent(void)
• *gettitleBrushChangedEvent(void)
• *gettitleFontChangedEvent(void)
• *gettitleTextChangedEvent(void)
• *gettitleVisibleChangedEvent(void)
• *getvisibleChangedEvent(void)
87.2
Parameters : void
Parent Class : AbstractSeries
• *set)
•
•
• *set)
•
•
•
•
•
• *set)
•
•
•
•
•
•
• *set)
• *)
• *)
• *)
• *)
87.2. AbstractBarSeries Class 1086

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getbarsetsAddedEvent(void)
• *getbarsetsRemovedEvent(void)
• *getclickedEvent(void)
• *getcountChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getlabelsAngleChangedEvent(void)
• *getlabelsFormatChangedEvent(void)
• *getlabelsPositionChangedEvent(void)
• *getlabelsPrecisionChangedEvent(void)
• *getlabelsVisibleChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
87.3
Parameters : QWidget *
Parent Class : QPlainTextEdit
• *c)
• *completer(void)
•
•
87.3. CodeEditor Class 1087

Ring Documentation, Release 1.14
87.4
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
87.5
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
• *group(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.4. QAbstractAspect Class 1088

Ring Documentation, Release 1.14
•
87.6
C++ Reference :
Parent Class : QEntity
•
•
•
•
•
•
• *camera)
•
•
•
87.7
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractScrollArea
•
•
•
•
•
•
•
•
•
•
•
•
•
• *indexWidget(QModelIndex)
• *itemDelegate(QModelIndex)
87.6. QAbstractCameraController Class 1089

Ring Documentation, Release 1.14
• *itemDelegateForColumn(int column)
• *itemDelegateForRow(int row)
•
• *model(void)
•
•
•
•
•
• *selectionModel(void)
•
•
•
•
•
•
•
•
•
•
•
• *widget)
• *delegate)
• *delegate)
• *delegate)
• *model)
•
•
• *selectionModel)
•
•
•
•
•
•
•
87.7. QAbstractItemView Class 1090

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
87.8
C++ Reference :
Parameters : QPrinter*,QWidget *
Parent Class : QDialog
•
•
•
•
•
•
•
• *> tabs)
•
•
87.9
C++ Reference :
Parameters : QWidget*parent
Parent Class : QFrame
• *widget, Qt::AlignmentFlag alignment)
• *cornerWidget(void)
• *horizontalScrollBar(void)
•
•
87.8. QAbstractPrintDialog Class 1091

Ring Documentation, Release 1.14
•
• *widget)
• *scrollBar)
•
• *scrollBar)
•
• *widget)
• *verticalScrollBar(void)
•
• *viewport(void)
87.10
C++ Reference :
Parameters : void
Parent Class : QObject
• *axis)
• *> attachedAxes(void)
• *chart(void)
• *axis)
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *getnameChangedEvent(void)
• *getopacityChangedEvent(void)
87.10. QAbstractSeries Class 1092

Ring Documentation, Release 1.14
• *getuseOpenGLChangedEvent(void)
• *getvisibleChangedEvent(void)
87.11
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.11. QAbstractSlider Class 1093

Ring Documentation, Release 1.14
87.12
C++ Reference :
Parameters : void
Parent Class : QIODevice
•
•
•
Socket::NetworkLayerProtocol protocol)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
vice::OpenModeFlag openMode)
•
• *socketDescriptor(void)
•
•
•
•
•
•
•
•
87.12. QAbstractSocket Class 1094

Ring Documentation, Release 1.14
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getconnectedEvent(void)
• *getdisconnectedEvent(void)
• *geterrorEvent(void)
• *gethostFoundEvent(void)
• *getproxyAuthenticationRequiredEvent(void)
• *getstateChangedEvent(void)
87.13
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
87.13. QAbstractSpinBox Class 1095

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
87.14
C++ Reference :
Parameters : QWidget*parent
• *actionGroup(void)
•
•
•
•
•
•
•
•
•
•
•
•
• *menu(void)
•
• *parentWidget(void)
•
• *group)
•
•
87.14. QAction Class 1096

Ring Documentation, Release 1.14
•
•
•
•
•
• *menu)
•
•
•
•
•
•
•
•
•
•
•
•
• *widget)
•
•
•
•
•
•
•
•
•
•
•
• *)
• *getClickEvent(void)
87.14. QAction Class 1097

Ring Documentation, Release 1.14
87.15
Parameters : QWidget *
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
87.15. QAllEvents Class 1098

Ring Documentation, Release 1.14
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *getKeyPressEvent(void)
• *getMouseButtonPressEvent(void)
• *getMouseButtonReleaseEvent(void)
• *getMouseButtonDblClickEvent(void)
• *getMouseMoveEvent(void)
• *getCloseEvent(void)
• *getContextMenuEvent(void)
• *getDragEnterEvent(void)
• *getDragLeaveEvent(void)
• *getDragMoveEvent(void)
• *getDropEvent(void)
• *getEnterEvent(void)
• *getFocusInEvent(void)
• *getFocusOutEvent(void)
• *getKeyReleaseEvent(void)
• *getLeaveEvent(void)
• *getNonClientAreaMouseButtonDblClickEvent(void)
• *getNonClientAreaMouseButtonPressEvent(void)
• *getNonClientAreaMouseButtonReleaseEvent(void)
• *getNonClientAreaMouseMoveEvent(void)
• *getMoveEvent(void)
• *getResizeEvent(void)
• *getWindowActivateEvent(void)
• *getWindowBlockedEvent(void)
• *getWindowDeactivateEvent(void)
• *getWindowStateChangeEvent(void)
87.15. QAllEvents Class 1099

Ring Documentation, Release 1.14
• *getWindowUnblockedEvent(void)
• *getPaintEvent(void)
• *getChildAddedEvent(void)
• *getChildPolishedEvent(void)
• *getChildRemovedEvent(void)
•
• *getParentObject(void)
• *getParentWidget(void)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
87.15. QAllEvents Class 1100

Ring Documentation, Release 1.14
• *cStr)
• *cStr)
• *cStr)
• *getKeyPressFunc(void)
• *getMouseButtonPressFunc(void)
• *getMouseButtonReleaseFunc(void)
• *getMouseButtonDblClickFunc(void)
• *getMouseMoveFunc(void)
• *getCloseFunc(void)
• *getContextMenuFunc(void)
• *getDragEnterFunc(void)
• *getDragLeaveFunc(void)
• *getDragMoveFunc(void)
• *getDropFunc(void)
• *getEnterFunc(void)
• *getFocusInFunc(void)
• *getFocusOutFunc(void)
• *getKeyReleaseFunc(void)
• *getLeaveFunc(void)
• *getNonClientAreaMouseButtonDblClickFunc(void)
• *getNonClientAreaMouseButtonPressFunc(void)
• *getNonClientAreaMouseButtonReleaseFunc(void)
• *getNonClientAreaMouseMoveFunc(void)
• *getMoveFunc(void)
• *getResizeFunc(void)
• *getWindowActivateFunc(void)
• *getWindowBlockedFunc(void)
• *getWindowDeactivateFunc(void)
• *getWindowStateChangeFunc(void)
• *getWindowUnblockedFunc(void)
• *getPaintFunc(void)
• *getChildAddedFunc(void)
• *getChildPolishedFunc(void)
• *getChildRemovedFunc(void)
• *getDropEventObject(void)
• *getDragMoveEventObject(void)
87.15. QAllEvents Class 1101

Ring Documentation, Release 1.14
• *getDragEnterEventObject(void)
• *getDragLeaveEventObject(void)
• *getChildEventObject(void)
87.16
C++ Reference :
Parent Class : QGuiApplication
•
•
•
•
•
•
•
•
•
•
87.17
C++ Reference :
Parent Class : QLegendMarker
•
•
87.18
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractSeries
•
•
•
•
•
•
87.16. QApp Class 1102

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *series)
•
•
•
•
•
•
•
• *series)
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getborderColorChangedEvent(void)
• *getclickedEvent(void)
• *getcolorChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getpointLabelsClippingChangedEvent(void)
87.18. QAreaSeries Class 1103

Ring Documentation, Release 1.14
• *getpointLabelsColorChangedEvent(void)
• *getpointLabelsFontChangedEvent(void)
• *getpointLabelsFormatChangedEvent(void)
• *getpointLabelsVisibilityChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
87.19
C++ Reference :
Parameters : QObject *
Parent Class : QObject
• *> aspects(void)
•
• *aspect)
•
•
•
• *aspect)
•
87.20
C++ Reference :
Parameters : QWidget *
Parent Class : QObject
•
•
•
•
•
• *function)
• *function,QVariant)
• *function,QVariant,QVariant)
• *function,QVariant,QVariant,QVariant)
• *function,QVariant,QVariant,QVariant,QVariant)
• *function,QVariant,QVariant,QVariant,QVariant,QVariant)
87.19. QAspectEngine Class 1104

Ring Documentation, Release 1.14
• *function,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant)
• *function,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant)
• *function,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant)
• *function, QList<QVariant> )
•
•
• *querySubObject(const char*name)
• *querySubObject_2(const char*name,QVariant)
• *querySubObject_3(const char*name,QVariant,QVariant)
• *querySubObject_4(const char*name,QVariant,QVariant,QVariant)
• *querySubObject_5(const char*name,QVariant,QVariant,QVariant,QVariant)
• *querySubObject_6(const char*name,QVariant,QVariant,QVariant,QVariant,QVariant)
• *querySubObject_7(const char*name,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant)
• *querySubObject_8(const char*name,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant)
• *querySubObject_9(const char*name,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant,QVariant)
•
•
87.21
C++ Reference :
Parameters : QString
Parent Class : QAxBase
•
87.22
C++ Reference :
Parameters : QWidget*parent, Qt::WindowFlags f
Parent Class : QAxBase
•
87.21. QAxObject Class 1105

Ring Documentation, Release 1.14
87.23
Parameters : QString c, QWidget*parent, Qt::WindowFlags f
Parent Class : QAxWidget
87.24
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractAxis
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *getcategoriesChangedEvent(void)
• *getcountChangedEvent(void)
• *getmaxChangedEvent(void)
• *getminChangedEvent(void)
• *getrangeChangedEvent(void)
87.23. QAxWidget2 Class 1106

Ring Documentation, Release 1.14
87.25
C++ Reference :
Parent Class : QLegendMarker
•
•
87.26
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractBarSeries
•
87.27
C++ Reference :
Parameters : QString,QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.25. QBarLegendMarker Class 1107

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getborderColorChangedEvent(void)
• *getbrushChangedEvent(void)
• *getclickedEvent(void)
• *getcolorChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getlabelBrushChangedEvent(void)
• *getlabelChangedEvent(void)
• *getlabelColorChangedEvent(void)
• *getlabelFontChangedEvent(void)
• *getpenChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *getvalueChangedEvent(void)
87.27. QBarSet Class 1108

Ring Documentation, Release 1.14
• *getvaluesAddedEvent(void)
• *getvaluesRemovedEvent(void)
87.28
C++ Reference :
Parameters : void
Parent Class : QPixmap
•
•
•
•
•
87.29
C++ Reference :
Parameters : void
•
•
•
•
87.30
C++ Reference :
Parameters : QObject *
•
•
•
•
•
•
•
•
• *)
• *)
87.28. QBitmap Class 1109

Ring Documentation, Release 1.14
• *)
• *)
• *getcanceledEvent(void)
• *getdeviceDiscoveredEvent(void)
• *geterrorEvent(void)
• *getnishedEvent(void)
87.31
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
• *completeness)
•
•
•
ness)
87.32
C++ Reference :
Parameters : void
•
•
•
•
87.31. QBluetoothDeviceInfo Class 1110

Ring Documentation, Release 1.14
87.33
C++ Reference :
Parameters : QObject *
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getdeviceConnectedEvent(void)
• *getdeviceDisconnectedEvent(void)
• *geterrorEvent(void)
• *gethostModeStateChangedEvent(void)
• *getpairingDisplayConrmationEvent(void)
• *getpairingDisplayPinCodeEvent(void)
• *getpairingFinishedEvent(void)
87.34
C++ Reference :
Parameters : QBluetoothServiceInfo::Protocol,QObject *
Parent Class : QObject
•
•
•
87.33. QBluetoothLocalDevice Class 1111

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *geterrorEvent(void)
• *getnewConnectionEvent(void)
87.35
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
87.35. QBluetoothServiceDiscoveryAgent Class 1112

Ring Documentation, Release 1.14
• *)
• *getcanceledEvent(void)
• *geterrorEvent(void)
• *getnishedEvent(void)
• *getserviceDiscoveredEvent(void)
87.36
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.36. QBluetoothServiceInfo Class 1113

Ring Documentation, Release 1.14
•
•
87.37
C++ Reference :
Parameters : QBluetoothServiceInfo::Protocol,QObject *
Parent Class : QIODevice
•
•
•
Mode)
•
•
•
•
•
•
•
•
•
•
•
Socket::SocketState socketState, QIODevice::OpenMode openMode)
•
•
•
• *)
• *)
• *)
• *)
• *getconnectedEvent(void)
• *getdisconnectedEvent(void)
• *geterrorEvent(void)
• *getstateChangedEvent(void)
87.37. QBluetoothSocket Class 1114

Ring Documentation, Release 1.14
87.38
C++ Reference :
Parameters : QObject *
Parent Class : QObject
• *data)
• *)
• *getnishedEvent(void)
87.39
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
• *)
• *)
• *)
• *geterrorEvent(void)
• *getnishedEvent(void)
• *gettransferProgressEvent(void)
87.40
C++ Reference :
Parameters : QBluetoothAddress
•
•
•
87.38. QBluetoothTransferManager Class 1115

Ring Documentation, Release 1.14
87.41
C++ Reference :
Parameters : void
Parent Class : QUuid
•
• *ok)
• *ok)
•
87.42
C++ Reference :
Parameters : QBoxLayout::Direction dir, QWidget*parent
Parent Class : QLayout
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.41. QBluetoothUuid Class 1116

Ring Documentation, Release 1.14
87.43
C++ Reference :
Parent Class : QLegendMarker
•
•
87.44
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractSeries
• *set)
• *> sets)
•
• *> boxSets(void)
•
•
•
•
• *set)
•
• *set)
•
•
•
•
• *set)
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
87.43. QBoxPlotLegendMarker Class 1117

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *getboxOutlineVisibilityChangedEvent(void)
• *getboxWidthChangedEvent(void)
• *getboxsetsAddedEvent(void)
• *getboxsetsRemovedEvent(void)
• *getbrushChangedEvent(void)
• *getclickedEvent(void)
• *getcountChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getpenChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
87.45
C++ Reference :
Parameters : QString,QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
87.45. QBoxSet Class 1118

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getbrushChangedEvent(void)
• *getclearedEvent(void)
• *getclickedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getpenChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *getvalueChangedEvent(void)
• *getvaluesChangedEvent(void)
87.46
C++ Reference :
Parameters : void
•
• *gradient(void)
•
•
•
•
•
•
•
•
•
•
•
87.46. QBrush Class 1119

Ring Documentation, Release 1.14
•
•
87.47
C++ Reference :
Parameters : QObject *
Parent Class : QIODevice
•
•
• *byteArray)
•
• *data, int size)
87.48
C++ Reference :
Parameters : QObject*parent
• *button, int id)
• *button(int id)
• *checkedButton(void)
•
•
• *button)
• *button)
•
• *button, int id)
• *)
• *)
• *)
• *getbuttonClickedEvent(void)
• *getbuttonPressedEvent(void)
• *getbuttonReleasedEvent(void)
87.47. QBuffer Class 1120

Ring Documentation, Release 1.14
87.49
C++ Reference :
Parameters : void
• *str)
•
•
•
•
• *constData(void)
• *str)
• *str)
• *data(void)
• *str)
•
• *str, int from)
• *str, int len)
•
•
• *str, int from)
•
•
•
•
• *str, int len)
• *str)
• *str)
•
•
• *after, int alen)
•
•
•
•
•
• *data, uint size)
87.49. QByteArray Class 1121

Ring Documentation, Release 1.14
•
•
•
• *str)
•
•
•
•
•
• *ok, int base)
• *ok, int base)
• *ok, int base)
•
•
• *ok, int base)
• *ok, int base)
• *ok, int base)
•
•
•
•
•
•
•
•
• *data, int size)
•
87.50
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
•
•
87.50. QCalendarWidget Class 1122

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.50. QCalendarWidget Class 1123

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *getactivatedEvent(void)
• *getclickedEvent(void)
• *getcurrentPageChangedEvent(void)
• *getselectionChangedEvent(void)
87.51
C++ Reference :
Parameters : void
Parent Class : QMediaObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.51. QCamera Class 1124

Ring Documentation, Release 1.14
•
•
•
87.52
C++ Reference :
Parameters : QMediaObject * mediaObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.53
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
87.52. QCameraImageCapture Class 1125

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.54
C++ Reference :
Parameters : Qt3DCore::QNode *
•
• *camera)
87.55
C++ Reference :
Parameters : QWidget *
Parent Class : QVideoWidget
87.54. QCameraSelector Class 1126

Ring Documentation, Release 1.14
87.56
C++ Reference :
Parent Class : QLegendMarker
•
•
87.57
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
• *model)
• *series)
• *)
• *)
• *getmodelReplacedEvent(void)
• *getseriesReplacedEvent(void)
87.58
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractSeries
• *set)
• *> sets)
•
•
•
•
•
•
•
•
87.56. QCandlestickLegendMarker Class 1127

Ring Documentation, Release 1.14
•
• *set)
•
•
•
• *set)
• *> sets)
•
•
•
•
•
•
•
•
•
•
• *> sets(void)
• *set)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
87.58. QCandlestickSeries Class 1128

Ring Documentation, Release 1.14
• *)
• *getbodyOutlineVisibilityChangedEvent(void)
• *getbodyWidthChangedEvent(void)
• *getbrushChangedEvent(void)
• *getcandlestickSetsAddedEvent(void)
• *getcandlestickSetsRemovedEvent(void)
• *getcapsVisibilityChangedEvent(void)
• *getcapsWidthChangedEvent(void)
• *getclickedEvent(void)
• *getcountChangedEvent(void)
• *getdecreasingColorChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getincreasingColorChangedEvent(void)
• *getmaximumColumnWidthChangedEvent(void)
• *getminimumColumnWidthChangedEvent(void)
• *getpenChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
87.59
C++ Reference :
Parameters : qreal,QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
87.59. QCandlestickSet Class 1129

Ring Documentation, Release 1.14
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getbrushChangedEvent(void)
• *getclickedEvent(void)
• *getcloseChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethighChangedEvent(void)
• *gethoveredEvent(void)
• *getlowChangedEvent(void)
• *getopenChangedEvent(void)
• *getpenChangedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *gettimestampChangedEvent(void)
87.60
C++ Reference :
Parameters : QObject *
Parent Class : QValueAxis
•
•
•
87.60. QCategoryAxis Class 1130

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
• *)
• *)
• *getcategoriesChangedEvent(void)
• *getlabelsPositionChangedEvent(void)
87.61
C++ Reference :
Parameters : int
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.61. QChar Class 1131

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.61. QChar Class 1132

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.62
C++ Reference :
Parameters : QGraphicsItem*,Qt::WindowFlags
Parent Class : QGraphicsWidget
• *axis, Qt::Alignment alignment)
• *series)
•
•
•
• *> axes(Qt::Orientations orientation, QAbstractSeries*series)
•
•
•
•
•
•
•
87.62. QChart Class 1133

Ring Documentation, Release 1.14
•
•
• *legend(void)
•
•
• *series)
• *series)
•
•
•
•
•
• *axis)
• *series)
•
• *> series(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.62. QChart Class 1134

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *)
• *getplotAreaChangedEvent(void)
87.63
C++ Reference :
Parameters : QWidget *
Parent Class : QGraphicsView
•
•
• *chart)
•
87.64
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractButton
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
87.63. QChartView Class 1135

Ring Documentation, Release 1.14
• *getstateChangedEvent(void)
• *getclickedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *gettoggledEvent(void)
87.65
C++ Reference :
Parameters : QEvent::Type,QObject *
Parent Class : QEvent
•
• *child(void)
•
•
87.66
C++ Reference :
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.65. QChildEvent Class 1136

Ring Documentation, Release 1.14
87.67
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
• *c, int*m, int*y, int*k, int*a)
• *c, qreal*m, qreal*y, qreal*k, qreal*a)
• *h, int*s, int*l, int*a)
• *h, qreal*s, qreal*l, qreal*a)
• *h, int*s, int*v, int*a)
• *h, qreal*s, qreal*v, qreal*a)
• *r, int*g, int*b, int*a)
• *r, qreal*g, qreal*b, qreal*a)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.67. QColor Class 1137

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.67. QColor Class 1138

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
87.68
C++ Reference :
Parameters : void
Parent Class : QDialog
•
•
•
•
•
•
•
•
•
•
•
tions)
•
•
•
• *)
• *)
• *getcolorSelectedEvent(void)
87.68. QColorDialog Class 1139

Ring Documentation, Release 1.14
• *getcurrentColorChangedEvent(void)
•
87.69
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
•
• *completer(void)
•
•
•
•
•
•
•
•
•
•
•
•
• *itemDelegate(void)
•
•
• *lineEdit(void)
•
•
•
• *model(void)
•
•
•
• *completer)
•
87.69. QComboBox Class 1140

Ring Documentation, Release 1.14
•
•
•
• *delegate)
•
•
• *edit)
•
•
•
• *model)
•
•
• *itemView)
•
• *view(void)
•
•
•
•
•
• *)
• *)
• *)
• *)
• *getactivatedEvent(void)
• *getcurrentIndexChangedEvent(void)
• *geteditTextChangedEvent(void)
• *gethighlightedEvent(void)
87.69. QComboBox Class 1141

Ring Documentation, Release 1.14
87.70
C++ Reference :
Parameters : QObject*parent
Parent Class : QObject
•
•
•
•
• *completionModel(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *model)
•
• *popup)
• *widget)
•
•
•
•
•
87.70. QCompleter Class 1142

Ring Documentation, Release 1.14
87.71
Parameters : QAbstractItemModel*model, QObject*parent
Parent Class : QCompleter
87.72
Parameters : QStringList list, QObject*parent
Parent Class : QCompleter
87.73
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.71. QCompleter2 Class 1143

Ring Documentation, Release 1.14
87.74
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.75
C++ Reference :
Parent Class : QObject
• *lterObj)
• *lterObject)
•
•
•
•
•
•
•
•
•
•
•
•
87.74. QConeMesh Class 1144

Ring Documentation, Release 1.14
• *translationFile)
•
•
•
•
•
• *receiver, QEvent*event, int priority)
•
•
•
• *receiver, int eventType)
• *translationFile)
• *receiver, QEvent*event)
• *receiver, int event_type)
•
•
•
• *eventDispatcher)
•
•
•
•
•
•
• *context, char*sourceText, char*disambiguation, int n)
87.76
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
87.76. QCuboidMesh Class 1145

Ring Documentation, Release 1.14
•
•
•
•
•
•
87.77
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
87.78
C++ Reference :
Parameters : void
• *bitmap(void)
•
• *mask(void)
•
•
•
•
• *)
•
• *screen, int x, int y)
•
• *screen, QPoint)
87.77. QCullFace Class 1146

Ring Documentation, Release 1.14
87.79
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
87.80
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.79. QCylinderMesh Class 1147

Ring Documentation, Release 1.14
•
•
•
•
•
•
87.81
C++ Reference :
Parameters : QWidget*parent
Parent Class : QDateTimeEdit
87.82
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.81. QDateEdit Class 1148

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
87.83
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractAxis
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *getformatChangedEvent(void)
• *getmaxChangedEvent(void)
• *getminChangedEvent(void)
• *getrangeChangedEvent(void)
87.83. QDateTimeAxis Class 1149

Ring Documentation, Release 1.14
• *gettickCountChangedEvent(void)
87.84
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractSpinBox
•
• *calendarWidget(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *calendarWidget)
•
•
•
•
87.84. QDateTimeEdit Class 1150

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.85
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
87.86
C++ Reference :
•
• *receiver, const char*method)
•
87.85. QDepthTest Class 1151

Ring Documentation, Release 1.14
87.87
C++ Reference :
Parameters : void
Parent Class : QWidget
•
•
•
• *screen(int screen)
•
•
• *widget)
87.88
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractSlider
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getactionTriggeredEvent(void)
• *getrangeChangedEvent(void)
• *getsliderMovedEvent(void)
• *getsliderPressedEvent(void)
87.87. QDesktopWidget Class 1152

Ring Documentation, Release 1.14
• *getsliderReleasedEvent(void)
• *getvalueChangedEvent(void)
87.89
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
87.90
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.89. QDialog Class 1153

Ring Documentation, Release 1.14
87.91
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.91. QDir Class 1154

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.92
C++ Reference :
Parameters : void
•
•
•
•
•
87.92. QDirModel Class 1155

Ring Documentation, Release 1.14
• *iconProvider(void)
•
•
•
•
•
•
•
•
•
•
• *provider)
•
•
•
•
•
•
•
87.93
C++ Reference :
Parameters : QWidget*parent,Qt::WindowType ag
Parent Class : QWidget
•
•
•
•
•
•
•
• *widget)
• *widget)
• *titleBarWidget(void)
• *toggleViewAction(void)
87.93. QDockWidget Class 1156

Ring Documentation, Release 1.14
• *widget(void)
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *getallowedAreasChangedEvent(void)
• *getdockLocationChangedEvent(void)
• *getfeaturesChangedEvent(void)
• *gettopLevelChangedEvent(void)
• *getvisibilityChangedEvent(void)
87.94
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
• *mimeData(void)
•
•
•
•
•
•
•
•
87.94. QDrag Class 1157

Ring Documentation, Release 1.14
• *)
• *)
• *getactionChangedEvent(void)
• *gettargetChangedEvent(void)
87.95
C++ Reference :
Parameters : QPoint,Qt::DropActions,const QMimeData*,Qt::MouseButtons,Qt::KeyboardModiers
Parent Class : QDragMoveEvent
87.96
C++ Reference :
Parameters : void
Parent Class : QEvent
87.97
C++ Reference :
Parameters : QPoint,Qt::DropActions,const QMimeData*,Qt::MouseButtons,Qt::KeyboardModiers,QEvent::Type
Parent Class : QDropEvent
•
•
•
•
•
87.98
C++ Reference :
Parameters : QPointF,Qt::DropActions,const QMimeData*,Qt::MouseButtons,Qt::KeyboardModiers,QEvent::Type
Parent Class : QEvent
•
•
•
•
87.95. QDragEnterEvent Class 1158

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
87.99
C++ Reference :
Parameters : Qt3DCore::QNode *
• *parameter)
• *t)
• *> parameters(void)
• *parameter)
• *t)
• *> techniques(void)
87.100
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QNode
• *comp)
•
•
• *comp)
87.101
C++ Reference :
Parameters : QEvent::Type Type
•
•
•
•
87.99. QEffect Class 1159

Ring Documentation, Release 1.14
•
•
87.102
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
87.103
C++ Reference :
Parameters : void
Parent Class : QFileDevice
•
•
•
• *fh, QIODevice::OpenMode mode, QFile::FileHandleFlags handleFlags)
•
•
•
•
•
•
•
•
• *localFileName)
•
•
•
•
•
87.102. QExtrudedTextMesh Class 1160

Ring Documentation, Release 1.14
•
•
•
•
87.104
Parameters : QString
Parent Class : QFile
87.105
C++ Reference :
Parent Class : QIODevice
•
•
•
•
•
•
•
• *address)
•
87.106
C++ Reference :
Parameters : QWidget*parent
Parent Class : QDialog
•
•
•
•
•
•
•
•
87.104. QFile2 Class 1161

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.106. QFileDialog Class 1162

Ring Documentation, Release 1.14
•
•
•
•
QStringList supportedSchemes)
•
•
edFilter, QFileDialog::Options options)
•
lectedFilter, QFileDialog::Options options)
•
QFileDialog::Options options, QStringList supportedSchemes)
•
Filter, QFileDialog::Options options, QStringList supportedSchemes)
•
•
edFilter, QFileDialog::Options options)
•
QFileDialog::Options options, QStringList supportedSchemes)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcurrentChangedEvent(void)
• *getcurrentUrlChangedEvent(void)
• *getdirectoryEnteredEvent(void)
• *getdirectoryUrlEnteredEvent(void)
• *getleSelectedEvent(void)
• *getlesSelectedEvent(void)
• *getlterSelectedEvent(void)
• *geturlSelectedEvent(void)
• *geturlsSelectedEvent(void)
•
87.106. QFileDialog Class 1163

Ring Documentation, Release 1.14
• *cFileTypes, const char*cCode)
• *FileContentList(void)
87.107
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.107. QFileInfo Class 1164

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.108
C++ Reference :
Parameters : void
•
•
•
•
•
• *iconProvider(void)
•
•
•
•
•
•
•
•
•
•
87.108. QFileSystemModel Class 1165

Ring Documentation, Release 1.14
•
•
•
•
•
• *provider)
•
•
•
•
•
•
•
•
•
•
• *data, Qt::DropAction action, int row, int column, QModelIndex parent)
•
•
•
•
•
•
•
•
•
•
•
87.109
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QAbstractCameraController
87.109. QFirstPersonCameraController Class 1166

Ring Documentation, Release 1.14
87.110
C++ Reference :
Parameters : QString, int, int, bool
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.110. QFont Class 1167

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.110. QFont Class 1168

Ring Documentation, Release 1.14
87.111
C++ Reference :
Parameters : void
Parent Class : QDialog
•
•
•
•
•
•
•
•
•
options)
•
• *)
• *)
• *getcurrentFontChangedEvent(void)
• *getfontSelectedEvent(void)
•
87.112
C++ Reference :
Parameters : QFont
•
•
•
•
•
•
•
•
•
•
•
87.111. QFontDialog Class 1169

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.113
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
• *camera)
•
•
•
•
• *surface)
•
87.113. QForwardRenderer Class 1170

Ring Documentation, Release 1.14
87.114
C++ Reference :
Parameters : QWidget*parent, Qt::WindowType ag
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.115
Parameters : void
Parent Class : QFrame
87.116
Parameters : QWidget*parent
Parent Class : QFrame
87.117
C++ Reference :
Parameters : Qt3DCore::QNode *
• *)
• *gettriggeredEvent(void)
87.114. QFrame Class 1171

Ring Documentation, Release 1.14
87.118
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.119
C++ Reference :
Parameters : QString
•
•
•
•
•
•
•
87.118. QGeoAddress Class 1172

Ring Documentation, Release 1.14
•
•
•
•
•
87.120
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
87.121
C++ Reference :
Parameters : void
•
•
•
•
•
•
87.122
C++ Reference :
Parameters : void
•
•
•
•
•
•
87.120. QGeoAreaMonitorSource Class 1173

Ring Documentation, Release 1.14
•
•
•
•
•
•
87.123
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
87.124
C++ Reference :
Parent Class : QObject
•
•
•
• *)
• *)
• *)
• *geterrorEvent(void)
• *getpositionUpdatedEvent(void)
• *getupdateTimeoutEvent(void)
•
• *createDefaultSource(QObject*parent)
• *createSource(QString sourceName, QObject*parent)
87.123. QGeoPositionInfo Class 1174

Ring Documentation, Release 1.14
87.125
C++ Reference :
Parameters : void
Parent Class : QGeoShape
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.126
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
87.125. QGeoRectangle Class 1175

Ring Documentation, Release 1.14
•
•
87.127
C++ Reference :
•
•
87.128
C++ Reference :
Parameters : void
•
•
•
•
87.129
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.127. QGeoSatelliteInfoSource Class 1176

Ring Documentation, Release 1.14
87.130
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
87.131
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
• *item)
•
•
•
•
•
•
•
•
•
• *widget, Qt::WindowFlags wFlags)
•
•
•
• *> collidingItems(QGraphicsItem*item, Qt::ItemSelectionMode mode)
87.130. QGradient Class 1177

Ring Documentation, Release 1.14
• *> items)
• *group)
•
•
•
•
•
•
•
•
•
•
• *> items(Qt::SortOrder order)
• *> items_2(QPointF pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, QTrans-
form deviceTransform)
• *> items_3(QRectF rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, QTrans-
form deviceTransform)
• *> items_4(QPolygonF polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order,
QTransform deviceTransform)
• *> items_5(QPainterPath path, Qt::ItemSelectionMode mode, Qt::SortOrder order,
QTransform deviceTransform)
• *> items_6(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode, Qt::SortOrder
order, QTransform deviceTransform)
•
•
•
•
• *item)
• *painter, QRectF target, QRectF source, Qt::AspectRatioMode aspectRatioMode)
•
• *> selectedItems(void)
•
• *item, QEvent*event)
• *item)
• *widget)
•
•
•
87.131. QGraphicsScene Class 1178

Ring Documentation, Release 1.14
• *item, Qt::FocusReason focusReason)
•
•
•
•
•
•
•
•
•
Qt::ItemSelectionMode mode, QTransform deviceTransform)
•
• *style)
•
•
•
• *> views(void)
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *getchangedEvent(void)
• *getfocusItemChangedEvent(void)
• *getsceneRectChangedEvent(void)
• *getselectionChangedEvent(void)
87.131. QGraphicsScene Class 1179

Ring Documentation, Release 1.14
87.132
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
87.133
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractScrollArea
•
•
•
•
•
• *item)
•
•
•
• *item, int xmargin, int ymargin)
•
•
• *item, Qt::AspectRatioMode aspectRatioMode)
•
•
•
•
•
• *> items(void)
• *> items_2(QPoint pos)
87.132. QGraphicsVideoItem Class 1180

Ring Documentation, Release 1.14
• *> items_3(int x, int y)
• *> items_4(QRect rect, Qt::ItemSelectionMode mode)
• *> items_5(int x, int y, int w, int h, Qt::ItemSelectionMode mode)
• *> items_6(QPolygon polygon, Qt::ItemSelectionMode mode)
• *> items_7(QPainterPath path, Qt::ItemSelectionMode mode)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *painter, QRectF target, QRect source, Qt::AspectRatioMode aspectRatioMode)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.133. QGraphicsView Class 1181

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *scene)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.134
C++ Reference :
Parameters : void
•
)
•
•
ment )
•
•
Qt::Alignment alignment )
•
87.134. QGridLayout Class 1182

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.135
C++ Reference :
Parent Class : QCoreApplication
Parameters : int,char **
•
•
•
•
•
•
•
•
•
•
87.135. QGuiApplication Class 1183

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *> screens(void)
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
87.135. QGuiApplication Class 1184

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getapplicationDisplayNameChangedEvent(void)
• *getapplicationStateChangedEvent(void)
• *getcommitDataRequestEvent(void)
• *getfocusObjectChangedEvent(void)
• *getfocusWindowChangedEvent(void)
• *getfontDatabaseChangedEvent(void)
• *getlastWindowClosedEvent(void)
• *getlayoutDirectionChangedEvent(void)
• *getpaletteChangedEvent(void)
• *getprimaryScreenChangedEvent(void)
• *getsaveStateRequestEvent(void)
• *getscreenAddedEvent(void)
• *getscreenRemovedEvent(void)
87.136
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
87.136. QHBarModelMapper Class 1185

Ring Documentation, Release 1.14
•
•
• *model)
• *series)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcolumnCountChangedEvent(void)
• *getrstBarSetRowChangedEvent(void)
• *getrstColumnChangedEvent(void)
• *getlastBarSetRowChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getseriesReplacedEvent(void)
87.137
C++ Reference :
Parameters : void
Parent Class : QBoxLayout
• *)
• *)
87.138
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
87.137. QHBoxLayout Class 1186

Ring Documentation, Release 1.14
•
•
•
• *model)
• *series)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcolumnCountChangedEvent(void)
• *getrstBoxSetRowChangedEvent(void)
• *getrstColumnChangedEvent(void)
• *getlastBoxSetRowChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getseriesReplacedEvent(void)
87.139
C++ Reference :
Parameters : QObject *
Parent Class : QCandlestickModelMapper
•
•
•
•
•
•
•
•
•
•
•
•
•
87.139. QHCandlestickModelMapper Class 1187

Ring Documentation, Release 1.14
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcloseColumnChangedEvent(void)
• *getrstSetRowChangedEvent(void)
• *gethighColumnChangedEvent(void)
• *getlastSetRowChangedEvent(void)
• *getlowColumnChangedEvent(void)
• *getopenColumnChangedEvent(void)
• *gettimestampColumnChangedEvent(void)
87.140
C++ Reference :
Parameters : QObject *
Parent Class : QPieModelMapper
•
•
•
•
•
•
•
•
• *model)
• *series)
•
•
• *)
• *)
• *)
87.140. QHPieModelMapper Class 1188

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *getcolumnCountChangedEvent(void)
• *getrstColumnChangedEvent(void)
• *getlabelsRowChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getseriesReplacedEvent(void)
• *getvaluesRowChangedEvent(void)
87.141
C++ Reference :
Parameters : QObject *
Parent Class : QXYModelMapper
•
•
•
•
•
•
• *model)
• *series)
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getcolumnCountChangedEvent(void)
• *getrstColumnChangedEvent(void)
• *getmodelReplacedEvent(void)
87.141. QHXYModelMapper Class 1189

Ring Documentation, Release 1.14
• *getseriesReplacedEvent(void)
• *getxRowChangedEvent(void)
• *getyRowChangedEvent(void)
87.142
C++ Reference :
Parameters : Qt::Orientation, QWidget *
Parent Class : QAbstractItemView
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.142. QHeaderView Class 1190

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
87.142. QHeaderView Class 1191

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getgeometriesChangedEvent(void)
• *getsectionClickedEvent(void)
• *getsectionCountChangedEvent(void)
• *getsectionDoubleClickedEvent(void)
• *getsectionEnteredEvent(void)
• *getsectionHandleDoubleClickedEvent(void)
• *getsectionMovedEvent(void)
• *getsectionPressedEvent(void)
• *getsectionResizedEvent(void)
• *getsortIndicatorChangedEvent(void)
•
87.143
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractBarSeries
•
87.144
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractBarSeries
•
87.143. QHorizontalBarSeries Class 1192

Ring Documentation, Release 1.14
87.145
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractBarSeries
•
87.146
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
87.147
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
87.145. QHorizontalStackedBarSeries Class 1193

Ring Documentation, Release 1.14
87.148
C++ Reference :
Parameters : void
Parent Class : QObject
•
• *c)
•
•
•
•
•
• *data, int maxSize)
• *data, int maxSize)
• *data, int maxSize)
•
• *data, int maxSize)
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *getaboutToCloseEvent(void)
• *getbytesWrittenEvent(void)
• *getreadChannelFinishedEvent(void)
• *getreadyReadEvent(void)
87.148. QIODevice Class 1194

Ring Documentation, Release 1.14
87.149
C++ Reference :
Parameters : QPixmap
87.150
C++ Reference :
Parameters : void
•
•
• *bits(void)
•
•
•
•
•
• *constBits(void)
• *constScanLine(int i)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *format) # In RingQt use : bool loadimage(QString, const char*format)
•
•
87.149. QIcon Class 1195

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
formMode)
•
•
• *scanLine(int i)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.151
C++ Reference :
Parameters : QObject *
•
•
87.151. QInputAspect Class 1196

Ring Documentation, Release 1.14
87.152
C++ Reference :
Parameters : QWidget *
Parent Class : QDialog
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *receiver, const char*member)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.152. QInputDialog Class 1197

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *parent,QString,QString, double value, double min, double max , int decimals, bool
*ok, Qt::WindowType ags)
• *parent,QString,QString, int value, int min, int max, int step, bool*ok, Qt::WindowType
ags)
87.153
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.153. QJsonArray Class 1198

Ring Documentation, Release 1.14
•
•
•
87.154
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.155
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
87.154. QJsonDocument Class 1199

Ring Documentation, Release 1.14
•
•
•
•
87.156
C++ Reference :
Parameters : void
•
87.157
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.156. QJsonParseError Class 1200

Ring Documentation, Release 1.14
87.158
C++ Reference :
Parameters : QString
87.159
C++ Reference :
Parameters : QWidget *
Parent Class : QFrame
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.160
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
• *buddy(void)
•
•
•
87.158. QKeySequence Class 1201

Ring Documentation, Release 1.14
•
• *movie(void)
•
• *picture(void)
• *pixmap(void)
•
•
•
• *buddy)
•
•
•
•
•
•
•
•
•
•
•
•
•
• *movie)
•
•
•
•
87.161
C++ Reference :
Parameters : QWidget *
Parent Class : QObject
•
• *w)
•
87.161. QLayout Class 1202

Ring Documentation, Release 1.14
•
• *left, int*top, int*right, int*bottom)
•
• *menuBar(void)
• *parentWidget(void)
• *item)
• *widget)
• *w, Qt::Alignment alignment)
•
• *l, Qt::Alignment alignment)
•
•
•
• *widget)
•
•
•
•
•
•
87.162
C++ Reference :
Parent Class : QGraphicsWidget
•
•
•
•
•
•
•
•
•
•
•
87.162. QLegend Class 1203

Ring Documentation, Release 1.14
•
• *> markers(QAbstractSeries*series)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.163
C++ Reference :
Parameters : void
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
87.163. QLegendMarker Class 1204

Ring Documentation, Release 1.14
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getbrushChangedEvent(void)
• *getclickedEvent(void)
• *getfontChangedEvent(void)
• *gethoveredEvent(void)
• *getlabelBrushChangedEvent(void)
• *getlabelChangedEvent(void)
• *getpenChangedEvent(void)
• *getshapeChangedEvent(void)
• *getvisibleChangedEvent(void)
87.164
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
•
• *completer(void)
• *createStandardContextMenu(void)
•
•
•
•
•
•
87.164. QLineEdit Class 1205

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
• *left, int*top, int*right, int*bottom)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *c)
•
•
•
•
•
•
•
•
•
•
•
•
87.164. QLineEdit Class 1206

Ring Documentation, Release 1.14
• *v)
•
•
• *validator(void)
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getTextChangedEvent(void)
• *getcursorPositionChangedEvent(void)
• *geteditingFinishedEvent(void)
• *getreturnPressedEvent(void)
• *getselectionChangedEvent(void)
• *gettextEditedEvent(void)
87.165
C++ Reference :
Parameters : QObject *
Parent Class : QXYSeries
•
87.165. QLineSeries Class 1207

Ring Documentation, Release 1.14
87.166
C++ Reference :
Parameters : void
Parent Class : QGradient
•
•
•
•
•
•
87.167
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractItemView
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.166. QLinearGradient Class 1208

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
87.168
C++ Reference :
Parameters : QWidget *
Parent Class : QListView
•
•
• *item)
•
• *item(int row)
• *itemAt(int x, int y)
• *itemWidget(QListWidgetItem*item)
• *item)
• *item)
• *item)
•
• *item, QWidget*widget)
•
•
• *takeItem(int row)
• *item)
•
• *item,QAbstractItemView::ScrollHint hint)
• *)
• *)
• *)
87.168. QListWidget Class 1209

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcurrentItemChangedEvent(void)
• *getcurrentRowChangedEvent(void)
• *getcurrentTextChangedEvent(void)
• *getitemActivatedEvent(void)
• *getitemChangedEvent(void)
• *getitemClickedEvent(void)
• *getitemDoubleClickedEvent(void)
• *getitemEnteredEvent(void)
• *getitemPressedEvent(void)
• *getitemSelectionChangedEvent(void)
87.169
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
• *listWidget(void)
•
•
•
•
•
87.169. QListWidgetItem Class 1210

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.170
C++ Reference :
Parameters : QString
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.170. QLocale Class 1211

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *ok)
• *ok)
• *ok)
• *ok)
• *ok)
• *ok)
• *ok)
•
• *ok)
• *ok)
•
•
•
•
•
•
•
•
•
•
•
•
87.170. QLocale Class 1212

Ring Documentation, Release 1.14
•
•
•
•
• *ok)
• *ok)
• *ok)
• *ok)
• *ok)
• *ok)
•
•
•
•
•
•
•
•
country)
•
•
•
87.171
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractAxis
•
•
•
•
•
•
•
•
•
87.171. QLogValueAxis Class 1213

Ring Documentation, Release 1.14
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getbaseChangedEvent(void)
• *getlabelFormatChangedEvent(void)
• *getmaxChangedEvent(void)
• *getminChangedEvent(void)
• *getminorTickCountChangedEvent(void)
• *getrangeChangedEvent(void)
• *gettickCountChangedEvent(void)
87.172
C++ Reference :
Parameters : QObject *
Parent Class : Qt3DCore::QAbstractAspect
87.173
C++ Reference :
Parameters : void
Parent Class : QWidget
• *dockwidget, Qt::Orientation orientation)
• *addToolBar(QString)
• *toolbar)
•
• *centralWidget(void)
•
• *createPopupMenu(void)
•
87.172. QLogicAspect Class 1214

Ring Documentation, Release 1.14
• *dockwidget)
•
•
• *before, QToolBar*toolbar)
• *before)
•
•
• *menuBar(void)
• *menuWidget(void)
• *dockwidget)
• *toolbar)
• *before)
• *dockwidget)
•
•
• *widget)
•
•
•
•
• *menuBar)
• *menuBar)
• *statusbar)
•
•
•
•
• *rst, QDockWidget*second, Qt::Orientation orientation)
• *statusBar(void)
•
•
• *rst, QDockWidget*second)
• *toolbar)
• *toolbar)
•
•
87.173. QMainWindow Class 1215

Ring Documentation, Release 1.14
87.174
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : Qt3DCore::QComponent
• *parameter)
•
• *> parameters(void)
• *parameter)
• *effect)
87.175
Parameters : qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal,qreal
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.174. QMaterial Class 1216

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.176
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractScrollArea
•
•
•
•
•
•
•
•
•
•
•
•
•
87.176. QMdiArea Class 1217

Ring Documentation, Release 1.14
•
•
•
• *> subWindowList(QMdiArea::WindowOrder order )
•
•
•
•
•
•
•
•
•
•
•
•
•
87.177
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
87.177. QMdiSubWindow Class 1218

Ring Documentation, Release 1.14
•
87.178
C++ Reference :
Parameters : void
Parent Class : QWidget
•
•
•
•
•
87.179
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
• *mediaStream(void)
•
• *playlist(void)
•
• *output)
•
•
•
87.178. QMediaObject Class 1219

Ring Documentation, Release 1.14
•
• *playlist)
•
•
•
87.180
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.181
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
• *actionAt(QPoint)
• *act)
• *activeAction(void)
• *)
• *addMenu(QString)
87.180. QMediaPlaylist Class 1220

Ring Documentation, Release 1.14
• *addSeparator(void)
•
• *defaultAction(void)
• *exec(const QPoint &)
• *exec_2(void)
• *exec_3(const QPoint &,QAction*)
•
•
• *insertMenu(QAction*before, QMenu*menu)
• *insertSeparator(QAction*before)
•
•
•
• *menuAction(void)
• *atAction)
•
• *act)
• *act)
•
•
•
•
•
87.182
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
• *actionAt(QPoint)
• *act)
• *activeAction(void)
• *addAction(QString)
• *addSeparator(void)
•
• *cornerWidget(Qt::Corner)
87.182. QMenuBar Class 1221

Ring Documentation, Release 1.14
• *insertSeparator(QAction*before)
•
•
• *act)
• *widget, Qt::Corner)
•
87.183
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
87.184
C++ Reference :
Parameters : QWidget*parent
Parent Class : QDialog
• *button, QMessageBox::ButtonRole role)
• *button(QMessageBox::StandardButton which)
• *button)
• *clickedButton(void)
• *defaultButton(void)
•
• *escapeButton(void)
•
•
• *receiver, const char*member)
• *button)
• *button)
•
• *button)
•
87.183. QMesh Class 1222

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *button)
•
•
•
•
• *parent, QString,QString)
• *parent, QString)
•
•
•
• *parent, QString,QString, int buttons,int defaultButton)
87.185
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
•
•
•
•
87.185. QMetalRoughMaterial Class 1223

Ring Documentation, Release 1.14
87.186
C++ Reference :
Parameters : void
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.187
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
87.186. QMimeData Class 1224

Ring Documentation, Release 1.14
•
•
•
•
87.188
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *device)
•
•
•
•
•
•
•
•
•
87.188. QMovie Class 1225

Ring Documentation, Release 1.14
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *geterrorEvent(void)
• *getnishedEvent(void)
• *getframeChangedEvent(void)
• *getresizedEvent(void)
• *getstartedEvent(void)
• *getstateChangedEvent(void)
• *getupdatedEvent(void)
87.189
C++ Reference :
Parameters : QMutex::RecursionMode
•
•
•
87.190
C++ Reference :
Parameters : QMutex *
•
•
•
87.189. QMutex Class 1226

Ring Documentation, Release 1.14
87.191
C++ Reference :
Parameters : QObject *
Parent Class : QObject
• *)
• *getnishedEvent(void)
•
• *cache(void)
•
•
•
• *deleteResource(QNetworkRequest)
• *get(QNetworkRequest) # In RingQt use : QNetworkReply*getvalue(QNetworkRequest)
• *head(QNetworkRequest)
•
• *post(QNetworkRequest, QByteArray)
•
• *proxyFactory(void)
• *put(QNetworkRequest, QByteArray) # In RingQt use : QNetworkReply *put-
value(QNetworkRequest, QByteArray)
• *sendCustomRequest(QNetworkRequest, QByteArray, QIODevice*)
• *cache)
•
• *cookieJar)
•
•
• *factory)
•
•
87.191. QNetworkAccessManager Class 1227

Ring Documentation, Release 1.14
87.192
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.193
C++ Reference :
Parameters : void
Parent Class : QIODevice
•
•
•
•
•
87.192. QNetworkProxy Class 1228

Ring Documentation, Release 1.14
•
• *manager(void)
•
•
•
•
87.194
C++ Reference :
Parameters : QUrl
•
•
•
• *originatingObject(void)
•
•
•
•
• *object)
•
•
•
•
87.195
C++ Reference :
Parameters : QNmeaPositionInfoSource::UpdateMode,QObject *
Parent Class : QGeoPositionInfoSource
•
•
•
87.194. QNetworkRequest Class 1229

Ring Documentation, Release 1.14
87.196
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
• *parent)
87.197
C++ Reference :
Parameters : void
•
•
•
•
• *className)
• *lterObj)
•
•
• *targetThread)
•
• *parent(void)
• *name)
• *obj)
87.196. QNode Class 1230

Ring Documentation, Release 1.14
•
• *parent)
• *name, QVariant)
• *name, int)
• *name, oat)
• *name, double)
• *name, QString)
• *name, int)
• *name, oat)
• *name, double)
• *name, QString)
•
•
• *thread(void)
•
87.198
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
87.198. QObjectPicker Class 1231

Ring Documentation, Release 1.14
• *getclickedEvent(void)
• *getcontainsMouseChangedEvent(void)
• *getdragEnabledChangedEvent(void)
• *getenteredEvent(void)
• *getexitedEvent(void)
• *gethoverEnabledChangedEvent(void)
• *getmovedEvent(void)
• *getpressedEvent(void)
• *getpressedChangedEvent(void)
• *getreleasedEvent(void)
87.199
C++ Reference :
Parameters : void
• *data, int count)
•
•
•
•
•
•
•
•
•
•
•
•
•
• *data, int count)
•
87.199. QOpenGLBuffer Class 1232

Ring Documentation, Release 1.14
87.200
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
• *procName)
•
•
•
• *surface)
•
•
•
•
• *screen)
• *shareContext)
•
•
•
• *surface)
•
•
• *rst, QOpenGLContext*second)
•
•
•
•
•
• *opengl32(void)
87.200. QOpenGLContext Class 1233

Ring Documentation, Release 1.14
87.201
C++ Reference :
Parameters : QObject *
•
QOpenGLDebugMessage::Severities severities)
•
bugMessage::Types types)
•
QOpenGLDebugMessage::Severities severities)
•
bugMessage::Types types)
•
•
•
•
•
•
•
•
•
•
87.202
C++ Reference :
Parameters : int,int,GLenum
•
•
•
•
•
•
•
•
•
•
•
87.201. QOpenGLDebugLogger Class 1234

Ring Documentation, Release 1.14
•
•
•
•
87.203
C++ Reference :
Parameters : void
•
•
• *name)
•
•
•
•
•
•
•
•
•
• *data, GLenum usage)
• *data)
•
•
•
•
•
•
•
•
height, GLint border, GLsizei imageSize, void*data)
•
GLsizei height, GLenum format, GLsizei imageSize, void*data)
•
width, GLsizei height, GLint border)
•
sizei width, GLsizei height)
87.203. QOpenGLFunctions Class 1235

Ring Documentation, Release 1.14
•
•
•
• *buffers)
• *framebuffers)
•
• *renderbuffers)
•
• *textures)
•
•
•
•
•
•
•
• *indices)
•
•
•
•
•
derbuffer)
•
level)
•
• *buffers)
• *framebuffers)
• *renderbuffers)
• *textures)
•
• *length, GLint*size, GLenum
*type, char*name)
• *length, GLint*size,
GLenum*type, char*name)
• *count, GLuint*shaders)
• *name)
87.203. QOpenGLFunctions Class 1236

Ring Documentation, Release 1.14
• *params)
• *params)
•
• *params)
•
*params)
• *params)
• *length, char*infolog)
• *params)
• *params)
• *length, char*infolog)
• *range, GLint*preci-
sion)
• *length, char*source)
• *params)
•
• *params)
• *params)
• *name)
• *params)
• *params)
• *params)
•
•
•
•
•
•
•
•
•
•
•
•
•
*pixels)
•
87.203. QOpenGLFunctions Class 1237

Ring Documentation, Release 1.14
•
•
•
• *shaders, GLenum binaryformat, void*binary, GLint length)
•
•
•
•
•
•
border, GLenum format, GLenum type, GLvoid*pixels)
•
• *params)
•
• *params)
•
height, GLenum format, GLenum type, GLvoid*pixels)
•
• *v)
•
• *v)
•
• *v)
•
• *v)
•
• *v)
•
• *v)
•
• *v)
•
• *v)
• *value)
• *value)
• *value)
•
87.203. QOpenGLFunctions Class 1238

Ring Documentation, Release 1.14
•
•
• *values)
•
• *values)
•
• *values)
•
• *values)
•
*ptr)
•
•
•
•
87.204
C++ Reference :
Parameters : void
•
•
•
•
•
• *name)
•
•
•
• *name)
•
•
•
•
•
•
•
87.204. QOpenGLFunctions_3_2_Core Class 1239

Ring Documentation, Release 1.14
•
•
torAlpha)
•
dstX1, GLint dstY1, GLbiteld mask, GLenum lter)
• *data, GLenum usage)
• *data)
•
•
•
•
• *value)
• *value)
• *value)
•
•
•
•
•
•
•
•
border, GLsizei imageSize, GLvoid*data)
•
height, GLint border, GLsizei imageSize, GLvoid*data)
•
height, GLsizei depth, GLint border, GLsizei imageSize, GLvoid*data)
•
mat, GLsizei imageSize, GLvoid*data)
•
GLsizei height, GLenum format, GLsizei imageSize, GLvoid*data)
•
GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, GLvoid*data)
•
set, GLsizeiptr size)
•
width, GLint border)
•
width, GLsizei height, GLint border)
•
87.204. QOpenGLFunctions_3_2_Core Class 1240

Ring Documentation, Release 1.14
•
sizei width, GLsizei height)
•
GLint y, GLsizei width, GLsizei height)
•
•
•
• *buffers)
• *framebuffers)
•
• *ids)
• *renderbuffers)
•
•
• *textures)
• *arrays)
•
•
•
•
•
•
•
•
•
•
• *bufs)
• *indices)
• *indices, GLint basev-
ertex)
• *indices, GLsizei in-
stancecount)
• *indices, GL-
sizei instancecount, GLint basevertex)
•
*indices)
•
GLvoid*indices, GLint basevertex)
87.204. QOpenGLFunctions_3_2_Core Class 1241

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
derbuffer)
•
•
level)
•
level)
•
level, GLint zoffset)
•
layer)
•
• *buffers)
• *framebuffers)
• *ids)
• *renderbuffers)
• *textures)
• *arrays)
•
• *length, GLint*size, GLenum
*type, GLchar*name)
• *length, GLint*size,
GLenum*type, GLchar*name)
•
*length, GLchar*uniformBlockName)
•
*params)
• *length,
GLchar*uniformName)
87.204. QOpenGLFunctions_3_2_Core Class 1242

Ring Documentation, Release 1.14
• *uniformIndices, GLenum
pname, GLint*params)
• *count, GLuint*obj)
• *name)
• *data)
• *params)
• *params)
• *params)
• *img)
• *params)
•
• *params)
• *name)
•
*params)
• *data)
• *params)
• *data)
• *params)
• *val)
• *params)
• *params)
• *params)
• *params)
• *params)
• *length, GLchar*infoLog)
• *length, GLchar*source)
• *params)
•
•
• *length, GLint*values)
• *pixels)
• *params)
• *params)
• *params)
• *params)
• *params)
87.204. QOpenGLFunctions_3_2_Core Class 1243

Ring Documentation, Release 1.14
• *params)
• *length, GL-
sizei*size, GLenum*type, GLchar*name)
• *uniformBlockName)
• *params)
• *params)
• *params)
• *params)
• *params)
• *params)
• *params)
•
•
• *c)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *rst, GLsizei*count, GLsizei drawcount)
•
•
• *params)
•
• *params)
87.204. QOpenGLFunctions_3_2_Core Class 1244

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
*pixels)
•
•
width, GLsizei height)
•
•
•
•
•
•
•
•
•
•
format, GLenum type, GLvoid*pixels)
•
border, GLenum format, GLenum type, GLvoid*pixels)
•
sizei height, GLboolean xedsamplelocations)
•
depth, GLint border, GLenum format, GLenum type, GLvoid*pixels)
•
sizei height, GLsizei depth, GLboolean xedsamplelocations)
• *params)
• *params)
•
• *params)
•
• *params)
•
type, GLvoid*pixels)
87.204. QOpenGLFunctions_3_2_Core Class 1245

Ring Documentation, Release 1.14
•
height, GLenum format, GLenum type, GLvoid*pixels)
•
GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid*pixels)
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
•
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
• *value)
87.204. QOpenGLFunctions_3_2_Core Class 1246

Ring Documentation, Release 1.14
•
•
•
•
•
87.205
C++ Reference :
Parameters : void
Parent Class : QPaintDevice
•
•
•
•
•
•
•
•
•
•
•
87.206
C++ Reference :
Parameters : QOpenGLShader::ShaderType,QObject *
• *source)
•
•
•
•
•
•
•
•
• *context)
87.205. QOpenGLPaintDevice Class 1247

Ring Documentation, Release 1.14
87.207
C++ Reference :
Parameters : QObject *
• *source)
•
•
•
• *name)
•
•
•
• *name, int location)
•
•
•
•
• *name)
•
• *name)
•
•
•
•
•
•
•
•
• *shader)
• *values, int tupleSize, int stride)
• *values, int stride)
• *values, int stride)
• *values, int stride)
• *values, int tupleSize, int stride)
• *name, GLoat*values, int tupleSize, int stride)
• *name, QVector2D*values, int stride)
87.207. QOpenGLShaderProgram Class 1248

Ring Documentation, Release 1.14
• *name, QVector3D*values, int stride)
• *name, QVector4D*values, int stride)
• *name, GLenum type, void*values, int tupleSize, int stride)
•
• *name, GLenum type, int offset, int tupleSize, int stride)
•
•
•
•
•
•
•
•
• *values, int columns, int rows)
• *name, GLoat value)
• *name, GLoat x, GLoat y)
• *name, GLoat x, GLoat y, GLoat z)
• *name, GLoat x, GLoat y, GLoat z, GLoat w)
• *name, QVector2D value)
• *name, QVector3D value)
• *name, QVector4D value)
•
•
•
•
•
• *name, QColor color)
• *name, QPoint point)
• *name, QPointF point)
• *name, QSize size)
• *name, QSizeF size)
• *name, QMatrix2x2 value)
• *name, QMatrix2x3 value)
• *name, QMatrix2x4 value)
• *name, QMatrix3x2 value)
• *name, QMatrix3x3 value)
87.207. QOpenGLShaderProgram Class 1249

Ring Documentation, Release 1.14
• *name, QMatrix3x4 value)
• *name, QMatrix4x2 value)
• *name, QMatrix4x3 value)
• *name, QMatrix4x4 value)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *name, GLoat value)
• *name, GLint value)
• *name, GLuint value)
• *name, GLoat x, GLoat y)
• *name, GLoat x, GLoat y, GLoat z)
• *name, GLoat x, GLoat y, GLoat z, GLoat w)
• *name, QVector2D value)
• *name, QVector3D value)
• *name, QVector4D value)
• *values, int count, int tupleSize)
• *values, int count)
87.207. QOpenGLShaderProgram Class 1250

Ring Documentation, Release 1.14
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *values, int count)
• *name, GLoat*values, int count, int tupleSize)
• *name, GLint*values, int count)
• *name, GLuint*values, int count)
• *name, QVector2D*values, int count)
• *name, QVector3D*values, int count)
• *name, QVector4D*values, int count)
• *name, QMatrix2x2*values, int count)
• *name, QMatrix2x3*values, int count)
• *name, QMatrix2x4*values, int count)
• *name, QMatrix3x2*values, int count)
• *name, QMatrix3x3*values, int count)
• *name, QMatrix3x4*values, int count)
• *name, QMatrix4x2*values, int count)
• *name, QMatrix4x3*values, int count)
• *name, QMatrix4x4*values, int count)
• *> shaders(void)
• *name)
•
•
• *context)
87.207. QOpenGLShaderProgram Class 1251

Ring Documentation, Release 1.14
87.208
C++ Reference :
Parameters : QOpenGLTexture::Target
•
•
•
• *border)
• *border)
• *border)
•
viewFormat, int minimumMipmapLevel, int maximumMipmapLevel, int minimumLayer, int maximumLayer)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.208. QOpenGLTexture Class 1252

Ring Documentation, Release 1.14
•
•
• *data, QOpenGLPixelTransferOptions * options)
• *data, QOpenGLPixelTransferOptions * options)
•
ture::PixelFormat sourceFormat, QOpenGLTexture::PixelType sourceType, void*data, QOpenGLPixel-
TransferOptions * options)
•
sourceType, void*data, QOpenGLPixelTransferOptions * options)
•
*data, QOpenGLPixelTransferOptions * options)
•
•
•
•
•
•
•
•
•
ture::Filter magnicationQOpenGLTexture::Filter)
•
•
•
•
•
•
•
value)
•
ture::SwizzleValue b, QOpenGLTexture::SwizzleValue a)
•
•
•
•
•
•
87.208. QOpenGLTexture Class 1253

Ring Documentation, Release 1.14
87.209
C++ Reference :
Parameters : QObject *
•
•
•
•
•
•
•
•
•
•
87.210
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
87.211
C++ Reference :
Parameters : QObject *
•
•
•
•
•
•
87.209. QOpenGLTimerQuery Class 1254

Ring Documentation, Release 1.14
87.212
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
• *cStr)
• *getInitEvent(void)
• *cStr)
• *getPaintEvent(void)
• *cStr)
• *getResizeEvent(void)
•
•
•
•
•
•
•
•
•
87.213
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QAbstractCameraController
•
•
87.212. QOpenGLWidget Class 1255

Ring Documentation, Release 1.14
87.214
C++ Reference :
Parameters : QPrinter*,QWidget *
Parent Class : QDialog
•
•
87.215
C++ Reference :
•
•
•
•
•
•
•
•
•
•
•
•
87.216
C++ Reference :
Parameters : void
•
•
• *device)
•
•
•
•
•
•
87.214. QPageSetupDialog Class 1256

Ring Documentation, Release 1.14
•
•
•
• *device(void)
•
•
•
•
•
•
•
• *lines, int lineCount)
•
•
•
•
•
•
• *rectangles, int rectCount)
•
•
•
•
•
•
•
•
•
•
•
•
• *widget)
•
•
•
• *paintEngine(void)
87.216. QPainter Class 1257

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.216. QPainter Class 1258

Ring Documentation, Release 1.14
•
• *pPoints, Qt::FillRule llRule)
• *pPoints)
• *pPoints)
• *pPoints)
87.217
Parameters : QPaintDevice *
Parent Class : QPainter
87.218
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.217. QPainter2 Class 1259

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.219
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
87.219. QPen Class 1260

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
87.220
C++ Reference :
Parameters : Qt3DCore::QNode *
87.221
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractBarSeries
•
87.222
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
87.220. QPerVertexColorMaterial Class 1261

Ring Documentation, Release 1.14
87.223
C++ Reference :
Parameters : void
•
• *data(void)
•
• *format) # In RingQt use : bool loadle(QString, const char*format)
• *painter)
• *format)
•
•
•
87.224
C++ Reference :
Parent Class : QLegendMarker
•
87.225
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractSeries
• *> slices)
•
•
•
•
•
• *slice)
•
•
•
•
• *slice)
87.223. QPicture Class 1262

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *> slices(void)
•
• *slice)
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getaddedEvent(void)
• *getclickedEvent(void)
• *getcountChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *getremovedEvent(void)
• *getsumChangedEvent(void)
87.225. QPieSeries Class 1263

Ring Documentation, Release 1.14
87.226
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.226. QPieSlice Class 1264

Ring Documentation, Release 1.14
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getangleSpanChangedEvent(void)
• *getborderColorChangedEvent(void)
• *getborderWidthChangedEvent(void)
• *getbrushChangedEvent(void)
• *getclickedEvent(void)
• *getcolorChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getlabelBrushChangedEvent(void)
• *getlabelChangedEvent(void)
• *getlabelColorChangedEvent(void)
• *getlabelFontChangedEvent(void)
• *getlabelVisibleChangedEvent(void)
• *getpenChangedEvent(void)
• *getpercentageChangedEvent(void)
87.226. QPieSlice Class 1265

Ring Documentation, Release 1.14
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *getstartAngleChangedEvent(void)
• *getvalueChangedEvent(void)
87.227
C++ Reference :
Parameters : const char *
•
•
formMode)
•
•
•
•
•
•
•
• *, Qt::ImageConversionFlags )
•
•
•
•
•
•
•
•
•
•
•
• *data, uint len, char*format, Qt::ImageConversionFlags ags)
• *format, Qt::ImageConversionFlags ags)
•
• *format, int quality)
• *device, char*format, int quality)
87.227. QPixmap Class 1266

Ring Documentation, Release 1.14
•
Mode)
•
•
• *exposed)
• *exposed)
•
•
•
•
•
•
•
•
• *imageReader, Qt::ImageConversionFlags ags)
•
•
87.228
Parameters : int width, int height
Parent Class : QPixmap
87.229
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractScrollArea
•
•
•
•
•
•
•
•
•
87.228. QPixmap2 Class 1267

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *printer)
•
•
•
•
• *document)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.229. QPlainTextEdit Class 1268

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *cStr)
• *getblockCountChangedEvent(void)
• *getcopyAvailableEvent(void)
• *getcursorPositionChangedEvent(void)
• *getmodicationChangedEvent(void)
• *getredoAvailableEvent(void)
• *getselectionChangedEvent(void)
• *gettextChangedEvent(void)
• *getundoAvailableEvent(void)
• *getupdateRequestEvent(void)
•
•
87.229. QPlainTextEdit Class 1269

Ring Documentation, Release 1.14
87.230
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
87.231
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
87.232
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
87.230. QPlaneMesh Class 1270

Ring Documentation, Release 1.14
•
•
87.233
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
87.234
C++ Reference :
Parameters : QGraphicsItem*,Qt::WindowFlags
Parent Class : QChart
• *> axes(QPolarChart::PolarOrientations polarOrientation, QAbstractSeries*series )
87.235
C++ Reference :
Parameters : QPrinter*,QWidget *
Parent Class : QAbstractPrintDialog
•
•
•
•
•
•
• *)
• *getacceptedEvent(void)
87.233. QPointLight Class 1271

Ring Documentation, Release 1.14
87.236
C++ Reference :
Parameters : QPrinter *
Parent Class : QDialog
•
•
• *)
• *getpaintRequestedEvent(void)
87.237
C++ Reference :
Parameters : QPrinter *
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.236. QPrintPreviewDialog Class 1272

Ring Documentation, Release 1.14
• *)
• *)
• *getpaintRequestedEvent(void)
• *getpreviewChangedEvent(void)
87.238
C++ Reference :
Parameters : QPrinter::PrinterMode
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *printEngine(void)
•
•
•
•
•
•
•
•
•
•
87.238. QPrinter Class 1273

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *paintEngine(void)
•
87.239
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
87.239. QPrinterInfo Class 1274

Ring Documentation, Release 1.14
87.240
C++ Reference :
Parameters : QObject *
Parent Class : QIODevice
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *destination)
•
•
•
•
•
•
•
•
87.240. QProcess Class 1275

Ring Documentation, Release 1.14
•
•
• *)
• *)
• *getreadyReadStandardErrorEvent(void)
• *getreadyReadStandardOutputEvent(void)
87.241
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *getvalueChangedEvent(void)
87.241. QProgressBar Class 1276

Ring Documentation, Release 1.14
87.242
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractButton
• *)
• *)
•
•
• *getClickEvent(void)
87.243
C++ Reference :
Parameters : QObject *
• *provider)
•
•
•
•
• *imageProvider(QString providerId)
•
• *errors)
• *incubationController(void)
• *networkAccessManager(void)
• *networkAccessManagerFactory(void)
•
•
•
•
•
• *rootContext(void)
•
•
• *controller)
• *factory)
•
87.242. QPushButton Class 1277

Ring Documentation, Release 1.14
•
•
•
•
• *object)
• *object)
• *object, QQmlContext*context)
• *object, QQmlEngine::ObjectOwnership ownership)
87.244
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
• *object)
•
•
•
87.245
C++ Reference :
Parameters : oat,oat,oat,oat
•
•
•
•
•
•
•
87.244. QQmlError Class 1278

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
87.246
C++ Reference :
Parameters : void
Parent Class : QWindow
• *engine(void)
•
•
•
• *rootContext(void)
• *rootObject(void)
•
•
•
•
•
87.246. QQuickView Class 1279

Ring Documentation, Release 1.14
87.247
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
• *engine(void)
•
•
•
•
• *quickWindow(void)
•
• *rootContext(void)
• *rootObject(void)
•
•
•
•
•
•
• *)
• *)
• *getsceneGraphErrorEvent(void)
• *getstatusChangedEvent(void)
87.248
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractButton
•
•
• *)
• *)
• *)
• *)
• *getclickedEvent(void)
87.247. QQuickWidget Class 1280

Ring Documentation, Release 1.14
• *getpressedEvent(void)
• *getreleasedEvent(void)
• *gettoggledEvent(void)
87.249
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
• *x1, int*y1, int*x2, int*y2)
• *x, int*y, int*width, int*height)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.249. QRect Class 1281

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.250
C++ Reference :
Parameters : void
•
•
•
•
•
•
87.250. QRegion Class 1282

Ring Documentation, Release 1.14
•
•
•
•
•
• *rects, int number)
•
•
•
•
•
•
•
•
•
87.251
C++ Reference :
Parameters : void
•
•
•
matchType, QRegularExpression::MatchOptions matchOptions)
•
•
QRegularExpression::MatchOptions matchOptions)
•
•
•
•
•
•
•
87.251. QRegularExpression Class 1283

Ring Documentation, Release 1.14
87.252
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.253
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
87.252. QRegularExpressionMatch Class 1284

Ring Documentation, Release 1.14
87.254
C++ Reference :
Parameters : QObject *
87.255
C++ Reference :
Parameters : Qt3DCore::QNode *
• *lterKey)
• *parameter)
• *state)
• *> lterKeys(void)
• *> parameters(void)
• *lterKey)
• *parameter)
• *state)
• *> renderStates(void)
•
• *shaderProgram)
87.256
C++ Reference :
Parameters : QObject *
Parent Class : QXYSeries
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *getborderColorChangedEvent(void)
87.254. QRenderAspect Class 1285

Ring Documentation, Release 1.14
• *getcolorChangedEvent(void)
• *getmarkerShapeChangedEvent(void)
• *getmarkerSizeChangedEvent(void)
87.257
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QComponent
•
componentType)
•
•
•
•
•
87.258
C++ Reference :
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.257. QSceneLoader Class 1286

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
87.259
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractScrollArea
•
•
• *childWidget, int xmargin , int ymargin )
•
• *widget)
•
• *takeWidget(void)
• *widget(void)
•
87.260
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractSlider
87.259. QScrollArea Class 1287

Ring Documentation, Release 1.14
87.261
C++ Reference :
Parameters : QObject *
Parent Class : QIODevice
•
•
•
•
•
•
•
• *handle(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
87.261. QSerialPort Class 1288

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *getbaudRateChangedEvent(void)
• *getbreakEnabledChangedEvent(void)
• *getdataBitsChangedEvent(void)
• *getdataTerminalReadyChangedEvent(void)
• *geterrorEvent(void)
• *getowControlChangedEvent(void)
• *getparityChangedEvent(void)
• *getrequestToSendChangedEvent(void)
• *getstopBitsChangedEvent(void)
87.262
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
87.262. QSerialPortInfo Class 1289

Ring Documentation, Release 1.14
87.263
C++ Reference :
Parameters : int width, int height
87.264
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QEntity
•
•
•
•
•
•
87.265
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractSlider
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getactionTriggeredEvent(void)
• *getrangeChangedEvent(void)
• *getsliderMovedEvent(void)
87.263. QSize Class 1290

Ring Documentation, Release 1.14
• *getsliderPressedEvent(void)
• *getsliderReleasedEvent(void)
• *getvalueChangedEvent(void)
87.266
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
87.267
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.266. QSphereMesh Class 1291

Ring Documentation, Release 1.14
•
• *)
• *getvalueChangedEvent(void)
87.268
C++ Reference :
Parameters : QPixmap
Parent Class : QWidget
• *mainWin)
•
•
•
•
•
87.269
C++ Reference :
Parameters : QObject *
Parent Class : QLineSeries
•
87.270
C++ Reference :
Parameters : QWidget*parent
Parent Class : QFrame
• *widget)
•
•
• *min, int*max)
•
•
• *widget)
• *widget)
•
87.268. QSplashScreen Class 1292

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.271
C++ Reference :
Parameters : void
•
•
•
•
•
• *driver(void)
•
•
•
•
•
•
•
•
•
•
•
87.271. QSqlDatabase Class 1293

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
•
87.272
C++ Reference :
Parameters : void
•
•
•
87.272. QSqlDriver Class 1294

Ring Documentation, Release 1.14
87.273
C++ Reference :
Parameters : void
87.274
C++ Reference :
Parameters : QString, QString, QSqlError::ErrorType
•
•
•
•
•
•
•
•
•
•
87.275
C++ Reference :
Parameters : QString,QVariant::Type
•
•
•
•
•
•
•
•
•
•
•
•
•
87.273. QSqlDriverCreatorBase Class 1295

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
87.276
C++ Reference :
Parameters : QString, QString
Parent Class : QSqlRecord
•
•
•
•
•
•
•
87.277
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
87.276. QSqlIndex Class 1296

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *result(void)
•
•
•
•
•
87.278
C++ Reference :
Parameters : void
•
•
•
•
•
87.278. QSqlRecord Class 1297

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
87.279
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractBarSeries
•
87.280
C++ Reference :
Parameters : QWidget *
Parent Class : QFrame
• *widget)
•
•
•
• *widget)
• *widget)
• *widget)
•
•
• *widget)
• *)
87.279. QStackedBarSeries Class 1298

Ring Documentation, Release 1.14
• *)
• *getcurrentChangedEvent(void)
• *getwidgetRemovedEvent(void)
87.281
C++ Reference :
Parameters : void
•
•
•
tions)
•
Paths::LocateOptions options)
•
•
•
87.282
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
•
•
•
•
•
• *widget)
•
•
•
87.281. QStandardPaths Class 1299

Ring Documentation, Release 1.14
87.283
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.283. QString2 Class 1300

Ring Documentation, Release 1.14
87.284
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.284. QStringList Class 1301

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
87.285
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.285. QStringRef Class 1302

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.286
C++ Reference :
Parameters : void
•
•
•
•
87.286. QSurfaceFormat Class 1303

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.286. QSurfaceFormat Class 1304

Ring Documentation, Release 1.14
87.287
C++ Reference :
Parameters : void
• *contextMenu(void)
•
•
•
• *menu)
•
•
•
•
•
•
•
•
•
87.288
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
•
87.287. QSystemTrayIcon Class 1305

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
87.288. QTabBar Class 1306

Ring Documentation, Release 1.14
• *)
• *getcurrentChangedEvent(void)
• *gettabCloseRequestedEvent(void)
• *gettabMovedEvent(void)
87.289
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
• *page, QString)
•
• *cornerWidget(Qt::Corner corner)
•
•
• *currentWidget(void)
•
•
•
• *w)
• *page,QString)
•
•
•
• *widget, Qt::Corner corner)
•
•
•
•
•
•
•
•
•
•
•
87.289. QTabWidget Class 1307

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *widget(int index)
•
•
•
•
• *widget)
• *)
• *)
• *getcurrentChangedEvent(void)
• *gettabCloseRequestedEvent(void)
•
87.290
C++ Reference :
Parameters : QWidget*parent
Parent Class : QAbstractItemView
•
•
•
•
•
•
• *horizontalHeader(void)
•
•
•
•
•
•
87.290. QTableView Class 1308

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *header)
•
•
•
•
• *header)
•
•
•
• *verticalHeader(void)
•
•
•
•
•
•
•
•
•
•
•
•
87.291
C++ Reference :
Parameters : QWidget*parent
Parent Class : QTableView
• *cellWidget(int row, int column)
• *item)
87.291. QTableWidget Class 1309

Ring Documentation, Release 1.14
• *item)
•
•
• *currentItem(void)
•
• *item)
• *horizontalHeaderItem(int column)
• *item(int row, int column)
• *itemAt(int ax, int ay)
• *itemPrototype(void)
• *item)
•
• *item)
•
• *> selectedItems(void)
•
• *widget)
•
•
•
• *item)
•
• *item)
• *item)
•
• *item)
•
• *takeHorizontalHeaderItem(int column)
• *takeItem(int row, int column)
• *takeVerticalHeaderItem(int row)
• *verticalHeaderItem(int row)
•
• *)
•
•
•
87.291. QTableWidget Class 1310

Ring Documentation, Release 1.14
•
•
•
•
• *item, QAbstractItemView::ScrollHint hint)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcellActivatedEvent(void)
• *getcellChangedEvent(void)
• *getcellClickedEvent(void)
• *getcellDoubleClickedEvent(void)
• *getcellEnteredEvent(void)
• *getcellPressedEvent(void)
• *getcurrentCellChangedEvent(void)
• *getcurrentItemChangedEvent(void)
• *getitemActivatedEvent(void)
• *getitemChangedEvent(void)
• *getitemClickedEvent(void)
• *getitemDoubleClickedEvent(void)
• *getitemEnteredEvent(void)
• *getitemPressedEvent(void)
• *getitemSelectionChangedEvent(void)
87.291. QTableWidget Class 1311

Ring Documentation, Release 1.14
87.292
C++ Reference :
Parameters : QString
•
•
• *clone(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *tableWidget(void)
•
•
•
87.292. QTableWidgetItem Class 1312

Ring Documentation, Release 1.14
•
•
•
87.293
C++ Reference :
Parameters : QWidget *
•
•
•
•
•
•
• *nextPendingConnection(void)
•
•
•
•
•
•
•
•
•
• *socketDescriptor(void)
• *timedOut)
• *)
• *)
• *getacceptErrorEvent(void)
• *getnewConnectionEvent(void)
87.293. QTcpServer Class 1313

Ring Documentation, Release 1.14
87.294
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractSocket
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getconnectedEvent(void)
• *getdisconnectedEvent(void)
• *geterrorEvent(void)
• *gethostFoundEvent(void)
• *getproxyAuthenticationRequiredEvent(void)
• *getstateChangedEvent(void)
• *getaboutToCloseEvent(void)
• *getbytesWrittenEvent(void)
• *getreadChannelFinishedEvent(void)
• *getreadyReadEvent(void)
87.295
C++ Reference :
Parameters : Qt3DCore::QNode *
• *lterKey)
• *parameter)
• *pass)
• *> lterKeys(void)
•
• *> parameters(void)
• *lterKey)
87.294. QTcpSocket Class 1314

Ring Documentation, Release 1.14
• *parameter)
• *pass)
• *> renderPasses(void)
87.296
C++ Reference :
•
87.297
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QEntity
•
•
•
•
•
•
•
•
•
•
87.298
C++ Reference :
Parameters : void
•
•
•
•
•
•
• *document(void)
•
87.296. QTest Class 1315

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.299
C++ Reference :
Parameters : QWidget *
Parent Class : QTextEdit
•
•
•
•
•
•
•
•
•
•
•
•
87.299. QTextBrowser Class 1316

Ring Documentation, Release 1.14
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getanchorClickedEvent(void)
• *getbackwardAvailableEvent(void)
• *getforwardAvailableEvent(void)
• *gethighlightedEvent(void)
• *gethistoryChangedEvent(void)
• *getsourceChangedEvent(void)
87.300
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.300. QTextCharFormat Class 1317

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.300. QTextCharFormat Class 1318

Ring Documentation, Release 1.14
87.301
C++ Reference :
• *codecForName(const char*name)
• *c)
87.302
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
• *createList(QTextListFormat)
• *currentFrame(void)
• *currentList(void)
• *currentTable(void)
•
•
• *document(void)
•
•
•
•
•
• *insertFrame(QTextFrameFormat)
•
87.301. QTextCodec Class 1319

Ring Documentation, Release 1.14
•
• *insertList(QTextListFormat)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *rstRow, int*numRows, int*rstColumn, int*numColumns)
•
•
•
•
•
•
•
•
•
•
•
•
•
87.302. QTextCursor Class 1320

Ring Documentation, Release 1.14
87.303
C++ Reference :
Parameters : void
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
• *clone(QObject*parent )
•
•
•
•
• *documentLayout(void)
•
• *p, QRectF rect)
•
•
•
•
•
•
•
•
•
•
•
•
•
87.303. QTextDocument Class 1321

Ring Documentation, Release 1.14
•
•
•
•
•
• *object(int objectIndex)
• *objectForFormat(QTextFormat f)
•
•
• *printer)
• *cursor)
•
•
• *rootFrame(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *cursor)
•
•
87.303. QTextDocument Class 1322

Ring Documentation, Release 1.14
87.304
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractScrollArea
•
•
•
•
•
•
•
•
•
• *document(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *document)
•
87.304. QTextEdit Class 1323

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.304. QTextEdit Class 1324

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcopyAvailableEvent(void)
• *getcurrentCharFormatChangedEvent(void)
• *getcursorPositionChangedEvent(void)
• *getredoAvailableEvent(void)
• *getselectionChangedEvent(void)
• *gettextChangedEvent(void)
• *getundoAvailableEvent(void)
•
•
87.305
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
87.305. QTextStream Class 1325

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.305. QTextStream Class 1326

Ring Documentation, Release 1.14
87.306
Parameters : QIODevice * device
Parent Class : QTextStream
87.307
Parameters : FILE * leHandle, QIODevice::OpenMode
Parent Class : QTextStream
87.308
Parameters : QString*, QIODevice::OpenMode
Parent Class : QTextStream
87.309
Parameters : QByteArray*, QIODevice::OpenMode
Parent Class : QTextStream
87.310
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
87.306. QTextStream2 Class 1327

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getlocaleChangedEvent(void)
• *getpitchChangedEvent(void)
• *getrateChangedEvent(void)
• *getstateChangedEvent(void)
• *getvoiceChangedEvent(void)
• *getvolumeChangedEvent(void)
87.311
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
87.312
C++ Reference :
Parameters : Qt3DCore::QNode *
•
• *texture(void)
•
•
•
87.311. QTextureLoader Class 1328

Ring Documentation, Release 1.14
• *texture)
•
•
87.313
C++ Reference :
Parameters : QObject *
Parent Class : QObject
• *eventDispatcher(void)
•
•
•
•
•
•
• *eventDispatcher)
•
•
•
•
•
•
•
• *currentThread(void)
•
•
•
•
•
•
• *)
• *)
• *getStartedEvent(void)
• *getFinishedEvent(void)
87.313. QThread Class 1329

Ring Documentation, Release 1.14
87.314
C++ Reference :
Parameters : void
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
• *globalInstance(void)
87.315
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.314. QThreadPool Class 1330

Ring Documentation, Release 1.14
•
•
•
•
87.316
C++ Reference :
Parameters : QObject*parent
•
•
•
•
•
•
•
•
• *)
• *gettimeoutEvent(void)
87.317
C++ Reference :
Parameters : QWidget *
Parent Class : QWidget
• *actionAt(int x, int y)
• *addAction(QString)
• *addSeparator(void)
• *addWidget(QWidget*widget)
•
•
•
• *insertSeparator(QAction*before)
• *insertWidget(QAction*before, QWidget*widget)
•
•
•
87.316. QTimer Class 1331

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *toggleViewAction(void)
•
• *widgetForAction(QAction*action)
•
•
87.318
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractButton
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *gettriggeredEvent(void)
• *)
• *getClickEvent(void)
87.318. QToolButton Class 1332

Ring Documentation, Release 1.14
87.319
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
87.320
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
tor3D axis3, oat angle3)
87.319. QTorusMesh Class 1333

Ring Documentation, Release 1.14
•
•
•
•
•
•
87.321
C++ Reference :
Parameters : QWidget *
Parent Class : QAbstractItemView
•
•
•
•
•
•
• *header(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.321. QTreeView Class 1334

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *model)
•
• *selectionModel)
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
87.321. QTreeView Class 1335

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *getcollapsedEvent(void)
• *getexpandedEvent(void)
• *getactivatedEvent(void)
• *getclickedEvent(void)
• *getdoubleClickedEvent(void)
• *getenteredEvent(void)
• *getpressedEvent(void)
• *getviewportEnteredEvent(void)
87.322
C++ Reference :
Parameters : QWidget *
Parent Class : QTreeView
• *item)
• *item, int column)
•
•
• *currentItem(void)
• *item, int column)
• *headerItem(void)
• *item)
• *item)
• *invisibleRootItem(void)
• *item)
• *itemAbove(QTreeWidgetItem*item)
• *itemAt(int x, int y)
• *itemBelow(QTreeWidgetItem*item)
• *itemWidget(QTreeWidgetItem*item, int column)
• *item, int column)
• *item, int column)
87.322. QTreeWidget Class 1336

Ring Documentation, Release 1.14
•
•
• *item, bool span)
• *item)
•
•
• *item, int column, QWidget * widget)
•
•
• *takeTopLevelItem(int index)
• *topLevelItem(int index)
•
• *item)
• *selectionModel)
•
• *item)
• *item)
• *item, QAbstractItemView::ScrollHint hint)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
87.322. QTreeWidget Class 1337

Ring Documentation, Release 1.14
• *getcollapsedEvent(void)
• *getexpandedEvent(void)
• *getactivatedEvent(void)
• *getclickedEvent(void)
• *getdoubleClickedEvent(void)
• *getenteredEvent(void)
• *getpressedEvent(void)
• *getviewportEnteredEvent(void)
• *getcurrentItemChangedEvent(void)
• *getitemActivatedEvent(void)
• *getitemChangedEvent(void)
• *getitemClickedEvent(void)
• *getitemCollapsedEvent(void)
• *getitemDoubleClickedEvent(void)
• *getitemEnteredEvent(void)
• *getitemExpandedEvent(void)
• *getitemPressedEvent(void)
• *getitemSelectionChangedEvent(void)
87.323
C++ Reference :
Parameters : void
• *child)
•
•
• *child(int index)
•
•
• *clone(void)
•
•
•
•
•
•
87.323. QTreeWidgetItem Class 1338

Ring Documentation, Release 1.14
• *child)
• *child)
•
•
•
•
•
• *parent(void)
•
• *child)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *takeChild(int index)
•
•
•
87.323. QTreeWidgetItem Class 1339

Ring Documentation, Release 1.14
• *treeWidget(void)
•
•
•
87.324
C++ Reference :
Parameters : QString
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.324. QUrl Class 1340

Ring Documentation, Release 1.14
•
•
•
•
•
•
87.325
C++ Reference :
Parameters : void
•
87.326
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
• *model)
•
• *series)
• *)
• *)
• *)
• *)
• *)
• *)
• *getrstBarSetColumnChangedEvent(void)
• *getrstRowChangedEvent(void)
87.325. QUuid Class 1341

Ring Documentation, Release 1.14
• *getlastBarSetColumnChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getrowCountChangedEvent(void)
• *getseriesReplacedEvent(void)
87.327
C++ Reference :
Parameters : void
Parent Class : QBoxLayout
• *)
• *)
87.328
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
•
•
• *model)
•
• *series)
• *)
• *)
• *)
• *)
• *)
• *)
• *getrstBoxSetColumnChangedEvent(void)
• *getrstRowChangedEvent(void)
87.327. QVBoxLayout Class 1342

Ring Documentation, Release 1.14
• *getlastBoxSetColumnChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getrowCountChangedEvent(void)
• *getseriesReplacedEvent(void)
87.329
C++ Reference :
Parameters : QObject *
Parent Class : QCandlestickModelMapper
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getcloseRowChangedEvent(void)
• *getrstSetColumnChangedEvent(void)
• *gethighRowChangedEvent(void)
• *getlastSetColumnChangedEvent(void)
• *getlowRowChangedEvent(void)
87.329. QVCandlestickModelMapper Class 1343

Ring Documentation, Release 1.14
• *getopenRowChangedEvent(void)
• *gettimestampRowChangedEvent(void)
87.330
C++ Reference :
Parameters : QObject *
Parent Class : QPieModelMapper
•
•
•
•
•
•
•
• *model)
•
• *series)
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getrstRowChangedEvent(void)
• *getlabelsColumnChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getrowCountChangedEvent(void)
• *getseriesReplacedEvent(void)
• *getvaluesColumnChangedEvent(void)
87.330. QVPieModelMapper Class 1344

Ring Documentation, Release 1.14
87.331
C++ Reference :
Parameters : QObject *
Parent Class : QXYModelMapper
•
•
•
•
•
• *model)
•
• *series)
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *getrstRowChangedEvent(void)
• *getmodelReplacedEvent(void)
• *getrowCountChangedEvent(void)
• *getseriesReplacedEvent(void)
• *getxColumnChangedEvent(void)
• *getyColumnChangedEvent(void)
87.331. QVXYModelMapper Class 1345

Ring Documentation, Release 1.14
87.332
C++ Reference :
Parameters : QObject *
Parent Class : QAbstractAxis
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getlabelFormatChangedEvent(void)
• *getmaxChangedEvent(void)
• *getminChangedEvent(void)
• *getminorTickCountChangedEvent(void)
• *getrangeChangedEvent(void)
87.332. QValueAxis Class 1346

Ring Documentation, Release 1.14
• *gettickAnchorChangedEvent(void)
• *gettickCountChangedEvent(void)
• *gettickIntervalChangedEvent(void)
• *gettickTypeChangedEvent(void)
87.333
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
•
•
• *ok)
•
• *ok)
• *ok)
•
•
•
•
•
•
•
• *ok)
•
•
• *ok)
87.333. QVariant Class 1347

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *ok)
• *ok)
•
•
•
• *typeName(void)
•
•
87.334
Parent Class : QVariant
Parameters : int
87.335
Parent Class : QVariant
Parameters : oat
87.336
Parent Class : QVariant
Parameters : double
87.334. QVariant2 Class 1348

Ring Documentation, Release 1.14
87.337
Parent Class : QVariant
Parameters : QString
87.338
C++ Reference :
Parent Class : QVariant
Parameters : double
87.339
C++ Reference :
Parent Class : QVariant
Parameters : oat
87.340
C++ Reference :
Parent Class : QVariant
Parameters : int
87.341
C++ Reference :
Parent Class : QVariant
Parameters : QString
87.342
C++ Reference :
Parameters : oat,oat
•
•
•
•
87.337. QVariant5 Class 1349

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
87.343
C++ Reference :
Parameters : oat,oat,oat
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.343. QVector3D Class 1350

Ring Documentation, Release 1.14
•
•
87.344
C++ Reference :
Parameters : oat,oat,oat,oat
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.345
C++ Reference :
Parameters : void
•
•
87.344. QVector4D Class 1351

Ring Documentation, Release 1.14
87.346
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *getbrightnessChangedEvent(void)
• *getcontrastChangedEvent(void)
• *getfullScreenChangedEvent(void)
• *gethueChangedEvent(void)
• *getsaturationChangedEvent(void)
87.347
C++ Reference :
Parent Class : QMediaControl
87.346. QVideoWidget Class 1352

Ring Documentation, Release 1.14
87.348
C++ Reference :
Parameters : Qt3DCore::QNode *
•
•
•
•
87.349
C++ Reference :
Parameters : void
•
•
•
•
•
87.350
C++ Reference :
Parameters : QObject *
Parent Class : QObject
•
•
•
•
•
•
Callback)
•
•
•
•
•
•
87.348. QViewport Class 1353

Ring Documentation, Release 1.14
•
• *printer,QWebEngineCallback<bool>)
•
•
•
•
•
•
•
•
•
• *devToolsPage)
•
QWebEnginePage::PermissionPolicy policy)
•
• *page)
• *channel)
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
87.350. QWebEnginePage Class 1354

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getaudioMutedChangedEvent(void)
• *getauthenticationRequiredEvent(void)
• *getcontentsSizeChangedEvent(void)
• *getfeaturePermissionRequestCanceledEvent(void)
• *getfeaturePermissionRequestedEvent(void)
• *getndTextFinishedEvent(void)
• *getfullScreenRequestedEvent(void)
• *getgeometryChangeRequestedEvent(void)
• *geticonChangedEvent(void)
• *geticonUrlChangedEvent(void)
• *getloadFinishedEvent(void)
• *getloadProgressEvent(void)
• *getloadStartedEvent(void)
• *getpdfPrintingFinishedEvent(void)
• *getprintRequestedEvent(void)
• *getproxyAuthenticationRequiredEvent(void)
• *getquotaRequestedEvent(void)
• *getrecentlyAudibleChangedEvent(void)
• *getrecommendedStateChangedEvent(void)
• *getregisterProtocolHandlerRequestedEvent(void)
• *getselectClientCerticateEvent(void)
• *getselectionChangedEvent(void)
87.350. QWebEnginePage Class 1355

Ring Documentation, Release 1.14
• *gettitleChangedEvent(void)
• *geturlChangedEvent(void)
• *getvisibleChangedEvent(void)
• *getwindowCloseRequestedEvent(void)
87.351
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
•
• *history(void)
•
• *page(void)
• *pageAction(QWebEnginePage::WebAction action)
•
•
•
• *page)
•
•
• *settings(void)
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
87.351. QWebEngineView Class 1356

Ring Documentation, Release 1.14
• *getloadFinishedEvent(void)
• *getloadProgressEvent(void)
• *getloadStartedEvent(void)
• *getselectionChangedEvent(void)
• *gettitleChangedEvent(void)
• *geturlChangedEvent(void)
• *printer,const char*cCode)
87.352
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWidget
• *history(void)
• *pageAction(QWebPage::WebAction action)
•
•
• *page)
•
• *settings(void)
•
•
•
•
•
• *printer)
•
•
• *)
• *)
• *)
• *)
• *getloadFinishedEvent(void)
• *getloadProgressEvent(void)
• *getloadStartedEvent(void)
• *getselectionChangedEvent(void)
87.352. QWebView Class 1357

Ring Documentation, Release 1.14
• *gettitleChangedEvent(void)
• *geturlChangedEvent(void)
87.353
C++ Reference :
Parameters : QWidget*parent
Parent Class : QWebEngineView
87.354
C++ Reference :
Parameters : void
Parent Class : QObject
•
•
•
•
• *action)
•
•
•
•
• *childAt(int x, int y)
•
•
•
•
•
•
•
•
•
•
•
• *focusProxy(void)
• *focusWidget(void)
87.353. QWebView Class 1358

Ring Documentation, Release 1.14
•
•
•
•
•
•
• *left, int*top, int*right, int*bottom)
•
•
•
•
•
• *graphicsEffect(void)
• *graphicsProxyWidget(void)
•
•
•
•
•
•
• *before, QAction*action)
•
• *child)
•
• *ancestor)
•
•
•
•
•
•
• *ancestor)
•
•
• *layout(void)
•
87.354. QWidget Class 1359

Ring Documentation, Release 1.14
•
• *parent, QPoint)
•
•
• *parent, QPoint)
•
•
•
•
•
•
•
•
•
•
• *nativeParentWidget(void)
• *nextInFocusChain(void)
•
•
•
• *parentWidget(void)
•
• *previousInFocusChain(void)
•
•
•
•
• *action)
• *target, QPoint,QRegion, QWidget::RenderFlag)
•
•
•
•
•
•
•
87.354. QWidget Class 1360

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
• *w)
•
•
•
• *effect)
•
• *layout)
•
•
•
•
•
•
•
•
•
•
•
• *parent)
•
•
•
•
87.354. QWidget Class 1361

Ring Documentation, Release 1.14
•
• *style)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *w)
•
• *style(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *window(void)
•
87.354. QWidget Class 1362

Ring Documentation, Release 1.14
•
• *windowHandle(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *nd(int id)
• *keyboardGrabber(void)
• *mouseGrabber(void)
• *rst, QWidget*second)
• *createWindowContainer(QWindow*window, QWidget*parent, Qt::WindowFlags ags)
87.354. QWidget Class 1363

Ring Documentation, Release 1.14
87.355
C++ Reference :
Parameters : QScreen *
Parent Class : QObject
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *child, QWindow::AncestorMode mode)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.355. QWindow Class 1364

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *parent)
•
•
• *newScreen)
•
• *parent)
•
•
•
•
•
•
•
87.355. QWindow Class 1365

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
87.355. QWindow Class 1366

Ring Documentation, Release 1.14
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getactiveChangedEvent(void)
• *getcontentOrientationChangedEvent(void)
• *getfocusObjectChangedEvent(void)
• *getheightChangedEvent(void)
• *getmaximumHeightChangedEvent(void)
• *getmaximumWidthChangedEvent(void)
• *getminimumHeightChangedEvent(void)
• *getminimumWidthChangedEvent(void)
• *getmodalityChangedEvent(void)
• *getopacityChangedEvent(void)
• *getscreenChangedEvent(void)
• *getvisibilityChangedEvent(void)
• *getvisibleChangedEvent(void)
• *getwidthChangedEvent(void)
• *getwindowStateChangedEvent(void)
• *getwindowTitleChangedEvent(void)
• *getxChangedEvent(void)
• *getyChangedEvent(void)
87.356
C++ Reference :
Parent Class : QLegendMarker
•
•
87.356. QXYLegendMarker Class 1367

Ring Documentation, Release 1.14
87.357
C++ Reference :
Parent Class : QAbstractSeries
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.357. QXYSeries Class 1368

Ring Documentation, Release 1.14
•
•
•
•
•
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *)
• *getclickedEvent(void)
• *getcolorChangedEvent(void)
• *getdoubleClickedEvent(void)
• *gethoveredEvent(void)
• *getpenChangedEvent(void)
• *getpointAddedEvent(void)
• *getpointLabelsClippingChangedEvent(void)
• *getpointLabelsColorChangedEvent(void)
• *getpointLabelsFontChangedEvent(void)
• *getpointLabelsFormatChangedEvent(void)
• *getpointLabelsVisibilityChangedEvent(void)
• *getpointRemovedEvent(void)
• *getpointReplacedEvent(void)
• *getpointsRemovedEvent(void)
87.357. QXYSeries Class 1369

Ring Documentation, Release 1.14
• *getpointsReplacedEvent(void)
• *getpressedEvent(void)
• *getreleasedEvent(void)
87.358
C++ Reference :
Parameters : void
•
•
•
•
•
•
87.359
C++ Reference :
Parameters : void
•
•
•
•
•
•
•
•
•
•
87.358. QXmlStreamAttribute Class 1370

Ring Documentation, Release 1.14
87.360
C++ Reference :
Parameters : void
•
•
•
•
•
87.361
C++ Reference :
Parameters : void
87.362
C++ Reference :
Parameters : void
•
•
87.363
C++ Reference :
Parameters : void
•
•
•
87.364
C++ Reference :
Parameters : void
•
•
•
87.360. QXmlStreamEntityDeclaration Class 1371

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
• *device(void)
•
•
•
•
•
•
• *entityResolver(void)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.364. QXmlStreamReader Class 1372

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
• *device)
• *resolver)
•
•
•
•
•
87.365
C++ Reference :
Parameters : void
•
•
• *codec(void)
• *device(void)
•
•
•
• *codec)
• *codecName)
• *device)
•
•
•
•
•
•
87.365. QXmlStreamWriter Class 1373

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.366
C++ Reference :
Parameters : Qt3DCore::QNode *
Parent Class : QEntity
•
•
•
•
•
•
• *lens(void)
•
•
•
•
•
87.366. Qt3DCamera Class 1374

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
87.366. Qt3DCamera Class 1375

Ring Documentation, Release 1.14
• *entity)
•
87.367
C++ Reference :
Parameters : void
Parent Class : QWindow
•
•
• *aspect)
•
•
• *activeFrameGraph)
• *root)
• *camera(void)
87.368
Parameters : QTextDocument*parent
•
•
87.367. Qt3DWindow Class 1376

CHAPTER
EIGHTYEIGHT
LOW LEVEL FUNCTIONS
In this chapter we will learn about the low level functions provided by Ring
*callgarbagecollector()| callgc()
*variablepointer() | varptr()
*space()
*nullpointer() | nullptr()
*object2pointer() | obj2ptr()
*pointer2object() | ptr2obj()
*ispointer() | isptr()
*pointercompare() | ptrcmp()
*setpointer() | setptr()
*getpointer() | getptr()
*pointer2string() | ptr2str()
*memorycopy() | memcpy()
*ringvm_cfunctionslist()
*ringvm_functionslist()
*ringvm_classeslist()
*ringvm_packageslist()
*ringvm_memorylist()
*ringvm_calllist()
*ringvm_fileslist()
*ringvm_settrace()
*ringvm_tracedata()
*ringvm_traceevent()
*ringvm_tracefunc()
*ringvm_scopescount()
*ringvm_evalinscope()
*ringvm_passerror()
*ringvm_hideerrorMsg()
*ringvm_callfunc()
*ringvm_see()
*ringvm_give()
*ringvm_info()
1377

Ring Documentation, Release 1.14
88.1
Syntax:
callgc() # Short name
callgarbagecollector() # Long name
Use this function to force calling the garbage collector during function execution when you use a loop that create temp.
variables that you don't free using the assignment operation.
It's very rare to need this function but it's useful when you create something like event-loop for your game engine and
start creating lists on the y when you call functions.
Example
While
# process events
# call functions using temp. lists like myfunc(["temp list"])
# call the garbage collector
callgc()
End
Tip:In Ring the garbage collector works automatically in the end of function execution or when you use the assign-
ment statement.
88.2
Use the varptr() function when you need to pass a pointer to a C/C++ function.
Syntax:
varptr(cVariableName,cPointerType)-->
variablepointer(cVariableName,cPointerType)-->
example:
r
z
seer
seevarptr("r","int")
seevarptr("z","int")
Output:
10
00E3C740
int
2
00E3BEC0
int
2
88.1. callgc() function 1378

Ring Documentation, Release 1.14
Note:the low level object is a list contains three items (The Pointer, The Type, The Status)
88.3
Use the space function to allocate a specic number of bytes in Memory.
Syntax:
Space(nBytesCount)--> String
Example:
mystring200)
See"String Size :
See"String :
See"String Pointer :
Seevarptr("mystring",:char)
Output:
String Size : 200
String :
String Pointer : 00FF8FE8
char
2
Note:You may need the space() and VarPtr() functions to pass buffers to C functions.
Tip:To free the memory allocated using the space() function, use the Assignment operator
mystring1000) # Allocate memory (1000 bytes)
mystring NULL # Free memory stored in mystring
Note:We don't need to free the memory if it's a local variable that will be deleted after the function execution.
88.4
Syntax:
nullptr() # Short name
nullpointer() # Long name
You may need to pass the NULL pointer to a C function that may expect a pointer as parameter and accept NULL
pointers for optional parameters.
Example:
88.3. space() function 1379

Ring Documentation, Release 1.14
The next example uses the SDL_BlitSurface() function from the LibSDL Library through RingSDL The function
accept SDL_Rect pointers in the second and the last parameter. Also the function accept NULL pointers, so we can
pass them using the NULLPointer() Function.
SDL_BlitSurface(text, nullpointer(), surface, nullpointer())
Note:The previous code doesn't work alone, you need to learn how to use RingSDL rst.
Tip:We can pass NULL as parameter instead of using the NULLPointer() function
SDL_BlitSurface(text, NULL, surface,NULL)
88.5
Use this function to get a C pointer for Ring lists and objects
Syntax:
obj2ptr(List|Object)-> # Short name
object2pointer(List|Object)-> # Long name
Note:You have to be sure that the Pointer still valid (Doesn't point to deallocated memory)
88.6
Use this function to get the Ring list and/or object from the low level object (C Pointer)
Syntax:
ptr2obj(Low Level Object)--> List|Object # Short name
pointer2object(Low Level Object)--> List|Object # Long name
Note:You have to be sure that the Pointer still valid (Doesn't point to deallocated memory)
Example:
# Create the list
mylist:5
# Create pointer to the list
x
seex
seenl
# Add items to the list
(continues on next page)
88.5. object2pointer() function 1380

Ring Documentation, Release 1.14
(continued from previous page)
mylistwelcome"
# print the list items
y
seey
Output:
0069A5D8
OBJECTPOINTER
0
1
2
3
4
5
welcome
Note:In Ring the assignment operator copy lists and objects by value, to copy by reference Just use the ob-
ject2pointer() and pointer2object() functions.
Tip:The object2pointer() and pointer2object() are used in the stdlib - Tree Class implementation to create a reference
for the parent node (object) in the child node (another object).
The functions Object2Pointer() and Pointer2Object() are low level functions
We have to be careful when using them to avoid memory problems
If we created a Pointer to a (Local Variable)
This local variable will be deleted from the memory after the end of the function/method execution
This means that the pointer created with Object2Pointer() will becomes a dangling pointer
i.e. A pointer that points to the memory location of the deallocated memory
Using this invalid pointer could lead to (CRASH or Memory Corruption).
If you will use pointers (Using Object2Pointer() or Pointer2Object) then never use pointers that point to the memory
that are deallocated.
In simple words, Keep the memory (Don't delete it if you still need it)
i.e. instead of using (Local Variables) that will be deleted, You can use Class Attributes or Global Variables.
88.6. pointer2object() function 1381

Ring Documentation, Release 1.14
88.7
Check if the parameter is a pointer (C Object) or not.
Syntax:
IsPtr(vPara) ---> True|False # Short name
IsPointer(vPara) ---> True|False # Long name
Example :
fp"r")
?
?
Output :
file
1
88.8
We can compare between two pointers (C Objects) using the ptrcmp() function.
Syntax:
ptrcmp(oObject1,oObject2)--> ifoObject1
value ifoObject1=
pointercompare(oObject1,oObject2)--> ifoObject1
value ifoObject1=
Example:
fp"ptrcmp.ring","r")
fp2
fp3"ptrcmp.ring","r")
seeptrcmp(fp,fp2)
seeptrcmp(fp,fp3)
fclose(fp)
fclose(fp3)
Output:
1
0
88.7. ispointer() function 1382

Ring Documentation, Release 1.14
88.9
Set the pointer address to another address
Syntax:
setptr(pointer,nNewAddress) # Short name
setpointer(pointer,nNewAddress) # Long name
Note:Using setPointer() and getPointer() functions we can change the Memory Address
88.10
Get the pointer address
Syntax:
getptr(pointer)--> # Short name
getpointer(pointer)--> # Long name
Example:
?Sample about using setPointer() and getPointer() functions"
?"=",50)
pointer
?
?Type:
?Address:
?"=",50)
namering"
pointer
?
?Type:
?Address:
?"=",50)
setpointer(pointer, getpointer(pointer)
?After Update"
?Address:
?"=",50)
Output:
==================================================
00000000
NULLPOINTER
0
Type: NULLPOINTER
Address: 0
==================================================
026E2BA8
char
0
(continues on next page)
88.9. setpointer() function 1383

Ring Documentation, Release 1.14
(continued from previous page)
Type: char
Address: 26E2BA8
==================================================
After Update
Address: 26E2BA9
==================================================
88.11
Convert a pointer to a string of binary data
If you want to convert the string to a pointer again use VarPtr() function
Syntax:
ptr2str(pointer,nStart,nCount)--> # Short name
pointer2string(pointer,nStart,nCount)--> # Long name
Note:pointer2String() return another copy of the data
Note:if nStart is Zero, this means starting from the rst character
Example:
namering"
pointer
?
?Type:
?Address:
?Get 4 bytes starting from the pointer address"
mystring0,4)
?
?Get 2 bytes starting from the pointer address + 1"
mystring21,2)
?
Output:
01E03380
char
0
Type: char
Address:E03380
Get4 fromthe pointer address
ring
Get2 fromthe pointer address
in
88.11. pointer2string() function 1384

Ring Documentation, Release 1.14
88.12
Syntax:
memcpy(pDestinationPointer,cSourceString,nSize) # Short name
memorycopy(pDestinationPointer,cSourceString,nSize) # Long name
Example:
str9)
pointer"char")
memcpy(pointer,"one",3)
?
setPointer(pointer,getPointer(pointer)+3)
memcpy(pointer,"one",3)
?
setPointer(pointer,getPointer(pointer)+3)
memcpy(pointer,"one",3)
?
Output:
one
oneone
oneoneone
88.13
The Function return a list of functions written in C.
Syntax:
RingVM_CFunctionsList()--> List
Example:
SeeRingVM_CFunctionsList()
88.14
The Function return a list of functions written in Ring.
Each List Member is a list contains the next items
•
•
•
•
Syntax:
88.12. memcpy() function 1385

Ring Documentation, Release 1.14
RingVM_FunctionsList()--> List
Example:
test()
functest
seeringvm_functionslist()
Output:
test
8
B:/ring/tests/scripts/functionslist.ring
0
88.15
The Function return a list of Classes.
Each List Member is a list contains the next items
•
•
•
•
•
•
Syntax:
RingVM_ClassesList()--> List
Example:
seeringvm_classeslist()
classclass1
funcf1
classclass2fromclass1
classclass3fromclass1
Output:
class1
9
f1
13
B:/ring/tests/scripts/classeslist.ring
0
0
(continues on next page)
88.15. ringvm_classeslist() function 1386

Ring Documentation, Release 1.14
(continued from previous page)
00000000
class2
16
class1
0
00000000
class3
20
class1
0
00000000
88.16
The Function return a list of Packages.
Each List Member is a list contains the next items
•
•
Syntax:
RingVM_PackagesList()--> List
Example:
seeringvm_packageslist()
package package1
classclass1
package package2
classclass1
package package3
classclass1
Output:
package1
class1
11
0
00FEF838
package2
class1
17
0
00FEF978
package3
class1
(continues on next page)
88.16. ringvm_packageslist() function 1387

Ring Documentation, Release 1.14
(continued from previous page)
23
0
00FEFF68
88.17
The Function return a list of Memory Scopes and Variables.
Each List Member is a list contains variables in a different scope.
Each Item in the scope list is a list contains the next items
•
•
•
•
•
Syntax:
RingVM_MemoryList()--> List
Example:
x
test()
functest
y
seeringvm_memorylist()
Output:
true
2
1
0
0
false
2
0
0
0
nl
1
0
0
null
1
0
(continues on next page)
88.17. ringvm_memorylist() function 1388

Ring Documentation, Release 1.14
(continued from previous page)
0
ring_gettemp_var
4
00000000
0
0
ccatcherror
1
NULL
0
0
ring_settemp_var
4
00000000
0
0
ring_tempflag_var
2
0
0
0
stdin
3
50512DB8
file
0
0
0
stdout
3
50512DD8
file
0
0
0
stderr
3
50512DF8
file
0
0
0
this
4
00000000
0
0
sysargv
3
B:ingin/ring
B:/ring/tests/scripts/memorylist.ring
0
0
x
2
10
0
(continues on next page)
88.17. ringvm_memorylist() function 1389

Ring Documentation, Release 1.14
(continued from previous page)
0
y
2
20
0
0
88.18
The Function return a list of the functions call list.
Each List Member is a list contains the next items
•
•
•
•
•
•
•
•
•
•
•
Syntax:
RingVM_CallList()--> List
Example:
hello()
funchello
test()
functest
mylist
fortinmylistseet[2] next
Output:
function hello() infile B:/ring/tests/scripts/calllist.ring
calledfromline
function test() infile B:/ring/tests/scripts/calllist.ring
calledfromline
ringvm_calllist
88.18. ringvm_calllist() function 1390

Ring Documentation, Release 1.14
88.19
Function return a list of the Ring Files.
Syntax:
RingVM_FilesList()--> List
Example:
load"stdlib.ring"
seeringvm_fileslist()
Output:
B:/ring/tests/scripts/fileslist.ring
B:\ring\bin\stdlib.ring
eval
stdlib.ring
stdlib.rh
stdclasses.ring
stdfunctions.ring
stdbase.ring
stdstring.ring
stdlist.ring
stdstack.ring
stdqueue.ring
stdmath.ring
stddatetime.ring
stdfile.ring
stdsystem.ring
stddebug.ring
stddatatype.ring
stdconversion.ring
stdodbc.ring
stdmysql.ring
stdsecurity.ring
stdinternet.ring
stdhashtable.ring
stdtree.ring
88.20
The function ringvm_settrace() determine the Trace function name
The trace function is a Ring function that will be called for each event
Syntax:
RingVM_SetTrace(cCode)
88.19. ringvm_leslist() function 1391

Ring Documentation, Release 1.14
88.21
Inside the function that we will use for tracing events
We can use the ringvm_tracedata() function to get the event data.
The event data is a list contains the next items
•
•
•
•
Syntax:
RingVM_TraceData()-->
88.22
Inside the function that we will use for tracing events
We can use ringvm_traceevent() to know the event type
•
•
•
•
•
•
Syntax:
RingVM_TraceEvent()-->
88.23
The function return the name of the function that we are using for tracing events.
Syntax:
RingVM_TraceEvent()-->
88.21. ringvm_tracedata() 1392

Ring Documentation, Release 1.14
88.24
We can use the RingVM_ScopesCount() function to know the number of scopes used in the application.
In the start of the program, We have the (global scope only)
When we call a function, A new scope is created.
When the function execution is done, the function scope is deleted.
Syntax:
RingVM_ScopesCount()-->
88.25
The function ringvm_evalinscope() is similar to the eval() function
Unlike eval() which execute the code in the current scope
Using RingVM_EvalInScope() we can execute the code in a specic scope.
Syntax:
RingVM_EvalInScope(nScope,cCode)
88.26
When we have runtime error, After printing the Error message, Ring will end the execution of the program.
Using ringvm_passerror() we can avoid that, and continue the execution of our program.
Syntax:
RingVM_PassError()
88.27
We can disable/enable displaying the runtime error messages using the RingVM_HideErrorMsg() function.
Syntax:
RingVM_HideErrorMsg(lStatus)
88.24. ringvm_scopescount() 1393

Ring Documentation, Release 1.14
88.28
We can call a function from a string without using eval() using the ringvm_callfunc()
Syntax:
RingVM_CallFunc(cFuncName)
88.29
The next example use the Trace Functions to trace the program Events!
In practical, We will use the Trace Library instead of these low level functions!
load"tracelib.ring"
ringvm_settrace("mytrace()")
see"Hello, world!"
see"Welcome"
see"How are you?"nl
mytest()
newmyclass { mymethod() }
funcmytest
see"Message from mytest"
funcmytrace
see"====== The Trace function is Active ======"
"Trace Function Name :
"Trace Event :
switchringvm_TraceEvent()
onTRACEEVENT_NEWLINE see"New Line"
onTRACEEVENT_NEWFUNC see"New Function"
onTRACEEVENT_RETURN see"Return"
onTRACEEVENT_ERROR see"Error"
onTRACEEVENT_BEFORECFUNC see"Before C Function"
onTRACEEVENT_AFTERCFUNC see"After C Function"
off
seenl
"Line Number :[TRACEDATA_LINENUMBER]
"File Name :[TRACEDATA_FILENAME]
"Function Name :[TRACEDATA_FUNCNAME]
"Method or Function :
ifringvm_tracedata()[TRACEDATA_METHODORFUNC]
TRACEDATA_METHODORFUNC_METHOD
see"Method"
else
ifringvm_tracedata()[TRACEDATA_FUNCNAME] NULL
see"Command"
else
see"Function"
ok
ok
seenl"=",42)
(continues on next page)
88.28. ringvm_callfunc() 1394

Ring Documentation, Release 1.14
(continued from previous page)
classmyclass
funcmymethod
see"Message from mymethod"
Output:
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 3
File Name : test1.ring
Function Name : ringvm_settrace
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 5
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
Hello, world!
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 6
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
Welcome
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 7
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
How are you?
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 8
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Function
Line Number : 8
File Name : test1.ring
Function Name : mytest
Method or Function : Function
(continues on next page)
88.29. Example - Using the Trace Functions 1395

Ring Documentation, Release 1.14
(continued from previous page)
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 12
File Name : test1.ring
Function Name : mytest
Method or Function : Function
==========================================
Message from mytest
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 14
File Name : test1.ring
Function Name : mytest
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Return
Line Number : 8
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 9
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 43
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Before C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
(continues on next page)
88.29. Example - Using the Trace Functions 1396

Ring Documentation, Release 1.14
(continued from previous page)
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Function
Line Number : 9
File Name : test1.ring
Function Name : mymethod
Method or Function : Method
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 44
File Name : test1.ring
Function Name : mymethod
Method or Function : Method
==========================================
Message from mymethod
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Return
Line Number : 9
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Before C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Before C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
(continues on next page)
88.29. Example - Using the Trace Functions 1397

Ring Documentation, Release 1.14
(continued from previous page)
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 11
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
88.30
The next example uses the Trace functions provided by the Ring language to create the Trace library.
Using the Trace library we have nice Tracing tools and Interaction debugger too.
# Trace Events
TRACEEVENT_NEWLINE = 1
TRACEEVENT_NEWFUNC = 2
TRACEEVENT_RETURN = 3
TRACEEVENT_ERROR = 4
TRACEEVENT_BEFORECFUNC = 5
TRACEEVENT_AFTERCFUNC = 6
# Trace Data
TRACEDATA_LINENUMBER = 1
TRACEDATA_FILENAME = 2
TRACEDATA_FUNCNAME = 3
TRACEDATA_METHODORFUNC = 4
# Method of Function
TRACEDATA_METHODORFUNC_METHOD = TRUE
TRACEDATA_METHODORFUNC_NOTMETHOD = FALSE
TRACE_BREAKPOINTS = TRUE
TRACE_TEMPLIST = []
func Trace cType
switch trim(lower(cType))
on :AllEvents
ringvm_settrace("TraceLib_AllEvents()")
on :Functions
ringvm_settrace("TraceLib_Functions()")
on :PassError
ringvm_settrace("TraceLib_PassError()")
on :Debugger
ringvm_settrace("TraceLib_Debugger()")
on :LineByLine
ringvm_settrace("TraceLib_LineByLine()")
off
func TraceLib_AllEvents
if right(ringvm_tracedata()[TRACEDATA_FILENAME],13) = "tracelib.ring"
(continues on next page)
88.30. Example - The Trace Library 1398

Ring Documentation, Release 1.14
(continued from previous page)
return
ok
see "====== The Trace function is Active ======" + nl +
"Trace Function Name : " + ringvm_TraceFunc() + nl +
"Trace Event : "
switch ringvm_TraceEvent()
on TRACEEVENT_NEWLINE see "New Line"
on TRACEEVENT_NEWFUNC see "New Function"
on TRACEEVENT_RETURN see "Return"
on TRACEEVENT_ERROR see "Error"
on TRACEEVENT_BEFORECFUNC see "Before C Function"
on TRACEEVENT_AFTERCFUNC see "After C Function"
off
see nl +
"Line Number : " + ringvm_tracedata()[TRACEDATA_LINENUMBER] + nl +
"File Name : " + ringvm_tracedata()[TRACEDATA_FILENAME] + nl +
"Function Name : " + ringvm_tracedata()[TRACEDATA_FUNCNAME] + nl +
"Method or Function : "
if ringvm_tracedata()[TRACEDATA_METHODORFUNC] =
TRACEDATA_METHODORFUNC_METHOD
see "Method"
else
if ringvm_tracedata()[TRACEDATA_FUNCNAME] = NULL
see "Command"
else
see "Function"
ok
ok
see nl + Copy("=",42) + nl
func TraceLib_Functions
if right(ringvm_tracedata()[TRACEDATA_FILENAME],13) = "tracelib.ring"
return
ok
switch ringvm_TraceEvent()
on TRACEEVENT_NEWFUNC
see "Open Func : " +
ringvm_TraceData()[TRACEDATA_FUNCNAME] + nl
on TRACEEVENT_RETURN
see "Return to Func : " +
ringvm_TraceData()[TRACEDATA_FUNCNAME] + nl
off
func TraceLib_PassError
if right(ringvm_tracedata()[TRACEDATA_FILENAME],13) = "tracelib.ring"
return
ok
switch ringvm_TraceEvent()
on TRACEEVENT_ERROR
see nl
see "TraceLib : After Error !" + nl
ringvm_passerror()
off
func TraceLib_Debugger
if right(ringvm_tracedata()[TRACEDATA_FILENAME],13) = "tracelib.ring"
return
(continues on next page)
88.30. Example - The Trace Library 1399

Ring Documentation, Release 1.14
(continued from previous page)
ok
switch ringvm_TraceEvent()
on TRACEEVENT_ERROR
_BreakPoint()
off
func TraceLib_LineByLine
if right(ringvm_tracedata()[TRACEDATA_FILENAME],13) = "tracelib.ring" or
ringvm_TraceEvent() != TRACEEVENT_NEWLINE
return
ok
aList = ringvm_tracedata()
see "Before Line : " + aList[TRACEDATA_LINENUMBER] + nl
_BreakPoint()
func BreakPoint
if not TRACE_BREAKPOINTS
return
ok
_BreakPoint()
func _BreakPoint
see nl+nl+Copy("=",60) + nl +
Copy(" ",20)+"Interactive Debugger" + nl +
Copy("=",60) + nl +
"Command (Exit) : End Program" + nl +
"Command (Cont) : Continue Execution" + nl +
"Command (Locals) : Print local variables names" + nl +
"Command (LocalsData) : Print local variables data" + nl +
"Command (Globals) : Print global variables names" + nl +
"We can execute Ring code" + nl +
Copy("=",60) + nl
while true
see nl + "code:> "
give cCode
cmd = trim(lower(cCode))
if cmd = "exit" or cmd = "bye"
shutdown()
ok
nScope = ringvm_scopescount()-2
switch cmd
on "locals"
ringvm_EvalInScope(nScope,"see locals() callgc()")
loop
on "localsdata"
PrintLocalsData(nScope)
loop
on "globals"
ringvm_EvalInScope(nScope,"see globals() callgc()")
loop
on "cont"
ringvm_passerror()
exit
off
Try
ringvm_EvalInScope(nScope,cCode)
catch
(continues on next page)
88.30. Example - The Trace Library 1400

Ring Documentation, Release 1.14
(continued from previous page)
see cCatchError
done
end
func NoBreakPoints
TRACE_BREAKPOINTS = FALSE
func PrintLocalsData nScope
if nScope = 1 # Global
ringvm_Evalinscope(nScope,TRACE_TEMPLIST = globals())
else
ringvm_Evalinscope(nScope,TRACE_TEMPLIST = locals() callgc())
ok
see nl
aTempList = TRACE_TEMPLIST
TRACE_TEMPLIST = []
nSpaces = 5
for TRACE_ITEM in aTempList
if len(TRACE_ITEM) + 5 > nSpaces
nSpaces = len(TRACE_ITEM) + 5
ok
next
for TRACE_ITEM in aTempList
see "Variable : " + TRACE_ITEM
cVarName = TRACE_ITEM
see copy(" ",nSpaces-len(cVarName)) + " Type : "
ringvm_Evalinscope(nScope,"see type(" + TRACE_ITEM +")")
ringvm_Evalinscope(nScope,"see Copy( ,fabs(15-len(type(" +
TRACE_ITEM +"))))")
see " Value : "
ringvm_Evalinscope(nScope,"see " + TRACE_ITEM)
see nl
next
88.31
Using the ringvm_see() function we can redene the behavior of the See command
Also we can use ring_see() to have the original behavior
Example:
see"Hello world"
see123
see["one","two","three"]
see point {x=10=20=30}
funcringvm_see t
ring_see("We want to print:)
ring_See(t)
classpoint x y z
Output:
88.31. ringvm_see() function 1401

Ring Documentation, Release 1.14
We want to print: Hello world
We want to print: 123
We want to print: one
two
three
We want to print: x: 10.000000
y: 20.000000
z: 30.000000
88.32
Using the ringvm_give() function we can redene the behavior of the Give command
Example:
see"Name: givename
see"Hello
funcringvm_give
see"Mahmoud"
return"Mahmoud"
Output:
Name: Mahmoud
Hello Mahmoud
88.33
The ringvm_info() is an internal function that return a list of information about the Ring VM structure.
It's used only by the Ring Team in advanced tests to check the VM status.
Syntax:
ringvm_info()--> Listof information about the VM structure
88.32. ringvm_give() function 1402

CHAPTER
EIGHTYNINE
TUTORIAL: RING EXTENSIONS IN C/C++
In this chapter we will see simple examples about using C code in Ring programs
89.1
Sample : ring/extensions/tutorial/helloworld
&#3627408455;&#3627408469;&#3627408466; ??????&#3627408473;&#3627408466; &#3627408474;&#3627408486;&#3627408473;&#3627408470;&#3627408463;◁&#3627408464; &#3627408464;&#3627408476;&#3627408475;&#3627408481;&#3627408462;&#3627408470;&#3627408475;&#3627408480;
#include
#include
RING_FUNC(ring_myfunction)
{
printf("Hello, World!");
}
RING_APIvoidringlib_init(RingState *pRingState)
{
ring_vm_funcregister("myfunction",ring_myfunction);
}
&#3627408436;&#3627408480; &#3627408484;&#3627408466; &#3627408480;&#3627408466;&#3627408466; &#3627408470;&#3627408475; &#3627408481;&#3627408469;&#3627408466; &#3627408480;&#3627408476;&#3627408482;&#3627408479;&#3627408464;&#3627408466; &#3627408464;&#3627408476;&#3627408465;&#3627408466;˓ &#3627408484;&#3627408466; &#3627408480;&#3627408481;&#3627408462;&#3627408479;&#3627408481; &#3627408484;&#3627408470;&#3627408481;&#3627408469; &#3627408470;&#3627408475;&#3627408464;&#3627408473;&#3627408482;&#3627408465;&#3627408470;&#3627408475;&#3627408468; &#3627408481;&#3627408469;&#3627408466; &#3627408479;&#3627408470;&#3627408475;&#3627408468;◁&#3627408469; ??????&#3627408473;&#3627408466; &#3627408484;&#3627408469;&#3627408470;&#3627408464;&#3627408469; &#3627408464;&#3627408476;&#3627408475;&#3627408481;&#3627408462;&#3627408470;&#3627408475;&#3627408480; &#3627408481;&#3627408469;&#3627408466; &#3627408465;&#3627408466;??????&#3627408475;&#3627408470;&#3627408481;&#3627408470;&#3627408476;&#3627408475;&#3627408480; &#3627408467;&#3627408476;&#3627408479; &#3627408453;&#3627408470;&#3627408475;&#3627408468; &#3627408436;&#3627408451;&#3627408444;
&#3627408455;&#3627408469;&#3627408466;&#3627408475; &#3627408484;&#3627408466; &#3627408482;&#3627408480;&#3627408466; &#3627408481;&#3627408469;&#3627408466; &#3627408453;&#3627408444;&#3627408449;&#3627408442;⌢&#3627408441;&#3627408456;&#3627408449;&#3627408438; &#3627408474;&#3627408462;&#3627408464;&#3627408479;&#3627408476; &#3627408481;&#3627408476; &#3627408465;&#3627408466;??????&#3627408475;&#3627408466; &#3627408475;&#3627408466;&#3627408484; &#3627408467;&#3627408482;&#3627408475;&#3627408464;&#3627408481;&#3627408470;&#3627408476;&#3627408475;&#3627408480;˓ &#3627408470;&#3627408481;??????&#3627408480; &#3627408462; &#3627408468;&#3627408476;&#3627408476;&#3627408465; &#3627408470;&#3627408465;&#3627408466;&#3627408462; &#3627408481;&#3627408476; &#3627408480;&#3627408481;&#3627408462;&#3627408479;&#3627408481; &#3627408481;&#3627408469;&#3627408466; &#3627408467;&#3627408482;&#3627408475;&#3627408464;&#3627408481;&#3627408470;&#3627408476;&#3627408475; &#3627408465;&#3627408466;??????&#3627408475;&#3627408470;&#3627408481;&#3627408470;&#3627408476;&#3627408475; &#3627408484;&#3627408470;&#3627408481;&#3627408469;
ring_&#3627408481;&#3627408476; &#3627408474;&#3627408462;&#3627408472;&#3627408466; &#3627408481;&#3627408469;&#3627408466;&#3627408480;&#3627408466; &#3627408465;&#3627408466;??????&#3627408475;&#3627408470;&#3627408481;&#3627408470;&#3627408476;&#3627408475;&#3627408480; &#3627408482;&#3627408475;&#3627408470;&#3627408478;&#3627408482;&#3627408466; &#3627408462;&#3627408475;&#3627408465; &#3627408465;&#3627408470;&#3627408467;&#3627408467;&#3627408466;&#3627408479;&#3627408466;&#3627408475;&#3627408481; &#3627408481;&#3627408469;&#3627408462;&#3627408475; &#3627408475;&#3627408476;&#3627408479;&#3627408474;&#3627408462;&#3627408473; &#3627408438; &#3627408467;&#3627408482;&#3627408475;&#3627408464;&#3627408481;&#3627408470;&#3627408476;&#3627408475;&#3627408480;
Then we have the function ringlib_init that will be called when the extension is loaded by the Ring VM
In this function we use the ring_vm_funcregister() function to register the new functions in Ring VM
Then we build the extension using :
buildvc.bat
&#3627408455;&#3627408469;&#3627408466; ??????&#3627408473;&#3627408466; &#3627408463;&#3627408482;&#3627408470;&#3627408473;&#3627408465;&#3627408483;&#3627408464;◁&#3627408463;&#3627408462;&#3627408481; &#3627408464;&#3627408476;&#3627408475;&#3627408481;&#3627408462;&#3627408470;&#3627408475;&#3627408480; &#3627408481;&#3627408469;&#3627408466; &#3627408475;&#3627408466;&#3627408485;&#3627408481; &#3627408464;&#3627408476;&#3627408474;&#3627408474;&#3627408462;&#3627408475;&#3627408465;&#3627408480; &#3627408481;&#3627408476; &#3627408463;&#3627408482;&#3627408470;&#3627408473;&#3627408465; &#3627408481;&#3627408469;&#3627408466; &#3627408466;&#3627408485;&#3627408481;&#3627408466;&#3627408475;&#3627408480;&#3627408470;&#3627408476;&#3627408475; &#3627408482;&#3627408480;&#3627408470;&#3627408475;&#3627408468; &#3627408457;&#3627408470;&#3627408480;&#3627408482;&#3627408462;&#3627408473; &#3627408438;▷&#3627408438;⇁⇁
cls
call ../../../src/locatevc.bat
cl /c /DEBUG mylib.c -I"..\..\..\include"
link /DEBUG mylib.obj ..\..\..\libing.lib /DLL /OUT:mylib.dll /SUBSYSTEM:CONSOLE,
˓→"5.01"
del mylib.obj
Then we test the function using
1403

Ring Documentation, Release 1.14
ring test.ring
The le test.ring contains
?Loading Library"
loadlib("mylib.dll")
?Calling a C Function"
myfunction()
Output
Loading Library
Calling a C Function
Hello, World!
89.2
Sample : ring/extensions/tutorial/helloworld2
This extension is the same as the rst one but in this time, we support Windows, Linux and macOS.
We will use the next les
buildvc.bat
buildgcc.sh
buildclang.sh
Where we use buildvc.bat in Windows, buildgcc.sh in Linux and buildclang.sh in macOS
The le buildgcc.sh contains the next commands
gcc -c -fpic mylib.c -I $PWD/../../../include
gcc -shared -o libmylib.so mylib.o -L $PWD/../../../lib -lring
sudo cp libmylib.so /usr/lib
sudo cp libmylib.so /usr/lib64
The le buildclang.sh contains
clang -c -fpic mylib.c -I $PWD/../../../include
clang -dynamiclib -o libmylib.dylib mylib.o -L $PWD/../../../lib -lring
cp libmylib.dylib /usr/local/lib
This time we use mylib.ring instead of using LoadLib() function directly
In mylib.ring we have the next code
ifiswindows()
LoadLib("mylib.dll")
butismacosx()
LoadLib("libmylib.dylib")
else
LoadLib("libmylib.so")
ok
The le test.ring contains
89.2. Build the extension on different platforms 1404

Ring Documentation, Release 1.14
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
89.3
Sample : ring/extensions/tutorial/sumtwonumbers
In this extension we learn how to create a C function to sum two numbers
This extension is an update to the (Hello World 2) extension in : ring/extensions/tutorial/helloworld2 folder
In mylib.c we update the le to add
RING_FUNC(ring_sumtwonumbers)
{
doublenNum1,nNum2,nSum;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
// Check Parameters Type
if(1)&2)) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Sum Numbers
nNum11);
nNum22);
nSum
// Return Output
RING_API_RETNUMBER(nSum);
}
Then we register the new function
ring_vm_funcregister("sumtwonumbers",ring_sumtwonumbers);
The previous code is written to check errors, and to be easy to understand
We can write short code like
RING_API_RETNUMBER(RING_API_GETNUMBER(1)2));
89.3. Sum Two Numbers 1405

Ring Documentation, Release 1.14
The le test.ring contains
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
89.4
Sample : ring/extensions/tutorial/sayhello
In this extension we learn how to create a C function that get a name as string then say hello.
This extension is an update to the (sumtwonumbers) extension in : ring/extensions/tutorial/sumtwonumbers folder
In mylib.c we update the le to add
RING_FUNC(ring_sayhello)
{
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
// Check Parameters Type
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
printf("Hello %s ",RING_API_GETSTRING(1));
}
Then we register the new function
ring_vm_funcregister("sayhello",ring_sayhello);
The le test.ring contains
?Loading Library"
load"mylib.ring"
(continues on next page)
89.4. Say Hello 1406

Ring Documentation, Release 1.14
(continued from previous page)
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
89.5
Sample : ring/extensions/tutorial/sumlist
In this extension we learn how to create a C function that sum list of numbers.
This extension is an update to the (sayhello) extension in : ring/extensions/tutorial/sayhello folder
In mylib.c we update the le to add
RING_FUNC(ring_sumlist)
{
List*pList;
intx,nSum;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
// Check Parameters Type
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Sum List Numbers
nSum;
pList1);
for(x=1=++) {
if( ring_list_isdouble(pList,x) ) {
nSum= int) ring_list_getdouble(pList,x) ;
}
(continues on next page)
89.5. Sum List of Numbers 1407

Ring Documentation, Release 1.14
(continued from previous page)
}
// Return Output
RING_API_RETNUMBER(nSum);
}
Then we register the new function
ring_vm_funcregister("sumlist",ring_sumlist);
The le test.ring contains
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
89.6
Sample : ring/extensions/tutorial/incrementlist
In this extension we learn how to create a C function that increment the list items.
This extension is an update to the (sumlist) extension in : ring/extensions/tutorial/sumlist folder
In mylib.c we update the le to add
RING_FUNC(ring_inclist)
{
(continues on next page)
89.6. Increment List Items 1408

Ring Documentation, Release 1.14
(continued from previous page)
List*pList;
intx,nSum;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
// Check Parameters Type
if(1)&2) ) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Increment List Items
nSum;
pList1);
for(x=1=++) {
if( ring_list_isdouble(pList,x) ) {
ring_list_setdouble(pList,x,
ring_list_getdouble(pList,x)+
RING_API_GETNUMBER(2)) ;
}
}
// Return Output
RING_API_RETLIST(pList);
}
Then we register the new function
ring_vm_funcregister("inclist",ring_inclist);
The le test.ring contains
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
Then we test the function using
ring test.ring
Output
89.6. Increment List Items 1409

Ring Documentation, Release 1.14
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
SumListcontains numbers from1to10
55
IncrementListItems
11
12
13
14
15
16
17
18
19
20
89.7
Sample : ring/extensions/tutorial/lterlist
In this extension we learn how to create a C function that lter the list items.
This extension is an update to the (incrementlist) extension in : ring/extensions/tutorial/incrementlist folder
In mylib.c we update the le to add
RING_FUNC(ring_filterlist)
{
List*pList;
intx;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
// Check Parameters Type
if(1)&2) ) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Filter List Items
pList1);
for(x=--)
if( ring_list_isdouble(pList,x) )
if(
RING_API_GETNUMBER(2)) )
ring_list_deleteitem(pList,x) ;
// Return Output
RING_API_RETLIST(pList);
}
Then we register the new function
89.7. Filter List Items 1410

Ring Documentation, Release 1.14
ring_vm_funcregister("filterlist",ring_filterlist);
The le test.ring contains
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
?Filter List Items (Items > 15)"
?15)
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
Increment List Items
11
12
13
14
15
16
17
18
19
20
Filter List Items (Items > 15)
16
17
(continues on next page)
89.7. Filter List Items 1411

Ring Documentation, Release 1.14
(continued from previous page)
18
19
20
89.8
Sample : ring/extensions/tutorial/replicatelist
In this extension we learn how to create a C function that add more items to the list.
This extension is an update to the (lterlist) extension in : ring/extensions/tutorial/lterlist folder
In mylib.c we update the le to add
RING_FUNC(ring_replicatelist)
{
List*pList;
intx,y,nTimes,nSize;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
// Check Parameters Type
if(1)&2) ) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Replicate List Items
pList1);
nSize
nTimes int) RING_API_GETNUMBER(2);
if(nTimes) {
RING_API_ERROR("Error: The second parameter must be >= 1 ");
return;
}
for(x=++)
for(y=++)
if( ring_list_isdouble(pList,y) )
ring_list_adddouble(pList,
ring_list_getdouble(pList,y));
// Return Output
RING_API_RETLIST(pList);
}
Then we register the new function
ring_vm_funcregister("replicatelist",ring_replicatelist);
The le test.ring contains
?Loading Library"
load"mylib.ring"
?Calling a C Function"
(continues on next page)
89.8. Replicate List Items 1412

Ring Documentation, Release 1.14
(continued from previous page)
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
?Filter List Items (Items > 15)"
?15)
aList:3
?Replicate list (1:3) three times then print the items (We expect 12 items)"
?3)
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
Increment List Items
11
12
13
14
15
16
17
18
19
20
Filter List Items (Items > 15)
16
17
18
19
20
(continues on next page)
89.8. Replicate List Items 1413

Ring Documentation, Release 1.14
(continued from previous page)
Replicate list (1:3) three times then print the items (We expect 12 items)
1
2
3
1
2
3
1
2
3
1
2
3
89.9
Sample : ring/extensions/tutorial/generatelist
In this extension we learn how to create a C function that create new list and add items to the list.
This extension is an update to the (replicatelist) extension in : ring/extensions/tutorial/replicatelist folder
In mylib.c we update the le to add
RING_FUNC(ring_generatelist)
{
List*pList;
intx,nSize;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
// Check Parameters Type
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Create the List
pList
// Generate List Items
nSize int) RING_API_GETNUMBER(1);
if(nSize) {
RING_API_ERROR("Error: The list size must be >= 1 ");
return;
}
for(x=++)
ring_list_adddouble(pList,( double) x);
// Return Output
RING_API_RETLIST(pList);
}
Then we register the new function
ring_vm_funcregister("generatelist",ring_generatelist);
89.9. Generate List 1414

Ring Documentation, Release 1.14
The le test.ring contains
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
?Filter List Items (Items > 15)"
?15)
aList:3
?Replicate list (1:3) three times then print the items (We expect 12 items)"
?3)
?Create list contains 5 items using C code"
aList5)
?
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
Increment List Items
11
12
13
14
15
16
17
18
19
20
(continues on next page)
89.9. Generate List 1415

Ring Documentation, Release 1.14
(continued from previous page)
Filter List Items (Items > 15)
16
17
18
19
20
Replicate list (1:3) three times then print the items (We expect 12 items)
1
2
3
1
2
3
1
2
3
1
2
3
Create list contains 5 items using C code
1
2
3
4
5
89.10
Sample : ring/extensions/tutorial/displaylist
In this extension we learn how to create a C function that display all of the list items including nested lists
In mylib.c we update the le to add
voidmylib_displaylist(List *pList);
RING_FUNC(ring_displaylist)
{
List*pList;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
// Check Parameters Type
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Get the List
pList1);
(continues on next page)
89.10. Display List 1416

Ring Documentation, Release 1.14
(continued from previous page)
// Display the List Items including Nested Lists
mylib_displaylist(pList);
}
voidmylib_displaylist(List *pList) {
intx;
for(x=1; x=++) {
if( ring_list_isdouble(pList,x) ) {
printf("Number : %f ", ring_list_getdouble(pList,x) ) ;
}else ( ring_list_isstring(pList,x) ) {
printf("String : %s ", ring_list_getstring(pList,x) ) ;
}else ( ring_list_islist(pList,x) ) {
printf("Sub List.. ");
mylib_displaylist( ring_list_getlist(pList,x) );
}
}
}
Then we register the new function
ring_vm_funcregister("displaylist",ring_displaylist);
The le test.ring contains
load"stdlib.ring"
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
?Filter List Items (Items > 15)"
?15)
aList:3
?Replicate list (1:3) three times then print the items (We expect 12 items)"
?3)
?Create list contains 5 items using C code"
aList5)
?
?Create List (3,2)"
(continues on next page)
89.10. Display List 1417

Ring Documentation, Release 1.14
(continued from previous page)
aList3,2)
aList[1][1]R 1 C 1"
aList[1][2]R 1 C 2"
aList[2][1]R 2 C 1"
aList[2][2]R 2 C 2"
aList[3][1]R 3 C 1"
aList[3][2]R 3 C 2"
?Print the List using Ring"
?
?Print the List by calling C Code"
displayList(aList)
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
Increment List Items
11
12
13
14
15
16
17
18
19
20
Filter List Items (Items > 15)
16
17
18
19
20
Replicate list (1:3) three times then print the items (We expect 12 items)
1
2
3
1
2
3
1
2
3
(continues on next page)
89.10. Display List 1418

Ring Documentation, Release 1.14
(continued from previous page)
1
2
3
Create list contains 5 items using C code
1
2
3
4
5
Create List (3,2)
Print the List using Ring
R 1 C 1
R 1 C 2
R 2 C 1
R 2 C 2
R 3 C 1
R 3 C 2
Print the List by calling C Code
Sub List..
String : R 1 C 1
String : R 1 C 2
Sub List..
String : R 2 C 1
String : R 2 C 2
Sub List..
String : R 3 C 1
String : R 3 C 2
89.11
Sample : ring/extensions/tutorial/updatetable
In this extension we learn how to create a C function that update a table contains rows and columns
In mylib.c we update the le to add
RING_FUNC(ring_updatetable)
{
List*pList,*pRow;
intnRow,nCol;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
// Check Parameters Type
if(1)&2) ) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Get the List (Represent a Table)
pList1);
(continues on next page)
89.11. Update Table 1419

Ring Documentation, Release 1.14
(continued from previous page)
// Update the Table Rows and Columns
for(nRow=++
if( ring_list_islist(pList,nRow) ) {
pRow
for(nCol=++
if( ring_list_isdouble(pRow,nCol) ) {
ring_list_setdouble(pRow,nCol,RING_API_GETNUMBER(2));
}else{
RING_API_ERROR("Error : We expect numbers! ");
return;
}
}
}else{
RING_API_ERROR("Error : The parameter is not a table! ");
return;
}
}
}
Then we register the new function
ring_vm_funcregister("updatetable",ring_updatetable);
The le test.ring contains
load"stdlib.ring"
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
?Filter List Items (Items > 15)"
?15)
aList:3
?Replicate list (1:3) three times then print the items (We expect 12 items)"
?3)
?Create list contains 5 items using C code"
aList5)
?
(continues on next page)
89.11. Update Table 1420

Ring Documentation, Release 1.14
(continued from previous page)
?Create List (3,2)"
aList3,2)
aList[1][1]R 1 C 1"
aList[1][2]R 1 C 2"
aList[2][1]R 2 C 1"
aList[2][2]R 2 C 2"
aList[3][1]R 3 C 1"
aList[3][2]R 3 C 2"
?Print the List using Ring"
?
?Print the List by calling C Code"
displayList(aList)
?"
?Create List (2,2)"
aList2,2)
?Update the list using C code - set all cells to 10"
UpdateTable(aList,10)
?aList[1][1] :[1][1]
?aList[1][2] :[1][2]
?aList[2][1] :[2][1]
?aList[2][2] :[2][2]
Then we test the function using
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
Increment List Items
11
12
13
14
15
16
17
18
19
20
Filter List Items (Items > 15)
16
17
18
19
20
(continues on next page)
89.11. Update Table 1421

Ring Documentation, Release 1.14
(continued from previous page)
Replicate list (1:3) three times then print the items (We expect 12 items)
1
2
3
1
2
3
1
2
3
1
2
3
Create list contains 5 items using C code
1
2
3
4
5
Create List (3,2)
Print the List using Ring
R 1 C 1
R 1 C 2
R 2 C 1
R 2 C 2
R 3 C 1
R 3 C 2
Print the List by calling C Code
Sub List..
String : R 1 C 1
String : R 1 C 2
Sub List..
String : R 2 C 1
String : R 2 C 2
Sub List..
String : R 3 C 1
String : R 3 C 2
Create List (2,2)
Update the list using C code - set all cells to 10
aList[1][1] : 10
aList[1][2] : 10
aList[2][1] : 10
aList[2][2] : 10
89.11. Update Table 1422

Ring Documentation, Release 1.14
89.12
Sample : ring/extensions/tutorial/createtable
In this extension we learn how to create a C function that create a table contains rows and columns
In mylib.c we update the le to add
RING_FUNC(ring_createtable)
{
List*pList,*pRow;
intx,y,nRows,nCols;
// Check Parameters Count
if(RING_API_PARACOUNT=) {
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
// Check Parameters Type
if(1)&2) ) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
// Create the List
pList
// Create the table items
nRows int) RING_API_GETNUMBER(1);
nCols int) RING_API_GETNUMBER(2);
if( (nRows)|) ) {
RING_API_ERROR("Error: The table rows and columns must be >= 1 ");
return;
}
for(x=++) {
pRow
for(y=++)
ring_list_adddouble(pRow,0.0);
}
// Return Output
RING_API_RETLIST(pList);
}
Then we register the new function
ring_vm_funcregister("createtable",ring_createtable);
The le test.ring contains
load"stdlib.ring"
?Loading Library"
load"mylib.ring"
?Calling a C Function"
myfunction()
?Sum Two Numbers (3,5)"
?3,5)
?Say Hello"
(continues on next page)
89.12. Create Table 1423

Ring Documentation, Release 1.14
(continued from previous page)
SayHello("Mahmoud")
?Sum List contains numbers from 1 to 10"
aList:10
?
?Increment List Items"
?10)
?Filter List Items (Items > 15)"
?15)
aList:3
?Replicate list (1:3) three times then print the items (We expect 12 items)"
?3)
?Create list contains 5 items using C code"
aList5)
?
?Create List (3,2)"
aList3,2)
aList[1][1]R 1 C 1"
aList[1][2]R 1 C 2"
aList[2][1]R 2 C 1"
aList[2][2]R 2 C 2"
aList[3][1]R 3 C 1"
aList[3][2]R 3 C 2"
?Print the List using Ring"
?
?Print the List by calling C Code"
displayList(aList)
?"
?Create List (2,2)"
aList2,2)
?Update the list using C code - set all cells to 10"
UpdateTable(aList,10)
?aList[1][1] :[1][1]
?aList[1][2] :[1][2]
?aList[2][1] :[2][1]
?aList[2][2] :[2][2]
?"
?Create List (3,3) using C code"
aList3,3)
?aList[1][1] :[1][1]
?aList[1][2] :[1][2]
?aList[1][3] :[1][3]
?aList[2][1] :[2][1]
?aList[2][2] :[2][2]
?aList[2][3] :[2][3]
?aList[3][1] :[3][1]
?aList[3][2] :[3][2]
?aList[3][3] :[3][3]
Then we test the function using
89.12. Create Table 1424

Ring Documentation, Release 1.14
ring test.ring
Output
Loading Library
Calling a C Function
Hello, World!
Sum Two Numbers (3,5)
8
Say Hello
Hello Mahmoud
Sum List contains numbers from 1 to 10
55
Increment List Items
11
12
13
14
15
16
17
18
19
20
Filter List Items (Items > 15)
16
17
18
19
20
Replicate list (1:3) three times then print the items (We expect 12 items)
1
2
3
1
2
3
1
2
3
1
2
3
Create list contains 5 items using C code
1
2
3
4
5
Create List (3,2)
Print the List using Ring
R 1 C 1
(continues on next page)
89.12. Create Table 1425

Ring Documentation, Release 1.14
(continued from previous page)
R 1 C 2
R 2 C 1
R 2 C 2
R 3 C 1
R 3 C 2
Print the List by calling C Code
Sub List..
String : R 1 C 1
String : R 1 C 2
Sub List..
String : R 2 C 1
String : R 2 C 2
Sub List..
String : R 3 C 1
String : R 3 C 2
Create List (2,2)
Update the list using C code - set all cells to 10
aList[1][1] : 10
aList[1][2] : 10
aList[2][1] : 10
aList[2][2] : 10
Create List (3,3) using C code
aList[1][1] : 0
aList[1][2] : 0
aList[1][3] : 0
aList[2][1] : 0
aList[2][2] : 0
aList[2][3] : 0
aList[3][1] : 0
aList[3][2] : 0
aList[3][3] : 0
89.12. Create Table 1426

CHAPTER
NINETY
EXTENSION USING THE C/C++ LANGUAGES
We can extend the Ring Virtual Machine (RingVM) by adding new functions written in the C programming language
or C++. The RingVM comes with many functions written in C that we can call like any Ring function.
We can extend the language by writing new functions then rebuilding the RingVM again, or we can create shared
library (DLL/So) le to extend the RingVM without the need to rebuild it.
The Ring language source code comes with two les to add new modules to the RingVM, ring_ext.h and ring_ext.c
90.1
The le ring_ext.h contains constants that we can change to include/exclude modules during the build process.
#ifndef ringext_h
#define ringext_h
/*Constants*/
#define RING_VM_LISTFUNCS 1
#define RING_VM_REFMETA 1
#define RING_VM_MATH 1
#define RING_VM_FILE 1
#define RING_VM_OS 1
#define RING_VM_MYSQL 1
#define RING_VM_ODBC 1
#define RING_VM_OPENSSL 1
#define RING_VM_CURL 1
#define RING_VM_DLL 1
#endif
90.2
The le ring_ext.c check constants dened in ring_ext.h before calling the start-up function in each module.
Each module contains a function that register the module functions in the RingVM.
#include
voidring_vm_extension *pRingState )
{
/*Reflection and Meta-programming */
#if RING_VM_REFMETA
ring_vm_refmeta_loadfunctions(pRingState);
(continues on next page)
1427

Ring Documentation, Release 1.14
(continued from previous page)
#endif
/*List Functions*/
#if RING_VM_LISTFUNCS
ring_vm_listfuncs_loadfunctions(pRingState);
#endif
/*Math*/
#if RING_VM_MATH
ring_vm_math_loadfunctions(pRingState);
#endif
/*File*/
#if RING_VM_FILE
ring_vm_file_loadfunctions(pRingState);
#endif
/*OS*/
#if RING_VM_OS
ring_vm_os_loadfunctions(pRingState);
#endif
/*MySQL*/
#if RING_VM_MYSQL
ring_vm_mysql_loadfunctions(pRingState);
#endif
/*ODBC*/
#if RING_VM_ODBC
ring_vm_odbc_loadfunctions(pRingState);
#endif
/*OPENSSL*/
#if RING_VM_OPENSSL
ring_vm_openssl_loadfunctions(pRingState);
#endif
/*CURL*/
#if RING_VM_CURL
ring_vm_curl_loadfunctions(pRingState);
#endif
/*DLL*/
#if RING_VM_DLL
ring_vm_dll_loadfunctions(pRingState);
#endif
}
90.3
Each module starts by include the ring header le (ring.h). This les contains the Ring API that we can use to extend
the RingVM.
Each module comes with a function to register the module functions in the RingVM The registration is done by using
ring_vm_funcregister() function.
The ring_vm_funcregister() function takes two parameters, the rst is the function name that will be used by Ring
programs to call the function. The second parameter is the function pointer in the C program.
for example, the ring_vmmath.c module contains the next code to register the module functions
#include
voidring_vm_math_loadfunctions *pRingState )
(continues on next page)
90.3. Module Organization 1428

Ring Documentation, Release 1.14
(continued from previous page)
{
ring_vm_funcregister("sin",ring_vm_math_sin);
ring_vm_funcregister("cos",ring_vm_math_cos);
ring_vm_funcregister("tan",ring_vm_math_tan);
ring_vm_funcregister("asin",ring_vm_math_asin);
ring_vm_funcregister("acos",ring_vm_math_acos);
ring_vm_funcregister("atan",ring_vm_math_atan);
ring_vm_funcregister("atan2",ring_vm_math_atan2);
ring_vm_funcregister("sinh",ring_vm_math_sinh);
ring_vm_funcregister("cosh",ring_vm_math_cosh);
ring_vm_funcregister("tanh",ring_vm_math_tanh);
ring_vm_funcregister("exp",ring_vm_math_exp);
ring_vm_funcregister("log",ring_vm_math_log);
ring_vm_funcregister("log10",ring_vm_math_log10);
ring_vm_funcregister("ceil",ring_vm_math_ceil);
ring_vm_funcregister("floor",ring_vm_math_floor);
ring_vm_funcregister("fabs",ring_vm_math_fabs);
ring_vm_funcregister("pow",ring_vm_math_pow);
ring_vm_funcregister("sqrt",ring_vm_math_sqrt);
ring_vm_funcregister("unsigned",ring_vm_math_unsigned);
ring_vm_funcregister("decimals",ring_vm_math_decimals);
ring_vm_funcregister("murmur3hash",ring_vm_math_murmur3hash);
}
Tip:Remember that the function ring_vm_math_loadfunctions() will be called by the ring_vm_extension() function
(in the ring_ext.c le).
90.4
Each module function may contains the next steps
1 - Check Parameters Count
2 - Check Parameters Type
3 - Get Parameters Values
4 - Execute Code/Call Functions
5 - Return Value
The structure is very similar to any function (Input - Process - Output) But here we will use the Ring API for the steps
1,2,3 and 5.
90.4. Function Structure 1429

Ring Documentation, Release 1.14
90.5
We can check the parameters count using the RING_API_PARACOUNT macro.
We can compare RING_API_PARACOUNT with any numeric value using == or != operators.
Example:
if( RING_API_PARACOUNT=
/*code*/
}
Example:
if( RING_API_PARACOUNT=
/*code*/
}
90.6
We can display error messages using the RING_API_ERROR() function.
The function will display the error and end the execution of the program.
Note:the behaviour of this function can be changed by the Ring code using Try/Catch/Done statements, so in your C
code, use Return after this function.
Syntax:
RING_API_ERROR(const *cErrorMsg);
&#3627408455;&#3627408469;&#3627408466; &#3627408453;&#3627408470;&#3627408475;&#3627408468; &#3627408436;&#3627408451;&#3627408444; &#3627408464;&#3627408476;&#3627408474;&#3627408466;&#3627408480; &#3627408484;&#3627408470;&#3627408481;&#3627408469; &#3627408480;&#3627408476;&#3627408474;&#3627408466; &#3627408476;&#3627408467; &#3627408477;&#3627408479;&#3627408466;&#3627408465;&#3627408466;??????&#3627408475;&#3627408466;&#3627408465; &#3627408466;&#3627408479;&#3627408479;&#3627408476;&#3627408479; &#3627408474;&#3627408466;&#3627408480;&#3627408480;&#3627408462;&#3627408468;&#3627408466;&#3627408480; &#3627408481;&#3627408469;&#3627408462;&#3627408481; &#3627408484;&#3627408466; &#3627408464;&#3627408462;&#3627408475; &#3627408482;&#3627408480;&#3627408466;
#define RING_API_MISS1PARA "Bad parameters count, the function expect one parameter"
#define RING_API_MISS2PARA "Bad parameters count, the function expect two parameters"
#define RING_API_MISS3PARA "Bad parameters count, the function expect three parameters
˓→"
#define RING_API_MISS4PARA "Bad parameters count, the function expect four parameters"
#define RING_API_BADPARATYPE "Bad parameter type!"
#define RING_API_BADPARACOUNT "Bad parameters count!"
#define RING_API_BADPARARANGE "Bad parameters value, error in range!"
#define RING_API_NOTPOINTER "Error in parameter, not pointer!"
#define RING_API_NULLPOINTER "Error in parameter, NULL pointer!"
#define RING_API_EMPTYLIST "Bad parameter, empty list!"
90.5. Check Parameters Count 1430

Ring Documentation, Release 1.14
90.7
We can check the parameter type using the next functions
intRING_API_ISNUMBER( intnParameterNumber);
intRING_API_ISSTRING( intnParameterNumber);
intRING_API_ISLIST( intnParameterNumber);
intRING_API_ISCPOINTER( intnParameterNumber);
intRING_API_ISPOINTER( intnParameterNumber); // List or C Pointer
The output of these functions will be 1 (True) or 0 (False).
90.8
We can get parameters values using the next functions
doubleRING_API_GETNUMBER( intnParameterNumber);
const *RING_API_GETSTRING( intnParameterNumber);
intRING_API_GETSTRINGSIZE( intnParameterNumber);
List*RING_API_GETLIST( intnParameterNumber);
void*RING_API_GETCPOINTER( intnParameterNumber, const *cPoinerType);
intRING_API_GETPOINTERTYPE( intnParameterNumber);
90.9
We can return values from our function using the next functions.
RING_API_RETNUMBER(doublenValue);
RING_API_RETSTRING(const *cString);
RING_API_RETSTRING2(const *cString,intnStringSize);
RING_API_RETLIST(List *pList);
RING_API_RETCPOINTER( void*pValue,const *cPointerType);
RING_API_RETMANAGEDCPOINTER( void*pValue,const *cPointerType,
void(*pFreeFunc)(void*,void*))
90.10
When we dene new function to be used for RingVM extension, we use the next prototype
voidmy_function_name( void*pPointer );
or we can use the RING_FUNC() Macro
RING_FUNC(my_function_name);
90.7. Check Parameters Type 1431

Ring Documentation, Release 1.14
90.11
The next code represents the sin() function implementation using the Ring API and the sin() C function.
voidring_vm_math_sin void*pPointer )
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
if( RING_API_ISNUMBER(1) ) {
RING_API_RETNUMBER(sin(RING_API_GETNUMBER(1)));
}else{
RING_API_ERROR(RING_API_BADPARATYPE);
}
}
90.12
The next code represents the fopen() function implementation using the Ring API and the fopen() C Function.
The function takes two parameters, the rst parameter is the le name as string. The second parameter is the mode as
string.
In the le ring_vmle.h we have some constants to use as the pointer type like
#define RING_VM_POINTER_FILE "file"
#define RING_VM_POINTER_FILEPOS "filepos"
The function implementation in ring_vmle.c
voidring_vm_file_fopen void*pPointer )
{
FILE*fp ;
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
if( RING_API_ISSTRING(1)&2) ) {
fp1),RING_API_GETSTRING(2));
RING_API_RETCPOINTER(fp,RING_VM_POINTER_FILE);
}else{
RING_API_ERROR(RING_API_BADPARATYPE);
}
}
The next code represents the fclose() function implementation
voidring_vm_file_fclose void*pPointer )
{
FILE*fp ;
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
(continues on next page)
90.11. Sin() Function Implementation 1432

Ring Documentation, Release 1.14
(continued from previous page)
if( RING_API_ISCPOINTER(1) ) {
fp FILE*) RING_API_GETCPOINTER(1,RING_VM_POINTER_FILE) ;
if( fp=
RING_API_RETNUMBER(fclose(fp));
RING_API_SETNULLPOINTER(1);
}
}else{
RING_API_ERROR(RING_API_BADPARATYPE);
}
}
From fopen() and fclose() implementation we learned
1 - how to return C pointer using RING_API_RETCPOINTER() function
2 - how to check if the parameter is a pointer using the RING_API_ISCPOINTER() function
3 - how to get C pointer value using the RING_API_GETCPOINTER() function
4 - how to set the C pointer variable (in RingVM) to NULL using the RING_API_SETNULLPOINTER() function
90.13
In this section we will learn about the list functions provided by the Ring API to create new lists and manipulate the
list items.
List*ring_list_new intnSize ) ;
voidring_list_newitem *pList ) ;
Item*ring_list_getitem *pList,intindex ) ;
List*ring_list_delete *pList ) ;
voidring_list_deleteitem *pList,intindex ) ;
voidring_list_print *pList ) ;
intring_list_gettype *pList,intindex ) ;
voidring_list_setint *pList,intindex ,intnumber ) ;
voidring_list_addint *pList,intx ) ;
voidring_list_setpointer *pList,intindex ,void*pValue ) ;
voidring_list_addpointer *pList,void*pValue ) ;
voidring_list_setfuncpointer *pList,intindex ,void(*pFunc)(void*) ) ;
voidring_list_addfuncpointer *pList,void(*pFunc)(void*) ) ;
intring_list_isfuncpointer *pList,intindex ) ;
voidring_list_setdouble *pList,intindex ,doublenumber ) ;
voidring_list_adddouble *pList,doublex ) ;
voidring_list_setstring *pList,intindex ,const *str ) ;
voidring_list_setstring2 *pList,intindex ,const *str,intnStrSize ) ;
voidring_list_addstring *pList,const *str ) ;
voidring_list_addstring2 *pList,const *str,intnStrSize ) ;
List*ring_list_newlist *pList ) ;
List*ring_list_getlist *pList,intindex ) ;
voidring_list_setlist *pList,intindex ) ;
voidring_list_setactiveitem *pList, Items*pItems,intindex ) ;
voidring_list_copy *pNewList, List*pList ) ;
intring_list_isnumber *pList,intindex ) ;
intring_list_isstring *pList,intindex ) ;
intring_list_islist *pList,intindex ) ;
intring_list_ispointer *pList,intindex ) ;
voidring_list_deleteallitems *pList ) ;
(continues on next page)
90.13. Ring API - List Functions 1433

Ring Documentation, Release 1.14
(continued from previous page)
voidring_list_insertitem *pList,intx ) ;
voidring_list_insertint *pList,intnPos,intx ) ;
voidring_list_insertdouble *pList,intnPos,doublex ) ;
voidring_list_insertpointer *pList,intnPos,void*pValue ) ;
voidring_list_insertstring *pList,intnPos,const *str ) ;
voidring_list_insertstring2 *pList,intnPos,const *str,intnStrSize ) ;
voidring_list_insertfuncpointer *pList,intnPos,void(*pFunc)(void*) ) ;
List*ring_list_insertlist *pList,intnPos ) ;
intring_list_isiteminsidelist *pList,Item*pItem ) ;
intring_list_findstring *pList,const *str,intnColumn ) ;
intring_list_finddouble *pList,doublenNum1,intnColumn ) ;
voidring_list_sortnum *pList,intleft,intright,intnColumn ) ;
voidring_list_sortstr *pList,intleft,intright,intnColumn ) ;
intring_list_binarysearchnum *pList,doublenNum1,intnColumn ) ;
intring_list_binarysearchstr *pList,const *cFind,intnColumn ) ;
voidring_list_swap *pList,intx,inty ) ;
doublering_list_getdoublecolumn *pList,intnIndex,intnColumn ) ;
char*ring_list_getstringcolumn *pList,intnIndex,intnColumn ) ;
voidring_list_genarray *pList ) ;
voidring_list_deletearray *pList ) ;
voidring_list_genhashtable *pList ) ;
voidring_list_genhashtable2 *pList ) ;
voidring_list_refcopy *pNewList, List*pList ) ;
voidring_list_clear *pList ) ;
/*Macro*/
ring_list_isdouble(pList,index)
ring_list_isint(pList,index)
ring_list_deletelastitem(x)
ring_list_gethashtable(x)
ring_list_getint(pList,index)
ring_list_getpointer(pList,index)
ring_list_getfuncpointer(pList,index)
ring_list_callfuncpointer(pList,index,x)
ring_list_getdouble(pList,index)
ring_list_getstring(pList,index)
ring_list_getstringobject(pList,index)
ring_list_getstringsize(pList,index)
ring_list_getsize(x) (x->nSize)
90.14
In this section we will learn about the string functions provided by the Ring API to create new string and manipulate
the string content.
String*ring_string_new const *str ) ;
String*ring_string_new2 const *str,intnStrSize ) ;
String*ring_string_delete *pString ) ;
intring_string_size *pString ) ;
voidring_string_set *pString,const *str ) ;
voidring_string_set2 *pString,const *str,intnStrSize ) ;
voidring_string_add *pString,const *str ) ;
voidring_string_add2 *pString,const *str,intnStrSize ) ;
voidring_string_print *pString ) ;
voidring_string_setfromint *pString,intx ) ;
(continues on next page)
90.14. Ring API - String Functions 1434

Ring Documentation, Release 1.14
(continued from previous page)
char*ring_string_lower char*cStr ) ;
char*ring_string_upper char*cStr ) ;
char*ring_string_lower2 char*cStr,intnStrSize ) ;
char*ring_string_upper2 char*cStr,intnStrSize ) ;
char*ring_string_find char*cStr1,char*cStr2 ) ;
char*ring_string_find2 char*cStr1,intnStrSize1,char*cStr2,intnStrSize2 ) ;
/*Macro*/
ring_string_tolower(x)
ring_string_toupper(x)
ring_string_get(x)
90.15
The next code presents the MySQL_Columns() function implementation.
This function returns table columns information.
voidring_vm_mysql_columns void*pPointer )
{
MYSQL*con ;
MYSQL_RES*result ;
intnColumns,x ;
MYSQL_ROW row ;
MYSQL_FIELD*field ;
List*pList,*pList2 ;
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
if( RING_API_ISCPOINTER(1) ) {
con *) RING_API_GETCPOINTER(1,RING_VM_POINTER_MYSQL) ;
if( con=
return;
}
result
if( result=
RING_API_RETNUMBER(0);
return;
}
pList
nColumns
if( row
while( field
pList2
ring_list_addstring(pList2,field->name);
ring_list_adddouble(pList2,field->length);
ring_list_adddouble(pList2,field->type);
ring_list_adddouble(pList2,field->flags);
}
}
mysql_free_result(result);
RING_API_RETLIST(pList);
}else{
RING_API_ERROR(RING_API_BADPARATYPE);
(continues on next page)
90.15. MySQL_Columns() Function Implementation 1435

Ring Documentation, Release 1.14
(continued from previous page)
}
}
Lists are of type List, in the previoud function we declared two pointers of type List using List*pList,*pList2;
Note:The function uses RING_API_NEWLIST to create new list instead of ring_list_new() to create the list in
Temp. Memory related to the function scope. This way we can return the list from the function. Also we don't delete
the list, if it's stored in a variable by Ring Code it will be saved, if not it will be automatically deleted by RingVM.
The list can contains sub lists, we used the function ring_list_newlist() to create a sublist.
The function ring_list_addstring() is used to add string items to the list/sublist.
The function ring_list_adddouble() is used to add numeric items to the list/sublist.
Note:All numeric items in lists returned from RingVM extension functions must be of type double and added to the
list using ring_list_adddouble() function.
We return the list from the extension function using the RING_API_RETLIST() function.
90.16
tion
Instead of rebuilding the RingVM after writing new functions using C/C++ and the Ring API, we can create a
DLL/So/Dylib le and dynamically use the functions provided by this le in the runtime using the LoadLib() function.
Dynamic library example in C
#include
RING_DLL(dllexport)
RING_FUNC(ring_ringlib_dlfunc)
{
printf("Message from dlfunc");
}
RING_DLLvoidringlib_init(RingState *pRingState)
{
ring_vm_funcregister("dlfunc",ring_ringlib_dlfunc);
}
the idea is to create the ringlib_init() function, this function will be called by the RingVM when we use the generated
DLL le though the LoadLib() function.
Inside the ringlib_init() function we can register the module function or call a function that do the registration process
for all of the module functions.
The next Ring code demonstrates how to use the DLL library during the runtime.
See"Dynamic DLL"
LoadLib("ringlib.dll")
dlfunc()
90.16. Dynamic/Shared Libraries (DLL/So/Dylib) and LoadLib() function 1436

Ring Documentation, Release 1.14
Output:
Dynamic DLL
Messagefromdlfunc
90.17
Using RING_API_RETMANAGEDCPOINTER() the Ring extensions written in C/C++ languages can return a man-
aged pointer to Ring. This pointer can be controlled by the Ring VM using reference counting.
This is important to avoid the need to write code that free the unmanaged resources like QPixMap objects in RingQt.
Also the Code Generator for extensions is updated to automatically use RING_API_RETMANAGEDCPOINTER()
based on need.
Syntax:
RING_API_RETMANAGEDCPOINTER(void *pValue,const char *cPointerType,
void (*pFreeFunc)(void *,void*))
Example:
The next example from ring_qt.cpp - QPixMap Class - Scaled() Method.
RING_FUNC(ring_QPixmap_scaled)
{
QPixmap*pObject ;
if ( RING_API_PARACOUNT != 5 ) {
RING_API_ERROR(RING_API_BADPARACOUNT);
return ;
}
RING_API_IGNORECPOINTERTYPE ;
if ( ! RING_API_ISCPOINTER(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return ;
}
pObject = (QPixmap *) RING_API_GETCPOINTER(1,"QPixmap");
if ( ! RING_API_ISNUMBER(2) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return ;
}
if ( ! RING_API_ISNUMBER(3) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return ;
}
if ( ! RING_API_ISNUMBER(4) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return ;
}
if ( ! RING_API_ISNUMBER(5) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return ;
}
{
QPixmap*pValue ;
pValue = new QPixmap() ;
*pValue = pObject->scaled( (int ) RING_API_GETNUMBER(2),
(continues on next page)
90.17. Using RING_API_RETMANAGEDCPOINTER() 1437

Ring Documentation, Release 1.14
(continued from previous page)
(int ) RING_API_GETNUMBER(3),
(Qt::AspectRatioMode ) (int) RING_API_GETNUMBER(4),
(Qt::TransformationMode ) (int) RING_API_GETNUMBER(5));
RING_API_RETMANAGEDCPOINTER(pValue,"QPixmap",ring_QPixmap_freefunc);
}
}
The function that will free the memory takes two parameters (Ring State and the allocated Memory Pointer)
Example:
void ring_QPixmap_freefunc(void *pState,void*pPointer)
{
QPixmap*pObject ;
pObject = (QPixmap *) pPointer;
delete pObject ;
}
90.17. Using RING_API_RETMANAGEDCPOINTER() 1438

CHAPTER
NINETYONE
EMBEDDING RING LANGUAGE IN C/C++ PROGRAMS
We can use the Ring language from C/C++ programs using the next functions
RingState*ring_state_init();
ring_state_runcode(RingState *pState,const *cCode);
ring_state_delete(RingState *pState);
91.1
The idea is to use the ring_state_init() to create new state for the Ring Language then call the ring_state_runcode()
function to execut Ring code using the same state. When we are done, we call the ring_state_delete() to free the
memory.
Example:
#include
#include
intmain( intargc,char*argv[])
{
RingState*pState
printf("welcome ");
ring_state_runcode(pState,"&#3627408480;&#3627408466;&#3627408466; &#3627409170;&#3627408469;&#3627408466;&#3627408473;&#3627408473;&#3627408476; &#3627408484;&#3627408476;&#3627408479;&#3627408473;&#3627408465; &#3627408467;&#3627408479;&#3627408476;&#3627408474; &#3627408481;&#3627408469;&#3627408466; &#3627408479;&#3627408470;&#3627408475;&#3627408468; &#3627408477;&#3627408479;&#3627408476;&#3627408468;&#3627408479;&#3627408462;&#3627408474;&#3627408474;&#3627408470;&#3627408475;&#3627408468; &#3627408473;&#3627408462;&#3627408475;&#3627408468;&#3627408482;&#3627408462;&#3627408468;&#3627408466;&#3627409170;⇁&#3627408475;&#3627408473;
˓→");
ring_state_delete(pState);
}
Output:
welcome
hello world from the ring programming language
91.2
The Ring API comes with the next functions to create and delete the state. Also we have functions to create new
variables and get variables values.
RingState*ring_state_init void) ;
RingState*ring_state_delete *pRingState ) ;
voidring_state_runcode *pRingState,const *cStr ) ;
List*ring_state_findvar *pRingState,const *cStr ) ;
(continues on next page)
1439

Ring Documentation, Release 1.14
(continued from previous page)
List*ring_state_newvar *pRingState,const *cStr ) ;
voidring_state_main intargc,char*argv[] ) ;
intring_state_runfile *pRingState,const *cFileName ) ;
voidring_state_runobjectfile *pRingState,const *cFileName ) ;
voidring_state_runobjectstring *pRingState,char*cString,const
˓→*cFileName ) ;
91.3
We can create more than one ring state in the same program and we can create and modify variable values.
&#3627408455;&#3627408476; &#3627408468;&#3627408466;&#3627408481; &#3627408481;&#3627408469;&#3627408466; &#3627408483;&#3627408462;&#3627408479;&#3627408470;&#3627408462;&#3627408463;&#3627408473;&#3627408466; &#3627408473;&#3627408470;&#3627408480;&#3627408481; &#3627408484;&#3627408466; &#3627408464;&#3627408462;&#3627408475; &#3627408482;&#3627408480;&#3627408466; &#3627408481;&#3627408469;&#3627408466; &#3627408479;&#3627408470;&#3627408475;&#3627408468;⌢&#3627408480;&#3627408481;&#3627408462;&#3627408481;&#3627408466;⌢??????&#3627408475;&#3627408465;&#3627408483;&#3627408462;&#3627408479;↼↽ &#3627408467;&#3627408482;&#3627408475;&#3627408464;&#3627408481;&#3627408470;&#3627408476;&#3627408475;◁
To create new variable we can use the ring_state_newvar() function.
Example:
#include
#include
intmain( intargc,char*argv[])
{
List*pList;
RingState*pState
RingState*pState2
printf("welcome ");
ring_state_runcode(pState,"&#3627408480;&#3627408466;&#3627408466; &#3627409170;&#3627408469;&#3627408466;&#3627408473;&#3627408473;&#3627408476; &#3627408484;&#3627408476;&#3627408479;&#3627408473;&#3627408465; &#3627408467;&#3627408479;&#3627408476;&#3627408474; &#3627408481;&#3627408469;&#3627408466; &#3627408479;&#3627408470;&#3627408475;&#3627408468; &#3627408477;&#3627408479;&#3627408476;&#3627408468;&#3627408479;&#3627408462;&#3627408474;&#3627408474;&#3627408470;&#3627408475;&#3627408468; &#3627408473;&#3627408462;&#3627408475;&#3627408468;&#3627408482;&#3627408462;&#3627408468;&#3627408466;&#3627409170;⇁&#3627408475;&#3627408473;
˓→");
printf("Again from C we will call ring code ");
ring_state_runcode(pState,"for x = 1 to 10 see x + nl next");
ring_state_runcode(pState2,"for x = 1 to 5 see x + nl next");
printf("Now we will display the x variable value from ring code ");
ring_state_runcode(pState,"&#3627408480;&#3627408466;&#3627408466; &#3627409170;&#3627408485; &#3627408483;&#3627408462;&#3627408473;&#3627408482;&#3627408466; . &#3627409170; ⇁ &#3627408485; ⇁ &#3627408475;&#3627408473;);
ring_state_runcode(pState2,"&#3627408480;&#3627408466;&#3627408466; &#3627409170;&#3627408485; &#3627408483;&#3627408462;&#3627408473;&#3627408482;&#3627408466; . &#3627409170; ⇁ &#3627408485; ⇁ &#3627408475;&#3627408473;);
pList"x");
printf("Printing Ring variable value from C , %.0f ",
ring_list_getdouble(pList,RING_VAR_VALUE));
printf("now we will set the ring variable value from C ");
ring_list_setdouble(pList,RING_VAR_VALUE,20);
ring_state_runcode(pState,"&#3627408480;&#3627408466;&#3627408466; &#3627409170;&#3627408485; &#3627408483;&#3627408462;&#3627408473;&#3627408482;&#3627408466; &#3627408462;&#3627408467;&#3627408481;&#3627408466;&#3627408479; &#3627408482;&#3627408477;&#3627408465;&#3627408462;&#3627408481;&#3627408466; . &#3627409170; ⇁ &#3627408485; ⇁ &#3627408475;&#3627408473;);
pList"v1");
ring_list_setdouble(pList,RING_VAR_VALUE,10);
pList"v2");
ring_list_setdouble(pList,RING_VAR_VALUE,20);
(continues on next page)
91.3. Ring State Variables 1440

Ring Documentation, Release 1.14
(continued from previous page)
ring_state_runcode(pState,"see v1 + v2 = see v1+v2 see nl");
ring_state_runcode(pState,"see end of test + nl");
ring_state_delete(pState);
ring_state_delete(pState2);
}
Output:
welcome
hello worldfromthe ring programming language
Again C we willcallring code
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
Now we will display the x variable value fromring code
x value :
x value :
Printing Ring variable value fromC ,
now we will set the ring variable value fromC
x value after update :
v1
endof test
91.3. Ring State Variables 1441

CHAPTER
NINETYTWO
CODE GENERATOR FOR WRAPPING C/C++ LIBRARIES
In this chapter we will learn how to use the code generator to wrap C/C++ Libraries to use it in our Ring applications.
92.1
The code generator program is parsec.ring that can be executed as any ring code using the ring language.
URL :
for example to read a conguration le called test.cf to generate the source code le test.c run parsec.ring as in the
next command
ring parsec.ring test.cf test.c
92.2
The conguration le (*.cf) is the input le that we pass to the code generator. This le determine the functions
prototypes that we need to use from a C/C++ library.
Writing conguration les is simple according to the next rules
92.3
•
Example:
ALLEGRO_DISPLAY *al_create_display(int w, int h)
void al_destroy_display(ALLEGRO_DISPLAY *display)
int al_get_new_display_flags(void)
void al_set_new_display_flags(int flags)
int al_get_new_display_option(int option, int *importance)
The previous example will guide the code generator to generate 5 functions that wraps the al_create_display(),
al_destroy_display(), al_get_new_display_ags(), al_set_new_diplay_as() and al_get_new_display_option() func-
tions.
The generated code will be as in the next example
1442

Ring Documentation, Release 1.14
RING_FUNC(ring_al_create_display)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
if(2) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
RING_API_RETCPOINTER(al_create_display( (int ) RING_API_GETNUMBER(1),
(int ) RING_API_GETNUMBER(2)),"ALLEGRO_DISPLAY");
}
RING_FUNC(ring_al_destroy_display)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
al_destroy_display((ALLEGRO_DISPLAY *) RING_API_GETCPOINTER(1,"ALLEGRO_DISPLAY"));
}
RING_FUNC(ring_al_get_new_display_flags)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_BADPARACOUNT);
return;
}
RING_API_RETNUMBER(al_get_new_display_flags());
}
RING_FUNC(ring_al_set_new_display_flags)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
al_set_new_display_flags( (int ) RING_API_GETNUMBER(1));
}
(continues on next page)
92.3. Using the function prototype 1443

Ring Documentation, Release 1.14
(continued from previous page)
RING_FUNC(ring_al_get_new_display_option)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS2PARA);
return;
}
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
if(2) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
RING_API_RETNUMBER(al_get_new_display_option( (int ) RING_API_GETNUMBER(1),
RING_API_GETINTPOINTER(2)));
RING_API_ACCEPTINTVALUE(2) ;
}
from the previous example we can see how much of time and effort is saved using the Code Generator.
92.4
•
Example :
<code>
/*some C code will be written here */
</code>
We use this feature when we need to do something without the help of the code generator. for example including
header les and dening constants using Macro.
92.5
•To determine a prex in all of the functions names type it between <funcstart> and </funcstart>for ex-
ample when we wrap the Allegro game programming library and we need all of the library functions
to start with “al” we type the next code in the conguration le
<funcstart>
al
</funcstart>
92.4. Adding code to the generated code 1444

Ring Documentation, Release 1.14
92.6
•
just type the structures names between <struct> and </struct> also after the structure name you can type the structure
members between { } separated by comma.
Example
<struct>
ALLEGRO_COLOR
ALLEGRO_EVENT { type , keyboard.keycode , mouse.x , mouse.y }
</struct>
from the previous example we will generate two function to create/delete the structure ALLEGRO_COLOR Also we
will generate two functions to create/delete the structure ALLEGRO_EVENT and four functions to get the structure
ALLEGRO_EVENT members (type, keyboard.keycode, mouse.x, mouse.y).
92.7
You can determine the pointer name before the strucuture member name.
Example:
SDL_Surface {flags,SDL_PixelFormat *format,w,h,pitch,void *pixels}
92.8
You can dene constants using <constant> and </constant>
The generator will generate the required functions to get the constant values
And will dene the constants to be used with the same name in Ring code using*.rh le that will be generated too.
rh = Ring Header
Example:
<constant>
MIX_DEFAULT_FORMAT
SDL_QUIT
SDL_BUTTON_LEFT
SDL_BUTTON_MIDDLE
SDL_BUTTON_RIGHT
</constant>
Note:You will need to pass the*.rh le name to parsec.ring after the generated source le name.
Example:
ring ..\codegen\parsec.ring libsdl.cf ring_libsdl.c ring_libsdl.rh
92.6. Generate function to wrap structures 1445

Ring Documentation, Release 1.14
92.9
We can register functions by typing the function prototype between <register> and </register> We need this feature
only when we don't provide the function prototype as input directly where we need to write the code of this function.
Example:
<register>
void al_exit(void)
</register>
<code>
RING_FUNC(ring_al_exit)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_BADPARACOUNT);
return;
}
exit(0);
}
</code>
In the previous example we register the al_exit() function. This function is not part of the Allegro Library, it's just an
extra function that we need to add. Then the code if this function is written inside <code> and </code>. This function
call the exit() function from the C language library.
92.10
•
Example:
<comment>
configuration files
</comment>
92.11
•
write the code between <runcode> and </runcode>
Example:
<runcode>
aNumberTypesal_fixed"
</runcode>
The previoud line of code add the string “al_xed” to the list aNumberTypes, This list contains types that can be
considered as numbers when the code generator nd it in the function prototype.
92.9. Register New Functions 1446

Ring Documentation, Release 1.14
92.12
We have the list aEnumTypes to use for adding each Enumeration we uses in the functions prototype.
Example:
<runcode>
aNumberTypesqreal"
aNumberTypesqint64"
aEnumTypesQt::GestureType"
aEnumTypesQt::GestureFlag"
</runcode>
92.13
using <lter> and </lter> we can include/exclude parts of the conguration le based on a condition, for example
<filter>
... functions related towindows
</filter>
92.14
The default type for constant is Number But Some constants may be another type, for example (pointer : void*)
before using <constant> and </constant> we can use <runcode> and </runcode> to determine the constant type using
two global variables used by the code generator.
The rst variable is $nDefaultConstantType which can be * C_CONSTANT_TYPE_NUMBER *
C_CONSTANT_TYPE_STRING * C_CONSTANT_TYPE_POINTER
if we are using C_CONSTANT_TYPE_POINTER then we will need the second global variable which is $cDefault-
ConstantPointerType to determine the pointer type.
Example :
The next example uses this feature to dene constants in the FreeGLUT library
<runcode>
$nDefaultConstantType
$cDefaultConstantPointerTypevoid"
</runcode>
<constant>
GLUT_STROKE_ROMAN
GLUT_STROKE_MONO_ROMAN
GLUT_BITMAP_9_BY_15
GLUT_BITMAP_8_BY_13
GLUT_BITMAP_TIMES_ROMAN_10
GLUT_BITMAP_TIMES_ROMAN_24
GLUT_BITMAP_HELVETICA_10
GLUT_BITMAP_HELVETICA_12
GLUT_BITMAP_HELVETICA_18
</constant>
92.12. Enum and Numbers 1447

Ring Documentation, Release 1.14
92.15
The next conguration le enable us to use the Allegro library functions. The conguration le size is less than 1000
lines. when the code generator take this le as input the generated source code le in the C language will be 12000
lines of code!
We can see this conguration le as a complete example about using the code generator Also we can use it to know
the functions that can be used from RingAllegro when you use it to create 2D games!
<code>
#define ALLEGRO_NO_MAGIC_MAIN
#include <allegro5/allegro.h>
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
#include <allegro5/allegro_opengl.h>
#include <allegro5/allegro_direct3d.h>
#include <allegro5/allegro_color.h>
#include <allegro5/allegro_memfile.h>
#include "allegro5/allegro_native_dialog.h"
#include <allegro5/allegro_physfs.h>
#include <allegro5/allegro_primitives.h>
</code>
<funcstart>
al
</funcstart>
<struct>
ALLEGRO_EVENT { type , keyboard.keycode , mouse.x , mouse.y }
ALLEGRO_TIMEOUT
ALLEGRO_SAMPLE_ID
ALLEGRO_COLOR
</struct>
<register>
void al_exit(void)
</register>
<code>
RING_FUNC(ring_al_exit)
{
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_BADPARACOUNT);
return;
}
exit(0);
}
</code>
int al_init(void)
<comment>
configuration files
(continues on next page)
92.15. Conguration le for the Allegro Library 1448

Ring Documentation, Release 1.14
(continued from previous page)
</comment>
<runcode>
aNumberTypesal_fixed"
</runcode>
ALLEGRO_CONFIG*al_create_config(void)
void al_destroy_config(ALLEGRO_CONFIG *config)
ALLEGRO_CONFIG*al_load_config_file(const char *filename)
ALLEGRO_CONFIG*al_load_config_file_f(ALLEGRO_FILE *file)
bool al_save_config_file(const char *filename, const ALLEGRO_CONFIG *config)
bool al_save_config_file_f(ALLEGRO_FILE *file, const ALLEGRO_CONFIG *config)
void al_add_config_section(ALLEGRO_CONFIG *config, const char *name)
Note:we just provided part of the conguration le, for complete copy check the Ring source code distribution.
92.16
Next, another part of the congutaiton le, it's important because we can learn from it how to add threads to our Ring
applications by using a threads library.
The idea is using ring_vm_mutexfunctions() and ring_vm_runcodefromthread() to execute Ring code.
<comment>
Threads
</comment>
<code>
void*al_func_thread(ALLEGRO_THREAD *thread, void*pPointer)
{
List*pList;
VM*pVM;
const char*cStr;
pList List*) pPointer ;
pVM *) ring_list_getpointer(pList,2);
cStr1);
ring_vm_runcodefromthread(pVM,cStr);
ring_list_delete(pList);
return ;
}
RING_FUNC(ring_al_create_thread)
{
ALLEGRO_THREAD*pThread;
List*pList;
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
(continues on next page)
92.16. Threads Support 1449

Ring Documentation, Release 1.14
(continued from previous page)
}
pList0);
ring_list_addstring(pList,RING_API_GETSTRING(1));
ring_list_addpointer(pList,pPointer);
ring_vm_mutexfunctions((VM *) pPointer,al_create_mutex,
al_lock_mutex,al_unlock_mutex,al_destroy_mutex);
pThread
al_start_thread(pThread);
RING_API_RETCPOINTER(pThread,"ALLEGRO_THREAD");
}
RING_FUNC(ring_al_run_detached_thread)
{
List*pList;
if( RING_API_PARACOUNT=
RING_API_ERROR(RING_API_MISS1PARA);
return;
}
if(1) ) {
RING_API_ERROR(RING_API_BADPARATYPE);
return;
}
pList0);
ring_list_addstring(pList,RING_API_GETSTRING(1));
ring_list_addpointer(pList,pPointer);
ring_vm_mutexfunctions((VM *) pPointer,al_create_mutex,
al_lock_mutex,al_unlock_mutex,al_destroy_mutex);
al_run_detached_thread(al_func_thread, pList);
}
</code>
<register>
ALLEGRO_THREAD*al_create_thread(void)
void al_run_detached_thread(void)
</register>
void al_start_thread(ALLEGRO_THREAD *thread)
void al_join_thread(ALLEGRO_THREAD *thread, void**ret_value)
void al_set_thread_should_stop(ALLEGRO_THREAD *thread)
bool al_get_thread_should_stop(ALLEGRO_THREAD *thread)
void al_destroy_thread(ALLEGRO_THREAD *thread)
ALLEGRO_MUTEX*al_create_mutex(void)
ALLEGRO_MUTEX*al_create_mutex_recursive(void)
void al_lock_mutex(ALLEGRO_MUTEX *mutex)
void al_unlock_mutex(ALLEGRO_MUTEX *mutex)
void al_destroy_mutex(ALLEGRO_MUTEX *mutex)
ALLEGRO_COND*al_create_cond(void)
void al_destroy_cond(ALLEGRO_COND *cond)
void al_wait_cond(ALLEGRO_COND *cond, ALLEGRO_MUTEX *mutex)
92.16. Threads Support 1450

Ring Documentation, Release 1.14
92.17
•
•
abstract and staticmethods”
•
•
code
•
•
•
•
objects, this happens when we set the codename attribute to a class that we will dene and this class need the
Virtual Machine pointer (for example to use it to execute Ring code from C++ code).
•
•
•
•
•
•
•
variable from a function
•
the C++ method. this feature is required because some C++ method may be identical to Ring Keywords like
“load”,”next”,”end” and “done”.
•
parameters (As in C++)
92.18
To run the code generator to generate code for using C++ library in the Ring application, we can do that as we did
with using C libraries but here we will generate.cpp le instead of *.c le. Also we will determine another le to be
generated (.ring). This le will contains classes in Ring code that wraps C++ functions for using C++ classes and
objects.
ring parsec.ring generator\qt.cf ring_qt.cpp ring_qt.ring
92.17. Code Generator Rules for Wrapping C++ Classes 1451

Ring Documentation, Release 1.14
92.19
The next conguration le is used to wrap many Qt classes The conguration le is around 3500 lines and generate
C++ code around 56000 lines and generate also Ring code around 9000 lines.
<nodllstartup>
<libinitfunc>
<ignorecpointertype>
<code>
externC"
#include "ring.h"
}
#include "ring_qt.h"
#include "gpushbutton.h"
#include "gaction.h"
#include "glineedit.h"
#include "gtextedit.h"
#include "glistwidget.h"
#include "gtreeview.h"
#include "gtreewidget.h"
#include "gcombobox.h"
#include "gtabwidget.h"
#include "gtablewidget.h"
#include "gprogressbar.h"
#include "gspinbox.h"
#include "gslider.h"
#include "gdial.h"
#include "gwebview.h"
#include "gcheckbox.h"
#include "gradiobutton.h"
#include "gbuttongroup.h"
#include "gvideowidget.h"
#include "gtimer.h"
#include "gtcpserver.h"
#include "giodevice.h"
#include "gabstractsocket.h"
#include "gtcpsocket.h"
#include "gcolordialog.h"
#include "gallevents.h"
#include <QApplication>
#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QPixmap>
#include <QIcon>
#include <QSize>
#include <QPushButton>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QTextEdit>
(continues on next page)
92.19. Conguration le for the Qt Framework 1452

Ring Documentation, Release 1.14
(continued from previous page)
#include <QListWidget>
#include <QTreeView>
#include <QDir>
#include <QFileSystemModel>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QComboBox>
#include <QVariant>
#include <QMenuBar>
#include <QMenu>
#include <QToolBar>
#include <QMainWindow>
#include <QStatusBar>
#include <QDockWidget>
#include <QTabWidget>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QSizePolicy>
#include <QFrame>
#include <QAbstractScrollArea>
#include <QAbstractItemView>
#include <QProgressBar>
#include <QSpinBox>
#include <QSlider>
#include <QAbstractSlider>
#include <QDateEdit>
#include <QDateTimeEdit>
#include <QAbstractSpinBox>
#include <QDial>
#include <QWebView>
#include <QUrl>
#include <QCheckBox>
#include <QRadioButton>
#include <QButtonGroup>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QVideoWidget>
#include <QPrinter>
#include <QAction>
#include <QEvent>
#include <QMessageBox>
#include <QTimer>
#include <QFileDialog>
#include <QPainter>
#include <QPicture>
#include <QPen>
#include <QColor>
#include <QPrinter>
#include <QFont>
#include <QWebSettings>
#include <QBrush>
#include <QByteArray>
#include <QIODevice>
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QTcpServer>
#include <QNetworkProxy>
(continues on next page)
92.19. Conguration le for the Qt Framework 1453

Ring Documentation, Release 1.14
(continued from previous page)
#include <QHostAddress>
#include <QHostInfo>
#include <QList>
#include <QFileInfo>
#include <QDirModel>
#include <QModelIndex>
#include <QFontDialog>
#include <QDialog>
#include <QTextCursor>
#include <QTextBlock>
#include <QTextDocumentFragment>
#include <QColorDialog>
#include <QHeaderView>
#include <QStringList>
#include <QKeySequence>
#include <QLCDNumber>
#include <QInputDialog>
#include <QDesktopWidget>
#include <QRect>
#include <QTextDocument>
externC"
#define RING_DLL __declspec(dllexport)
RING_DLL void ringlib_init(RingState *pRingState)
{
newQApplication(pRingState->argc,pRingState->argv);
ring_qt_start(pRingState) ;
}
}
</code>
<runcode>
aStringTypesQString"
aBeforeReturn"QString",".toStdString().c_str()"]
aNewMethodName"QWebView","load","loadpage"]
aNewMethodName"QMediaPlaylist","load","loadfile"]
aNewMethodName"QMediaPlaylist","next","movenext"]
aNewMethodName"QPainter","end","endpaint"]
aNewMethodName"QPicture","load","loadfile"]
aNewMethodName"QLineEdit","end","endtext"]
aNewMethodName"QDialog","done","donedialog"]
aNewMethodName"QTextDocument","end","enddoc"]
aNewMethodName"QTextBlock","next","nextblock"]
</runcode>
<class>
name: qApp
nonew
</class>
<register>
void exec(void)
(continues on next page)
92.19. Conguration le for the Qt Framework 1454

Ring Documentation, Release 1.14
(continued from previous page)
void quit(void)
void processEvents(void)
</register>
<code>
RING_FUNC(ring_qApp_quit)
{
qApp->quit();
}
RING_FUNC(ring_qApp_exec)
{
qApp->exec();
}
RING_FUNC(ring_qApp_processEvents)
{
qApp->processEvents();
}
</code>
<class>
name: QObject
para: void
</class>
bool blockSignals(bool block)
QObjectList children(void)
void dumpObjectInfo(void)
void dumpObjectTree(void)
bool inherits(const char *className)
void installEventFilter(QObject *filterObj)
bool isWidgetType(void)
void killTimer(int id)
void moveToThread(QThread *targetThread)
QString objectName(void)
QObject*parent(void)
QVariant property(const char *name)
void removeEventFilter(QObject *obj)
void setObjectName(QString)
void setParent(QObject *parent)
bool setProperty(const char *name, QVariant)
bool signalsBlocked(void)
int startTimer(int interval)
QThread*thread(void)
void deleteLater(void)
<class>
name: QWidget
para: void
parent: QObject
</class>
bool acceptDrops(void)
QString accessibleDescription(void)
(continues on next page)
92.19. Conguration le for the Qt Framework 1455

Ring Documentation, Release 1.14
(continued from previous page)
QString accessibleName(void)
void activateWindow(void)
void addAction(QAction *action)
void adjustSize(void)
bool autoFillBackground(void)
int backgroundRole(void)
QSize baseSize(void)
QWidget*childAt(int x, int y)
QRect childrenRect(void)
QRegion childrenRegion(void)
void clearFocus(void)
void clearMask(void)
QMargins contentsMargins(void)
QRect contentsRect(void)
int contextMenuPolicy(void)
QCursor cursor(void)
int effectiveWinId(void)
void ensurePolished(void)
int focusPolicy(void)
QWidget*focusProxy(void)
QWidget*focusWidget(void)
QFont font(void)
QFontInfo fontInfo(void)
QFontMetrics fontMetrics(void)
int foregroundRole(void)
QRect frameGeometry(void)
QSize frameSize(void)
QRect geometry(void)
void getContentsMargins(int *left, int*top, int*right, int*bottom)
void grabGesture(int gesture, int flags)
void grabKeyboard(void)
void grabMouse(void)
int grabShortcut(QKeySequence , int context)
QGraphicsEffect *graphicsEffect(void)
QGraphicsProxyWidget *graphicsProxyWidget(void)
bool hasFocus(void)
bool hasMouseTracking(void)
int height(void)
int heightForWidth(int w)
int inputMethodHints(void)
QVariant inputMethodQuery(int query)
void insertAction(QAction *before, QAction *action)
bool isActiveWindow(void)
bool isAncestorOf(QWidget *child)
bool isEnabled(void)
bool isEnabledTo(QWidget *ancestor)
bool isFullScreen(void)
bool isHidden(void)
bool isMaximized(void)
bool isMinimized(void)
bool isModal(void)
bool isVisible(void)
bool isVisibleTo(QWidget *ancestor)
bool isWindow(void)
bool isWindowModified(void)
QLayout*layout(void)
int layoutDirection(void)
(continues on next page)
92.19. Conguration le for the Qt Framework 1456

Ring Documentation, Release 1.14
(continued from previous page)
QLocale locale(void)
QPoint mapFrom(QWidget *parent, QPoint)
QPoint mapFromGlobal(QPoint)
QPoint mapFromParent(QPoint)
QPoint mapTo(QWidget *parent, QPoint)
QPoint mapToGlobal(QPoint pos)
QPoint mapToParent(QPoint pos)
QRegion mask(void)
int maximumHeight(void)
QSize maximumSize(void)
int maximumWidth(void)
int minimumHeight(void)
QSize minimumSize(void)
int minimumWidth(void)
void move(int x, int y)
QWidget*nativeParentWidget(void)
QWidget*nextInFocusChain(void)
QRect normalGeometry(void)
void overrideWindowFlags(int flags)
QPalette palette(void)
QWidget*parentWidget(void)
QPoint pos(void)
QWidget*previousInFocusChain(void)
QRect rect(void)
void releaseKeyboard(void)
void releaseMouse(void)
void releaseShortcut(int id)
void removeAction(QAction *action)
void render(QPaintDevice *target, QPoint,QRegion, int)
void repaint(int x, int y, int w, int h)
void resize(int w, int h)
bool restoreGeometry(QByteArray)
QByteArray saveGeometry(void)
void scroll(int dx, int dy)
void setAcceptDrops(bool on)
void setAccessibleDescription(QString)
void setAccessibleName(QString)
void setAttribute(int attribute, bool on)
void setAutoFillBackground(bool enabled)
void setBackgroundRole(int role)
void setBaseSize(int basew, int baseh)
void setContentsMargins(int left, int top, int right, int bottom)
void setContextMenuPolicy(int policy)
void setCursor(QCursor)
void setFixedHeight(int h)
void setFixedSize(int w, int h)
void setFixedWidth(int w)
void setFocus(int reason)
void setFocusPolicy(int policy)
void setFocusProxy(QWidget *w)
void setFont(QFont)
void setForegroundRole(int role)
void setGeometry(int x, int y, int w, int h)
void setGraphicsEffect(QGraphicsEffect *effect)
void setInputMethodHints(int hints)
void setLayout(QLayout *layout)
void setLayoutDirection(int direction)
(continues on next page)
92.19. Conguration le for the Qt Framework 1457

Ring Documentation, Release 1.14
(continued from previous page)
void setLocale(QLocale)
void setMask(QBitmap)
void setMaximumHeight(int maxh)
void setMaximumSize(int maxw, int maxh)
void setMaximumWidth(int maxw)
void setMinimumHeight(int minh)
void setMinimumSize(int minw, int minh)
void setMinimumWidth(int minw)
void setMouseTracking(bool enable)
void setPalette(QPalette)
void setParent(QWidget *parent)
void setShortcutAutoRepeat(int id, bool enable)
void setShortcutEnabled(int id, bool enable)
void setSizeIncrement(int w, int h)
void setSizePolicy(int horizontal, int vertical)
void setStatusTip(QString)
void setStyle(QStyle *style)
void setToolTip(QString)
void setUpdatesEnabled(bool enable)
void setWhatsThis(QString)
void setWindowFilePath(QString)
void setWindowFlags(int type)
void setWindowIcon(QIcon)
void setWindowIconText(QString)
void setWindowModality(int windowModality)
void setWindowOpacity(double level)
void setWindowRole(QString)
void setWindowState(int windowState)
QSize size(void)
QSize sizeIncrement(void)
QSizePolicy sizePolicy(void)
void stackUnder(QWidget *w)
QString statusTip(void)
QStyle*style(void)
QString styleSheet(void)
bool testAttribute(int attribute)
QString toolTip(void)
bool underMouse(void)
void ungrabGesture(int gesture)
void unsetCursor(void)
void unsetLayoutDirection(void)
void unsetLocale(void)
void update(int x, int y, int w, int h)
void updateGeometry(void)
bool updatesEnabled(void)
QRegion visibleRegion(void)
QString whatsThis(void)
int width(void)
int winId(void)
QWidget*window(void)
QString windowFilePath(void)
int windowFlags(void)
QIcon windowIcon(void)
QString windowIconText(void)
int windowModality(void)
double windowOpacity(void)
QString windowRole(void)
(continues on next page)
92.19. Conguration le for the Qt Framework 1458

Ring Documentation, Release 1.14
(continued from previous page)
int windowState(void)
QString windowTitle(void)
int windowType(void)
int x(void)
int y(void)
bool close(void)
void hide(void)
void lower(void)
void raise(void)
void setDisabled(bool disable)
void setEnabled(bool)
void setHidden(bool hidden)
void setStyleSheet(QString)
void setWindowModified(bool)
void setWindowTitle(QString)
void show(void)
void showFullScreen(void)
void showMaximized(void)
void showMinimized(void)
void showNormal(void)
QWidget*find(int id)
QWidget*keyboardGrabber(void)
QWidget*mouseGrabber(void)
void setTabOrder(QWidget *first, QWidget *second)
<class>
name: QLabel
para: QWidget*
parent: QWidget
</class>
int alignment(void)
QWidget*buddy(void)
bool hasScaledContents(void)
bool hasSelectedText(void)
int indent(void)
int margin(void)
QMovie*movie(void)
bool openExternalLinks(void)
QPicture*picture(void)
QPixmap*pixmap(void)
QString selectedText(void)
int selectionStart(void)
void setAlignment(int)
void setBuddy(QWidget *buddy)
void setIndent(int)
void setMargin(int)
void setOpenExternalLinks(bool open)
void setScaledContents(bool)
void setSelection(int start, int length)
void setTextFormat(int)
void setTextInteractionFlags(int flags)
void setWordWrap(bool on)
QString text(void)
int textFormat(void)
int textInteractionFlags(void)
bool wordWrap(void)
(continues on next page)
92.19. Conguration le for the Qt Framework 1459

Ring Documentation, Release 1.14
(continued from previous page)
void clear(void)
void setMovie(QMovie *movie)
void setNum(double num)
void setPicture(QPicture)
void setPixmap(QPixmap)
void setText(QString)
<class>
name: QPushButton
para: QWidget*
parent: QWidget
codename: GPushButton
passvmpointer
</class>
void setText(const char *)
void setClickEvent(const char *)
void setIcon(QIcon)
void setIconSize(QSize)
<class>
name: QLineEdit
para: QWidget*
parent: QWidget
codename: GLineEdit
passvmpointer
</class>
int alignment(void)
void backspace(void)
QCompleter*completer(void)
QMenu*createStandardContextMenu(void)
void cursorBackward(bool mark, int steps)
void cursorForward(bool mark, int steps)
int cursorMoveStyle(void)
int cursorPosition(void)
int cursorPositionAt(QPoint)
void cursorWordBackward(bool mark)
void cursorWordForward(bool mark)
void del(void)
void deselect(void)
QString displayText(void)
bool dragEnabled(void)
int echoMode(void)
voidend(bool mark)
void getTextMargins(int *left, int*top, int*right, int*bottom)
bool hasAcceptableInput(void)
bool hasFrame(void)
bool hasSelectedText(void)
void home(bool mark)
QString inputMask(void)
void insert(QString)
bool isModified(void)
bool isReadOnly(void)
bool isRedoAvailable(void)
bool isUndoAvailable(void)
int maxLength(void)
(continues on next page)
92.19. Conguration le for the Qt Framework 1460

Ring Documentation, Release 1.14
(continued from previous page)
QString placeholderText(void)
QString selectedText(void)
int selectionStart(void)
void setAlignment(int flag)
void setCompleter(QCompleter *c)
void setCursorMoveStyle(int style)
void setCursorPosition(int)
void setDragEnabled(bool b)
void setEchoMode(int)
void setFrame(bool)
void setInputMask(QString)
void setMaxLength(int)
void setModified(bool)
void setPlaceholderText(QString)
void setReadOnly(bool)
void setSelection(int start, int length)
void setTextMargins(int left, int top, int right, int bottom)
void setValidator(QValidator *v)
QString text(void)
QMargins textMargins(void)
QValidator*validator(void)
void clear(void)
void copy(void)
void cut(void)
void paste(void)
void redo(void)
void selectAll(void)
void setText(QString)
void undo(void)
void setTextChangedEvent(const char *)
void setcursorPositionChangedEvent(const char *)
void seteditingFinishedEvent(const char *)
void setreturnPressedEvent(const char *)
void setselectionChangedEvent(const char *)
void settextEditedEvent(const char *)
Note:Most of the content of the previous conguration le is removed from this documentation, for a complete
version see the Ring source code distribution.
92.20
Starting from Ring 1.8 the code generator support the staticmethods option.
So the code generator can know that the class doesn't need an object to call the methods.
Example:
<class>
name: QStandardPaths
para: void
nonew
(continues on next page)
92.20. Static Methods 1461

Ring Documentation, Release 1.14
(continued from previous page)
staticmethods
</class>
QString displayName(QStandardPaths::StandardLocation type)
QString findExecutable(QString executableName, QStringList paths))
92.21
Starting from Ring 1.9 the code generator support the <loadle> command.
<loadfile>
This is useful to separate the extension conguraition le to many les
Example:
The le : qt_module_network.cf in the RingQt Extension
<comment>
Module (network)
</comment>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
92.22
Starting from Ring 1.9 the code generator support the <managed> option when dening classes.
Using this option, the generator will use RING_API_RETMANAGEDCPOINTER() to return the C pointer.
So the Garabage Collector will manage these C pointers.
Example
<class>
name: QFont
para: QString, int, int, bool
managed
</class>
92.21. Loading Files 1462

Ring Documentation, Release 1.14
92.23
You can learn from the next examples
•
•
•
After moding the conguration le, You will need to generate the code, You can learn from the next examples
•
•
•
After generating the code, You will need to build the library, You can learn from the next examples
•
•
•
92.23. Conguration Files Examples 1463

CHAPTER
NINETYTHREE
CREATE YOUR FIRST EXTENSION
In this chapter we will create RingBeep
RingBeep is a simple extension for the beep() function in Windows API
Just a simple example about creating extensions
93.1
You will nd this extension in the ring/extensions/ringbeep folder
93.2
At rst we write the conguration le in : ringbeep.cf
notepad ringbeep.cf
The le ringbeep.cf contains
<code>
#include "windows.h"
</code>
int Beep(int dwFreq,int dwDuration)
Then we run : gencode.bat to generate ringbeep.c
gencode.bat
The gencode.bat contains the next command to call Ring Extensions Generator
ring ..\codegen\parsec.ring ringbeep.cf ringbeep.c
Then we build the extension using :
buildvc.bat
The le buildvc.bat contains the next commands to build the extension using Visual C/C++
1464

Ring Documentation, Release 1.14
cls
call ../../src/locatevc.bat
cl /c /DEBUG ringbeep.c -I"..\..\include"
link /DEBUG ringbeep.obj ..\..\libing.lib kernel32.lib /DLL /OUT:ringbeep.dll ^
/SUBSYSTEM:CONSOLE,"5.01"
del ringbeep.obj
93.3
Then we test the function using
ring test.ring
The le test.ring contains
loadlib("ringbeep.dll")
forf to1000step50
beep(f,300)
next
93.3. Testing the extension 1465

CHAPTER
NINETYFOUR
LANGUAGE DESIGN
In this chapter we will learn about the basic concepts behind the language design.
94.1
The language is simple, trying to be natural, encourage organization and comes with transparent and visual implemen-
tation. It comes with compact syntax and a group of features that enable the programmer to create natural interfaces
and declarative domain-specic languages in a fraction of time. It is very small, fast and comes with smart garbage
collector that puts the memory under the programmer control. It supports many programming paradigms, comes with
useful and practical libraries. The language is designed for productivity and developing high quality solutions that can
scale.
94.2
•
•
•
•
•
•
software.
94.3
Ring is a very simple language, and has a very straightforward syntax. It encourages programmers to program without
boilerplate code
See"Hello, World!"
The Main function is optional and will be executed after the statements, and is useful for using the local scope.
FuncMain
See"Hello, World!"
1466

Ring Documentation, Release 1.14
Uses Dynamic Typing and Lexical scoping. No $ is required before the variable name! You can use the `+' operator
for string concatenation and the language is weakly typed and will convert automatically between numbers and strings
based on the context.
nCount # Global variable
FuncMain
nID # Local variable
See"Count =
94.4
Ring is not case-sensitive
See"Enter your name ?
Givename
See"Hello # Name is the same as name
The list index starts from 1
aList"one","two","three"]
SeeaList[1] # print one
Call functions before denition
one()
two()
three()
Funcone
See"One"
Functwo
See"two"
Functhree
See"three"
The assignment operator uses Deep copy (no references in this operation)
aList"one","two","three"]
aList2
aList[1]
seealist[1] # print 1
seeaList2[1] # print one
Pass numbers and strings by value, but pass lists and objects by reference. The for in loop can update the list items.
FuncMain
aList1,2,3]
update(aList)
seeaList # print one two three
Funcupdate aList
forxinaList
switchx
on1one"
on2two"
on3three"
(continues on next page)
94.4. Trying to be natural 1467

Ring Documentation, Release 1.14
(continued from previous page)
off
next
Using Lists during denition
aList1,2,3,4,5][1][1]
seeaList # print 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Exit from more than one loop
forx to10
fory to10
see"x=""
ifx andy
exit2 # exit from 2 loops
ok
next
next
94.5
The language encourage organization, Forget bad days using languages where the programmer start with function then
class then function and a strange mix between things!
Each source le follow the next structure
•
•
•
•
This enable us to use Packages, Classes and Functions without the need to use a keyword to end these components.
We can write one line comments and multi-line comments The comment starts with # or // Multi-line comments are
written between /* and*/
/*
Program Name : My first program using Ring
Date :.05.08
*/
See"What is your name? # print message on screen
givecName # get input from the user
see"Hello # say hello!
//See"Bye!"
94.5. Encourage Organization 1468

Ring Documentation, Release 1.14
94.6
Ring contains only 4 types that represent the program data
These types are (String, Number, List & Object)
The idea is to have many use cases for each type which increase the exibility and the ability to write functions that
are more usable in different situtations.
The String type is used to represent: * One character * A string of many characters * Multi-line string * Binary Data
cStr1a" # One character
cStr2Hello, World!" # A string of many characters
cStr3Hello
Welcometothe Ring language!
"
cStr4 # Read executable file (Binary Data)
The Number type is used to represent * Boolean Values * Signed/Unsigned Integers * Float/Double
nNum1 True # Boolean Value (1)
nNum2 False # Boolean Value (0)
nNum3 # Integer
nNum410 # Signed Integer
nNum5.11 # Float/Double
The List type is used instead of * One Dimension Arrays * Multi-Dimension Arrays * Lists of multiple types * Nested
Lists * Hash Tables (Key & Value) * Tree * Wrapper around a C Pointer
aList1"one","two","three"] # Strings
aList21,2,3,4,5,6,7,8,9,10] # Numbers
aList3"Ring",1234] # Multiple types
aList4["Fayed","Egypt"],["Mansour","Tunisia"]] # Nested Lists
aList5Fayed", :countryEgypt"] # Hash Tables
The Object type is used to represent objects created from classes
Using classes and operator overloading we can create custom types
94.7
The language is not line sensitive, you don't need to write ; after statements, also you don't need to press ENTER or
TAB, so we can write the next code
See"The First Message" See"
See"Enter your name?" GiveNameSee"Hello
The next code create a class called Point contains three attributes X,Y and Z. No keywords is used to end the pack-
age/class/function denition. Also, we can write the attributes names directly below the class name.
ClassPoint X Y Z
We can use classes and functions before their denition, In this example we will create new object, set the object
attributes then print the object values.
94.6. Data Representation 1469

Ring Documentation, Release 1.14
o1 Newpoint o1.x=10=20=30 SeeO1ClassPoint X Y Z
Instead of using the dot `.' operator to access the object attributes and methods we can use braces { } to access the
object, then we can use the object attributes and methods.
o1 Newpoint { x=10=20=30 SeeO1ClassPoint X Y Z
Now we will call a method after accessing the object using { }
oPerson newPerson
{
NameSomebody"
AddressSomewhere"
Phone0000000"
Print() # here we call the Print() method
}
ClassPerson Name Address Phone
FuncPrint
See"Name :"
"Address :"
"Phone :
When we use { } to access the object then write any attribute name, the language will check the class for any set-
ter/getter methods that will be called automatically.
NewNumber {
Seeone # Execute GetOne()
Seetwo # Execute GetTwo()
Seethree # Execute GetThree()
}
ClassNumber one two three
FuncGetOne
See"Number : One"
return1
FuncGetTwo
See"Number : Two"
return2
FuncGetThree
See"Number : Three"
return3
94.8
After the object access using { } if the class contains a method called BraceEnd() it will be executed!
TimeForFun newjourney
# The first surprise!
TimeForFun {
Hello it is me # What a beatiful programming world!
}
# Our Class
Classjourney
hello=0=0=0=0
funcGetHello
(continues on next page)
94.8. Dene Natural Statements 1470

Ring Documentation, Release 1.14
(continued from previous page)
See"Hello"
funcbraceEnd
See"Goodbye!"
We can execute code written in strings using the Eval() function
cCodeSeeCode that will be executed later!
Eval(cCode) # execute the code to print the message
We can create a list then execute code generated from that list
aWords"hello","it","is","me"]
forwordinaWords cCode=word+"=0" next
We can read text les using the Read(cFileName) function and we can write les using the Write(cFileName,cString)
function.
See"Enter File Name:" GivecFileNameSeeRead(cFileName) # Print the file content
The next example presents how to create a class that denes two instructions The rst instruction is : I want window
The second instruction is : Window title = Expression Also keywords that can be ignored like the `the' keyword
NewApp
{
I want window
The window titlehello world"
}
ClassApp
# Attributes for the instruction I want window
i want window
nIwantwindow
# Attributes for the instruction Window title
# Here we dont define the window attribute again
title
nWindowTitle
# Keywords to ignore, just give them any value
the=0
funcgeti
ifnIwantwindow
nIwantwindow++
ok
funcgetwant
ifnIwantwindow
nIwantwindow++
ok
funcgetwindow
ifnIwantwindow
nIwantwindow=
see"Instruction : I want window"
ok
ifnWindowTitle
(continues on next page)
94.8. Dene Natural Statements 1471

Ring Documentation, Release 1.14
(continued from previous page)
nWindowTitle++
ok
funcsettitle cValue
ifnWindowTitle
nWindowTitle=0
see"Instruction : Window Title =
ok
To complete the previous example, use read() to get the content of a le that contains
I want window
The window titlehello world"
Then use eval() to execute the content of that le!. Also, you can update the methods GetWindow() and SetTitle() to
create Real windows using the GUI Library
94.9
We learned how to use Natural statements to execute our code and using the same features we can use nested structures
to execute our code.
The next example from the Web library, generate HTML document using the Bootstrap library. No HTML code is
written directly in this example, we created a similar language (just as example) Then using this declarative language
that uses nested structures, we generated the HTML Document.. The idea in this example is that the GetDiv() and
GetH1() methods return an object that we can access using {} and after each object access the method BraceEnd() will
be executed to send the generated HTML to the parent object until we reach to the root where BraceEnd() will print
the output.
Load"weblib.ring"
ImportSystem.Web
FuncMain
BootStrapWebPage()
{
div
{
classname
div
{
classname
H1 { text("Bootstrap Page") }
}
div
{
classname
forx to3
div
{
classnamecol-sm-4"
H3 { html("Welcome to the Ring programming language") }
P { html("Using a scripting language is very fun!") }
}
(continues on next page)
94.9. Dene Declarative Languages 1472

Ring Documentation, Release 1.14
(continued from previous page)
next
}
}
}
The classes that power the declarative interface looks like this
ClassLinkfromObjsBase
title link
Funcbraceend
cOutput+GetTabs()<a href="
Link>+
ClassDivfromObjsBase
Funcbraceend
cOutput=+<div
addattributes()
AddStyle()
getobjsdata()
cOutput=+"</div>"
cOutput
94.10
Ring comes with transparent implementation. We can know what is happening in each compiler stage and what is
going on during the run-time by the Virtual Machine Example : ring helloworld.ring -tokens -rules -ic
See"Hello, World!"
Output
==================================================================
Tokens
==================================================================
Keyword :SEE
Literal : Hello, World!
EndLine
==================================================================
==================================================================
Grammar Rules Used by The Parser
==================================================================
Rule : Program->
Line
Rule : Factor->
Rule : Range->
Rule : Term->
Rule : Arithmetic->
Rule : BitShift->
Rule : BitAnd->
(continues on next page)
94.10. Transparent Implementation 1473

Ring Documentation, Release 1.14
(continued from previous page)
Rule : BitOrXOR->
Rule : Compare->
Rule : EqualOrNot->
Rule : LogicNot>
Rule : Expr->
Rule : Statement->See
==================================================================
==================================================================
Byte Code
==================================================================
PC OPCode Data
1
2!
3
4
==================================================================
Hello, World!
94.11
The Ring programming language is designed using the PWCT visual programming tool and you will nd the visual
source of the language in the folder “language/visualsrc” -*.ssf les and the generated source code (In the C Language)
in the language/src folder and the language/include folder.
The next screen shot from the ring_vm.ssf le (Generate ring_vm.c and ring_vm.h)
94.11. Visual Implementation 1474

Ring Documentation, Release 1.14
The next screen shot from the ring_list.ssf le (Generate ring_list.c and ring_list.h)
94.11. Visual Implementation 1475

Ring Documentation, Release 1.14
94.12
Avoid memory problems :-
•
•
•
•
Rules :-
•
•
•
ment.
Example:
aList1,2,3,4,5]
aListnice"
After the second line directly, The list [1,2,3,4,5] will be deleted from the memory and we will have a string “nice”
•
•
based on reference counting, if no references everything will be deleted, but if we have a reference, the data will
stay in memory.
94.13
When we use threads in Ring applications, We don't have global interpreter (VM) lock (No GIL)
So threads can work in parallel and execute Ring instructions at the same time
This is better for threads and concurrency (More Faster!)
94.14
Ring is designed to be a simple, small and exible language in the rst place, but also it is fast enough for many
applications.
Ring can do each of the next tasks in around 1 second using normal computers in the market during the last 5 years
(1)
(2)
(3)
(The worst case)
(4)
(5)
94.12. Smart Garbage Collector 1476

Ring Documentation, Release 1.14
(6)
(7)
Also when we need more speed we can use C/C++ extensions!
94.14. Fast Enough For Many Applications 1477

CHAPTER
NINETYFIVE
WHAT IS NEW IN RING 1.1?
In this chapter we will learn about the changes and new features in Ring 1.1 release.
95.1
Ring 1.1 comes with many new features
•
• *.ringo)
•
•
•
•
•
•
•
•
•
•
95.2
Ring is an innovative language because of it's compact syntax, smart implementation (small, transparent & visual) and
it's ability to create declarative and natural domain specic languages in a fraction of time.
This release add support for calling methods when an expression is evaluated
check this example:
# Natural Code
newprogram {
Accept
}
# Natural Code Implementation
(continues on next page)
1478

Ring Documentation, Release 1.14
(continued from previous page)
classprogram
# Keywords
Accept=0=0=0=0=0=0
# Execution
funcbraceexpreval x
value
funcgetnumbers
forx=1tovalue
see"Enter Number ("+x+") :" givenNumber
aNumbers
next
funcgetsum
nSUm
forxinaNumbers nSum+= next
see"The Sum :
private
value=0=[]
Output:
Enter Number (1) :3
Enter Number (2) :4
The Sum :
for more information see the “Natural Language Programming” chapter.
95.3*.ringo)
This feature enable you to distribute your applications without distributing the source code. Also it makes application
distribution a simple process where you get one Ring object le for the complete project (many source code les).
Also using Ring object le remove the loading time required for compiling the application.
Check the “command line options” chapter to know more about this feature.
95.4
tures
Programmers are sensitive to the programming language syntax. Great programmers know how to work using many
different styles but each programmer may have his/her favorite style.
Each programming language comes with a style that you may like or not. Ring is just one of these languages, but as a
response to many programmers asking for a better syntax we decided to provide more options.
Also some of these features are very necessary for Natural Language Programming.
Example :
We have two commands to change language keywords and operators.
ChangeRingOperator +
ChangeRingKeyword print
(continues on next page)
95.3. Generate/Execute Ring Object Files (*.ringo) 1479

Ring Documentation, Release 1.14
(continued from previous page)
Print
ChangeRingOperator plus
ChangeRingKeyword printsee
We have new styles (Optional) for Input/Output.
Example :
Put"What is your name?
GetcName
Put"Hello
Example :
Load"stdlib.ring"
Print("What is your name?) # print message on screen
cName=GetString() # get input from the user
print("Hello #{cName}") # say hello!
We have new styles (optional) for control structures.
Example :
While
Put"
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
"
SwitchnOption
Case1
Put"Enter your name :
Getname
Put"Hello
Case2
Put"Sample : using while loop"
Case3
Bye
Else
Put"bad option..."
End
End
Example :
Load"stdlib.ring"
While {
print("
(continues on next page)
95.4. Syntax Flexibility and different styles for I/O and Control Structures 1480

Ring Documentation, Release 1.14
(continued from previous page)
Main Menu
---------
(1) Say Hello
(2) About
(3)Exit
")
nOption
switchnOption {
case1
print("Enter your name :)
name
print("Hello #{name} ")
case2
print("Sample : using switch statement ")
case3
Bye
else
print("bad option... ")
}
}
Check the next chapters:-
•
•
•
•
•
Note:All of these styles are provided automatically by the compiler at the same time, It's better to select one style for
the same project (you can create your style as a mix from these styles) for example you can use Put/Get and Braces.
95.5
Changed:
•
•
•
Added:
•
•
•
95.5. New Functions and Changes 1481

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
Check the next chapters
•
•
•
95.6
Ring 1.1 comes with a library called StdLib, it's written in Ring by the help of Ring Team
The library provide a useful group of new functions and classes
Example:
Load"stdlib.ring"
Puts("Test Times()")
Times ( func{see"Hello, World!"
Example:
Load"stdlib.ring"
Puts("Test Map()")
SeeMap(:10, funcx {returnx*x } )
Example:
Load"stdlib.ring"
Puts("Test Filter()")
SeeFilter(:10 funcx {ifx= return } )
Example:
Load"stdlib.ring"
See"Testing the String Class"
oString new ("Hello, World!")
oString.println()
oString.upper().println()
oString.lower().println()
oString.left(5).println()
oString.right(6).println()
95.6. StdLib functions and classes written in Ring 1482

Ring Documentation, Release 1.14
Example:
Load"stdlib.ring"
oList new (1,2,3]
oList.Add(4)
oList.print()
Example:
Load"stdlib.ring"
oStack new
oStack.push(1)
oStack.push(2)
oStack.push(3)
seeoStack.pop()
Example:
Load"stdlib.ring"
oQueue new
oQueue.add(1)
oQueue.add(2)
oQueue.add(3)
seeoQueue.remove()
Example:
Load"stdlib.ring"
ohashtable new
See"Test the hashtable Class Methods"
ohashtable {
Add("Egypt","Cairo")
Add("KSA","Riyadh")
seeself["Egypt"]
seeself["KSA"]
seecontains("Egypt")
seecontains("USA")
seeindex("KSA")
print()
delete(index("KSA"))
seecopy(" *",60)
print()
}
Example:
Load"stdlib.ring"
otree new
See"Test the tree Class Methods"
otree {
set("The first step") # set the root node value
seevalue()
Add("one")
(continues on next page)
95.6. StdLib functions and classes written in Ring 1483

Ring Documentation, Release 1.14
(continued from previous page)
Add("two")
Add("three") {
Add("3.1")
Add("3.2")
Add("3.3")
seechildren
}
seechildren
oTree.children[2]
Add("2.1") Add("2.2") Add("2.3") {
Add("2.3.1") Add("2.3.2") Add("test")
}
}
oTree.children[2].children[3].children[3].set("2.3.3")
}
seecopy(" *",60)
oTree.print()
Check the next chapters:
•
•
95.7
Ring 1.0 provided RingAllegro to be able to create games using the Allegro game programming library
Now Ring 1.1 provide RingLibSDL also so we can have the choice between Allegro or LibSDL
Example:
Load"libsdl.ring"
SDL_Init(SDL_INIT_EVERYTHING)
win"Hello World!",,,,, SDL_WINDOW_SHOWN)
SDL_Delay(2000)
SDL_DestroyWindow(win)
SDL_Quit()
See the RingLibSDL Chapter.
95.8
In practice we would create a game engine in a language like C/C++ to get the best performance then provide Ring
classes to use the engine.
But many 2D Games are simple and creating a game engine in Ring will be fast enough in many cases
Also this would be a good demo project to learn about the language concepts where we build things using Object Ori-
ented Programming (OOP) then access the power that we have using declarative programming using nested structures
or using natural programming.
In this project we selected the rst way (declarative programming using nested structures)
Example:
95.7. RingLibSDL 1484

Ring Documentation, Release 1.14
Load"gameengine.ring" # Give Control to the Game Engine
funcmain # Called by the Game Engine
oGame NewGame # Create the Game Object
{
titleMy First Game"
text {
x=50
animate false
size
filefonts/pirulen.ttf"
textgame development using ring is very fun!"
color0,0,0) # Color = black
}
text {
x=150
# Animation Part ======================================
animate true # Use Animation
direction # Increase y
point # Continue until y=400
nStep # Each time y+= 3
#======================================================
size
filefonts/pirulen.ttf"
textwelcome to the real world!"
color0,0,255) # Color = Blue
}
Sound { # Play Sound
filesound/music1.wav" # Sound File Name
}
} # Start the Events Loop
See the “Demo Project - Game Engine for 2D Games” chapter.
95.9
Ring 1.0 provided support for ODBC to use any database and provided native support for MySQL.
Now Ring 1.1 provide native support for SQLite database too.
Example:
oSQLite
sqlite_open(oSQLite,"mytest.db")
sqlCREATE TABLE COMPANY("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"AGE INT NOT NULL,"
"ADDRESS CHAR(50),"
"SALARY REAL );"
sqlite_execute(oSQLite,sql)
(continues on next page)
95.9. RingSQLite 1485

Ring Documentation, Release 1.14
(continued from previous page)
sqlINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
"VALUES (1,Mahmoud, 29,Jeddah, 20000.00 );
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
"VALUES (2,Ahmed, 27,Jeddah, 15000.00 );
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (3,Mohammed, 31,Egypt, 20000.00 );"
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (4,Ibrahim, 24,Egypt, 65000.00 );"
sqlite_execute(oSQLite,sql)
aResult"select *from COMPANY")
forxinaResult
fortinx
seet[2]
next
next
seecopy(" *",50)
forxinaResult
seex["name"]
next
sqlite_close(oSQLite)
95.10
We are using the code generator (written in Ring) every day to add new libraries to Ring.
The generator is used to create RingQt and RingAllegro
Also in Ring 1.1 it's used to create RingLibSDL.
more features are added like
•
•
•
See the Code Generator chapter.
95.11
tributes
We can use Self.Attribute in the Class Region (after the class name and before any methods) to dene new attributes.
classPerson
name # Define name as attribute if its not a global variable
address
phone
classperson2
self.name # Must Define the attribute
(continues on next page)
95.10. Better Code Generator for Extensions 1486

Ring Documentation, Release 1.14
(continued from previous page)
self.address
self.phone
95.12
We can use nested braces {} while we are inside methods to access another objects, In this case the current object
scope will be changed while we are inside the brace and Self will point to the object that we access using braces {}. In
this case we can use This.Attribute and This.Method() to access the object that will be created from the current class.
Check the Object Oriented Programming chapter for more information.
Also Check the Weight History Application in GUI Development using RingQt chapter.
95.13
Ring 1.1 documentation (800 pages) is better than Ring 1.0 documentation (340 pages)
Many chapters are added for providing better information about the language like:
•
•
•
And more!
95.12. Using This.Attribute in nested Braces inside the Class Methods 1487

CHAPTER
NINETYSIX
WHAT IS NEW IN RING 1.2?
In this chapter we will learn about the changes and new features in Ring 1.2 release.
96.1
Ring 1.2 comes with many new features
•
•
•
•
•
•
•
•
•
•
96.2
•
•
•
•
•
•
•
•
•
Example:
1488

Ring Documentation, Release 1.14
fp"ptrcmp.ring","r")
fp2
fp3"ptrcmp.ring","r")
seeptrcmp(fp,fp2)
seeptrcmp(fp,fp3)
fclose(fp)
fclose(fp3)
Output:
1
0
Also we can compare between them using the `=' operator
Example:
fp"ptrcmp2.ring","r")
fp2"ptrcmp2.ring","r")
fp3
seefp
seenl
seefp
fclose(fp)
fclose(fp2)
Output:
0
1
Example:
The next function in stdlib.ring uses the PrevFileName() to know if the le of the caller function is the main source
le of the program or not.
FuncIsMainSourceFile
ifPrevFileName()[2]
return
ok
return
96.3
The nd() function is updated to support searching in lists using C pointers like GUI Objects.
The type() function is updated to display the C pointers types (like the GUI Object Class Name).
96.3. Better Functions 1489

Ring Documentation, Release 1.14
96.4
The Ring Notepad will save the current line number of opened les to be restored when we switch between les.
Also Ring Notepad will ask the user to save the le if the le content is changed when the user switch between les.
96.5
RingQt classes are updated to include methods to get events (The code that will be executed when an event is red).
This is necessary to enable/disable events for some time or to get the events information.
For example the next code disable an event then call a method then enable the event again.
cEvent
oView.oListResult.setCurrentItemChangedEvent("")
FindValueAction() # Call Method while an event is disabled
oView.oListResult.setCurrentItemChangedEvent(cEvent)
Also the QAllEvents class is updated where we can set the output from the event function to be true or false using a
new method added to the class called setEventOutput.
Load"guilib.ring"
MyApp NewqApp {
win newqWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
lineedit1 newqlineedit(win) {
setGeometry(10,100,350,30)
setinputmask("9999;_")
oFilter newqallevents(lineedit1)
oFilter.setfocusoutEvent("pMove()")
installeventfilter(oFilter)
}
lineedit2 newqlineedit(win) {
setGeometry(10,150,350,30)
}
show()
}
exec()
}
funcpMove
win.setWindowTitle("xxxx")
oFilter.setEventOutput( False)
96.4. Better Ring Notepad 1490

Ring Documentation, Release 1.14
96.6
Ring 1.2 comes with the Objects library for RingQt applications. Instead of using global variables for windows
objects and connecting events to objects using the object name, the Objects Library will manage the GUI objects and
will provide a more natural API to quickly create one or many windows from the same class and the library provide
a way to quickly set methods to be executed when an event is red. Also the library provide a natural interface to
quickly use the parent or the caller windows from the child or sub windows.
The Objects Library is designed to be used with the MVC Design Pattern.
The Objects Library is merged in RingQt so you can use it directly when you use RingQt
Example :
load"guilib.ring"
newqApp {
open_window( :MainWindowController )
exec()
}
classMainWindowController fromWindowsControllerParent
oView newMainWindowView
funcSubWindowAction
Open_window( :SubWindowController )
Last_Window().SetParentObject(self)
classMainWindowViewfromWindowsViewParent
win newqWidget() {
SetWindowTitle("Main Window")
btnSub newqPushButton(win) {
setText("Sub Window")
setClickEvent( Method( :SubWindowAction ) )
}
resize(400,400)
}
classSubWindowController fromWindowsControllerParent
oView newSubWindowView
funcSetMainWindowTitleAction
Parent().oView.win.SetWindowTitle("Message from the Sub Window")
oView.win.SetWindowTitle("Click Event Done!")
classSubWindowViewfromWindowsViewParent
win newqWidget() {
SetWindowTitle("Sub Window")
btnMsg newqPushButton(win) {
setText("Set Main Window Title")
setClickEvent( Method( :SetMainWindowTitleAction ) )
}
btnClose newqPushButton(win) {
Move(200,0)
setText("Close")
setClickEvent( Method( :CloseAction ) )
}
resize(400,400)
}
96.6. Objects Library for RingQt 1491

Ring Documentation, Release 1.14
96.7
The LibCurl library is used starting from Ring 1.0 for the Download() and SendEmail() functions implementation. In
Ring 1.2 more functions are added to provide a powerful library (RingLibCurl) around LibCurl.
Example:
load"libcurl.ring"
curl
cPostThispage=4&Number1=4&Number2=5"
curl_easy_setopt(curl, CURLOPT_URL,http://localhost/ringapp/index.ring?page=3")
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, cPostThis)
curl_easy_perform(curl)
curl_easy_cleanup(curl)
96.8
The Call command is updated to support calling functions from object attributes also (not only variables).
For example the next code from the Stars Fighter Game
cFunc
callcFunc(oGame,oSelf,Key_Space)
Can be written in one line
calloself.keypress(oGame,oSelf,Key_Space)
96.9
We can pass NULL to functions instead of using NULLPointer()
For example the next code from RingLibSDL
SDL_RenderCopy(SDL_ren,tex,NULLPointer(),rect)
Can be written as in the next line
SDL_RenderCopy(SDL_ren,tex, NULL,rect)
96.7. RingLibCurl 1492

Ring Documentation, Release 1.14
96.10
In Ring 1.2 the Ring compiler is updated to include the Display Warnings option (-w)
Example:
load"stdlib.ring"
load"stdlib.ring"
compiling the program using the Display Warnings option will display the le duplication warning, While without that
option the error will pass silent.
This is a warning (not an error) because in large projects you may use the same le more than one time. For example
it's common to start each le with the next code. where the function IsMainSourceFile() is part from the stdlib.ring
load"stdlib.ring"
ifIsMainSourceFile()
//
ok
96.11
Ring 1.2 is more stable, We discovered and xed more bugs during Ring usage everyday in practical projects. Some
functions are optimized to be faster like the SubStr() function. Also the documentation is more better.
96.10. Display Warnings Option 1493

CHAPTER
NINETYSEVEN
WHAT IS NEW IN RING 1.3?
In this chapter we will learn about the changes and new features in Ring 1.3 release.
97.1
Ring 1.3 comes with many new features
•
•
•
•
•
•
•
•
•
•
•
97.2
(1) Another version of QPixMap class is added (QPixMap2) which takes (int width,int height) during object init.
Example:
Load"guilib.ring"
Newqapp
{
win1 newqwidget()
{
setwindowtitle("Drawing using QPixMap")
setgeometry(100,100,500,500)
label1 newqlabel(win1)
{
setgeometry(10,10,400,400)
(continues on next page)
1494

Ring Documentation, Release 1.14
(continued from previous page)
settext("")
}
imageStock newqlabel(win1)
{
image newqPixMap2(200,200)
color newqcolor() {
setrgb(255,255,255,255)
}
pen newqpen() {
setcolor(color)
setwidth(10)
}
newqpainter() {
begin(image)
setpen(pen)
drawline(0,0,200,200)
drawline(200,0,0,200)
endpaint()
}
setpixmap(image)
}
show()
}
exec()
}
Screen Shot:
97.2. Better RingQt 1495

Ring Documentation, Release 1.14
(2)
•
•
•
Also the class name (WindowViewBase) is changed to (WindowsViewParent).
In The next code for example the Open_WindowAndLink() will create an object from the SecondWindowController
Class Then will add the Method SecondWindow() to the FirstWindowController Class Also will add the Method
FirstWindow() to the SecondWindowController Class
So the SendMessage() method in FirstWindowController class can use the SecondWindow() method to access the
object.
classfirstwindowController fromwindowsControllerParent
oView newfirstwindowView
funcOpenSecondWindow
Open_WindowAndLink(:SecondWindowController,self)
(continues on next page)
97.2. Better RingQt 1496

Ring Documentation, Release 1.14
(continued from previous page)
funcSendMessage
ifIsSecondWindow()
SecondWindow().setMessage("Message from the first window")
ok
funcsetMessage cMessage
oView.Label1.setText(cMessage)
(3)
•
•
•
•
•
•
•
•
•
•
•
•
(4)
(5)
We added new classes to RingQt - another version of classes where the class names doesn't start with the “q” letter
Also updated methods so the index start from 1 when we deal with the GUI controls like
•
•
•
•
These classes are inside guilib.ring under the package name : System.GUI
To use it
load"guilib.ring"
importSystem.GUI
This doesn't have any effect on our previous code, It's just another choice for better code that is consistent with Ring
rules.
Also the form designer is updated to provide us the choice between using classes where (index start from 0) or (index
start from 1)
Example (Uses the Form Designer)
97.2. Better RingQt 1497

Ring Documentation, Release 1.14
(1)
(2)
97.3
(1)
(2)
Screen Shot:
(3)
97.3. Better Ring Notepad 1498

Ring Documentation, Release 1.14
(4)
97.3. Better Ring Notepad 1499

Ring Documentation, Release 1.14
(5)(6)
97.3. Better Ring Notepad 1500

Ring Documentation, Release 1.14
(7)
97.3. Better Ring Notepad 1501

Ring Documentation, Release 1.14
97.4
Ring 1.3 comes with Ring mode for Emacs Editor
Screen Shot:
97.5
The StdLib is updated to include the next functions
•
•
•
97.6
The Loop|Exit command is updated to accept Expressions after the command (not only numbers).
The syntax:
Loop|Exit[Number]
Changed to
Loop|Exit[Expression]
Example
97.4. Ring mode for Emacs Editor 1502

Ring Documentation, Release 1.14
XLoop # The outer loop
YLoop # The first inner loop
forx to10
fory to10
see"x=""
ifx andy
exitXLoop
ok
next
next
97.7
•
•
Example:
aList:one,:two,:four,:three]
seeaList
seecopy(" *",50)
swap(aList,3,4)
seeaList
Output
one
two
four
three
**************************************************
one
two
three
four
97.8
In this release, using Return Self in class methods will return the object by reference.
Example:
mylist newmytest() {
seeself
x
seeself
}]
seemylist
classmytest
x
(continues on next page)
97.7. New Functions 1503

Ring Documentation, Release 1.14
(continued from previous page)
funcinit
returnself # Return by reference
Output
x:.000000
x:.000000
x:.000000
97.9
In this release of the Ring language we can use the `<' and `:' operators as the `from' keyword
Syntax (1):
classCatfromAnimal
Syntax (2):
classCat
Syntax (3):
classCat : Animal
97.10
From Ring 1.0 we already have functions for embedding Ring in the C language. Also we can execute Ring code
inside Ring programs using the eval() function. In this release we provide functions for embedding Ring in Ring
programs without sharing the state.
Advantages:
(1)
(2)
Example:
pState
ring_state_runcode(pState,"SeeHello, World!+nl")
ring_state_runcode(pState,"x = 10")
pState2
ring_state_runcode(pState2,"SeeHello, World!+nl")
ring_state_runcode(pState2,"x = 20")
ring_state_runcode(pState,"see x +nl")
ring_state_runcode(pState2,"see x +nl")
v1"x")
v2"x")
(continues on next page)
97.9. Using `<' and `:' operators as `from' keyword 1504

Ring Documentation, Release 1.14
(continued from previous page)
seev1[3]
seeV2[3]
ring_state_delete(pState)
ring_state_delete(pState2)
Output:
Hello, World!
Hello, World!
10
20
10
20
97.11
Ring 1.3 comes with the RingZip library for creating, modifying and extracting*.zip les.
Example (1): Create myle.zip contains 4 les
load"ziplib.ring"
oZip"myfile.zip",w)
zip_addfile(oZip,"test.c")
zip_addfile(oZip,"zip.c")
zip_addfile(oZip,"zip.h")
zip_addfile(oZip,"miniz.h")
zip_close(oZip)
Example (2): Extract myle.zip to myfolder folder.
load"ziplib.ring"
zip_extract_allfiles("myfile.zip","myfolder")
Example (3): Print le names in the myle.zip
load"ziplib.ring"
oZip"myfile.zip",r)
forx=1tozip_filescount(oZip)
seezip_getfilenamebyindex(oZip,x)
next
zip_close(oZip)
Example (4) : Using Classes instead of Functions
load"ziplib.ring"
newZip {
SetFileName("myfile.zip")
Open("w")
AddFile("test.c")
AddFile("zip.c")
AddFile("zip.h")
AddFile("miniz.h")
(continues on next page)
97.11. RingZip Library 1505

Ring Documentation, Release 1.14
(continued from previous page)
Close()
}
97.12
Ring 1.3 comes with the Form Designer to quickly design your GUI application windows/forms and generate the Ring
source code.
It's written in Ring (Around 8000 Lines of code) using Object-Oriented Programming and Meta-Programming.
We can run the From Designer from Ring Notepad
Also we can run the Form Designer in another window.
97.12. Form Designer 1506

Ring Documentation, Release 1.14
97.12. Form Designer 1507

CHAPTER
NINETYEIGHT
WHAT IS NEW IN RING 1.4?
In this chapter we will learn about the changes and new features in Ring 1.4 release.
98.1
Ring 1.4 comes with many new features
•
•
•
•
•
•
•
•
•
98.2
In Ring 1.4 the next libraries are separated from RingVM
•
•
•
•
•
To use these libraries, Use the Load command.
load "odbclib.ring"
# use ODBC Functions
load "mysqllib.ring"
# use MySQL Functions
1508

Ring Documentation, Release 1.14
load "sqlitelib.ring"
# use SQLite Functions
load "openssllib.ring"
# use OpenSSL Functions ( Hash and Security functions)
load "internetlib.ring"
# use Internet Functions ( Download() and SendEmail() )
If you will use all of these libraries, You can just use stdlib.ring And the stdlib.ring will load odbclib.ring, mysqllib.ring,
sqlitelib.ring, opensslib.ring and internetlib.ring les.
load "stdlib.ring"
98.3
Ring 1.4 comes with the Natural Library to quickly dene a language that contains a group of commands.
We will write the natural code in a Text le, for example program.txt
File: program.txt
Welcome to the Ring programming language!
What you are reading now is not comments, I swear!
After many years of programming I decided to think different about
programming and solve the problems in a better way.
We are writing commands or code and the Ring language is reading
it to understand us! Sure, What you are seeing now is
just***part of the code - Not the Complete Program ***
You have to write little things before and after this
part to be able to run it!
It is the natural part of our code where we can write in English,
Arabic or any Natural Language Then we will tell the computer
through the Ring language what must happens! in a way that we can scale
for large frameworks and programs.
Just imagine what will happens to the world of programming once
we create many powerful frameworks using the Ring language that
uses this way (Natural Programming).
For example When we say Hello to the Machine, It can reply! and when we
say count from 1 to 5 it will understand us, Also if
we said count from 5 to 1 it will
understand us too! You can see the Output window!
This Goal is not new, but the Ring language comes
with an innovative solution to this problem.
Output:
98.3. The Natural Library 1509

Ring Documentation, Release 1.14
Hello, Sir!
The Numbers!
1
2
3
4
5
I will count Again!
5
4
3
2
1
To execute the natural code, We have start.ring
In start.ring we dene the language and the commands.
File: start.ring
load"stdlib.ring"
load"naturallib.ring"
NewNaturalLanguage {
SetLanguageName(:MyLanguage)
SetCommandsPath(CurrentDir()+"/../command")
SetPackageName("MyLanguage.Natural")
UseCommand(:Hello)
UseCommand(:Count)
RunFile("program.txt")
}
We dened a language called MyLanguage, We have folder for the language commands.
Each command will dene a class that belong to the MyLanguage.Natural package.
We will dene two commands, Hello and Count.
So we must have two les for dening the commands in the CurrentDir()+”/../command” folder
File: hello.ring
DefineNaturalCommand.SyntaxIsKeyword([
:PackageMyLanguage.Natural",
:Keyword
:Function func{
(continues on next page)
98.3. The Natural Library 1510

Ring Documentation, Release 1.14
(continued from previous page)
See"Hello, Sir!"
}
])
File: count.ring
DefineNaturalCommand.SyntaxIsKeywordNumberNumber([
:PackageMyLanguage.Natural",
:Keyword
:Function func{
if isattribute(self,:count_times) {
AddAttribute(self,:count_times)
Count_Times
}
ifExpr(1)2) {
nStep1
else
nStep
}
ifCount_Times
seenl+"The Numbers!"
Count_Times++
else
seenlI will count Again!"nl
}
forx1) toExpr(2) stepnStep {
seenl+x+nl
}
CommandReturn(fabs(Expr(1)-Expr(2))+1)
}
])
98.4
In Ring Notepad - From View - Styles - Select the (Modern) Style
Screen Shot:
98.4. New Style is added to Ring Notepad 1511

Ring Documentation, Release 1.14
98.5
In the application folder, You will nd RingREPL (Read-Eval-Print-Loop)
Also you can run it from Ring Notepad (Menubar - Tools)
Screen Shot:
98.5. RingREPL 1512

Ring Documentation, Release 1.14
98.6
Ring 1.4 comes with the next functions to convert between Numbers and Bytes.
•
•
•
•
•
•
Example:
see"Test Int2Bytes() and Bytes2Int() - Value : 77"
r77)
see"Int Size :
(continues on next page)
98.6. Convert between Numbers and Bytes 1513

Ring Documentation, Release 1.14
(continued from previous page)
seer
seeBytes2Int(r)
see"Test Float2Bytes() and Bytes2Float() - Value 77.12"
r77.12)
see"Float Size :
seer
seeBytes2Float(r)
see"Test Double2Bytes() and Bytes2Double() - Value 9999977.12345"
r9999977.12345)
see"Double Size :
seer
decimals(5)
seeBytes2Double(r)
98.7
The StdLib is updated to include the next functions
•
The print() function is updated to accept local variables.
load"stdlib.ring"
funcmain
print("Enter your name :) ;
Name
print(Hello : #{Name}) ;
return ;
98.8
The web library is updated
•
(1)
(2)
•
html(template("main.rhtml", NULL))
•
BootStrapWebPage()
{
TitleThe Ring Programming Language"
html(template("main.rhtml", NULL))
div {
classname
div
{
(continues on next page)
98.7. Better StdLib 1514

Ring Documentation, Release 1.14
(continued from previous page)
iddiv3"
colorblack"
backgroundcolorwhite"
width100%"
form
{
methodPOST"
Action
Targetcodeoutput"
input { type="hidden"="page"=1
Table
{
style"100%")
stylegradient(3)
TR
{
TD { align="center"
WIDTH="10%"
text("Code :")
}
TD {
html(
<textarea namecCode"
rows="5"
style="width : 100%;>
See"Hello, World!"
</textarea>)
}
}
}
Input { typesubmit"
classname="btn btn-primary btn-block"
valueExecute"
Table
{
style"100%")
stylegradient(34)
TR
{
TD { align="center"
WIDTH="10%"
text("Output :")
}
TD {
html(
<iframe name="codeoutput"
width="100%"
style="background-color:white;">
</iframe>)
}
}
}
}
}
(continues on next page)
98.8. Better WebLib 1515

Ring Documentation, Release 1.14
(continued from previous page)
}
html(template("footer.rhtml", NULL))
}
98.9
The next functions are added to RingQt
•
•
•
•
•
•
•
The next classes are added to RingQt
•
•
•
98.10
Ring 1.4 comes with a simple tool that help in porting Qt classes to RingQt.
You will nd it in ring/extensions/ringqt/converter
Online :
Screen Shot:
98.9. Better RingQt 1516

Ring Documentation, Release 1.14
98.11
Ring 1.4.1 comes with the next changes
•
•
•
•
•
The scripts are updated for building from source code.
Tested using Windows, Ubuntu Linux, Linux Mint and MacOS X.
Screen Shot:
98.11. What is new in Ring 1.4.1? 1517

Ring Documentation, Release 1.14
In Ring Notepad - the (Modern) Style colors are updated
Screen Shot:
The StdLib is updated to include the next functions
•
•
•
•
98.11. What is new in Ring 1.4.1? 1518

Ring Documentation, Release 1.14
The next functions are updated to display the dialogs on the top of other windows.
•
•
•
•
•
•
•
The Sixteen Puzzle is added to the Applications folder.
Screen Shot:
98.11. What is new in Ring 1.4.1? 1519

Ring Documentation, Release 1.14
98.11. What is new in Ring 1.4.1? 1520

CHAPTER
NINETYNINE
WHAT IS NEW IN RING 1.5?
In this chapter we will learn about the changes and new features in Ring 1.5 release.
99.1
Ring 1.5 comes with many new features!
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1521

Ring Documentation, Release 1.14
99.2
The Video-Music-Player application is added to the Applications folder.
Screen Shot:
99.3
The Windows StartUp Manager
URL :
Screen Shot:
99.2. Video-Music-Player Application 1522

Ring Documentation, Release 1.14
99.4
The Calculator application is added to the Applications folder.
Screen Shot:
99.4. Calculator Application 1523

Ring Documentation, Release 1.14
99.5
(1)
The idea of the Main File ToolBar is to determine the main le in the project When the project contains many source
code les
This way you can run the project ( Main File ) at any time while opening other les in the project without the need to
switch to the Main File to run the project.
To quickly use this feature
(Open the project main le)
Press Ctrl+Shift+M to set the current source code le as the main le
Open and modify other source code les in the project
To run the project (Main File) at any time press Ctrl+Shift+F5 (GUI) or Ctrl+Shift+D (Console)
Screen Shots:
99.5. Better Ring Notepad 1524

Ring Documentation, Release 1.14
99.5. Better Ring Notepad 1525

Ring Documentation, Release 1.14
(2)
Screen Shot:
(3) The Ring Notepad is updated to quickly open and switch between large les while preparing the functions/classes
lists in the background.
Screen Shot:
99.5. Better Ring Notepad 1526

Ring Documentation, Release 1.14
99.6
New Functions
•
•
•
(1)
Example:
load"stdlib.ring"
worldWorld!"
mystring"Hello, #{world} In Year#{2000+17}")
seemystring
Output:
Hello, World!
InYear
2017
(2)
Using this function we can quickly do a process on a group of les in a folder and it's sub folders.
Example:
99.6. Better StdLib 1527

Ring Documentation, Release 1.14
load"stdlib.ring"
aList"c:/ring/ringlibs","ring") #*.ring only
aList
seeaList
Example:
load"stdlib.ring"
seelistallfiles("b:/ring/ringlibs/weblib","") # All Files
(3)
The function will execute a system command like the System() function but will return the output in a string.
Example:
cYou"whoami")
See"SystemCmd: whoami ====="+nl
Output:
SystemCmd: whoami====
desktop-umberto\umberto
99.7
The WebLib is updated to include the HTMLPage class
Using this class we can create HTML documents without printing the output to the standard output
So instead of using the WebLib in Web Applications only
We can use it in Console/GUI/Mobile Applications too
Example:
load"stdlib.ring"
load"weblib.ring"
importSystem.Web
funcmain
mypage newHtmlPage {
h1 { text("Customers Report") }
Table
{
style"100%")4)
TR
{
TD { WIDTH="10%""Customers Count :
TD { text (100) }
}
}
Table
{
(continues on next page)
99.7. Better WebLib 1528

Ring Documentation, Release 1.14
(continued from previous page)
style"100%")26)
TR
{
style"100%")24)
TD { text("Name
TD { text("Age"
TD { text("Country"
TD { text("Job"
TD { text("Company"
}
forx to100
TR
{
TD { text("Test"
TD { text("30"
TD { text("Egypt"
TD { text("Sales"
TD { text("Future"
}
next
}
}
write("report.html",mypage.output())
Using this feature we can create reports quickly using WebLib & GUILib together
Example:
load"stdlib.ring"
load"weblib.ring"
load"guilib.ring"
importSystem.Web
importSystem.GUI
newqApp {
open_window(:CustomersReportController)
exec()
}
classCustomersReportController
oView newCustomersReportView
funcStart
CreateReport()
funcCreateReport
mypage newHtmlPage {
h1 { text("Customers Report") }
Table
{
style"100%")4)
TR
{
(continues on next page)
99.7. Better WebLib 1529

Ring Documentation, Release 1.14
(continued from previous page)
TD { WIDTH="10%"
text("Customers Count :
TD { text (100) }
}
}
Table
{
style"100%")26)
TR
{
style"100%")
stylegradient(24)
TD { text("Name
TD { text("Age"
TD { text("Country"
TD { text("Job"
TD { text("Company"
}
forx to100
TR
{
TD { text("Test"
TD { text("30"
TD { text("Egypt"
TD { text("Sales"
TD { text("Future"
}
next
}
}
write("report.html",mypage.output())
funcPrintEvent
printer1 newqPrinter(0) {
setoutputformat(1)
setoutputfilename("report.pdf")
}
oView {
web.print(printer1)
web.show()
}
system ("report.pdf")
classCustomersReportView
win newwindow() {
setwindowtitle("Report Window")
setgeometry(100,100,500,500)
web newwebview(win) {
setgeometry(100,100,1000,500)
loadpage(newqurl("file:///"+
currentdir()+"/report.html"))
}
newpushbutton(win) {
setGeometry(100,20,100,30)
settext("Print")
setclickevent(Method(:PrintEvent))
(continues on next page)
99.7. Better WebLib 1530

Ring Documentation, Release 1.14
(continued from previous page)
}
showMaximized()
}
Screen Shot:
99.8
New classes added to RingQt :
•
•
•
•
•
•
•
•
•
•
•
•
•
99.8. Better RingQt 1531

Ring Documentation, Release 1.14
•
•
•
•
Example:
### Submits your car VIN - Vehicle Id Number - to the Web Site - vpic.nhtsa.dot.gov -
### Parses XML data returned
### Prints out the car info result
load"libcurl.ring"
load"guilib.ring"
load"stdlib.ring"
curl
# request = "3G1JC5248YS251015?format=xml" ### VIN - Chevrolet
request3GYFK62847G247323?format=xml" ### VIN - Cadillac
call_typedecodevinvalues/"
urlhttps://vpic.nhtsa.dot.gov/api/vehicles/"
url_request
See"URL Request:+nl
curl_easy_setopt(curl, curlopt_url, url_request)
response
Seenl"Response Raw:+nlnl
curl_easy_cleanup(curl)
xml newqxmlstreamreader()
xml.adddata_2(response)
x newqstringref()
while xml.atend()
ifxml.error()
seexml.errorstring() seenl
exit
ok
x
if x.length()
see"Length: seex.length()"
see"Value: seex.tostring()seenl
ok
xml.readnext()
end
getx
###------------------------------------------
### Results
(continues on next page)
99.8. Better RingQt 1532

Ring Documentation, Release 1.14
(continued from previous page)
#
# ==>Value: 115
# ==>Value: Results returned successfully
# ==>Value: VIN(s): 3G1JC5248YS251015
# ==>Value: 3G1JC5248YS251015
# ==>Value: Sedan/Saloon
# ==>Value: 4
# ==>Value: 2200.0
# ==>Value: 134.25223700841
# ==>Value: 2.2
# ==>Value: 4
# ==>Value: LN2
# ==>Value: CHEVROLET
# ==>Value: GENERAL MOTORS LLC
# ==>Value: Cavalier
# ==>Value: 2000
# ==>Value: Ramos Arzipe
# ==>Value: PASSENGER CAR
# ==>Value: 4
# ==>Value: In-Line
# ==>Value: 1st Row (Driver & Passenger)
# ==>Value: Sequential Fuel Injection (SFI)
# ==>Value: Mexico
# ==>Value: NA
# ==>Value: Manual
# ==>Value: Body Type: Sedan, 4-6 Window, Notchback (GM codes: 19, 69)
# ==>Value: Name Plate: Chevrolet, Pontiac
# ==>Value: 0 - VIN decoded clean. Check Digit (9th position) is correct
# ==>Value: LAN
# ==>Value: 984
#
###-----------------------------------------
99.9
The function Open_WindowInPackages() is added to the Objects library.
The Open_WindowInPackages() function is the same as Open_Window() but takes an extra list that determine the
packages to import before opening the window.
Syntax:
Open_WindowInPackages(cClassName,aPackagesList)
Example:
The next example from the Form Designer source code, Open the Window Flags window using the
open_windowInPackages() function.
We determine the class name “WindowFlagsController” and the packages name.
The Window Flags window uses the FormDesigner and System.GUI packages.
open_windowInPackages(:WindowFlagsController,[
"formdesigner",
(continues on next page)
99.9. Better Objects Library 1533

Ring Documentation, Release 1.14
(continued from previous page)
"System.GUI"
])
99.10
Ring 1.5 comes with RingFreeGLUT extension to support the FreeGLUT library
Example:
/*
This sample is based on C Tutorials
from : http://www.lighthouse3d.com/tutorials/glut-tutorial/
*/
load "freeglut.ring"
load "opengl21lib.ring"
// angle of rotation for the camera direction
angle = 0.0
// actual vector representing the cameras direction
lx=0.0 lz=-1.0
// XZ position of the camera
x=0.0 z=5.0
// the key states. These variables will be zero
//when no key is being presses
deltaAngle = 0.0
deltaMove = 0
xOrigin = -1
// Constant definitions for Menus
C_RED = 1
C_GREEN = 2
C_BLUE = 3
C_ORANGE = 4
C_FILL = 5
C_LINE = 6
// Pop up menu identifiers
fillMenu=NULL
fontMenu=NULL
mainMenu=NULL
colorMenu=NULL
// color for the nose
red = 1.0
blue=0.5
green=0.5
// scale of snowman
(continues on next page)
99.10. RingFreeGLUT Extension 1534

Ring Documentation, Release 1.14
(continued from previous page)
scale = 1.0
// menu status
menuFlag = 0
// default font
font = GLUT_BITMAP_TIMES_ROMAN_24
C_INT_GLUT_BITMAP_8_BY_13 = 7
C_INT_GLUT_BITMAP_9_BY_15 = 8
C_INT_GLUT_BITMAP_TIMES_ROMAN_10 = 9
C_INT_GLUT_BITMAP_TIMES_ROMAN_24 = 10
C_INT_GLUT_BITMAP_HELVETICA_10 = 11
C_INT_GLUT_BITMAP_HELVETICA_12 = 12
C_INT_GLUT_BITMAP_HELVETICA_18 = 13
// width and height of the window
h = 0
w = 0
// variables to compute frames per second
frame=0
time=0
timebase=0
s = ""
func changeSize
w = glutEventWidth()
h = glutEventHeight()
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if h = 0
h = 1
ok
ratio = w *1.0 / h
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION)
// Reset Matrix
glLoadIdentity()
// Set the viewport to be the entire window
glViewport(0, 0, w, h)
// Set the correct perspective.
gluPerspective(45.0, ratio, 0.1, 100.0)
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW)
func drawSnowMan
glScalef(scale, scale, scale)
glColor3f(1.0, 1.0, 1.0)
(continues on next page)
99.10. RingFreeGLUT Extension 1535

Ring Documentation, Release 1.14
(continued from previous page)
// Draw Body
glTranslatef(0.0 ,0.75, 0.0)
glutSolidSphere(0.75,20,20)
// Draw Head
glTranslatef(0.0, 1.0, 0.0)
glutSolidSphere(0.25,20,20)
// Draw Eyes
glPushMatrix()
glColor3f(0.0,0.0,0.0)
glTranslatef(0.05, 0.10, 0.18)
glutSolidSphere(0.05,10,10)
glTranslatef(-0.1, 0.0, 0.0)
glutSolidSphere(0.05,10,10)
glPopMatrix()
// Draw Nose
glColor3f(red, green, blue)
glRotatef(0.0,1.0, 0.0, 0.0)
glutSolidCone(0.08,0.5,10,2)
glColor3f(1.0, 1.0, 1.0)
func renderBitmapString x,y,z,font,string
glRasterPos3f(x, y,z)
for c in string
glutBitmapCharacter(font,ascii(c))
next
func renderStrokeFontString x,y,z,font,string
glPushMatrix()
glTranslatef(x, y,z)
glScalef(0.002, 0.002, 0.002)
for c in string
glutStrokeCharacter(font, Ascii(c));
next
glPopMatrix()
func restorePerspectiveProjection
glMatrixMode(GL_PROJECTION)
// restore previous projection matrix
glPopMatrix()
// get back to modelview mode
glMatrixMode(GL_MODELVIEW)
func setOrthographicProjection
// switch to projection mode
glMatrixMode(GL_PROJECTION)
// save previous matrix which contains the
(continues on next page)
99.10. RingFreeGLUT Extension 1536

Ring Documentation, Release 1.14
(continued from previous page)
//settings for the perspective projection
glPushMatrix()
// reset matrix
glLoadIdentity()
// set a 2D orthographic projection
gluOrtho2D(0, w, h, 0)
// switch back to modelview mode
glMatrixMode(GL_MODELVIEW)
func computePos deltaMove
x += deltaMove*lx*0.1
z += deltaMove*lz*0.1
func renderScene
if deltaMove
computePos(deltaMove)
ok
// Clear Color and Depth Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
// Reset transformations
glLoadIdentity()
// Set the camera
gluLookAt( x, 1.0, z,
x+lx, 1.0, z+lz,
0.0, 1.0, 0.0)
// Draw ground
glColor3f(0.9, 0.9, 0.9)
glBegin(GL_QUADS)
glVertex3f(-100.0, 0.0, -100.0)
glVertex3f(-100.0, 0.0, 100.0)
glVertex3f( 100.0, 0.0, 100.0)
glVertex3f( 100.0, 0.0, -100.0)
glEnd()
// Draw 9 SnowMen
for i = -3 to -1
for j = -3 to -1
glPushMatrix()
glTranslatef(i*10.0, 0.0, j*10.0)
drawSnowMan()
number = (i+3)*3+(j+3)
renderBitmapString(0.0, 0.5, 0.0,font ,""+number)
glPopMatrix()
next
(continues on next page)
99.10. RingFreeGLUT Extension 1537

Ring Documentation, Release 1.14
(continued from previous page)
next
// Code to compute frames per second
frame++
time=glutGet(GLUT_ELAPSED_TIME)
if time - timebase > 1000
s = "RingFreeGLUT - FPS: " + (frame *1000.0/(time-timebase))
timebase = time
frame = 0
ok
// Code to display a string (fps) with bitmap fonts
setOrthographicProjection()
glPushMatrix()
glLoadIdentity()
renderBitmapString(5,30,0,GLUT_BITMAP_HELVETICA_18,s)
glPopMatrix()
restorePerspectiveProjection()
glutSwapBuffers()
// -----------------------------------
// KEYBOARD
// -----------------------------------
func processNormalKeys
key = glutEventKey()
xx = glutEventX()
yy = glutEventY()
switch key
on 27
glutDestroyMenu(mainMenu)
glutDestroyMenu(fillMenu)
glutDestroyMenu(colorMenu)
glutDestroyMenu(fontMenu)
Shutdown()
off
func pressKey
key = glutEventKey()
xx = glutEventX()
yy = glutEventY()
switch key
on GLUT_KEY_UP
deltaMove = 0.5
on GLUT_KEY_DOWN
deltaMove = -0.5
off
(continues on next page)
99.10. RingFreeGLUT Extension 1538

Ring Documentation, Release 1.14
(continued from previous page)
func releaseKey
key = glutEventKey()
switch key
on GLUT_KEY_UP
deltaMove = 0
on GLUT_KEY_DOWN
deltaMove = 0
off
// -----------------------------------
// MOUSE
// -----------------------------------
func mouseMove
xx = glutEventX()
yy = glutEventY()
// this will only be true when the left button is down
if xOrigin >= 0
// update deltaAngle
deltaAngle = (xx - xOrigin) *0.001
// update cameras direction
lx = sin(angle + deltaAngle)
lz = -cos(angle + deltaAngle)
ok
func mouseButton
button = glutEventButton()
state = glutEventState()
xx = glutEventX()
yy = glutEventY()
// only start motion if the left button is pressed
if button = GLUT_LEFT_BUTTON
// when the button is released
if state = GLUT_UP
angle += deltaAngle
xOrigin = -1
else
// state = GLUT_DOWN
xOrigin = xx
ok
ok
// -----------------------------------
// MENUS
// -----------------------------------
(continues on next page)
99.10. RingFreeGLUT Extension 1539

Ring Documentation, Release 1.14
(continued from previous page)
func processMenuStatus
status = glutEventStatus()
if status = GLUT_MENU_IN_USE
menuFlag = 1
else
menuFlag = 0
ok
func processMainMenu
// nothing to do in here
// all actions are for submenus
func processFillMenu
option = glutEventValue()
switch option
on C_FILL
glPolygonMode(GL_FRONT, GL_FILL)
on C_LINE
glPolygonMode(GL_FRONT, GL_LINE)
off
func processFontMenu
option = glutEventValue()
switch (option) {
on C_INT_GLUT_BITMAP_8_BY_13
font = GLUT_BITMAP_8_BY_13
on C_INT_GLUT_BITMAP_9_BY_15
font = GLUT_BITMAP_9_BY_15
on C_INT_GLUT_BITMAP_TIMES_ROMAN_10
font = GLUT_BITMAP_TIMES_ROMAN_10
on C_INT_GLUT_BITMAP_TIMES_ROMAN_24
font = GLUT_BITMAP_TIMES_ROMAN_24
on C_INT_GLUT_BITMAP_HELVETICA_10
font = GLUT_BITMAP_HELVETICA_10
on C_INT_GLUT_BITMAP_HELVETICA_12
font = GLUT_BITMAP_HELVETICA_12
on C_INT_GLUT_BITMAP_HELVETICA_18
font = GLUT_BITMAP_HELVETICA_18
off
func processColorMenu
option = glutEventValue()
switch option
on C_RED
(continues on next page)
99.10. RingFreeGLUT Extension 1540

Ring Documentation, Release 1.14
(continued from previous page)
red = 1.0
green = 0.0
blue = 0.0
on C_GREEN
red = 0.0
green = 1.0
blue = 0.0
on C_BLUE
red = 0.0
green = 0.0
blue = 1.0
on C_ORANGE
red = 1.0
green = 0.5
blue = 0.5
off
func createPopupMenus
fontMenu = glutCreateMenu(:processFontMenu)
glutAddMenuEntry("BITMAP_8_BY_13 ",C_INT_GLUT_BITMAP_8_BY_13 )
glutAddMenuEntry("BITMAP_9_BY_15",C_INT_GLUT_BITMAP_9_BY_15 )
glutAddMenuEntry("BITMAP_TIMES_ROMAN_10 ",C_INT_GLUT_BITMAP_TIMES_ROMAN_10 )
glutAddMenuEntry("BITMAP_TIMES_ROMAN_24",C_INT_GLUT_BITMAP_TIMES_ROMAN_24 )
glutAddMenuEntry("BITMAP_HELVETICA_10 ",C_INT_GLUT_BITMAP_HELVETICA_10 )
glutAddMenuEntry("BITMAP_HELVETICA_12",C_INT_GLUT_BITMAP_HELVETICA_12 )
glutAddMenuEntry("BITMAP_HELVETICA_18",C_INT_GLUT_BITMAP_HELVETICA_18 )
fillMenu = glutCreateMenu(:processFillMenu)
glutAddMenuEntry("Fill",C_FILL)
glutAddMenuEntry("Line",C_LINE)
colorMenu = glutCreateMenu(:processColorMenu)
glutAddMenuEntry("Red",C_RED);
glutAddMenuEntry("Blue",C_BLUE);
glutAddMenuEntry("Green",C_GREEN);
glutAddMenuEntry("Orange",C_ORANGE);
mainMenu = glutCreateMenu(:processMainMenu)
glutAddSubMenu("Polygon Mode", fillMenu)
glutAddSubMenu("Color", colorMenu)
glutAddSubMenu("Font",fontMenu)
// attach the menu to the right button
glutAttachMenu(GLUT_RIGHT_BUTTON)
// this will allow us to know if the menu is active
glutMenuStatusFunc(:processMenuStatus)
// -----------------------------------
// MAIN
// -----------------------------------
(continues on next page)
99.10. RingFreeGLUT Extension 1541

Ring Documentation, Release 1.14
(continued from previous page)
func main
// init GLUT and create window
glutInit()
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("RingFreeGLUT - Test - 9 SnowMan")
// register callbacks
glutDisplayFunc(:renderScene)
glutReshapeFunc(:changeSize)
glutIdleFunc(:renderScene)
glutIgnoreKeyRepeat(1)
glutKeyboardFunc(:processNormalKeys)
glutSpecialFunc(:pressKey)
glutSpecialUpFunc(:releaseKey)
// here are the two new functions
glutMouseFunc(:mouseButton)
glutMotionFunc(:mouseMove)
// OpenGL init
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
// init Menus
createPopupMenus()
// enter GLUT event processing cycle
glutMainLoop()
Screen Shots:
99.10. RingFreeGLUT Extension 1542

Ring Documentation, Release 1.14
99.11
Ring 1.5 comes with RingOpenGL and support for the next versions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Example:
99.11. RingOpenGL Extension 1543

Ring Documentation, Release 1.14
/*
This sample is based onC Tutorials
from:
http://www.wikihow.com/Make-a-Cube- in-OpenGL
*/
load"freeglut.ring"
load"opengl21lib.ring"
//---------------------------------------------------------
//
//---------------------------------------------------------
rotate_y=0
rotate_x=0
//---------------------------------------------------------
//
//---------------------------------------------------------
funcdisplay
// andZ-buffer
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
//
glLoadIdentity()
// androtate_y
glRotatef( rotate_x,.0,.0,.0
glRotatef( rotate_y,.0,.0,.0
//Multi-colored side
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0.5,0.5,0.5 # P1 is red
glColor3f(.0,.0,.0.5,.5,0.5 # P2 is green
glColor3f(.0,.0,.00.5,.5,0.5 # P3 is blue
glColor3f(.0,.0,.00.5,0.5,0.5 # P4 is purple
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,0.5,.5
glVertex3f(.5,.5,.5
glVertex3f(0.5,.5,.5
glVertex3f(0.5,0.5,.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,0.5,0.5
glVertex3f(.5,.5,0.5
glVertex3f(.5,.5,.5
glVertex3f(.5,0.5,.5
glEnd()
(continues on next page)
99.11. RingOpenGL Extension 1544

Ring Documentation, Release 1.14
(continued from previous page)
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(0.5,0.5,.5
glVertex3f(0.5,.5,.5
glVertex3f(0.5,.5,0.5
glVertex3f(0.5,0.5,0.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,.5,.5
glVertex3f(.5,.5,0.5
glVertex3f(0.5,.5,0.5
glVertex3f(0.5,.5,.5
glEnd()
//
glBegin(GL_POLYGON)
glColor3f(.0,.0,.0
glVertex3f(.5,0.5,0.5
glVertex3f(.5,0.5,.5
glVertex3f(0.5,0.5,.5
glVertex3f(0.5,0.5,0.5
glEnd()
glFlush()
glutSwapBuffers()
//---------------------------------------------------------
//
//---------------------------------------------------------
funcspecialKeys
key
//
switchKey
onGLUT_KEY_RIGHT
rotate_y=
//
onGLUT_KEY_LEFT
rotate_y=
onGLUT_KEY_UP
rotate_x=
onGLUT_KEY_DOWN
rotate_x=
off
(continues on next page)
99.11. RingOpenGL Extension 1545

Ring Documentation, Release 1.14
(continued from previous page)
//
glutPostRedisplay()
//---------------------------------------------------------
//
//---------------------------------------------------------
funcmain
// andprocess user parameters
glutInit()
// truecolor window with Z-buffer
glutInitDisplayMode(GLUT_DOUBLE
//
glutCreateWindow("Awesome Cube")
//-buffer depth test
glEnable(GL_DEPTH_TEST)
//
glutDisplayFunc(:display)
glutSpecialFunc(:specialKeys)
// toGLUTforevents
glutMainLoop()
//Return OS
Screen Shot:
99.11. RingOpenGL Extension 1546

Ring Documentation, Release 1.14
99.12
The Code Generator is updated to support <constant> type, So we can have constants other than numbers, for example
: Strings and Pointers.
When we have pointers we can determine the pointer type. To use this feature, before <constant> and </constant> we
can use
$nDefaultConstantType
$cDefaultConstantPointerTypevoid *"
The next example from the RingFreeGLUT extension
<runcode>
$nDefaultConstantType
$cDefaultConstantPointerTypevoid"
</runcode>
<constant>
GLUT_STROKE_ROMAN
GLUT_STROKE_MONO_ROMAN
GLUT_BITMAP_9_BY_15
GLUT_BITMAP_8_BY_13
GLUT_BITMAP_TIMES_ROMAN_10
GLUT_BITMAP_TIMES_ROMAN_24
GLUT_BITMAP_HELVETICA_10
GLUT_BITMAP_HELVETICA_12
GLUT_BITMAP_HELVETICA_18
</constant>
99.13
The documentation generator for extensions is updated to generate a list of constants in the generated documentation
The previous versions provides the functions prototype only, Now we have the list of constants too.
99.14
In Ring 1.5 the next functions are added to Ring VM
•
•
•
•
•
•
•
•
•
99.12. Better Code Generator for Extensions 1547

Ring Documentation, Release 1.14
Example:
load"tracelib.ring"
ringvm_settrace("mytrace()")
see"Hello, world!"
see"Welcome"
see"How are you?"nl
mytest()
newmyclass { mymethod() }
funcmytest
see"Message from mytest"
funcmytrace
see"====== The Trace function is Active ======"
"Trace Function Name :
"Trace Event :
switchringvm_TraceEvent()
onTRACEEVENT_NEWLINE see"New Line"
onTRACEEVENT_NEWFUNC see"New Function"
onTRACEEVENT_RETURN see"Return"
onTRACEEVENT_ERROR see"Error"
onTRACEEVENT_BEFORECFUNC see"Before C Function"
onTRACEEVENT_AFTERCFUNC see"After C Function"
off
seenl
"Line Number :[TRACEDATA_LINENUMBER]
"File Name :[TRACEDATA_FILENAME]
"Function Name :[TRACEDATA_FUNCNAME]
"Method or Function :
ifringvm_tracedata()[TRACEDATA_METHODORFUNC]
TRACEDATA_METHODORFUNC_METHOD
see"Method"
else
ifringvm_tracedata()[TRACEDATA_FUNCNAME] NULL
see"Command"
else
see"Function"
ok
ok
seenl"=",42)
classmyclass
funcmymethod
see"Message from mymethod"
Output:
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 3
File Name : test1.ring
Function Name : ringvm_settrace
Method or Function : Function
==========================================
(continues on next page)
99.14. Ring VM - Tracing Functions 1548

Ring Documentation, Release 1.14
(continued from previous page)
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 5
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
Hello, world!
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 6
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
Welcome
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 7
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
How are you?
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 8
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Function
Line Number : 8
File Name : test1.ring
Function Name : mytest
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 12
File Name : test1.ring
Function Name : mytest
Method or Function : Function
==========================================
Message from mytest
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 14
File Name : test1.ring
(continues on next page)
99.14. Ring VM - Tracing Functions 1549

Ring Documentation, Release 1.14
(continued from previous page)
Function Name : mytest
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Return
Line Number : 8
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 9
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 43
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Before C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Function
Line Number : 9
File Name : test1.ring
Function Name : mymethod
Method or Function : Method
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 44
File Name : test1.ring
Function Name : mymethod
(continues on next page)
99.14. Ring VM - Tracing Functions 1550

Ring Documentation, Release 1.14
(continued from previous page)
Method or Function : Method
==========================================
Message from mymethod
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Return
Line Number : 9
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Before C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : Before C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : After C Function
Line Number : 9
File Name : test1.ring
Function Name : ismethod
Method or Function : Function
==========================================
====== The Trace function is Active ======
Trace Function Name : mytrace()
Trace Event : New Line
Line Number : 11
File Name : test1.ring
Function Name :
Method or Function : Command
==========================================
99.14. Ring VM - Tracing Functions 1551

Ring Documentation, Release 1.14
99.15
Ring 1.5 comes with the Trace Library and the Interactive Debugger
Using this library we can trace events, execute programs line by line, open the Interactive Debugger when an error
happens or at breakpoints.
Example:
The next example uses a Breakpoint to open the Interactive Debugger!
load"tracelib.ring"
test1()
functest1
x
see:test1
t
BreakPoint()
see"After breakpoint!"nl
see"t =
see"End of program!"
Screen Shots:
We have the Interactive Debugger at the Breakpoint!
We can print the variables values
99.15. Trace Library and Interactive Debugger 1552

Ring Documentation, Release 1.14
We can change the variables values then continue executionWe can run the Interactive Debugger in the Output Window
99.15. Trace Library and Interactive Debugger 1553

Ring Documentation, Release 1.14
99.16
•
Example:
load"stdlib.ring"
importmypackage
newmyclass {
myfunc()
}
package mypackage
{
classmyclass
{
funcmyfunc
{
print("Hello, World! ")
}
}
}
•
Example:
importmypackage
newmyclass {
myfunc()
}
package mypackage
classmyclass
defmyfunc
put"Hello, World!"
end
end
end
•
Example:
importmypackage
newmyclass { myfunc() }
package mypackage
classmyclass
funcmyfunc
see"welcome"
endfunc
endclass
endpackage
99.16. More Syntax Flexibility 1554

Ring Documentation, Release 1.14
99.17
Ring 1.5 comes with the Type Hints library
Using this library we can add the type information to the source code which will be very useful for tools like
•
•
Example:
load"typehints.ring"
seesum(3,4)
seesayHello("Mahmoud");
intfuncsum(int x,int y) {
returnx+y ;
}
string sayHello(stringname) {
return"Hello
}
The library is very powerful and support the User types (Classes) automatically!
Example:
load"typehints.ring"
importmypackage
test() { main([:one,:two,:three]) }
myclassfunctest() {
see"Testing User Types!"
return myclass
}
package mypackage {
publicclassmyclass {
public static void funcmain(listargs) {
see"welcome"
seeargs
}
}
}
Also You can use the types inside the code (not only the function prototype)
Example:
load"typehints.ring"
int sum3,4)
stringmsg"Mahmoud")
see"Sum =
(continues on next page)
99.17. Type Hints Library 1555

Ring Documentation, Release 1.14
(continued from previous page)
intfuncsum(int x,int y) {
returnx+y ;
}
string sayHello(stringname) {
return"Hello
}
Rules:
•
•
Note:Ring is a dynamic language, No type checking will be done by the compiler.
99.18
Based on Ring usage every day in practical projects
Ring 1.5 is more stable and more productive!
We are adding features based on clear vision and practical needs.
Also the documentation is better.
99.19
•
•
•
•
Source Code:
load"gamelib.ring"
load"opengl21lib.ring"
funcmain
newGraphicsApp {
start()
}
classGraphicsAppfromGraphicsAppBase
TITLERing Cube"
(continues on next page)
99.18. Better Quality 1556

Ring Documentation, Release 1.14
(continued from previous page)
bitmap texture
xrot.0
yrot.0
zrot.0
funcloadresources
bitmap"ring.bmp")
texture
funcdestroyResources
al_destroy_bitmap(bitmap)
funcdrawScene
w
ratio
glViewport(0,, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45,ratio,1,100)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_TEXTURE_2D)
glShadeModel(GL_SMOOTH)
glClearColor(0.0,.0,.0,.5)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glClear(GL_COLOR_BUFFER_BIT
glLoadIdentity();
glTranslatef(0.0,0.0,-5.0);
glRotatef(xrot,1.0,0.0,0.0);
glRotatef(yrot,0.0,1.0,0.0);
glRotatef(zrot,0.0,0.0,1.0);
glBindTexture(GL_TEXTURE_2D, texture)
glBegin(GL_QUADS)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,1.0)
(continues on next page)
99.19. What is new in Ring 1.5.1? 1557

Ring Documentation, Release 1.14
(continued from previous page)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
//
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
//
glTexCoord2f(1.0,.0) glVertex3f(.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(.0,.0,1.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(.0,1.0,.0)
//
glTexCoord2f(0.0,.0) glVertex3f(-1.0,1.0,1.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,1.0,.0)
glTexCoord2f(1.0,.0) glVertex3f(-1.0,.0,.0)
glTexCoord2f(0.0,.0) glVertex3f(-1.0,.0,1.0)
glEnd()
xrot=.3
yrot=.2
zrot=.4
classGraphicsAppBase
display event_queue ev timeout
timer redraw true
FPS
SCREEN_W
SCREEN_H
KEY_UP
KEY_DOWN
KEY_LEFT
KEY_RIGHT
Key false,false,false,false]
TITLEGraphics Application"
funcstart
SetUp()
loadResources()
eventsLoop()
destroy()
funcsetup
al_init()
(continues on next page)
99.19. What is new in Ring 1.5.1? 1558

Ring Documentation, Release 1.14
(continued from previous page)
al_init_image_addon()
al_set_new_display_flags(ALLEGRO_OPENGL)
display
al_set_Window_title(display,TITLE)
al_clear_to_color(al_map_rgb(0,0,0))
event_queue
al_register_event_source(event_queue,
al_get_display_event_source(display))
ev
timeout
al_init_timeout(timeout,.06)
timer1.0
al_register_event_source(event_queue,
al_get_timer_event_source(timer))
al_start_timer(timer)
al_install_mouse()
al_register_event_source(event_queue,
al_get_mouse_event_source())
al_install_keyboard()
al_register_event_source(event_queue,
al_get_keyboard_event_source())
funceventsLoop
while
al_wait_for_event_until(event_queue, ev, timeout)
switchal_get_allegro_event_type(ev)
onALLEGRO_EVENT_DISPLAY_CLOSE
exit
onALLEGRO_EVENT_TIMER
redraw true
onALLEGRO_EVENT_MOUSE_AXES
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_ENTER_DISPLAY
mouse_x
mouse_y
onALLEGRO_EVENT_MOUSE_BUTTON_UP
exit
onALLEGRO_EVENT_KEY_DOWN
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] true
onALLEGRO_KEY_DOWN
key[KEY_DOWN] true
onALLEGRO_KEY_LEFT
key[KEY_LEFT] true
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] true
off
onALLEGRO_EVENT_KEY_UP
switchal_get_allegro_event_keyboard_keycode(ev)
onALLEGRO_KEY_UP
key[KEY_UP] false
onALLEGRO_KEY_DOWN
key[KEY_DOWN] false
onALLEGRO_KEY_LEFT
(continues on next page)
99.19. What is new in Ring 1.5.1? 1559

Ring Documentation, Release 1.14
(continued from previous page)
key[KEY_LEFT] false
onALLEGRO_KEY_RIGHT
key[KEY_RIGHT] false
onALLEGRO_KEY_ESCAPE
exit
off
off
ifredrawandal_is_event_queue_empty(event_queue)
redraw false
drawScene()
al_flip_display()
ok
callgc()
end
funcdestroy
destroyResources()
al_destroy_timer(timer)
al_destroy_allegro_event(ev)
al_destroy_allegro_timeout(timeout)
al_destroy_event_queue(event_queue)
al_destroy_display(display)
funcloadresources
funcdrawScene
funcdestroyResources
Screen Shot:
99.19. What is new in Ring 1.5.1? 1560

Ring Documentation, Release 1.14
99.20
•
•
•
•
•
•
•
•
•
•
•
•
•
Screen Shot:
99.20. What is new in Ring 1.5.2? 1561

Ring Documentation, Release 1.14
99.21
•
•
•
•
•
•
•
Screen Shot:
•
•
Example:
load"guilib.ring"
newqApp {
(continues on next page)
99.21. What is new in Ring 1.5.3? 1562

Ring Documentation, Release 1.14
(continued from previous page)
win newqwidget() {
setwindowtitle("Context Menu")
resize(400,400)
myfilter newqAllEvents(win) {
setContextmenuEvent("mymenu()")
}
installeventfilter(myfilter)
show()
}
exec()
}
funcmymenu
newqMenu(win) {
oAction newqAction(win) {
settext("new")
SetCLickevent("See :New")
}
addaction(oAction)
oAction newqAction(win) {
settext("open")
SetCLickevent("See :Open")
}
addaction(oAction)
oAction newqAction(win) {
settext("save")
SetCLickevent("See :Save")
}
addaction(oAction)
oAction newqAction(win) {
settext("close")
SetCLickevent("See :Close")
}
addaction(oAction)
oCursor newqCursor()
exec(oCursor.pos())
}
•
Example:
x
seetype(x)+nl
seex+1+nl
Output:
NUMBER
100000001
•
Example:
99.21. What is new in Ring 1.5.3? 1563

Ring Documentation, Release 1.14
x = 19.99f
see type(x) + nl
Output:
NUMBER
•
Screen Shots:
•
Screen Shot:
99.21. What is new in Ring 1.5.3? 1564

Ring Documentation, Release 1.14
99.22
•
•
•
•
•
•
•
•
•
•
•
•
•RingQt - Added Classes :-
–QScreen
99.22. What is new in Ring 1.5.4? 1565

Ring Documentation, Release 1.14
–QWindow
–QGuiApplication
–QTextBrowser
•
•
•
•
99.22. What is new in Ring 1.5.4? 1566

CHAPTER
WHAT IS NEW IN RING 1.6?
In this chapter we will learn about the changes and new features in Ring 1.6 release.
100.1
Ring 1.6 comes with many new features!
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1567

Ring Documentation, Release 1.14
100.2
The Employee application is added to ring/applications
Developer: Ahmed Hassouna
100.3
In Ring 1.6 we have a nice tool called Ring2EXE (Written in Ring itself)
Using Ring2EXE we can distribute applications quickly for Windows, Linux, macOS and Mobile devices
Read the chapter “Distributing Ring Applications using Ring2EXE” for more information!
100.4
Ring For Android (using RingQt) is updated to use the Ring Object File (*.ringo ) instead of using many source code
les (*.ring )
The next screen shot is an example of building the cards game for Android
We are using cards.ringo instead of cards.ring
If you have large project (many*.ring les) it will use only one*.ringo le.
100.2. Employee Application 1568

Ring Documentation, Release 1.14
To prepare Qt project to distribute RingQt application for Mobile use Ring2EXE
Example
ring2exe cards.ringdistmobileqt
Example (2)
ring2exe formdesigner.ringdistmobileqt
100.4. Better Ring For Android 1569

Ring Documentation, Release 1.14
100.5
When we have large RingQt project that contains a lot of images and les, We need to add these les to the resource
le (*.qrc ) when distributing applications for Mobile devices.
Instead of adding these les one by one, Ring 1.6 comes with a simple tool that save our time, It's called Folder2qrc.
Example:
folder2qrc formdesigner.ring
We determine the main source le while we are in the application folder, and Folder2qrc will check all of the les in
the current folder and sub folders, Then add them to the resource le after the mainle.ringo (In our example this will
be formdesigner.ringo)
The output le will be : project.qrc
You can open it and remove the les that you don't need in the resources!
100.6
Ring 1.6 comes with better scripts for building Ring from source code.
The updates are tested on 32bit and 64bit systems on Windows, Linux (Ubuntu,Fedora) and macOS.
The scripts for Windows are updated to nd the Visual C/C++ compiler based on your Visual Studio version.
100.7
Using the RingConsoleColors extension we can easily change the colors used in our console applications
For more information check the RingConsoleColors chapter in the documentation.
100.5. New Tool: Folder2qrc 1570

Ring Documentation, Release 1.14
100.8
Ring 1.6 comes with the RingMurmurHash extension!
Developer: Hassan Ahmed
Example:
load "murmurhashlib.ring"
key = "Ring Language"
see murmurhash3_x86_32(key, 0, 0) + nl // Output: 1894444853
see murmurhash3_x86_32(key, 0, 1) + nl // Output: 70eaef35
For more information check the RingMurmurHash chapter in the documentation.
100.9
Ring Notepad comes with the next updates
(1)
(2)
(3)
(4)
For Windows users, Ring 1.6 comes with Apache Web server!
We can run any web application from any folder directly without doing any conguration.
100.8. RingMurmurHash Extension 1571

Ring Documentation, Release 1.14
(5)So we can quickly open the Command Prompt or the Explorer at the application folder.
100.9. Better Ring Notepad 1572

Ring Documentation, Release 1.14
(6) *.sh &*.bat extensions.
(7)100.10
RingQt comes with the next updates
(1)
(2)
(3)
(4)
100.10. Better RingQt 1573

Ring Documentation, Release 1.14
(5)
(6)
(7)
100.11
StdLib comes with the next updates
(1)
(2)
(3)
Also this is useful when developing standalone console applications
Because using stdlib.ring (functions & classes) will load libraries like RingLibCurl, RingOpenSSL, etc.
(4)
•
•
•
•
•
•
•
100.12
RingVM comes with the next updates
(1)
(2)
(3)
(4)
(5)
(6)
(7)
100.11. Better StdLib 1574

Ring Documentation, Release 1.14
100.13
RingREPL comes with the next updates
(1)
(2)
100.14
The variable Tab is dened to be used instead of char(9)
Example (1):
see:one
Output:
one
two
three
You can change the variable to another value
Example (2):
tab
see:one
Output:
one
two
three
100.15
The next example count from 1 to 10 in the same line during 10 seconds
load"stdlibcore.ring"
forx to10seex sleep(1) seecrnext
100.16
We have = and != in the Ring language
But for the logical operators we have and, or & not
Now we can use the ! operator as not
Example:
100.13. Better RingREPL 1575

Ring Documentation, Release 1.14
if!false
see"True!"
ok
Output
True!
100.17
In Ring we have the next keywords for the logical operations
•
•
•
Now we have also the next operators
•
•
•
Example:
ifone()andtwo()
see"Test1 - Fail"
else
see"Test1 - Pass"
ok
iftwo()orone()
see"Test2 - Pass"
else
see"Test2 - Fail"
ok
ifone()&
see"Test3 - Fail"
else
see"Test3 - Pass"
ok
iftwo()|
see"Test4 - Pass"
else
see"Test4 - Fail"
ok
funconereturn
functworeturn
Output:
100.17. Using && and || operators 1576

Ring Documentation, Release 1.14
Test1 - Pass
Test2 - Pass
Test3 - Pass
Test4 - Pass
100.18
It's common to print new line after printing an expression, We can use the ? operator to do that!
Example:
?Hello, World!"
forx to10
?
next
Output:
Hello, World!
1
2
3
4
5
6
7
8
9
10
100.18. Using ? to print expression then new line 1577

CHAPTER
ONE
WHAT IS NEW IN RING 1.7?
In this chapter we will learn about the changes and new features in Ring 1.7 release.
101.1
Ring 1.7 comes with many new features!
•
•
•
•
•
•
•
•
•
•
•
101.2
Using the `load' command we can use many ring source les in the same project
But all of these les will share the same global scope
Now we have the “Load Package” command too
Using “Load Package” we can load a library (*.ring le) in new global scope
This is very useful to create libraries that avoid conicts in global variables
Example:
File: loadpackage.ring
1578

Ring Documentation, Release 1.14
x
?Hello, World!"
loadpackagetestloadpackage.ring"
?
test()
File: testloadpackage.ring
?Hello from testloadpackage.ring"
x
test()
functest
?
Output:
Hello, World!
Hello from testloadpackage.ring
1000
100
1000
101.3
Using the ringvm_see() function we can redene the behavior of the See command
Also we can use ring_see() to have the original behavior
Example:
see"Hello world"
see123
see["one","two","three"]
see point {x=10=20=30}
funcringvm_see t
ring_see("We want to print:)
ring_See(t)
classpoint x y z
Output:
We want to print: Hello world
We want to print: 123
We want to print: one
two
three
We want to print: x: 10.000000
y: 20.000000
z: 30.000000
101.3. ringvm_see() and ringvm_give() functions 1579

Ring Documentation, Release 1.14
Using the ringvm_give() function we can redene the behavior of the Give command
Also we can use ring_give() to have the original behavior
Example:
see"Name: givename
see"Hello
funcringvm_give
see"Mahmoud"
return"Mahmoud"
Output:
Name: Mahmoud
Hello Mahmoud
101.4
Using ring_state_new() and ring_state_mainle() we can run Ring programs from Ring programs
But unlike ring_state_main(), Here we can control when to delete the Ring state!
This is important when we run GUI programs from GUI programs
Because they will share the GUI Library (RingQt), And In this case the caller will call
qApp.Exec()
So the sub program, will not stop and will return to the Main program
Here deleting the State of the sub programs will lead to a problem when we run the sub program events
So keeping the state is important for sub GUI programs hosted in GUI programs.
101.5
The Trace library is updated, In the Debugger at break points we have now the “callstack” command
This command will print the functions call stack.
Example:
load"tracelib.ring"
funcmain
?Hello from main!"
test1()
functest1
?Hello from test1!"
test2()
functest2
?Hello from test2!"
test3()
(continues on next page)
101.4. ring_state_new() and ring_state_mainle() functions 1580

Ring Documentation, Release 1.14
(continued from previous page)
functest3
?Hello from test3!"
breakpoint()
101.6
Ring Notepad comes with the next updates
(1) *.cf extension
(2)
(3)
101.7
The next classes are added to RingQt
(1)
(2)
(3)
(4)
(5)
(6)
(7)
101.6. Better Ring Notepad 1581

Ring Documentation, Release 1.14
(8)
(9)
(10)
(11)
(12)
(13)
(14)
(15)
(16)
(17)
(18)
(19)
(20)
(21)
(22)
(23)
101.8
Ring2EXE is updated to works as expected when we don't have a C/C++ compiler
Where we can distribute applications and get (exe le and ringo le) in this case.
101.9
The library is updated to support extracting les contains sub folders!
101.10
(1)
101.11
(1)
(2)
(3)
(4)
(5)
101.8. Better Ring2EXE 1582

Ring Documentation, Release 1.14
(6)
(7)
(8)
(9)
(10)
(11)
(12)
101.12
Ring 1.7 comes with the RingLibuv extension
Libuv is a multi-platform support library with a focus on asynchronous I/O.
Example (Events Loop):
load"libuv.ring"
counter
idler NULL
funcmain
idler
uv_idle_init(uv_default_loop(), idler)
uv_idle_start(idler,wait()")
?Idling..."
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
uv_loop_close(uv_default_loop());
destroy_uv_idle_t(idler)
funcwait
counter++
ifcounter=
uv_idle_stop(idler)
ok
Output:
Idling...
Example (Server):
load"libuv.ring"
load"objectslib.ring"
?Testing RingLibuv - Server Side - Using Classes"
open_object(:MyServer)
classMyServerfromObjectControllerParent
DEFAULT_PORT
DEFAULT_BACKLOG
(continues on next page)
101.12. RingLibuv Extension 1583

Ring Documentation, Release 1.14
(continued from previous page)
addr
server NULL
client NULL
myloop NULL
funcstart
myloop
server
uv_tcp_init(myloop, server)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_bind(server, addr,)
r
ifr
?Listen error
return1
ok
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(server)
destroy_uv_sockaddr_in(addr)
funcnewconnection
?New Connection"
aPara
nStatus[2]
ifnStatus
?New connection error :
return
ok
client
uv_tcp_init(myloop, client)
ifuv_accept(server, client)
uv_read_start(client, uv_myalloccallback(),
Method(:echo_read))
ok
funcecho_read
aPara
nRead[2]
buf[3]
ifnRead
req
wrbuf
uv_write(req, client, wrbuf,, Method(:echo_write))
?
messagemessage from the server to the client"
buf
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message","char *"))
uv_write(req, client, buf,, Method(:echo_write))
ok
funcecho_write
aPara
req[1]
Output:
101.12. RingLibuv Extension 1584

Ring Documentation, Release 1.14
When we run the client, We will see the message “New Connection”
Then the message “hello from the client”
Testing RingLibuv - Server Side - Using Classes
New Connection
hello from the client
Example (Using Threads):
load"libuv.ring"
load"objectslib.ring"
?Testing RingLibuv - Threads - Using Classes"
open_object(:MyThreads)
classMyThreadsfromObjectControllerParent
funcStart
one_id
two_id
uv_thread_create(one_id, Method(:One))
uv_thread_create(two_id, Method(:Two))
uv_thread_join(one_id)
uv_thread_join(two_id)
destroy_uv_thread_t(one_id)
destroy_uv_thread_t(two_id)
funcone
?Message from the First Thread!"
funcTwo
?Message from the Second Thread!"
Output:
Testing RingLibuv - Threads - Using Classes
Message from the First Thread!
Message from the Second Thread!
For more information about this extension (RingLibuv) check the chapter: Using RingLibuv
101.12. RingLibuv Extension 1585

CHAPTER
TWO
WHAT IS NEW IN RING 1.8?
In this chapter we will learn about the changes and new features in Ring 1.8 release.
102.1
Ring 1.8 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1586

Ring Documentation, Release 1.14
102.2
Ring 1.8 is faster than Ring 1.7
The performance gain is between 10% and 100% based on the application.
Check the 3D samples in this release to get an idea about the current performance.
For more information check the Performance Tips chapter.
102.3
Ring 1.8 comes with Find in les application
102.2. Better Performance 1587

Ring Documentation, Release 1.14
102.4
Ring 1.8 comes with String2Constant application
Using this tool we can convert the source code to be based on constants instead of string literals
Then we can store constants in separate source code les that we can translate to different languages
Where we can have special le for each language, like (English.ring, Arabic.ring and so on)
Using this simple tool, the Form Designer is translated to the Arabic language.
For more information check the Multi-language Applications chapter.
102.4. String2Constant Application 1588

Ring Documentation, Release 1.14
102.5
Ring 1.8 comes with StopWatch application
102.6
Ring 1.8 comes with more 3D Samples
The next screen shot for the Top-Down view - Many levels of cubes sample
102.5. StopWatch Application 1589

Ring Documentation, Release 1.14
The next screen shot for the Camera SampleThe next screen shot for the Camera and background sample
Developer : Azzeddine Remmal
102.6. More 3D Samples 1590

Ring Documentation, Release 1.14
102.7
Ring 1.8 is tested on Manjaro Linux too
Tests by : Iip Rifai
102.7. Compiling on Manjaro Linux 1591

Ring Documentation, Release 1.14
102.8
The class region is the region that comes after the class name and before any method.
Now we can use This in the class region as Self.
Example:
funcmain
o1 newprogram {
test()
}
?
classprogram
this.nameMy Application"
this.version1.0"
?
functest
?Name =
?Version =
Output
My Application
1.0
Name = My Application
Version = 1.0
name: My Application
version: 1.0
Note:When we use braces to change the current active object, Using This we can still point to the class.
Tip:The difference between This and Self is that Self point to the current active object that we can change using
braces.
Remember that in most cases we don't need to use This or Self in the class region
We can write
classprogram name version
Or
classprogram name="My Application"="1.0"
Note:We use This or Self in the class region just to avoid conict with global variables that are dened with the same
name.
102.8. Using This in the class region as Self 1592

Ring Documentation, Release 1.14
102.9
Starting from Ring 1.8 the default value for object attributes is NULL
In Ring, the NULL value is just an empty string or a string that contains “NULL”
We can check for NULL values using the isNULL() function
Example:
oProgram newProgram
?
?
?
?
oProgram { name="My Application"="1.0"
?
?
?
classprogram
name
version
Output:
NULL
NULL
1
1
0
0
name: My Application
version: 1.0
In previous versions of Ring, trying to access the object attribute before assigning a value to it
Will lead to runtime error and you can't check it using isnull()
The only way was assigning a value or using try/catch/end
We changed this behavior so we can have full control in seamless way.
102.10
In Ring 1.8, when the For Loop denes new identier (variable) it will dene it in the local scope.
Example:
x
? # Print 10
test1()
? # Print 10
test2()
? # Print 10
functest1
(continues on next page)
102.9. Default value for object attributes is NULL 1593

Ring Documentation, Release 1.14
(continued from previous page)
forx to5
next
? # Print 6
functest2
list=:5
forxin
next
? # Print NULL (The "For In" loop will kill the reference after the
˓→loop)
Output:
10
6
10
NULL
10
102.11
From Ring 1.0 we can create binary strings and do operations on these strings.
Now in Ring 1.8, we can get individual characters from these strings and merge them together using the `+' operator.
Example:
cStrWelcome"
?[1][2][5]
v[1][2][5]
?
?
c1[1]
?
aList1,2,3]
cStr"
foriteminaList
cStr=
next
?All String"
?
?First Part"
n1[1][2][3][4]
?
?Second Part"
n2[5][6][7][8]
?
?Third Part"
n3[9][10][11][12]
?
?All String"
cString[1][2][3][4]
cStr[5][6][7][8]
cStr[9][10][11][12]
?
(continues on next page)
102.11. Merge binary characters 1594

Ring Documentation, Release 1.14
(continued from previous page)
?[1])
?[2])
Output:
Weo
Weo
3
W
All String
12
First Part
4
Second Part
4 }
Third Part
4
All String
12
1
1
102.12
Developer: Jose Rosado
A class with some of the functions I used in FoxPro
Example:
Load"foxring.ring"
mf newfrFunctions
?-45)
?10-30)
?30-10)
?",
"@! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
?", Null)
Output:
45
20
20
RING IS A GOOD LANGUAGE
Ring is a good language
102.12. FoxRing Library 1595

Ring Documentation, Release 1.14
102.13
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
(13)
102.14
The Cards game is updated and we can play with the Computer
102.13. Better Form Designer 1596

Ring Documentation, Release 1.14
102.15
•
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
•
Tested using
(1)
(2)
(3)
•
102.16
New Option: StaticMethods
Starting from Ring 1.8 the code generator support the staticmethods option.
So the code generator can know that the class doesn't need an object to call the methods.
Example:
<class>
name: QStandardPaths
para: void
nonew
staticmethods
</class>
QString displayName(QStandardPaths::StandardLocation type)
QString findExecutable(QString executableName, QStringList paths))
102.15. Better RingQt 1597

Ring Documentation, Release 1.14
102.17
(1)
(2)
(3)
(4)
Example:
?Start the test!"
pState
ring_state_runcode(pState,"Let us try having an error")
ring_state_delete(pState)
?"
?End of test!"
Output:
Start the test!
Let us try having an error
Line 1 Error (R24) : Using uninitialized variable : x
in file Ring_EmbeddedCode
End of test!
(5)
Example:
see
"
Hello, World!
"
test()
func
#======================#
Test
#======================#
?
"
Hellofromthe Test function
"
Output:
Hello, World!
(continues on next page)
102.17. Better Ring Compiler and VM 1598

Ring Documentation, Release 1.14
(continued from previous page)
Hello from the Test function
(6)
(7)
(8)
102.18
If you have created new extensions for Ring in the C/C++ languages.
You have to rebuild your extension (Generate the DLL le again using Ring 1.8 header les) before usage with Ring
1.8
Because we changed the internal structure of the VM, but no changes to the code are required. just rebuild.
102.18. Notes to extensions creators 1599

CHAPTER
THREE
WHAT IS NEW IN RING 1.9?
In this chapter we will learn about the changes and new features in Ring 1.9 release.
103.1
Ring 1.9 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
103.2
The Gold Magic 800 is a new puzzle game.
Ring 1.9 comes with the Demo Version (18 Levels) and the game source code.
Steam Page (44 Levels) :
We can select the level
1600

Ring Documentation, Release 1.14
The next screen shot for level (1)The Gold Magic 800 Level Editor
103.2. New Game : Gold Magic 800 1601

Ring Documentation, Release 1.14
103.3
The next games are added to Ring Applications
(1)
(2)
(3)
(4)
(5)
The next screen shot for the 2048 game on Android
103.3. More Games 1602

Ring Documentation, Release 1.14
The next screen shot for the Tessera game
103.3. More Games 1603

Ring Documentation, Release 1.14
The next screen shot for the Othello game
103.3. More Games 1604

Ring Documentation, Release 1.14
103.4
(1)
(2)
(3)
(4)
103.4. Better Ring Notepad 1605

Ring Documentation, Release 1.14
103.5
(1)
This function convert a Ring list during the runtime to Ring source code that we can save to source les.
The list may contains strings, numbers or sub lists.
Example:
load"stdlibcore.ring"
aList:10
?
Output:
[
1,2,3,4,5,6,7,8,9,10
]
(2)
Using these functions we can convert between string of bytes and a list of numbers where each item represent the
ASCII code of one byte in the string.
So we may convert a string of bytes to ASCII List then do some operations on the list numbers (Like XOR)
Example:
load"stdlibcore.ring"
cStrMmMm"
aList
(continues on next page)
103.5. Better StdLib 1606

Ring Documentation, Release 1.14
(continued from previous page)
?
cStr2
?
?
Output:
77
109
77
109
MmMm
4
103.6
Using the BigNumber library we can do arithmetic operations on huge numbers.
Example:
load"bignumber.ring"
num162345678901234567891678345123456789" ### Big
num21237894567890123419871236545" ### Small
num364" ### Divide Small
num4765432"
num53" ### Power
?Add big numbers:"
a1 newBigNumber(num1) a1.Print()
a2 newBigNumber(num2) a2.Print()
a3
?Substract big numbers:"
a1 newBigNumber(num1) a1.Print()
a2 newBigNumber(num2) a2.Print()
a3
?Multiply big numbers:"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num2) a2.print()
a3 *a2 a3.print()
?Divide big numbers:"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num2) a2.print()
a3
?Divide big numbers: by very small number"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num3) a2.print()
a3
(continues on next page)
103.6. BigNumber Library 1607

Ring Documentation, Release 1.14
(continued from previous page)
?Power of big number:"
a1 newBigNumber(num1) a1.print()
a2 newBigNumber(num5) a2.print()
a3
Output:
Add big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
62345680139129135781801764994693334
Substract big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
52345687663340000001554925252220244
Multiply big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
77177377243260150103462178714197454736432472780119682305154005
Divide big numbers:
62345678901234567891678345123456789
1237894567890123419871236545
50364288
Divide big numbers: by very small number
62345678901234567891678345123456789
64
974151232831790123307474142554012
Power of big number:
62345678901234567891678345123456789
3
242336636261471172092347146031727004 (Output continue in next line)
371698195628343934238988256152289508 (Output continue in next line)
493964611043228971692389860897069
For more information check the BigNumber Library Chapter in the documentation
103.6. BigNumber Library 1608

Ring Documentation, Release 1.14
103.7
Ring 1.9 provide native support for PostgreSQL database using the RingPostgreSQL Extension.
Example:
load"postgresqllib.ring"
conninfouser=postgres password=sa dbname = mahdb"
exit_nicely funcconn {
PQfinish(conn)
shutdown(1)
}
conn
if(PQstatus(conn)=
fputs(stderr,Connection to database failed:+PQerrorMessage(conn))
callexit_nicely(conn)
ok
res
DROP DATABASE mahdb;
")
ifPQresultStatus(res)=
fputs(stderr,Remove failed:
PQclear(res)
ok
PQclear(res)
resCREATE DATABASE mahdb;")
ifPQresultStatus(res)=
fputs(stderr,Create database failed:
PQclear(res)
ok
res
CREATE TABLE COMPANY (
ID INT PRIMARY KEY NOT ,
NAME TEXT NOT ,
AGE INT NOT ,
ADDRESS CHAR(50),
SALARY REAL );
")
ifPQresultStatus(res)=
fputs(stderr,Create Table failed:
PQclear(res)
ok
PQclear(res)
res
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,Mahmoud,Jeddah,.00
(2,Ahmed,Jeddah,.00
(continues on next page)
103.7. RingPostgreSQL Extension 1609

Ring Documentation, Release 1.14
(continued from previous page)
(3,Mohammed,,Egypt.00
(4,Ibrahim,Egypt,.00
")
ifPQresultStatus(res)=
fputs(stderr,Insert Table failed:
PQclear(res)
ok
PQclear(res)
res
select*fromCOMPANY
")
ifPQresultStatus(res)=
fputs(stderr,Select failed:
PQclear(res)
callexit_nicely(conn)
ok
nFields
fori tonFields
?-1)
next
?" *",60)
fori toPQntuples(res)
forj=1tonFields
seePQgetvalue(res, i-1, j-1)
next
seenl
next
PQclear(res)
PQfinish(conn)
Output:
id
name
age
address
salary
************************************************************
1 Mahmoud 31 Jeddah 10
2 Ahmed 27 Jeddah 20
3 Mohammed 31 Egypt 30
4 Ibrahim 24 Egypt 40
For more information check the PostgreSQL Chapter in the documentation
103.7. RingPostgreSQL Extension 1610

Ring Documentation, Release 1.14
103.8
We created a new project and tutorial to explain how to deploy Ring web applications in the Cloud using Heroku
Demo :
Project :
Heroku Website :
For more information check the Deploying Web Applications In The Cloud chapter in the documentation.
103.9
(1)
•
•
•
•
•
•
•
•
•
103.8. Deploying Web applications in the Cloud 1611

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
(2)
•
•
•
•
The next example for using the QPrintPreviewDialog class
Example:
load"guilib.ring"
newqApp {
win1 newqwidget() {
setwindowtitle("Printer Preview Dialog")
setgeometry(100,100,800,880)
printer1 newqPrinter(0)
show()
oPreview newqPrintPreviewDialog(printer1) {
setParent(win1)
move(10,10)
setPaintrequestedevent("printPreview()")
exec()
}
}
(continues on next page)
103.9. Better RingQt 1612

Ring Documentation, Release 1.14
(continued from previous page)
exec()
}
funcprintPreview
printer1 {
painter newqpainter() {
begin(printer1)
myfont newqfont("Times",50,-1,0)
setfont(myfont)
drawtext(100,100,"Test - Page (1)")
printer1.newpage()
drawtext(100,100,"Test - Page (2)")
printer1.newpage()
myfont2 newqfont("Times",14,-1,0)
setfont(myfont2)
forx to30
drawtext(100,100+(20 *x),"Number :
next
endpaint()
}
}
Screen Shot:
103.9. Better RingQt 1613

Ring Documentation, Release 1.14
103.9. Better RingQt 1614

Ring Documentation, Release 1.14
103.10
The Ring API is updated to include RING_API_RETMANAGEDCPOINTER()
Using RING_API_RETMANAGEDCPOINTER() the Ring extensions written in C/C++ languages can return a man-
aged pointer to Ring. This pointer can be controlled by the Ring VM using reference counting.
This is important to avoid the need to write code that free the unmanaged resources like QPixMap objects in RingQt.
Also the Code Generator for extensions is updated to automatically use RING_API_RETMANAGEDCPOINTER()
based on need.
Syntax:
RING_API_RETMANAGEDCPOINTER(void *pValue,const char *cPointerType,
void (*pFreeFunc)(void *,void*))
For more information about RING_API_RETMANAGEDCPOINTER()
See the “Extension using the C/C++ languages” Chapter in the documentation
103.11
(1)
<loadfile>
This is useful to separate the extension conguraition le to many les
Example:
The le : qt_module_network.cf in the RingQt Extension
<comment>
Module (network)
</comment>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
<loadfile>
(2)
Using this option, the generator will use RING_API_RETMANAGEDCPOINTER() to return the C pointer.
So the Garabage Collector will manage these C pointers.
Example
<class>
name: QFont
para: QString, int, int, bool
(continues on next page)
103.10. Better Memory Management 1615

Ring Documentation, Release 1.14
(continued from previous page)
managed
</class>
103.12
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
(13)
(14)
(15)
(16)
(17)
(18)
(19)
(20)
(21)
(22)
(23)
(24)
(25)
(26)
(27)
(28)
(29)
(30)
(31)
103.12. More Improvements 1616

Ring Documentation, Release 1.14
(32)
(33)
(34)
(35)
103.12. More Improvements 1617

CHAPTER
FOUR
WHAT IS NEW IN RING 1.10?
In this chapter we will learn about the changes and new features in Ring 1.10 release.
104.1
Ring 1.10 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
104.2
Chess Game (2 Players)
1618

Ring Documentation, Release 1.14
104.3
The objective of the game is to clear a rectangular board containing hidden “mines” or bombs without detonating any
of them.
104.3. Minesweeper Game 1619

Ring Documentation, Release 1.14
104.4
Move to every square on the chess board, using only the moves of a knight.
Can you visit every square in just 63 moves?
104.4. Knight Tour Game 1620

Ring Documentation, Release 1.14
104.5
The game is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input.
One interacts with the Game of Life by creating an initial conguration and observing how it evolves, or, for advanced
players, by creating patterns with particular properties.
104.5. Game of Life Game 1621

Ring Documentation, Release 1.14
104.6
Simple “tennis like” game features two paddles and a ball.
The goal is to defeat your opponent once the opponent misses a ball.
104.6. Pong Game 1622

Ring Documentation, Release 1.14
104.7
The Snakes and Ladder Game using Ring Game Engine for 2D Games
104.7. Snakes And Ladder Game 1623

Ring Documentation, Release 1.14
104.8
The next games are added to the application folder
•
•
•
•
The next screen shot for the Sum Puzzle Game
104.8. More Games 1624

Ring Documentation, Release 1.14
104.9
This extension support the Ring programming language in Visual Studio Code
104.9. Ring Extension for Visual Studio Code 1625

Ring Documentation, Release 1.14
104.10
Ring comes with a package manager (RingPM) that we can use to install, update and remove packages.
The Package Manager uses Semantic Versioning to check compatibility between packages
The Package Manager comes with the next options
===========================================================================
Usage : ringpm [command]
Command : search [keywords...]
Command : refresh : Update the Registry (Packages List)
Command : install [ <packagename> [from <UserName>] [branch <branchname>] ]
Command : list [-u : Check updates]
Command : run [packagename]
Command : update <packagename>
Command : remove <packagename>
Command : format : Delete All Packages
Command : new <packagename>
Command : package : Create package in the current folder
===========================================================================
104.10. The Ring Package Manager (RingPM) 1626

Ring Documentation, Release 1.14
104.11
New framework for Ring programming language tests that test the language.
104.12
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
(13)
(14)
104.11. Better Tests 1627

Ring Documentation, Release 1.14
(15)
104.12. More Improvements 1628

CHAPTER
FIVE
WHAT IS NEW IN RING 1.11?
In this chapter we will learn about the changes and new features in Ring 1.11 release.
105.1
Ring 1.11 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
105.2
Ring 1.11 comes with more 3D samples based on Qt3D
•
1629

Ring Documentation, Release 1.14
105.3
It plays the - Must Jump - version of Checkers, The International Rules
It handles various invalid moves, invalid jumps, and must jumps.
The squares are colored to reect errors.
The Sqaures are colored to show source and destination of the move or jump.
105.3. Checkers Game 1630

Ring Documentation, Release 1.14
105.4
A quick implementation for the Sokoban Game
Developed using Ring Game Engine for 2D Games in 2 hours (Less than 300 lines of code)
105.4. Sokoban Game 1631

Ring Documentation, Release 1.14
105.5
A quick implementation for the Maze Game
Developed using Ring Game Engine for 2D Games (Around 100 lines of code)
Also the game comes with a level designer (Developed in 10 minutes, 37 Lines of code)
105.5. Maze Game 1632

Ring Documentation, Release 1.14
105.6
A quick implementation for the Snake Game
Developed using Ring Game Engine for 2D Games (Around 200 lines of code)
105.6. Snake Game 1633

Ring Documentation, Release 1.14
105.7
Fill a 9 x 9 grid with digits so that each column, each row, and each of the nine 3 x 3 subgrids that compose the grid
contain all of the digits from 1 to 9.
105.7. Sudoku Game 1634

Ring Documentation, Release 1.14
105.7. Sudoku Game 1635

Ring Documentation, Release 1.14
105.8
105.9
105.8. Desktop Screen Shot Application 1636

Ring Documentation, Release 1.14
105.10
Ring 1.11 comes with new extension to support the RayLib game programming library
Example:
load"raylib.ring"
screenWidth
screenHeight
InitWindow(screenWidth, screenHeight,raylib [core] example - basic window")
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RED)
DrawText("Congrats! You created your first window!",,,, WHITE)
EndDrawing()
end
CloseWindow()
Output:
Example:
load"raylib.ring"
screenWidth
(continues on next page)
105.10. RingRayLib Extension 1637

Ring Documentation, Release 1.14
(continued from previous page)
screenHeight
InitWindow(screenWidth, screenHeight,raylib [shapes] example - basic shapes drawing
˓→")
SetTargetFPS(60)
while!WindowShouldClose()
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText("some basic shapes available on raylib",,,, DARKGRAY)
DrawCircle(screenWidth/4,,, DARKBLUE)
DrawRectangle(screenWidth/4 *2,,,, RED)
DrawRectangleLines(screenWidth/4 *2,,,, ORANGE)
DrawRectangleGradientH(screenWidth/4 *2,,,, MAROON, GOLD)
DrawTriangle(Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,), VIOLET)
DrawPoly(Vector2(screenWidth/4 *3,),,,, BROWN)
DrawCircleGradient(screenWidth/4,,, GREEN, SKYBLUE)
DrawLine(18,, screenWidth,, BLACK)
DrawCircleLines(screenWidth/4,,, DARKBLUE)
DrawTriangleLines(Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,),
Vector2(screenWidth/4 *3,), DARKBLUE)
EndDrawing()
end
CloseWindow()
Output:
105.10. RingRayLib Extension 1638

Ring Documentation, Release 1.14
105.11
Ring 1.11 comes with the ZeroLib library that contains classes for Lists and Strings where the index starts from 0.
Example:
load"zerolib.ring"
?Using List - Index start from 0"
List=1,2,3]
List.Add(4)
List.Add(5)
?List[0]
?List[1]
?List[2]
?List[3]
?List[4]
nIndex List.find(2)
?Find(2) =
List.delete(0)
?After deleting the first item : List[0]"
?Now List[0] = List[0]
?Using String - Index start from 0"
String=Welcome"
?String[0]
?String[1]
?String[2]
?String[3]
(continues on next page)
105.11. ZeroLib Library 1639

Ring Documentation, Release 1.14
(continued from previous page)
?String[4]
?String[5]
?String[6]
Output:
UsingList- from0
1
2
3
4
5
Find(2)
After deleting the first item : List[0]
NowList[0]
UsingString- from0
W
e
l
c
o
m
e
105.12
The next functions are added to the StdLib
•
•
•
Example:
load"stdlibcore.ring"
?Using the IsListContainsItems() function"
aList1a":"z"
aList2:h,:l,:p,:u]
?
?Using the IsBetween() function"
?1,3,4)
?4,1,6)
?Using the TimeInfo() function"
?
?
?
?
Output:
Using the IsListContainsItems() function
1
Using the IsBetween() function
(continues on next page)
105.12. StdLib - More Functions 1640

Ring Documentation, Release 1.14
(continued from previous page)
0
1
Using the TimeInfo() function
05/24/19
2019
15:30:33
03
For more information about these functions, see the StdLib functions chapter.
105.13
•
•
•
–compare()
–contains()
–indexOf()
–insert()
–isRightToLeft()
–remove()
–repeated()
–replace()
–startsWith()
–endsWith()
–toHtmlEscaped()
–clear()
–isnull()
–resize()
–ll()
•
•
–QQuickView Class
–QPrintDialog Class
–QAxWidget2 Class
–QTextToSpeech Class
–QGraphicsView Class
–QAbstractAspect Class
–QNode Class
105.13. Better RingQt 1641

Ring Documentation, Release 1.14
–QEntity Class
–QTransform Class
–QAspectEngine Class
–QTorusMesh Class
–QConeMesh Class
–QCylinderMesh Class
–QCuboidMesh Class
–QPlaneMesh Class
–QSphereMesh Class
–QPhongMaterial Class
–QForwardRenderer Class
–Qt3DWindow Class
–QAbstractCameraController Class
–QFirstPersonCameraController Class
–QTextureMaterial Class
–QExtrudedTextMesh Class
–QText2DEntity Class
–QSkyBoxEntity Class
–QConeGeometry Class
–QOrbitCameraController Class
–QDiffuseSpecularMaterial Class
–QGoochMaterial Class
–QMetalroughMaterial Class
–MorphPhongMaterial Class
–QPervertexColorMaterial Class
–QInputAspect Class
–QFrameAction Class
–QLogicAspect Class
–QCamera Class
–QCameraLens Class
–QMesh Class
–QTechnique Class
–QMaterial Class
–QEffect Class
–QRenderPass Class
–QSceneLoader Class
105.13. Better RingQt 1642

Ring Documentation, Release 1.14
–QPointLight Class
–QRenderAspect Class
–QTextureLoader Class
–QObjectPicker Class
–QCameraSelector Class
–QCullFace Class
–QDepthTest Class
–QViewPort Class
105.14
Ring 1.11 is faster than Ring 1.10
The performance gain is between 10% and 30% based on the application.
105.15
The next chapters are added to the documentation
•
•
•
•
105.16
•New Samples
–samples/other/ModuloTimesTableCircle folder
–samples/other/saveimage folder
–samples/other/UsingQML folder
–samples/other/myguicontrol.ring
–samples/other/qcalendarwidget.ring
–samples/other/qcalendarwidget2.ring
–samples/other/sudoku-KL02.ring
–samples/other/sudoku-KL02-longproblem.ring
–samples/other/zerobasedlist.ring
–ringlibs/gameengine/lesson17.ring (Using Buttons)
–samples/other/SQLTutorial/SQL-Tutorial.ring
–samples/other/DrawFourier/AA-Draw-Fourier.ring
105.14. Better Performance 1643

Ring Documentation, Release 1.14
–samples/other/SmartPhoneEmulator/ejemploKey.ring
–samples/other/DiscreteFourierTransform/DiscreteFourierTransform.ring
–samples/other/phonedatabase/PhoneDatabase.ring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
105.16. More Improvements 1644

CHAPTER
SIX
WHAT IS NEW IN RING 1.12?
In this chapter we will learn about the changes and new features in Ring 1.12 release.
106.1
Ring 1.12 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
106.2
An implementation for the Go Game
1645

Ring Documentation, Release 1.14
106.3
Simple application for displaying the ASCII table
106.3. ASCII Table application 1646

Ring Documentation, Release 1.14
106.4
Simple application for calculating the BMI
106.5
The Calendar for Year 2020
106.4. BMI Calculator application 1647

Ring Documentation, Release 1.14
106.6
The Julian Day Calendar application
106.6. Julian Day Calendar application 1648

Ring Documentation, Release 1.14
106.7
Folder : ring/samples/other/number2words
106.7. Tutorial: Number to Words 1649

Ring Documentation, Release 1.14
106.8
Ring 1.12 comes with the Load Again command
Using this command we can load the Ring source le which contains constants more than one time.
This is useful when using Ring source les for translations through global constants.
Example:
The next function is part from a project which support Arabic and English languages
The les english.ring and arabic.ring contains constants for translation
One of these les is loaded in the start of the program
Loading the same le again using the (Load) command is not possible
Because the (Load) command load the same source le only for the rst time and ignore next times.
So we have to use the (Load Again) command.
Where we can use these les again during the runtime as in the next code
106.8. Load Again Command 1650

Ring Documentation, Release 1.14
funcsetLang nLanguage
ifC_ENV_DEFAULT_LANG
return
ok
C_ENV_DEFAULT_LANG
# Change the language
switchnLanguage
onC_TRANSLATION_ENGLISH
load "translation/english.ring"
onC_TRANSLATION_ARABIC
load "translation/arabic.ring"
off
106.9
Using the ring_state_letokens() function we can get all the tokens in the ring source code le.
C_FILENAMEtest_tokens.ring"
C_WIDTH
# write the file
write(C_FILENAME,
see"Hello, World!"
?*2+3
NameRing"
?
)
# Token Type
C_KEYWORD
C_OPERATOR
C_LITERAL
C_NUMBER
C_IDENTIFIER
C_ENDLINE
# Keywords List
aKEYWORDS"IF","TO","OR","AND","NOT","FOR","NEW","FUNC",
"FROM","NEXT","LOAD","ELSE","SEE","WHILE","OK","CLASS","RETURN","BUT",
"END","GIVE","BYE","EXIT","TRY","CATCH","DONE","SWITCH","ON","OTHER","OFF",
"IN","LOOP","PACKAGE","IMPORT","PRIVATE","STEP","DO","AGAIN","CALL","ELSEIF",
"PUT","GET","CASE","DEF","ENDFUNC","ENDCLASS","ENDPACKAGE",
"CHANGERINGKEYWORD","CHANGERINGOPERATOR","LOADSYNTAX"]
pState
aList
PrintTokens(aList)
ring_state_delete(pState)
funcPrintTokens aList
foraTokeninaList
switchaToken[1]
onC_KEYWORD
?"Keyword",C_WIDTH):[0+aToken[2]]
onC_OPERATOR
(continues on next page)
106.9. ring_state_letokens() function 1651

Ring Documentation, Release 1.14
(continued from previous page)
?"Operator",C_WIDTH):[2]
onC_LITERAL
?"Literal",C_WIDTH):[2]
onC_NUMBER
?"Number",C_WIDTH):[2]
onC_IDENTIFIER
?"Identifier",C_WIDTH):[2]
onC_ENDLINE
?EndLine"
off
next
funcWidth cText,nWidth
returncText+copy(",nWidth-len(cText))
Output:
EndLine
Keyword : SEE
Literal : Hello, World!
EndLine
Operator : ?
Number : 3
Operator : *
Number : 2
Operator : +
Number : 3
EndLine
Identifier : name
Operator : =
Literal : Ring
EndLine
Operator : ?
Identifier : name
EndLine
106.10
We can generate embedded object le (C source code) from the source code le (*.ring) using -geo option
Command:
ring test.ringgeo
This command will generate at least three les
test.c
ringappcode.c
ringappcode.h
More les could be generated based on the project size
The generated les will pass the byte code to Ring VM to be executed
106.10. Generate Embedded Ring Object File 1652

Ring Documentation, Release 1.14
106.11
More Samples are added to RingRayLib
•
•
•
•
•
•
•
•
•
•
•
Screen Shot:
106.11. Better RingRayLib 1653

Ring Documentation, Release 1.14
106.12
•New Samples
–ring/samples/other/Hex2UTF8.ring
–ring/samples/other/CalmoSoftPrimesTable.ring
–ring/samples/other/CalmoSoftTicTacToeGame.ring
–ring/samples/other/CalmoSoftSimpleGoGame.ring
–ring/samples/other/arabicmysql.ring
–ring/samples/other/CalmoSoftExtraCube.ring
–ring/samples/other/DynamicCode/anonfunc.ring
–ring/samples/other/DynamicCode/deletethisle.ring
–ring/samples/other/DynamicCode/modifythisle.ring
–ring/samples/other/changesyntax/ArabicDemo.ring
–ring/samples/other/changesyntax/EnglishDemo.ring
–ring/samples/other/changesyntax/ChangeKeywordsArabic.ring
–ring/samples/other/changesyntax/ChangeKeywordsEnglish.ring
–ring/samples/other/changesyntax/pascal.ring
–ring/samples/other/hijridate.ring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
106.12. More Improvements 1654

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
106.12. More Improvements 1655

CHAPTER
SEVEN
WHAT IS NEW IN RING 1.13?
In this chapter we will learn about the changes and new features in Ring 1.13 release.
107.1
Ring 1.13 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1656

Ring Documentation, Release 1.14
107.2
Apress: Beginning Ring Programming (From Novice to Professional)
URL:
Gain a gentle introduction to the world of Ring programming with clarity as a rst concern using a lot of practical
examples.
What You Will Learn
•
•
•
•
107.2. New Book by Apress 1657

Ring Documentation, Release 1.14
107.3
Ring support distributing applications for WebAssembly (Using Qt for WebAssembly)
•
•
•
•
•
•
107.4
Ring 1.13 provides better support for threads
(1)
(2)
(3)
107.3. Ring for WebAssembly 1658

Ring Documentation, Release 1.14
107.5
An implementation for the Laser Game
107.5. Laser Game 1659

Ring Documentation, Release 1.14
107.6
An implementation for the Magic Balls Game
107.6. Magic Balls Game 1660

Ring Documentation, Release 1.14
107.7
See if you can collect the required amount of money by opening boxes!
107.8
An implementation for the Matching Game
107.7. Money Boxes Game 1661

Ring Documentation, Release 1.14
107.9
An implementation for the Pairs Game
107.9. Pairs Game 1662

Ring Documentation, Release 1.14
107.10
An implementation for the Word Game
107.10. Word Game 1663

Ring Documentation, Release 1.14
107.11
An implementation for the Tetris Game
Features
•
•
•
•
cally)
107.11. Tetris Game 1664

Ring Documentation, Release 1.14
107.12
Escape from the Snake and collect the Stars to prevent it from growing!
107.12. Escape Game 1665

Ring Documentation, Release 1.14
107.13
URL (YouTube):
The course samples are added to ring/samples/UsingArabic/HassounaCourse folder
The Rockets sample
107.13. Hassouna Course Samples 1666

Ring Documentation, Release 1.14
107.14
URL:
Screen Shot:
107.14. Ring support in SpaceVim 1667

Ring Documentation, Release 1.14
107.15
(1)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
107.15. Better RingQt 1668

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
(2)
This application is used for preparing Qt classes for the Ring Code Generator
Then using the Ring Code Generator we generate RingQt classes
The application user interface is updated for better productivity!
(3)
107.15. Better RingQt 1669

Ring Documentation, Release 1.14
(4)
107.16
(1)
(2)
(3)
•
•
•
•
•
•
•
•
107.16. Better RingRayLib 1670

Ring Documentation, Release 1.14
107.17
New extension support the stb_image library
Example:
# Load the library
load"stbimage.ring"
# Image Information
width=0=0=0
# Ring will Free cData automatically in the end of the program
cData"ring.jpg",:width,:height,:channels,STBI_rgb)
# Display the output
?Size (bytes):
?Width :
?Height:
?Channels:
Output:
Size (bytes):
Width :
Height:
Channels:
107.17. RingStbImage Extension 1671

Ring Documentation, Release 1.14
107.18
The next functions are added to the Low Level functions
For more information see the Low Level Functions chapter in the documentation
setpointer(pointer,nNewAddress)
getpointer(pointer)-->
pointer2string(pointer,nStart,nCount)-->
memcpy(pDestinationPointer,cSourceString,nSize)
107.19
We have better organization for the project folders and source code les
(1)
Machine
(2)
folders)
(3)
(4)
(5)
107.20
•More Applications
–Towers of Hanoi
–Questions Game
–Money Case Game
–Rock Paper Scissors Game
–Lottery Game
–Nim Game
–Eight Queens Game
–Typing Quiz
–Pong 2 Game
–Space Shooter Game
•More Samples
–ring/samples/Language/HelloWorld folder
–ring/samples/Language/ChangeIsNULL folder
–ring/samples/Language/Console/customsee.ring
–ring/samples/Language/Numbers/decimalscount.ring
107.18. More Low Level Functions 1672

Ring Documentation, Release 1.14
–ring/samples/Language/EvalInScope/swap.ring
–ring/samples/Language/EvalInScope/global.ring
–ring/samples/Language/EvalInScope/enum.ring
–ring/samples/Language/Endian/endian.ring
–ring/samples/Language/VariablePointer/varptr4.ring
–ring/samples/Language/VariablePointer/varptr5.ring
–ring/samples/Language/DebugCode folder
–ring/samples/Language/ClassMethods folder
–ring/samples/Language/Lists/CheckHashTableAttribute.ring
–ring/samples/Language/RingFileTokens folder (Ring Compiler - Scanner Output)
–ring/samples/ProblemSolving/Fib folder
–ring/samples/ProblemSolving/ArrayPathDest/solveArrayPathDest.ring
–ring/samples/ProblemSolving/PegSolitaire/peg-soli.ring
–ring/samples/General/RosettaCode/uniquecharacters.ring
–ring/samples/General/RosettaCode/similarcharacters.ring
–ring/samples/General/RandomLatinSquares folder
–ring/samples/General/FactorialRecursion folder
–ring/samples/UsingArabic/RightToLeft folder (Set Layout Direction)
–ring/samples/UsingWebLib/Unicode folder
–ring/samples/UsingQt/InputMask folder
–ring/samples/UsingQt/PlayGif folder
–ring/samples/UsingQt/TableWidget folder
–ring/samples/UsingQt/ButtonSizeInLayout folder
–ring/samples/UsingQt/DateTimeEditFormat folder (Date Picker Control)
–ring/samples/UsingQML/sample10 folder (Charts Samples)
–ring/samples/UsingQML/sample11 folder (Data Visualization Samples)
–ring/samples/UsingQtWASM/colordialog folder
–ring/samples/UsingQtWASM/fontdialog folder
–ring/samples/UsingQtWASM/ledialog folder
–ring/samples/UsingQtWASM/lecontent folder (Download/Upload Files)
–ring/samples/UsingRayLib/more/ex4_levelsofcubes.ring
–ring/samples/UsingOpenGL/cubeongpu/cubeongpu.ring
–ring/samples/UsingOpenGL/cubeongpu2/cubeongpu.ring
•
•
•
107.20. More Improvements 1673

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
107.20. More Improvements 1674

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
107.20. More Improvements 1675

CHAPTER
EIGHT
WHAT IS NEW IN RING 1.14?
In this chapter we will learn about the changes and new features in Ring 1.14 release.
108.1
Ring 1.14 comes with the next features!
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1676

Ring Documentation, Release 1.14
108.2
A web application that uses the WebLib library and PostgreSQL database
Screen Shots:
108.2. MyCoffee (Web Application) 1677

Ring Documentation, Release 1.14
108.3
Starting from lesson 301, the Hassouna Course provides lessons about web development.
These lessons uses the WebLib library for Back-end web development.
Special YouTube playlist for these lessons:
•
The samples are added to this folder:
•
Screen Shot:
•
108.3. Web Development Samples 1678

Ring Documentation, Release 1.14
108.4
The next samples are added to the samples folder
•
•
•
•
•
•
Screen Shots:
108.4. More Samples 1679

Ring Documentation, Release 1.14
108.4. More Samples 1680

Ring Documentation, Release 1.14
108.5
An application that uses the Erlang B Formula (Circuit Switching Systems)
108.5. Erlang B Formula 1681

Ring Documentation, Release 1.14
108.6
An application that uses SQLite and TableWidget
The Use Interface is provided in Arabic, English & French
108.6. Customers Form 1682

Ring Documentation, Release 1.14
108.7
This extension provides support for Tilengine - The 2D retro graphics engine with raster effects
Example:
load"tilengine.ring"
TLN_Init(400,,,,)
TLN_SetLoadPath("assets\sonic")
foreground"Sonic_md_fg1.tmx", NULL)
TLN_SetLayerTilemap(0, foreground)
TLN_CreateWindow(NULL,)
whileTLN_ProcessWindow()
TLN_DrawFrame(0)
end
TLN_DeleteTilemap(foreground)
TLN_Deinit()
108.7. RingTilengine Extension 1683

Ring Documentation, Release 1.14
Screen Shots:
108.7. RingTilengine Extension 1684

Ring Documentation, Release 1.14
108.7. RingTilengine Extension 1685

Ring Documentation, Release 1.14
108.8
This extension provides complete support for Libui
Using this extension we can develop and distribute lightweight GUI Applications using Ring (Less than 1 MB)
Runtime les and their size
•
•
•
•
•
Example:
load"libui.ring"
oWindowSay Hello",,, True)
uiWindowOnClosing(oWindow,"closeApp()")
lbl1"Name:)
text1
btn1"SayHello")
uiButtonOnClicked(btn1,"sayHello()")
btn2"Close")
uiButtonOnClicked(btn2,"closeApp()")
lbl2"")
g) uiWindowSetChild(oWindow, g)
uiGridAppend(g, lbl1,,,,,, uiAlignCenter,, uiAlignCenter)
uiGridAppend(g, text1,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, btn1,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, btn2,,,,,, uiAlignFill,, uiAlignFill)
uiGridAppend(g, lbl2,,,,,, uiAlignCenter,, uiAlignCenter)
uiControlShow( oWindow )
uiMain()
funcsayHello
uiLabelSetText(lbl2,"Hello
funccloseApp
uiQuit()
Screen Shots:
108.8. RingLibui Extension 1686

Ring Documentation, Release 1.14
108.8. RingLibui Extension 1687

Ring Documentation, Release 1.14
108.8. RingLibui Extension 1688

Ring Documentation, Release 1.14
108.8. RingLibui Extension 1689

Ring Documentation, Release 1.14
108.9
In Ring, We have sockets using different extensions like RingQt, RingLibuv and RingLibSDL
In this release we provide a special extension for sockets
This will be useful if your application doesn't use the previous libraries
Example (Server Code)
# TCP SERVER
load"sockets.ring"
sock0)
bind(sock,"127.0.0.1",5050)
listen(sock,5)
ns
send(ns,"Hello Client")
msg1024)
?Client Say >>
close(sock)
?Socket connection closed"
Example (Client Code)
# TCP Client
load"sockets.ring"
sock
connect(sock,"127.0.0.1",5050)
send(sock,"Hello Server")
msg1024)
?Server Say >>
close(sock)
?Socket connection closed"
108.10
In Ring, We have threads using different extensions like RingQt, RingLibuv and RingAllegro
In this release we provide a special extension for threads
This will be useful if your application doesn't use the previous libraries
Example:
load"threads.ring"
funcmain
nThreads
aList list(nThreads)
(continues on next page)
108.9. RingSockets Extension 1690

Ring Documentation, Release 1.14
(continued from previous page)
forx=1tonThreads
aList[x]
thrd_create(aList[x],"Hello("+x+")")
next
forx=1tonThreads
res=
thrd_join(aList[x],:res)
next
?Done
shutdown()
funcHello x
forr=1to100
?Message from the Hello("+x+") function"
next
108.11
The next functions are added to the RingOpenSSL extension
These functions compute the hash of large les/data without the need to load all of the content in a single string.
md5init() -> MD5_CTX
md5update (MD5_CTX, string) -> 1 for success or 0 for failure
md5final (MD5_CTX) -> string
sha1init() -> SHA_CTX
sha1update (SHA_CTX, string) -> 1 for success or 0 for failure
sha1final (SHA_CTX) -> string
sha224init() -> SHA224_CTX
sha224update (SHA224_CTX, string) -> 1 for success or 0 for failure
sha224final (SHA224_CTX) -> string
sha256init() -> SHA256_CTX
sha256update (SHA256_CTX, string) -> 1 for success or 0 for failure
sha256final (SHA256_CTX) -> string
sha384init() -> SHA384_CTX
sha384update (SHA384_CTX, string) -> 1 for success or 0 for failure
sha384final (SHA384_CTX) -> string
sha512init() -> SHA512_CTX
sha512update (SHA512_CTX, string) -> 1 for success or 0 for failure
sha512final (SHA512_CTX) -> string
108.11. Better RingOpenSSL 1691

Ring Documentation, Release 1.14
108.12
•
DirExists(cDirPath) ---> returns 1 if the directory exists
•
GetPathType(cPath) ---> 0 if the path doesnt exists
1 if it corresponds to existing file
2 if it corresponds to existing directory
-1 if the path exists but has
an unknown type (e.g. a pipe)
•
We can set environment variables using the SysSet() function
SysSet(cVariable, cValue) ---> Returns 1 for success and return 0 for failure
•
We can delete an environment variables using the SysUnset() function
SysUnset(cVariable) ---> Returns 1 for success and return 0 for failure
•
We can detect the architecture of the Ring executable using the GetArch() function
Syntax:
GetArch() ---> cString (The name of the architecture of the Ring executable)
Example:
switchgetarch()
on"x86"
?x86 32bit architecture"
on"x64"
?x64 64bit architecture"
on"arm64"
?ARM64 64bit architecture"
on"arm"
?ARM 32bit architecture"
other
?Unknown architecture"
off
•
We can detect the number of processors using the NofProcessors() Function
Syntax:
NofProcessors() ---> nProcessors
Example:
108.12. More Functions 1692

Ring Documentation, Release 1.14
?
108.13
•
The functions is updated to support calculating the logarithm to any base
Syntax:
Log(nNumber) --> logarithm of nNumber to the base of e
Log(nNumber,nBase) --> logarithm of nNumber to the base of nBase
Example:
?10) # 2.30
?2) # 0.69
?10,10) # 1
?2,2) # 1
?100,10) # 2
108.14
•
Example:
load"openssllib.ring"
f"rb")
h
while
s)
ifisstring(s)
SHA256Update(h, s)
else
exit
ok
end
digest
fclose(f)
?
Output:
4e677154639dae3baa048ce5ae0b04b63bcd33316e2d2041297dcee85604d778
•
Example:
t1
testMy Ring"
forx to20000
(continues on next page)
108.13. Better Functions 1693

Ring Documentation, Release 1.14
(continued from previous page)
test=
next
?Time :-t1)/clockspersecond())"
Output:
Time : 0.01 seconds
•
108.15
(1)
Example:
x
? # 16
x
? # 255
x
? # 10
? # 65535
? # 10+1 = 11
(2)
Example:
c
fori to13
c*=
next
?c =
Output:
c = 9.
˓→999999999999862032924046117813879019544782068185773946275755888189234614925384380788550958e+209
(3)
Example:
c1
fori to13
c1*=
next
s string(c1)c1 =
c2c2 =
?c2 - c1 =
str1-2222044646462"
(continues on next page)
108.15. Better Handling For Numbers 1694

Ring Documentation, Release 1.14
(continued from previous page)
c
str2 String(c)
ifstr1
?Strings Identical"
else
?Strings Mismatch!"
ok
Output:
c1 = 9.
˓→999999999999862032924046117813879019544782068185773946275755888189234614925384380788550958e+209
c2 = 9.
˓→999999999999862032924046117813879019544782068185773946275755888189234614925384380788550958e+209
c2 - c1 = 0
Strings Identical
108.16
Usage:
ringcloc <application_folder_path>
Example(1):
ringcloc c:ing oolsingnotepad
Output:
47 text files.
47 unique files.
11 files ignored.
github.com/AlDanial/cloc v 1.88 T=1.18 s (39.0 files/s, 3212.2 lines/s)
-----------------------------------------------------------------------------------
Language files blank comment code
-----------------------------------------------------------------------------------
Ring 33 273 139 3186
Bourne Shell 4 22 9 88
DOS Batch 4 3 7 20
INI 1 0 0 15
C 1 0 1 10
Markdown 2 4 0 8
Windows Resource File 1 0 0 1
-----------------------------------------------------------------------------------
SUM: 46 302 156 3328
-----------------------------------------------------------------------------------
Example(2):
ringcloc c:ing oolsormdesigner
Output:
108.16. Using CLOC (Count Lines of Code) 1695

Ring Documentation, Release 1.14
54 text files.
54 unique files.
13 files ignored.
github.com/AlDanial/cloc v 1.88 T=1.54 s (34.5 files/s, 7122.4 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Ring 52 1306 567 9071
Markdown 1 5 0 7
-------------------------------------------------------------------------------
SUM: 53 1311 567 9078
-------------------------------------------------------------------------------
108.17
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
108.17. More Improvements 1696

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
108.17. More Improvements 1697

CHAPTER
NINE
USING OTHER CODE EDITORS
In the Ring/Tools/Editors folder you will nd extensions for the next editors
•
•
•
•
•
•
•
•
109.1
Folder : ring/tools/editors/notepad_plus_plus
•
•
•
•
• Ring.xml
•
•
1698

Ring Documentation, Release 1.14
109.2
Folder : ring/tools/editors/geany
•
•
•
•
•
109.2. Using Geany 1699

Ring Documentation, Release 1.14
109.3
Folder : ring/tools/editors/atom
Just Copy the folder atom-language-ring to the next path
"C:\Users\{UserName}\.atom\Packages"
109.3. Using Atom 1700

Ring Documentation, Release 1.14
109.4
Folder : ring/tools/editors/sublime text 2
In the folder Sublime_Text_2 you will nd the next three les
1 - ring.json-tmlanguage
2 - ring.sublime-build
3 - ring.tmlanguage
Just Copy the les to the next path
"C:\Users\{UserName}\AppData\Roaming\Sublime Text 2\Packages\User\"
The le ring.sublime-build includes the next line
"cmd": ["B:ingining.exe","$file"],
You can modify it according to the ring.exe path in your machine
109.4. Using Sublime Text 2 1701

Ring Documentation, Release 1.14
109.5
Folder : ring/tools/editors/visualstudio
Check the ReadMe le for installation instructions.109.5. Using Visual Studio IDE 1702

Ring Documentation, Release 1.14
109.6
Folder : ring/tools/editors/emacs
Check the ReadMe le for installation instructions.
Screen Shot:
109.7
Folder : ring/tools/editors/vscode
Check the ReadMe le for installation instructions.
Screen Shot:
109.6. Using Emacs Editor 1703

Ring Documentation, Release 1.14
109.8
URL:
Screen Shot:
109.8. SpaceVim 1704

CHAPTER
FREQUENTLY ASKED QUESTIONS (FAQ)
110.1
The language comes with better support for natural language programming and declarative programming. The inno-
vation comes in supporting these paradigms with new practical techniques on the top of object-oriented programming
and functional programming. Ring provides the programmers with the tools required to build a natural language like
Supernova or a declarative language like REBOL and QML without the need to know anything about (compilers and
parsing). You get the language constructs ready for use to create domain-specic languages in a fraction of time.
Take a look at the Supernova programming language, in this language you can type: (I want window and the window
title is hello world.) and it will create a GUI window with “Hello, World!” as the window title. When I created
Supernova language in 2010, i discovered that using the natural code can be (similar to English and without limits and
we can use the power of human language in programming) but to implement that you need a new language that has:
(1)
(2)
(3)
So we can get a system that can increase ease of use and productivity to the maximum level.
So I created Ring because it was the best way to achieve this goal.
Supernova was just a test of the idea, it helped getting a better view of the advantages and the disadvantages of the idea.
And After testing the new ideas you are provided with something practical. So now we have Ring after Supernova.
A story that is maybe similar to having Python after ABC.Where Python avoids the problems of ABC, but keeps the
advantages of ABC. Also, Ring learns from Ruby and ROR's story. The language power could appear in frameworks
better than the direct usage as a general purpose language. Also Ring comes with a clear goal/motivation; (Creating a
new version of the PWCT Software) something that was learned from the design the C language in a certain way to
create the Unix Operating System. In other words, you have a goal that directs you in each design decision.
You will understand the value of our decisions once you start trying to solve the problem that we will use Ring to solve.
The questions is: could you enable any one in the world without knowledge about computer programming concepts
to create very powerful software? Scientically the answer is (visual Programming) and (natural Programming). In
practice we are still away from switching to these paradigms without introducing other problems. Ring is designed
to solve this problem. It is designed to provide natural programming in a practical way. And to create a powerful
visual programming tool. Ring is designed to be a new world of programming after 10 years of research in visual
programming and natural languages.
The Ring Programming Language (Compiler+VM) is developed 100% using visual programming without writing a
single line of code. I used my tool (Programming Without Coding Technology) to design everything and get the C
code generated for me.
Advantages ?
(1)
(2)
1705

Ring Documentation, Release 1.14
(3)
(4)
Using my experience in using visual programming for 10 years and natural programming for 5 years, I designed Ring
to move the knowledge to mainstream programmers by providing a practical language that supports these ideas.
I agree that each programmer/developer has the freedom to form his opinions about any software including program-
ming languages. Ring is not an exception but you may miss the idea behind the language. It is innovative and may
help you to think differently about how to solve your problems. Maybe this is not clear to many programmers because
It is a practical language and includes many features known to programmers and when a programmer looks at the
language they maight think that nothing new because it's familiar. I created Ring to solve problems in a different way.
Where I will start programming just by describing the software using new natural interfaces that I will implement later
when I move from the design stage to the implementation stage. (I don't determine the time to switch between stages,
You are free to use Agile methods). Since Ring is a new language you have 3 options:
(1)
(2)
(3)
Summary:
•
Once we nish PWCT 2.0 we will have good and large software developed using Ring.
•
we have a plan to present a new paradigm for network programming and concurrency. We tested this new paradigm
through simple prototypes during the last years and we will integrate it with Ring in future releases.
110.2
We have the next architecture
(1)
(2)
(3)
ring/extensions
(4)
(5)
The extensions are just dynamic libraries (DLL, So, Dylib) You can update the extensions without the need to update
your code.
Folder (ring/extensions/libdepwin) ====> C libraries used for building Ring Extensions (written in C) on Windows
platform
Folder (ring/libraries) ====> Ring libraries written in Ring itself (StdLib, WebLib, GameEngine, etc)
Folder (ring/language/visualsrc) ====> The Visual Source Code of the Ring Compiler & Ring VM developed using
Programming Without Coding Technology (PWCT)
We use the term Ring Library —> When the library code is written in Ring We use the term Ring Extension —> When
the library code is Written in C or C++
110.2. What is the Ring Architecture? 1706

Ring Documentation, Release 1.14
110.3
(1)
Also we get Temp. memory for this function. Inside this temp. memory we store temp. lists
All of this will be deleted directly after the end of the function call (end of scope)
(2)
2.1 Wait until the end of the function scope
2.2 Use the Assignment operator
2.3 Use callgc() function (delete temp. lists only)
(3)
In 90% of cases, the Escape Analysis is used so we don't waste time in running the garbage collector We directly know
what will be deleted and what will remain in the memory.
https://en.wikipedia.org/wiki/Escape_analysis
In 10% of cases (or less than that) Ring may use Reference Counting.
For example when we pass a list and sub list to a function Ring will pass the lists by reference, but what will happens
if we deleted the Parent List? In this case, the Sub List will use reference counting, and when deleting the Parent List,
it will stay in memory until the end of the function.
Remember that Ring encourage us to avoid using references, and the Assignment Operator will copy lists by value,
so Ring usage of reference counting is very limited to special cases and in most cases the Escape Analysis is enough
which is very fast.
Starting from Ring 1.9 we extended the Reference Counting support to Ring Extensions and low level C pointers. So
we don't have to care about using fclose() when we use fopen() for example. and the same for other extensions like
RingODBC, RingSQLite, RingMySQL, RingQt, etc.
All of the allocated resources will be cleaned by the Garbage Collector when we nish using it (when we lost the last
reference).
110.4
(1)
Ring is 8-bit clean, Each character in the string is 8 bits (1 byte)
So these functions (Int2Bytes(), Float2Bytes() and Double2Bytes()) just return a string.
Also we can store binary data in strings
mystring"myfile.exe")
(2)
•
•
Computer memory —-> Just store [Bytes] - Each byte is 8-bit - (Here we avoid the memory word concept)
These bytes could be grouped together when moved between the memory and the processor registers. Here we have
(The register size) and things like 32-bit and 64-bit for example. Also we have the bytes order.
110.3. What about Memory Management in Ring? 1707

Ring Documentation, Release 1.14
Programming Languages —-> Add Types (Just as a concept) to these bytes so we can determine what to do with them
and how operations should be done.
And programming language could allow (Type Conversion) —> Because the Type is a logical concept in most cases,
What we really have is just data (Bytes, Bytes Count, Bytes Order, etc)
Ring Strings —-> You have these bytes (each byte is 8-bit) and Ring know the string size (stored as number in the
String structure)
So we don't check the NULL character or add it to the end of the string (Not Required)
All operations inside Ring VM, will check the Ring size and deal with the string as binary data (each character is 8-bit)
In the C language —> The normal case is adding NULL character (0) to the end of each string
And the string functions check this character, This is not suitable for binary data.
Signed vs Unsigned —> Is a logical concept which is important when you do arithmetic operations on the data, but
when storing the data, if you will include all of the (8-bits) and will not ignore any of them —> Then don't care.
In Ring, don't think about these details, we are hiding it from you, so you can focus on your application and what you
will do.
Think in C when you write C code which could be (based on need) low level code to have control on everything.
—-> Good for performance and memory management
Think in Ring when you write Ring code which let you ignore a lot of details and concentrate only on the result —–>
Good for productivity and delivering software quickly
The good news (We can mix between Ring and C in our projects)
(3)
These function take input as (Number) —> Convert it to group of bytes based on the number type (int|oat|double)
—> Then return a Ring string that contains these bytes
Int2Bytes() —> Ring string (Group of bytes) and the string size = sizeof(int)
Float2Bytes() —> Ring string (Group of bytes) and the string size = sizeof(oat)
Double2Bytes() —> Ring string (Group of bytes) and the string size = sizeof(double)
Example:
?1) )
?1) )
?1) )
Output:
4
4
8
(4)
When we use a number, Ring always use the (Double) data type for representing these numbers in memory. This is
important to know when we do arithmetic operations on numbers.
But when we convert the number to a String using “” + number or using string(number) we get a string where each
digit is represented in 1 byte (Not good idea for storage, but useful for string processing)
If you need the number to be represented in specic size (int|oat|double) for storage then use bytes2int() , bytes2oat()
and bytes2double() when writing the data to binary les.
110.4. What about Data Representation in Ring? 1708

Ring Documentation, Release 1.14
Ring Number (double) —-> int2bytes() - will cast the number from double to int then return the bytes —-> 4 bytes
(Ring String)
Ring Number (double) —-> oat2bytes() - will cast the number from double to oat then return the bytes —-> 4 bytes
(Ring String)
Ring Number (double) —-> double2bytes() - will use the number (double) to return the bytes —-> 8 bytes (Ring
String)
The (int) type is used only for internal Ring operations, but Ring applications|code will use only the (double) type for
numbers.
(5)
The function unsigned() expect the rst and the second parameters as numbers
unsigned(nNumber1,nNumber2,cOperator)
We can use the bytes2int() function to convert the bytes to a number
Example:
B list(4)
fork=1to4
{
B[k]=4)
forkk=1 to4[k][kk]=60+4 *kkk) }
?"k":B[k]
}
A12=4) A12=[1]) ^ bytes2int(B[2])
?A12: string(A12)
A34=4) A34=[3]) ^ bytes2int(B[4])
?A34: string(A34)
A12=4) A12=[1]),bytes2int(B[2]),"^")
?unsigned A12:A12
A34=4) A34=[3]),bytes2int(B[4]),"^")
?unsigned A34:A34
Output:
B1: ABCD
B2: EFGH
B3: IJKL
B4: MNOP
A12: 201589764
A34: 470025220
unsigned A12: 201589764
unsigned A34: 470025220
110.4. What about Data Representation in Ring? 1709

Ring Documentation, Release 1.14
110.5
Because it's faster and more natural, and this is important for the language's goals. One of the rules is: the data type
at the beginning affects the nal result. For example, when you type “Print : ” + 5 , The String comes rst, so 5 will
be converted to a String. While when you type 5 + “10” The number comes rst so “10” will be converted to 10. This
helps a lot to quickly convert between numbers and strings using the same operator. If you want to prevent conversion
(Write code that prevent conversion) In these cases you will notice that what you are writing is less code (And can be
removed).
Weakly typed = automatic conversion andautomaticisgood thingand is better thanmanualif you know how to use
it correctly.
110.6
Smalltalk and Lisp are GREAT languages. I like many of the concepts behind them but I'm sure that selecting the
right programming language is based on the problem and comes after the problem's denition. I have a problem that
I want to solve and these GREAT languages are not ideal for this problem so I designed Ring.
When you design a new language, You can learn from the past but you must look forward and live in the future. What
you know about natural programming maybe based on theold knowledgeabout the power of these paradigms in the
practical world and I agree with you but I see other techniques that can be applied to get this to work in practice. What
you miss aboutnatural languageis that they arecontext sensitiveand this means we can use it and think differently
about how we can express our ideas.
Example : I want window contains 3 buttons.
In one sentence I created 4 objects (The window and the three buttons) and added the buttons to the window. The idea
of natural programming is to get many things done like that.
110.7
Yes UI creation is one of the important things in the language features because it is designed to create a visual pro-
gramming tool, But the language is a multi-paradigm language where we can select the programming paradigm based
on the problem.
110.8
Ring is not designed to replace PHP, Lua or Smalltalk. Ring's support for declarative programming and natural
language programming is very innovative and much better than staying with procedural, object-oriented and functional
languages. Ring see the future in programming without code (using natural languages) and is designed to support that.
110.5. Why is Ring weakly typed? 1710

Ring Documentation, Release 1.14
110.9
Ring provides a better way to mix between different programming paradigms in solving problems.
The different programming paradigms play well together in the same language.
(1)
syntax for similar concepts.
(2)
for example you can create a game engine using object-oriented programming but write the game code using declara-
tive programming or natural programming and behind the scenes your declarative or natural code will use the object-
oriented classes.
(3)
(4)
and weakly typed for exibility.
(5)
provides control to the programmer who can delete memory at any time.
(6)
platform.
(7)
classes. so when you need more performance or when you need to use more libraries you can easily do that.
110.10
Open Source?
Yes the language is Open Source (MIT license)
In general I like Python and Ruby but I was looking for a language more suitable for creating the next version of the
Programming Without Coding Technology (PWCT) software so I started the Ring design.
Some simple changes that matters for my goal are
(1)
(2)
(3)
(4)
(5)
(6)
(7)
Critical changes are
(1)
to libraries and are optional when we go for using the language in C/C++ programs.
(2)
determine when to delete memory using the assignment operator
110.9. What are the advantages of using Ring over native C or C++? 1711

Ring Documentation, Release 1.14
(3)
statements
(4)
(5)
(6)
The Ring programming language is designed based on my experience from using many other languages like C, C++,
C#, Lua, PHP, Python, Ruby, Harbour, Basic and Supernova And the language comes with innovative features added
to achieve the language goal
•
•
•
•
•
•
software.
110.11
or Ruby?
(1)
(2)
(3)
(4)
(5)
(6)
110.12
(1)
(2)
110.13
(1)
(2)
110.11. What are the advantages to using Ring over Perl, PHP, Python or Ruby? 1712

Ring Documentation, Release 1.14
110.14
ported, but then this happens?
The question was about this code
f func{
a
return {returna }
}
innerF callf()
callinnerF()
Output:
Using uninitialized variable : a In function _ring_anonymous_func_16601()
The Answer:
•
•
that doesn't go against the language goals or spirit.
•
solution.
•
the function. Pass the list to the function when you use it.
•
•
where at each point you have only at maximum three scopes (Global, Object Scope and Local Scope).
•
then we will create a very complex language or we will save our time and use other languages.
•
better in this language?) to know when to use it. Don't compare a new language just released little months ago
with languages started many years ago and expect to nd everything that you used to have.
•
ability behind all of the features together.
110.15
handing over the syntax so you can parse it using whatever
code you like?
It's innovation - You create natural statements without the need to learn about parsing. You just use Classes which is
intelligent decision (where later we can mix between classes to support more statements based on the context - We can
change and translate the dened statements and many more!). Also the statements are added in Ring World where you
can use any Ring statement.
110.14. The documentation says functional programming is supported, but then this happens?1713

Ring Documentation, Release 1.14
110.16
out of?
The language supports programming in the small and programming in the large. The selection of what features to
use is based on what are you going to do. Any programmer can write poorly code in any language if he/she wants to
do that. The idea is what must be done in the language design to prevent errors without causing other problems like
killing exibility.
Read some source code in the Linux Kernel and Ruby Implementation for example, You will nd good usage for
GOTO as a practical example that General Rules are not for All Use Cases and great programmers know when to
break the rules. I'm not saying go and use GOTO or saying Ring add things like that. But the ability to break more
than one loop and/or the ability to break the loop from sub functions is practical for small programs.
Anyway these are some of the small new things added by the language (Not the big idea).
110.17
See and Give are selected not to be “opposite actions” but to reect what I want to do as a programmer.
When I want to see something on the screen I use `See'.
When I want to give some input to the program I use `Give'.
My selection of “but” and “ok” is based on selecting keywords that can be written quickly.
Also using “but” is easy to remember than elseif/elif/elsif where each language select a different keyword.
In Ring 1.1 and later versions All of this is just an option.
You can use `Put' and `Get' instead of `See' and `Give'
You can use `elseif' and `end' insetad of `But' and `Ok'
It's your choice. In Ring we have syntax exibility where we provide more than one style.
Also you can change the language keywords and operators.
Also you can dene new natural languages too.
110.18
The Ring programming language is designed to be SMALL. The language provides the basic constructs that you need
to do anything! One of the goals is to keep the basic constructs simple and small as possible.
Using Lists in Ring you can
•
•
•
•
The same principle is applied to Numbers
•
•
110.16. Why you can specify the number of loops you want to break out of? 1714

Ring Documentation, Release 1.14
•
The sample principle is applied for Strings
•
•
•
•
•
•
And we have Object Oriented Support + Operator Overloading where the programmer can dene new data types and
use them as default types dened by the language
So We have
•
•
•
110.19
You can use true for 1 and false for 0
when you test the result of Boolean expressions in your code.
Just when you print the value using the see command you will see 1 for (true) and 0 for (false)
Why ?
Because Ring contains only 4 types of variables
(1)
(2)
(3)
(4)
The rst type (Number) is used to represent int, double and Boolean values.
The second type (String) is used to represent char, array of characters, date and time.
The third type (List) is used to represent Arrays of one type, Arrays of more than one type, Hash (Dictionary), Tree,
etc.
The object can be an object created from a Ring class (Any Class) or just a C Pointer that we get from calling a C/C++
function/method.
Why ?
The Ring is designed to give the programmer/developer the most simple constructs that can be used to do everything.
The programmer/developer can customize the language by creating new classes (and use operator overloading) to get
more types that he care about according to the problem domain.
Why ?
110.19. What about the Boolean values in Ring? 1715

Ring Documentation, Release 1.14
Because simple is better, and easy to learn and remember! And this provide exibility to convert between high level
types that can be represented using the same basic type
110.20
The main function is very important, you need it when you want to write statements that uses local variables instead
of the Global scope.
Example:
x
myfunc()
See"X value = # here I expect that x will be (10)
# but I will get another value (6) because myfunc() uses x !
Funcmyfunc
forx to5
Seex
next
Output:
1
2
3
4
5
X value
Now using the Main function
FuncMain
x
myfunc()
See"X value =
Funcmyfunc
forx to5
Seex
next
Output
1
2
3
4
5
X value
110.20. What is the goal of including the “Main” function in Ring? 1716

Ring Documentation, Release 1.14
110.21
Its about how we count in the real world, when we have three apples in our hand
we say 1 2 3
We dont start from 0
The question must be why the other languages start from 0 ?
The answer is, because this is related to the machine and how we deal with values and memory address.
Example
we have array called myarray[5]
In memory : myarray will have an address
The rst item will be stored in that address
The second item will come after that address and so on
Now when we need to point to the rst item we need the address of myarray
So we type myarray[0] because myarray + 0 result will still point to the rst item
for the second item myarray[1] because myarray + 1 result will point to the second item and so on
In Low Level languages or languages near to the machine its good to be like this
But for high level language designed for applications its better to be natural
Example
mylist1,2,3,4,5]
forx tolen(mylist)
seex
next
In the previous example we start from 1 to the length of the array if the index starts from 0 we will write
forx tolen(mylist)-1
or remember the for loop in other languages
for(x=0<nMax ; x++
You will use the < operator !
110.22
(1)
(2)
(3)
(4)
see"lower case!"
110.21. Why the list index start from 1 in Ring? 1717

Ring Documentation, Release 1.14
SEE"UPPER case!"
See"First Letter is UPPER case!"
(5)
(6)
(7)
We can write person as variable name and Person as class name.
person newPerson
classPerson
name address phone
110.23
“Because it's a poor tradeoff to add complexity for dubious performance gains, a good approach to deep vs. shallow
copies is to prefer deep copies until proven otherwise.”
, Steve McConnell, Code Complete
(1)
(2)
(3)
(4)
sense.
(5)We have references when this is natural, like passing lists and objects to functions,creating objects (Like
GUI Objects) from a C/C++ library, returning an object stored inside a list.
(6)It is a feature, We can use it to create pure functions. The Value() function in thestdlib uses this feature to
pass lists & objects by value when we need this.
(7)
(8)
(9)In Ring, we start without thinking about the little details and concentrate on the application, Youdon't
have to write the type (Dynamic Typing), You don't have to write explicit conversions between numbers
and strings (Weakly Typed) and you don't have to select between using values or references, You don't
have to write the scope (Lexical Scoping).
(10)In Ring, we have smart garbage collector (Simple & Fast), We can delete the memory directlyat any
time using the Assignment operator too. Reducing references usage or using them through managers
helps a lot to achieve this goal. by doing this we have full control.
(11)If you want to create references and avoid creating a manager,You can use Object2Pointer() and
Pointer2Object() functions But It's not the Ring way “Spirit” to do things.
110.23. Why the Assignment operator uses Deep Copy? 1718

Ring Documentation, Release 1.14
110.24
When you create new object for example
newpoint
1 - Ring will allocate dynamic memory space to be used for the new object attributes that Ring doesn't know anything
about them.
2 - Ring will change the current local scope and the current object scope to use the object state created in step (1)
3 - Ring will move the execution to the class Region (After the class name and before any methods)
4 - Any Instructions/Code in the class region will be executed as any Ring code
5 - Control is moved from the class region to the location of (new point) once we reach the end of the class region or
we uses a Return command.
So All attributes that added to the object are dynamic attributes, this mean that you can control what attributes will be
added through the runtime.
Example:
$3D = False
see new point
$3D = True
see new point
class point
x y
if not $3D return ok
z
Output:
x: NULL
y: NULL
x: NULL
y: NULL
z: NULL
You have an option to call init() method directly when you create a new object
This method can do anything with the object attributes as it will be called after creating the object and executing the
class region code.
p1 newpoint3d(100,200,300)
seep1
classpoint3d
x y z
funcinit p1,p2,p3
x=p1 y=p2 z=p3
110.24. Is there constructor methods in Ring? 1719

Ring Documentation, Release 1.14
110.25
1- When you create an object, the class region code will be executed and you will have the object attributes based on
the code in that region
2- Ring don't care about the object methods until you start calling a method
3- When you call a method, Ring will check the object class and the class parent (if you are using inheritance) and
will collect the methods for you to be used now or later from any object that belong to the same class.
4- Since methods are dynamic and each object get the method from the class, you can after creating objects, add new
methods and use it with the object or any object created or will be created from the same class.
Example:
o1 newpoint {x=10=20=30}
o2 newpoint {x=100=200300}
addmethod(o1,"print", func{seex
o1.print()
o2.print()
classpoint x y z
Output:
10
20
30
100
200
300
110.26
methods?
Yes we can, The setter/getter methods are called automatically when you start using the attributes from outside the
class Also you can call the methods instead of using the attributes. It's your choice.
Example:
o1 newDeveloper
o1.nameMahmoud" seeo1.name
o1 { nameGal" seename }
o1 { nameBert" seename }
o1.setname("Marino")
seeo1.getname()
ClassDeveloper
name languageRing Programming Language"
funcsetname value
(continues on next page)
110.25. What happens when we create a new object? 1720

Ring Documentation, Release 1.14
(continued from previous page)
see"Message from SetName() Function!"
name
funcgetname
see"Message from GetName() Function!"
return"Mr.
Output
Message from SetName() Function!
Message from GetName() Function!
Mr. Mahmoud - Ring Programming Language
Message from SetName() Function!
Message from GetName() Function!
Mr. Gal - Ring Programming Language
Message from SetName() Function!
Message from GetName() Function!
Mr. Bert - Ring Programming Language
Message from SetName() Function!
Message from GetName() Function!
Mr. Marino - Ring Programming Language
110.27
the class attributes?
The question is why we don't avoid conicts with global variable names when we dene the class attributes ?
At rst remember that using the optional $ mark in the global variables names solve the problem. Also using the Main
function and avoiding global variables may help.
The Answer:
Ring is a dynamic language
We can in the run-time determine the class attributes (Add/Remove)
We can execute (any code) while dening the class attributes
Example (1)
oPerson newPerson
ClassPerson
See"Welcome to the Ring language"
Example (2)
Customize attributes based on global variable value
$debug true
oPerson newPerson
seeoPerson
(continues on next page)
110.27. Why should a search of global names be made while dening the class attributes? 1721

Ring Documentation, Release 1.14
(continued from previous page)
ClassPerson
if$debug date=date() time=time() ok
In the previous example when we have the $debug ag set to true, we will add the Date and Time attributes to the
object state.
Example (3)
Store the object index based on global variable
$ObjectsCount
oPerson newPerson
seeoPerson
oPerson2 newPerson
seeoPerson2
ClassPerson
$ObjectsCount++
nIndexObjectsCount
Output:
nindex:.000000
nindex:.000000
Common Example:
•
•
•
It's exibility but remember that power comes with great responsibility.
110.28
and Class Attributes Names?
In this use case we have
1 - Global Variable dened without a special mark like $
2 - Class contains Attributes dened using a special syntax (where we type the attribute name directly after the class)
3 - The Attributes are dened in the class region that allows writing code and using global variables
If I will accepted your proposal about changing how Ring nd variables in the class region I must break one of the
previous three features which will lead to more problems that are more important than this problem.
I don't like changing the feature number (1) because I would like to keep Ring code more clean and let the programmer
decide when to use $ or not.
I don't like changing the feature number (2) because I like this feature and I don't like forcing the programmer to type
self.attribute
I don't like changing the feature number (3) because it's very important in many applications to access global variables
in the class region.
So what was my decision ?
110.28. Why Ring doesn't avoid the conict between Global Variables and Class Attributes
Names?
1722

Ring Documentation, Release 1.14
I decided to leave this case for the programmer who will decide what to do to avoid this special case
1 - The programmer can avoid using global variables (Better) and can use the Main function (Optional)
2 - The programmer can use $ before the variable name or any mark likeglobal_org_
3 - The programmer can use self.attribute after the class name to dene the attributes
In general, for small programs you can use global variables and functions. For large programs, use classes and objects
and small number of global variables or avoid them at all.
110.29
Run the Ring Notepad where you can write/execute programs.
If you want to run programs using the command line
Add Ring/bin folder to the path then
ring <filename.ring>|<filename.ringo>
110.30
The next function can be used to get the le size without reading the le!
funcgetFileSize fp
C_FILESTART
C_FILEEND
fseek(fp,0,C_FILEEND)
nFileSize
fseek(fp,0,C_FILESTART)
returnnFileSize
Note:The previous function take the fp (le pointer) as parameter, We can get the fp from opening the le using
fopen() function.
fp"filename","r")
see"File Size :
Another solution (Read the le)
seelen(read("filename"))
110.29. Where can I write a program and execute it? 1723

Ring Documentation, Release 1.14
110.31
We can use the next function to get the current source le path then we can add the path variable to the le name
cPath
funccurrentpath
cFileName
forx to1step-1
ifcFileName[x]/"
returnleft(cFileName,x-1)
ok
next
returncFileName
110.32
functions?
if you want to use predened parameters or optional parameters Just accept a list that works like hash/dictionary
Example
sum([, :b])
sum([)
sum([)
funcsum pList
ifplist[:a] NULLpList[:a] ok
ifplist[:b] NULLpList[:b] ok
seepList[:a][:b]
Output
3
6
6
110.33
If you want to print keys only or values only just select the index of the item (one or two).
Example
C_COUNTRY
C_CITY
mylist
:KSARiyadh"
:EgyptCairo"
]
forxinmylist
seex[C_COUNTRY]
next
(continues on next page)
110.31. How to get the current source le path? 1724

Ring Documentation, Release 1.14
(continued from previous page)
forxinmylist
seex[C_CITY]
next
Output
ksa
egypt
Riyadh
Cairo
110.34
In the next code
list=:5 # list = [1,2,3,4,5]
see +
New Line will be added to the list then the list will be printed, the default print of the lists will print a newline at the
end, You added new newline and You have now 2 newlines to be printed.
See<Expr>
The see command just print the nal result of the expression, the expression will be evaluated as it
nl13)10) # just a variable that you can change to anything !
The + is an operator
string + string ---> new string
string + number ---> new string
number + number ---> new number
number + string ---> new number
list + item —> nothing new will be created but the item will be added to the same list
Exception
number + nl -> New String
This exception is added to easily print numbers then new line.
No need for this with printing lists because after printing the last item we already get a new line.
110.35
At rst remember that you can check strings using `=' operator directly.
seestrcmp("hello","hello")
strcmp("abc","bcd")
strcmp("bcd","abc")
110.34. Why I get a strange result when printing nl with lists? 1725

Ring Documentation, Release 1.14
if the two strings are the same then it returns 0
abc and bcd aren't the same. in the second line it returns -1 and in the third line it returns 1
In the second line we compare between “abc” and “bcd”
Not equal because the rst letter in “abc” = “a” and the rst letter in “bcd” = “b”
So we have “a” != “b” and “a” < “b”
So we get output = -1
In the third line we have “bcd” and “abc”
the rst letter in “bcd” is “b” and the rst letter in “abc” is “a”
So we have “b” != “a” and “b” > “a”
So we get output = 1
Note:ASCII(“a”) = 97 and ASCII(“b”) = 98 So “a” < “b” because 97 < 98
110.36
Example:
I have the next folder
C:\LRing
Contains the next les
C:\LRing 1.ring
C:\LRing\mylib.ring
C:\LRing\libs\mylib2.ring
The le t1.ring contains the next code
load"mylib.ring"
load"libs\mylib2.ring"
myfunc()
test()
The le mylib.ring contains the next code
funcmyfunc
see"message from myfunc"+nl
The le libsmylib2.ring contains the next code
functest
see"message from test"
from the folder C:LRing
If Ring is not added to the path you can add it or use the next command
110.36. How to use many source code les in the project? 1726

Ring Documentation, Release 1.14
set path=%path%;c:ingin;
Where c:ring is the Ring folder
Now run
Ring t1.ring
Output
message from myfunc
message from test
110.37
The GetChar() function accept one character from the keyboard buffer
In this example
While
See"
Main Menu
(1) Say Hello
(2)Exit
"
Option
GetChar() GetChar() # End of line
# the previous two lines can be replaced with the next line
# Give Option
ifOption
see"Enter your name : givecName
see"Hello
else
bye
ok
End
We uses GetChar() Three times
The rst time we get the user option
Option
But in the second and the third times (We accept the new line characters from the buffer)
GetChar() GetChar() # End of line
Example : when the user select the option number 1 then press ENTER
We have Three Characters
•
•
•
Because Windows uses CHAR(13) and CHAR(10) for each new line ( i.e. CR+LF )
110.37. Why this example use the GetChar() twice? 1727

Ring Documentation, Release 1.14
110.38
when we try to use uninitialized variable in the Ring programming language, we get a clear runtime error message
Example
Seex
Output
Line 1 Error (R24) : Using uninitialized variable : x
in file tests\seeuninit.ring
The same happens when you try to access uninitialized attributes
Example
o1 newpoint
seeo1
seeo1.x
classpoint x y z
Output
x: NULL
y: NULL
z: NULL
Line 3 Error (R24) : Using uninitialized variable : x
in file tests\seeuninit2.ring
if you want to check for the error, just use Try/Catch/End
Try
seex
Catch
See"Sorry, We cant use x!"
Done
Output
Sorry, We cant use x!
Now we will talk about NULL and ISNULL()
Since we get error message when we deal with uninitialized variables
We can check these errors using Try/Catch/Done, So we uses NULL and ISNULL() for dealing with Strings.
NULL is a variable contains an empty string
ISNULL() is a function that returns true (1) if the input is an empty string or just a string contains “NULL”
This because we need to test these values (empty strings) and strings contains “NULL” that sometimes come from
external resource like DBMS.
Example
110.38. How to use NULL and ISNULL() function? 1728

Ring Documentation, Release 1.14
SeeIsNull(5) # print 0
IsNull("hello") # print 0
IsNull([1,3,5]) # print 0
IsNull("") # print 1
IsNull("NULL") # print 1
110.39
In this example we will see how we can print a list contains objects.
aList[1,2,3] newpoint(1,2,3), newpoint(1,2,3)]
see"print the list"
seealist
see"print the item (object)"
seealist[2]
classpoint x y z
funcinit p1,p2,p3 x=p1 y=p2 z=p3
Output
print the list
1
2
3
x: 1.000000
y: 2.000000
z: 3.000000
x: 1.000000
y: 2.000000
z: 3.000000
print the item (object)
x: 1.000000
y: 2.000000
z: 3.000000
110.40
To insert an item we can use the insert(aList,nIndex,Value) function.
aList:5
insert(aList,0,0)
SeeaList# print numbers from 0 to 5
110.39. How to print lists that contains objects? 1729

Ring Documentation, Release 1.14
110.41
To print new line we can use the nl variable.
See"Hello"
or we can use multi-line literal as in the next example
See"Hello
"
if we want to print other characters we can use the char(nASCII) function
Seechar(109) # print m
char(77) # print M
110.42
When we use RingQt to create GUI application, we uses () after the class name when we create new objects for
example.
newqWidget() { setWindowTitle("Hello World") resize(400,400) show() }
but before doing that we create an object from the qApp class and we don't use () after that
Load"guilib.ring"
app newqApp
{
win=newqWidget()
{
setwindowtitle(:test)
show()
}
exec()
}
Using () after the class name means calling the init() method in the class and passing parameters to this method.
If we used () while no init() method in the class we get the expected error message.
The class qApp don't have this method while the other classes have it because they need it to create an object using
a function that return a pointer to that object and this pointer will be stored in an attribute called pObject, for more
information see ring_qt.ring le which contains the classes.
110.41. How to print new lines and other characters? 1730

Ring Documentation, Release 1.14
110.43
When we write the next code
Load"guilib.ring"
app newqApp
{
win=newqWidget()
{
setwindowtitle(:test)
setGeometry(0,0,200,200)
show()
}
exec()
}
I would expect that the window will run at the point (0,0) with (200,200) size but the actual result is that the window
title bar is going outside the screen.
This is related to the behavior of Qt framework.
The next code will avoid the problem
load"guilib.ring"
newqApp {
newqWidget() {
move(0,0)
resize(200,200)
show()
}
exec()
}
110.44
Check the next example:
Load"guilib.ring"
App1 newqApp {
win1 newqWidget() {
move(0,0)
resize(500,500)
newqPushButton(win1)
{
settext("OK")
setclickevent("click()")
}
btn1 newqPushButton(win1)
{
setgeometry(100,100,100,30)
settext("Button1")
}
(continues on next page)
110.43. Why the window title bar is going outside the screen? 1731

Ring Documentation, Release 1.14
(continued from previous page)
btn2 newqPushButton(win1)
{
setgeometry(200,100,100,30)
settext("Button2")
}
buttonbtn1, btn2]
show()
}
exec()
}
funcclick
button[1]"Button3") }
button[2]"Button4") }
110.45
This example demonstrates how to close a window and show another one
Load "guilib.ring"
app=new qApp
{
frmBefore=new Qwidget()
{
setWindowTitle("before!")
resize(300,320)
move(200,200)
button=new qPushButton(frmBefore)
{
setText("Close")
setClickEvent("frmBefore.close() frmMain.show()")
}
show()
}
frmMain=new Qwidget()
{
setWindowTitle("After!")
resize(300,320)
move(200,200)
}
exec()
}
110.45. How to Close a window then displaying another one? 1732

Ring Documentation, Release 1.14
110.46
This example demonstrates how to create a modal window
load"guilib.ring"
app=newqApp
{
frmStart= newQwidget()
{
setWindowTitle("The First Window")
resize(300,320)
move(200,200)
button= newqPushButton(frmStart)
{
setText("Show Modal Window")
resize(200,30)
setClickEvent("frmModal.show()")
}
newqPushButton(frmStart)
{
setText("Close Window")
move(0,50)
resize(200,30)
setClickEvent("frmStart.Close()")
}
show()
}
frmModal newQwidget()
{
setWindowTitle("Modal Window")
resize(300,320)
move(200,200)
setparent(frmStart)
setwindowmodality(true)
setwindowflags(Qt_Dialog)
}
exec()
}
Related Documents
•
•
•
•
110.46. How to create a Modal Window? 1733

Ring Documentation, Release 1.14
110.47
Use the method setWindowFlags()
Load"guilib.ring"
app1 newqapp {
win1 newqwidget() {
setwindowtitle("First")
setgeometry(100,100,500,500)
newqpushbutton(win1) {
setgeometry(100,100,100,30)
settext("close")
setclickevent("app1.quit()")
}
newqpushbutton(win1) {
setgeometry(250,100,100,30)
settext("Second")
setclickevent("second()")
}
showmaximized()
}
exec()
}
funcsecond
win2 newqwidget() {
setwindowtitle("Second")
setgeometry(100,100,500,500)
setwindowflags(Qt_dialog)
show()
}
110.48
In Ring 1.1 and later versions we have native support for SQLite, so you don't need to use it through ODBC.
Also we can access SQLite through RingQt.
The answer to your question
pODBC
odbc_connect(pODBC,"DRIVER=SQLite3 ODBC Driver;Database=mydb.db;LongNames=0;"+
"Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;")
odbc_execute(pODBC,"create tabletelID,NAME,PHONE);")
odbc_execute(pODBC,"insert intotel1,Mahmoud,123456);")
odbc_execute(pODBC,"insert intotel2,Ahmed,123456);")
odbc_execute(pODBC,"insert intotel3,Ibrahim,123456);")
odbc_execute(pODBC,"select *from tel")
nMax
See"Columns Count :
whileodbc_fetch(pODBC)
Seenl
(continues on next page)
110.47. How can I disable maximize button and resize window? 1734

Ring Documentation, Release 1.14
(continued from previous page)
forx tonMax
seeodbc_getdata(pODBC,x)
ifx= see" ok
next
end
odbc_disconnect(pODBC)
odbc_close(pODBC)
Output:
Columns Count : 3
1 - Mahmoud - 123456
2 - Ahmed - 123456
3 - Ibrahim - 123456
The program will create the le : mydb.db
Note : when I print the odbc drivers I see the long list that includes
SQLite3 ODBC Driver - UsageCount=1
SQLite ODBC Driver - UsageCount=1
SQLite ODBC (UTF-8) Driver - UsageCount=1
And I'm using “SQLite3 ODBC Driver”.
110.49
You can connect to any database using ODBC
To connect to xbase les (*.DBF)
See"Using DBF Files using ODBC"
pODBC
See"Connect to database"
odbc_connect(pODBC,"Driver={Microsoft dBase Driver ( *.dbf)};"+
"datasource=dBase Files;DriverID=277")
See"Select data"
odbc_execute(pODBC,"select *from tel.dbf")
nMax
See"Columns Count :
whileodbc_fetch(pODBC)
See"Row data:"
forx tonMax
seeodbc_getdata(pODBC,x)
next
end
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
Output
Using DBF Files using ODBC
Connect to database
(continues on next page)
110.49. Can I connect to dbase/harbour database? 1735

Ring Documentation, Release 1.14
(continued from previous page)
Select data
Columns Count : 3
Row data:
Ahmad - Egypt - 234567 - Row data:
Fady - Egypt - 345678 - Row data:
Shady - Egypt - 456789 - Row data:
Mahmoud - Egypt - 123456 - Close database...
Also you can connect to a Visual FoxPro database (requires installing Visual FoxPro driver)
See"ODBC test 6"
pODBC
See"Connect to database"
odbc_connect(pODBC,"Driver={Microsoft Visual FoxPro Driver};"+
"SourceType=DBC;SourceDB=C:\PWCT19\ssbuild\PWCTDATA \CH1\Data\mydata.dbc;")
See"Select data"
seeodbc_execute(pODBC,"select *from t38")
nMax
See"Columns Count :
whileodbc_fetch(pODBC)
See"Row data:"
forx tonMax
seeodbc_getdata(pODBC,x)
next
end
See"Close database..."
odbc_disconnect(pODBC)
odbc_close(pODBC)
110.50
setClickEvent(cCode) take a string contains code. The code will be executed when the event happens.
Ring support Many Programming Paradigms like Procedural, OOP, Functional and others.
But when you support many paradigms at the language level you can't know which paradigm will be used so you have
two options
(1)
(2)
setClickEvent() and others belong to (General Solutions that works with many programming paradigms).
You just pass a string of code that will be executed without any care about classes and objects.
This code could be anything like calling a function, calling a method and setting variable value.
Some other languages force you to use OOP and call methods for events. Also some other languages uses anonymous
functions that may get parameters like the current object.
Now we have the general solution (not restricted with any paradigm), In the future we may add specic solutions that
match specic paradigms (OOP, Functional, Declarative and Natural).
110.50. Why setClickEvent() doesn't see the object methods directly? 1736

Ring Documentation, Release 1.14
110.51
Each program follow the next order
1 - Loading Files 2 - Global Variables and Statements 3 - Functions 4 - Packages, Classes and Methods
So what does that mean ?
(1)**** No Functions comes After Classes****
(2)**** No command is required to end functions/methods/classes/packages****
Look at this example
See"Hello"
test()
functest
see"message from the test function!"
classtest
In the previous example we have a function called test() so we can call it directly using test()
In the next example, test() will become a method
See"Hello"
test() # runtime error message
classtest
functest# Test() now is a method (not a function)
see"message from the test method!"
The errors comes when you dene a method then try calling it directly as a function.
The previous program must be
See"Hello"
newtest { test() } # now will call the method
classtest
functest# Test() now is a method (not a function)
see"message from the test method!"
110.52
Ring can work on Windows XP and load extensions without problems.
Just be sure that the extension can work on Windows XP and your compiler version support that (modern compilers
requires some ags to support XP)
Check this topic
For example, We added
/link /SUBSYSTEM:CONSOLE,"5.01"
To the batch le to support Windows XP
See :
110.51. Why I get Calling Function without denition Error? 1737

Ring Documentation, Release 1.14
110.53
You have many options
In general you can extend Ring using C or C++ code
Ring from Ring code you can call C Functions or use C++ Classes & Methods
This chapter in the documentation explains this part in the language
extension.html
For example the next code in.c le can be compiled to a DLL le using the Ring library (.lib)
#include
RING_FUNC(ring_ringlib_dlfunc)
{
printf("Message from dlfunc");
}
RING_APIvoidringlib_init(RingState *pRingState)
{
ring_vm_funcregister("dlfunc",ring_ringlib_dlfunc);
}
Then from Ring you can load the DLL le using LoadLib() function then call the C function that called dlfunc() as
any Ring function.
See"Dynamic DLL"
LoadLib("ringlib.dll")
dlfunc()
Output
Dynamic DLL
Message from dlfunc
When you read the documentation you will know about how to get parameters like (strings, numbers, lists and objects)
And how to return a value (any type) from you function.
From experience, when we support a C library or C++ Library
We discovered that a lot of functions share a lot of code
To save our time, and to quickly generate wrappers for C/C++ Libraries to be used in Ring
We have this code generator
https://github.com/ring-lang/ring/blob/master/extensions/codegen/parsec.ring
The code generator is just a Ring program < 1200 lines of Ring code
The generator take as input a conguration le contains the C/C++ library information
like Functions Prototype, Classes and Methods, Constants, Enum, Structures and members , etc.
Then the generator will generate
*.C File for C libraries (to be able to use the library functions)
*.CPP File for C++ libraries (to be able to use C++ classes and methods)
*.Ring File (to be able to use C++ classes as Ring classes)
110.53. How to extend RingQt and add more classes? 1738

Ring Documentation, Release 1.14
*.RH le (Constants)
To understand how the generator work check this extension for the Allegro game programming library
https://github.com/ring-lang/ring/tree/master/extensions/ringallegro
At rst we have the conguration le
https://github.com/ring-lang/ring/blob/master/extensions/ringallegro/allegro.cf
To write this le, i just used the Allegro documentation + the Ring code generator rules
Then after executing the generator using this batch le
https://github.com/ring-lang/ring/blob/master/extensions/ringallegro/gencode.bat
or using this script
https://github.com/ring-lang/ring/blob/master/extensions/ringallegro/gencode.sh
I get the generated source code le
https://github.com/ring-lang/ring/blob/master/extensions/ringallegro/ring_allegro.c
The generated source code le (ring_allegro.c) is around 12,000 Lines of code (12 KLOC)
While the conguration le is less than 1 KLOC
To build the library (create the DLL les)
https://github.com/ring-lang/ring/blob/master/extensions/ringallegro/buildvc.bat
Also you can check this extension for the LibSDL Library
https://github.com/ring-lang/ring/tree/master/extensions/ringsdl
After this know you should know about
1 - Writing the conguration le
2 - Using the Code Generator
3 - Building your library/extension
4 - Using your library/extension from Ring code
Let us move now to you question about Qt
We have RingQt which is just an extension to ring (ringqt.dll)
You don't need to modify Ring.
(1)
(2)
For the rst option see the RingQt extension
https://github.com/ring-lang/ring/tree/master/extensions/ringqt
Conguration le
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/classes/qt.cf
To generate the source code
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/gencode.bat
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/gencode.sh
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/gencodeandroid.bat
110.53. How to extend RingQt and add more classes? 1739

Ring Documentation, Release 1.14
To build the DLL/so/Dylib les
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/buildmingw32.bat
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/buildgcc.sh
https://github.com/ring-lang/ring/blob/master/extensions/ringqt/buildclang.sh
Study RingQt
Learn about the options that you have
(1)
(2)
For the second option (in the previous two points or in the two points before that)
You will create new classes in C++ code
Then you merge these classes to RingQt or provide special DLL for them (your decision)
If your work is general (will help others) just put it to RingQt.
if your work is special (to specic application) just put it in another extension.
110.54
QTableWidget?
Check the next code
Load"guilib.ring"
NewqApp
{
win1 newqMainWindow() {
setGeometry(100,100,1100,370)
setwindowtitle("Using QTableWidget")
Table1 newqTableWidget(win1) {
setrowcount(10) setcolumncount(10)
setGeometry(0,0,800,400)
setselectionbehavior(QAbstractItemView_SelectRows)
forx to10
fory to10
item1 newqtablewidgetitem("R"+X+"C"+Y)
setitem(x-1,y-1, item1)
next
next
cmb newQComboBox(Table1) {
alist"one","two","three","four","five"]
forxinaList additem(x,0) next
}
setCellWidget(5,, cmb)
}
setcentralwidget(table1)
show()
}
(continues on next page)
110.54. How to add Combobox and other elements to the cells of a QTableWidget? 1740

Ring Documentation, Release 1.14
(continued from previous page)
exec()
}
110.55
QTableWidget?
Check the next sample
Load"guilib.ring"
NewqApp {
win1 newqMainWindow() {
setGeometry(100,100,800,600)
setwindowtitle("Using QTableWidget")
Table1 newqTableWidget(win1) {
setrowcount(10) setcolumncount(10)
setGeometry(10,10,400,400)
forx to10
fory to10
item1 newqtablewidgetitem("10")
setitem(x-1,y-1,item1)
next
next
}
btn1 newqPushButton(win1) {
setText("Increase")
setGeometry(510,10,100,30)
setClickEvent("pClick()")
}
show()
}
exec()
}
funcpClick
fornRow toTable1.rowcount()
fornCol toTable1.columncount()
Table1.item(nRow,nCol) {
ifisSelected()
setText("
ok
}
next
next
110.55. How to perform some manipulations on selected cells in QTableWidget? 1741

Ring Documentation, Release 1.14
110.56
mended by the community?
(1)Just select any style of them but don't mix between the different styles in the same projector at least in
the same context (Implementation, Tests, Scripts, etc)
Note:State the rules in the start of each project and follow it.
(2)
Note:It's better to change keywords and create new style only for a clear reason like using another natural language
(Arabic, French, etc.)
(3)The First style is better (IMHO) for questions, tutorials and small applications/programs (Less than 5,000 LOC)
Example : Ring Book, Most of Ring Samples and Applications.
(4)
Example (Form Designer) :
110.56. Which of 3 coding styles are commonly used or recommended by the community? 1742

CHAPTER
ONE
BUILDING FROM SOURCE CODE
The Ring programming language is a free open source product (MIT License).
You can build Ring using CMake or using Scripts (Batch Files or Shell Scripts).
The next steps explains building using scripts.
111.1
Get the source code
git clone http://github.com/ring-lang/ring.git
Build Ring (Compiler/VM)
cd ring/language/src
buildvc.bat
buildvcw.bat
Build Ring2EXE
cd ring/tools/ring2exe
buildring2exe.bat
Generate RingConsoleColors Source Code and Build
cd ring/extensions/ringconsolecolors
gencode.bat
buildvc.bat
Build RingInternet
cd ring/extensions/ringinternet
buildvc.bat
Generate RingLibCurl Source Code and Build
cd ring/extensions/ringcurl
gencode.bat
buildvc.bat
Generate RingZip Source Code and Build
1743

Ring Documentation, Release 1.14
cd ring/extensions/ringzip
gencode.bat
buildvc.bat
Build RingPM
cd ring/tools/ringpm
buildringpm.bat
Build RingODBC
cd ring/extensions/ringodbc
buildvc.bat
Build RingMySQL
cd ring/extensions/ringmysql
buildvc.bat
Build RingSQLite
cd ring/extensions/ringsqlite
buildvc.bat
Build RingPostgreSQL
cd ring/extensions/ringpostgresql
gencode.bat
buildvc.bat
Build RingOpenSSL
cd ring/extensions/ringopenssl
buildvc.bat
Build RingMurmurHash
cd ring/extensions/ringmurmurhash
buildvc.bat
Generate RingAllegro Source Code and Build
cd ring/extensions/ringallegro
gencode.bat
buildvc.bat
Generate RingLibuv Source Code and Build
cd ring/extensions/ringlibuv
gencode.bat
buildvc.bat
Generate RingFreeGLUT Source Code and Build
cd ring/extensions/ringfreeglut
gencode.bat
buildvc.bat
111.1. Building using Microsoft Windows 1744

Ring Documentation, Release 1.14
Generate RingOpenGL Source Code and Build
The ringopengl folder contains many sub folders for different OpenGL versions
Starting from OpenGL 1.1 to OpenGL 4.6
cd ring/extensions/ringopengl/opengl21
gencode.bat
buildvc.bat
Generate RingPostgreSQL Source Code and Build
cd ring/extensions/ringpostgresql
gencode.bat
buildvc.bat
Generate RingQt Source Code and Build
Tested using Qt 5.12 and Qt 5.15
For Qt 5.12 ( Install Qt 5.12 :
cd ring/extensions/ringqt
gencodeqt512_nobluetooth.bat
buildqt512_nobluetooth.bat
To Copy the Qt runtime les to ring/bin folder
cd ring/extensions/ringqt/binupdate
installqt512.bat
For Qt 5.15 ( Install Qt 5.15 :
cd ring/extensions/ringqt
gencodeqt515_nobluetooth.bat
buildqt515_nobluetooth.bat
To Copy the Qt runtime les to ring/bin folder
cd ring/extensions/ringqt/binupdate
installqt515.bat
To be able to call ring from any folder
cd ring/bin
install.bat
Add Ring/bin to System path
Hit "windows key".
Type "Edit the System environment variables"
Select "Advanced" tab.
Click on "Enviroment Variables..."
Double click on "Path"
Add at the end the new path separated by semicolon.
;C:\Ring\Bin
Run Ring Notepad
111.1. Building using Microsoft Windows 1745

Ring Documentation, Release 1.14
cd ring/tools/ringnotepad
ring rnote.ring
111.2
Get the source code
git clone http://github.com/ring-lang/ring.git
Install Libraries
cd ring/language/src
./installdep.sh
Build Ring (Compiler/VM)
sudo ./buildgcc.sh
Build Ring2EXE
cd ring/tools/ring2exe
sudo ./buildring2exe.sh
Generate RingConsoleColors Source Code and Build
cd ring/extensions/ringconsolecolors
./gencode.sh
./buildgcc.sh
Build RingInternet
cd ring/extensions/ringinternet
./buildgcc.sh
Generate RingLibCurl Source Code and Build
cd ring/extensions/ringcurl
./gencode.sh
./buildgcc.sh
Generate RingZip Source Code and Build
cd ring/extensions/ringzip
./gencode.sh
./buildgcc.sh
Build RingPM
cd ring/tools/ringpm
sudo ./buildringpm.sh
Build RingODBC
cd ring/extensions/ringodbc
./buildgcc.sh
111.2. Building using Ubuntu Linux 1746

Ring Documentation, Release 1.14
Build RingMySQL
cd ring/extensions/ringmysql
./buildgcc.sh
Build RingSQLite
cd ring/extensions/ringsqlite
./buildgcc.sh
Build RingPostgreSQL
cd ring/extensions/ringpostgresql
gencode.sh
buildgcc.sh
Build RingOpenSSL
cd ring/extensions/ringopenssl
./buildgcc.sh
Build RingMurmurHash
cd ring/extensions/ringmurmurhash
./buildgcc.sh
Generate RingAllegro Source Code and Build
cd ring/extensions/ringallegro
./gencode.sh
./buildgcc.sh
Generate RingLibuv Source Code and Build
We will build Libuv rst
cd ring/extensions/ringlibuv/libuv
sudo apt-get install libtool m4 automake
sh autogen.sh
./configure
make
make check
sudo make install
Then we will build RingLibuv
cd ring/extensions/ringlibuv
./gencode.sh
./buildgcc.sh
Generate RingFreeGLUT Source Code and Build
cd ring/extensions/ringfreeglut
./gencode.sh
./buildgcc.sh
Generate RingOpenGL Source Code and Build
The ringopengl folder contains many sub folders for different OpenGL versions
111.2. Building using Ubuntu Linux 1747

Ring Documentation, Release 1.14
Starting from OpenGL 1.1 to OpenGL 4.6
cd ring/extensions/ringopengl/opengl21
gencode.sh
buildgcc.sh
Generate RingPostgreSQL Source Code and Build
cd ring/extensions/ringpostgresql
./gencode.sh
./buildgcc.sh
Generate RingQt Source Code and Build
cd ring/extensions/ringqt
./gencode.sh
./buildgcc.sh
To be able to call ring from any folder
cd ring/bin
sudo ./install.sh
Run Ring Notepad
cd ring/tools/ringnotepad
ring rnote.ring
111.3
Get the source code
git clone http://github.com/ring-lang/ring.git
Install Libraries
cd ring/language/src
./installdepfedora.sh
Build Ring (Compiler/VM)
sudo ./buildgcc.sh
Build Ring2EXE
cd ring/tools/ring2exe
sudo ./buildring2exe.sh
Generate RingConsoleColors Source Code and Build
cd ring/extensions/ringconsolecolors
./gencode.sh
./buildgcc.sh
Build RingInternet
111.3. Building using Fedora Linux 1748

Ring Documentation, Release 1.14
cd ring/extensions/ringinternet
./buildgcc.sh
Generate RingLibCurl Source Code and Build
cd ring/extensions/ringcurl
./gencode.sh
./buildgcc.sh
Generate RingZip Source Code and Build
cd ring/extensions/ringzip
./gencode.sh
./buildgcc.sh
Build RingPM
cd ring/tools/ringpm
sudo ./buildringpm.sh
Build RingODBC
cd ring/extensions/ringodbc
./buildgcc.sh
Build RingMySQL
cd ring/extensions/ringmysql
./buildgccfedora.sh
Build RingSQLite
cd ring/extensions/ringsqlite
./buildgcc.sh
Build RingPostgreSQL
cd ring/extensions/ringpostgresql
gencode.sh
buildgcc.sh
Build RingOpenSSL
cd ring/extensions/ringopenssl
./buildgcc.sh
Build RingMurmurHash
cd ring/extensions/ringmurmurhash
./buildgcc.sh
Generate RingAllegro Source Code and Build
cd ring/extensions/ringallegro
./gencode.sh
./buildgcc.sh
111.3. Building using Fedora Linux 1749

Ring Documentation, Release 1.14
Generate RingLibuv Source Code and Build
We will build Libuv rst
cd ring/extensions/ringlibuv/libuv
sudo dnf install libtool m4 autoconf automake
sh autogen.sh
./configure
make
make check
sudo make install
Then we will build RingLibuv
cd ring/extensions/ringlibuv
./gencode.sh
./buildgcc.sh
Generate RingFreeGLUT Source Code and Build
cd ring/extensions/ringfreeglut
./gencode.sh
./buildgcc.sh
Generate RingOpenGL Source Code and Build
The ringopengl folder contains many sub folders for different OpenGL versions
Starting from OpenGL 1.1 to OpenGL 4.6
cd ring/extensions/ringopengl/opengl21
gencode.sh
buildgcc.sh
Generate RingPostgreSQL Source Code and Build
cd ring/extensions/ringpostgresql
./gencode.sh
./buildgcc.sh
Generate RingQt Source Code and Build
cd ring/extensions/ringqt
./gencode.sh
./buildgccfedora.sh
To be able to call ring from any folder
cd ring/bin
sudo ./install.sh
Run Ring Notepad
cd ring/tools/ringnotepad
ring rnote.ring
111.3. Building using Fedora Linux 1750

Ring Documentation, Release 1.14
111.4
Get the source code
git clone http://github.com/ring-lang/ring.git
Install homebrew (follow the directions on homebrew's homepage). Install Libraries
cd ring/language/src
./installdepmac.sh
Build Ring (Compiler/VM)
./buildclang.sh
Build Ring2EXE
cd ring/tools/ring2exe
sudo ./buildring2exe.sh
Generate RingConsoleColors Source Code and Build
cd ring/extensions/ringconsolecolors
./gencode.sh
./buildclang.sh
Build RingInternet
cd ring/extensions/ringinternet
./buildclang.sh
Generate RingLibCurl Source Code and Build
cd ring/extensions/ringcurl
./gencode.sh
./buildclang.sh
Generate RingZip Source Code and Build
cd ring/extensions/ringzip
./gencode.sh
./buildclang.sh
Build RingPM
cd ring/tools/ringpm
sudo ./buildringpm.sh
Build RingODBC
cd ring/extensions/ringodbc
./buildclang.sh
Build RingMySQL
cd ring/extensions/ringmysql
./buildclang.sh
111.4. Building using MacOS X 1751

Ring Documentation, Release 1.14
Build RingSQLite
cd ring/extensions/ringsqlite
./buildclang.sh
Build RingPostgreSQL
cd ring/extensions/ringpostgresql
gencode.sh
buildclang.sh
Build RingOpenSSL
cd ring/extensions/ringopenssl
./buildclang.sh
Build RingMurmurHash
cd ring/extensions/ringmurmurhash
./buildclang.sh
Generate RingAllegro Source Code and Build
cd ring/extensions/ringallegro
./gencode.sh
./buildclang.sh
Generate RingLibuv Source Code and Build
cd ring/extensions/ringlibuv
./gencode.sh
./buildclang.sh
Generate RingFreeGLUT Source Code and Build
cd ring/extensions/ringfreeglut
./gencode.sh
./buildclang.sh
Generate RingOpenGL Source Code and Build
The ringopengl folder contains many sub folders for different OpenGL versions Starting from OpenGL 1.1 to OpenGL
4.6
cd ring/extensions/ringopengl/opengl21
./gencode.sh
./buildclang.sh
Generate RingPostgreSQL Source Code and Build
cd ring/extensions/ringpostgresql
./gencode.sh
./buildclang.sh
Generate RingQt Source Code and Build
cd ring/extensions/ringqt
./gencodemac.sh
./buildclang.sh
111.4. Building using MacOS X 1752

Ring Documentation, Release 1.14
To be able to call ring from any folder
cd ring/bin
sudo ./install.sh
Run Ring Notepad
cd ring/tools/ringnotepad
sudo ring rnote.ring
111.5
This will build the Ring compiler and Ring Virtual Machine
cmake .
make
111.5. Building using CMake 1753

CHAPTER
TWO
HOW TO CONTRIBUTE?
Ring is a free-open source project, Everyone is welcome to contribute to Ring.
Project Home :
To editing on web browser without Git client, when login GitHub then click pencil icon in target le. Then, sends pull
request.
You can help in many parts in the project
•
•
•
•
•
•
•
•
•
112.1
Throughout the creation of this project, Ring relied heavily on contributions from experts along with college students.
Their input was invaluable, and we want to take a moment to thank them and recognize them for all of their hard work.
Ring Team:
112.2
You can modify anything in the documentation, by updating the text les (*.txt) in this folder :
ring-lang/ring/tree/master/documents/source
The documentation is created using Sphinx :
1754

Ring Documentation, Release 1.14
112.3
You can write new tests in this folder
https://github.com/ring-lang/ring/tree/master/language/tests/scripts
112.4
You can add new samples to this folder
https://github.com/ring-lang/ring/tree/master/samples
112.5
You can add new applications to this folder
https://github.com/ring-lang/ring/tree/master/applications
112.6
You can help in supporting Ring in different code editors
Check the next folder
https://github.com/ring-lang/ring/tree/master/tools/editors
112.7
You can update and add libraries to this folder
https://github.com/ring-lang/ring/tree/master/libraries
112.8
You can add and update extensions in this folder
https://github.com/ring-lang/ring/tree/master/extensions
112.3. Testing 1755

Ring Documentation, Release 1.14
112.9
•
•
112.9. Compiler and Virtual Machine (VM) 1756

CHAPTER
THREE
LANGUAGE SPECIFICATION
In this chapter we will learn about
•
•
•
•
•
•
•
113.1
Keywords Count : 49
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1757

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
113.1. Language Keywords 1758

Ring Documentation, Release 1.14
113.2
Functions Count : 236
acos()
add()
addattribute()
adddays()
addmethod()
addsublistsbyfastcopy()
addsublistsbymove()
ascii()
asin()
assert()
atan()
atan2()
attributes()
binarysearch()
bytes2double()
bytes2float()
bytes2int()
callgarbagecollector()
callgc()
ceil()
cfunctions()
char()
chdir()
checkoverflow()
classes()
classname()
clearerr()
clock()
clockspersecond()
closelib()
copy()
cos()
cosh()
currentdir()
date()
dec()
decimals()
del()
diffdays()
dir()
direxists()
double2bytes()
eval()
exefilename()
exefolder()
exp()
fabs()
fclose()
feof()
ferror()
fexists()
fflush()
fgetc()
(continues on next page)
113.2. Language Functions 1759

Ring Documentation, Release 1.14
(continued from previous page)
fgetpos()
fgets()
filename()
find()
float2bytes()
floor()
fopen()
fputc()
fputs()
fread()
freopen()
fseek()
fsetpos()
ftell()
functions()
fwrite()
getarch()
getattribute()
getchar()
getpathtype()
getpointer()
getptr()
globals()
hex()
hex2str()
input()
insert()
int2bytes()
intvalue()
isalnum()
isalpha()
isandroid()
isattribute()
iscfunction()
isclass()
iscntrl()
isdigit()
isfreebsd()
isfunction()
isglobal()
isgraph()
islinux()
islist()
islocal()
islower()
ismacosx()
ismethod()
ismsdos()
isnull()
isnumber()
isobject()
ispackage()
ispackageclass()
ispointer()
isprint()
isprivateattribute()
isprivatemethod()
(continues on next page)
113.2. Language Functions 1760

Ring Documentation, Release 1.14
(continued from previous page)
ispunct()
isspace()
isstring()
isunix()
isupper()
iswindows()
iswindows64()
isxdigit()
left()
len()
lines()
list()
list2str()
loadlib()
locals()
log()
log10()
lower()
max()
memcpy()
memorycopy()
mergemethods()
methods()
min()
murmur3hash()
newlist()
nofprocessors()
nullpointer()
nullptr()
number()
obj2ptr()
object2pointer()
objectid()
packageclasses()
packagename()
packages()
perror()
pointer2object()
pointer2string()
pointercompare()
pow()
prevfilename()
ptr2obj()
ptr2str()
ptrcmp()
raise()
random()
randomize()
read()
remove()
rename()
reverse()
rewind()
right()
ring_give()
ring_see()
ring_state_delete()
(continues on next page)
113.2. Language Functions 1761

Ring Documentation, Release 1.14
(continued from previous page)
ring_state_filetokens()
ring_state_findvar()
ring_state_init()
ring_state_main()
ring_state_mainfile()
ring_state_new()
ring_state_newvar()
ring_state_runcode()
ring_state_runfile()
ring_state_runobjectfile()
ring_state_setvar()
ringvm_callfunc()
ringvm_calllist()
ringvm_cfunctionslist()
ringvm_classeslist()
ringvm_evalinscope()
ringvm_fileslist()
ringvm_functionslist()
ringvm_genarray()
ringvm_give()
ringvm_hideerrormsg()
ringvm_info()
ringvm_memorylist()
ringvm_packageslist()
ringvm_passerror()
ringvm_scopescount()
ringvm_see()
ringvm_settrace()
ringvm_tracedata()
ringvm_traceevent()
ringvm_tracefunc()
setattribute()
setpointer()
setptr()
shutdown()
sin()
sinh()
sort()
space()
sqrt()
srandom()
str2hex()
str2hexcstyle()
str2list()
strcmp()
string()
substr()
swap()
sysget()
sysset()
system()
sysunset()
tan()
tanh()
tempfile()
tempname()
time()
(continues on next page)
113.2. Language Functions 1762

Ring Documentation, Release 1.14
(continued from previous page)
timelist()
trim()
type()
ungetc()
unsigned()
upper()
uptime()
variablepointer()
varptr()
version()
windowsnl()
write()
113.3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
113.3. Compiler Errors 1763

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
113.4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
113.4. Runtime Errors 1764

Ring Documentation, Release 1.14
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
113.5
•
•
•
•
•
•
•
•
113.5. Environment Errors 1765

Ring Documentation, Release 1.14
113.6
Program —> {statement}
Statement —> `package' <Identier> { `.' <Identier> } [`{` {statement} `}'] [`end'|'endpackage']
Statement —> `class' <Identier> [ `from'|':'|'<' <Identier> ] [`{` {statement} `}'][`end'|'endclass']
Statement —> `func'|'def' <Identier> [ParaList] [`{` {statement} `}'][`end'|'endfunc']
Statement —> `import' <Identier> { `.' <Identier> }
Statement —> `private'
Statement —> `load' [`package'|'again'] <Literal>
Statement —> `loadsyntax' <Literal>
Statement —> `changeringkeyword' <OldKeyword> <NewKeyword>
Statement —> `changeringoperator' <OldOperator> <NewOperator>
Statement —> `see'|'put' <Expr>
Statement —> `give'|'get' <Identier>
Statement —> `if' <Expr> [`{`] {statement} [ {`but'|'elseif' <Expr> {Statement} } ] [`else' {Statement} ]
`ok'|'end'|'}'
Statement —> `Switch' <Expr> [`{`] { `on'|'case' <Expr> {statement} } [`other' {Statement} ] `off'|'end'|'}'
Statement —> `for' <Identier> `=' <Expr> `to' <Expr> [ `step' <Expr> ] [`{`] {Statement} `next'|'end'|'}'
Statement —> `for' <Identier> `in' <Expr> [ `step' <Expr> ] [`{`] {statement} `next'|'end'|'}'
Statement —> `while' <Expr> [`{`] {statement} `end'|'}'
Statement —> `do' {statement} `again' <Expr>
Statement —> `try' {statement} [`{`] `catch' {statement} `done'|'end'|'}'
Statement —> `return' <Expr>
Statement —> `bye'
Statement —> `exit'
Statement —> `loop'
Statement —> <Expr>
Statement —> epslion
ParaList —> epslion
ParaList —> [`(`] <Identier> [{ `,' <Identier> }] [`)']
Expr —> <LogicNot> [{ `and'|'or' <LogicNot> }]
LogicNot –> [`not'] <EqualOrNot>
EqualOrNot –> [ `='|'!=' ] <Compare>
Compare —> <BitOrXor> [ { `<' | `>' | `<=' | `>=' <BitOrXor> } ]
BitOrXor —> <BitAnd> [ { `|' | `^' <BitAnd> } ]
BitAnd —> <BitShift> [ { `&' <BitShift> } ]
BitShift —> <Arithmetic> [ { `<<' | `>>' <Arithmetic> } ]
113.6. Language Grammar 1766

Ring Documentation, Release 1.14
Arithmetic —> <Term> [ { `+' | `-` <Term> } ]
Term —> <Range> [ { `*' | `/' | `%' <Range> } ]
Range —> <Factor> [ `:' <Factor> ]
Factor —> <Identier> [ {Mixer} ] [ `=' <Expr> ]
Factor —> <Number>
Factor —> <Literal>
Factor —> `:' <Identier>
Factor —> `-` <Factor>
Factor —> `(` <Expr> `)'
Factor —> <List>
Factor —> `new' <Identier>
Factor —> <AnonymousFunction>
Factor —> `call' <identier> { `.' <Identier> } `(` <Parameters> `)'
List —> `[` [ <Expr> { `,' <Expr> } ] `]'
Mixer —> { `.' <Identier> }
Mixer —> `[` <Expr> `]'
Mixer —> `(` [ <Expr> [ { `,' <Expr> }] ] `)'
Mixer —> `{` {Statement} `}'
AnonymousFunction —> `func'|'def'| [<ParaList>] `{` {Statement} `}'
113.7
Denitions :-
•
•
•
•
•
•
•
(Stack and Variables)
113.7. Virtual Machine (VM) Instructions 1767

Ring Documentation, Release 1.14
Operation Description
•
Add string from the IR to the stack
•
Add number from the IR to the stack
•
Replace VP in the stack[nSize] with the variable value
•
Read variable name from the IR, push VP to the stack
•
Stack[nSize-1] VV = Stack[nSize] VV , POP
Stack[nSize]
•
Increment Number in Stack[nSize] by 1
•
The same as ICO_LOADADDRESS then ICO_PUSHV
•
Store new line number (debug info)
•
Remove all items from the stack , nSize = 0
•
Store the source code le name (debug info)
•
Free the Scope List of the current Expression
(Jump)
Operation Description
•
Set PC to new value from the IR
•
If Stack[nSize] is a number = 0 then Set PC to new value
from the IR
•
End of for loop
•
If Stack[nSize] is a number = 1 then Set PC to new value
from the IR
•
As ICO_JUMPZERO but add 1 to the stack (required
for many `AND' conditions)
•
As ICO_JUMPONE but add 1 to the stack (required for
many `OR' conditions)
(Compare)
113.7. Virtual Machine (VM) Instructions 1768

Ring Documentation, Release 1.14
Operation Description
•
If stack[nSize-1] <= stack[nSize] , POP stack[nSize],
set Stack[nSize-1] = 1 else set Stack[nSize-1] = 0
•
If stack[nSize-1] = stack[nSize] , POP stack[nSize], set
Stack[nSize-1] = 1 else set Stack[nSize-1] = 0
•
If stack[nSize-1] < stack[nSize] , POP stack[nSize], set
Stack[nSize-1] = 1 else set Stack[nSize-1] = 0
•
If stack[nSize-1] > stack[nSize] , POP stack[nSize], set
Stack[nSize-1] = 1 else set Stack[nSize-1] = 0
•
If stack[nSize-1] >= stack[nSize] , POP stack[nSize],
set Stack[nSize-1] = 1 else set Stack[nSize-1] = 0
•
If stack[nSize-1] != stack[nSize] , POP stack[nSize], set
Stack[nSize-1] = 1 else set Stack[nSize-1] = 0
(Math)
Operation Description
•
Stack[nSize-1] = Stack[nSize-1] + Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] - Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] * Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] / Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] % Stack[nSize] , POP
stack[nSize]
•
Stack[nSize] = - Stack[nSize-1]
•
Stack[nSize] = Stack[nSize] + 1
•
Stack[nSize] = Stack[nSize] - 1
(Logic)
113.7. Virtual Machine (VM) Instructions 1769

Ring Documentation, Release 1.14
Operation Description
•
Stack[nSize-1] = Stack[nSize-1] && Stack[nSize] ,
POP stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] || Stack[nSize] , POP
stack[nSize]
•
Stack[nSize] = ! Stack[nSize]
(Lists)
Operation Description
•
Start New List in Temp. Memory
•
Add List Item
•
End List
•
Stack[nSize-1] = Stack[nSize-1] VV [ Stack[nSize] ] ,
POP stack[nSize]
(Functions)
113.7. Virtual Machine (VM) Instructions 1770

Ring Documentation, Release 1.14
Operation Description
•
Find function
•
Call function
•
Return from function
•
Return NULl from function
•
Return after eval()
•
Return the list item reference - not the value
•
Start new function
•
Flag to determine where to jump later (after
ICO_RETURN)
•
Start executing function
•
End function execution
•
Anonymous function
•
Delete temp. lists
(User Interface)
Operation Description
•
Print value to the standard output
•
Get input from the keyboard
(End Program/Loop)
113.7. Virtual Machine (VM) Instructions 1771

Ring Documentation, Release 1.14
Operation Description
•
End execution of VM
•
Place to exit to from a loop
•
Remove exit mark
•
Break from one loop or more
•
Continue to next loop
(For Better Performance)
Operation Description
•
Push pointer to the stack
•
Increment variable value using pointer
•
Push value of variable using variable pointer
•
Increment then jump
•
Increment using pointer then jump
•
Jump if variable value is <= numeric value
•
Jump if variable value (using pointer) <= numeric value
•
Push function pointer
•
Push pointer to local variable
•
Increment value using pointer to local variable then
jump
•
Jump if the variable value (using pointer) <= numeric
value
•
Increment value using variable pointer then jump (for
loop step = 1)
•
Increment value using variable pointer then jump (for
loop step = 1)
113.7. Virtual Machine (VM) Instructions 1772

Ring Documentation, Release 1.14
(Try-Catch-Done)
Operation Description
•
Start try region
•
End try region
(Duplicate and Range)
Operation Description
•
Duplicate stack value
•
Create list from value to value
(OOP)
113.7. Virtual Machine (VM) Instructions 1773

Ring Documentation, Release 1.14
Operation Description
•
Create new object, get class name from the IR, push ob-
ject pointer to the stack.
•
Called after creating new object, set the active scope to
be the object scope.
•
Get object attribute, push the pointer to the stack.
•
Find object method
•
Used after calling a method - normal case
•
Used after calling a method - second case
•
Start new class region
•
Open brace
•
End brace
•
Import package
•
start private attributes region
•
set attribute value - check for setter.
•
call class init() method.
(Other)
Operation Description
•
Copy by reference
•
Remove reference
•
Determine the left side variable
•
Determine operators like += , -= , . . . etc
(Bitwise Operators)
113.7. Virtual Machine (VM) Instructions 1774

Ring Documentation, Release 1.14
Operation Description
•
Stack[nSize-1] = Stack[nSize-1] & Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] | Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] ^ Stack[nSize] , POP
stack[nSize]
•
Stack[nSize] = ! Stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] << Stack[nSize] , POP
stack[nSize]
•
Stack[nSize-1] = Stack[nSize-1] >> Stack[nSize] , POP
stack[nSize]
(For Step)
Operation Description
•
Determine step number in for loop
•
POP step number from steps stack
•
Load the rst address of variable name
(Custom Global Scope)
Operation Description
•
Start new custom global scope - used by `load package'
command
•
End of custom global scope - used by `load package'
command
•
Set the current global scope
113.7. Virtual Machine (VM) Instructions 1775

CHAPTER
FOUR
RESOURCES
In this section you will nd resources about the language
114.1
For news about the language check the website
http://ring-lang.net
114.2
Ring is Free-Open Source (MIT License)
Source Code :
114.3
URL :
1776

INDEX
3D Camera
Using RingRayLib,
3D Camera Free
Using RingRayLib,
3D Cube and Texture
Using RingOpenGL and RingAllegro for 3D Graph-
ics,
3D Picking
Using RingRayLib,
AbstractAxis Class
RingQt Classes Reference,
AbstractBarSeries Class
RingQt Classes Reference,
Access List Items by String Index
Lists,
Access Objects Using Braces
Object Oriented Programming,
Access String Letters
Strings,
Accessing the class attributes from braces inside class
methods
Scope Rules,
Add Items
Lists,
addattribute()
Reection and Meta-programming,
AddDays()
Date and Time,
Adding code to the generated code
Code Generator,
Adding Hyperlink to QLabel
Desktop, WebAssembly and Mobile Development,
382
addmethod()
Reection and Meta-programming,
Analog Clock
Applications developed in a few hours,
Animate Class
Game Engine for 2D Games,
Animate Events
Game Engine for 2D Games,
Animation
Game Engine for 2D Games,
Animation and Functions
Game Engine for 2D Games,
Anonymous and Nested Functions
Functional Programming,
Application Class
Web DevelopmentCGI Library,
Application Database
Deploying Web Applications in the Cloud,
Applications
How to contribute?,
Applications developed in a few hours
Analog Clock,
FetchStockData Application,
Fifteen Puzzle Game,
Google API Shortener Application,
Innovative,
Introduction,
Practical,
Quotes about Ring,
Samples in this book,
Squares Puzzle Game,
Video-Music-Player Application,
apppath()
Stdlib Functions,
Arithmetic Operations
Performance Tips,
Arithmetic Operators
Operators,
ASCII Table application
What is new in Ring 1.12?,
Ascii()
Data Type,
ASCIIList2Str()
Stdlib Functions,
Assert()
Eval() and Debugging,
Assignment Operators
Operators,
attributes()
Reection and Meta-programming,
Basic Shapes
1777

Ring Documentation, Release 1.14
Using RingRayLib,
Basic Window
Using RingRayLib,
Better Call Command
What is new in Ring 1.2?,
Better Cards Game
What is new in Ring 1.8?,
Better Code Generator For Extensions
What is new in Ring 1.8?,
Better Code Generator for Extensions
What is new in Ring 1.1?,
What is new in Ring 1.5?,
What is new in Ring 1.9?,
Better Documentation
What is new in Ring 1.11?,
What is new in Ring 1.1?,
What is new in Ring 1.7?,
Better Documentation Generator for Extensions
What is new in Ring 1.5?,
Better Form Designer
What is new in Ring 1.8?,
Better Functions
What is new in Ring 1.14?,
What is new in Ring 1.2?,
Better Handling For Numbers
What is new in Ring 1.14?,
Better Loop|Exit Command
What is new in Ring 1.3?,
Better Memory Management
What is new in Ring 1.9?,
Better Natural Language Programming Support
What is new in Ring 1.1?,
Better Objects Library
What is new in Ring 1.5?,
Better Organization
What is new in Ring 1.13?,
Better Performance
What is new in Ring 1.11?,
What is new in Ring 1.8?,
Better Performance For Strings
What is new in Ring 1.14?,
Better Quality
What is new in Ring 1.2?,
What is new in Ring 1.5?,
Better Ring Compiler and VM
What is new in Ring 1.8?,
Better Ring For Android
What is new in Ring 1.6?,
Better Ring Notepad
What is new in Ring 1.2?,
What is new in Ring 1.3?,
What is new in Ring 1.5?,
What is new in Ring 1.6?,
What is new in Ring 1.7?,
What is new in Ring 1.9?,
Better Ring VM
What is new in Ring 1.7?,
Better Ring2EXE
What is new in Ring 1.7?,
Better RingOpenSSL
What is new in Ring 1.14?,
Better RingQt
What is new in Ring 1.11?,
What is new in Ring 1.13?,
What is new in Ring 1.2?,
What is new in Ring 1.3?,
What is new in Ring 1.4?,
What is new in Ring 1.5?,
What is new in Ring 1.6?,
What is new in Ring 1.7?,
What is new in Ring 1.8?,
What is new in Ring 1.9?,
Better RingRayLib
What is new in Ring 1.12?,
What is new in Ring 1.13?,
Better RingREPL
What is new in Ring 1.6?,
Better RingVM
What is new in Ring 1.6?,
Better RingZip
What is new in Ring 1.7?,
Better Scripts for building Ring
What is new in Ring 1.6?,
Better StdLib
What is new in Ring 1.3?,
What is new in Ring 1.4?,
What is new in Ring 1.5?,
What is new in Ring 1.6?,
What is new in Ring 1.9?,
Better Tests
What is new in Ring 1.10?,
Better Threads Support
What is new in Ring 1.13?,
Better Trace Library
What is new in Ring 1.7?,
Better WebLib
What is new in Ring 1.4?,
What is new in Ring 1.5?,
Bezier Lines
Using RingRayLib,
bignumber
BigNumber Class,
BigNumber Functions,
Examples,
Introduction,
Library Source Code,
Loading the library,
BigNumber Class
Index 1778

Ring Documentation, Release 1.14
bignumber,
BigNumber Functions
bignumber,
BigNumber Library
What is new in Ring 1.9?,
binarydigits()
Stdlib Functions,
Bitwise Operators
Operators,
BMI Calculator application
What is new in Ring 1.12?,
BraceError() Method
Natural Language Programming,
BraceExprEval Method
Natural Language Programming,
BraceStart and BraceEnd Methods
Natural Language Programming,
Branching
Control Structures,
Control Structures - Second Style,
Control Structures - Third Style,
BreakPoint
The Trace Library and the Interactive Debugger,
Build the extension on different platforms
Tutorial: Ring Extensions in C/C++,
Building From Source Code
Building using CMake,
Building using Fedora Linux,
Building using MacOS X,
Building using Microsoft Windows,
Building using Ubuntu Linux,
Introduction,
Building Games For Android
Building the project,
Download Requirements and Update the Android
SDK,
Introduction,
Project Folder,
Building RingQt Applications for Mobile
Comments about developing for Android using
RingQt,
Download Requirements,
Install Qt for Android,
Introduction,
The Qt project for your Ring application,
Update the Android SDK,
Using Ring2EXE,
Building RingQt Applications for WebAssembly
Comments about developing for WebAssembly us-
ing RingQt,
Dialogs,
Download Requirements,
Introduction,
Online Applications,
The Qt project for your Ring application,
Using Ring2EXE,
Building standalone console application
Distributing Ring Application using Ring2EXE,
Building the Cards Game for Mobile using RingQt
Distributing Ring Application using Ring2EXE,
Building the Form Designer for Mobile using RingQt
Distributing Ring Application using Ring2EXE,
Building the project
Building Games For Android,
Building the Weight History Application for Mobile using
RingQt
Distributing Ring Application using Ring2EXE,
Building using CMake
Building From Source Code,
Building using Fedora Linux
Building From Source Code,
Building using MacOS X
Building From Source Code,
Building using Microsoft Windows
Building From Source Code,
Building using Ubuntu Linux
Building From Source Code,
Calculator Application
What is new in Ring 1.5?,
Calendar application
What is new in Ring 1.12?,
Call Functions
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
callgc()
Low Level Functions,
Calling a function sharing the name with a method in the
current class
Scope Rules for Functions and Methods,
Calling Functions and Methods
Performance Tips,
Camera
Using Qt3D,
Camera First Person
Using RingRayLib,
Can I connect to dbase/harbour database?
Frequently Asked Questions,
Can Ring work on Windows XP?
Frequently Asked Questions,
capitalized()
Stdlib Functions,
cfunctions()
Reection and Meta-programming,
CGI Support
Command Line Options,
Change Focus
Index 1779

Ring Documentation, Release 1.14
Desktop, WebAssembly and Mobile Development,
420
Change Language Keywords
Syntax Flexibility,
Change Language Operators
Syntax Flexibility,
Change the = operator to is
Natural Language Programming,
Change the Ring Keyword And
Natural Language Programming,
Change the Ring Operator +
Natural Language Programming,
Change: Basic Extensions are separated from RingVM
What is new in Ring 1.4?,
changestring()
Stdlib Functions,
Char()
Data Type,
ChDir() Function
System Functions,
Check Character
Data Type,
Check Data Type
Data Type,
Check Parameters Count
Extension,
Check Parameters Type
Extension,
Checkers Game
What is new in Ring 1.11?,
Chess Game
What is new in Ring 1.10?,
Classes and Objects
Object Oriented Programming,
Classes and their Methods to use the default events
Desktop, WebAssembly and Mobile Development,
451
classes()
Reection and Meta-programming,
classname()
Reection and Meta-programming,
Clean Natural Code
Natural Language Programming,
Clearerr()
Files,
Client Example
RingLibuv,
Client Example - Using Classes
RingLibuv,
clock()
Date and Time,
Close Window Event
RingLibSDL,
ClosPerSecond()
Date and Time,
Code Generator
Adding code to the generated code,
Comments in conguration le,
Conguration le,
Conguration le for the Allegro library,
Conguration Files Examples,
Constants Type,
Dening Constants,
Determine Structure Members Types,
Enum and Numbers,
Executing code during code generation,
Filtering using Expressions,
function prototype,
Introduction,
Loading Files,
Managed Classes,
Prex for Functions Names,
Qt conguration le,
Register New Functions,
Static Methods,
Threads Support,
Using conguration le that wrap C++ library,
Using the tool,
Wrap structures,
Wrapping C++ Classes,
CodeEditor Class
RingQt Classes Reference,
Collision Area
Using RingRayLib,
Colors Palette
Using RingRayLib,
Command Line Options
CGI Support,
Generate Embedded Object File,
Generate Object File,
Introduction,
No Run,
Performance,
Printing Final Intermediate Code,
Printing Instruction Operation Code,
Printing Intermediate Code,
Printing Rules,
Printing Tokens,
Comments about developing for Android using RingQt
Building RingQt Applications for Mobile,
Comments about developing for WebAssembly using
RingQt
Building RingQt Applications for WebAssembly,
523
Comments about evaluation
Control Structures - First Style,
Comments in conguration le
Code Generator,
Index 1780

Ring Documentation, Release 1.14
Compact Syntax
Language Design,
Compiler and Virtual MachineVM
How to contribute?,
Compiler Errors
Language Specication,
Compiling on Manjaro Linux
What is new in Ring 1.8?,
Composition
Object Oriented Programming,
Conguration le
Code Generator,
Conguration le for the Allegro library
Code Generator,
Conguration Files Examples
Code Generator,
Congure the Apache web server
Using XAMPP Apache web server,
Web DevelopmentCGI Library,
Conict between Class Attributes and Local Variables
Scope Rules,
Conict between Global Variables and Class Attributes
Frequently Asked Questions,
Scope Rules,
Conict between self inside braces and self in the class
region
Scope Rules,
Constants
socket,
Constants Type
Code Generator,
Constructor methods in Ring
Frequently Asked Questions,
Context Menu
Desktop, WebAssembly and Mobile Development,
364
Control Gallery
libui,
Control Structures
Branching,
Looping,
Control Structures - First Style
Comments about evaluation,
Do Again Loop,
Exit,
Exit from two loops,
For In Loop,
for in to modify lists,
For Loop,
Introduction,
Loop Command,
Looping,
Short-circuit evaluation,
Step Option,
Switch Statement,
While Loop,
Control Structures - Second Style
Branching,
Exceptions,
For In Loop,
For Loop,
If Statement,
Introduction,
Looping,
Switch Statement,
Control Structures - Third Style
Branching,
Exceptions,
For In Loop,
For Loop,
If Statement,
Introduction,
Switch Statement,
While Loop,
Conversion
Data Type,
Conversion Class
Stdlib Classes,
Convert between Numbers and Bytes
What is new in Ring 1.4?,
Convert Letters Case
Strings,
Cookies
Web DevelopmentCGI Library,
Copy Lists
Lists,
Copy()
Strings,
Could you explain the output of the StrCmp() function?
Frequently Asked Questions,
Create Database
MySQL Functions,
Create Executable File
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
Create Lists
Lists,
Create Multi Dimension Array Using List and Recursion
Lists,
Create Package in the Current Folder
Ring Package ManagerRingPM,
Create Table
Tutorial: Ring Extensions in C/C++,
Create Table and Insert Data
MySQL Functions,
Create Window
RingLibSDL,
Index 1781

Ring Documentation, Release 1.14
Create your rst extension
Introduction,
Location,
Steps to create the extension,
Testing the extension,
Create Zip File
RingZip,
Creating a Class for each Window in GUI applications
Scope Rules,
Creating Lists
Performance Tips,
Creating Menubar
Desktop, WebAssembly and Mobile Development,
362
Creating more than one window
Desktop, WebAssembly and Mobile Development,
402
Creating New Package
Ring Package ManagerRingPM,
Creating Reports using the WebLib and the GUILib
Desktop, WebAssembly and Mobile Development,
457
Creating StatusBar
Desktop, WebAssembly and Mobile Development,
366
Creating the Game Window
Game Engine for 2D Games,
Creating the Qt resource le using Folder2qrc
Distributing Ring Application using Ring2EXE,
Creating Threads
Threads,
Creating Toolbar
Desktop, WebAssembly and Mobile Development,
365
Creating Windows Installer
Distributing Ring Application,
CRUD Example using MVC
Web DevelopmentCGI Library,
Cubic Map
Using RingRayLib,
CurrentDir() Function
System Functions,
Customers Form
What is new in Ring 1.14?,
Data Representation
Language Design,
Data Type
Ascii(),
Char(),
Check Character,
Check Data Type,
Conversion,
Dec(),
Hex(),
Hex2str(),
Introduction,
IsAlNum(),
IsAlpha(),
IsCntrl(),
IsDigit(),
IsGraph(),
IsList(),
IsLower(),
IsNULL(),
IsNumber(),
IsPrint(),
IsPunct(),
IsSpace(),
IsString(),
IsUpper(),
IsXdigit(),
Number(),
Str2Hex(),
String(),
Type(),
Database, ModelBase & ControllerBase classes
Web DevelopmentCGI Library,
DataType Class
Stdlib Classes,
Date and Time
AddDays(),
clock(),
ClosPerSecond(),
Date(),
DiffDays(),
EpochTime(),
Introduction,
Time(),
TimeList(),
Date()
Date and Time,
DateTime Class
Stdlib Classes,
dayofweek()
Stdlib Functions,
Debug Class
Stdlib Classes,
Dec()
Data Type,
Decimals()
Mathematical Functions,
Declarative Programming
Declarative programming on the top of Object-
Oriented,
executing code after the end of object access,
Introduction,
More Beatiful Code,
Index 1782

Ring Documentation, Release 1.14
Objects inside lists,
Return object by reference,
Declarative programming on the top of Object-Oriented
Declarative Programming,
Declare parameters
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
Decrypt()
Security and Internet Functions,
Deep Copy
Variables,
Default value for object attributes
Object Oriented Programming,
Default value for object attributes is NULL
What is new in Ring 1.8?,
Dene Declarative Languages
Language Design,
Dene Functions
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
Dene Natural Statements
Language Design,
Dening Commands
Using the Natural Library,
Dening commands using classes
Using the Natural Library,
Dening Constants
Code Generator,
Dening Variables and Variables Access
Scope Rules,
Delete Item From List
Lists,
Deleting All Packages
Ring Package ManagerRingPM,
Demo Programs
Introduction,
Language Shell,
Main Menu,
The Cards Game,
Deploying after updates
Deploying Web Applications in the Cloud,
Deploying Web Applications in the Cloud
Application Database,
Deploying after updates,
Hello World program,
Introduction,,
Local Tests,
Ring source code les and permissions,
Usage,
Deploying Web applications in the Cloud
What is new in Ring 1.9?,
Designed for a clear goal
Language Design,
Desktop Screen Shot Application
What is new in Ring 1.11?,
Desktop, WebAssembly and Mobile Development
Adding Hyperlink to QLabel,
Change Focus,
Classes and their Methods to use the default events,
451
Context Menu,
Creating Menubar,
Creating more than one window,
Creating Reports using the WebLib and the GUILib,
457
Creating StatusBar,
Creating Toolbar,
Dialog Functions,
Display Image using QLabel,
Display Scaled Image using QLabel,
Drawing using QPainter,
Dynamic Objects,
Inheritance from GUI Classes,
KeyPress and Mouse Move Events,
Menubar and StyleSheet Example,
Methods to use Events with Events Filter,
Movable Label Example,
Moving Objects using the Mouse,
New Classes names - Index Start from 1,
Notepad Application,
Other Widgets Events,
Playing Sound,
Printing using QPrinter,
QLineEdit Events and QMessageBox,
QMessagebox Example,
QVideoWidget and QMediaPlayer,
Regular Expressions,
RingQt Classes and their Qt Documentation,
Rotate Text,
Simple Client and Server Example,
The Cards Game,
The Difference between Qt and RingQt,
The Events Loop,
The First GUI Application,
Using Layout,
Using QCheckBox,
Using QComboBox Class,
Using QDateEdit,
Using QDesktopWidget Class,
Using QDial,
Using QDockWidget,
Using QFrame,
Using QInputDialog Class,
Using qLCDNumber,
Using QPrintPreviewDialog,
Using QProgressBar,
Index 1783

Ring Documentation, Release 1.14
Using QProgressBar and Timer,
Using QRadioButton and QButtonGroup,
Using QSlider,
Using QSpinBox,
Using QTableWidget,
Using QTabWidget,
Using QTreeView and QFileSystemModel,
Using QTreeWidget and QTreeWidgetItem,
Using QWebView,
Using the QColorDialog Class,
Using the QFileDialog Class,
Using the QListWidget Class,
Using the QTextEdit Class,
Using the QTimer Class,
Weight History Application,
Determine Structure Members Types
Code Generator,
Dialog Functions
Desktop, WebAssembly and Mobile Development,
410
Dialogs
Building RingQt Applications for WebAssembly,
524
DiffDays()
Date and Time,
Dir()
Files,
Direxists()
Files,
Disable BreakPoints
The Trace Library and the Interactive Debugger,
Discovering Packages
Ring Package ManagerRingPM,
Display Error Message
Extension,
Display Image
RingLibSDL,
Display Image using QLabel
Desktop, WebAssembly and Mobile Development,
386
Display List
Tutorial: Ring Extensions in C/C++,
Display PNG Images
RingLibSDL,
Display Scaled Image using QLabel
Desktop, WebAssembly and Mobile Development,
395
Display Transparent Images
RingLibSDL,
Display Warnings Option
What is new in Ring 1.2?,
Distributing Applications and Games for Mobile
Distributing Ring Application,
Distributing Applications for Microsoft Windows
Distributing Ring Application,
Distributing Applications for Mobile using RingQt
Distributing Ring Application using Ring2EXE,
Distributing Applications for WebAssembly using RingQt
Distributing Ring Application using Ring2EXE,
Distributing Ring Application
Creating Windows Installer,
Distributing Applications and Games for Mobile,
841
Distributing Applications for Microsoft Windows,
840
Introduction,
Protecting the Source Code,
The les ring.ring and ring.ringo,
Using C/C++ Compiler and Linker,
Distributing Ring Application using Ring2EXE
Building standalone console application,
Building the Cards Game for Mobile using RingQt,
847
Building the Form Designer for Mobile using
RingQt,
Building the Weight History Application for Mobile
using RingQt,
Creating the Qt resource le using Folder2qrc,
Distributing Applications for Mobile using RingQt,
846
Distributing Applications for WebAssembly using
RingQt,
Distributing RingAllegro Applications,,
Example,
How Ring2EXE works?,
Important Information about Ring2EXE,
Introduction,
Options,
Using Ring2EXE,
Distributing RingAllegro Applications
Distributing Ring Application using Ring2EXE,,
846
Do Again Loop
Control Structures - First Style,
Documentation
How to contribute?,
Download Requirements
Building RingQt Applications for Mobile,
Building RingQt Applications for WebAssembly,
522
Download Requirements and Update the Android SDK
Building Games For Android,
Download()
Security and Internet Functions,
Draw Gradient
libui,
Draw Ofce
Using Qt3D,
Index 1784

Ring Documentation, Release 1.14
Draw Rectangle
RingLibSDL,
Draw Ring
Using RingRayLib,
Drawing Cone
Using Qt3D,
Drawing Cube
Using Qt3D,
Drawing Cylinder
Using Qt3D,
Drawing Plane
Using Qt3D,
Drawing Sample
libui,
Drawing Sphere
Using Qt3D,
Drawing Text
Game Engine for 2D Games,
Drawing Torus
Using Qt3D,
Drawing using QPainter
Desktop, WebAssembly and Mobile Development,
397
Drawing using RingOpenGL
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Drawing, Animation and Input
Graphics and Game Programming,
Dynamic Attributes
Object Oriented Programming,
Dynamic Objects
Desktop, WebAssembly and Mobile Development,
424
Dynamic Typing
Variables,
Editors Support
How to contribute?,
Embedding Ring in Ring
Embedding Ring in Ring,
Embedding Ring in Ring without sharing the State,
299
ring_state_letokens() function,
ring_state_new() and ring_state_mainle(),
ring_state_setvar(),
Runtime Errors when Embedding Ring in Ring,
Serial Execution of Programs,
Embedding Ring in Ring without sharing the State
Embedding Ring in Ring,
What is new in Ring 1.3?,
Embedding Ring Language in C/C++ Programs
Introduction,
Ring State,
Ring State Functions,
Ring State Variables,
Employee Application
What is new in Ring 1.6?,
Encourage Organization
Language Design,
Encrypt()
Security and Internet Functions,
endswith()
Stdlib Functions,
Entering Items
Form Designer,
Enum and Numbers
Code Generator,
Environment Errors
Language Specication,
EpochTime()
Date and Time,
Stdlib Functions,
Equality of functions
Functional Programming,
Erlang B Formula
What is new in Ring 1.14?,
Escape Game
What is new in Ring 1.13?,
Eval()
Eval() and Debugging,
Eval() and Debugging
Assert(),
Eval(),
Introduction,
Raise(),
Try/Carch/Done,
evenorodd()
Stdlib Functions,
Events Code
Form Designer,
Example
Distributing Ring Application using Ring2EXE,
Files,
FoxRing Functions Reference,
Mathematical Functions,
Natural Language Programming,
Objects Library for RingQt Application,
RingMurmurHash Functions Reference,
Security and Internet Functions,
System Functions,
The Type Hints Library,
Example - The Trace Library
Low Level Functions,
Example - Using the Trace Functions
Low Level Functions,
Example about Sharing Names between Functions and
Methods
Scope Rules for Functions and Methods,
Index 1785

Ring Documentation, Release 1.14
Examples
bignumber,
PostgreSQL,
Exceptions
Control Structures - Second Style,
Control Structures - Third Style,
Execute Program Line by Line
The Trace Library and the Interactive Debugger,
Execute Query and Print Result
ODBC Functions,
executing code after the end of object access
Declarative Programming,
Executing code during code generation
Code Generator,
ExeFileName() Function
System Functions,
ExeFolder() Function
System Functions,
Exit
Control Structures - First Style,
Exit from two loops
Control Structures - First Style,
Extension
Check Parameters Count,
Check Parameters Type,
Display Error Message,
Fopen() and Fclose() Implementation,
Function Prototype,
Function Structure,
Get Parameters Values,
Introduction,
Module Organization,
MySQL_Columns() Implementation,
Return Value,
RING API - list Functions,
RING API - String Functions,
ring_ext.c,
ring_ext.h,
Shared Libraries,
Sin() Implementation,
Using RING_API_RETMANAGEDCPOINTER(),
1437
Extensions in C/C++
How to contribute?,
Extract Zip File
RingZip,
Extruded Text
Using Qt3D,
Facebook Login
RingLibCurl,
factorial()
Stdlib Functions,
factors()
Stdlib Functions,
Fast Enough For Many Applications
Language Design,
Fclose()
Files,
Features
Introduction,
Ring Package ManagerRingPM,
Feof()
Files,
Ferror()
Files,
FetchStockData Application
Applications developed in a few hours,
Fexists()
Files,
Fush()
Files,
Fgetc()
Files,
Fgetpos()
Files,
Fgets()
Files,
bonacci()
Stdlib Functions,
Fifteen Puzzle Game
Applications developed in a few hours,
File Class
Stdlib Classes,
File Hash
Security and Internet Functions,
le2list()
Stdlib Functions,
Files
Clearerr(),
Dir(),
Direxists(),
Example,
Fclose(),
Feof(),
Ferror(),
Fexists(),
Fush(),
Fgetc(),
Fgetpos(),
Fgets(),
Fopen(),
Fputc(),
Fputs(),
Fread(),
Freopen(),
Fseek(),
Fsetpos(),
Index 1786

Ring Documentation, Release 1.14
Ftell(),
Fwrite(),
Getpathtype(),
Introduction,
Numbers and Bytes,
Perror(),
Read File using Read(),
Remove(),
Rename(),
Rewind(),
Temple(),
Tempname(),
Ungetc(),
Write le using Write(),
Filter List Items
Tutorial: Ring Extensions in C/C++,
lter()
Stdlib Functions,
Filtering using Expressions
Code Generator,
Find in les Application
What is new in Ring 1.8?,
Find SubString
Strings,
Find() and List of Objects
Object Oriented Programming,
First Application using RingLibuv
RingLibuv,
First-Class Functions
Functional Programming,
First-Class Lists
Lists,
Flappy Bird 3000 Game
Game Engine for 2D Games,
Following Eyes
Using RingRayLib,
Fopen()
Files,
Fopen() and Fclose() Implementation
Extension,
For In Loop
Control Structures - First Style,
Control Structures - Second Style,
Control Structures - Third Style,
for in to modify lists
Control Structures - First Style,
For Loop
Control Structures - First Style,
Control Structures - Second Style,
Control Structures - Third Style,
Form Designer
Entering Items,
Events Code,
Introduction,
Keyboard Shortcuts,
Menubar Designer,
More Samples and Tests,
Running Forms,
The Designer Windows,
The Properties,
Using Layouts,
What is new in Ring 1.3?,
Window Flags,
Form Designer Translation
Multi-language applications,
Forms Translation
Multi-language applications,
FoxRing functions
FoxRing Functions Reference,
FoxRing Functions Reference
Example,
FoxRing functions,
frAbs() function,
frAddBs() function,
frALines() function,
frAllTrim() function,
frAsc() function,
frAt() function,
frAtC() function,
frBetween() function,
frChr() function,
frEmpty() function,
frFile() function,
frFileToStr() function,
frForceExt() function,
frForcePath() function,
frIIf() function,
frInList() function,
frInt() function,
frJustDrive() function,
frJustExt() function,
frJustFName() function,
frJustPath() function,
frJustStem() function,
frLen() function,
frListToString() function,
frLTrim() function,
frPadL() function,
frPadR() function,
frProper() function,
frReplicate() function,
frRTrim() function,
frSetIfEmpty() function,
frSetSeparatorTo() function,
frSpace() function,
frStr() function,
frStringToList() function,
frStrTran() function,
Index 1787

Ring Documentation, Release 1.14
frStuff() function,
frSubStr() function,
frTransform() function,
frVal() function,
frVarType() function,
Introduction,
FoxRing Library
What is new in Ring 1.8?,
Fputc()
Files,
Fputs()
Files,
frAbs() function
FoxRing Functions Reference,
frAddBs() function
FoxRing Functions Reference,
frALines() function
FoxRing Functions Reference,
frAllTrim() function
FoxRing Functions Reference,
Frame Action
Using Qt3D,
Frames Per Second
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
frAsc() function
FoxRing Functions Reference,
frAt() function
FoxRing Functions Reference,
frAtC() function
FoxRing Functions Reference,
frBetween() function
FoxRing Functions Reference,
frChr() function
FoxRing Functions Reference,
Fread()
Files,
frEmpty() function
FoxRing Functions Reference,
Freopen()
Files,
Frequently Asked Questions
Can I connect to dbase/harbour database?,
Can Ring work on Windows XP?,
Conict between Global Variables and Class At-
tributes,
Constructor methods in Ring,
Could you explain the output of the StrCmp() func-
tion?,
Getter and Setter Methods,
Goal of including the "Main" function in Ring,
How can I disable maximize button and resize win-
dow?,
How to add Combobox and other elements to the
cells of a QTableWidget?,
How to Close a window then displaying another
one?,
How to create a Modal Window?,
How to create an array of buttons in GUI applica-
tions?,
How to extend RingQt and add more classes?,
How to get the current source le path?,
How to get the le size using ftell() and fseek() func-
tions?,
How to insert an item to the rst position in the list?,
1729
How to perform some manipulations on selected
cells in QTableWidget?,
How to print keys or values only in List/Dictionary?,
1724
How to print lists that contains objects?,
How to print new lines and other characters?,
How to use many source code les in the project?,
1726
How to use NULL and ISNULL() function?,
How to use SQLite using ODBC?,
Introduction,
Is Ring some sort of an improvement of PHP?,
List index start from 1,
Philosophy behind data types in Ring,
Search of global names while dening the class at-
tributes,
The documentation says functional programming is
supported, but then this happens?,
What about Data Representation in Ring?,
What about Memory Management in Ring?,
What about predened parameters or optional pa-
rameters in functions?,
What about the Boolean values in Ring?,
What are the advantages of using Ring over native C
or C++?,
What are the advantages to using Ring over C# or
Java?,
What are the advantages to using Ring over Lisp or
Smalltalk?,
What are the advantages to using Ring over Python
and Ruby?,
What are the advantages to using Ring over Tcl and
Lua?,
What happens when we create a new object?,
What is the difference between Ring and Python?
And is Ring Open Source?,
What is the Ring Architecture?,
Where can I write a program and execute it?,
Which of 3 coding styles are commonly used or rec-
ommended by the community?,
Why do we need Yet Another Programming Lan-
Index 1788

Ring Documentation, Release 1.14
guage (YAPL)?,
Why I get a strange result when printing nl with
lists?,
Why I get Calling Function without denition Er-
ror?,
Why is Ring largely focussed on UI creation?,
Why is Ring weakly typed?,
Why Ring is not case-sensitive,
Why Ring uses See, Give, But and Ok Key-
words?,
Why setClickEvent() doesnt see the object methods
directly?,
Why the ability to dene your own languages Instead
of just handing over the syntax so you can parse
it using whatever code you like?,
Why the Assignment operator uses Deep copy?,
1718
Why the window title bar is going outside the
screen?,
Why this example use the GetChar() twice?,
Why we dont use () after the QApp class name?,
1730
Why you can specify the number of loops you want
to break out of?,
frFile() function
FoxRing Functions Reference,
frFileToStr() function
FoxRing Functions Reference,
frForceExt() function
FoxRing Functions Reference,
frForcePath() function
FoxRing Functions Reference,
frIIf() function
FoxRing Functions Reference,
frInList() function
FoxRing Functions Reference,
frInt() function
FoxRing Functions Reference,
frJustDrive() function
FoxRing Functions Reference,
frJustExt() function
FoxRing Functions Reference,
frJustFName() function
FoxRing Functions Reference,
frJustPath() function
FoxRing Functions Reference,
frJustStem() function
FoxRing Functions Reference,
frLen() function
FoxRing Functions Reference,
frListToString() function
FoxRing Functions Reference,
frLTrim() function
FoxRing Functions Reference,
frPadL() function
FoxRing Functions Reference,
frPadR() function
FoxRing Functions Reference,
frProper() function
FoxRing Functions Reference,
frReplicate() function
FoxRing Functions Reference,
frRTrim() function
FoxRing Functions Reference,
frSetIfEmpty() function
FoxRing Functions Reference,
frSetSeparatorTo() function
FoxRing Functions Reference,
frSpace() function
FoxRing Functions Reference,
frStr() function
FoxRing Functions Reference,
frStringToList() function
FoxRing Functions Reference,
frStrTran() function
FoxRing Functions Reference,
frStuff() function
FoxRing Functions Reference,
frSubStr() function
FoxRing Functions Reference,
frTransform() function
FoxRing Functions Reference,
frVal() function
FoxRing Functions Reference,
frVarType() function
FoxRing Functions Reference,
Fseek()
Files,
Fsetpos()
Files,
FSize()
Stdlib Functions,
Ftell()
Files,
Full Screen
Using RingRayLib,
Function Prototype
Extension,
function prototype
Code Generator,
Function Structure
Extension,
Functional Programming
Anonymous and Nested Functions,
Equality of functions,
First-Class Functions,
Higher-order Functions,
Introduction,
Index 1789

Ring Documentation, Release 1.14
Pure Functions,
Functions
sockets,
Using RingRayLib,
Functions - First Style
Call Functions,
Declare parameters,
Dene Functions,
Introduction,
Main Function,
Recursion,
Return Value,
Send Parameters,
Variables Scope,
Functions - Second Style
Call Functions,
Declare parameters,
Dene Functions,
Introduction,
Main Function,
Recursion,
Return Value,
Send Parameters,
Variables Scope,
Functions - Third Style
Call Functions,
Declare parameters,
Dene Functions,
Introduction,
Main Function,
Recursion,
Return Value,
Send Parameters,
Variables Scope,
functions()
Reection and Meta-programming,
Fwrite()
Files,
Game Class
Game Engine for 2D Games,
Game Engine Classes
Game Engine for 2D Games,
Game Engine for 2D Games
Animate Class,
Animate Events,
Animation,
Animation and Functions,
Creating the Game Window,
Drawing Text,
Flappy Bird 3000 Game,
Game Class,
Game Engine Classes,
GameObject Class,
Games Layer,
Graphics Library Bindings,
Interface to graphics library,
Introduction,
Map,
Map Class,
Map Events,
Moving Text,
Object and Drawing,
Playing Sound,
Project Layers,
Sound Class,
Sprite Automatic Movement,
Sprite Class,
Sprite Keypress Event,
Sprite Mouse Event,
Sprite State Event,
Stars Fighter Game,
Super Man 2016 Game,
Text Class,
What is new in Ring 1.1?,
Game of Life Game
What is new in Ring 1.10?,
GameObject Class
Game Engine for 2D Games,
Games Layer
Game Engine for 2D Games,
gcd()
Stdlib Functions,
Generate Embedded Object File
Command Line Options,
What is new in Ring 1.12?,
Generate List
Tutorial: Ring Extensions in C/C++,
Generate Object File
Command Line Options,
Generate/Execute Ring Object Files*.ringo
What is new in Ring 1.1?,
Generating Pages using Objects
Web DevelopmentCGI Library,
Geometric Shapes
Using RingRayLib,
Get Active Source File Name
System Functions,
Get Command Line Arguments
System Functions,
Get List Item
Lists,
Get List Size
Lists,
Get Number of Characters from position
Strings,
Get Parameters Values
Extension,
Index 1790

Ring Documentation, Release 1.14
Get Request
RingLibCurl,
Get Stock Data From Yahoo
RingLibCurl,
Get String Length
Strings,
Get Substring from position to end
Strings,
GetArch() Function
System Functions,
getattribute()
Reection and Meta-programming,
GetChar()
Getting Input,
getnumber()
Stdlib Functions,
Getpathtype()
Files,
getpointer()
Low Level Functions,
getstring()
Stdlib Functions,
Getter and Setter Methods
Frequently Asked Questions,
Getting Input
GetChar(),
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
Give Command,
Input(),
Introduction,
Getting Started
tilengine,
Getting Started - First Style
Create Executable File,
Getting Input,
Hello World,
Introduction,
Multi-Line literals,
No Explicit End For Statements,
Not Case-Sensitive,
Run the program,
Using ? to print expression then new line,
Writing Comments,
Getting Started - Second Style
Create Executable File,
Getting Input,
Hello World,
Introduction,
Multi-Line literals,
No Explicit End For Statements,
Not Case-Sensitive,
Run the program,
Writing Comments,
Getting Started - Third Style
Create Executable File,
Getting Input,
Hello World,
Introduction,
Multi-Line literals,
No Explicit End For Statements,
Not Case-Sensitive,
Run the program,
Writing Comments,
Give Command
Getting Input,
globals()
Reection and Meta-programming,
Go Game
What is new in Ring 1.12?,
Goal of including the "Main" function in Ring
Frequently Asked Questions,
Google API Shortener Application
Applications developed in a few hours,
Gradient
Web DevelopmentCGI Library,
Grant Ring les execution permission
Web DevelopmentCGI Library,
Graphics and Game Programming
Drawing, Animation and Input,
Introduction,
Playing Sound,
Scaling and Rotating Images,
Threads,
Transparent Image,
TrueType Fonts,
Graphics Library Bindings
Game Engine for 2D Games,
Hash Functions
Web DevelopmentCGI Library,
HashTable Class
Stdlib Classes,
Hassouna Course Samples
What is new in Ring 1.13?,
Hello World
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
libui,
Tutorial: Ring Extensions in C/C++,
Hello World program
Deploying Web Applications in the Cloud,
Hello World Program using the Web Library
Web DevelopmentCGI Library,
Hex()
Data Type,
Index 1791

Ring Documentation, Release 1.14
Hex2str()
Data Type,
Higher-order Functions
Functional Programming,
Histogram
libui,
History
Introduction,
Natural Language Programming,
How can I disable maximize button and resize window?
Frequently Asked Questions,
How Ring nd a functions and methods?
Scope Rules for Functions and Methods,
How Ring nd the Variable?
Scope Rules,
How Ring2EXE works?
Distributing Ring Application using Ring2EXE,
How to add Combobox and other elements to the cells of
a QTableWidget?
Frequently Asked Questions,
How to Close a window then displaying another one?
Frequently Asked Questions,
How to contribute?
Applications,
Compiler and Virtual MachineVM,
Documentation,
Editors Support,
Extensions in C/C++,
Ideas and suggestions,
Introduction,
Libraries in Ring,
Samples,
Special thanks to contributors,
Testing,
How to create a Modal Window?
Frequently Asked Questions,
How to create an array of buttons in GUI applications?
Frequently Asked Questions,
How to extend RingQt and add more classes?
Frequently Asked Questions,
How to get the current source le path?
Frequently Asked Questions,
How to get the le size using ftell() and fseek() functions?
Frequently Asked Questions,
How to insert an item to the rst position in the list?
Frequently Asked Questions,
How to perform some manipulations on selected cells in
QTableWidget?
Frequently Asked Questions,
How to play?
The Gold Magic 800 Game,
How to print keys or values only in List/Dictionary?
Frequently Asked Questions,
How to print lists that contains objects?
Frequently Asked Questions,
How to print new lines and other characters?
Frequently Asked Questions,
How to use many source code les in the project?
Frequently Asked Questions,
How to use NULL and ISNULL() function?
Frequently Asked Questions,
How to use SQLite using ODBC?
Frequently Asked Questions,
HTML Lists
Web DevelopmentCGI Library,
HTML Special Characters
Web DevelopmentCGI Library,
HTML Tables
Web DevelopmentCGI Library,
HtmlPage Class
Web DevelopmentCGI Library,,
HTTP Get Example
Web DevelopmentCGI Library,
HTTP POST Example
Web DevelopmentCGI Library,
Ideas and suggestions
How to contribute?,
If Statement
Control Structures - Second Style,
Control Structures - Third Style,
Ignore new lines after keywords
Syntax Flexibility,
Image Drawing
Using RingRayLib,
Image Generation
Using RingRayLib,
Implicit Conversion
Variables,
Important Information about Ring2EXE
Distributing Ring Application using Ring2EXE,
Increment List Items
Tutorial: Ring Extensions in C/C++,
Inheritance
Object Oriented Programming,
Inheritance from GUI Classes
Desktop, WebAssembly and Mobile Development,
416
Innovative
Applications developed in a few hours,
Input Keys
Using RingRayLib,
Input Mouse
Using RingRayLib,
Input Multi-touch
Using RingRayLib,
Input()
Getting Input,
Index 1792

Ring Documentation, Release 1.14
Insert()
Lists,
Install Qt for Android
Building RingQt Applications for Mobile,
Installing Packages
Ring Package ManagerRingPM,
Interactive Debugger
The Trace Library and the Interactive Debugger,
Interface to graphics library
Game Engine for 2D Games,
Internet Class
Stdlib Classes,
Introduction
Deploying Web Applications in the Cloud,
Features,
History,
Introduction,
Motivation,
Performance Tips,
Ring and other languages,
Using RingRayLib,
Using ZeroLib,
Is Ring some sort of an improvement of PHP?
Frequently Asked Questions,
IsAlNum()
Data Type,
IsAlpha()
Data Type,
IsAndroid() Function
System Functions,
isattribute()
Reection and Meta-programming,
IsBetween()
Stdlib Functions,
iscfunction()
Reection and Meta-programming,
isclass()
Reection and Meta-programming,
IsCntrl()
Data Type,
IsDigit()
Data Type,
IsFreeBSD() Function
System Functions,
isfunction()
Reection and Meta-programming,
isglobal()
Reection and Meta-programming,
IsGraph()
Data Type,
isleapyear()
Stdlib Functions,
IsLinux() Function
System Functions,
IsList()
Data Type,
IsListContainsItems()
Stdlib Functions,
islocal()
Reection and Meta-programming,
IsLower()
Data Type,
IsMacOSX() Function
System Functions,
ismainsourcele()
Stdlib Functions,
ismethod()
Reection and Meta-programming,
IsMSDOS() Function
System Functions,
IsNULL()
Data Type,
IsNumber()
Data Type,
isobject()
Reection and Meta-programming,
ispackage()
Reection and Meta-programming,
ispackagesclass()
Reection and Meta-programming,
ispalindrome()
Stdlib Functions,
ispointer()
Low Level Functions,
isprime()
Stdlib Functions,
IsPrint()
Data Type,
isprivateattribute()
Reection and Meta-programming,
isprivatemethod()
Reection and Meta-programming,
IsPunct()
Data Type,
IsSpace()
Data Type,
isspecial()
Stdlib Functions,
IsString()
Data Type,
IsUnix() Function
System Functions,
IsUpper()
Data Type,
isvowel()
Stdlib Functions,
IsWindows() Function
System Functions,
Index 1793

Ring Documentation, Release 1.14
IsWindows64() Function
System Functions,
IsXdigit()
Data Type,
Julian Day Calendar application
What is new in Ring 1.12?,
JustFileName()
Stdlib Functions,
JustFilePath()
Stdlib Functions,
Key Press
Using Qt3D,
Keyboard Events and Colors
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Keyboard Shortcuts
Form Designer,
KeyPress and Mouse Move Events
Desktop, WebAssembly and Mobile Development,
411
Knight Tour Game
What is new in Ring 1.10?,
Language Design
Compact Syntax,
Data Representation,
Dene Declarative Languages,
Dene Natural Statements,
Designed for a clear goal,
Encourage Organization,
Fast Enough For Many Applications,
Introduction,
No Global Interpreter (VM) Lock - No GIL,
Simple,
Smart Garbage Collector,
Transparent Implementation,
Trying to be natural,
Visual Implementation,
Why Ring?,
Language Functions
Language Specication,
Language Grammar
Language Specication,
Language Keywords
Language Specication,
Language Shell
Demo Programs,
Language Specication
Compiler Errors,
Environment Errors,
Introduction,
Language Functions,
Language Grammar,
Language Keywords,
Runtime Errors,
Virtual Machine Instructions,
Large Files Hash
Security and Internet Functions,
Laser Game
What is new in Ring 1.13?,
lcm()
Stdlib Functions,
Left()
Strings,
Libraries in Ring
How to contribute?,
Library Source Code
bignumber,
Library Usage with GUI Applications
Objects Library for RingQt Application,
libui
Control Gallery,
Draw Gradient,
Drawing Sample,
Hello World,
Histogram,
Introduction,
More Drawing Samples,
Say Hello,
Say Something,
Text Drawing,
Using the Menubar,
linecount()
Stdlib Functions,
Lines()
Strings,
List Class
Stdlib Classes,
List index start from 1
Frequently Asked Questions,
List of changes and new features
What is new in Ring 1.10?,
What is new in Ring 1.11?,
What is new in Ring 1.12?,
What is new in Ring 1.13?,
What is new in Ring 1.14?,
What is new in Ring 1.1?,
What is new in Ring 1.2?,
What is new in Ring 1.3?,
What is new in Ring 1.4?,
What is new in Ring 1.5?,
What is new in Ring 1.6?,
What is new in Ring 1.7?,
What is new in Ring 1.8?,
What is new in Ring 1.9?,
list of functions
Mathematical Functions,
Index 1794

Ring Documentation, Release 1.14
List2Code() Function
Stdlib Functions,
list2le()
Stdlib Functions,
ListAllFiles() Function
Stdlib Functions,
Lists
Access List Items by String Index,
Add Items,
Copy Lists,
Create Lists,
Create Multi Dimension Array Using List and Re-
cursion,
Delete Item From List,
First-Class Lists,
Get List Item,
Get List Size,
Insert(),
Introduction,
Nested Lists,
Passing Lists to Functions,
Passing Parameters Arguments Using List Array,
Passing Parameters or Arguments Using List,
Return as List or Hash Table,
Reverse(),
Search,
Set List Item,
Sort(),
Swap Items,
Using Lists during denition,
Load Again
Program Structure,
Load Again Command
What is new in Ring 1.12?,
Load Package
Program Structure,
Load Syntax Files
Syntax Flexibility,
Loading Files
Code Generator,
Loading the library
bignumber,
PostgreSQL,
Loading the Trace library
The Trace Library and the Interactive Debugger,
Local Tests
Deploying Web Applications in the Cloud,
locals()
Reection and Meta-programming,
Location
Create your rst extension,
Logical Operators
Operators,
Loop Command
Control Structures - First Style,
Looping
Control Structures,
Control Structures - First Style,
Control Structures - Second Style,
Low Level Functions
callgc(),
Example - The Trace Library,
Example - Using the Trace Functions,
getpointer(),
Introduction,
ispointer(),
memcpy(),
nullpointer(),
object2pointer(),
pointer2object(),
pointer2string(),
ptrcmp(),
ringvm_callfunc(),
RingVM_CallList(),
RingVM_CFunctionsList(),
RingVM_ClassesList(),
ringvm_evalinscope(),
RingVM_FilesList(),
RingVM_FunctionsList(),
ringvm_give() function,
ringvm_hideerrorMsg(),
ringvm_info(),
RingVM_MemoryList(),
RingVM_PackagesList(),
ringvm_passerror(),
ringvm_scopescount(),
ringvm_see() function,
ringvm_settrace(),
ringvm_tracedata(),
ringvm_traceevent(),
ringvm_tracefunc(),
setpointer(),
space(),
varptr(),
Magic Balls Game
What is new in Ring 1.13?,
Main Function
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
Main Menu
Demo Programs,
Make a Cube using RingOpenGL and RingFreeGLUT
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
makedir()
Stdlib Functions,
Index 1795

Ring Documentation, Release 1.14
Managed Classes
Code Generator,
Many Cubes
Using RingOpenGL and RingAllegro for 3D Graph-
ics,
Many Objects
Using Qt3D,
Map
Game Engine for 2D Games,
Map Class
Game Engine for 2D Games,
Map Events
Game Engine for 2D Games,
map()
Stdlib Functions,
Matching Game
What is new in Ring 1.13?,
Math Class
Stdlib Classes,
Mathematical Functions
Decimals(),
Example,
Introduction,
list of functions,
Random(),
SRandom(),
Unsigned(),
Using _ in numbers,
Using f after numbers,
matrixmulti()
Stdlib Functions,
matrixtrans()
Stdlib Functions,
Maze Game
What is new in Ring 1.11?,
MD5()
Security and Internet Functions,
memcpy()
Low Level Functions,
Menu Events
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Menubar and StyleSheet Example
Desktop, WebAssembly and Mobile Development,
387
Menubar Designer
Form Designer,
Merge binary characters
Strings,
What is new in Ring 1.8?,
mergemethods()
Reection and Meta-programming,
Methods to use Events with Events Filter
Desktop, WebAssembly and Mobile Development,
454
methods()
Reection and Meta-programming,
Minesweeper Game
What is new in Ring 1.10?,
Misc Operators
Operators,
Model
Using Qt3D,
Model Texture
Using Qt3D,
Module Organization
Extension,
MoneyBoxes Game
What is new in Ring 1.13?,
More 3D Samples
Using RingOpenGL and RingAllegro for 3D Graph-
ics,
What is new in Ring 1.11?,
What is new in Ring 1.8?,
More Beatiful Code
Declarative Programming,
More Drawing Samples
libui,
More Examples
Threads,
More Functions
What is new in Ring 1.14?,
More Games
What is new in Ring 1.10?,
What is new in Ring 1.9?,
More Improvements
What is new in Ring 1.10?,
What is new in Ring 1.11?,
What is new in Ring 1.12?,
What is new in Ring 1.13?,
What is new in Ring 1.14?,
What is new in Ring 1.9?,
More Low Level Functions
What is new in Ring 1.13?,
More Samples
tilengine,
What is new in Ring 1.14?,
More Samples and Tests
Form Designer,
More Syntax Flexibility
What is new in Ring 1.5?,
Motivation
Introduction,
Mouse Events
RingLibSDL,
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Index 1796

Ring Documentation, Release 1.14
Mouse Wheel
Using RingRayLib,
Movable Label Example
Desktop, WebAssembly and Mobile Development,
406
Moving Objects using the Mouse
Desktop, WebAssembly and Mobile Development,
412
Moving Text
Game Engine for 2D Games,
Multi-language applications
Form Designer Translation,
Forms Translation,
Introduction,
Using String2Constant,
Multi-Line literals
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
MurmurHash1 functions
RingMurmurHash Functions Reference,
MurmurHash2 functions
RingMurmurHash Functions Reference,
MurmurHash3 functions
RingMurmurHash Functions Reference,
Music Playing
Using RingRayLib,
MyCoffeeWeb Application
What is new in Ring 1.14?,
MySQL Class
Stdlib Classes,
MySQL Functions
Create Database,
Create Table and Insert Data,
Introduction,
MySQL_AutoCommit(),
MySQL_Close(),
MySQL_Columns(),
MySQL_Commit(),
MySQL_Connect(),
MySQL_Error(),
MySQL_Escape_String(),
MySQL_Info(),
MySQL_Init(),
MySQL_Inser_ID(),
MySQL_Next_Result(),
MySQL_Query(),
MySQL_Result(),
MySQL_Result2(),
MySQL_Rollback(),
Print Query Result,
Restore Image From The Database,
Save Image Inside the Database,
Transaction Example,
MySQL_AutoCommit()
MySQL Functions,
MySQL_Close()
MySQL Functions,
MySQL_Columns()
MySQL Functions,
MySQL_Columns() Implementation
Extension,
MySQL_Commit()
MySQL Functions,
MySQL_Connect()
MySQL Functions,
MySQL_Error()
MySQL Functions,
MySQL_Escape_String()
MySQL Functions,
MySQL_Info()
MySQL Functions,
MySQL_Init()
MySQL Functions,
MySQL_Inser_ID()
MySQL Functions,
MySQL_Next_Result()
MySQL Functions,
MySQL_Query()
MySQL Functions,
MySQL_Result()
MySQL Functions,
MySQL_Result2()
MySQL Functions,
MySQL_Rollback()
MySQL Functions,
Natural Language Programming
BraceError() Method,
BraceExprEval Method,
BraceStart and BraceEnd Methods,
Change the = operator to is,
Change the Ring Keyword And,
Change the Ring Operator +,
Clean Natural Code,
Example,
History,
Introduction,
Real Natual Code,
Using Eval() with our Natural Code,
Natural Library - Demo Program
Using the Natural Library,
Nested Lists
Lists,
New Book by Apress
What is new in Ring 1.13?,
New Classes names - Index Start from 1
Index 1797

Ring Documentation, Release 1.14
Desktop, WebAssembly and Mobile Development,
456
New Command: Load Package
What is new in Ring 1.7?,
New Functions
What is new in Ring 1.2?,
What is new in Ring 1.3?,
New Functions and Changes
What is new in Ring 1.1?,
New Game : Gold Magic 800
What is new in Ring 1.9?,
New Style to Ring Notepad
What is new in Ring 1.4?,
New Tool: Folder2qrc
What is new in Ring 1.6?,
New Tool: Ring2EXE
What is new in Ring 1.6?,
No Explicit End For Statements
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
No Global Interpreter (VM) Lock - No GIL
Language Design,
No Run
Command Line Options,
NofProcessors() Function
System Functions,
Not Case-Sensitive
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
Notepad Application
Desktop, WebAssembly and Mobile Development,
429
Notes to extensions creators
What is new in Ring 1.8?,
nullpointer()
Low Level Functions,
Number()
Data Type,
Numbers and Bytes
Files,
Object and Drawing
Game Engine for 2D Games,
Object Library Source Code
Objects Library for RingQt Application,
Object Oriented Programming
Access Objects Using Braces,
Classes and Objects,
Composition,
Default value for object attributes,
Dynamic Attributes,
Find() and List of Objects,
Inheritance,
Introduction,
Operator Overloading,
Packages,
Printing Objects,
Private Attributes and Methods,
Setter and Getter,
Sort() and List of Objects,
Using Self.Attribute,
Using This in the class region as Self,
Using This.Attribute and This.Method(),
Object Picker
Using Qt3D,
object2pointer()
Low Level Functions,
objectid()
Reection and Meta-programming,
Objects inside lists
Declarative Programming,
Objects Library for RingQt
What is new in Ring 1.2?,
Objects Library for RingQt Application
Example,
Introduction,
Library Usage with GUI Applications,
Object Library Source Code,
openWindowAndLink() Function,,
openWindowInPackages() Function,
ODBC Class
Stdlib Classes,
ODBC Functions
Execute Query and Print Result,
Introduction,
odbc_autocommit(),
odbc_close(),
odbc_colcount(),
odbc_columns(),
odbc_commit(),
odbc_connect(),
odbc_datasources(),
odbc_disconnect(),
odbc_drivers(),
odbc_execute(),
odbc_fetch(),
odbc_getdata(),
odbc_init(),
odbc_rollback(),
odbc_tables(),
Open and Close Connection,
Print List of ODBC Data Sources,
Print List of ODBC Drivers,
Save and Restore Images,
Transactions and Using Commit and Rollback,
odbc_autocommit()
Index 1798

Ring Documentation, Release 1.14
ODBC Functions,
odbc_close()
ODBC Functions,
odbc_colcount()
ODBC Functions,
odbc_columns()
ODBC Functions,
odbc_commit()
ODBC Functions,
odbc_connect()
ODBC Functions,
odbc_datasources()
ODBC Functions,
odbc_disconnect()
ODBC Functions,
odbc_drivers()
ODBC Functions,
odbc_execute()
ODBC Functions,
odbc_fetch()
ODBC Functions,
odbc_getdata()
ODBC Functions,
odbc_init()
ODBC Functions,
odbc_rollback()
ODBC Functions,
odbc_tables()
ODBC Functions,
Online Applications
Building RingQt Applications for WebAssembly,
524
Open and Close Connection
ODBC Functions,
openWindowAndLink() Function
Objects Library for RingQt Application,,
openWindowInPackages() Function
Objects Library for RingQt Application,
Operator Overloading
Object Oriented Programming,
Operators
Arithmetic Operators,
Assignment Operators,
Bitwise Operators,
Introduction,
Logical Operators,
Misc Operators,
Operators Precedence,
Relational Operators,
Using the Natural Library,
Operators Precedence
Operators,
Options
Distributing Ring Application using Ring2EXE,
OSCopyFile() Function
Stdlib Functions,
OSCopyFolder() Function
Stdlib Functions,
OSCreateOpenFolder() Function
Stdlib Functions,
OSDeleteFile() Function
Stdlib Functions,
OSDeleteFolder() Function
Stdlib Functions,
OSRenameFile() Function
Stdlib Functions,
Other Widgets Events
Desktop, WebAssembly and Mobile Development,
391
packagename()
Reection and Meta-programming,
Packages
Object Oriented Programming,
packages()
Reection and Meta-programming,
packagesclasses()
Reection and Meta-programming,
Page Class
Web DevelopmentCGI Library,
Pairs Game
What is new in Ring 1.13?,
Pass Error
The Trace Library and the Interactive Debugger,
Passing Lists to Functions
Lists,
Passing Parameters Arguments Using List Array
Lists,
Passing Parameters or Arguments Using List
Lists,
Performance
Command Line Options,
Performance Tips
Arithmetic Operations,
Calling Functions and Methods,
Creating Lists,
Introduction,,
Using len() and For Loops,
permutation()
Stdlib Functions,
Perror()
Files,
Philosophy behind data types in Ring
Frequently Asked Questions,
Play Sound
RingLibSDL,
Playing Sound
Index 1799

Ring Documentation, Release 1.14
Desktop, WebAssembly and Mobile Development,
404
Game Engine for 2D Games,
Graphics and Game Programming,
pointer2object()
Low Level Functions,
pointer2string()
Low Level Functions,
Pong Game
What is new in Ring 1.10?,
Post Request
RingLibCurl,
PostgreSQL
Examples,
Introduction,
Loading the library,
RingPostgreSQL Constants,
RingPostgreSQL Functions,
PostgreSQL Class
Stdlib Classes,
Practical
Applications developed in a few hours,
Prex for Functions Names
Code Generator,
PrevFileName() Function
System Functions,
Print les in Zip le
RingZip,
Print List of ODBC Data Sources
ODBC Functions,
Print List of ODBC Drivers
ODBC Functions,
Print Query Result
MySQL Functions,
print()
Stdlib Functions,
Print2Str() Function
Stdlib Functions,
Printing Final Intermediate Code
Command Line Options,
Printing Instruction Operation Code
Command Line Options,
Printing Intermediate Code
Command Line Options,
Printing List of Installed Packages
Ring Package ManagerRingPM,
Printing Objects
Object Oriented Programming,
Printing Rules
Command Line Options,
Printing Tokens
Command Line Options,
Printing using QPrinter
Desktop, WebAssembly and Mobile Development,
399
Private Attributes and Methods
Object Oriented Programming,
prodlist()
Stdlib Functions,
Program Structure
Introduction,
Load Again,
Load Package,
Source Code File Sections,
Using Many Source Code Files,
Project Folder
Building Games For Android,
Project Layers
Game Engine for 2D Games,
Protecting the Source Code
Distributing Ring Application,
ptrcmp()
Low Level Functions,
Pure Functions
Functional Programming,
puts()
Stdlib Functions,
QAbstractAspect Class
RingQt Classes Reference,
QAbstractButton Class
RingQt Classes Reference,
QAbstractCameraController Class
RingQt Classes Reference,
QAbstractItemView Class
RingQt Classes Reference,
QAbstractPrintDialog Class
RingQt Classes Reference,
QAbstractScrollArea Class
RingQt Classes Reference,
QAbstractSeries Class
RingQt Classes Reference,
QAbstractSlider Class
RingQt Classes Reference,
QAbstractSocket Class
RingQt Classes Reference,
QAbstractSpinBox Class
RingQt Classes Reference,
QAction Class
RingQt Classes Reference,
QAllEvents Class
RingQt Classes Reference,
QApp Class
RingQt Classes Reference,
QAreaLegendMarker Class
RingQt Classes Reference,
QAreaSeries Class
Index 1800

Ring Documentation, Release 1.14
RingQt Classes Reference,
QAspectEngine Class
RingQt Classes Reference,
QAxBase Class
RingQt Classes Reference,
QAxObject Class
RingQt Classes Reference,
QAxWidget Class
RingQt Classes Reference,
QAxWidget2 Class
RingQt Classes Reference,
QBarCategoryAxis Class
RingQt Classes Reference,
QBarLegendMarker Class
RingQt Classes Reference,
QBarSeries Class
RingQt Classes Reference,
QBarSet Class
RingQt Classes Reference,
QBitmap Class
RingQt Classes Reference,
QBluetoothAddress Class
RingQt Classes Reference,
QBluetoothDeviceDiscoveryAgent Class
RingQt Classes Reference,
QBluetoothDeviceInfo Class
RingQt Classes Reference,
QBluetoothHostInfo Class
RingQt Classes Reference,
QBluetoothLocalDevice Class
RingQt Classes Reference,
QBluetoothServer Class
RingQt Classes Reference,
QBluetoothServiceDiscoveryAgent Class
RingQt Classes Reference,
QBluetoothServiceInfo Class
RingQt Classes Reference,
QBluetoothSocket Class
RingQt Classes Reference,
QBluetoothTransferManager Class
RingQt Classes Reference,
QBluetoothTransferReply Class
RingQt Classes Reference,
QBluetoothTransferRequest Class
RingQt Classes Reference,
QBluetoothUuid Class
RingQt Classes Reference,
QBoxLayout Class
RingQt Classes Reference,
QBoxPlotLegendMarker Class
RingQt Classes Reference,
QBoxPlotSeries Class
RingQt Classes Reference,
QBoxSet Class
RingQt Classes Reference,
QBrush Class
RingQt Classes Reference,
QBuffer Class
RingQt Classes Reference,
QButtonGroup Class
RingQt Classes Reference,
QByteArray Class
RingQt Classes Reference,
QCalendarWidget Class
RingQt Classes Reference,
QCamera Class
RingQt Classes Reference,
QCameraImageCapture Class
RingQt Classes Reference,
QCameraLens Class
RingQt Classes Reference,
QCameraSelector Class
RingQt Classes Reference,
QCameraViewnder Class
RingQt Classes Reference,
QCandlestickLegendMarker Class
RingQt Classes Reference,
QCandlestickModelMapper Class
RingQt Classes Reference,
QCandlestickSeries Class
RingQt Classes Reference,
QCandlestickSet Class
RingQt Classes Reference,
QCategoryAxis Class
RingQt Classes Reference,
QChar Class
RingQt Classes Reference,
QChart Class
RingQt Classes Reference,
QChartView Class
RingQt Classes Reference,
QCheckBox Class
RingQt Classes Reference,
QChildEvent Class
RingQt Classes Reference,
QClipboard Class
RingQt Classes Reference,
QColor Class
RingQt Classes Reference,
QColorDialog Class
RingQt Classes Reference,
QComboBox Class
RingQt Classes Reference,
QCompleter Class
RingQt Classes Reference,
QCompleter2 Class
RingQt Classes Reference,
QCompleter3 Class
Index 1801

Ring Documentation, Release 1.14
RingQt Classes Reference,
QConeGeometry Class
RingQt Classes Reference,
QConeMesh Class
RingQt Classes Reference,
QCoreApplication Class
RingQt Classes Reference,
QCuboidMesh Class
RingQt Classes Reference,
QCullFace Class
RingQt Classes Reference,
QCursor Class
RingQt Classes Reference,
QCylinderMesh Class
RingQt Classes Reference,
QDate Class
RingQt Classes Reference,
QDateEdit Class
RingQt Classes Reference,
QDateTime Class
RingQt Classes Reference,
QDateTimeAxis Class
RingQt Classes Reference,
QDateTimeEdit Class
RingQt Classes Reference,
QDepthTest Class
RingQt Classes Reference,
QDesktopServices Class
RingQt Classes Reference,
QDesktopWidget Class
RingQt Classes Reference,
QDial Class
RingQt Classes Reference,
QDialog Class
RingQt Classes Reference,
QDiffuseSpecularMaterial Class
RingQt Classes Reference,
QDir Class
RingQt Classes Reference,
QDirModel Class
RingQt Classes Reference,
QDockWidget Class
RingQt Classes Reference,
QDrag Class
RingQt Classes Reference,
QDragEnterEvent Class
RingQt Classes Reference,
QDragLeaveEvent Class
RingQt Classes Reference,
QDragMoveEvent Class
RingQt Classes Reference,
QDropEvent Class
RingQt Classes Reference,
QEffect Class
RingQt Classes Reference,
QEntity Class
RingQt Classes Reference,
QEvent Class
RingQt Classes Reference,
QExtrudedTextMesh Class
RingQt Classes Reference,
QFile Class
RingQt Classes Reference,
QFile2 Class
RingQt Classes Reference,
QFileDevice Class
RingQt Classes Reference,
QFileDialog Class
RingQt Classes Reference,
QFileInfo Class
RingQt Classes Reference,
QFileSystemModel Class
RingQt Classes Reference,
QFirstPersonCameraController Class
RingQt Classes Reference,
QFont Class
RingQt Classes Reference,
QFontDialog Class
RingQt Classes Reference,
QFontMetrics Class
RingQt Classes Reference,
QForwardRenderer Class
RingQt Classes Reference,
QFrame Class
RingQt Classes Reference,
QFrame2 Class
RingQt Classes Reference,
QFrame3 Class
RingQt Classes Reference,
QFrameAction Class
RingQt Classes Reference,
QGeoAddress Class
RingQt Classes Reference,
QGeoAreaMonitorInfo Class
RingQt Classes Reference,
QGeoAreaMonitorSource Class
RingQt Classes Reference,
QGeoCircle Class
RingQt Classes Reference,
QGeoCoordinate Class
RingQt Classes Reference,
QGeoPositionInfo Class
RingQt Classes Reference,
QGeoPositionInfoSource Class
RingQt Classes Reference,
QGeoRectangle Class
RingQt Classes Reference,
QGeoSatelliteInfo Class
Index 1802

Ring Documentation, Release 1.14
RingQt Classes Reference,
QGeoSatelliteInfoSource Class
RingQt Classes Reference,
QGeoShape Class
RingQt Classes Reference,
QGoochMaterial Class
RingQt Classes Reference,
QGradient Class
RingQt Classes Reference,
QGraphicsScene Class
RingQt Classes Reference,
QGraphicsVideoItem Class
RingQt Classes Reference,
QGraphicsView Class
RingQt Classes Reference,
QGridLayout Class
RingQt Classes Reference,
QGuiApplication Class
RingQt Classes Reference,
QHBarModelMapper Class
RingQt Classes Reference,
QHBoxLayout Class
RingQt Classes Reference,
QHBoxPlotModelMapper Class
RingQt Classes Reference,
QHCandlestickModelMapper Class
RingQt Classes Reference,
QHeaderView Class
RingQt Classes Reference,
QHorizontalBarSeries Class
RingQt Classes Reference,
QHorizontalPercentBarSeries Class
RingQt Classes Reference,
QHorizontalStackedBarSeries Class
RingQt Classes Reference,
QHostAddress Class
RingQt Classes Reference,
QHostInfo Class
RingQt Classes Reference,
QHPieModelMapper Class
RingQt Classes Reference,
QHXYModelMapper Class
RingQt Classes Reference,
QIcon Class
RingQt Classes Reference,
QImage Class
RingQt Classes Reference,
QInputAspect Class
RingQt Classes Reference,
QInputDialog Class
RingQt Classes Reference,
QIODevice Class
RingQt Classes Reference,
QJsonArray Class
RingQt Classes Reference,
QJsonDocument Class
RingQt Classes Reference,
QJsonObject Class
RingQt Classes Reference,
QJsonParseError Class
RingQt Classes Reference,
QJsonValue Class
RingQt Classes Reference,
QKeySequence Class
RingQt Classes Reference,
QLabel Class
RingQt Classes Reference,
QLayout Class
RingQt Classes Reference,
QLCDNumber Class
RingQt Classes Reference,
QLegend Class
RingQt Classes Reference,
QLegendMarker Class
RingQt Classes Reference,
QLinearGradient Class
RingQt Classes Reference,
QLineEdit Class
RingQt Classes Reference,
QLineEdit Events and QMessageBox
Desktop, WebAssembly and Mobile Development,
389
QLineSeries Class
RingQt Classes Reference,
QListView Class
RingQt Classes Reference,
QListWidget Class
RingQt Classes Reference,
QListWidgetItem Class
RingQt Classes Reference,
QLocale Class
RingQt Classes Reference,
QLogicAspect Class
RingQt Classes Reference,
QLogValueAxis Class
RingQt Classes Reference,
QMainWindow Class
RingQt Classes Reference,
QMaterial Class
RingQt Classes Reference,
QMatrix4x4 Class
RingQt Classes Reference,
QMdiArea Class
RingQt Classes Reference,
QMdiSubWindow Class
RingQt Classes Reference,
QMediaObject Class
RingQt Classes Reference,
Index 1803

Ring Documentation, Release 1.14
QMediaPlayer Class
RingQt Classes Reference,
QMediaPlaylist Class
RingQt Classes Reference,
QMenu Class
RingQt Classes Reference,
QMenuBar Class
RingQt Classes Reference,
QMesh Class
RingQt Classes Reference,
QMessageBox Class
RingQt Classes Reference,
QMessagebox Example
Desktop, WebAssembly and Mobile Development,
407
QMetalRoughMaterial Class
RingQt Classes Reference,
QMimeData Class
RingQt Classes Reference,
QMorphPhongMaterial Class
RingQt Classes Reference,
QMovie Class
RingQt Classes Reference,
QMutex Class
RingQt Classes Reference,
QMutexLocker Class
RingQt Classes Reference,
QNetworkAccessManager Class
RingQt Classes Reference,
QNetworkProxy Class
RingQt Classes Reference,
QNetworkReply Class
RingQt Classes Reference,
QNetworkRequest Class
RingQt Classes Reference,
QNmeaPositionInfoSource Class
RingQt Classes Reference,
QNode Class
RingQt Classes Reference,
QObject Class
RingQt Classes Reference,
QObjectPicker Class
RingQt Classes Reference,
QOpenGLBuffer Class
RingQt Classes Reference,
QOpenGLContext Class
RingQt Classes Reference,
QOpenGLDebugLogger Class
RingQt Classes Reference,
QOpenGLFramebufferObject Class
RingQt Classes Reference,
QOpenGLFunctions Class
RingQt Classes Reference,
QOpenGLFunctions_3_2_Core Class
RingQt Classes Reference,
QOpenGLPaintDevice Class
RingQt Classes Reference,
QOpenGLShader Class
RingQt Classes Reference,
QOpenGLShaderProgram Class
RingQt Classes Reference,
QOpenGLTexture Class
RingQt Classes Reference,
QOpenGLTimerQuery Class
RingQt Classes Reference,
QOpenGLVersionProle Class
RingQt Classes Reference,
QOpenGLVertexArrayObject Class
RingQt Classes Reference,
QOpenGLWidget Class
RingQt Classes Reference,
QOrbitCameraController Class
RingQt Classes Reference,
QPageSetupDialog Class
RingQt Classes Reference,
QPaintDevice Class
RingQt Classes Reference,
QPainter Class
RingQt Classes Reference,
QPainter2 Class
RingQt Classes Reference,
QPainterPath Class
RingQt Classes Reference,
QPen Class
RingQt Classes Reference,
QPercentBarSeries Class
RingQt Classes Reference,
QPerVertexColorMaterial Class
RingQt Classes Reference,
QPhongMaterial Class
RingQt Classes Reference,
QPicture Class
RingQt Classes Reference,
QPieLegendMarker Class
RingQt Classes Reference,
QPieSeries Class
RingQt Classes Reference,
QPieSlice Class
RingQt Classes Reference,
QPixmap Class
RingQt Classes Reference,
QPixmap2 Class
RingQt Classes Reference,
QPlainTextEdit Class
RingQt Classes Reference,
QPlaneMesh Class
RingQt Classes Reference,
QPoint Class
Index 1804

Ring Documentation, Release 1.14
RingQt Classes Reference,
QPointF Class
RingQt Classes Reference,
QPointLight Class
RingQt Classes Reference,
QPolarChart Class
RingQt Classes Reference,
QPrintDialog Class
RingQt Classes Reference,
QPrinter Class
RingQt Classes Reference,
QPrinterInfo Class
RingQt Classes Reference,
QPrintPreviewDialog Class
RingQt Classes Reference,
QPrintPreviewWidget Class
RingQt Classes Reference,
QProcess Class
RingQt Classes Reference,
QProgressBar Class
RingQt Classes Reference,
QPushButton Class
RingQt Classes Reference,
QQmlEngine Class
RingQt Classes Reference,
QQmlError Class
RingQt Classes Reference,
QQuaternion Class
RingQt Classes Reference,
QQuickView Class
RingQt Classes Reference,
QQuickWidget Class
RingQt Classes Reference,
QRadioButton Class
RingQt Classes Reference,
QRect Class
RingQt Classes Reference,
QRegion Class
RingQt Classes Reference,
QRegularExpression Class
RingQt Classes Reference,
QRegularExpressionMatch Class
RingQt Classes Reference,
QRegularExpressionMatchIterator Class
RingQt Classes Reference,
QRenderAspect Class
RingQt Classes Reference,
QRenderPass Class
RingQt Classes Reference,
QScatterSeries Class
RingQt Classes Reference,
QSceneLoader Class
RingQt Classes Reference,
QScreen Class
RingQt Classes Reference,
QScrollArea Class
RingQt Classes Reference,
QScrollBar Class
RingQt Classes Reference,
QSerialPort Class
RingQt Classes Reference,
QSerialPortInfo Class
RingQt Classes Reference,
QSize Class
RingQt Classes Reference,
QSkyboxEntity Class
RingQt Classes Reference,
QSlider Class
RingQt Classes Reference,
QSphereMesh Class
RingQt Classes Reference,
QSpinBox Class
RingQt Classes Reference,
QSplashScreen Class
RingQt Classes Reference,
QSplineSeries Class
RingQt Classes Reference,
QSplitter Class
RingQt Classes Reference,
QSqlDatabase Class
RingQt Classes Reference,
QSqlDriver Class
RingQt Classes Reference,
QSqlDriverCreatorBase Class
RingQt Classes Reference,
QSqlError Class
RingQt Classes Reference,
QSqlField Class
RingQt Classes Reference,
QSqlIndex Class
RingQt Classes Reference,
QSqlQuery Class
RingQt Classes Reference,
QSqlRecord Class
RingQt Classes Reference,
QStackedBarSeries Class
RingQt Classes Reference,
QStackedWidget Class
RingQt Classes Reference,
QStandardPaths Class
RingQt Classes Reference,
QStatusBar Class
RingQt Classes Reference,
QString2 Class
RingQt Classes Reference,
QStringList Class
RingQt Classes Reference,
QStringRef Class
Index 1805

Ring Documentation, Release 1.14
RingQt Classes Reference,
QSurfaceFormat Class
RingQt Classes Reference,
QSystemTrayIcon Class
RingQt Classes Reference,
Qt Class Convertor
What is new in Ring 1.4?,
Qt conguration le
Code Generator,
Qt3DCamera Class
RingQt Classes Reference,
Qt3DWindow Class
RingQt Classes Reference,
QTabBar Class
RingQt Classes Reference,
QTableView Class
RingQt Classes Reference,
QTableWidget Class
RingQt Classes Reference,
QTableWidgetItem Class
RingQt Classes Reference,
QTabWidget Class
RingQt Classes Reference,
QTcpServer Class
RingQt Classes Reference,
QTcpSocket Class
RingQt Classes Reference,
QTechnique Class
RingQt Classes Reference,
QTest Class
RingQt Classes Reference,
QText2DEntity Class
RingQt Classes Reference,
QTextBlock Class
RingQt Classes Reference,
QTextBrowser Class
RingQt Classes Reference,
QTextCharFormat Class
RingQt Classes Reference,
QTextCodec Class
RingQt Classes Reference,
QTextCursor Class
RingQt Classes Reference,
QTextDocument Class
RingQt Classes Reference,
QTextEdit Class
RingQt Classes Reference,
QTextStream Class
RingQt Classes Reference,
QTextStream2 Class
RingQt Classes Reference,
QTextStream3 Class
RingQt Classes Reference,
QTextStream4 Class
RingQt Classes Reference,
QTextStream5 Class
RingQt Classes Reference,
QTextToSpeech Class
RingQt Classes Reference,
QTextureLoader Class
RingQt Classes Reference,
QTextureMaterial Class
RingQt Classes Reference,
QThread Class
RingQt Classes Reference,
QThreadPool Class
RingQt Classes Reference,
QTime Class
RingQt Classes Reference,
QTimer Class
RingQt Classes Reference,
QToolBar Class
RingQt Classes Reference,
QToolButton Class
RingQt Classes Reference,
QTorusMesh Class
RingQt Classes Reference,
QTransform Class
RingQt Classes Reference,
QTreeView Class
RingQt Classes Reference,
QTreeWidget Class
RingQt Classes Reference,
QTreeWidgetItem Class
RingQt Classes Reference,
Queue Class
Stdlib Classes,
Quotes about Ring
Applications developed in a few hours,
QUrl Class
RingQt Classes Reference,
QUuid Class
RingQt Classes Reference,
QValueAxis Class
RingQt Classes Reference,
QVariant Class
RingQt Classes Reference,
QVariant2 Class
RingQt Classes Reference,
QVariant3 Class
RingQt Classes Reference,
QVariant4 Class
RingQt Classes Reference,
QVariant5 Class
RingQt Classes Reference,
QVariantDouble Class
RingQt Classes Reference,
QVariantFloat Class
Index 1806

Ring Documentation, Release 1.14
RingQt Classes Reference,
QVariantInt Class
RingQt Classes Reference,
QVariantString Class
RingQt Classes Reference,
QVBarModelMapper Class
RingQt Classes Reference,
QVBoxLayout Class
RingQt Classes Reference,
QVBoxPlotModelMapper Class
RingQt Classes Reference,
QVCandlestickModelMapper Class
RingQt Classes Reference,
QVector2D Class
RingQt Classes Reference,
QVector3D Class
RingQt Classes Reference,
QVector4D Class
RingQt Classes Reference,
QVectorQVoice Class
RingQt Classes Reference,
QVideoWidget and QMediaPlayer
Desktop, WebAssembly and Mobile Development,
383
QVideoWidget Class
RingQt Classes Reference,
QVideoWidgetControl Class
RingQt Classes Reference,
QViewport Class
RingQt Classes Reference,
QVoice Class
RingQt Classes Reference,
QVPieModelMapper Class
RingQt Classes Reference,
QVXYModelMapper Class
RingQt Classes Reference,
QWebEnginePage Class
RingQt Classes Reference,
QWebEngineView Class
RingQt Classes Reference,
QWebView Class
RingQt Classes Reference,,
QWidget Class
RingQt Classes Reference,
QWindow Class
RingQt Classes Reference,
QXmlStreamAttribute Class
RingQt Classes Reference,
QXmlStreamAttributes Class
RingQt Classes Reference,
QXmlStreamEntityDeclaration Class
RingQt Classes Reference,
QXmlStreamEntityResolver Class
RingQt Classes Reference,
QXmlStreamNamespaceDeclaration Class
RingQt Classes Reference,
QXmlStreamNotationDeclaration Class
RingQt Classes Reference,
QXmlStreamReader Class
RingQt Classes Reference,
QXmlStreamWriter Class
RingQt Classes Reference,
QXYLegendMarker Class
RingQt Classes Reference,
QXYSeries Class
RingQt Classes Reference,
Raise()
Eval() and Debugging,
RandBytes()
Security and Internet Functions,
Random Image
Web DevelopmentCGI Library,
Random()
Mathematical Functions,
Read File using Read()
Files,
readline()
Stdlib Functions,
Real Natual Code
Natural Language Programming,
Rectangle Scaling
Using RingRayLib,
Recursion
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
Reference
Threads,
tilengine,
Reection and Meta-programming
addattribute(),
addmethod(),
attributes(),
cfunctions(),
classes(),
classname(),
functions(),
getattribute(),
globals(),
Introduction,
isattribute(),
iscfunction(),
isclass(),
isfunction(),
isglobal(),
islocal(),
ismethod(),
Index 1807

Ring Documentation, Release 1.14
isobject(),
ispackage(),
ispackagesclass(),
isprivateattribute(),
isprivatemethod(),
locals(),
mergemethods(),
methods(),
objectid(),
packagename(),
packages(),
packagesclasses(),
setattribute(),
Register New Functions
Code Generator,
Regular Expressions
Desktop, WebAssembly and Mobile Development,
421
Relational Operators
Operators,
Remove Package
Ring Package ManagerRingPM,
Remove()
Files,
Rename()
Files,
Replicate List Items
Tutorial: Ring Extensions in C/C++,
Resources
Introduction,
Ring Language Website,
Ring Team,
Source Code,
Restore Image From The Database
MySQL Functions,
Return as List or Hash Table
Lists,
Return object by reference
Declarative Programming,
Return Self by Reference
What is new in Ring 1.3?,
Return Value
Extension,
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
Reverse()
Lists,
Rewind()
Files,
Right()
Strings,
Ring and other languages
Introduction,
RING API - list Functions
Extension,
RING API - String Functions
Extension,
Ring CGI Hello World Program
Web DevelopmentCGI Library,
Ring Extension for Visual Studio Code
What is new in Ring 1.10?,
Ring for WebAssembly
What is new in Ring 1.13?,
Ring Language Website
Resources,
Ring mode for Emacs Editor
What is new in Ring 1.3?,
Ring Notepad
Introduction,
Ring Notepad - Creating and running your rst con-
sole application,
Ring Notepad - Creating and running your rst game,
35
Ring Notepad - Creating and running your rst
GUI/WebAssembly/Mobile application,
Ring Notepad - Creating and running your rst Web
application,
Ring Notepad - Main Window,
The Browser Menu,
The Distribute Menu,
The Edit Menu,
The File Menu,
The Help Menu,
The Main File in the Project,
The Program Menu,
The Tools Menu,
The View Menu,
Ring Notepad - Creating and running your rst console
application
Ring Notepad,
Ring Notepad - Creating and running your rst game
Ring Notepad,
Ring Notepad - Creating and running your rst
GUI/WebAssembly/Mobile application
Ring Notepad,
Ring Notepad - Creating and running your rst Web ap-
plication
Ring Notepad,
Ring Notepad - Main Window
Ring Notepad,
Ring Package ManagerRingPM
Create Package in the Current Folder,
Creating New Package,
Deleting All Packages,
Discovering Packages,
Features,
Installing Packages,
Index 1808

Ring Documentation, Release 1.14
Introduction,
Printing List of Installed Packages,
Remove Package,
Run Package,
The Package Description File,
The RingPM Registry File,
Update Package,
Updating the RingPM Registry,
Ring source code les and permissions
Deploying Web Applications in the Cloud,
Ring State
Embedding Ring Language in C/C++ Programs,
1439
Ring State Functions
Embedding Ring Language in C/C++ Programs,
1439
Ring State Variables
Embedding Ring Language in C/C++ Programs,
1440
Ring support in SpaceVim
What is new in Ring 1.13?,
Ring Team
Resources,
Ring VM - Tracing Functions
What is new in Ring 1.5?,
ring_ext.c
Extension,
ring_ext.h
Extension,
ring_state_letokens() function
Embedding Ring in Ring,
What is new in Ring 1.12?,
ring_state_new() and ring_state_mainle()
Embedding Ring in Ring,
ring_state_new() and ring_state_mainle() functions
What is new in Ring 1.7?,
ring_state_setvar()
Embedding Ring in Ring,
RingAllegro Functions Reference
Introduction,
RingCodeHighlighter Class
RingQt Classes Reference,
RingConsoleColors Extension
What is new in Ring 1.6?,
RingConsoleColors Functions Reference
Introduction,
RingFreeGLUT Extension
What is new in Ring 1.5?,
RingFreeGLUT Functions Reference
Introduction,
RingLibCurl
Facebook Login,
Get Request,
Get Stock Data From Yahoo,
Introduction,
Post Request,
Save output to string,
What is new in Ring 1.2?,
RingLibCurl Functions Reference
Introduction,
RingLibSDL
Close Window Event,
Create Window,
Display Image,
Display PNG Images,
Display Transparent Images,
Draw Rectangle,
Introduction,
Mouse Events,
Play Sound,
Switch Between Two Images,
Use TTF Fonts,
What is new in Ring 1.1?,
RingLibSDL Functions Reference
Introduction,
RingLibui Extension
What is new in Ring 1.14?,
RingLibuv
Client Example,
Client Example - Using Classes,
First Application using RingLibuv,
Introduction,
Server Example,
Server Example using Classes,
The Events Loop,
Threads Example,
Threads Example - Using Classes,
RingLibuv Extension
What is new in Ring 1.7?,
RingLibuv Functions Reference
Introduction,
RingLibZip Functions Reference
Introduction,
RingMurmurHash Extension
What is new in Ring 1.6?,
RingMurmurHash Functions Reference
Example,
Introduction,
MurmurHash1 functions,
MurmurHash2 functions,
MurmurHash3 functions,
RingOpenGL (OpenGL 3.2) Functions Reference
Introduction,
RingOpenGL Extension
What is new in Ring 1.5?,
RingPostgreSQL Constants
PostgreSQL,
RingPostgreSQL Extension
Index 1809

Ring Documentation, Release 1.14
What is new in Ring 1.9?,
RingPostgreSQL Functions
PostgreSQL,
RingQt Classes and their Qt Documentation
Desktop, WebAssembly and Mobile Development,
456
RingQt Classes Reference
AbstractAxis Class,
AbstractBarSeries Class,
CodeEditor Class,
Introduction,
QAbstractAspect Class,
QAbstractButton Class,
QAbstractCameraController Class,
QAbstractItemView Class,
QAbstractPrintDialog Class,
QAbstractScrollArea Class,
QAbstractSeries Class,
QAbstractSlider Class,
QAbstractSocket Class,
QAbstractSpinBox Class,
QAction Class,
QAllEvents Class,
QApp Class,
QAreaLegendMarker Class,
QAreaSeries Class,
QAspectEngine Class,
QAxBase Class,
QAxObject Class,
QAxWidget Class,
QAxWidget2 Class,
QBarCategoryAxis Class,
QBarLegendMarker Class,
QBarSeries Class,
QBarSet Class,
QBitmap Class,
QBluetoothAddress Class,
QBluetoothDeviceDiscoveryAgent Class,
QBluetoothDeviceInfo Class,
QBluetoothHostInfo Class,
QBluetoothLocalDevice Class,
QBluetoothServer Class,
QBluetoothServiceDiscoveryAgent Class,
QBluetoothServiceInfo Class,
QBluetoothSocket Class,
QBluetoothTransferManager Class,
QBluetoothTransferReply Class,
QBluetoothTransferRequest Class,
QBluetoothUuid Class,
QBoxLayout Class,
QBoxPlotLegendMarker Class,
QBoxPlotSeries Class,
QBoxSet Class,
QBrush Class,
QBuffer Class,
QButtonGroup Class,
QByteArray Class,
QCalendarWidget Class,
QCamera Class,
QCameraImageCapture Class,
QCameraLens Class,
QCameraSelector Class,
QCameraViewnder Class,
QCandlestickLegendMarker Class,
QCandlestickModelMapper Class,
QCandlestickSeries Class,
QCandlestickSet Class,
QCategoryAxis Class,
QChar Class,
QChart Class,
QChartView Class,
QCheckBox Class,
QChildEvent Class,
QClipboard Class,
QColor Class,
QColorDialog Class,
QComboBox Class,
QCompleter Class,
QCompleter2 Class,
QCompleter3 Class,
QConeGeometry Class,
QConeMesh Class,
QCoreApplication Class,
QCuboidMesh Class,
QCullFace Class,
QCursor Class,
QCylinderMesh Class,
QDate Class,
QDateEdit Class,
QDateTime Class,
QDateTimeAxis Class,
QDateTimeEdit Class,
QDepthTest Class,
QDesktopServices Class,
QDesktopWidget Class,
QDial Class,
QDialog Class,
QDiffuseSpecularMaterial Class,
QDir Class,
QDirModel Class,
QDockWidget Class,
QDrag Class,
QDragEnterEvent Class,
QDragLeaveEvent Class,
QDragMoveEvent Class,
QDropEvent Class,
QEffect Class,
QEntity Class,
Index 1810

Ring Documentation, Release 1.14
QEvent Class,
QExtrudedTextMesh Class,
QFile Class,
QFile2 Class,
QFileDevice Class,
QFileDialog Class,
QFileInfo Class,
QFileSystemModel Class,
QFirstPersonCameraController Class,
QFont Class,
QFontDialog Class,
QFontMetrics Class,
QForwardRenderer Class,
QFrame Class,
QFrame2 Class,
QFrame3 Class,
QFrameAction Class,
QGeoAddress Class,
QGeoAreaMonitorInfo Class,
QGeoAreaMonitorSource Class,
QGeoCircle Class,
QGeoCoordinate Class,
QGeoPositionInfo Class,
QGeoPositionInfoSource Class,
QGeoRectangle Class,
QGeoSatelliteInfo Class,
QGeoSatelliteInfoSource Class,
QGeoShape Class,
QGoochMaterial Class,
QGradient Class,
QGraphicsScene Class,
QGraphicsVideoItem Class,
QGraphicsView Class,
QGridLayout Class,
QGuiApplication Class,
QHBarModelMapper Class,
QHBoxLayout Class,
QHBoxPlotModelMapper Class,
QHCandlestickModelMapper Class,
QHeaderView Class,
QHorizontalBarSeries Class,
QHorizontalPercentBarSeries Class,
QHorizontalStackedBarSeries Class,
QHostAddress Class,
QHostInfo Class,
QHPieModelMapper Class,
QHXYModelMapper Class,
QIcon Class,
QImage Class,
QInputAspect Class,
QInputDialog Class,
QIODevice Class,
QJsonArray Class,
QJsonDocument Class,
QJsonObject Class,
QJsonParseError Class,
QJsonValue Class,
QKeySequence Class,
QLabel Class,
QLayout Class,
QLCDNumber Class,
QLegend Class,
QLegendMarker Class,
QLinearGradient Class,
QLineEdit Class,
QLineSeries Class,
QListView Class,
QListWidget Class,
QListWidgetItem Class,
QLocale Class,
QLogicAspect Class,
QLogValueAxis Class,
QMainWindow Class,
QMaterial Class,
QMatrix4x4 Class,
QMdiArea Class,
QMdiSubWindow Class,
QMediaObject Class,
QMediaPlayer Class,
QMediaPlaylist Class,
QMenu Class,
QMenuBar Class,
QMesh Class,
QMessageBox Class,
QMetalRoughMaterial Class,
QMimeData Class,
QMorphPhongMaterial Class,
QMovie Class,
QMutex Class,
QMutexLocker Class,
QNetworkAccessManager Class,
QNetworkProxy Class,
QNetworkReply Class,
QNetworkRequest Class,
QNmeaPositionInfoSource Class,
QNode Class,
QObject Class,
QObjectPicker Class,
QOpenGLBuffer Class,
QOpenGLContext Class,
QOpenGLDebugLogger Class,
QOpenGLFramebufferObject Class,
QOpenGLFunctions Class,
QOpenGLFunctions_3_2_Core Class,
QOpenGLPaintDevice Class,
QOpenGLShader Class,
QOpenGLShaderProgram Class,
QOpenGLTexture Class,
Index 1811

Ring Documentation, Release 1.14
QOpenGLTimerQuery Class,
QOpenGLVersionProle Class,
QOpenGLVertexArrayObject Class,
QOpenGLWidget Class,
QOrbitCameraController Class,
QPageSetupDialog Class,
QPaintDevice Class,
QPainter Class,
QPainter2 Class,
QPainterPath Class,
QPen Class,
QPercentBarSeries Class,
QPerVertexColorMaterial Class,
QPhongMaterial Class,
QPicture Class,
QPieLegendMarker Class,
QPieSeries Class,
QPieSlice Class,
QPixmap Class,
QPixmap2 Class,
QPlainTextEdit Class,
QPlaneMesh Class,
QPoint Class,
QPointF Class,
QPointLight Class,
QPolarChart Class,
QPrintDialog Class,
QPrinter Class,
QPrinterInfo Class,
QPrintPreviewDialog Class,
QPrintPreviewWidget Class,
QProcess Class,
QProgressBar Class,
QPushButton Class,
QQmlEngine Class,
QQmlError Class,
QQuaternion Class,
QQuickView Class,
QQuickWidget Class,
QRadioButton Class,
QRect Class,
QRegion Class,
QRegularExpression Class,
QRegularExpressionMatch Class,
QRegularExpressionMatchIterator Class,
QRenderAspect Class,
QRenderPass Class,
QScatterSeries Class,
QSceneLoader Class,
QScreen Class,
QScrollArea Class,
QScrollBar Class,
QSerialPort Class,
QSerialPortInfo Class,
QSize Class,
QSkyboxEntity Class,
QSlider Class,
QSphereMesh Class,
QSpinBox Class,
QSplashScreen Class,
QSplineSeries Class,
QSplitter Class,
QSqlDatabase Class,
QSqlDriver Class,
QSqlDriverCreatorBase Class,
QSqlError Class,
QSqlField Class,
QSqlIndex Class,
QSqlQuery Class,
QSqlRecord Class,
QStackedBarSeries Class,
QStackedWidget Class,
QStandardPaths Class,
QStatusBar Class,
QString2 Class,
QStringList Class,
QStringRef Class,
QSurfaceFormat Class,
QSystemTrayIcon Class,
Qt3DCamera Class,
Qt3DWindow Class,
QTabBar Class,
QTableView Class,
QTableWidget Class,
QTableWidgetItem Class,
QTabWidget Class,
QTcpServer Class,
QTcpSocket Class,
QTechnique Class,
QTest Class,
QText2DEntity Class,
QTextBlock Class,
QTextBrowser Class,
QTextCharFormat Class,
QTextCodec Class,
QTextCursor Class,
QTextDocument Class,
QTextEdit Class,
QTextStream Class,
QTextStream2 Class,
QTextStream3 Class,
QTextStream4 Class,
QTextStream5 Class,
QTextToSpeech Class,
QTextureLoader Class,
QTextureMaterial Class,
QThread Class,
QThreadPool Class,
Index 1812

Ring Documentation, Release 1.14
QTime Class,
QTimer Class,
QToolBar Class,
QToolButton Class,
QTorusMesh Class,
QTransform Class,
QTreeView Class,
QTreeWidget Class,
QTreeWidgetItem Class,
QUrl Class,
QUuid Class,
QValueAxis Class,
QVariant Class,
QVariant2 Class,
QVariant3 Class,
QVariant4 Class,
QVariant5 Class,
QVariantDouble Class,
QVariantFloat Class,
QVariantInt Class,
QVariantString Class,
QVBarModelMapper Class,
QVBoxLayout Class,
QVBoxPlotModelMapper Class,
QVCandlestickModelMapper Class,
QVector2D Class,
QVector3D Class,
QVector4D Class,
QVectorQVoice Class,
QVideoWidget Class,
QVideoWidgetControl Class,
QViewport Class,
QVoice Class,
QVPieModelMapper Class,
QVXYModelMapper Class,
QWebEnginePage Class,
QWebEngineView Class,
QWebView Class,,
QWidget Class,
QWindow Class,
QXmlStreamAttribute Class,
QXmlStreamAttributes Class,
QXmlStreamEntityDeclaration Class,
QXmlStreamEntityResolver Class,
QXmlStreamNamespaceDeclaration Class,
QXmlStreamNotationDeclaration Class,
QXmlStreamReader Class,
QXmlStreamWriter Class,
QXYLegendMarker Class,
QXYSeries Class,
RingCodeHighlighter Class,
RingRayLib Extension
What is new in Ring 1.11?,
RingREPL
What is new in Ring 1.4?,
RingSockets Extension
What is new in Ring 1.14?,
RingSQLite
What is new in Ring 1.1?,
RingStbImage Extension
What is new in Ring 1.13?,
RingStbImage Functions Reference
Introduction,
RingThreads Extension
What is new in Ring 1.14?,
RingTilengine Extension
What is new in Ring 1.14?,
ringvm_callfunc()
Low Level Functions,
RingVM_CallList()
Low Level Functions,
RingVM_CFunctionsList()
Low Level Functions,
RingVM_ClassesList()
Low Level Functions,
ringvm_evalinscope()
Low Level Functions,
RingVM_FilesList()
Low Level Functions,
RingVM_FunctionsList()
Low Level Functions,
ringvm_give() function
Low Level Functions,
ringvm_hideerrorMsg()
Low Level Functions,
ringvm_info()
Low Level Functions,
RingVM_MemoryList()
Low Level Functions,
RingVM_PackagesList()
Low Level Functions,
ringvm_passerror()
Low Level Functions,
ringvm_scopescount()
Low Level Functions,
ringvm_see() and ringvm_give() functions
What is new in Ring 1.7?,
ringvm_see() function
Low Level Functions,
ringvm_settrace()
Low Level Functions,
ringvm_tracedata()
Low Level Functions,
ringvm_traceevent()
Low Level Functions,
ringvm_tracefunc()
Low Level Functions,
RingZip
Index 1813

Ring Documentation, Release 1.14
Create Zip File,
Extract Zip File,
Introduction,
Print les in Zip le,
Using RingZip Classes,
Zip Class Reference,
ZipEntry Class Reference,
RingZip Library
What is new in Ring 1.3?,
Rotate Text
Desktop, WebAssembly and Mobile Development,
418
Rules
The Type Hints Library,
Run Package
Ring Package ManagerRingPM,
Run the program
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
Running Forms
Form Designer,
Runtime Errors
Language Specication,
Runtime Errors when Embedding Ring in Ring
Embedding Ring in Ring,
Samples
How to contribute?,
Samples in this book
Applications developed in a few hours,
Samples SourceAuthors
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Save and Restore Images
ODBC Functions,
Save Image Inside the Database
MySQL Functions,
Save output to string
RingLibCurl,
Say Hello
libui,
Tutorial: Ring Extensions in C/C++,
Say Something
libui,
Scaling and Rotating Images
Graphics and Game Programming,
Scene
Using Qt3D,
Scope Rules
Accessing the class attributes from braces inside
class methods,
Conict between Class Attributes and Local Vari-
ables,
Conict between Global Variables and Class At-
tributes,
Conict between self inside braces and self in the
class region,
Creating a Class for each Window in GUI applica-
tions,
Dening Variables and Variables Access,
How Ring nd the Variable?,
Introduction,
Summary of Scope Rules,
The For Loops uses the local scope,
The Self Object,
Three Scopes,
Using Braces to access objects inside Class Methods,
263
Using braces to escape from the current object scope,
271
Using Object.Attribute,
Scope Rules for Functions and Methods
Calling a function sharing the name with a method in
the current class,
Example about Sharing Names between Functions
and Methods,
How Ring nd a functions and methods?,
Introduction,
Screen Shots
The Gold Magic 800 Game,
ScriptFunctions Class
Web DevelopmentCGI Library,
Search
Lists,
Search of global names while dening the class attributes
Frequently Asked Questions,
Security and Internet Functions
Decrypt(),
Download(),
Encrypt(),
Example,
File Hash,
Introduction,
Large Files Hash,
MD5(),
RandBytes(),
SendEmail(),
SHA1(),
SHA224(),
SHA256(),
SHA384(),
SHA512(),
Security Class
Stdlib Classes,
Send Parameters
Functions - First Style,
Functions - Second Style,
Index 1814

Ring Documentation, Release 1.14
Functions - Third Style,
SendEmail()
Security and Internet Functions,
Serial Execution of Programs
Embedding Ring in Ring,
Server Example
RingLibuv,
Server Example using Classes
RingLibuv,
Set List Item
Lists,
setattribute()
Reection and Meta-programming,
setpointer()
Low Level Functions,
Setter and Getter
Object Oriented Programming,
Setting the shebang line
Web DevelopmentCGI Library,
SHA1()
Security and Internet Functions,
SHA224()
Security and Internet Functions,
SHA256()
Security and Internet Functions,
SHA384()
Security and Internet Functions,
SHA512()
Security and Internet Functions,
Shared Libraries
Extension,
Short-circuit evaluation
Control Structures - First Style,
Shutdown() Function
System Functions,
sign()
Stdlib Functions,
Simple
Language Design,
Simple Client and Server Example
Desktop, WebAssembly and Mobile Development,
422
Sin() Implementation
Extension,
Single: Desktop,
Single: Using Qt3D
Using Qt3D,
Single: Using RingRayLib
Introduction,
Single: Using ZeroLib
Introduction,
sleep()
Stdlib Functions,
Smart Garbage Collector
Language Design,
Snake Game
What is new in Ring 1.11?,
Snakes And Ladder Game
What is new in Ring 1.10?,
socket
Constants,
sockets
Functions,
Introduction,
TCP Client,
TCP Server,
Sokoban Game
What is new in Ring 1.11?,
Sort()
Lists,
Sort() and List of Objects
Object Oriented Programming,
Sound Class
Game Engine for 2D Games,
Sound Loading
Using RingRayLib,
Source Code
Resources,
The Gold Magic 800 Game,
Using ZeroLib,
Source Code File Sections
Program Structure,
space()
Low Level Functions,
SpaceVim
Using Other Code Editors,
Special thanks to contributors
How to contribute?,
split()
Stdlib Functions,
splitmany()
Stdlib Functions,
Sprite Automatic Movement
Game Engine for 2D Games,
Sprite Class
Game Engine for 2D Games,
Sprite Keypress Event
Game Engine for 2D Games,
Sprite Mouse Event
Game Engine for 2D Games,
Sprite State Event
Game Engine for 2D Games,
SQLite
Introduction,
sqlite_close(),
sqlite_execute(),
sqlite_init(),
sqlite_open(),
Index 1815

Ring Documentation, Release 1.14
SQLite Class
Stdlib Classes,
sqlite_close()
SQLite,
sqlite_execute()
SQLite,
sqlite_init()
SQLite,
sqlite_open()
SQLite,
Squares Puzzle Game
Applications developed in a few hours,
SRandom()
Mathematical Functions,
Stack Class
Stdlib Classes,
Stars Fighter Game
Game Engine for 2D Games,
startswith()
Stdlib Functions,
Static Methods
Code Generator,
StdBase Class
Stdlib Classes,
StdLib - More Functions
What is new in Ring 1.11?,
Stdlib Classes
Conversion Class,
DataType Class,
DateTime Class,
Debug Class,
File Class,
HashTable Class,
Internet Class,
Introduction,
List Class,
Math Class,
MySQL Class,
ODBC Class,
PostgreSQL Class,
Queue Class,
Security Class,
SQLite Class,
Stack Class,
StdBase Class,
String Class,
System Class,
Tree Class,
Stdlib Functions
apppath(),
ASCIIList2Str(),
binarydigits(),
capitalized(),
changestring(),
dayofweek(),
endswith(),
EpochTime(),
evenorodd(),
factorial(),
factors(),
bonacci(),
le2list(),
lter(),
FSize(),
gcd(),
getnumber(),
getstring(),
Introduction,
IsBetween(),
isleapyear(),
IsListContainsItems(),
ismainsourcele(),
ispalindrome(),
isprime(),
isspecial(),
isvowel(),
JustFileName(),
JustFilePath(),
lcm(),
linecount(),
List2Code() Function,
list2le(),
ListAllFiles() Function,
makedir(),
map(),
matrixmulti(),
matrixtrans(),
OSCopyFile() Function,
OSCopyFolder() Function,
OSCreateOpenFolder() Function,
OSDeleteFile() Function,
OSDeleteFolder() Function,
OSRenameFile() Function,
permutation(),
print(),
Print2Str() Function,
prodlist(),
puts(),
readline(),
sign(),
sleep(),
split(),
splitmany(),
startswith(),
Str2ASCIIList(),
substring(),
sumlist(),
SystemCmd() Function,
Index 1816

Ring Documentation, Release 1.14
SystemSilent() Function,
TimeInfo(),
times(),
TrimAll(),
TrimLeft(),
TrimRight(),
value(),
StdLib functions and classes written in Ring
What is new in Ring 1.1?,
Step Option
Control Structures - First Style,
Steps to create the extension
Create your rst extension,
StopWatch Application
What is new in Ring 1.8?,
Str2ASCIIList()
Stdlib Functions,
Str2Hex()
Data Type,
str2list() and list2str()
Strings,
strcmp()
Strings,
String Class
Stdlib Classes,
String Literals
Strings,
String()
Data Type,
String2Constant Application
What is new in Ring 1.8?,
Strings
Access String Letters,
Convert Letters Case,
Copy(),
Find SubString,
Get Number of Characters from position,
Get String Length,
Get Substring from position to end,
Introduction,
Left(),
Lines(),
Merge binary characters,
Right(),
str2list() and list2str(),
strcmp(),
String Literals,
Substr(),
Transform Substring To Another Substring,
Trim(),
StyleFunctions Class
Web DevelopmentCGI Library,
Substr()
Strings,
substring()
Stdlib Functions,
Sudoku Game
What is new in Ring 1.11?,
Sum List of Numbers
Tutorial: Ring Extensions in C/C++,
Sum Two Numbers
Tutorial: Ring Extensions in C/C++,
sumlist()
Stdlib Functions,
Summary of Scope Rules
Scope Rules,
Super Man 2016 Game
Game Engine for 2D Games,
Swap Items
Lists,
Switch Between Two Images
RingLibSDL,
Switch Statement
Control Structures - First Style,
Control Structures - Second Style,
Control Structures - Third Style,
Syntax Flexibility
Change Language Keywords,
Change Language Operators,
Ignore new lines after keywords,
Introduction,
Load Syntax Files,
Using "()" around the function parameters,
Using $ and @ in the start of the variable name,
Using case as on in switch statements,
Using def as func in functions/methods denition,
288
Using end keyword after Pack-
ages/Classes/Functions,
Using endpackage/endclass/endfunc keywords af-
ter Packages/Classes/Functions,
Using put and get as see and give,
Using braces { } in Packages/Classes/Functions,
Using braces to start and end different control struc-
tures,
Using Semi-colon after and between statements,
Using the else keyword as other in switch state-
ment,
Using the elseif keyword as but in if statement,
Using the end keyword in different control struc-
tures,
What is new in Ring 1.1?,
SysGet() Function
System Functions,
SysSet() Function
System Functions,
System Class
Stdlib Classes,
Index 1817

Ring Documentation, Release 1.14
System Functions
ChDir() Function,
CurrentDir() Function,
Example,
ExeFileName() Function,
ExeFolder() Function,
Get Active Source File Name,
Get Command Line Arguments,
GetArch() Function,
Introduction,
IsAndroid() Function,
IsFreeBSD() Function,
IsLinux() Function,
IsMacOSX() Function,
IsMSDOS() Function,
IsUnix() Function,
IsWindows() Function,
IsWindows64() Function,
NofProcessors() Function,
PrevFileName() Function,
Shutdown() Function,
SysGet() Function,
SysSet() Function,
System() Function,
SysUnset() Function,
Version() Function,
Windowsnl() Function,
System() Function
System Functions,
SystemCmd() Function
Stdlib Functions,
SystemSilent() Function
Stdlib Functions,
SysUnset() Function
System Functions,
TCP Client
sockets,
TCP Server
sockets,
Temple()
Files,
Templates
Web DevelopmentCGI Library,
Tempname()
Files,
Testing
How to contribute?,
Testing the extension
Create your rst extension,
Tetris Game
What is new in Ring 1.13?,
Text 2D
Using Qt3D,
Text Class
Game Engine for 2D Games,
Text Drawing
libui,
Text To Speech Application
What is new in Ring 1.11?,
Texture
Using Qt3D,
Texture Source
Using RingRayLib,
The Browser Menu
Ring Notepad,
The Camera
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
The Cards Game
Demo Programs,
Desktop, WebAssembly and Mobile Development,
445
The Designer Windows
Form Designer,
The Difference between Qt and RingQt
Desktop, WebAssembly and Mobile Development,
455
The Distribute Menu
Ring Notepad,
The documentation says functional programming is sup-
ported, but then this happens?
Frequently Asked Questions,
The Edit Menu
Ring Notepad,
The Events Loop
Desktop, WebAssembly and Mobile Development,
352
RingLibuv,
The File Menu
Ring Notepad,
The les ring.ring and ring.ringo
Distributing Ring Application,
The First GUI Application
Desktop, WebAssembly and Mobile Development,
351
The First Triangle
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
The First Window using RingFreeGLUT
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
The For Loops uses the local scope
Scope Rules,
What is new in Ring 1.8?,
The Game Story
The Gold Magic 800 Game,
The Gold Magic 800 Game
Index 1818

Ring Documentation, Release 1.14
How to play?,
Introduction,
Screen Shots,
Source Code,
The Game Story,
What will you learn?,
The Help Menu
Ring Notepad,
The Main File in the Project
Ring Notepad,
The Natural Library
What is new in Ring 1.4?,
The Package Description File
Ring Package ManagerRingPM,
The Program Menu
Ring Notepad,
The Properties
Form Designer,
The Qt project for your Ring application
Building RingQt Applications for Mobile,
Building RingQt Applications for WebAssembly,
523
The Ring Package ManagerRingPM
What is new in Ring 1.10?,
The RingPM Registry File
Ring Package ManagerRingPM,
The Self Object
Scope Rules,
The Tools Menu
Ring Notepad,
The Trace Library and the Interactive Debugger
BreakPoint,
Disable BreakPoints,
Execute Program Line by Line,
Interactive Debugger,
Introduction,
Loading the Trace library,
Pass Error,
Trace All Events,
Trace control ow between functions,
Using the Interactive Debugger,
The Type Hints Library
Example,
Introduction to the Type Hints Library,
Rules,
User Types,
Using Types inside Code,
Why Type Hints?,
The View Menu
Ring Notepad,
Threads
Creating Threads,
Graphics and Game Programming,
Introduction,
More Examples,
Reference,
Threads Example
RingLibuv,
Threads Example - Using Classes
RingLibuv,
Threads Support
Code Generator,
Three Scopes
Scope Rules,
TicTacToe 3D Game
Using RingOpenGL and RingAllegro for 3D Graph-
ics,
tilengine
Getting Started,
Introduction,
More Samples,
Reference,
Using LibSDL and Tilengine,
Time()
Date and Time,
TimeInfo()
Stdlib Functions,
TimeList()
Date and Time,
times()
Stdlib Functions,
Trace All Events
The Trace Library and the Interactive Debugger,
Trace control ow between functions
The Trace Library and the Interactive Debugger,
Trace Library and Interactive Debugger
What is new in Ring 1.5?,
Transaction Example
MySQL Functions,
Transactions and Using Commit and Rollback
ODBC Functions,
Transform Substring To Another Substring
Strings,
Transparent Image
Graphics and Game Programming,
Transparent Implementation
Language Design,
Tree Class
Stdlib Classes,
Triangle Rotation
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Trim()
Strings,
TrimAll()
Stdlib Functions,
TrimLeft()
Stdlib Functions,
Index 1819

Ring Documentation, Release 1.14
TrimRight()
Stdlib Functions,
TrueType Fonts
Graphics and Game Programming,
Try/Carch/Done
Eval() and Debugging,
Trying to be natural
Language Design,
Tutorial: Number to Words
What is new in Ring 1.12?,
Tutorial: Ring Extensions in C/C++
Build the extension on different platforms,
Create Table,
Display List,
Filter List Items,
Generate List,
Hello World,
Increment List Items,
Replicate List Items,
Say Hello,
Sum List of Numbers,
Sum Two Numbers,
Tutorial: Ring Extensions in C/C++,
Update Table,
Two Cubes
Using RingRayLib,
Type Hints Library
What is new in Ring 1.5?,
Type()
Data Type,
Ungetc()
Files,
Unsigned()
Mathematical Functions,
Update Package
Ring Package ManagerRingPM,
Update Table
Tutorial: Ring Extensions in C/C++,
Update the Android SDK
Building RingQt Applications for Mobile,
Updating the RingPM Registry
Ring Package ManagerRingPM,
Upload Files
Web DevelopmentCGI Library,
URL Encode
Web DevelopmentCGI Library,
Usage
Deploying Web Applications in the Cloud,
Use TTF Fonts
RingLibSDL,
User Types
The Type Hints Library,
Users registration and Login
Web DevelopmentCGI Library,
Using "()" around the function parameters
Syntax Flexibility,
Using ? to print expression then new line
Getting Started - First Style,
What is new in Ring 1.6?,
Using $ and @ in the start of the variable name
Syntax Flexibility,
Using && and || operators
What is new in Ring 1.6?,
Using _ in numbers
Mathematical Functions,
Using < and : operators as from keyword
What is new in Ring 1.3?,
Using case as on in switch statements
Syntax Flexibility,
Using def as func in functions/methods denition
Syntax Flexibility,
Using end keyword after Packages/Classes/Functions
Syntax Flexibility,
Using endpackage/endclass/endfunc keywords after
Packages/Classes/Functions
Syntax Flexibility,
Using put and get as see and give
Syntax Flexibility,
Using Atom
Using Other Code Editors,
Using Bootstrap Library using Functions
Web DevelopmentCGI Library,
Using Bootstrap Library using Objects
Web DevelopmentCGI Library,
Using braces { } in Packages/Classes/Functions
Syntax Flexibility,
Using Braces to access objects inside Class Methods
Scope Rules,
Using braces to escape from the current object scope
Scope Rules,
Using braces to start and end different control structures
Syntax Flexibility,
Using C/C++ Compiler and Linker
Distributing Ring Application,
Using CLOCCount Lines of Code
What is new in Ring 1.14?,
Using conguration le that wrap C++ library
Code Generator,
Using CR as Carriage return
What is new in Ring 1.6?,
Using Emacs Editor
Using Other Code Editors,
Using Eval() with our Natural Code
Natural Language Programming,
Using f after numbers
Mathematical Functions,
Using Fonts
Index 1820

Ring Documentation, Release 1.14
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Using Geany
Using Other Code Editors,
Using Layout
Desktop, WebAssembly and Mobile Development,
353
Using Layouts
Form Designer,
Using len() and For Loops
Performance Tips,
Using LibSDL and Tilengine
tilengine,
Using Lists during denition
Lists,
Using Many Source Code Files
Program Structure,
Using Notepad++
Using Other Code Editors,
Using NULL instead of NULLPointer()
What is new in Ring 1.2?,
Using Object.Attribute
Scope Rules,
Using Other Code Editors
Introduction,
SpaceVim,
Using Atom,
Using Emacs Editor,
Using Geany,
Using Notepad++,
Using Sublime Text 2,
Using Visual Studio IDE,
Visual Studio Code,
Using QCheckBox
Desktop, WebAssembly and Mobile Development,
379
Using QComboBox Class
Desktop, WebAssembly and Mobile Development,
361
Using QDateEdit
Desktop, WebAssembly and Mobile Development,
374
Using QDesktopWidget Class
Desktop, WebAssembly and Mobile Development,
417
Using QDial
Desktop, WebAssembly and Mobile Development,
375
Using QDockWidget
Desktop, WebAssembly and Mobile Development,
367
Using QFrame
Desktop, WebAssembly and Mobile Development,
385
Using QInputDialog Class
Desktop, WebAssembly and Mobile Development,
409
Using qLCDNumber
Desktop, WebAssembly and Mobile Development,
405
Using QPrintPreviewDialog
Desktop, WebAssembly and Mobile Development,
400
Using QProgressBar
Desktop, WebAssembly and Mobile Development,
371
Using QProgressBar and Timer
Desktop, WebAssembly and Mobile Development,
394
Using QRadioButton and QButtonGroup
Desktop, WebAssembly and Mobile Development,
380
Using QSlider
Desktop, WebAssembly and Mobile Development,
373
Using QSpinBox
Desktop, WebAssembly and Mobile Development,
372
Using Qt3D
Camera,
Draw Ofce,
Drawing Cone,
Drawing Cube,
Drawing Cylinder,
Drawing Plane,
Drawing Sphere,
Drawing Torus,
Extruded Text,
Frame Action,
Key Press,
Many Objects,
Model,
Model Texture,
Object Picker,
Scene,
Text 2D,
Texture,
Using QTableWidget
Desktop, WebAssembly and Mobile Development,
370
Using QTabWidget
Desktop, WebAssembly and Mobile Development,
369
Using QTreeView and QFileSystemModel
Desktop, WebAssembly and Mobile Development,
358
Using QTreeWidget and QTreeWidgetItem
Index 1821

Ring Documentation, Release 1.14
Desktop, WebAssembly and Mobile Development,
359
Using QWebView
Desktop, WebAssembly and Mobile Development,
378
Using Ring2EXE
Building RingQt Applications for Mobile,
Building RingQt Applications for WebAssembly,
522
Distributing Ring Application using Ring2EXE,
Using RING_API_RETMANAGEDCPOINTER()
Extension,
Using RingOpenGL and RingAllegro for 3D Graphics
3D Cube and Texture,
Introduction,
Many Cubes,
More 3D Samples,
TicTacToe 3D Game,
Using RingOpenGL and RingFreeGLUT for 3D Graphics
Drawing using RingOpenGL,
Frames Per Second,
Introduction,
Keyboard Events and Colors,
Make a Cube using RingOpenGL and RingFreeG-
LUT,
Menu Events,
Mouse Events,
Samples SourceAuthors,
The Camera,
The First Triangle,
The First Window using RingFreeGLUT,
Triangle Rotation,
Using Fonts,
What is RingFreeGLUT?,
What is RingOpenGL?,
Window Resize Event,
Using RingRayLib
3D Camera,
3D Camera Free,
3D Picking,
Basic Shapes,
Basic Window,
Bezier Lines,
Camera First Person,
Collision Area,
Colors Palette,
Cubic Map,
Draw Ring,
Following Eyes,
Full Screen,
Functions,
Geometric Shapes,
Image Drawing,
Image Generation,
Input Keys,
Input Mouse,
Input Multi-touch,
Introduction,
Mouse Wheel,
Music Playing,
Rectangle Scaling,
Sound Loading,
Texture Source,
Two Cubes,
Using RingZip Classes
RingZip,
Using Self.Attribute
Object Oriented Programming,
Using Self.Attribute in the Class Region to dene new at-
tributes
What is new in Ring 1.1?,
Using Semi-colon after and between statements
Syntax Flexibility,
Using String2Constant
Multi-language applications,
Using Sublime Text 2
Using Other Code Editors,
Using Tab instead of char(9)
What is new in Ring 1.6?,
Using the ! operator as not
What is new in Ring 1.6?,
Using the else keyword as other in switch statement
Syntax Flexibility,
Using the elseif keyword as but in if statement
Syntax Flexibility,
Using the end keyword in different control structures
Syntax Flexibility,
Using the Interactive Debugger
The Trace Library and the Interactive Debugger,
Using the Menubar
libui,
Using the Natural Library
Dening Commands,
Dening commands using classes,
Introduction,
Natural Library - Demo Program,
Operators,
Using the QColorDialog Class
Desktop, WebAssembly and Mobile Development,
404
Using the QFileDialog Class
Desktop, WebAssembly and Mobile Development,
396
Using the QListWidget Class
Desktop, WebAssembly and Mobile Development,
355
Using the QTextEdit Class
Index 1822

Ring Documentation, Release 1.14
Desktop, WebAssembly and Mobile Development,
354
Using the QTimer Class
Desktop, WebAssembly and Mobile Development,
393
Using the tool
Code Generator,
Using This in the class region as Self
Object Oriented Programming,
What is new in Ring 1.8?,
Using This.Attribute and This.Method()
Object Oriented Programming,
Using This.Attribute in nested Braces inside the Class
Methods
What is new in Ring 1.1?,
Using Types inside Code
The Type Hints Library,
Using Visual Studio IDE
Using Other Code Editors,
Using XAMPP Apache web server
Congure the Apache web server,
Using ZeroLib
Introduction,
Source Code,
Z() function,
ZeroBasedList Class,
ZeroBasedString Class,
value()
Stdlib Functions,
Variables
Deep Copy,
Dynamic Typing,
Implicit Conversion,
Introduction,
Variables Scope
Functions - First Style,
Functions - Second Style,
Functions - Third Style,
varptr()
Low Level Functions,
Version() Function
System Functions,
Video-Music-Player Application
Applications developed in a few hours,
What is new in Ring 1.5?,
Virtual Machine Instructions
Language Specication,
Visual Implementation
Language Design,
Visual Studio Code
Using Other Code Editors,
Web DevelopmentCGI Library
Application Class,
Congure the Apache web server,
Cookies,
CRUD Example using MVC,
Database, ModelBase & ControllerBase classes,
Generating Pages using Objects,
Gradient,
Grant Ring les execution permission,
Hash Functions,
Hello World Program using the Web Library,
HTML Lists,
HTML Special Characters,
HTML Tables,
HtmlPage Class,,
HTTP Get Example,
HTTP POST Example,
Introduction,
Page Class,
Random Image,
Ring CGI Hello World Program,
ScriptFunctions Class,
Setting the shebang line,
StyleFunctions Class,
Templates,
Upload Files,
URL Encode,
Users registration and Login,
Using Bootstrap Library using Functions,
Using Bootstrap Library using Objects,
Web Library Features,
WebLib API,
WebPage Class,
Web Development Samples
What is new in Ring 1.14?,
Web Library Features
Web DevelopmentCGI Library,
WebAssembly and Mobile Development
Introduction,
WebLib API
Web DevelopmentCGI Library,
WebPage Class
Web DevelopmentCGI Library,
Weight History Application
Desktop, WebAssembly and Mobile Development,
425
What about Data Representation in Ring?
Frequently Asked Questions,
What about Memory Management in Ring?
Frequently Asked Questions,
What about predened parameters or optional parameters
in functions?
Frequently Asked Questions,
What about the Boolean values in Ring?
Frequently Asked Questions,
Index 1823

Ring Documentation, Release 1.14
What are the advantages of using Ring over native C or
C++?
Frequently Asked Questions,
What are the advantages to using Ring over C# or Java?
Frequently Asked Questions,
What are the advantages to using Ring over Lisp or
Smalltalk?
Frequently Asked Questions,
What are the advantages to using Ring over Python and
Ruby?
Frequently Asked Questions,
What are the advantages to using Ring over Tcl and Lua?
Frequently Asked Questions,
What happens when we create a new object?
Frequently Asked Questions,
What is new in Ring 1.10?
Better Tests,
Chess Game,
Game of Life Game,
Introduction,
Knight Tour Game,
List of changes and new features,
Minesweeper Game,
More Games,
More Improvements,
Pong Game,
Ring Extension for Visual Studio Code,
Snakes And Ladder Game,
The Ring Package ManagerRingPM,
What is new in Ring 1.11?
Better Documentation,
Better Performance,
Better RingQt,
Checkers Game,
Desktop Screen Shot Application,
Introduction,
List of changes and new features,
Maze Game,
More 3D Samples,
More Improvements,
RingRayLib Extension,
Snake Game,
Sokoban Game,
StdLib - More Functions,
Sudoku Game,
Text To Speech Application,
ZeroLib Library,
What is new in Ring 1.12?
ASCII Table application,
Better RingRayLib,
BMI Calculator application,
Calendar application,
Generate Embedded Object File,
Go Game,
Introduction,
Julian Day Calendar application,
List of changes and new features,
Load Again Command,
More Improvements,
ring_state_letokens() function,
Tutorial: Number to Words,
What is new in Ring 1.13?
Better Organization,
Better RingQt,
Better RingRayLib,
Better Threads Support,
Escape Game,
Hassouna Course Samples,
Introduction,
Laser Game,
List of changes and new features,
Magic Balls Game,
Matching Game,
MoneyBoxes Game,
More Improvements,
More Low Level Functions,
New Book by Apress,
Pairs Game,
Ring for WebAssembly,
Ring support in SpaceVim,
RingStbImage Extension,
Tetris Game,
Word Game,
What is new in Ring 1.14?
Better Functions,
Better Handling For Numbers,
Better Performance For Strings,
Better RingOpenSSL,
Customers Form,
Erlang B Formula,
Introduction,
List of changes and new features,
More Functions,
More Improvements,
More Samples,
MyCoffeeWeb Application,
RingLibui Extension,
RingSockets Extension,
RingThreads Extension,
RingTilengine Extension,
Using CLOCCount Lines of Code,
Web Development Samples,
What is new in Ring 1.1?
Better Code Generator for Extensions,
Better Documentation,
Better Natural Language Programming Support,
1478
Game Engine for 2D Games,
Index 1824

Ring Documentation, Release 1.14
Generate/Execute Ring Object Files*.ringo,
Introduction,
List of changes and new features,
New Functions and Changes,
RingLibSDL,
RingSQLite,
StdLib functions and classes written in Ring,
Syntax Flexibility,
Using Self.Attribute in the Class Region to dene
new attributes,
Using This.Attribute in nested Braces inside the
Class Methods,
What is new in Ring 1.2?
Better Call Command,
Better Functions,
Better Quality,
Better Ring Notepad,
Better RingQt,
Display Warnings Option,
Introduction,
List of changes and new features,
New Functions,
Objects Library for RingQt,
RingLibCurl,
Using NULL instead of NULLPointer(),
What is new in Ring 1.3?
Better Loop|Exit Command,
Better Ring Notepad,
Better RingQt,
Better StdLib,
Embedding Ring in Ring without sharing the State,
1504
Form Designer,
Introduction,
List of changes and new features,
New Functions,
Return Self by Reference,
Ring mode for Emacs Editor,
RingZip Library,
Using < and : operators as from keyword,
What is new in Ring 1.4.1?
What is new in Ring 1.4?,
What is new in Ring 1.4?
Better RingQt,
Better StdLib,
Better WebLib,
Change: Basic Extensions are separated from
RingVM,
Convert between Numbers and Bytes,
Introduction,
List of changes and new features,
New Style to Ring Notepad,
Qt Class Convertor,
RingREPL,
The Natural Library,
What is new in Ring 1.4.1?,
What is new in Ring 1.5.1?
What is new in Ring 1.5?,
What is new in Ring 1.5.2?
What is new in Ring 1.5?,
What is new in Ring 1.5.3?
What is new in Ring 1.5?,
What is new in Ring 1.5.4?
What is new in Ring 1.5?,
What is new in Ring 1.5?
Better Code Generator for Extensions,
Better Documentation Generator for Extensions,
1547
Better Objects Library,
Better Quality,
Better Ring Notepad,
Better RingQt,
Better StdLib,
Better WebLib,
Calculator Application,
Introduction,
List of changes and new features,
More Syntax Flexibility,
Ring VM - Tracing Functions,
RingFreeGLUT Extension,
RingOpenGL Extension,
Trace Library and Interactive Debugger,
Type Hints Library,
Video-Music-Player Application,
What is new in Ring 1.5.1?,
What is new in Ring 1.5.2?,
What is new in Ring 1.5.3?,
What is new in Ring 1.5.4?,
Windows StartUp Manager Application,
What is new in Ring 1.6?
Better Ring For Android,
Better Ring Notepad,
Better RingQt,
Better RingREPL,
Better RingVM,
Better Scripts for building Ring,
Better StdLib,
Employee Application,
Introduction,
List of changes and new features,
New Tool: Folder2qrc,
New Tool: Ring2EXE,
RingConsoleColors Extension,
RingMurmurHash Extension,
Using ? to print expression then new line,
Using && and || operators,
Using CR as Carriage return,
Using Tab instead of char(9),
Index 1825

Ring Documentation, Release 1.14
Using the ! operator as not,
What is new in Ring 1.7?
Better Documentation,
Better Ring Notepad,
Better Ring VM,
Better Ring2EXE,
Better RingQt,
Better RingZip,
Better Trace Library,
Introduction,
List of changes and new features,
New Command: Load Package,
ring_state_new() and ring_state_mainle() func-
tions,
RingLibuv Extension,
ringvm_see() and ringvm_give() functions,
What is new in Ring 1.8?
Better Cards Game,
Better Code Generator For Extensions,
Better Form Designer,
Better Performance,
Better Ring Compiler and VM,
Better RingQt,
Compiling on Manjaro Linux,
Default value for object attributes is NULL,
Find in les Application,
FoxRing Library,
Introduction,
List of changes and new features,
Merge binary characters,
More 3D Samples,
Notes to extensions creators,
StopWatch Application,
String2Constant Application,
The For Loops uses the local scope,
Using This in the class region as Self,
What is new in Ring 1.9?
Better Code Generator for Extensions,
Better Memory Management,
Better Ring Notepad,
Better RingQt,
Better StdLib,
BigNumber Library,
Deploying Web applications in the Cloud,
Introduction,
List of changes and new features,
More Games,
More Improvements,
New Game : Gold Magic 800,
RingPostgreSQL Extension,
What is RingFreeGLUT?
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
What is RingOpenGL?
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
What is the difference between Ring and Python? And is
Ring Open Source?
Frequently Asked Questions,
What is the Ring Architecture?
Frequently Asked Questions,
What will you learn?
The Gold Magic 800 Game,
Where can I write a program and execute it?
Frequently Asked Questions,
Which of 3 coding styles are commonly used or recom-
mended by the community?
Frequently Asked Questions,
While Loop
Control Structures - First Style,
Control Structures - Third Style,
Why do we need Yet Another Programming Language
(YAPL)?
Frequently Asked Questions,
Why I get a strange result when printing nl with lists?
Frequently Asked Questions,
Why I get Calling Function without denition Error?
Frequently Asked Questions,
Why is Ring largely focussed on UI creation?
Frequently Asked Questions,
Why is Ring weakly typed?
Frequently Asked Questions,
Why Ring is not case-sensitive
Frequently Asked Questions,
Why Ring uses See, Give, But and Ok Keywords?
Frequently Asked Questions,
Why Ring?
Language Design,
Why setClickEvent() doesnt see the object methods di-
rectly?
Frequently Asked Questions,
Why the ability to dene your own languages Instead of
just handing over the syntax so you can parse it
using whatever code you like?
Frequently Asked Questions,
Why the Assignment operator uses Deep copy?
Frequently Asked Questions,
Why the window title bar is going outside the screen?
Frequently Asked Questions,
Why this example use the GetChar() twice?
Frequently Asked Questions,
Why Type Hints?
The Type Hints Library,
Why we dont use () after the QApp class name?
Frequently Asked Questions,
Why you can specify the number of loops you want to
break out of?
Frequently Asked Questions,
Index 1826

Ring Documentation, Release 1.14
Window Flags
Form Designer,
Window Resize Event
Using RingOpenGL and RingFreeGLUT for 3D
Graphics,
Windows StartUp Manager Application
What is new in Ring 1.5?,
Windowsnl() Function
System Functions,
Word Game
What is new in Ring 1.13?,
Wrap structures
Code Generator,
Wrapping C++ Classes
Code Generator,
Write le using Write()
Files,
Writing Comments
Getting Started - First Style,
Getting Started - Second Style,
Getting Started - Third Style,
Z() function
Using ZeroLib,
ZeroBasedList Class
Using ZeroLib,
ZeroBasedString Class
Using ZeroLib,
ZeroLib Library
What is new in Ring 1.11?,
Zip Class Reference
RingZip,
ZipEntry Class Reference
RingZip,
Index 1827