To start things off, let me make this clear: I understand the basic for loop structure.
for i = 1,20, 1 do
--does somthing
end
What I need help with is things like this:
for item in stack:iterator() do
print("Item: ".. item)
end
If you want to see the full code with all the variables, its right here, but this is the important part. Why does this work? I looked at the page on for loops in the roblox developer articles, but all it mentions are the basic for loop structure I mentioned above. Can someone please explain to me the actual structure of a for loop, that enables this to work?
for iteration, value in pairs(table) do
– v is the value of the item as it goes through the table. i is the current number or index of the item.
end
1 Like
look at this:
local table = {"hi", "hello"}
local dictionary = {
["hello"] = 5,
["effff"] = 2442,
["ea sports"] = 381230948
}
for i,v in pairs(table) do
print(i, v) -- will print the current counter and value.
end
for i,v in pairs(dictionary) do
print(i, v) -- i prints the key or the first value in a **pair**. v prints the actual value of the pair.
end
for i, v in ipairs(dictionary) do
print(i, v) -- prints the counter just like normal pairs but will not print the key for dictionarys. still prints the value
end
1 Like
Read about dictionarys in lua so you can understand this better.
I’m assuming you’re asking more about custom iterators, in that case It might be helpful to look at some of the pages in lua’s documentation like this one. You can create custom iterators in lua, using closures and closure factories. In lua, closures are just functions that contain upvalues (variables that are locally scoped but can be accessed in a different/encapsulating scope). In other words they work by creating a function (the factory)–that returns a function (the closure) that when called returns a value for the next step in the iteration.
local function iterator(start, max) -- very simple iterator for demonstration
local i = start ---local variable
return function() --Closure
if i <= max then
i = i + 1
return string.char(63 + i)
end
end
end
for value in iterator(1,5) do
print(value ) --> A, B, C, D, E
end
3 Likes