I’m having trouble finding a random item within a folder, the output returns the following error
math.random()
requires two parameters, you would need to do math.random(1,#ItemsFolder:GetChildren())
Also, to use table lookup via [], you must need to be a table. I would recommend making a table of the children and using it with that. It should look like this below:
local ItemsTable = ItemsFolder:GetChildren()
for _ = 1, MaxObjects do
local index = math.random(1, #ItemsTable)
local obj = ItemsTable[index]
If this comes up with any errors, please feel free to let me know, and as always; happy scripting!
i was using a system with 2 parameters but it was going wrong for the system i needed
I don’t fully understand what you are saying. Can you try to elaborate more?
Sorry for the lack of information. But is that I need a system that places random items in random places. But when placing a second parameter in math.random() the first item of the folder is always chosen. By leaving math.random() with just the amount of items inside the folder, it works correctly.
the solution was to change the name of the items to the name of the indexers
What is the issue?
If it a not a valid member of the folder, did you remember to call :getchildren() on it?
example
local Object = folder:GetChildren()[2]
Your issue is that you can’t get the child of an object with an index value. instead you need to place the children into a table first to then grab them from that table with an index.
local Children = ItemsFolder:GetChildren()
for _ = 1, MaxObjects do
local index = math.random(#Children)
local obj = Children[index]
end
OK i see the issue, you named it as a number, add the “” … to refer to the STRING reference to the object
example:
["" .. 1]
The first parameter on the math.random method is to say where the number is FIRST being chosen from, as lua is a “1 index” thing (I forgot the actual term :P), giving the one parameter is fine.
The thing that can fix your issue is listing your children for the ItemsTable[index]
portion.
i’m gonna try all of these, ty guys <3
This is not a healthy way to do this. The best way to do this is to convert a number to a string using the tostring()
method that is embedded with Lua(U).
Hi Alice,
Thanks for the reply, It may be bad to append numbers to strings without directly converting it to a string with luas tostring() function. But the “…” operator automatically converts numbers to strings and is built into LUA, so I am unsure if it is exactly bad practice.
You can view the documentation here:
It may work, but it’s way easier to use a built in Lua function than use weird concatenation like the way you showed. It’s always good to use the best practice when available and it’s really easy.
Happy Scripting!
for _ = 1, MaxObjects do
local obj = ItemsFolder:GetChildren()[math.random(1, #ItemsFolder:GetChildren())]
-- Rest of code here
end
Edit: Not sure why my last post automatically replied to a random person