Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use for loop to iterate over table without index

Tags:

lua

I want to iterate over a table in Lua, and it works with a code like this (tabline_length and tab.width have been set before):

for index, tab in ipairs(tabs) do
    tabline_length = tabline_length + tab.width
end

What bothers me (and my editor) a bit, is that the index variable defined in the for loop is not used. Can't I iterate the tabs table without defining the index? I've tested the following code, but it did not work:

for tab in tabs do
    tabline_length = tabline_length + tab.width
end
like image 572
Daniel Rotter Avatar asked Dec 31 '25 15:12

Daniel Rotter


1 Answers

Your first option is to simply use _ by convention for unused variables (please only do this for local variables though, don't pollute the global variables with an _ entry containing some garbage which won't be collected).

This convention is recognized by most Lua linters, most notably Luacheck. Your editor is probably using Luacheck under the hood.

Alternatively, you could implement your own iterator ivalues which keeps the iteration index "private" as upvalue of a returned iterator closure:

function ivalues(t)
    local i = 0
    return function()
        i = i + 1
        return t[i]
    end
end

this could then be used as

for tab in ivalues(tabs) do
    ...
end

writing a (most probably less efficient) iterator just to discard a variable would be silly though, which is why you'll usually find for _, val in ipairs(vals) instead; however, such an iterator comes in handy when you implement more iterator helpers such as map or fold; for example, given an iterator helper sum which sums over the elements of an iterator, you could simply do sum(ivalues(nums)) to find the sum of the numbers in a table of numbers nums. Writing this in terms of ipairs would be more awkward; you'd probably fall back to writing an imperative solution.

like image 139
LMD Avatar answered Jan 02 '26 16:01

LMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!