tags:

views:

93

answers:

5

I have found myself having to turn a chunk of Lua code into a string so it can be run as a proper Lua chunk. Writing code like that is not too difficult, but it's time consuming and prone to minor errors that result in lost development time and patience.

Is there any tool/filter capable of taking a piece of runnable code and turning it into a proper string?

If I am not explaining myself right (not native English speaker, my apologies!), I want to find a tool that turns code like

MyFunction("String!")

into

"MyFunction(\"String!\")"

It's trivial in the example, but when talking several lines of code, it's pretty tedious.

I am using Linux as my main OS, perhaps there is some filtering tool available? A Lua-based solution would be interesting just for amusement, too.

A: 

Would something like this work?

sed 's/"/\\"/g;' join_string | tr '\n' '\a' | sed 's/\a/\\n/g' | more
archgoon
+1  A: 

IntelliJ does it very well.

fastcodejava
+5  A: 

You can just wrap the code with a long string. This should be simple regardless of the method you use to achieve it:

myString = [==[
    for i = 1, 10 do
        print("Hello #"..i)
    end
]==]

You can have as many = signs as you want (including none) between the opening and closing brackets as long as they match. This way you're sure to have an "end comment" symbol that doesn't appear in the enclosed source code.

Cogwheel - Matthew Orlando
Whoa, this is really useful, never read about this being possible.This is even better than converting to string, so I will stick to this answer, thank you very much!
MissHalberd
+2  A: 

Use string.format("%q",s).

lhf
A: 

You may do something like this, however the result is only readable via the Lua compiler itself.

string.dump(function() print("Hello world") end)

Run such code you may do this

loadstring(string.dump(function() print("Hello world") end))()
Camoy