Richard Bucker

Compare table length in Perl and Lua

Posted at — Jun 20, 2012

In the beginning there Perl; and in Perl was the array and the hash. Later there was Lua; and in Lua there is the table. The table in Lua seems to be both an array and hash, where they are both implemented as a hash. But let’s start with Perl.In Perl (don’t panic there are idioms that make this less straight forward):[sourcecode language=“perl”]# length of an arraymy @a = (4,5,6);print scalar @a; #– prints 3# length of a hashmy %h = (four=>4, five=>5, six=>6);print scalar keys %h; #– prints 3[/sourcecode]In the array example I’m thinking that the number of elements in the array is actually stored in the array and that the function of converting the array to a scalar causes Perl to return the stored value. I really hate the idea that Perl might be counting every element in the array every time this was performed… and if it was then that might justify storing the length locally for the different uses although this get’s funky when multi-threading.As for the hash version.  The keys() method exports the keys held in the hash as an array which is then converted to a scalar as in the array example.In Lua (go ahead and panic as the code is ugly):[sourcecode]– length of an arraylocal a = { 4, 5, 6}count = 0for _ in pairs(a) do count = count + 1 endprint(count)print(#a)– length of a hashlocal h = { four = 4, five = 5, six = 6}count = 0for _ in pairs(h) do count = count + 1 endprint(count)print(#h)[/sourcecode]In the array example the values 4, 5, 6 are assigned to index' 1, 2, 3 respectfully. When counting the pairs() we are evaluating each entry in the table just like the perl hash function keys(). However, when we execute #a, unlike the perl array functionality, Lua starts initialized an index counter at ‘1’ and increments it so long as the value is not nil. So in the case of the array these two methods are synonyms.In the hash example the count method works exactly the same, however,  the #h fails completely.Clearly the language designers did not think this was a big deal. Whether it was because counting the pairs is truly efficient or there is another more efficient way or the reader is actually expected to fill in the gaps with more robust code. After all Lua is not made up of too much code anyway.I’m not certain that I really care but it is frustrating. Specially when modern languages like Python and Ruby seem to have done away with particular issue. And as a side comment we should do away with idiomatic programming.