Well my first question is how did you even come to the conclusion that using math.random was inefficient, unless you are talking about chaining if statements. Can you please clarify?
It’s not exactly inefficient, but i want to do it to randomize attacks in a boss fight, so it will fill a lot of lines and i wanted to know if there is a more efficient way.
The only issue with this is you’d be calling way more functions which might not necessarily be a good thing, but it definitely is a more organized way.
Hmm If you’re talking about data usage and things like that I don’t know too much in detail. But I do know that both ways have a very small impact on performance, and you shouldn’t worry about it.
Talking more in terms of function calling, although the speed would be miniscule in small usage, in bulk it might be worse. Really depends on how their system works.
What? You’re premaking the function just like you do in module scripts and just like in libraries roblox provides such table to then use for later. Calling a function is technically the same thing as running code, if I remember correctly Lua just saves it in it’s memory the function and will go back there to run it whenever it sees the function’s name.
Well it’s good practice
@Faczki
It’s assigning a function to the index in the dicionnary. (Not to confuse with a list of values such {1, 2, 3, 4}.)
local t = {
[1] = function(x)
return x^2
end,
[2] = function(x)
return x*2
end
}
print(t[1](2))
local randomAttack = math.random(1, 2)
t[randomAttack]() -- getting the index's function and running it `()`
Just like how module scripts work, but it’s not in a module script and directly inside the script.
As far as performance, there’s nothing you can do since the math.random is being used from C as far as I know.
Lua’s math.random() is an interface to the C rand() function provided by the OS libc; its implementation varies by platform.
What I’m saying is if you have a lot of functions and you are calling them in bulk in short amount of times it will be slower than just doing something directly. Obviously you should use functions I am not saying not to, especially if you aren’t calling them quickly.
To add on to this, if their system does not perform a lot of instructions when they evaluate their pseudorandom number, it might be better just to do it directly instead of the function way. However, if they do a ton of stuff it’s better to slap them in functions of their own and work with that.