Buffer.tostring() returns nil

is this a bug? every time i try to use buffer.tostring() it returns nil
other functions like buffer.len() work correctly

example:

if currentData then -- currentData is an array of buffers
	for _, v in pairs(currentData) do
		print(buffer.tostring(v)) -- prints ""
		print(buffer.len(v)) -- prints actual size
	end
end

It might be because of how it turns it into string. if you have any zeros in your buffer it might be the case, 0 or \0 is interpreted as end of string that’s why it may not print you whole content of a buffer.

is there any other way to do this?

What you’re doing wrong is you’re calling buffer.tostring(v) as a function, but in many buffer libraries, tostring is a method you call on the buffer object itself, like this:

v:tostring()

Because of this, buffer.tostring(v) returns empty or nil even though your buffer has data.

so you’re code would look like this if it were corrected:

if currentData then
for _, v in pairs(currentData) do
print(“Length:”, buffer.len(v))

local str
if v.tostring then
  str = v:tostring()
else
  str = buffer.tostring(v)
end

if not str or str == "" then
  print("buffer.tostring() returned empty or nil")
else
  print("Buffer as string:", str)
end

end
end

I would recommend to use v:tostring() instead of buffer.tostring(v). The method call usually works better to convert buffer contents to string.

doing tostring(v) will return “buffer: id” not the actual buffer as a string (also i got it to work)

print(v) -- buffer
print(tostring(v)) -- string
print(buffer.tostring(v)) -- buffer string

image

Not the best solution, but as prototype you could iterate over each byte convert it into string using string.char and combine it into some temporary string variable by attending characters to it.

I would say gsub out the nul bytes from the string before printing it.

string.gsub(buffer, "%z", "")

but that might be really expensive.