2

I have a lua file. It reads 2 files, one "script" file, one "source" file. The lua file interprets the script file and changes the source file (in memory) with some instructions in the script file. Then outputs this modified source into an output file. This works fine until somethings a CR. The modified source gets modified to have a CRLF instead of CR. This breaks a lot of things, and i do not know how to fix this. Heres the lua file.

progargs = {...}

if #progargs ~= 3 then
    print("Usage: patch <src> <script> <output>")
    return "u didnt do it right"
end


opcodes = {
    ["\000"] = {
        function(args)
            local inp=outc:sub(pos,pos):byte()
            strt={}
            for j=1,#src do
                table.insert(strt,outc:sub(j,j))
            end
            strt[pos]=string.char(inp-args[1])
            outc=table.concat(strt,"")
        end,
        1
    },
    ["\080"] = {
        function(args)
            local val = args[4] * 1 + args[3] * 256 + args[2] * 65536 + args[1] * 16777216
            pos = val+1
        end,
        4
    },   
    ["\255"] = {
        function(args)            
            local inp=outc:sub(pos,pos):byte()
            strt={}
            for j=1,#src do
                table.insert(strt,outc:sub(j,j))
            end
            strt[pos]=string.char(inp+args[1])
            outc=table.concat(strt,"")
        end,
        1
    },   
}

srcf = io.open(progargs[1])
src = srcf:read("*a")
srcf:close()

scrf = io.open(progargs[2])
scr = scrf:read("*a")
scrf:close()
i=1
pos=1
outc=src
while i<scr:len() do
    local opc = scr:sub(i,i)
    if opcodes[opc] ~= nil then
        local argc = opcodes[opc][2]
        local func = opcodes[opc][1]
        local args = {}
        for j=1,argc do
            table.insert(args,scr:sub(i+j,i+j):byte())
        end
        func(args)
        i=i+argc+1
    else
        print("unknown opcode xd fuck u")
        i=i+1
    end
end
print("doned")
outf = io.open(progargs[3], "w")
outf:write(outc)
outf:close()

Any method on how to fix this would be appreciated.

Epic8009
  • 33
  • 1
  • 8

1 Answers1

6

You must add "b" to the mode string when using io.open with binary files otherwise you will run into problems on Windows.

The simple model functions io.input and io.output always open a file in text mode (the default). In Unix, there is no difference between binary files and text files. But in some systems, notably Windows, binary files must be opened with a special flag. To handle such binary files, you must use io.open, with the letter `b´ in the mode string.

From https://www.lua.org/pil/21.2.2.html

SirSavary
  • 88
  • 6