3 ms·
The easiest way to have a value which "acts like null" but doesn't mess with table indexing is to use `false`, which is the only Lua value other than nil which
by scythe 10y ago
The easiest way to have a value which "acts like null" but doesn't mess with table indexing is to use `false`, which is the only Lua value other than nil which is falsey (0 and "" are truthy).
- amttc 10y agoYeah, I wish Lua hadn't taken undefined and nil to be the same thing given the way tables work in it. Most of the time it doesn't matter, thankfully. Sometimes you bump into it. A sigil value can work too if you absolutely need it. ex: undef = {} function isundef(val) return undef == val end The sigil value is truthy and makes your code more convoluted, though. ex: if not val or isundef(val) then -- ... So, :/. I do love the language though.
- wruza 10y agoIf 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.