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
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/scripting/luascripts.h"
#include "gate/results.h"
#include "gate/guids.h"
#include "gate/times.h"
#include "gate/console.h"
#include "gate/functions.h"
#include "gate/files.h"
#include "gate/platforms.h"

#if defined(GATE_EXTLIB_LUA)
#	define GATE_SCRIPTING_LUA_USE_LUA 1
#else
#	define GATE_SCRIPTING_LUA_NO_IMPL 1
#endif


#if defined(GATE_SCRIPTING_LUA_USE_LUA)

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>


#define GATE_SCRIPT_LUA_SESSION_POINTER_NAME "__gate_script_lua_session"

void gate_lua_writestring(char const* str, size_t len, gate_bool_t flushcon)
{
    gate_size_t written = 0;
    gate_console_t* con = gate_console();
    gate_stream_write_block((gate_stream_t*)con, str, len, &written);
    if (flushcon)
    {
        gate_stream_flush((gate_stream_t*)con);
    }
}

void gate_lua_writestring_err(char const* str, size_t len, gate_bool_t flushcon)
{
    gate_size_t written = 0;
    gate_console_t* con = gate_console();
    gate_stream_write_block((gate_stream_t*)con, str, len, &written);
    if (flushcon)
    {
        gate_stream_flush((gate_stream_t*)con);
    }
}

gate_result_t gate_script_lua_init(gate_script_lua_session_t* session)
{
    gate_result_t ret;

    do
    {
        gate_mem_clear(session, sizeof(gate_script_lua_session_t));
        ret = gate_script_lua_reset(session);
    } while (0);
    return ret;
}
gate_result_t gate_script_lua_uninit(gate_script_lua_session_t* session)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate = NULL;

    do
    {
        lstate = (lua_State*)session->state;
        if (lstate != NULL)
        {
            lua_close(lstate);
            session->state = NULL;
        }
        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}
gate_result_t gate_script_lua_reset(gate_script_lua_session_t* session)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate = NULL;

    do
    {
        lstate = luaL_newstate();
        if (NULL == lstate)
        {
            ret = GATE_RESULT_OUTOFRESOURCES;
            break;
        }

        luaopen_base(lstate);
        luaopen_table(lstate);
        luaopen_string(lstate);
        luaopen_math(lstate);
        luaopen_coroutine(lstate);
        luaopen_utf8(lstate);

        if (session->state != NULL)
        {
            lua_close((lua_State*)session->state);
        }
        lua_pushlightuserdata(lstate, session);
        lua_setglobal(lstate, GATE_SCRIPT_LUA_SESSION_POINTER_NAME);
        session->state = lstate;
        lstate = NULL;
        ret = GATE_RESULT_OK;
    } while (0);

    if (lstate != NULL)
    {
        lua_close(lstate);
    }

    return ret;
}

static gate_script_lua_session_t* gate_script_lua_get_session(lua_State* L)
{
    lua_getglobal(L, GATE_SCRIPT_LUA_SESSION_POINTER_NAME);
    return (gate_script_lua_session_t*)lua_touserdata(L, -1);
}


struct gate_script_lua_code_block
{
    char const* data;
    gate_size_t	size;
};

static char const* gate_script_lua_code_reader(lua_State* L, void* data, size_t* size)
{
    char const* ret = NULL;
    struct gate_script_lua_code_block* block = (struct gate_script_lua_code_block*)data;

    (void)L;
    *size = 0;
    if (block->size > 0)
    {
        ret = block->data;
        *size = block->size;

        block->data += block->size;
        block->size = 0;
    }
    return ret;
}

static gate_result_t gate_script_lua_map_error(int lua_result_code)
{
    switch (lua_result_code)
    {
    case LUA_OK:		return GATE_RESULT_OK;
    case LUA_YIELD:		return GATE_RESULT_OK_PARTIAL;
    case LUA_ERRRUN:	return GATE_RESULT_EXECUTIONFAILED;
    case LUA_ERRSYNTAX:	return GATE_RESULT_INVALIDDATA;
    case LUA_ERRMEM:	return GATE_RESULT_OUTOFMEMORY;
    case LUA_ERRERR:	return GATE_RESULT_CRITICALERROR;
    default:			return GATE_RESULT_FAILED;
    }
}

static gate_result_t gate_script_lua_load_impl(lua_State* lstate, gate_string_t const* code, gate_bool_t print_error)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    int result;
    struct gate_script_lua_code_block block;

    (void)print_error;
    do
    {
        block.data = gate_string_ptr(code, 0);
        block.size = gate_string_length(code);
        result = lua_load(lstate, &gate_script_lua_code_reader, &block, "gate_lua_code", NULL);
        ret = gate_script_lua_map_error(result);
        GATE_BREAK_IF_FAILED(ret);

        result = lua_pcall(lstate, 0, 0, 0);
        ret = gate_script_lua_map_error(result);
        GATE_BREAK_IF_FAILED(ret);
    } while (0);

    return ret;

}

gate_result_t gate_script_lua_load(gate_script_lua_session_t* session, gate_string_t const* code)
{
    return gate_script_lua_load_impl((lua_State*)session->state, code, false);
}


