Lua: Convert spaces at the beginning of each line to tabs

I'm making a code editor in a game engine powered by Lua. Its menu system has the unfortunate limitation that tab characters aren't supported in fields, each tab gets converted to a space. I wish to ensure the resulting scripts are tabbed accordingly. Unless the engine lifts this limitation, I'll have to manually use an expression to undo the conversion effects.

What is the pattern matching I can use to convert each space to a tab, but only for spaces located at the beginning of each line before any other character? For example: <space><space>if(a<space>==<space>b)<space>then must become <tab><tab>if(a<space>==<space>b)<space>then

The text is stored in a local variable, with however it stores newlines naturally as when you copy multi-line text to the clipboard: I should be able to fix my issue by running it through the conversion process before writing it back to a text file. If you know please share how to achieve the opposite as well (tabs to spaces) as it may be safer to do that myself when loading the text into the menu than letting the interface strip tabs for me.


  • Someone in the engine chat provided the answer I was looking for, which upon testing I can confirm works just as intended. For anyone who needs this here's the conversion function to pass the string through:

    local function tabify(str)
        return str:gsub("%f[^\n]() + ()", function(i, j) return ("\t"):rep(j - i) end)