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

counting number of strings in a table.

Started by subzero22, 02 November 2014 - 10:50 AM
subzero22 #1
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 on 02 November 2014 - 10:50 AM
JustPingo #2
Posted 02 November 2014 - 11:58 AM
amountOfTableEntries = table.getn(myTable)

(I read somewhere that you can also use #myTable instead of table.getn)
theoriginalbit #3
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 on 02 November 2014 - 11:05 AM
Bomb Bloke #4
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
subzero22 #5
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.