gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
lua test = {['A'] = 1, ['B'] =2} how can i use math.random to randomly select one of…
- User
lua test = {['A'] = 1, ['B'] =2} how can i use math.random to randomly select one of items then print the values eg if selcts 'A' then it would print 1
- Assistant
You can use the
pairsfunction to iterate over the key-value pairs in thetesttable, and then use themath.randomfunction to select a random key:code-- Get a table of keys from the test table local keys = {} for k, v in pairs(test) do table.insert(keys, k) end -- Select a random key from the keys table local randomKey = keys[math.random(#keys)] -- Print the value associated with the random key print(test[randomKey])This will output either
1or2, depending on whether 'A' or 'B' was randomly selected.