Home > Mobile >  About lua for loop
About lua for loop

Time:11-10

function string.split(input, delimiter)
    input = tostring(input)
    delimiter = tostring(delimiter)
    if (delimiter=='') then return false end
    local pos,arr = 0, {}
    -- for each divider found
    for st,sp in function() return string.find(input, delimiter, pos, true) end do
        table.insert(arr, string.sub(input, pos, st - 1))
        pos = sp   1
    end
    table.insert(arr, string.sub(input, pos))
    return arr
end

why use

function() return string.find(input, delimiter, pos, true) end

after in , rather then use

for st,sp in string.find(input, delimiter, pos, true) do
    table.insert(arr, string.sub(input, pos, st - 1))
    pos = sp   1
end

I just want to know why do this

CodePudding user response:

for .. in is the generic for statement which works with iterators. string.find() returns for only once and the return value is not an iterator so cannot be used with for .. in.

The Lua doc says this:

The generic for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil.

Logically speaking, the for loop is the same as this:

while true do
    st, sp = string.find(input, delimiter, pos, true)
    if not st then
        break
    end
    table.insert(arr, string.sub(input, pos, st - 1))
    pos = sp   1
end

CodePudding user response:

The line you are asking about is a lambda function defining an iterator for this lua generic for loop. The generic for loop requires this argument to produce a function closure that can be called repeatedly (each time through the loop).

For more examples see this chapter

  • Related