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

Table Problems :(

Started by Nicba1010, 12 July 2014 - 09:25 PM
Nicba1010 #1
Posted 12 July 2014 - 11:25 PM
This is returning 0, should it not return 1?

local i = {}
i["local"] = "sam"
print(#i)
Bubba #2
Posted 13 July 2014 - 12:07 AM
Nope, it's returning the correct number. When you get the length of an array using this method, it only takes into account sequentially indexed data. For example:

local t = {}
t[1] = "test"
t["some_index"] = "another_test"

print(#t)

This will output "1", because there is only one sequentially indexed value ("test"). It is also important to keep in mind that if you skip a number (e.g. t[1] = "something", t[3] = "something_else"), lua will only return the length up to the first gap.

If you need to get the actual length of a table, you could implement a function like this:

local function getTableSize(t)
  local size = 0
  for k,v in pairs(t) do
    size = size + 1
  end
  return size
end

This would account for non-numerical indexes and gaps in the indexes as well.
Nicba1010 #3
Posted 13 July 2014 - 03:55 PM
Thx, figured it out by myself, but still. I'm so used to for(String s:javaArray) ;)/>