• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

Adding a default value to a table makes the ipairs method goes in a infinity loop (1 Viewer)

Herly Quijano

Mar 19, 2021
Reaction score
Hello, I wanna know if this thing is something that could be fixed or there is a logical reason to have it, but if you add a "default value" to a table, like in other programming languages, for example a table that contains integer, a not declared index returns 0 instead of nil:
list = <table with default value>
list[1], list[2], list[3] = 1, 3, 5
print(list[2]) -- prints 3
print(list[6]) -- should print 0
A method that I'm using is (not created by me):
local mts = {}
local cleaner = {__mode = "k"} --without this, tables with non-nilled values pointing to dynamic objects will never be garbage collected.
local setmt = function(default, tab)
    local mt
    if default then
        mt = mts[default]
        if not mt then
            mt = {__index = function() return default end, __mode = "k"}
            mts[default] = mt
        mt = cleaner
    return setmetatable(tab or {}, mt)
So if I do:
list = setmt(0)
All the not defined indexes of list return me 0 instead of nil.

The problem is if I wanna iterate in the list using ipairs it goes to an infinity loop, because it is supposed that function stops iterating when reaches the first nil value of the list, but in my list there is no nil values.

I know the solution would be be sure that where and with what I'm using ipairs or iterating using other methods, but as I said in the beggining, I wanna know if there is a reason the ipairs works not using the rawset function to detect the first nil value.