code_fodder
code_fodder

Reputation: 16341

Issue with array acces in lua

I am not sure why this does not work:

-- split data into an array of chars
dataList = string.gmatch(data, ".")

-- edit char 5 DOES NOT WORK
dataList[5] = 0x66

-- Print out the data in hex
for chr in dataList do
  io.write(string.format("[%02x] ", string.byte(chr)))
end

So if I remove the line dataList[5] = 0x66 then this works ok. So I don't get why I can't modify the element 5. The error I get is even more confusing for me:

Error: main.lua:33: attempt to index global 'dataList' (a function value)
stack traceback:
        main.lua:33: in function 'update'
        [string "boot.lua"]:463: in function <[string "boot.lua"]:435>
        [C]: in function 'xpcall'

What does that mean? - how can I achieve this?

Really all I want to do is modify a specific character of a string - but in lua people are saying you can't do it because they are immutable. So my idea is to split the string into an array and then modify this and then turn it back into a string when I am done...

update

Thanks to hjpotter92 I now have:

dataList = {data:byte(1, data:len())}         
dataList[5] = 0x66    
if dataList then
  finalString = string.char(table.unpack(dataList))     -- <---- this does not work :(
  printStringAsHex("final", finalString)  
end

However I am struggling to turn this back into a string, I get the error:

Error: main.lua:34: attempt to call field 'unpack' (a nil value) stack traceback: main.lua:34: in function 'update' [string "boot.lua"]:463: in function <[string "boot.lua"]:435> [C]: in function 'xpcall'

how can I achieve this?

Upvotes: 1

Views: 324

Answers (1)

hjpotter92
hjpotter92

Reputation: 80639

You want to perhaps store the string as a table (arrays are actually tables in lua):

dataList = {data:byte(1, data:len())}
dataList[5] = 0x66

print( string.char(table.unpack(dataList)) )

update

Didn't want to write a separate answer, so I have added a complete working example for any Lua version based on all the great answers / feedback. This is just for reference in case someone else encounters similar issues...

unpack = unpack or table.unpack

data = string.char(0x42, 0x42, 0x43, 0x15, 0x034, 0x33, 0x48)
dataList = {data:byte(1, data:len())}
dataList[5] = 0x66
print(string.char(unpack(dataList)))

Upvotes: 3

Related Questions