lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 28.06.2013 02:57, Tim Hill wrote:

> But, let's face it; they ARE all workarounds. I think there IS a case to be made for being able to store a value in a Lua array that is uniquely NOT any other Lua value. Essentially, I think that value is "empty"; a valid Lua value that is simply not the same as any other Lua value (including nil).

So what is wrong with it? Lua is small and flexible enough that you can
- if you need -  add a few lines of code and then forget that there is
any workaround. But others, who don't need that (because they learned to
live with current implementation), can continue using original (read:
small and fast, so portable, not bloated with every feature added at the
language level) implementation.

> Basically, empty would act like nil in most regards, except:
> -- Storing empty in a table element actually stores the value, rather than deletes it.
> -- When used in a boolean context, the empty value evaluates to true (unlike nil).
> -- Has a type() of "empty"

That code should do it:

_EMPTYMT={__tostring=function() return '<empty>' end}
empty=setmetatable({}, _EMPTYMT)
type=function(o)
  if getmetatable(o)==_EMPTYMT then
    return 'empty'
  else
    return type(o)
  end
end

And then some tests:

print(empty)
assert(1~=empty)
assert(nil~=empty)
assert(true~=empty)
assert(false~=empty)
if empty then print('empty is true') end
t={1,empty,3}
for k,v in ipairs(t) do print(k, v) end
t2={[1]=1, [empty]=empty, [3]=3}
for k,v in pairs(t2) do print(k, v) end
print('Type:', type(empty))

Regards,
	miko