Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
- better explanation of the length operator
- no functions in table constructors
- spaces after { and before }
  • Loading branch information
catwell committed Nov 20, 2013
1 parent 49dae75 commit 8997401
Showing 1 changed file with 40 additions and 15 deletions.
55 changes: 40 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,35 +109,60 @@ you find any mistakes or typos.
}
```

- Consider `nil` properties when selecting lengths.
A good idea is to store an `n` property on lists that contain the length
- The length operator does not work as you may expect on tables that
contain `nil`.
A good idea is to store an `n` property on lists that contain their length
(as noted in [Storing Nils in Tables](http://lua-users.org/wiki/StoringNilsInTables))

```lua
-- nils don't count
local list = {}
list[0] = nil
list[1] = "item"
list[2] = nil

print(#list) -- 0
print(select('#', list)) -- 1
print(#list) -- 1
```

```lua
local list = {}
list[1] = "item"
list[2] = nil
list[3] = "item"

print(#list) -- undefined result
```

- The length operator always counts from 1. If you store values at negative
positions in a table (including 0) they will be ignored.

```lua
local list = {}
list[0] = "item"
list[1] = "item"

print(#list) -- 1
```

- When tables have functions, use `self` when referring to itself.

```lua
-- bad
local fullname = function(this)
return this.first_name + " " + this.last_name
end
local me = {
fullname = function(this)
return this.first_name + " " + this.last_name
end
fullname = fullname,
first_name = "Jack",
last_name = "Smith",
}

-- good
local fullname = function(self)
return self.first_name + " " + self.last_name
end
local me = {
fullname = function(self)
return self.first_name + " " + self.last_name
end
fullname = fullname,
first_name = "Jack",
last_name = "Smith",
}
```

Expand Down Expand Up @@ -547,11 +572,11 @@ you find any mistakes or typos.
```lua
--bad
local thing = {1,2,3}
thing = {1 , 2 , 3}
thing = {1 ,2 ,3}
thing = { 1 , 2 , 3 }
thing = { 1 ,2 ,3 }

--good
local thing = {1, 2, 3}
local thing = { 1, 2, 3 }
```

- Add a line break after multiline blocks.
Expand Down

0 comments on commit 8997401

Please sign in to comment.