This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
DannySMc's profile picture

How to unpack a table into a string?

Started by DannySMc, 27 August 2014 - 12:25 AM
DannySMc #1
Posted 27 August 2014 - 02:25 AM
Okay so I am trying to recreate the read program, adding my own bits and pieces…

The thing I am stuck on is outputting the table as a string without all the syntax… I found a function in Lua called unpack() which does exactly what I want… but it doesn't seem to be working… are there any other ways?

Here is my code anyway:

function read(sAlt, sStart)
  local tReadData = {}
  local nPos = 0
  xPos, yPos = term.getCursorPos()
  term.setCursorPos(1, yPos + 1)
  while true do
	local args = { os.pullEvent() }
	if sStart then
	  nStart = string.len(sStart)
	  write(sStart)
	end
	if args[1] == "key" then
	  if args[2] == 28 then
		return unpack(tReadData)
	  elseif args[2] == 14 then
		-- add back key use table.remove()
		-- and clear the char space.
	  end
	elseif args[1] == "char" then
	  table.insert(tReadData, args[2])
	  nPos = nPos + 1
	  if sAlt then
		write(sAlt)
	  else
		write(args[2])
	  end
	end
  end
end

print("-----------------------")
local text = read()
term.setCursorPos(1,10)
print(text)

Forgot to say it doesn't work because when I print the returned variable it only prints the first entry in the table?
Edited on 27 August 2014 - 12:27 AM
KingofGamesYami #2
Posted 27 August 2014 - 02:28 AM
table.concat( tbl, seperation )

eg.

local tbl = { "hello", "goodby" }
local sTbl = table.concat( tbl, " " )
print( sTbl ) --#prints: "hello goodby"
Edited on 27 August 2014 - 12:29 AM
natedogith1 #3
Posted 27 August 2014 - 04:41 AM
You're returning all the values you seem to want, but you're storing them to a single variable. That variable is only storing the first argument returned, and as such you're only printing the first table entry.