static gate_result_t gate_script_lua_push_value(lua_State* L, gate_value_t const* val)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_type_id_t value_type = gate_value_type(val);
    void const* value_ptr = gate_value_get_ptr(val);

    char buffer[8192];
    gate_size_t buffer_used = 0;
    gate_datetime_t datetime = GATE_INIT_EMPTY;

    do
    {
        if (!value_ptr)
        {
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }

        ret = GATE_RESULT_OK;

        switch (value_type)
        {
        case GATE_TYPE_BOOL:	lua_pushboolean(L, *((gate_bool_t const*)value_ptr) ? 1 : 0); break;
        case GATE_TYPE_I8:		lua_pushinteger(L, (lua_Integer) * ((gate_int8_t const*)value_ptr)); break;
        case GATE_TYPE_UI8:		lua_pushinteger(L, (lua_Integer) * ((gate_uint8_t const*)value_ptr)); break;
        case GATE_TYPE_I16:		lua_pushinteger(L, (lua_Integer) * ((gate_int16_t const*)value_ptr)); break;
        case GATE_TYPE_UI16:	lua_pushinteger(L, (lua_Integer) * ((gate_uint16_t const*)value_ptr)); break;
        case GATE_TYPE_I32:		lua_pushinteger(L, (lua_Integer) * ((gate_int32_t const*)value_ptr)); break;
        case GATE_TYPE_UI32:	lua_pushinteger(L, (lua_Integer) * ((gate_uint32_t const*)value_ptr)); break;
        case GATE_TYPE_I64:		lua_pushinteger(L, (lua_Integer) * ((gate_int64_t const*)value_ptr)); break;
        case GATE_TYPE_UI64:	lua_pushinteger(L, (lua_Integer) * ((gate_uint64_t const*)value_ptr)); break;
        case GATE_TYPE_ADDRESS:	lua_pushinteger(L, (lua_Integer) * ((gate_uintptr_t const*)value_ptr)); break;
        case GATE_TYPE_R32:		lua_pushnumber(L, (lua_Number) * ((gate_real32_t const*)value_ptr)); break;
        case GATE_TYPE_R64:		lua_pushnumber(L, (lua_Number) * ((gate_real64_t const*)value_ptr)); break;

        case GATE_TYPE_CSTR:	lua_pushlstring(L, (char const*)value_ptr, gate_str_length((char const*)value_ptr)); break;
        case GATE_TYPE_WSTR:
            buffer_used = gate_str_utf16_2_utf8((gate_char16_t const*)value_ptr,
                gate_str16_length((gate_char16_t const*)value_ptr),
                buffer, sizeof(buffer));
            lua_pushlstring(L, buffer, buffer_used);
            break;
        case GATE_TYPE_GUID:
            gate_guid_to_string((gate_guid_t const*)value_ptr, buffer);
            lua_pushlstring(L, buffer, 36);
            break;
        case GATE_TYPE_DATE:
            datetime.date = *((gate_date_t const*)value_ptr);
            buffer_used = sizeof(buffer);
            gate_date_to_string(&datetime, 0, "{YYYY}-{MM}-{DD}", buffer, &buffer_used);
            lua_pushlstring(L, buffer, buffer_used);
            break;
        case GATE_TYPE_DAYTIME:
            datetime.time = *((gate_daytime_t const*)value_ptr);
            buffer_used = sizeof(buffer);
            gate_date_to_string(&datetime, 0, "{hh}:{mm}:{ss}.{SSS}", buffer, &buffer_used);
            lua_pushlstring(L, buffer, buffer_used);
            break;
        case GATE_TYPE_DATETIME:
            buffer_used = sizeof(buffer);
            gate_date_to_string((gate_datetime_t const*)value_ptr, 0, NULL, buffer, &buffer_used);
            lua_pushlstring(L, buffer, buffer_used);
            break;
        case GATE_TYPE_TIME:
            gate_time_to_datetime((gate_time_t const*)value_ptr, &datetime);
            buffer_used = sizeof(buffer);
            gate_date_to_string((gate_datetime_t const*)value_ptr, 0, NULL, buffer, &buffer_used);
            lua_pushlstring(L, buffer, buffer_used);
            break;
        case GATE_TYPE_STRING:
            lua_pushlstring(L, gate_string_ptr((gate_string_t const*)value_ptr, 0),
                gate_string_length((gate_string_t const*)value_ptr));
            break;


        default:
            ret = GATE_RESULT_NOTSUPPORTED;
            break;
        }


    } while (0);

    return ret;
}


static gate_result_t gate_script_lua_get_value(lua_State* L, int index, gate_value_t* value)
{
    int ltype = lua_type(L, index);

    gate_value_t* ret_value = NULL;
    gate_bool_t bool_val = false;
    gate_real64_t real_val = 0.0;
    gate_string_t str_val = GATE_STRING_INIT_EMPTY;
    size_t str_len = 0;
    gate_cstr_t cstr = NULL;


    switch (ltype)
    {
    case LUA_TNIL:
    {
        ret_value = gate_value_create(GATE_TYPE_EMPTY, NULL, value);
        break;
    }
    case LUA_TBOOLEAN:
    {
        bool_val = (lua_toboolean(L, index) == 0) ? false : true;
        ret_value = gate_value_create(GATE_TYPE_BOOL, &bool_val, value);
        break;
    }
    case LUA_TNUMBER:
    {
        real_val = (gate_real64_t)lua_tonumber(L, index);
        ret_value = gate_value_create(GATE_TYPE_R64, &real_val, value);
        break;
    }
    case LUA_TSTRING:
    {
        cstr = lua_tolstring(L, index, &str_len);
        if (gate_string_create(&str_val, cstr, str_len))
        {
            ret_value = gate_value_create(GATE_TYPE_STRING, &str_val, value);
        }
        break;
    }
    case LUA_TFUNCTION:
    case LUA_TTABLE:
    default:
    {
        break;
    }
    }

    gate_string_release(&str_val);
    return ret_value == NULL ? GATE_RESULT_NOTSUPPORTED : GATE_RESULT_OK;
}

gate_result_t gate_script_lua_invoke(gate_script_lua_session_t* session, gate_string_t const* func_name,
    gate_value_t* args, gate_size_t arg_count, gate_value_t* ret_val)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate;
    int result;
    char buffer[4096];
    int index;

    do
    {
        lstate = (lua_State*)session->state;
        gate_string_to_buffer(func_name, buffer, sizeof(buffer));

        lua_checkstack(lstate, (int)(arg_count + 2));
        result = lua_getglobal(lstate, buffer);
        ret = gate_script_lua_map_error(result);
        GATE_BREAK_IF_FAILED(ret);

        for (index = 0; index != arg_count; ++index)
        {
            ret = gate_script_lua_push_value(lstate, &args[index]);
            if (GATE_FAILED(ret))
            {
                lua_pop(lstate, index + 1);
                break;
            }
        }
        GATE_BREAK_IF_FAILED(ret);

        result = lua_pcall(lstate, (int)arg_count, 1, 0);
        ret = gate_script_lua_map_error(result);
        GATE_BREAK_IF_FAILED(ret);

        ret = gate_script_lua_get_value(lstate, -1, ret_val);
        lua_pop(lstate, 1);

    } while (0);

    return ret;
}
gate_result_t gate_script_lua_set_var(gate_script_lua_session_t* session,
    gate_string_t const* name, gate_value_t const* value)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate;
    char buffer[4096];

    do
    {
        gate_string_to_buffer(name, buffer, sizeof(buffer));
        lstate = (lua_State*)session->state;
        ret = gate_script_lua_push_value(lstate, value);
        lua_setglobal(lstate, buffer);
    } while (0);
    return ret;
}
gate_result_t gate_script_lua_get_var(gate_script_lua_session_t* session,
    gate_string_t const* name, gate_value_t* value)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate;
    char buffer[4096];

    do
    {
        gate_string_to_buffer(name, buffer, sizeof(buffer));
        lstate = (lua_State*)session->state;
        lua_getglobal(lstate, buffer);

        ret = gate_script_lua_get_value(lstate, -1, value);
        GATE_BREAK_IF_FAILED(ret);

        lua_pop(lstate, 1);
        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}

