[...]
Incidentally, you have touched the other topic which I find interesting: garbage collection - who knows if there is a way to make it automatic as it is done in Rust?
In C++ you can use the std::unique_ptr class template to manage objects in essentially the same way. You use regular (raw) pointers for borrowed values. I would not call it automatic, not even in Rust, because you have to think about who owns and who borrows. You're forced to follow a set of rules, never creating more than one pointer that actually 'owns' the object (i.e. is responsible for destroying it).
The automatic garbage collection in Lua, Java, C# etc. does not require you to do any of that, but it has a lot more overhead and does not free memory instantly, which is why the "<close>" facility was added in Lua 5.4.0.
If I understand correctly Lua 5.4 will have "const" but this refers to the variables and their bindings not to the values they are bound to, so table cannot be made 'constant' / read-only (I know that a table can be made read-only by redefining the newindex metamethod)
No, __newindex can be used to block adding new keys, but you can still delete keys or modify the associated value. You can make a proxy table that blocks all modifications. This creates some overhead, though, and 'rawset' etc. will still ignore the readonly status.
local function readonly(t)
local mt = {
__index = t,
__newindex = function()
error("attempt to modify read-only table", 2)
end,
__len = function() return #t end,
__pairs = function() return pairs(t) end,
}
return setmetatable({}, mt)
end
local t = readonly{1,2,3,x=4}
print(#t)
for k, v in pairs(t) do
print(k, v)
end
-- cause error
t.x = 12
--