kdb+: use string as variable name
Asked Answered
F

2

5

How can I use a string as a variable name?

I want my variable name to be constructed during runtime, but how can I use it as a left argument and assign a value to it?

Example:

[`$"test"] : 1              / 'assign error
Fenton answered 26/4, 2015 at 11:18 Comment(0)
P
7

You could use "set" but it will create a global:

q){(`$"test") set 1;test}[]
1
q)test
1

or (as noted by user2393012 in the comments):

@[`.;`test;:;1]

If you want to avoid globals you could use some sort of namespace/dictionary/mapping:

q){d:()!();d[`$"test"]:1;d`test}[]
1
Potable answered 26/4, 2015 at 12:39 Comment(2)
Re the latter one - generic way is @ apply on namespace - very useful! @[`.;`test;:;1]Seraglio
This still creates a global though - just to be clearPotable
H
1

Provided .data exists, Amend At does the job:

q)@[`.data;`test;:;1]       / .data not defined
'type
  [0]  @[`.data;`test;:;1]
       ^
q).data.foo: 42             / defined .data
q)@[`.data;`$"test";:;1]
`.data
q).data.test
1
Halakah answered 1/2, 2023 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.