Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

table.foreach(), being deprecated? [closed]

Asked by
LuaQuest 450 Moderation Voter
8 years ago

Just wondering, can (or should) i still use table.foreach whenever necessary? The reason i ask this is just to wonder if there's a difference between them, and for loops. for example:

local dictionary = {
    x = 1,
    y = 2,
    z = 3
}

table.foreach(dictionary,function(k,v)
    print('Key: '..k, 'Value: '..tostring(v))
end)

instead of:

local dictionary = {
    x = 1,
    y = 2,
    z = 3
}

for i,v in pairs(dictionary)do
    print(i,v)
end

Will using table.foreach risk a higher chance of something breaking? Or does it just not matter.

Locked by EpicMetatableMoment and DeceptiveCaster

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

1 answer

Log in to vote
3
Answered by 8 years ago

An Introduction

table.foreach is actually a quick and fast way to merely output different keys and values in a table. If you are curious as to why exactly it is deprecated, it is because the table.foreach method was originally in Lua before the introduction of for (for iterations). When the framers of Lua finally added for into the language, the whole nature of table.foreach was being unnecessary because the same functionality could be achieved with just using for.

These are how tables were usually handled, from earliest to latest:

Earliest

local array = {"DigitalVeer", "To The Moon", 5911345, "Updoots!"}
table.foreach(array, function(k,v) print(k,v) end)

After Introduction To For

local array = {"DigitalVeer", "To The Moon", 5911345, "Updoots!"}
for k,v in array do
print(k,v)
end

After Introduction To Iterator Functions

local array = {"DigitalVeer", "To The Moon", 5911345, "Updoots!"}
for k,v in pairs(array) do
print(k,v)
end

for k,v in ipairs(array) do
print(k,v)
end

In summary, table.foreach replicates behavior of the earliest for iterator that came about in Lua history (Lua 4.0). Using it for quick and clean objectives such as outputting the elements in an array is completely fine. Nothing bad should end up occurring from this. For anything else, however, it is always good practice to use the rather newer and trusted methods since they are more likely to give you better performance and enhance functionality.

Ad