User:Ganaram inukshuk/Provisional style guide for Lua: Difference between revisions
No edit summary |
No edit summary |
||
| Line 203: | Line 203: | ||
| ee | | ee | ||
| ff | | ff | ||
|}</syntaxhighlight>'''Avoid'''<syntaxhighlight lang="wikitext"> | |}</syntaxhighlight> | ||
{| class="wikitable" | |||
'''Avoid''' | |||
<syntaxhighlight lang="wikitext">{| class="wikitable" | |||
|+ Caption text | |+ Caption text | ||
|- | |- | ||
| Line 213: | Line 216: | ||
| dd || ee || ff | | dd || ee || ff | ||
|} | |} | ||
</syntaxhighlight> | |||
=== <code>ipairs</code> versus <code>pairs</code> versus <code>for</code> loop === | |||
<syntaxhighlight lang="lua"> | |||
local sometable = { "egg", "bread", "banana", nil, "milk" } | |||
-- As a for loop | |||
-- Order is guaranteed, but where to stop and start is needed | |||
-- Iterates through all numeric indices, even if values are nil | |||
for i = 1, #sometable do | |||
-- Code goes here | |||
end | |||
-- As a for loop using ipairs | |||
-- Order is guaranteed, in ascending order | |||
-- Iterates through numeric keys/indices, but stops at the first value of nil encountered | |||
-- Obviates using sometable[i], as value has the same... value | |||
for index, value in ipairs(sometable) do | |||
-- Code goes here | |||
end | |||
-- As a for loop using pairs | |||
-- Order is not guaranteed | |||
-- Iterates through numeric and non-numeric keys | |||
for key, value in pairs(sometable) do | |||
-- Code goes here | |||
end | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== Templates and modules == | == Templates and modules == | ||