[Closed] Get variable name as string
Is there a way to get a variable a name as string ? For debugging purpose, I would like to automatically log something like that :
a = 2
format “%: %” (a.name) a
result :
a: 2
was it a long day today?
format "a: %
" a
why do you need variable name if you already know it and use it the format expression?
Because I could gather all variables in a loop and automatically log one entry per variable.
Yes, a long day… made shorter thanks to you ahah
For example :
myVariables = #(a, b, c)
For variable in myVariables do format "%: %
" (variable.name) (variable.value)
myVariables = #(#(a,"a"), #(b,"b"), #(c,"c"))
For variable in myVariables do format "%: %
" (variable[2]) (variable[1])
Yeah I thought about that… But it’s a little bit tedious to manage. How do you manage debugging ?
there is no any other way… only you knows the name of the variable. for the code it’s just a pointer to some piece of memory. global variables are registered. and you can find them by name. but you cannot do the same for local variables.
but you can check
Manual Stack Dump using the Stack() Function
and
Assert Functions
Stack() is good, I use it with from inside the debugger, but now I will work without the debugger because it’s way too slow. Assert is nice too.
Yup, print and format for me as well. Tried all the other methods and just Jett coming back to the old stand by.
A little bit less tedious :
fn trace variable =
(
assert (isKindOf variable string) message:"Debug.Trace() error: argument \"variable\" is not a string"
variable2 = undefined
try(variable2 = execute variable)catch()
format "% (%): %
" variable (classof variable2) variable2
)
myVariable = 2
trace "myVariable"
result:
myVariable (Integer): 2
as i see you want to do what the stack() does. all that you have to do is to output the trace result to the stream and parse it to get the info you need.
fn getTheValue val =
(
val
)
fn setTheValue val =
(
local theValue = val
getTheValue theValue
stack firstFrameOnly:on
)
setTheValue 7
This will only work for global variables, in which case you can replace the execute method with globalVars.get <variable_name_or_string>, and can also pass a name instead of a string.
for local variables you can use a function signature such as fn trace varName varValue