Search code examples
kdb

Are side-effects sometimes necessary when using KDB?


Let's say I have a state variable s.

I've got a .z.ws hook that responds to websocket messages and runs:

.z.ws: {handleMsg x}

Do I have to declare s as global for handleMsg to be able to update s?

Ideally, what I'd want is something like:

s: handleMsg[s;x]

where handleMsg is a pure function (it doesn't affect any globals on the inside).

Should I declare s as global and then try to do this assignment inside the websocket callback?


Solution

  • You don't pre-declare variables as global in kdb, they're global if you make them global at any point (and if you reference them as a global).

    q)func:{x+1}
    
    /s is local and treated as such
    q){s:func[1]}[]
    2
    
    /it is not a global
    q)s
    's
    
    /this would make it global
    q){`s set func[1]}[]
    `s
    /or
    q){s::func[1]}[]
    
    /now it's global
    q)s
    2
    
    /but a local of the same name would take preference
    q){s:func[100];s}[]
    101
    q)s
    2
    
    /you can force-reference the global if required
    q){s:func[100];value `s}[]
    2
    

    So you're in complete control over what's global, what isn't, when you're referencing a local and when you're referencing a global.