What is next()? A small guide

Introduction

Hello I am dand, a 2 year lua programmer and this is just a small guide to hopefully explain next to beginners and people who don’t even know it existed.

next is a builtin function used to give functionality to pairs (not ipairs) and allows us to loop through dictionaries easily.


Simple terms

next returns the a tuple of the next index and value in the given dictionary. The first arguement is the given dictionary, and the second arguement is the current index. To get the first index you set the second parameter to nil

Example

Heres an example in code

local dict = {
  ['Greeting'] = 'Hello!'
  ['Farewell'] = 'Bye!'
}

local i, v = next(dict) -- 'Greeting', 'Hello!'

next(dict, i) -- 'Farewell', 'Bye!'

What does this mean?

Well this allows for use to loop through dictionaries and this is what pairs does!

pairs described as a function:

local function pairs(t)
  return next, t, nil
end

This may be confusing, and tbh for anyone who isn’t a magician at lua, it is. It might take you a while to understand by what a for loop does when given a function, is keep running that function and uses the returned value as the second parameter to run again.

local function for(func, t, f)
  while true do
    local i, v = func(t, i)
    if i and v then
      f(i, v)
    else
      break
    end
  end
end

local t = {
  ['Hello'] = 'hi'
}

for(next, t, function(i, v)
  print(i, v)
end)

This is just a custom for loop in function form as an example.


What about ipairs?

Well ipairs is just simple. It just keeps adding up the index until the value becomes nil.

local function iterate(t, i)
  i += 1
  local v = t[i]
  if v then
    return i,v
  end
end

local function ipairs(t)
  return iterate, t, 0
end

Conclusion

This is just a small guide and requires a good knowledges of lua to understand. Feel free to read these sources for more information and ask questions if you’re confused.

https://www.lua.org/pil/7.3.html

33 Likes

Thanks for the tutorial. I didn’t know what next() was at all?

Quick off-topic question though: Why is the topic tagged with “ban” and “banned”

1 Like

Sorry there was a previous draft that used those two tags, forgot to remove them. Thanks for reminding me though.

1 Like

Wow i barely knew what next was before reading this Amazing Tutorial
now i understand more

before reading this i would use next as synatixs suger in my i,v loops haha

some code i made after reading this

local _, V = next, {5,10,15,20}

print(V[1])

1 Like