Question

I'm working on a system for serialization/deserialization, and I'm trying to get some really fancy stuff going with functions. My goal is to serialize objects containing functions in a human-readable and reversible manner (the serialized files will need processing after the loadfile() step). I need a way to get the actual source of a function, and it looks like I can't always do that with debug.getinfo().

I know that debug.getinfo() will give be the file and line where it was defined (or the source of the function, depending on its origin). Is there a way I can read the function text from that file? I'd be willing to use some kind of parser utilities to do so. Maybe there are Lua packages for parsing Lua code?

Perhaps there's a way I can get loadfile() or require() to automatically retain function source somewhere?

Yes, I know you can get all sorts of information out of debug.getinfo, but it was unable to deal with functions loaded through stdin...

uberblah@glade-m:~$ lua
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> a = function() print("hello, world!") end
> require("serpent")
> s = require("serpent")
> =s.block(debug.getinfo(a))
{
  currentline = -1,
  func = loadstring("LuaQ\000\000\000\000\000\000\000\000\000=stdin\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000A@\000\000@\000\000�\000\000\000\000\000\000\000\000\000\000\000print\000\000\000\000\000\000\000\000hello, world!\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000",'@serialized') --[[function: 0x2068a30]],
  lastlinedefined = 1,
  linedefined = 1,
  namewhat = "",
  nups = 0,
  short_src = "stdin",
  source = "=stdin",
  what = "Lua"
} --[[table: 0x206cf80]]
> f = io.open("stdin", "r")
> =f
nil

SOLUTION FOR SOURCE FROM STDIN... 1) Capture all STDIN, write it to a file 2) Load the information from that file, instead of from stdin 3) debug will track the function line numbers in that file

Was it helpful?

Solution

Using debug.getinfo you can get source, linedefined, and lastlinedefined. Unless you format your code really weirdly you should be able to extract the complete code of your function from this info. There is no need to parse code, just to get the correct set of lines.

OTHER TIPS

You want to disasseble the bytecode into Lua statements and expressions. Try http://chunkspy.luaforge.net/. Or maybe http://luadec.luaforge.net/ but I haven't used them so can't give much more info. Luac (Lua compiler) also has -l switch which produces assembly listing that could potentially be parsed. Then there is lbci (bhttp://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lbci). You might find Getting the AST of a function useful. Finally, I suggest you do a search for "lua decompiler".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top