Talk:Table.size

From Multi Theft Auto: Wiki
Jump to navigation Jump to search

What about using the builtin lua function:

table.getn(table)

--Subenji99 06:54, 13 July 2009 (CEST)


table.getn was replaced by the #-operator, which returns the number of table elements with a numerical (!) index.
table.size counts all elements regardless of which type their index is.
Of course it's a bad idea to use this function for a table with only numerical indices.
NeonBlack 16:19, 13 July 2009 (CEST)


Indded, I actually just attempted it with non-numerical indices and found it didn't work. I stand corrected. :D

I shall leave my humiliation (lol) here so anyone else wondering what the point of this function would be can see that it is for non-numerical indices.

Oh, reading up, I'd like to point out that if you structure your table, planning for this, you can still use the # operator. you have to count the additions you make to your table then use table.setn like so:

table.setn(table, <number of values>)

if you are using a loop to create your table, it would be a simple matter to add it after:

   table = {}
   local count = 0
   for _,v in pairs(results) do
       table[v] = someFunction(v)
       count = count + 1
   end
   table.setn(table, count)

Array Size

In my case though, this function was still required as the table I was checking against was a returned table from an exported function of mapmanager.

--Subenji99 20:43, 13 July 2009 (CEST)


You should really update your Lua skills. table.setn is deprecated like table.getn is, too.
Of course setting the n of the table would be much more efficient than iterating through it to get the size, but it's as I already said deprecated.
Alternatively you could use a mostly unused index for storing the size like _ for example. But I don't think iterating through the table and just increasing one value each step isn't that expensive.
NeonBlack 20:50, 14 July 2009 (CEST)

Sebas

Please keep using pairs instead of next for new people :)


I don't think that's useful. People should learn to use next instead of pairs. Apart from that it's no code for learning but more a code for copying.
NeonBlack 22:18, 18 August 2009 (UTC)


Actually, pairs is defined as so:

function pairs( t )
    return next, t, nil
end

...so it shouldn't really matter which one to use as they're basically the same. Awwu 15:57, 19 August 2009 (UTC)


It doesn't matter which one you use but when newcomers take the code and will try to learn from it they won't even know pairs exists. If there is pairs and ipairs to make the code easier to read then why would you make things harder for beginners. You can use next for yourself but try to avoid it when teaching newcomers otherwise they'll know about ipairs and next which are different in use. 50p 16:37, 19 August 2009 (UTC)