lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]




On Fri, Nov 21, 2014 at 9:40 AM, Thiago L. <fakedme@gmail.com> wrote:

On 21/11/14 01:37 PM, Marco Mastropaolo wrote:
Probably a scenario which is totally unlikely and broken on so many other aspects.. but this code

t = { 1, 2, 3 };
setmetatable(t, { __len = function(tbl) return tostring(rawlen(tbl)); end });
x = ##t;
-- x = 1

actually works and would break if ## would be implemented.

As I said, totally unlikely and super-dirty to starts of, but at the moment the parser treats (correctly) ## as two executions of the # operator and if a __len meta returns a string or table, it's actually "working" code (for some definition of working).

-- Marco

On Fri, Nov 21, 2014 at 4:23 PM, Thiago L. <fakedme@gmail.com> wrote:
(IRC logs)

<SoniEx2> I wish Lua had a way to count keys in a table
<SoniEx2> so for example {1,2,3} would be 3, {[0]=0,1,2,3} would be 4, {A = 1, B = 2, C = 3} would be 3
<SoniEx2> etc
<SoniEx2> I can use __newindex to count key adds
<SoniEx2> but there's no __remindex or something
<SoniEx2> and it wouldn't help with what I wanna do
<SoniEx2> sure, I can use pairs() and a counter but that's slow :/
<kansuu> should be possible with proxy table?
<SoniEx2> kansuu, won't help when you're taking in random tables
<kansuu> nope, then you'd need to count the number of entries first anyway
<mniip> except the part where lua already knows the value internally
<SoniEx2> see? this is why lua needs to count when ppl set things and stuff
<kansuu> it doesn't _need_ to, it'd just be an optimization
<kansuu> for your specific use case
<SoniEx2> if setting to nil and it wasn't already nil, decrement, if setting to non-nil and it wasn't non-nil, increment
<SoniEx2> then provide a table.nkeys()
<SoniEx2> or a ## operator

Hmm... then a ! operator?

I have to admit to wanting something along these lines from time to time. Usually, I want to know the number of non-numeric keys, but knowing the total count is probably better.

I think I remember someone saying that the trouble with this is that it's not trivial to implement it in a way that wasn't the same speed as a while loop. Maybe weak values had something to do with it?

--Andrew