I'm trying to explore more methods in Lua and am interested in metatables. That said, I'm attempting to create a function that can be called on a service. I'm not sure how to explain this, but I'll try.
Here is my old and boring code
function GetRandom(obj, seed)
local dispose = math.random()
seed = seed or dispose
assert(typeof({}) == typeof(obj) or typeof("") == typeof(obj) or typeof(game) == typeof(obj), "bad argument #1 to 'GetRandom' (table, string, or object expected, got " .. typeof(obj or nil) or type(obj or nil) or "nil" .. ")")
assert(typeof(seed) == typeof(0), "bad argument #2 to 'GetRandom' (number expected, got " .. typeof(seed) .. ")")
if dispose ~= seed and typeof(0) == typeof(seed) then
math.randomseed(seed)
end
if typeof("") == typeof(obj) then
dispose = obj
obj = {}
for loop = 1, dispose:len() do
table.insert(obj, dispose:sub(loop, loop))
end
elseif typeof(game) == typeof(obj) then
assert(0 < #obj:GetChildren(), "bad argument #1 to 'GetRandom' (" .. #obj:GetChildren() .. " children found in " .. obj .. ")")
obj = obj:GetChildren()
end
assert(0 < #obj, "bad argument #1 to 'GetRandom' (" .. #obj .. " items found in " .. typeof(obj or {}) .. ")")
return obj[math.random(1, #obj)]
end
function GetRandomPlayer()
return game.Players:GetPlayers()[math.random(1, game.Players:GetPlayers())]
end
print(GetRandom("Random String", 1234))
print("Random Player:" .. GetRandom(game.Players:GetPlayers()))
-- local r = game.Players:GetRandomPlayer() -- error > GetRandomPlayer isn't a function of object class
How can I turn that into a method like "string:sub()" or "object:GetChildren()" or "object:WaitForChild()" and still get same results?
Example:
print(("Random String"):GetRandom(1234))
print("Random Player:" .. (game.Players:GetPlayers()):GetRandom())
Another example I could think of that may help with understanding would be how string.rep() is the very same as string:rep(). Calling a function from self.
I'm not looking for a method of returning a random child (or change part color), just wondering if the concept could be explained. I was interested when I found this line in a script
-- part is a basepart
part:ChangeColor("Black")
-- Skipped BrickColor.new(). Metatable?
And I'm pretty sure ChangeColor is not a roblox function.
