[英]how to convert a function to string in Lua?
怎么output的內容一個function?
function a()
print("Hello,World")
end
print(func_toString(a))
我希望func_toString(a)的結果可以是
function a()
print("Hello,World")
end
要不就
print("Hello,World")
假設源代碼直接執行,無需預編譯或嵌入。 這個怎么做?
這在正在運行的 Lua 程序中是不可能的。
Lua 提供debug
庫來檢查函數和變量。 這允許您獲取源(定義 function 的路徑或字符串)和定義 function 的行范圍。 在絕大多數情況下,這實際上可能就足夠了:只需在第一行找到第一次出現的function(...)
並在最后一行找到第一次出現的end
,然后string.sub
相關部分。 然而,這很容易出錯; 考慮例如
function a() function b() end end
a()
func_toString(a)
因為這兩個函數都在同一行,所以你無法區分它們——調試庫只為你提供行信息,僅此而已。 您可以嘗試通過它們的簽名來區分它們,因為存在獲取方法簽名的黑客攻擊,但這也會失敗,因為這兩個函數具有相同的簽名。 您可以嘗試gsub
根據它們的名稱將它們取出,但請記住,函數在 Lua 中可以是匿名的。
Lua還提供了string.dump
function來獲取function的字節碼。 我非常懷疑這對您有什么用處; 從理論上講,您可以對其進行反編譯以獲取 function 所做的“Lua”表示,但它幾乎無法識別或讀取。
好吧,這並非完全不可能,在某些情況下,代碼可以從 lua 文件中讀取,例如:
function a()
print("Hello,World")
end
local function get_source_code(f)
local t = debug.getinfo (f)
if t.linedefined < 0 then print("source",t.source); return end
local name = t.source:gsub("^@","")
local i = 0
local text = {}
for line in io.lines(name) do
i=i+1
if i >= t.linedefined then text[#text+1] = line end
if i >= t.lastlinedefined then break end
end
return table.concat(text,"\n")
end
print( get_source_code(a) )
也許這就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.