在 Lua 中字符串化對象名稱 (Stringify object name in Lua)


問題描述

在 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 JohnPaŭlo EbermannjpjacobsPuppy)

參考文件

  1. Stringify object name in Lua (CC BY-SA 3.0/4.0)

#lua






相關問題

使用 MSXML2.ServerXMLHTTP 從網頁訪問數據會在 Lua 中返回截斷的數據 (Using MSXML2.ServerXMLHTTP to access data from a web page returns truncated data in Lua)

如何在 VS 2008 中包含 Lua 庫 (How can I include Lua library in VS 2008)

Corona 中的 iPad 式慣性滾動 (iPad-style inertial scrolling in Corona)

Lua cư xử kỳ lạ trên nền tảng PowerPC / LynxOS, tại sao? (Lua behaves weird on PowerPC/LynxOS platform, why?)

我們如何在函數輸入參數中輸入類型值作為對象? (How do we input type value as object in function input parameter?)

反編譯 Lua 字節碼的最佳工具? (Best tool(s) for decompiling Lua bytecode?)

本機 Lua 中的高效可變字節數組 (Efficient mutable byte array in native Lua)

在 Lua 中字符串化對象名稱 (Stringify object name in Lua)

純 Lua 中的全功能正則表達式庫 (Fully-featured regex library in pure Lua)

自我作為參數,並設置範圍? (self as param, and setting scope?)

已經放 } 但錯誤仍然說 } 是預期的? (Already put } but the error still says that } is expected?)

我想使用 HPC 的 gpu 並嘗試 module add CUDA ...但出現錯誤。錯誤是“Lmod 檢測到以下錯誤: (I want to use the gpu of the HPC and try module add CUDA... But errors occurs. The error is "Lmod has detected the following error:)







留言討論