aboutsummaryrefslogtreecommitdiff
path: root/Northstar.Custom/mod/scripts/vscripts/sh_northstar_safe_io.gnut
blob: f7b31cc2139c56ec25d66357fd766eaa3b647e2a (plain)
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
globalize_all_functions

table< int, void functionref( string ) > pendingCallbacks
table< int, void functionref( table ) > pendingJSONCallbacks
table< int, void functionref() > failedCallbacks


void function NSLoadFile( string file, void functionref( string ) onSuccess, void functionref() onFailure = null )
{
    int handle = NS_InternalLoadFile( file )

    pendingCallbacks[handle] <- onSuccess
    if (onFailure != null)
        failedCallbacks[handle] <- onFailure
}

void function NSLoadJSONFile( string file, void functionref( table ) onSuccess, void functionref() onFailure = null )
{
    int handle = NS_InternalLoadFile( file )

    pendingJSONCallbacks[handle] <- onSuccess
    if (onFailure != null)
        failedCallbacks[handle] <- onFailure
}

void function NSHandleLoadResult( int handle, bool success, string result )
{
    bool hasFailedCallback = handle in failedCallbacks
    bool isJSONRequest = handle in pendingJSONCallbacks
    bool isValid = isJSONRequest || handle in pendingCallbacks

    if (!isValid)
        throw "Invalid IO callback handle"

    if (success)
    {
        if (isJSONRequest)
        {
            try
            {
                table result = DecodeJSON(result, true)
                pendingJSONCallbacks[handle](result)
            }
            catch (ex)
            {
                print(ex)
                // parsing failed, setting 'success' to false, since we
                // consider this a failure.
                success = false
            }
        }
        else
        {
            pendingCallbacks[handle](result)
        }
    }
    // don't use 'else', json might fail parsing and set 'success' to false.
    if (!success)
    {
        if (hasFailedCallback)
            failedCallbacks[handle]()
        else
        {
            if (isJSONRequest)
                pendingJSONCallbacks[handle]({})
            else
                pendingCallbacks[handle]("")
        }
    }

    if (isJSONRequest)
        delete pendingJSONCallbacks[handle]
    else
        delete pendingCallbacks[handle]

    if (hasFailedCallback)
        delete failedCallbacks[handle]
}

array<string> function NSGetAllFiles( string path = "" )
{
    return NS_InternalGetAllFiles(path)
}