gate_result_t gate_script_lua_cfunc_add(
    gate_script_lua_session_t* session,
    gate_string_t const* func_name,
    int(*lua_cfunc)(void* lstate),
    void* userparam)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate;
    gate_cstrbuffer_t name_buffer = GATE_INIT_EMPTY;

    do
    {
        if (!session || !func_name || !lua_cfunc)
        {
            ret = GATE_RESULT_INVALIDARG;
            break;
        }

        if (NULL == gate_cstrbuffer_create_string(&name_buffer, func_name, false))
        {
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        lstate = (lua_State*)session->state;

        if (userparam)
        {
            /* add userparam to stack */
            lua_pushlightuserdata(lstate, userparam);
            lua_pushcclosure(lstate, (lua_CFunction)lua_cfunc, 1);
        }
        else
        {
            /* add function dispatcher with one upvalue (cfunc-def) */
            lua_pushcclosure(lstate, (lua_CFunction)lua_cfunc, 0);
        }

        /* set global name of function */
        lua_setglobal(lstate, gate_cstrbuffer_get(&name_buffer));

        ret = GATE_RESULT_OK;
    } while (0);

    gate_cstrbuffer_destroy(&name_buffer);

    return ret;
}

gate_size_t gate_script_lua_cfunc_get_arg_count(void* lstate)
{
    lua_State* L = (lua_State*)lstate;
    return (gate_size_t)lua_gettop(L);
}

static void lua_stack_get_bool(lua_State* state, int index, gate_bool_t* ptr)
{
    *ptr = lua_toboolean(state, index) == 0 ? false : true;
}

static void lua_stack_get_int(lua_State* state, int index, gate_int32_t* ptr)
{
    *ptr = (gate_int32_t)lua_tointeger(state, index);
}

static void lua_stack_get_number(lua_State* state, int index, gate_real64_t* ptr)
{
    *ptr = (gate_real64_t)lua_tonumber(state, index);
}

static void lua_stack_get_string(lua_State* state, int index, gate_string_t* ptr)
{
    size_t len = 0;
    char const* str = lua_tolstring(state, index, &len);
    gate_string_create(ptr, str, len);
}

static gate_result_t lua_stack_item_to_prop(lua_State* L, int index, gate_property_t* prop)
{
    gate_result_t result;
    gate_property_t* ret = NULL;
    if (lua_isboolean(L, index))
    {
        gate_bool_t v = false;
        lua_stack_get_bool(L, index, &v);
        ret = gate_property_create_bool(prop, v);
    }
    else if (lua_isinteger(L, index))
    {
        gate_int32_t v = 0;
        lua_stack_get_int(L, index, &v);
        ret = gate_property_create_int(prop, (gate_int64_t)v);
    }
    else if (lua_isnumber(L, index))
    {
        gate_real64_t v = 0.0;
        lua_stack_get_number(L, index, &v);
        ret = gate_property_create_real(prop, (gate_real64_t)v);
    }
    else if (lua_isstring(L, index))
    {
        gate_string_t gstr = GATE_STRING_INIT_EMPTY;
        lua_stack_get_string(L, index, &gstr);
        ret = gate_property_create_string(prop, &gstr);
        gate_string_release(&gstr);
    }
    else if (lua_istable(L, index))
    {
        gate_bool_t prop_init = false;
        /* empty-pre-first-key to search next: */
        lua_pushnil(L);

        /* search next key from stack and push key-vakue pair */
        while (lua_next(L, index) != 0)
        {
            gate_property_t item = GATE_INIT_EMPTY;
            result = lua_stack_item_to_prop(L, -1, &item);
            if (GATE_SUCCEEDED(result))
            {
                if (lua_isnumber(L, -2))
                {
                    lua_Integer tbl_ndx = lua_tointeger(L, -2);
                    if (!prop_init)
                    {
                        /* first key is a number -> table is an array */
                        ret = gate_property_create_array(prop, NULL, 0);
                        prop_init = true;
                    }
                    gate_property_array_add(prop, &item);
                }
                else if (lua_isstring(L, -2))
                {
                    size_t key_len;
                    char const* key_value;
                    gate_string_t key_str = GATE_STRING_INIT_EMPTY;
                    if (!prop_init)
                    {
                        /* first key is a string -> table is a property object */
                        ret = gate_property_create_object(prop);
                        prop_init = true;
                    }
                    key_value = lua_tolstring(L, -2, &key_len);
                    gate_string_create(&key_str, key_value, key_len);
                    gate_property_member_add(prop, &key_str, &item);
                    gate_string_release(&key_str);
                }

                gate_property_destroy(&item);
            }
            lua_pop(L, 1);
        }
    }
    if (ret == NULL)
    {
        return GATE_RESULT_FAILED;
    }
    return GATE_RESULT_OK;
}

gate_result_t gate_script_lua_cfunc_get_stack_item(void* lstate, int arg_index, gate_property_t* prop)
{
    lua_State* const L = (lua_State*)lstate;
    return lua_stack_item_to_prop(L, arg_index, prop);
}

gate_result_t gate_script_lua_cfunc_get_arg(void* lstate, gate_size_t arg_index, gate_property_t* prop)
{
    lua_State* const L = (lua_State*)lstate;
    int const lua_func_arg_count = lua_gettop(L);
    int const lua_func_arg_index = (int)arg_index + 1;

    if (lua_func_arg_index > lua_func_arg_count)
    {
        return GATE_RESULT_OUTOFBOUNDS;
    }

    return lua_stack_item_to_prop(L, lua_func_arg_index, prop);
}


