What is table.foreach() actually do?

Hello everyone!

I am a bit confused, and thats the foreach, so what is that actually do? I am new in tables, and I want learn everything what I need. I never was so intrested in tables. I worked with metatable but not with tables, anyways.

So can somoene explain me everything of that table.foreach()?

How you explain me it:

  1. What does it do?
  2. What is the parameter exactly of it - do I need to use 1 or the second and when?
  3. Give me a script example.
  4. Give me a example when I have to use it.

Important: Take your time with your explanation Thanks!

table.foreach was implemented before the generic for loop existed in Lua, so it takes a table for the first argument, then a function to apply to every element as the second argument, i.e smoething like table.foreach({ "a", "b", "c" }, print) would print out every element including the index of it in the table. Later versions of Lua implemented the generic for loop, and thus, this function is deprecated and you should use the more idiomatic generic for loop instead.

2 Likes

It takes in the table and a function as the parameters. It automatically passes the key and value as the parameters of the function, so that function can do whatever it likes with the key and value. For example, this program prints them:

local keys, values = {}, {}
local function seperate(k v)
	
	print(k, v) --prints it like it'd do in a for loop
	table.insert(keys, k)
	table.insert(values, v)
	
end

local dict = {Key = 'Value', Key2 = 'Value2'}

table.foreach(dict, seperate)

There’s also foreachi, which is for arrays where it’s the index passed first instead of the key. You can think of this like ipairs() vs pairs().

1 Like

unfortunately I cant give everyone solution, but anyways I will give u heart because u was the second one