2 ms·
If you want, you can add t.exists[key]=true, and check it if you really want to know if key exists despite it's value is nil. function exists(t, k)
by wruza 10y ago
If you want, you can add t.exists[key]=true, and check it if you really want to know if key exists despite it's value is nil.
function exists(t, k)
return t[k] ~= nil or t.exists[k]
end
t = { 1, 2, nil, 4, exists={ [3]=true } }
i = math.random(4)
if exists(t, i) then
...
That's pretty close to Perl's semantics, where undef is inoperable under 'use strict' but arrays/hashes can have them explicit. Also can move exists out of t easily with weak table.
local exists_t = setmetatable({ }, { __mode='k' })
function set_exists(t, k)
exists_t[t] = exists_t[t] or { }
exists_t[t][k] = true
end
function exists(t, k)
return t[k] ~= nil or exists_t[t][k]
end
That said, I really like math-like attitude of definitions in Lua. No bs like 'bloated for your convenience', you just use your logic skills to program.