static void lua_stack_push_property(lua_State* L, gate_property_t const* prop)
{
    switch (gate_property_get_type(prop))
    {
    case GATE_PROPERTY_TYPE_EMPTY:
    {
        lua_pushnil(L);
        return;
    }
    case GATE_PROPERTY_TYPE_BOOL:
    {
        gate_bool_t b = false;
        gate_property_get_bool(prop, &b);
        lua_pushboolean(L, b ? 1 : 0);
        return;
    }
    case GATE_PROPERTY_TYPE_INT:
    {
        gate_int64_t v = 0;
        gate_property_get_int(prop, &v);
        if ((v < -2147483648LL) || (v > 2147483647LL))
        {
            lua_pushnumber(L, (lua_Number)v);
        }
        else
        {
            lua_pushinteger(L, (lua_Integer)v);
        }
        return;
    }
    case GATE_PROPERTY_TYPE_REAL:
    {
        gate_real64_t v = 0.0;
        gate_property_get_real(prop, &v);
        lua_pushnumber(L, (lua_Number)v);
        return;
    }
    case GATE_PROPERTY_TYPE_STRING:
    {
        gate_string_t str = GATE_STRING_INIT_EMPTY;
        gate_property_get_string(prop, &str);
        lua_pushlstring(L, gate_string_ptr(&str, 0), gate_string_length(&str));
        gate_string_release(&str);
        return;
    }
    case GATE_PROPERTY_TYPE_ARRAY:
    {
        gate_size_t ndx;
        const gate_size_t length = gate_property_array_length(prop);
        lua_createtable(L, (int)length, 0);
        for (ndx = 0; ndx < (int)length; ++ndx)
        {
            gate_property_t const* item = gate_property_array_get(prop, ndx);
            if (item)
            {
                lua_stack_push_property(L, item);
            }
            else
            {
                lua_pushnil(L);
            }
            lua_rawseti(L, -2, (lua_Integer)(ndx + 1));
        }
        return;
    }
    case GATE_PROPERTY_TYPE_OBJECT:
    {
        gate_size_t ndx, length;
        gate_array_t names = GATE_INIT_EMPTY;
        gate_property_member_names(prop, &names);
        length = gate_array_length(&names);

        lua_newtable(L);
        for (ndx = 0; ndx != length; ++ndx)
        {
            gate_string_t const* name = (gate_string_t const*)gate_array_get(&names, ndx);
            gate_property_t const* item;
            if (!name)
            {
                continue;
            }
            item = gate_property_member_get(prop, name);
            if (!item)
            {
                continue;
            }
            lua_pushlstring(L, gate_string_ptr(name, 0), gate_string_length(name));
            lua_stack_push_property(L, item);
            lua_settable(L, -3);
        }
        return;
    }
    }
}

gate_result_t gate_script_lua_cfunc_push_stack_item(void* lstate, gate_property_t const* prop)
{
    lua_State* const L = (lua_State*)lstate;
    if (!L || !prop)
    {
        return GATE_RESULT_INVALIDARG;
    }
    lua_stack_push_property(L, prop);
    return GATE_RESULT_OK;
}

gate_size_t gate_script_lua_cfunc_def_param_count(gate_script_lua_cfunc_def_t const* cfunc_def)
{
    unsigned ndx;
    for (ndx = 0; ndx != GATE_SCRIPTING_LUA_MAX_FUNC_PARAMS; ++ndx)
    {
        if (cfunc_def->params[ndx] == GATE_TYPE_VOID)
        {
            return ndx;
        }
    }
    return GATE_SCRIPTING_LUA_MAX_FUNC_PARAMS;
}

#define CREATE_INT_VALUE(native_type)	\
	const native_type v = (native_type)lua_tointeger(L, lua_param_index); \
	gate_value_create(required_type, &v, ptr_val)

#define CREATE_NUM_VALUE(native_type)	\
	const native_type v = (native_type)lua_tonumber(L, lua_param_index); \
	gate_value_create(required_type, &v, ptr_val)


