Hello there,
Is anyone able to tell me why my little bit of code just returns:
[NIL]
[NIL]
[NIL]
[NIL]
...and so on?
I thought maybe I had to manually return something from the function, but I understand all values are global unless declared local - is that right? I thought maybe forcing it into a string with TOSTR might work, but no.
I'm not sure where to go from here.
function _init() createtable() end function _update() pickrandomteam() end function _draw() print(randteam) end -- user functions function createtable() team={"liverpool","welling utd","arsenal","accrington stanley"} end function pickrandomteam() n=rnd(3) randteam=team[n] end |
Hi Pico Noob! You are correct about needing to use flr, however lua arrays are one indexed and rnd gets a number from 0 so you actually need
flr(rnd(3))+1
On top of that, there is a #
key in lua that gets the number of items in a table, so you could use
flr(rnd (#team))+1
So then you could add and take away entries from team and this line of code would scale to compensate.
As @Felice has pointed out to me before, while it looks like you're saving a token you have to remember that rnd(1) would return between 0 and 0.99999 (or some decimal around there). So doing this method leaves the (very very slim) chance of rnd returning 0, then ceil 0 returns 0 and trying to access element at index 0 causing a nil return.
If you're not worried about space, here is a robust random function I use in all my code that needs a random operator. It can be used three ways:
a=fnr(nn) |
Gives you a random number zero to nn minus one.
a=fnr(8) : 0..1..2..3..4..5..6..7
a=fnr(n1,n2) |
Gives you a random number from n1 to n2.
a=fnr(2,6) : 2..3..4..5..6
Reversing numbers also gets you the same results.
a=fnr(6,2) : 2..3..4..5..6
Negative numbers are also allowed.
a=fnr(-3,3) : -3..-2..-1..0..1..2..3
If you're curious about that a=b,b=a that idea comes from Felice. A good way to swap variables without using a 3rd.
As the results are always integer, you don't need to worry about floating point numbers, the decimal place, or returning non-integer values for integer arrays.
-- get random # --------------- function fnr(a,b) if (b==nil) return flr(rnd(a)) if (a>b) a,b=b,a return a+flr(rnd(b-a+1)) end--fnrr(..) |
[Please log in to post a comment]