3 ms·
Wow, accidentally putting holes in the middle of a numeric table sounds nasty. These issues don't bite me very often, but they are pretty easy to prevent. f
by anonymoushn 13y ago
Wow, accidentally putting holes in the middle of a numeric table sounds nasty. These issues don't bite me very often, but they are pretty easy to prevent.
function a_stricter_table()
return setmetatable({}, {__index = function(t,k)
error("no value at "..tostring(k))
end})
end
t = a_stricter_table()
t.a = 5
print(t.a) -- 5
print(t.b) -- crash D:
A similar trick can make trying to unset a value by assignment raise an error, while unsetting a value using a delete() function is allowed.
Edit: Removed the fake table/backing table thing, since you can do the one trick without it. I think the other trick requires it, though.
- vor_ 13y agoArray holes can be quite nasty, as they lead to incorrect return values for the length operator. Protecting individual tables with a custom solution, on top of prohibiting undefined globals, naturally makes one wonder why the language doesn't behave this way natively. Lua is praised for being unafraid to break backwards compatibility in major releases because embedders can retain their existing versions of the codebase indefinitely. This seems like an opportunity for a future version.
- justincormack 13y agoIt doesnt because there are cases when you want that behaviour and the language gives you tools not policy. In a serious project pretty much every table will have a metatable anyway.