static gate_result_t load_lua_params(lua_State* L, gate_type_id_t required_type, int lua_param_index, gate_value_t* ptr_val)
{
    gate_result_t ret = GATE_RESULT_OK;

    switch (required_type)
    {
    case GATE_TYPE_BOOL:
    {
        const gate_bool_t v = lua_toboolean(L, lua_param_index);
        gate_value_create(GATE_TYPE_BOOL, &v, ptr_val);
        break;
    }
    case GATE_TYPE_I8: { CREATE_INT_VALUE(gate_int8_t); break; }
    case GATE_TYPE_UI8: { CREATE_INT_VALUE(gate_uint8_t); break; }
    case GATE_TYPE_I16: { CREATE_INT_VALUE(gate_int16_t); break; }
    case GATE_TYPE_UI16: { CREATE_INT_VALUE(gate_uint16_t); break; }
    case GATE_TYPE_I32: { CREATE_INT_VALUE(gate_int32_t); break; }
    case GATE_TYPE_UI32: { CREATE_INT_VALUE(gate_uint32_t); break; }
    case GATE_TYPE_I64: { CREATE_NUM_VALUE(gate_int64_t); break; }
    case GATE_TYPE_UI64: { CREATE_NUM_VALUE(gate_uint64_t); break; }
    case GATE_TYPE_R32: { CREATE_NUM_VALUE(gate_real32_t); break; }
    case GATE_TYPE_R64: { CREATE_NUM_VALUE(gate_real64_t); break; }
    case GATE_TYPE_ADDRESS:
    case GATE_TYPE_DATAPTR:
    case GATE_TYPE_FUNCPTR:
    {
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }
    case GATE_TYPE_CSTR:
    {
        size_t l;
        gate_cstr_t s = luaL_tolstring(L, lua_param_index, &l);
        gate_value_create(GATE_TYPE_CSTR, &s, ptr_val);
        break;
    }
    case GATE_TYPE_WSTR:
    case GATE_TYPE_GUID:
    {
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }
    case GATE_TYPE_DATE:
    {
        gate_time_t tm = GATE_INIT_EMPTY;
        gate_datetime_t dt = GATE_INIT_EMPTY;
        const gate_int64_t unix_seconds = (gate_int64_t)lua_tointeger(L, lua_param_index);
        gate_time_from_unix(unix_seconds, &tm.timestamp);
        gate_time_to_datetime(&tm, &dt);
        gate_value_create(GATE_TYPE_DATE, &dt.date, ptr_val);
        break;
    }
    case GATE_TYPE_DAYTIME:
    {
        gate_time_t tm = GATE_INIT_EMPTY;
        gate_datetime_t dt = GATE_INIT_EMPTY;
        const gate_int64_t unix_seconds = (gate_int64_t)lua_tointeger(L, lua_param_index);
        gate_time_from_unix(unix_seconds, &tm.timestamp);
        gate_time_to_datetime(&tm, &dt);
        gate_value_create(GATE_TYPE_DAYTIME, &dt.time, ptr_val);
        break;
    }
    case GATE_TYPE_DATETIME:
    {
        gate_time_t tm = GATE_INIT_EMPTY;
        gate_datetime_t dt = GATE_INIT_EMPTY;
        const gate_int64_t unix_seconds = (gate_int64_t)lua_tointeger(L, lua_param_index);
        gate_time_from_unix(unix_seconds, &tm.timestamp);
        gate_time_to_datetime(&tm, &dt);
        gate_value_create(GATE_TYPE_DATETIME, &dt, ptr_val);
        break;
    }
    case GATE_TYPE_TIME:
    {
        gate_time_t tm = GATE_INIT_EMPTY;
        const gate_int64_t unix_seconds = (gate_int64_t)lua_tointeger(L, lua_param_index);
        gate_time_from_unix(unix_seconds, &tm.timestamp);
        gate_value_create(GATE_TYPE_TIME, &tm, ptr_val);
        break;
    }
    case GATE_TYPE_STRING:
    {
        gate_string_t str = GATE_STRING_INIT_EMPTY;
        size_t l;
        gate_cstr_t s = luaL_tolstring(L, lua_param_index, &l);
        gate_string_create(&str, s, l);
        gate_value_create(GATE_TYPE_STRING, &str, ptr_val);
        gate_string_release(&str);
        break;
    }
    case GATE_TYPE_BLOB:
    {
        gate_blob_t blob = GATE_INIT_EMPTY;
        size_t l;
        gate_cstr_t s = luaL_tolstring(L, lua_param_index, &l);
        gate_blob_create(&blob, s, l);
        gate_value_create(GATE_TYPE_BLOB, &blob, ptr_val);
        gate_blob_release(&blob);
        break;
    }
    case GATE_TYPE_STRUCT:
    case GATE_TYPE_OBJECT:
    case GATE_TYPE_PROPERTY:

    case GATE_TYPE_ARRAY:
    case GATE_TYPE_ARRAYLIST:
    case GATE_TYPE_ARRAYLIST_BOOL:
    case GATE_TYPE_ARRAYLIST_I8:
    case GATE_TYPE_ARRAYLIST_UI8:
    case GATE_TYPE_ARRAYLIST_I16:
    case GATE_TYPE_ARRAYLIST_UI16:
    case GATE_TYPE_ARRAYLIST_I32:
    case GATE_TYPE_ARRAYLIST_UI32:
    case GATE_TYPE_ARRAYLIST_I64:
    case GATE_TYPE_ARRAYLIST_UI64:
    case GATE_TYPE_ARRAYLIST_R32:
    case GATE_TYPE_ARRAYLIST_R64:
    case GATE_TYPE_ARRAYLIST_ADDRESS:

    case GATE_TYPE_ARRAYLIST_DATAPTR:
    case GATE_TYPE_ARRAYLIST_FUNCPTR:
    case GATE_TYPE_ARRAYLIST_CSTR:
    case GATE_TYPE_ARRAYLIST_WSTR:
    case GATE_TYPE_ARRAYLIST_GUID:
    case GATE_TYPE_ARRAYLIST_DATE:
    case GATE_TYPE_ARRAYLIST_DAYTIME:
    case GATE_TYPE_ARRAYLIST_DATETIME:
    case GATE_TYPE_ARRAYLIST_TIME:

    case GATE_TYPE_ARRAYLIST_STRING:
    case GATE_TYPE_ARRAYLIST_ARRAY:
    case GATE_TYPE_ARRAYLIST_BLOB:

    case GATE_TYPE_ARRAYLIST_STRUCT:
    case GATE_TYPE_ARRAYLIST_OBJECT:
    case GATE_TYPE_ARRAYLIST_PROPERTY:
    default:
    {
        /*TODO*/
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }

    }

    return ret;
}

static gate_result_t convert_value_to_func_arg(gate_value_t const* ptr_val, gate_function_argument_t* ptr_arg)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_type_id_t const gt = gate_value_type(ptr_val);
    switch (gt)
    {
    case GATE_TYPE_BOOL:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_UCHAR;
        ptr_arg->arg_value.u_chr = ptr_val->content.bool_value;
        break;
    case GATE_TYPE_I8:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_SCHAR;
        ptr_arg->arg_value.s_chr = ptr_val->content.i8_value;
        break;
    case GATE_TYPE_UI8:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_UCHAR;
        ptr_arg->arg_value.u_chr = ptr_val->content.ui8_value;
        break;
    case GATE_TYPE_I16:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_SSHORT;
        ptr_arg->arg_value.s_short = ptr_val->content.i16_value;
        break;
    case GATE_TYPE_UI16:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_USHORT;
        ptr_arg->arg_value.u_short = ptr_val->content.ui16_value;
        break;
    case GATE_TYPE_I32:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_SLONG;
        ptr_arg->arg_value.s_long = ptr_val->content.i32_value;
        break;
    case GATE_TYPE_UI32:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_ULONG;
        ptr_arg->arg_value.u_long = ptr_val->content.ui32_value;
        break;
    case GATE_TYPE_I64:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_SLONGLONG;
        ptr_arg->arg_value.s_long_long = ptr_val->content.i64_value;
        break;
    case GATE_TYPE_UI64:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_ULONGLONG;
        ptr_arg->arg_value.u_long_long = ptr_val->content.ui64_value;
        break;
    case GATE_TYPE_R32:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_FLOAT;
        ptr_arg->arg_value.flt = ptr_val->content.r32_value;
        break;
    case GATE_TYPE_R64:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_DOUBLE;
        ptr_arg->arg_value.dbl = ptr_val->content.r64_value;
        break;
        /* pointer types: */
    case GATE_TYPE_ADDRESS:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)ptr_val->content.address_value;
        break;
    case GATE_TYPE_DATAPTR:
    case GATE_TYPE_FUNCPTR:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = ptr_val->content.ptr_value;
        break;
    case GATE_TYPE_CSTR:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)ptr_val->content.cstring_value;
        break;
    case GATE_TYPE_WSTR:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)ptr_val->content.wstring_value;
        break;
    case GATE_TYPE_GUID:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.guid_value;
        break;
    case GATE_TYPE_DATE:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.date_value;
        break;
    case GATE_TYPE_DAYTIME:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.daytime_value;
        break;
    case GATE_TYPE_DATETIME:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.datetime_value;
        break;
    case GATE_TYPE_TIME:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.time_value;
        break;
    case GATE_TYPE_STRING:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.string_value;
        break;
    case GATE_TYPE_BLOB:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.blob_value;
        break;
    case GATE_TYPE_ARRAY:
        ptr_arg->arg_type = GATE_FUNCTION_ARG_POINTER;
        ptr_arg->arg_value.ptr = (void*)&ptr_val->content.array_value;
        break;
    default:
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }
    return ret;
}

