Jump to content




counting number of strings in a table.


  • You cannot reply to this topic
4 replies to this topic

#1 subzero22

  • Members
  • 97 posts

Posted 02 November 2014 - 11:50 AM

How would you go about counting how many things are in a table so you can the code to do math with it later.

an example of what I'm trying to do is:

local table = {"message 1", "message 2", "message 3"}
tablemath = table entries + 2

Edited by subzero22, 02 November 2014 - 11:50 AM.


#2 JustPingo

  • Members
  • 108 posts
  • LocationFrance

Posted 02 November 2014 - 11:58 AM

amountOfTableEntries = table.getn(myTable)

(I read somewhere that you can also use #myTable instead of table.getn)

#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 02 November 2014 - 12:04 PM

there are multiple ways you can do this, each with a different result, the simplest to use however is the # symbol which is the same as table.getn

local t = {"a", "b", "c"}
print( #t ) --# will output 3

also it is advised that you be careful with your variable naming, for example you have a table named 'table' this will override the table API and could cause problems in the future, especially when you attempt to use the functions that reside in the table.

Edited by theoriginalbit, 02 November 2014 - 12:05 PM.


#4 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 02 November 2014 - 12:17 PM

#myTable and table.getn(myTable) are not the same - for one thing, the former executes much faster, and for another, the two options won't always return the same answer.

#myTable returns the highest index before encountering one set to a nil value.

table.getn() will usually return the highest index "full stop", but if the table was constructed in a certain way, it may still return a lower index than expected.

table.maxn() is your best bet if you need reliability.

Note that none of the above three methods are any good for counting non-numeric keys - for those you'd want to do it manually with a pairs loop, eg:

local myTable = {["key1"] = "moo", ["key2"] = "moo2", "this last string will go against numeric index 1"}

local keys = 0

for key, value in pairs(myTable) do
  keys = keys + 1
end

print(keys) --> 3


#5 subzero22

  • Members
  • 97 posts

Posted 02 November 2014 - 12:39 PM

ok thanks for your help. I was thinking about the keys = keys + 1 way but wasn't sure if tehre were simplier ways.





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users