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

Length of an array

Started by ShadeOfBlack, 02 September 2012 - 10:44 PM
ShadeOfBlack #1
Posted 03 September 2012 - 12:44 AM
I am new to ComputerCraft, but have been self taught in many other object-oriented computer languages. I understand the root of how it works, but I don't know some of the variable names.

I just would like to know the variable for the length of an array.

Thanks!
Kingdaro #2
Posted 03 September 2012 - 01:39 AM
An array in lua is actually called a table. You can find the length of a table via the hash symbol: #

So if I wanted to find the length of table "t", i would do "#t".
KaoS #3
Posted 03 September 2012 - 05:21 AM
watch out though, that is bugged, it only counts values if they are defined by consecutive numbers starting at 1. for example


mytable={}
mytable[1]='asd'
mytable[2]='qwe'
mytable[3]='zxc'
print(#mytable)

would print 3 but



mytable={}
mytable[1]='aaa'
mytable['firstvalue']='asd'
mytable['secondvalue']='qwe'
mytable['thirdvalue']='zxc'
print(#mytable)

would print 1… that is why if I am planning on using custom delimiters I make a custom counter


local function count(input)
  if type(input)~='table' then
   return nil
  end
  local int=0
  for k,v in pairs(input) do
   int=int+1
  end
  return int
end
Kingdaro #4
Posted 03 September 2012 - 05:24 AM
It's not a bug, lol. It's only supposed to count number indexes.
KaoS #5
Posted 03 September 2012 - 05:34 AM
but why??? why not count all of the values?
Mmmmmmmm #6
Posted 03 September 2012 - 07:32 AM
but why??? why not count all of the values?
table.getn() is able to get the size regardless of sequence, so it's not really a problem.
KaoS #7
Posted 03 September 2012 - 07:34 AM
ah, I did not know that, thanks
Mmmmmmmm #8
Posted 03 September 2012 - 08:13 AM
ah, I did not know that, thanks
Do keep in mind that it still doesn't count nil values.