static int gate_lua_cfunc_dispatcher(lua_State* L)
{
    static char const* const error_msg_fmt = "LUA C-function dispatcher error: #%d %s";
    int const lua_func_arg_count = lua_gettop(L);
    gate_script_lua_cfunc_def_t const* const cfunc_def =
        (gate_script_lua_cfunc_def_t const*)lua_touserdata(L, lua_upvalueindex(1));
    gate_size_t cfunc_count = 0;
    gate_value_t value_store[GATE_SCRIPTING_LUA_MAX_FUNC_PARAMS] = GATE_INIT_EMPTY;
    gate_function_argument_t cfunc_args[GATE_SCRIPTING_LUA_MAX_FUNC_PARAMS] = GATE_INIT_EMPTY;
    gate_function_argument_t ret_val = GATE_INIT_EMPTY;
    int ret = 0;
    int ndx;
    gate_result_t result;

    do
    {
        if (NULL == cfunc_def)
        {
            ret = luaL_error(L, error_msg_fmt, 1, "internal lua_cfunc_def parameter is missing");
            break;
        }

        cfunc_count = gate_script_lua_cfunc_def_param_count(cfunc_def);

        if (lua_func_arg_count < (int)cfunc_count)
        {
            ret = luaL_error(L, error_msg_fmt, (int)cfunc_count, " required parameters not available");
            break;
        }

        if (lua_func_arg_count > GATE_SCRIPTING_LUA_MAX_FUNC_PARAMS)
        {
            ret = luaL_error(L, error_msg_fmt, (int)lua_func_arg_count, " too many parameters");
            break;
        }

        /* store lua parameters as gate_value objects */
        for (ndx = 0; ndx < (int)cfunc_count; ++ndx)
        {
            result = load_lua_params(L, cfunc_def->params[ndx], ndx + 1, &value_store[ndx]);
        }

        /* create generic function args from gate_value objects */
        for (ndx = 0; ndx < (int)cfunc_count; ++ndx)
        {
            result = convert_value_to_func_arg(&value_store[ndx], &cfunc_args[ndx]);
        }

        /* call native gate-function pointer */
        result = gate_function_invoke_generic(cfunc_def->func_ptr, 0, cfunc_args, cfunc_count, &ret_val);


    } while (0);

    for (ndx = 0; ndx < (int)cfunc_count; ++ndx)
    {
        gate_value_release(&value_store[ndx]);
    }

    return ret;
}

gate_result_t gate_script_lua_add_function(
    gate_script_lua_session_t* session,
    gate_string_t const* func_name,
    gate_script_lua_cfunc_def_t const* func_def)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    lua_State* lstate;
    void* const cfunc_def_param = (void*)func_def;
    char name[128];

    do
    {
        gate_string_to_buffer(func_name, name, sizeof(name));

        lstate = (lua_State*)session->state;

        /* push pointer to function definition as upvalue for function */
        lua_pushlightuserdata(lstate, cfunc_def_param);

        /* add function dispatcher with one upvalue (cfunc-def) */
        lua_pushcclosure(lstate, &gate_lua_cfunc_dispatcher, 1);

        /* set global name of function */
        lua_setglobal(lstate, name);

        ret = GATE_RESULT_OK;

    } while (0);

    return ret;
}


static int gate_lua_print(lua_State* L)
{
    int n = lua_gettop(L);	/* number of arguments */
    int i;
    for (i = 1; i <= n; i++)
    {
        size_t l;
        const char* s = luaL_tolstring(L, i, &l);  /* convert it to string */
        if (i > 1)
        {
            /* not the first element? */
            gate_lua_writestring(" ", 1, false);  /* add a tab before it */
        }
        gate_lua_writestring(s, l, false);  /* print it */
        lua_pop(L, 1);  /* pop result */
    }
    gate_lua_writestring(GATE_STR_NEWLINE, GATE_STR_NEWLINE_LENGTH, true);
    return 0;
}

static int gate_lua_printerr(lua_State* L)
{
    int n = lua_gettop(L);	/* number of arguments */
    int i;
    for (i = 1; i <= n; i++)
    {
        size_t l;
        const char* s = luaL_tolstring(L, i, &l);  /* convert it to string */
        if (i > 1)
        {
            /* not the first element? */
            gate_lua_writestring_err(" ", 1, false);  /* add a tab before it */
        }
        gate_lua_writestring_err(s, l, false);  /* print it */
        lua_pop(L, 1);  /* pop result */
    }
    gate_lua_writestring_err(GATE_STR_NEWLINE, GATE_STR_NEWLINE_LENGTH, true);
    return 0;
}

static int gate_lua_read(lua_State* L)
{
    int ret = 0;<--- Variable 'ret' is assigned a value that is never used.
    gate_string_t line = GATE_STRING_INIT_EMPTY;
    gate_console_t* const con = gate_console();

    gate_console_readln(con, &line);

    lua_pushlstring(L, gate_string_ptr(&line, 0), gate_string_length(&line));

    gate_string_release(&line);
    return 1;
}

static void add_console_feature(lua_State* lstate)
{
    lua_register(lstate, "print", &gate_lua_print);
    lua_register(lstate, "printerror", &gate_lua_printerr);
    lua_register(lstate, "read", &gate_lua_read);
}

