Is there a way to get a variable name from a string?
For example, a program that asks the user to input a string for a variable name, then input a number, and finally set a variable with the name of the string passed in first to the number. Would this be possible?
Getting variable name from string?
Root / Programming Questions / [.]
a_load_of_barnaclesCreated:
Is there a way to get a variable name from a string? For example, a program that asks the user to input a string for a variable name, then input a number, and finally set a variable with the name of the string passed in first to the number. Would this be possible?Does the variable in question already exist? If so this is easy. If you want to dynamically allocate named variables, there's a multitude of ways to do this
I was thinking along the lines of inputting the variable name in the program, [declaring it after getting the name, and then assigning a value to it. Hope that's a bit clearer.
I was thinking along the lines of inputting the variable name in the program, [declaring it after getting the name, and then assigning a value to it. Hope that's a bit clearer.Ah hm, so the variable doesn't exist yet. Therein lies the problem, because there are a myriad ways of doing this depending on what you need. Do you absolutely NEED these to be "real" SB variables or do they just need to be named values?
I would like them to be real variables, but using some sort of named values would probably work. Any way of doing this with the real variables though?
Hmm, yeah I'll just try and find another way to do something like this. Thanks for the suggestions though.
Wow, that syntax is nowhere in the documentation. I wonder why they would leave something out that useful. I'll look into it a bit more, that is very helpful to know.
Garbage that doesn't work because LOL eval doesn't exist
DIM VARS$[0] 'Holds all variables we've created DIM NAME$ 'Name for next variable DIM VALUE 'The actual loop WHILE TRUE INPUT "Variable name:";NAME$ INPUT "Set value:";VALUE IF CONTAINS(VARS$,NAME$) THEN 'Variable already exists; use VAR to set. VAR(NAME$)=VALUE ELSE 'Variable doesn't exist, use EVAL to create EVAL("DIM "+NAME$+"="+STR$(VALUE)) ENDIF WEND 'Helper function to check if array contains item. DEF CONTAINS(ARRAY$,ITEM$) DIM I FOR I=0 TO LEN(ARRAY$)-1 IF ARRAY$[I]==ITEM$ THEN RETURN #TRUE NEXT RETURN #FALSE END
I believe you can declare variables across program slots using
VAR "(slot):(var name)", I may be wrong with the syntax there, but I know that it can be done.I imagine you could easily perform
VAR "0:"+INPUT$, but for what context you intend to use this in I do not know, because if you're using the declared variable in the same slot, the variable will have to already be in the code.