Quick actions

cmd+k|ctrl+k

Navigation

Languages

Implement an Iterated For Loop

Snippet info

Language

Lua

Visibility

public

Author

captain.g

Created

2021-02-27T06:18:40Z

Updated

2021-02-27T06:18:40Z

local function myfor(iterator, callback) 
    while true do 
        local returns = {iterator()}
        if #returns == 0 then break end
        callback(unpack(returns))
    end
end

-- Value iterator

local function justvalues(t)
    local index = 0
    
    return function()
        index = index + 1
        return t[index]
    end
end

-- Index value iterator

local function justipairs(t)
    local length = #t
    local index = 0
    
    return function()
        index = index + 1
        local value = t[index]
        if index <= length then
            return index, value
        else
            return
        end
    end
end

-- Example

local a = {"Bob","Mark","Jessie","Greg","Alice"}

myfor(justvalues(a), print)
myfor(justipairs(a), print)
INFO