問題描述
在 Lua 中字符串化對象名稱 (Stringify object name in Lua)
In C I can do following:
<pre class="lang-c prettyprint-override">#define S1(x) #x
define S(x) S1(x)
define foo(x) bar(x, S(x))
int obj = 3;
foo(obj);
void bar(int v, const char * name)
{
// v == 3
// name == "obj"
}
</code></pre>
Can I do the same in Lua?
foo(barbar)
function foo(ob)
-- can I get "barbar"?
end
參考解法
方法 1:
I think you could do something similar only by using a preprocessor which does something similar to your C preprocessor code. (The plain C compiler can't do something like that, too.)
Or write it explicitly:
foo(barbar, "barbar")
方法 2:
You Could do this, but as DeadMG suggested: don't.
A way would be:
function foo(bar)
return bar
end
print(foo(bar)) -- prints nil
setmetatable(_G,{__index=function(t,k)
if k:match"^_" then -- Don't use on system variables
return nil
else
return k
end
end})
print(foo(bar)) -- prints bar
But I would strongly comment against it, as this can have nasty side effects.
方法 3:
No, I don't believe you can. The use of such is dubious to begin with.
(by John、Paŭlo Ebermann、jpjacobs、Puppy)
參考文件