Hey! I am messing around with a free model vignette effect and just found this code:
for side,sideInfo in next, viewModel.sides do
end
What does the ‘next’ keyword do?
Hey! I am messing around with a free model vignette effect and just found this code:
for side,sideInfo in next, viewModel.sides do
end
What does the ‘next’ keyword do?
Ok very cool. Just experimented with this and crashed my studio
In this instance it is the same as using pairs. This is been asked about a million times though and there are a lot better answers if you want to look around and learn about everything it can do.
Okay. I just don’t understand why there is “in next, table” instead of next(table)
next is an internal lua “iterator” function which provides, when given a table and an index, the “next” value
This works in junction with the for loop to loop through a table
First point:
next, table is the same as pairs(table)
function pairs(tbl)
return next, tbl
end
--pairs returns next, its just behind a layer
Second point:
local test_table = {"a","b","c"}
print(next(test_table,nil)) --prints 1, "a", because the index is nil, or its the "start" point
print(next(test_table,1)) --prints 2, "b", because the next index after 1 is 2, or "b"
print(next(test_table,2)) --prints 3, "c"
print(next(test_table,3)) --prints nil because theres no more values
Edit for further info:
The reason its “next, table” is because this is how the for loop was designed to work
It calls the next function over and over with the “table” argument until it returns nil
Here is a sample function of how a for loop might work if you programmed it yourself
local test_table = {"a","b","c","d"}
function fakeForLoop(iterator, tbl)
local current_index, current_value = iterator(tbl)
while current_value do
print(current_index.." "..current_value)
current_index, current_value = iterator(tbl,current_index)
end
end
fakeForLoop(next,test_table)
Thanks. Now I kinda understand it.