Log In  

So apologies if this has been asked before,

I am looking to build a sentence with random strings that will be stored in a table.

For example:

    text = {}
names = {"a", "b", "c"}

name = names[rnd(2)] <-- doesn't work :(

foo = {
    str = "Hi my name is" .. name
}

Everything I have found is in the Non P8 version of Lua.

P#54142 2018-07-13 12:56 ( Edited 2018-07-18 08:53)

1
name = names[flr(rnd(#names))+1]

In Lua you can have non integer tables indices, you need to round the random value (float) to an int.

P#54143 2018-07-13 13:59 ( Edited 2018-07-13 17:59)

rnd() doesn't return an integer. also table indices start at 1:

name = names[1+flr(rnd(2))]

if you need this a lot you could use:

function rndt(t) return t[1+flr(rnd(#t))] end

name=rndt(names)
P#54144 2018-07-13 14:02 ( Edited 2018-07-13 18:02)

Thank you!

P#54145 2018-07-13 14:13 ( Edited 2018-07-13 18:13)

Can save a token by using ceil instead of flr

name = names[ceil(rnd(2))]
P#54146 2018-07-13 14:37 ( Edited 2018-07-13 18:38)

@Davbo: of course! ceil was (finally) added 6+ months ago. still not wired in my brain I guess ¯\_(ツ)_/¯

P#54147 2018-07-13 15:16 ( Edited 2018-07-13 19:17)

I'm not sure that's a good idea:

rnd() can return 0.0, and ceil(0) == 0.

P#54237 2018-07-17 22:29 ( Edited 2018-07-18 02:30)

Awjeez. I gotta find some tokens.

P#54244 2018-07-18 04:18 ( Edited 2018-07-18 08:18)

@Felice: of course! (-‸ლ)

P#54245 2018-07-18 04:53 ( Edited 2018-07-18 08:53)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-19 18:03:10 | 0.044s | Q:23