3 ms·
I understand the reason for the behavior--Lua pretends that new tables start with all possible keys set to nil. I find it regrettable because it necessitates st
by vor_ 13y ago
I understand the reason for the behavior--Lua pretends that new tables start with all possible keys set to nil. I find it regrettable because it necessitates static analyzers for larger projects and contributes to a lack of safety, especially since the language is targeted at non-professionals and hobbyists. With multiple contributors to a project, one typo can lead to unintended sparse arrays and hard-to-debug errors that propagate far from their origins. The behavior seems inconsistent with Lua's existing policy of raising errors for attempted indexing of nil and for order comparisons of different types of values.
The issue was raised on the Lua mailing list, and the response from one of Lua's curators was, literally, "I used to make mistakes like that, but then I got used to it." Lua is admirable for its size and speed, but I believe that it's sometimes too conservative about changing historical behaviors to accommodate safer policy.
- anonymoushn 13y agoWow, 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.