3

I'm having issues writing strings to binary in Lua. There is an existing example and I tried modifying it. Take a look:

function StringToBinary()
  local file = io.open("file.bin", "wb")
  local t = {}
  local u = {}
  local str = "Hello World" 
  file:write("string len = " ..#str ..'\n')
  math.randomseed(os.time())
  for i=1, #str do
    t[i] =  string.byte(str[i])
    file:write(t[i].." ");   
  end  
  file:write("\n")
  for i=1, #str do 
    u[i] = math.random(0,255) 
    file:write(u[i].." ");
  end
  file:write("\n"..string.char(unpack(t)))
  file:write("\n"..string.char(unpack(u)))
  file:close()
end

file:write(t[i].." ") and file:write(u[i].." ") write both tables with integer value. However with my last two writes: unpack(t) displays the original text, while unpack(u) displays the binaries.

It's probably string.byte(str[i]) that is mistaken. What should I replace it with? Am I missing something?

3
  • Is there any problems other than compiling? Where is your question? Commented Oct 31, 2013 at 4:51
  • If this code works fine (except the compilation problem), like you commented below, edit your question so. Your question was not clear about what kinds of problem, and people may be confused that it's in error and still needs to be solved. Commented Oct 31, 2013 at 8:12
  • (Semantic point) Lua strings are binary: They are an immutable, counted sequence of bytes. There is no assumption nor requirement that they be one or any encoding of characters from any character set. Functions, of course, can treat them otherwise. Commented Nov 1, 2013 at 1:09

1 Answer 1

4
t[i] =  string.byte(str[i])

is wrong, it should be:

t[i] =  string.byte(str, i)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I found out the code works just fine. Now my problem just gotten bigger. Do you know how I declare unsigned __int32, unsigned __int16, and unsigned __int8 just like in C++?
@xacrilege Lua has only one number type, which is the same as double in C++ by default. There's no built-in integer types, and you don't need to declare variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.