static int gate_lua_fileopen(lua_State* lstate)
{
    gate_result_t ret = 0;
    gate_result_t result;
    gate_string_t str_path = GATE_STRING_INIT_EMPTY;
    gate_string_t str_flags = GATE_STRING_INIT_EMPTY;
    gate_enumint_t openflags = GATE_STREAM_OPEN_READ;
    gate_bool_t truncate = false;
    gate_size_t arg_count;
    gate_file_t f;

    do
    {
        arg_count = gate_script_lua_cfunc_get_arg_count(lstate);
        if (arg_count < 1)
        {
            luaL_error(lstate, "Missing arguments");
            break;
        }

        lua_stack_get_string(lstate, 1, &str_path);
        if (gate_string_is_empty(&str_path))
        {
            lua_pushnil(lstate);
            ret = 1;
            break;
        }

        if (arg_count >= 2)
        {
            lua_stack_get_string(lstate, 2, &str_flags);
        }
        if (gate_string_equals_str(&str_flags, "r") || gate_string_is_empty(&str_flags))
        {
            openflags = GATE_STREAM_OPEN_READ;
        }
        else if (gate_string_equals_str(&str_flags, "r+"))
        {
            openflags = GATE_STREAM_OPEN_READWRITE;
        }
        else if (gate_string_equals_str(&str_flags, "w"))
        {
            openflags = GATE_STREAM_OPEN_WRITE;
        }
        else if (gate_string_equals_str(&str_flags, "w+"))
        {
            openflags = GATE_STREAM_OPEN_READWRITE;
            truncate = true;
        }
        else if (gate_string_equals_str(&str_flags, "a"))
        {
            openflags = GATE_STREAM_OPEN_APPENDWRITE;
        }
        else if (gate_string_equals_str(&str_flags, "a+"))
        {
            openflags = GATE_STREAM_OPEN_APPENDREADWRITE;
        }
        else
        {
            /* unsupported open-type */
            lua_pushnil(lstate);
            ret = 1;
            break;
        }

        result = gate_file_open(&str_path, openflags, &f);
        if (GATE_FAILED(result))
        {
            /* error case */
            lua_pushnil(lstate);
            ret = 1;
            break;
        }

        if (truncate)
        {
            gate_file_truncate(f);
        }

        /* success case */
        lua_pushinteger(lstate, (lua_Integer)(gate_intptr_t)(void*)f);
        ret = 1;
    } while (0);

    gate_string_release(&str_flags);
    gate_string_release(&str_path);
    return ret;
}

static int gate_lua_fileclose(lua_State* lstate)
{
    gate_result_t ret = 0;
    gate_size_t arg_count;
    gate_int32_t file_handle;
    gate_file_t f;

    do
    {
        arg_count = gate_script_lua_cfunc_get_arg_count(lstate);
        if (arg_count < 1)
        {
            luaL_error(lstate, "Missing arguments");
            break;
        }

        lua_stack_get_int(lstate, 1, &file_handle);
        f = (gate_file_t)(gate_intptr_t)file_handle;

        gate_file_close(f);
        /* success case */
    } while (0);

    return ret;
}

static int gate_lua_fileread(lua_State* lstate)
{
    gate_result_t ret = 0;
    gate_result_t result;
    gate_size_t arg_count;
    gate_int32_t file_handle = 0;
    gate_int32_t read_len = 0;
    gate_file_t f;
    char buffer[GATE_MAX_COPYBUFFER_LENGTH];
    char* ptr_buffer = &buffer[0];
    gate_size_t buffer_len;
    gate_size_t buffer_used = 0;

    do
    {
        arg_count = gate_script_lua_cfunc_get_arg_count(lstate);
        if (arg_count < 2)
        {
            luaL_error(lstate, "Missing arguments");
            break;
        }

        lua_stack_get_int(lstate, 1, &file_handle);
        f = (gate_file_t)(gate_intptr_t)file_handle;

        lua_stack_get_int(lstate, 2, &read_len);

        if (read_len <= 0)
        {
            /* invalid read-length */
            lua_pushnil(lstate);
            ret = 1;
            break;
        }

        buffer_len = (gate_size_t)read_len;
        if (buffer_len > sizeof(buffer))
        {
            ptr_buffer = gate_mem_alloc(buffer_len);
            if (NULL == ptr_buffer)
            {
                luaL_error(lstate, "Out of memory");
                break;
            }
        }

        result = gate_file_read(f, ptr_buffer, buffer_len, &buffer_used);
        if (GATE_FAILED(result))
        {
            /* failed to read from file */
            lua_pushnil(lstate);
            ret = 1;
            break;
        }

        /* succes case, return buffer content as string */
        lua_pushlstring(lstate, ptr_buffer, buffer_used);
        ret = 1;
    } while (0);

    if (ptr_buffer && (ptr_buffer != &buffer[0]))
    {
        gate_mem_dealloc(ptr_buffer);
    }

    return ret;
}

static int gate_lua_filewrite(lua_State* lstate)
{
    gate_result_t ret = 0;
    gate_result_t result;
    gate_size_t arg_count;
    gate_int32_t file_handle = 0;
    gate_file_t f;
    gate_string_t buffer = GATE_STRING_INIT_EMPTY;
    gate_size_t written;

    do
    {
        arg_count = gate_script_lua_cfunc_get_arg_count(lstate);
        if (arg_count < 2)
        {
            luaL_error(lstate, "Missing arguments");
            break;
        }

        lua_stack_get_int(lstate, 1, &file_handle);
        f = (gate_file_t)(gate_intptr_t)file_handle;

        lua_stack_get_string(lstate, 2, &buffer);

        result = gate_file_write(f, gate_string_ptr(&buffer, 0), gate_string_length(&buffer), &written);
        if (GATE_FAILED(result))
        {
            /* failed to read from file */
            lua_pushnil(lstate);
            ret = 1;
            break;
        }

        /* success case, return amount of written bytes */
        lua_pushinteger(lstate, (lua_Integer)written);
        ret = 1;
    } while (0);

    gate_string_release(&buffer);
    return ret;
}



static void add_fileaccess_feature(lua_State* lstate)
{
    lua_register(lstate, "file_open", &gate_lua_fileopen);
    lua_register(lstate, "file_close", &gate_lua_fileclose);
    lua_register(lstate, "file_read", &gate_lua_fileread);
    lua_register(lstate, "file_write", &gate_lua_filewrite);
}

