[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Asking a variable its name
- From: Jose Torre-Bueno <jtorrebueno@...>
- Date: Mon, 18 Nov 2013 23:17:54 -0800
For debugging outputs I have occasionally wanted to ask a variable its name. I don't know a direct way to do this but I notice that the type of the values given to __index are a table and a string.
Following that lead I discovered that the following will give me a variable's name as a string
> tricktable = {__index = function (_,v) return v end}
> setmetatable(tricktable, tricktable)
> a = 1
> =a
1
> =tricktable.a
a
> =type(tricktable.a)
string
This seems a roundabout way to get something and of course I can't make this into a function because all functions are call by value. I came up with this experimenting with rawget which actually needs a string as its second parameter. I was led to this because strict.lua traps access to undeclared globals. That is nice but it prevents the construction:
local something = a_global_if_it_exists or the_default_value
because strict will trap a_global_if_it_exists instead of letting it be nil. I thought to make a function that would use strict's declared table to return the value of a variable if it existed or nil for those cases where I want explicitly to test if a variable is declared without causing an error but I don't see how this could be made into a function. A macro would work if Lua had macros.
Is there some much more straightforward way of doing this that I am missing?
Jose de la Torre-Bueno, Ph.D.
Empowered Energy Solutions Inc.
Intellectual Property & Technology Management
T (619) 977-0553
F (760) 295-7119
jtorrebueno@cox.net