I just get objects directly from the Selection service. I have a plugin that loads various commands into the command bar environment. Here’s the relevant portion of it:
local lib = {}
--[==[ Selection
Get nth selection:
s[n]
Insert object as nth selection:
s[n] = object
Remove nth selection:
s[n] = nil
Call function with each selection:
s(function(v,i) print(v,i) -- object, index end)
Alternative:
s[[print(v,i) -- object, index]]
Get selection table:
s()
Set selection table:
s{object, ...}
]==]
lib.s = setmetatable({},{
__index = function(t,k)
return Game:GetService('Selection'):Get()[k]
end;
__newindex = function(t,k,v)
local Selection = Game:GetService('Selection')
local sel = Selection:Get()
if v == nil then
table.remove(sel,k)
else
table.insert(sel,k,v)
end
Selection:Set(sel)
end;
__call = function(t,f)
if type(f) == 'function' then
for i,v in pairs(Game:GetService('Selection'):Get()) do
f(v,i)
end
elseif type(f) == 'string' then
local func,o = loadstring([[return function(v,i) ]]..f..[[ end]])
if func then
func = func()
for i,v in pairs(Game:GetService('Selection'):Get()) do
func(v,i)
end
else
print(o)
end
elseif type(f) == 'table' then
Game:GetService('Selection'):Set(f)
elseif type(f) == 'nil' then
return Game:GetService('Selection'):Get()
end
end;
})
-- load commands into current environment
function _G.c()
local env = getfenv(2)
for k,v in pairs(lib) do
env[k] = v
end
end
Whenever you open a place, you have to call _G.c()
to load in the commands, but only once. After that, the s
variable can be used to do various things with selections, as described in the script.