gate_result_t gate_script_lua_add_feature(gate_script_lua_session_t* session, gate_script_lua_feature_enum_t feature)
{
    lua_State* lstate = (lua_State*)session->state;

    switch (feature)
    {
    case gate_script_lua_feature_console:
        add_console_feature(lstate);
        return GATE_RESULT_OK;
    case gate_script_lua_feature_fileaccess:
        add_fileaccess_feature(lstate);
        return GATE_RESULT_OK;
    case gate_script_lua_feature_filesystem:
    case gate_script_lua_feature_process:
    default:
        return GATE_RESULT_NOTSUPPORTED;
    }
}

static int gate_script_lua_console_quit(lua_State* L)
{
    gate_script_lua_session_t* ptr_session = gate_script_lua_get_session(L);
    if (ptr_session)
    {
        ptr_session->cancel = true;
    }
    return 0;
}

gate_result_t gate_script_lua_console(gate_stream_t* console)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_script_lua_session_t session = GATE_INIT_EMPTY;
    gate_strbuilder_t builder = GATE_INIT_EMPTY;
    char buffer[4096];
    gate_size_t buffer_used;
    gate_bool_t command_completed;
    gate_string_t command = GATE_STRING_INIT_EMPTY;
    lua_State* lstate;
    gate_size_t pos;

    do
    {
        ret = gate_script_lua_init(&session);
        GATE_BREAK_IF_FAILED(ret);

        ret = gate_script_lua_add_feature(&session, gate_script_lua_feature_console);
        GATE_BREAK_IF_FAILED(ret);
        ret = gate_script_lua_add_feature(&session, gate_script_lua_feature_fileaccess);
        GATE_BREAK_IF_FAILED(ret);

        gate_strbuilder_create(&builder, 0);

        lstate = (lua_State*)session.state;
        session.cancel = false;

        lua_pushcfunction(lstate, &gate_script_lua_console_quit);
        lua_setglobal(lstate, "quit");

        while (!session.cancel)
        {
            buffer_used = 0;
            if (gate_strbuilder_length(&builder) == 0)
            {
                gate_stream_print_cstr(console, "[LUA] > ");
            }
            else
            {
                gate_stream_print_cstr(console, "      > ");

            }
            ret = gate_stream_read_line(console, buffer, sizeof(buffer), &buffer_used);
            GATE_BREAK_IF_FAILED(ret);

            pos = gate_str_find_last_not_of(buffer, buffer_used, " \r\n\t", 4);
            if (pos == GATE_STR_NPOS)
            {
                /* empty line */
            }
            else
            {
                buffer_used = pos + 1;
                if (gate_str_ends_with(buffer, buffer_used, "\\", 1))
                {
                    gate_strbuilder_append_text(&builder, buffer, buffer_used - 1);
                    gate_strbuilder_append_cstr(&builder, "\n");
                    command_completed = false;
                }
                else
                {
                    gate_strbuilder_append_text(&builder, buffer, buffer_used);
                    command_completed = true;
                }
                if (command_completed)
                {
                    if (gate_strbuilder_to_string(&builder, &command))
                    {
                        ret = gate_script_lua_load_impl(lstate, &command, true);
                        gate_strbuilder_release(&builder);
                        gate_strbuilder_create(&builder, 0);
                        if (GATE_SUCCEEDED(ret))
                        {
                            gate_stream_println_cstr(console, NULL);
                            gate_stream_println_cstr(console, "[LUA] : OK (^_^)");
                        }
                        else
                        {
                            gate_stream_println_cstr(console, NULL);
                            gate_stream_print_cstr(console, "[LUA] : ERROR ");
                            gate_stream_print_int(console, ret);
                            gate_stream_println_cstr(console, " (>_<)");
                            ret = GATE_RESULT_OK;
                        }
                    }
                    else
                    {
                        ret = GATE_RESULT_OUTOFMEMORY;
                    }
                    gate_string_release(&command);
                    GATE_BREAK_IF_FAILED(ret);
                }
            }

        }
        gate_script_lua_uninit(&session);

    } while (0);

    gate_strbuilder_release(&builder);

    return ret;
}

#endif /* GATE_SCRIPTING_LUA_USE_LUA */


#if defined(GATE_SCRIPTING_LUA_NO_IMPL)

gate_result_t gate_script_lua_init(gate_script_lua_session_t* session)
{
    GATE_UNUSED_ARG(session);
    return GATE_RESULT_NOTIMPLEMENTED;
}
gate_result_t gate_script_lua_uninit(gate_script_lua_session_t* session)
{
    GATE_UNUSED_ARG(session);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_reset(gate_script_lua_session_t* session)
{
    GATE_UNUSED_ARG(session);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_load(gate_script_lua_session_t* session, gate_string_t const* code)
{
    GATE_UNUSED_ARG(session);
    GATE_UNUSED_ARG(code);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_invoke(gate_script_lua_session_t* session,
    gate_string_t const* func_name,
    gate_value_t* args, gate_size_t arg_count,
    gate_value_t* ret_val)
{
    GATE_UNUSED_ARG(session);
    GATE_UNUSED_ARG(func_name);
    GATE_UNUSED_ARG(args);
    GATE_UNUSED_ARG(arg_count);
    GATE_UNUSED_ARG(ret_val);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_set_var(gate_script_lua_session_t* session,
    gate_string_t const* name, gate_value_t const* value)
{
    GATE_UNUSED_ARG(session);
    GATE_UNUSED_ARG(name);
    GATE_UNUSED_ARG(value);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_get_var(gate_script_lua_session_t* session,
    gate_string_t const* name, gate_value_t* value)
{
    GATE_UNUSED_ARG(session);
    GATE_UNUSED_ARG(name);
    GATE_UNUSED_ARG(value);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_add_feature(gate_script_lua_session_t* session, gate_script_lua_feature_enum_t feature)
{
    GATE_UNUSED_ARG(session);
    GATE_UNUSED_ARG(feature);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_script_lua_console(gate_stream_t* console)
{
    GATE_UNUSED_ARG(console);
    return GATE_RESULT_NOTIMPLEMENTED;
}

#endif /* GATE_SCRIPTING_LUA_NO_IMPL */