541 posts
Location
Melbourne, Australia
Posted 17 November 2014 - 09:41 AM
I am wanting to be able to view the content of a function so I can run it differently in a program i am working on.
Example:
hello = function()
print("Hello World!")
for i = 1, 10
print("I am number "..i.."!")
end
end
I want to be able to extract the code that is run when the function is called, so I would be left with:
print("Hello World!")
for i = 1, 10
print("I am number "..i.."!")
end
Edited on 17 November 2014 - 08:42 AM
7083 posts
Location
Tasmania (AU)
Posted 17 November 2014 - 11:28 AM
Possible, but not easy.
When the Lua interpreter reaches your function definition, it compiles it into bytecode, dumps that in memory somewhere, and stores a pointer to that against your variable ("hello", in your example). To get the original code using that "hello" variable, you'd need to decompile the function.
Another option would be to have your script open itself as a file, hunt down the function definition you're interested in, and extract it as a string. This still requires some parsing, as you need to spot where the function begins, and where it ends - and that involves processing every if/while/do/for/whatever in order to make sure you get the right "end" statement at the bottom of the function. Still miles easier than decompiling, I'd assume.
Perhaps elaborate on your actual end goal - odds are you're going about this the hard way.
541 posts
Location
Melbourne, Australia
Posted 17 November 2014 - 11:36 AM
I can't quite remember what I was intending, but I am trying to somewhat port love2d to computercraft. I think I was extracting functions in order to run them inside a loop for love.update or love.draw, realising now I could have just run them or called them by loading them as an api.