Herly Quijano
Newcomer
- Joined
- Mar 19, 2021
- Messages
- 79
- Reaction score
- 10
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:
A method that I'm using is (not created by me):
So if I do:
All the not defined indexes of
The problem is if I wanna iterate in the list using
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
Lua:
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
Lua:
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
end
else
mt = cleaner
end
return setmetatable(tab or {}, mt)
end
Lua:
list = setmt(0)
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.