Search code examples
replacelua

Replace shortened variables with their full string


I have a code written in Lua with a load of variables in a string like this:

local var={[1]= "dothis", [2]= "clevermaths", [3]= "longstring"}

than the rest of the code uses these variables in the format of var[1], var [2] all over the place.

I was to replace all the var[1]s with "dothis", the var[2]s with "clevermaths".

I started using Find and Replace in VS Code and doing each one manually, but this was taking ages as there are over 50 of them in this script alone.

I googled along the lines of "how to replace shortened variables stored in a table with their full-length values" - no help (unless I'm some sort of coding expert - which I'm not).

I joined Stackoverflow to ask you clever people very nicely for some help, bearing in mind I'm not a coder, but get by more or less by modifying, tweaking, watching youtube tutorials etc.

Sadly I have to interact with Lua code in a very specific piece of software used for my job. It makes tasks easier, but there's no resources or budget to employ someone, so it falls on my shoulders. If I can't do it, I just have to do things manually and stay late at work.


Solution

  • I suppose it would not make much sense to implement in your code the ability to self-change. So you have two main options: use your editor manually to change your code, or script it (whether inside your editor, or using an independent program).

    I do not use VSCode but I believe you can do it using JavaScript (*), using VSCode Tasks. (You could also build an extension, but this is an overkill.)

    The easiest way is to just make an independent script; it can be written in anything you want. Lua is an obvious choice because you already have a Lua table with the desired changes, but with little tweaking you can do it in any language you are comfortable with. Here's Lua script that should do what you want.

    -- Set the filename of your code here
    local filename = "my_script.lua"
    
    -- Paste your lookup table here
    local var = { [1] = "dothis", [2] = "clevermaths", [3] = "longstring" }
    
    -- read the file
    local file = io.open(filename, "r")
    local text = file:read("a")
    file:close()
    
    -- replace each of the table entries
    for i, repl in pairs(var) do
      local key = "var%[" .. i .. "%]"
      text = text:gsub(key, repl)
    end
    
    -- save the changes
    file = io.open(filename, "w")
    file:write(text)
    file:close()
    

    After executing this script, your file should have been updated with all the replacements you had in your lookup table.

    The other poster did mention an important safety tip: whenever you are performing a large-scale change on one of your files, make sure to use version control and commit beforehand (or, at the very least, make a backup), for safety.


    *) or at least, a JavaScript build system, like grunt or npm — the code itself can be any executable.