無所謂
無所謂

Reputation: 31

About lua for loop

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

Upvotes: 2

Views: 83

Answers (2)

pynexj
pynexj

Reputation: 20688

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

Upvotes: 3

Dan Bonachea
Dan Bonachea

Reputation: 2477

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

Upvotes: 1

Related Questions