SharedTable
s have no metatable or metamethod support, which makes sense because functions are bound to the state they’re created in. My solution to this is something of a wrapper table that uses __index
and __newindex
metamethods to write to the SharedTable
. Specifically, all of this allowed me to add the equivalent of Instance.Changed
events for a SharedTable
that represented a player’s DataStore
save data. When I went to implement the __iter
metamethod into the so-called wrapper table, I realized that it was not going to be possible to implement performantly, because the next
global function does not work on SharedTable
s. Here is the solution I use instead:
__iter = function(t)
local raw = t._RAW --this is the sharedtable
local keys = {}
return function()
for i, v in raw do
if not keys[i] then
keys[i] = true
return i, v
end
end
end
end
It works, but it is very inefficient compared to what would be possible if next
supported SharedTable
s. Metaphorically speaking, instead of Luau counting from 1 to 10 and returning all the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
, it counts 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
, returning only new values. Obviously for linear arrays this isn’t a problem; you can alternatively use a for
loop with its bound set to the SharedTable
’s length. When working with dictionaries, however, this is the only way to currently implement something similar to what next
offers.
Expected behavior
next
should support SharedTable
s, or an equivalent function for use with SharedTable
s should be added.