Jean-Paul
Jean-Paul

Reputation: 21180

kdb+: use string as variable name

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

Upvotes: 5

Views: 2995

Answers (2)

SJT
SJT

Reputation: 1097

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

Upvotes: 1

terrylynch
terrylynch

Reputation: 13657

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

Upvotes: 7

Related Questions