Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update README.md #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

krzysztof-o
Copy link

Since lua tables start counting from 1 the example was wrong (#list was 1)

Since lua tables start counting from 1 the example was wrong (#list was 1)
@catwell
Copy link
Contributor

catwell commented May 21, 2014

This example is terribly confusing anyway. This pull request doesn't fix it correctly.

I will use the definition of the length operator from Lua 5.2 to explain. It is also broken for 5.1 but even harder to understand so I'll skip it.

The length of a table is defined only when it is a sequence, i.e. the set of its positive numeric keys is either empty or [1..N] for some N. In that case the length is N.

Before your change, setting key 0 to nil didn't do anything and the length was obviously 1.

After your change, the set of keys is {2} so the length of the table is undefined. Using the # operator on that table makes no sense. The fact that the implementation returns 0 is irrelevant. Actually it will break on LuaJIT:

$ luajit
LuaJIT 2.0.3 -- Copyright (C) 2005-2014 Mike Pall. http://luajit.org/
JIT: ON CMOV SSE2 SSE3 SSE4.1 fold cse dce fwd dse narrow loop abc sink fuse
> l = {}
> l[1] = nil
> l[2] = 'item'
> =#l
2

Now, select. Of course select returns 1 here. Actually:

> l = {}
> =select('#', l)
1
> l = {1,2,3}
> =select('#', l)
1

select does not work as the author of this example thought it does. select with # counts the number of arguments passed to it. Here you pass a single argument: the table list...

My POV is that this example should just be removed from the style guide entirely. It is not a matter of style, it is a matter of knowing the language. There already is a document for this and it is the Lua manual.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants