how to convert a function to string in Lua?

Viewed 89

How to output the contents of a function?

function a()
print("Hello,World")
end
print(func_toString(a))

I hope the result of func_toString(a) could be

function a()
print("Hello,World")
end

or just

print("Hello,World")

It is assumed that the source code is executed directly without precompiling or embedding. How to do this?

2 Answers

well, it's not completely impossible, the code in some cases can be read from a lua file, for example:

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) )

maybe that will be enough.

This is not possible from within the running Lua program.

Lua provides the debug library to inspect functions and variable. This allows you to obtain the source (the path or string where the function is defined) and the line range on which the function is defined. In the vast majority of cases this might actually be enough: Just find the first occurrence of function(...) on the first line and the first occurrence of end on the last line, then string.sub the relevant portion. This is however rather error prone; consider e.g.

function a() function b() end end
a()
func_toString(a)

since both functions are on the same line, you can't distinguish them - the debug library only provides you line info, nothing more. You could try to distinguish them by their signature since hacks exist to obtain the method signature, but that would fail here as well since both functions have the same signature. You could try gsubing them out based on their names, but remember that functions can be anonymous in Lua.

Lua also provides the string.dump function to obtain the bytecode of a function. I highly doubt that this is of any use to you; theoretically you could decompile it to get back a "Lua" representation of what the function does, but it would hardly be recognizable or readable.

Related