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

When returning a table from a function to a new table values are nil

Started by CaptiveCreeper, 31 March 2015 - 05:39 PM
CaptiveCreeper #1
Posted 31 March 2015 - 07:39 PM
I am trying to make a program similar to the dj program included in computer craft. I planned on making a interface that would show a list of all the disks attached to a computer (most of which are on wired modems) and play the one that the user wants. To do this i am getting all attached peripherals and checking to see if it has audio with the disk.hasAudio and putting all that do have audio in a table to be returned. When i receive that table from from the function it only has values of nil. I do not know what is going wrong any help would be appreciated in advanced.

function hasAudio()
	  local names = peripheral.getNames()
	  local audio = {}
	for i = 1 , #names do
	if disk.hasAudio(names[i]) == true then

audio[i] = names[i]

	end
	end
	print()
return audio
	end

function getAudioTitle()
local audio = hasAudio()
local title = {}
for i = 1 , #audio do
title[i] = disk.getAudioTitle(audio[i])
end
return title
end
getAudioTitle()
Bomb Bloke #2
Posted 31 March 2015 - 09:23 PM
#audio returns the highest index in audio before encountering one set to nil. For example, if your first found peripheral wasn't a disk drive with an audio disc in it, then audio[1] will be nil, and #audio will be 0; even if audio[2] does have a value assigned to it.

So in your hasAudio() function, use something like this:

audio[#audio + 1] = names[i]
CaptiveCreeper #3
Posted 31 March 2015 - 09:47 PM
Thank you so much. I made the change and it works perfectly.